forked from CortexReach/memory-lancedb-pro
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
2931 lines (2667 loc) · 113 KB
/
index.ts
File metadata and controls
2931 lines (2667 loc) · 113 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Memory LanceDB Pro Plugin
* Enhanced LanceDB-backed long-term memory with hybrid retrieval and multi-scope isolation
*/
import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
import { homedir, tmpdir } from "node:os";
import { join, dirname, basename } from "node:path";
import { readFile, readdir, writeFile, mkdir, appendFile, unlink, stat } from "node:fs/promises";
import { readFileSync } from "node:fs";
import { createHash } from "node:crypto";
import { pathToFileURL } from "node:url";
import { createRequire } from "node:module";
import { spawn } from "node:child_process";
// Import core components
import { MemoryStore, validateStoragePath } from "./src/store.js";
import { createEmbedder, getVectorDimensions } from "./src/embedder.js";
import { createRetriever, DEFAULT_RETRIEVAL_CONFIG, type RetrievalResult } from "./src/retriever.js";
import { createScopeManager } from "./src/scopes.js";
import { createMigrator } from "./src/migrate.js";
import { registerAllMemoryTools } from "./src/tools.js";
import { appendSelfImprovementEntry, ensureSelfImprovementLearningFiles } from "./src/self-improvement-files.js";
import type { MdMirrorWriter } from "./src/tools.js";
import { AccessTracker } from "./src/access-tracker.js";
import { runWithReflectionTransientRetryOnce } from "./src/reflection-retry.js";
import { resolveReflectionSessionSearchDirs, stripResetSuffix } from "./src/session-recovery.js";
import {
storeReflectionToLanceDB,
loadAgentReflectionSlicesFromEntries,
loadAgentDerivedFocusRowsForHandoffFromEntries,
DEFAULT_REFLECTION_DERIVED_MAX_AGE_MS,
DEFAULT_REFLECTION_DERIVED_FINAL_LIMIT,
DEFAULT_REFLECTION_DERIVED_SHORTLIST_LIMIT,
} from "./src/reflection-store.js";
import {
extractReflectionLearningGovernanceCandidates,
extractReflectionMappedMemoryItems,
extractReflectionOpenLoops,
} from "./src/reflection-slices.js";
import { createReflectionEventId } from "./src/reflection-event-store.js";
import { buildReflectionMappedMetadata } from "./src/reflection-mapped-metadata.js";
import { createMemoryCLI } from "./cli.js";
import {
createDynamicRecallSessionState,
clearDynamicRecallSessionState,
normalizeRecallTextKey,
orchestrateDynamicRecall,
filterByMaxAge,
keepMostRecentPerNormalizedKey,
} from "./src/recall-engine.js";
import { rankDynamicReflectionRecallFromEntries } from "./src/reflection-recall.js";
import { selectFinalAutoRecallResults } from "./src/auto-recall-final-selection.js";
// ============================================================================
// Configuration & Types
// ============================================================================
interface PluginConfig {
embedding: {
provider: "openai-compatible";
apiKey?: string;
model?: string;
baseURL?: string;
dimensions?: number;
taskQuery?: string;
taskPassage?: string;
normalized?: boolean;
chunking?: boolean;
};
dbPath?: string;
autoCapture?: boolean;
autoRecall?: boolean;
autoRecallMinLength?: number;
autoRecallMinRepeated?: number;
autoRecallTopK?: number;
autoRecallSelectionMode?: AutoRecallSelectionMode;
autoRecallCategories?: MemoryCategory[];
autoRecallExcludeReflection?: boolean;
autoRecallMaxAgeDays?: number;
autoRecallMaxEntriesPerKey?: number;
captureAssistant?: boolean;
retrieval?: {
mode?: "hybrid" | "vector";
vectorWeight?: number;
bm25Weight?: number;
minScore?: number;
rerank?: "cross-encoder" | "lightweight" | "none";
candidatePoolSize?: number;
rerankApiKey?: string;
rerankModel?: string;
rerankEndpoint?: string;
rerankProvider?: "jina" | "siliconflow" | "voyage" | "pinecone" | "vllm";
recencyHalfLifeDays?: number;
recencyWeight?: number;
filterNoise?: boolean;
lengthNormAnchor?: number;
hardMinScore?: number;
timeDecayHalfLifeDays?: number;
reinforcementFactor?: number;
maxHalfLifeMultiplier?: number;
};
scopes?: {
default?: string;
definitions?: Record<string, { description: string }>;
agentAccess?: Record<string, string[]>;
};
enableManagementTools?: boolean;
sessionStrategy?: SessionStrategy;
sessionMemory?: { enabled?: boolean; messageCount?: number };
selfImprovement?: {
enabled?: boolean;
beforeResetNote?: boolean;
skipSubagentBootstrap?: boolean;
ensureLearningFiles?: boolean;
};
memoryReflection?: {
enabled?: boolean;
storeToLanceDB?: boolean;
injectMode?: ReflectionInjectMode;
agentId?: string;
messageCount?: number;
maxInputChars?: number;
timeoutMs?: number;
thinkLevel?: ReflectionThinkLevel;
errorReminderMaxEntries?: number;
dedupeErrorSignals?: boolean;
recall?: {
mode?: ReflectionRecallMode;
topK?: number;
includeKinds?: ReflectionRecallKind[];
maxAgeDays?: number;
maxEntriesPerKey?: number;
minRepeated?: number;
minScore?: number;
minPromptLength?: number;
};
};
mdMirror?: { enabled?: boolean; dir?: string };
}
type ReflectionThinkLevel = "off" | "minimal" | "low" | "medium" | "high";
type SessionStrategy = "memoryReflection" | "systemSessionMemory" | "none";
type ReflectionInjectMode = "inheritance-only" | "inheritance+derived";
type ReflectionRecallMode = "fixed" | "dynamic";
type ReflectionRecallKind = "invariant" | "derived";
type AutoRecallSelectionMode = "mmr" | "setwise-v2";
type MemoryCategory = "preference" | "fact" | "decision" | "entity" | "other" | "reflection";
// ============================================================================
// Default Configuration
// ============================================================================
function getDefaultDbPath(): string {
const home = homedir();
return join(home, ".openclaw", "memory", "lancedb-pro");
}
function getDefaultWorkspaceDir(): string {
const home = homedir();
return join(home, ".openclaw", "workspace");
}
function resolveWorkspaceDirFromContext(context: Record<string, unknown> | undefined): string {
const runtimePath = typeof context?.workspaceDir === "string" ? context.workspaceDir.trim() : "";
return runtimePath || getDefaultWorkspaceDir();
}
function resolveEnvVars(value: string): string {
return value.replace(/\$\{([^}]+)\}/g, (_, envVar) => {
const envValue = process.env[envVar];
if (!envValue) {
throw new Error(`Environment variable ${envVar} is not set`);
}
return envValue;
});
}
function parsePositiveInt(value: unknown): number | undefined {
if (typeof value === "number" && Number.isFinite(value) && value > 0) {
return Math.floor(value);
}
if (typeof value === "string") {
const s = value.trim();
if (!s) return undefined;
const resolved = resolveEnvVars(s);
const n = Number(resolved);
if (Number.isFinite(n) && n > 0) return Math.floor(n);
}
return undefined;
}
function parseNonNegativeNumber(value: unknown): number | undefined {
if (typeof value === "number" && Number.isFinite(value) && value >= 0) {
return value;
}
if (typeof value === "string") {
const s = value.trim();
if (!s) return undefined;
const resolved = resolveEnvVars(s);
const n = Number(resolved);
if (Number.isFinite(n) && n >= 0) return n;
}
return undefined;
}
function parseMemoryCategories(value: unknown, fallback: MemoryCategory[]): MemoryCategory[] {
if (!Array.isArray(value)) return [...fallback];
const parsed = value
.filter((item): item is string => typeof item === "string")
.map((item) => item.trim())
.filter((item): item is MemoryCategory =>
item === "preference" ||
item === "fact" ||
item === "decision" ||
item === "entity" ||
item === "other" ||
item === "reflection"
);
return parsed.length > 0 ? [...new Set(parsed)] : [...fallback];
}
function parseReflectionRecallKinds(value: unknown, fallback: ReflectionRecallKind[]): ReflectionRecallKind[] {
if (!Array.isArray(value)) return [...fallback];
const parsed = value
.filter((item): item is string => typeof item === "string")
.map((item) => item.trim())
.filter((item): item is ReflectionRecallKind => item === "invariant" || item === "derived");
return parsed.length > 0 ? [...new Set(parsed)] : [...fallback];
}
function daysToMs(days: number | undefined): number | undefined {
if (!Number.isFinite(days) || Number(days) <= 0) return undefined;
return Number(days) * 24 * 60 * 60 * 1000;
}
const DEFAULT_SELF_IMPROVEMENT_REMINDER = `## Self-Improvement Reminder
After completing tasks, evaluate if any learnings should be captured:
**Log when:**
- User corrects you -> .learnings/LEARNINGS.md
- Command/operation fails -> .learnings/ERRORS.md
- You discover your knowledge was wrong -> .learnings/LEARNINGS.md
- You find a better approach -> .learnings/LEARNINGS.md
**Promote when pattern is proven:**
- Behavioral patterns -> SOUL.md
- Workflow improvements -> AGENTS.md
- Tool gotchas -> TOOLS.md
Keep entries simple: date, title, what happened, what to do differently.`;
const SELF_IMPROVEMENT_NOTE_PREFIX = "/note self-improvement (before reset):";
const DEFAULT_REFLECTION_MESSAGE_COUNT = 120;
const DEFAULT_REFLECTION_MAX_INPUT_CHARS = 24_000;
const DEFAULT_REFLECTION_TIMEOUT_MS = 20_000;
const DEFAULT_REFLECTION_THINK_LEVEL: ReflectionThinkLevel = "medium";
const DEFAULT_REFLECTION_ERROR_REMINDER_MAX_ENTRIES = 3;
const DEFAULT_REFLECTION_DEDUPE_ERROR_SIGNALS = true;
const DEFAULT_REFLECTION_SESSION_TTL_MS = 30 * 60 * 1000;
const DEFAULT_REFLECTION_MAX_TRACKED_SESSIONS = 200;
const DEFAULT_REFLECTION_ERROR_SCAN_MAX_CHARS = 8_000;
const DEFAULT_AUTO_RECALL_TOP_K = 3;
const DEFAULT_AUTO_RECALL_SELECTION_MODE: AutoRecallSelectionMode = "mmr";
const DEFAULT_AUTO_RECALL_EXCLUDE_REFLECTION = true;
const DEFAULT_AUTO_RECALL_MAX_AGE_DAYS = 30;
const DEFAULT_AUTO_RECALL_MAX_ENTRIES_PER_KEY = 10;
const DEFAULT_AUTO_RECALL_CATEGORIES: MemoryCategory[] = ["preference", "fact", "decision", "entity", "other"];
const DEFAULT_REFLECTION_RECALL_MODE: ReflectionRecallMode = "fixed";
const DEFAULT_REFLECTION_RECALL_TOP_K = 6;
const DEFAULT_REFLECTION_RECALL_INCLUDE_KINDS: ReflectionRecallKind[] = ["invariant"];
const DEFAULT_REFLECTION_RECALL_MAX_AGE_DAYS = 45;
const DEFAULT_REFLECTION_RECALL_MAX_ENTRIES_PER_KEY = 10;
const DEFAULT_REFLECTION_RECALL_MIN_REPEATED = 2;
const DEFAULT_REFLECTION_RECALL_MIN_SCORE = 0.18;
const DEFAULT_REFLECTION_RECALL_MIN_PROMPT_LENGTH = 8;
// Rendering safety guard only; ranking/store layer owns the semantic final-13 cap.
const DERIVED_FOCUS_RENDER_HARD_LIMIT = 64;
const REFLECTION_FALLBACK_MARKER = "(fallback) Reflection generation failed; storing minimal pointer only.";
const DIAG_BUILD_TAG = "memory-lancedb-pro-diag-20260308-0058";
function buildReflectionDerivedFocusBlock(derivedLines: string[]): string {
const trimmed = derivedLines
.map((line) => line.trim())
.filter((line) => line.length > 0)
.slice(0, DERIVED_FOCUS_RENDER_HARD_LIMIT);
if (trimmed.length === 0) return "";
return [
"<derived-focus>",
"Weighted recent derived execution deltas from reflection memory:",
...trimmed.map((line, i) => `${i + 1}. ${line}`),
"</derived-focus>",
].join("\n");
}
function buildReflectionOpenLoopsBlock(openLoopLines: string[]): string {
const trimmed = openLoopLines
.map((line) => line.trim())
.filter((line) => line.length > 0)
.slice(0, 6);
if (trimmed.length === 0) return "";
return [
"<open-loops>",
"Fresh open loops / next actions from this reflection run:",
...trimmed.map((line, i) => `${i + 1}. ${line}`),
"</open-loops>",
].join("\n");
}
function buildSelfImprovementResetNote(params?: { openLoopsBlock?: string; derivedFocusBlock?: string }): string {
const openLoopsBlock = typeof params?.openLoopsBlock === "string" ? params.openLoopsBlock : "";
const derivedFocusBlock = typeof params?.derivedFocusBlock === "string" ? params.derivedFocusBlock : "";
const base = [
SELF_IMPROVEMENT_NOTE_PREFIX,
"- If anything was learned/corrected, log it now:",
" - .learnings/LEARNINGS.md (corrections/best practices)",
" - .learnings/ERRORS.md (failures/root causes)",
"- Distill reusable rules to AGENTS.md / SOUL.md / TOOLS.md.",
"- If reusable across tasks, extract a new skill from the learning.",
];
if (openLoopsBlock) {
base.push("- Fresh run handoff:");
base.push(openLoopsBlock);
}
if (derivedFocusBlock) {
base.push("- Historical reflection-derived focus:");
base.push(derivedFocusBlock);
}
base.push("- Then proceed with the new session.");
return base.join("\n");
}
type ReflectionErrorSignal = {
at: number;
toolName: string;
summary: string;
source: "tool_error" | "tool_output";
signature: string;
signatureHash: string;
};
type ReflectionErrorState = {
entries: ReflectionErrorSignal[];
lastInjectedCount: number;
signatureSet: Set<string>;
updatedAt: number;
};
type EmbeddedPiRunner = (params: Record<string, unknown>) => Promise<unknown>;
const requireFromHere = createRequire(import.meta.url);
let embeddedPiRunnerPromise: Promise<EmbeddedPiRunner> | null = null;
function toImportSpecifier(value: string): string {
const trimmed = value.trim();
if (!trimmed) return "";
if (trimmed.startsWith("file://")) return trimmed;
if (trimmed.startsWith("/")) return pathToFileURL(trimmed).href;
return trimmed;
}
function getExtensionApiImportSpecifiers(): string[] {
const envPath = process.env.OPENCLAW_EXTENSION_API_PATH?.trim();
const specifiers: string[] = [];
if (envPath) specifiers.push(toImportSpecifier(envPath));
specifiers.push("openclaw/dist/extensionAPI.js");
try {
specifiers.push(toImportSpecifier(requireFromHere.resolve("openclaw/dist/extensionAPI.js")));
} catch {
// ignore resolve failures and continue fallback probing
}
specifiers.push(toImportSpecifier("/usr/lib/node_modules/openclaw/dist/extensionAPI.js"));
specifiers.push(toImportSpecifier("/usr/local/lib/node_modules/openclaw/dist/extensionAPI.js"));
return [...new Set(specifiers.filter(Boolean))];
}
async function loadEmbeddedPiRunner(): Promise<EmbeddedPiRunner> {
if (!embeddedPiRunnerPromise) {
embeddedPiRunnerPromise = (async () => {
const importErrors: string[] = [];
for (const specifier of getExtensionApiImportSpecifiers()) {
try {
const mod = await import(specifier);
const runner = (mod as Record<string, unknown>).runEmbeddedPiAgent;
if (typeof runner === "function") return runner as EmbeddedPiRunner;
importErrors.push(`${specifier}: runEmbeddedPiAgent export not found`);
} catch (err) {
importErrors.push(`${specifier}: ${err instanceof Error ? err.message : String(err)}`);
}
}
throw new Error(
`Unable to load OpenClaw embedded runtime API. ` +
`Set OPENCLAW_EXTENSION_API_PATH if runtime layout differs. ` +
`Attempts: ${importErrors.join(" | ")}`
);
})();
}
try {
return await embeddedPiRunnerPromise;
} catch (err) {
embeddedPiRunnerPromise = null;
throw err;
}
}
function clipDiagnostic(text: string, maxLen = 400): string {
const oneLine = text.replace(/\s+/g, " ").trim();
if (oneLine.length <= maxLen) return oneLine;
return `${oneLine.slice(0, maxLen - 3)}...`;
}
function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string): Promise<T> {
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(() => {
reject(new Error(`${label} timed out after ${timeoutMs}ms`));
}, timeoutMs);
promise.then(
(value) => {
clearTimeout(timer);
resolve(value);
},
(err) => {
clearTimeout(timer);
reject(err);
}
);
});
}
function tryParseJsonObject(raw: string): Record<string, unknown> | null {
try {
const parsed = JSON.parse(raw);
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
return parsed as Record<string, unknown>;
}
} catch {
// ignore
}
return null;
}
function extractJsonObjectFromOutput(stdout: string): Record<string, unknown> {
const trimmed = stdout.trim();
if (!trimmed) throw new Error("empty stdout");
const direct = tryParseJsonObject(trimmed);
if (direct) return direct;
const lines = trimmed.split(/\r?\n/);
for (let i = 0; i < lines.length; i++) {
if (!lines[i].trim().startsWith("{")) continue;
const candidate = lines.slice(i).join("\n");
const parsed = tryParseJsonObject(candidate);
if (parsed) return parsed;
}
throw new Error(`unable to parse JSON from CLI output: ${clipDiagnostic(trimmed, 280)}`);
}
function extractReflectionTextFromCliResult(resultObj: Record<string, unknown>): string | null {
const result = resultObj.result as Record<string, unknown> | undefined;
const payloads = Array.isArray(resultObj.payloads)
? resultObj.payloads
: Array.isArray(result?.payloads)
? result.payloads
: [];
const firstWithText = payloads.find(
(p) => p && typeof p === "object" && typeof (p as Record<string, unknown>).text === "string" && ((p as Record<string, unknown>).text as string).trim().length
) as Record<string, unknown> | undefined;
const text = typeof firstWithText?.text === "string" ? firstWithText.text.trim() : "";
return text || null;
}
async function runReflectionViaCli(params: {
prompt: string;
agentId: string;
workspaceDir: string;
timeoutMs: number;
thinkLevel: ReflectionThinkLevel;
}): Promise<string> {
const cliBin = process.env.OPENCLAW_CLI_BIN?.trim() || "openclaw";
const outerTimeoutMs = Math.max(params.timeoutMs + 5000, 15000);
const agentTimeoutSec = Math.max(1, Math.ceil(params.timeoutMs / 1000));
const sessionId = `memory-reflection-cli-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
const args = [
"agent",
"--local",
"--agent",
params.agentId,
"--message",
params.prompt,
"--json",
"--thinking",
params.thinkLevel,
"--timeout",
String(agentTimeoutSec),
"--session-id",
sessionId,
];
return await new Promise<string>((resolve, reject) => {
const child = spawn(cliBin, args, {
cwd: params.workspaceDir,
env: { ...process.env, NO_COLOR: "1" },
stdio: ["ignore", "pipe", "pipe"],
});
let stdout = "";
let stderr = "";
let settled = false;
let timedOut = false;
const timer = setTimeout(() => {
timedOut = true;
child.kill("SIGTERM");
setTimeout(() => child.kill("SIGKILL"), 1500).unref();
}, outerTimeoutMs);
child.stdout.setEncoding("utf8");
child.stdout.on("data", (chunk) => {
stdout += chunk;
});
child.stderr.setEncoding("utf8");
child.stderr.on("data", (chunk) => {
stderr += chunk;
});
child.once("error", (err) => {
if (settled) return;
settled = true;
clearTimeout(timer);
reject(new Error(`spawn ${cliBin} failed: ${err.message}`));
});
child.once("close", (code, signal) => {
if (settled) return;
settled = true;
clearTimeout(timer);
if (timedOut) {
reject(new Error(`${cliBin} timed out after ${outerTimeoutMs}ms`));
return;
}
if (signal) {
reject(new Error(`${cliBin} exited by signal ${signal}. stderr=${clipDiagnostic(stderr)}`));
return;
}
if (code !== 0) {
reject(new Error(`${cliBin} exited with code ${code}. stderr=${clipDiagnostic(stderr)}`));
return;
}
try {
const parsed = extractJsonObjectFromOutput(stdout);
const text = extractReflectionTextFromCliResult(parsed);
if (!text) {
reject(new Error(`CLI JSON returned no text payload. stdout=${clipDiagnostic(stdout)}`));
return;
}
resolve(text);
} catch (err) {
reject(err instanceof Error ? err : new Error(String(err)));
}
});
});
}
async function loadSelfImprovementReminderContent(workspaceDir?: string): Promise<string> {
const baseDir = typeof workspaceDir === "string" && workspaceDir.trim().length ? workspaceDir.trim() : "";
if (!baseDir) return DEFAULT_SELF_IMPROVEMENT_REMINDER;
const reminderPath = join(baseDir, "SELF_IMPROVEMENT_REMINDER.md");
try {
const content = await readFile(reminderPath, "utf-8");
const trimmed = content.trim();
return trimmed.length ? trimmed : DEFAULT_SELF_IMPROVEMENT_REMINDER;
} catch {
return DEFAULT_SELF_IMPROVEMENT_REMINDER;
}
}
function parseAgentIdFromSessionKey(sessionKey: string | undefined): string | undefined {
const sk = (sessionKey ?? "").trim();
const parts = sk.split(":");
if (parts.length >= 2 && parts[0] === "agent" && parts[1]) return parts[1];
return undefined;
}
function resolveAgentPrimaryModelRef(cfg: unknown, agentId: string): string | undefined {
try {
const root = cfg as Record<string, unknown>;
const agents = root.agents as Record<string, unknown> | undefined;
const list = agents?.list as unknown;
if (Array.isArray(list)) {
const found = list.find((x) => {
if (!x || typeof x !== "object") return false;
return (x as Record<string, unknown>).id === agentId;
}) as Record<string, unknown> | undefined;
const model = found?.model as Record<string, unknown> | undefined;
const primary = model?.primary;
if (typeof primary === "string" && primary.trim()) return primary.trim();
}
const defaults = agents?.defaults as Record<string, unknown> | undefined;
const defModel = defaults?.model as Record<string, unknown> | undefined;
const defPrimary = defModel?.primary;
if (typeof defPrimary === "string" && defPrimary.trim()) return defPrimary.trim();
} catch {
// ignore
}
return undefined;
}
function isAgentDeclaredInConfig(cfg: unknown, agentId: string): boolean {
const target = agentId.trim();
if (!target) return false;
try {
const root = cfg as Record<string, unknown>;
const agents = root.agents as Record<string, unknown> | undefined;
const list = agents?.list as unknown;
if (!Array.isArray(list)) return false;
return list.some((x) => {
if (!x || typeof x !== "object") return false;
return (x as Record<string, unknown>).id === target;
});
} catch {
return false;
}
}
function splitProviderModel(modelRef: string): { provider?: string; model?: string } {
const s = modelRef.trim();
if (!s) return {};
const idx = s.indexOf("/");
if (idx > 0) {
const provider = s.slice(0, idx).trim();
const model = s.slice(idx + 1).trim();
return { provider: provider || undefined, model: model || undefined };
}
return { model: s };
}
function asNonEmptyString(value: unknown): string | undefined {
if (typeof value !== "string") return undefined;
const trimmed = value.trim();
return trimmed.length ? trimmed : undefined;
}
function isInternalReflectionSessionKey(sessionKey: unknown): boolean {
return typeof sessionKey === "string" && sessionKey.trim().startsWith("temp:memory-reflection");
}
function extractTextContent(content: unknown): string | null {
if (!content) return null;
if (typeof content === "string") return content;
if (Array.isArray(content)) {
const block = content.find(
(c) => c && typeof c === "object" && (c as Record<string, unknown>).type === "text" && typeof (c as Record<string, unknown>).text === "string"
) as Record<string, unknown> | undefined;
const text = block?.text;
return typeof text === "string" ? text : null;
}
return null;
}
function shouldSkipReflectionMessage(role: string, text: string): boolean {
const trimmed = text.trim();
if (!trimmed) return true;
if (trimmed.startsWith("/")) return true;
if (role === "user") {
if (
trimmed.includes("<relevant-memories>") ||
trimmed.includes("UNTRUSTED DATA") ||
trimmed.includes("END UNTRUSTED DATA")
) {
return true;
}
}
return false;
}
function redactSecrets(text: string): string {
const patterns: RegExp[] = [
/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,
/\bsk-[A-Za-z0-9]{20,}\b/g,
/\bsk-proj-[A-Za-z0-9\-_]{20,}\b/g,
/\bsk-ant-[A-Za-z0-9\-_]{20,}\b/g,
/\bghp_[A-Za-z0-9]{36,}\b/g,
/\bgho_[A-Za-z0-9]{36,}\b/g,
/\bghu_[A-Za-z0-9]{36,}\b/g,
/\bghs_[A-Za-z0-9]{36,}\b/g,
/\bgithub_pat_[A-Za-z0-9_]{22,}\b/g,
/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g,
/\bAIza[0-9A-Za-z_-]{20,}\b/g,
/\bAKIA[0-9A-Z]{16}\b/g,
/\bnpm_[A-Za-z0-9]{36,}\b/g,
/\b(?:token|api[_-]?key|secret|password)\s*[:=]\s*["']?[^\s"',;)}\]]{6,}["']?\b/gi,
/-----BEGIN\s+(?:RSA\s+|EC\s+|DSA\s+|OPENSSH\s+)?PRIVATE\s+KEY-----[\s\S]*?-----END\s+(?:RSA\s+|EC\s+|DSA\s+|OPENSSH\s+)?PRIVATE\s+KEY-----/g,
/(?<=:\/\/)[^@\s]+:[^@\s]+(?=@)/g,
/\/home\/[^\s"',;)}\]]+/g,
/\/Users\/[^\s"',;)}\]]+/g,
/[A-Z]:\\[^\s"',;)}\]]+/g,
/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,
];
let out = text;
for (const re of patterns) {
out = out.replace(re, (m) => (m.startsWith("Bearer") || m.startsWith("bearer") ? "Bearer [REDACTED]" : "[REDACTED]"));
}
return out;
}
function containsErrorSignal(text: string): boolean {
const normalized = text.toLowerCase();
return (
/\[error\]|error:|exception:|fatal:|traceback|syntaxerror|typeerror|referenceerror|npm err!/.test(normalized) ||
/command not found|no such file|permission denied|non-zero|exit code/.test(normalized) ||
/"status"\s*:\s*"error"|"status"\s*:\s*"failed"|\biserror\b/.test(normalized) ||
/错误\s*[::]|异常\s*[::]|报错\s*[::]|失败\s*[::]/.test(normalized)
);
}
function summarizeErrorText(text: string, maxLen = 220): string {
const oneLine = redactSecrets(text).replace(/\s+/g, " ").trim();
if (!oneLine) return "(empty tool error)";
return oneLine.length <= maxLen ? oneLine : `${oneLine.slice(0, maxLen - 3)}...`;
}
function sha256Hex(text: string): string {
return createHash("sha256").update(text, "utf8").digest("hex");
}
function normalizeErrorSignature(text: string): string {
return redactSecrets(String(text || ""))
.toLowerCase()
.replace(/[a-z]:\\[^ \n\r\t]+/gi, "<path>")
.replace(/\/[^ \n\r\t]+/g, "<path>")
.replace(/\b0x[0-9a-f]+\b/gi, "<hex>")
.replace(/\b\d+\b/g, "<n>")
.replace(/\s+/g, " ")
.trim()
.slice(0, 240);
}
function extractTextFromToolResult(result: unknown): string {
if (result == null) return "";
if (typeof result === "string") return result;
if (typeof result === "object") {
const obj = result as Record<string, unknown>;
const content = obj.content;
if (Array.isArray(content)) {
const textParts = content
.filter((c) => c && typeof c === "object")
.map((c) => (c as Record<string, unknown>).text)
.filter((t): t is string => typeof t === "string");
if (textParts.length > 0) return textParts.join("\n");
}
if (typeof obj.text === "string") return obj.text;
if (typeof obj.error === "string") return obj.error;
if (typeof obj.details === "string") return obj.details;
}
try {
return JSON.stringify(result);
} catch {
return "";
}
}
async function readSessionConversationForReflection(filePath: string, messageCount: number): Promise<string | null> {
try {
const lines = (await readFile(filePath, "utf-8")).trim().split("\n");
const messages: string[] = [];
for (const line of lines) {
try {
const entry = JSON.parse(line);
if (entry?.type !== "message" || !entry?.message) continue;
const msg = entry.message as Record<string, unknown>;
const role = typeof msg.role === "string" ? msg.role : "";
if (role !== "user" && role !== "assistant") continue;
const text = extractTextContent(msg.content);
if (!text || shouldSkipReflectionMessage(role, text)) continue;
messages.push(`${role}: ${redactSecrets(text)}`);
} catch {
// ignore JSON parse errors
}
}
if (messages.length === 0) return null;
return messages.slice(-messageCount).join("\n");
} catch {
return null;
}
}
export async function readSessionConversationWithResetFallback(sessionFilePath: string, messageCount: number): Promise<string | null> {
const primary = await readSessionConversationForReflection(sessionFilePath, messageCount);
if (primary) return primary;
try {
const dir = dirname(sessionFilePath);
const resetPrefix = `${basename(sessionFilePath)}.reset.`;
const files = await readdir(dir);
const resetCandidates = await sortFileNamesByMtimeDesc(
dir,
files.filter((name) => name.startsWith(resetPrefix))
);
if (resetCandidates.length > 0) {
const latestResetPath = join(dir, resetCandidates[0]);
return await readSessionConversationForReflection(latestResetPath, messageCount);
}
} catch {
// ignore
}
return primary;
}
async function ensureDailyLogFile(dailyPath: string, dateStr: string): Promise<void> {
try {
await readFile(dailyPath, "utf-8");
} catch {
await writeFile(dailyPath, `# ${dateStr}\n\n`, "utf-8");
}
}
function buildReflectionPrompt(
conversation: string,
maxInputChars: number,
toolErrorSignals: ReflectionErrorSignal[] = []
): string {
const clipped = conversation.slice(-maxInputChars);
const errorHints = toolErrorSignals.length > 0
? toolErrorSignals
.map((e, i) => `${i + 1}. [${e.toolName}] ${e.summary} (sig:${e.signatureHash.slice(0, 8)})`)
.join("\n")
: "- (none)";
return [
"You are generating a durable MEMORY REFLECTION entry for an AI assistant system.",
"",
"Output Markdown only. No intro text. No outro text. No extra headings.",
"",
"Use these headings exactly once, in this exact order, with exact spelling:",
"## Context (session background)",
"## Decisions (durable)",
"## User model deltas (about the human)",
"## Agent model deltas (about the assistant/system)",
"## Lessons & pitfalls (symptom / cause / fix / prevention)",
"## Learning governance candidates (.learnings / promotion / skill extraction)",
"## Open loops / next actions",
"## Retrieval tags / keywords",
"## Invariants",
"## Derived",
"",
"Hard rules:",
"- Do not rename, translate, merge, reorder, or omit headings.",
"- Every section must appear exactly once.",
"- For bullet sections, use one item per line, starting with '- '.",
"- Do not wrap one bullet across multiple lines.",
"- If a bullet section is empty, write exactly: '- (none captured)'",
"- Do not paste raw transcript.",
"- Do not invent Logged timestamps, ids, file paths, commit hashes, session ids, or storage metadata unless they already appear in the input.",
"- If secrets/tokens/passwords appear, keep them as [REDACTED].",
"",
"Section rules:",
"- Context / Decisions / User model / Agent model / Open loops / Retrieval tags / Invariants / Derived = bullet lists only.",
"- Lessons & pitfalls = bullet list only; each bullet must be one single line in this shape:",
" - Symptom: ... Cause: ... Fix: ... Prevention: ...",
"- Invariants = stable cross-session rules only; prefer bullets starting with Always / Never / When / If / Before / After / Prefer / Avoid / Require.",
"- Derived = recent-run distilled learnings, adjustments, and follow-up heuristics that may help the next several runs, but should decay over time.",
"- Keep Invariants stable and long-lived; keep Derived recent, reusable across near-term runs, and decayable.",
"- Start Derived bullets with varied lead-ins (for example: Next run..., When..., If..., To avoid...) instead of repeating one opening phrase.",
"- Keep Derived phrasing non-redundant; do not start every bullet with the same words.",
"- Do not restate long-term rules in Derived.",
"",
"Governance section rules:",
"- If empty, write exactly:",
" - (none captured)",
"- Otherwise, do NOT use bullet lists there.",
"- Use one or more entries in exactly this format:",
"",
"### Entry 1",
"**Priority**: low|medium|high|critical",
"**Status**: pending|triage|promoted_to_skill|done",
"**Area**: frontend|backend|infra|tests|docs|config|<custom area>",
"### Summary",
"<one concise candidate>",
"### Details",
"<short supporting details>",
"### Suggested Action",
"<one concrete next action>",
"",
"Notes:",
"- Keep writer-owned metadata out of the output. The writer generates Logged and IDs.",
"- Prefer structured, machine-parseable output over elegant prose.",
"",
"OUTPUT TEMPLATE (copy this structure exactly):",
"## Context (session background)",
"- ...",
"",
"## Decisions (durable)",
"- ...",
"",
"## User model deltas (about the human)",
"- ...",
"",
"## Agent model deltas (about the assistant/system)",
"- ...",
"",
"## Lessons & pitfalls (symptom / cause / fix / prevention)",
"- Symptom: ... Cause: ... Fix: ... Prevention: ...",
"",
"## Learning governance candidates (.learnings / promotion / skill extraction)",
"### Entry 1",
"**Priority**: medium",
"**Status**: pending",
"**Area**: config",
"### Summary",
"...",
"### Details",
"...",
"### Suggested Action",
"...",
"",
"## Open loops / next actions",
"- ...",
"",
"## Retrieval tags / keywords",
"- ...",
"",
"## Invariants",
"- Always ...",
"",
"## Derived",
"- Next run, ...",
"",
"Recent tool error signals:",
errorHints,
"",
"INPUT:",
"```",
clipped,
"```",
].join("\n");
}
function buildReflectionFallbackText(): string {
return [
"## Context (session background)",
`- ${REFLECTION_FALLBACK_MARKER}`,
"",
"## Decisions (durable)",
"- (none captured)",
"",
"## User model deltas (about the human)",
"- (none captured)",
"",
"## Agent model deltas (about the assistant/system)",
"- (none captured)",
"",
"## Lessons & pitfalls (symptom / cause / fix / prevention)",
"- (none captured)",
"",
"## Learning governance candidates (.learnings / promotion / skill extraction)",
"### Entry 1",
"**Priority**: medium",
"**Status**: triage",
"**Area**: config",
"### Summary",
"Investigate last failed tool execution and decide whether it belongs in .learnings/ERRORS.md.",
"### Details",
"The reflection pipeline fell back; confirm the failure is reproducible before treating it as a durable error record.",
"### Suggested Action",
"Reproduce the latest failed tool execution, classify it as triage or error, and then log it with the appropriate tool/file path evidence.",
"",
"## Open loops / next actions",
"- Investigate why embedded reflection generation failed.",
"",
"## Retrieval tags / keywords",
"- memory-reflection",
"",
"## Invariants",
"- (none captured)",
"",
"## Derived",