-
Notifications
You must be signed in to change notification settings - Fork 730
Expand file tree
/
Copy pathindex.ts
More file actions
7234 lines (6732 loc) · 313 KB
/
Copy pathindex.ts
File metadata and controls
7234 lines (6732 loc) · 313 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, win32 as winPath } 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";
// Detect CLI mode: when running as a CLI subcommand (e.g. `openclaw memory-pro stats`),
// OpenClaw sets OPENCLAW_CLI=1 in the process environment. Registration and
// lifecycle logs are noisy in CLI context (printed to stderr before command output),
// so we downgrade them to debug level when running in CLI mode.
const isCliMode = () => process.env.OPENCLAW_CLI === "1";
// register() can run several times per gateway boot (one per registration
// context) and once per CLI command; the dual-memory hint only needs to be
// taught once per process.
let dualMemoryHintLogged = false;
// Import core components
import { MemoryStore, normalizeStoragePath, type MemoryEntry } from "./src/store.js";
import {
createEmbedder,
getEffectiveVectorDimensions,
} from "./src/embedder.js";
import type { ChunkerAstConfig, CodeChunkLanguage } from "./src/chunker.js";
import {
createRetriever,
normalizeRetrievalConfig,
type RetrievalConfig,
type RetrievalConfigInput,
} from "./src/retriever.js";
import { createScopeManager, resolveScopeFilter, isSystemBypassId, parseAgentIdFromSessionKey } 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 { shouldSkipRetrieval } from "./src/adaptive-retrieval.js";
import { parseClawteamScopes, applyClawteamScopes } from "./src/clawteam-scope.js";
import {
runCompaction,
shouldRunCompaction,
recordCompactionRun,
type CompactionConfig,
} from "./src/memory-compactor.js";
import { embedWithReflectionTransientRetry, runWithReflectionTransientRetryOnce } from "./src/reflection-retry.js";
import { resolveReflectionSessionSearchDirs, stripResetSuffix } from "./src/session-recovery.js";
import {
storeReflectionToLanceDB,
loadAgentReflectionSlicesFromEntries,
DEFAULT_REFLECTION_DERIVED_MAX_AGE_MS,
isOwnedByAgent,
isReflectionMetadataType,
} from "./src/reflection-store.js";
import { parseReflectionMetadata } from "./src/reflection-metadata.js";
import {
extractReflectionLearningGovernanceCandidates,
extractInjectableReflectionMappedMemoryItems,
isRecallUsed,
} from "./src/reflection-slices.js";
import { createReflectionEventId } from "./src/reflection-event-store.js";
import { buildReflectionMappedMetadata, getReflectionMappedMemoryCategory, getReflectionMappedStorageCategory } from "./src/reflection-mapped-metadata.js";
import { buildFallbackCandidate, gateRegexFallbackCapture } from "./src/autocapture-fallback-admission.js";
import { gateMappedReflectionEntries, resolveMappedRowAdmissionController } from "./src/reflection-mapped-admission.js";
import { createMemoryCLI } from "./cli.js";
import { isNoise } from "./src/noise-filter.js";
import {
type ConversationTurn,
buildConversationTurnsForExtraction,
formatConversationTranscript,
neutralizeSpeakerTagSpoof,
nextAutoCaptureMessageId,
normalizeAutoCaptureText,
reconcileTurnsWithKeptTexts,
} from "./src/auto-capture-cleanup.js";
// Import smart extraction & lifecycle components
import { SmartExtractor, createExtractionRateLimiter, stripEnvelopeMetadata } from "./src/smart-extractor.js";
import { compressTexts, estimateConversationValue } from "./src/session-compressor.js";
import { NoisePrototypeBank } from "./src/noise-prototypes.js";
import { createLlmClient, normalizeDirectModelRef } from "./src/llm-client.js";
import { createDecayEngine, DEFAULT_DECAY_CONFIG } from "./src/decay-engine.js";
import { createTierManager, DEFAULT_TIER_CONFIG } from "./src/tier-manager.js";
import { createMemoryUpgrader } from "./src/memory-upgrader.js";
import {
buildSmartMetadata,
parseSmartMetadata,
stringifySmartMetadata,
toLifecycleMemory,
} from "./src/smart-metadata.js";
import {
computeTier1Patch,
isSuppressed as isTier1Suppressed,
TIER1_DEFAULT_BAD_RECALL_DECAY_MS,
TIER1_DEFAULT_SUPPRESSION_DURATION_MS,
} from "./src/auto-recall-tier1.js";
import {
filterUserMdExclusiveRecallResults,
isUserMdExclusiveMemory,
type WorkspaceBoundaryConfig,
} from "./src/workspace-boundary.js";
import {
createAdmissionController,
normalizeAdmissionControlConfig,
resolveAdmissionModel,
resolveRejectedAuditFilePath,
type AdmissionControlConfig,
type AdmissionRejectionAuditEntry,
AdmissionController,
} from "./src/admission-control.js";
import { analyzeIntent, applyCategoryBoost } from "./src/intent-analyzer.js";
import { createOpenClawMemoryCapability } from "./src/openclaw-memory-capability.js";
import {
CanonicalCorpusIndexer,
parseCanonicalCorpusConfig,
type CanonicalCorpusConfig,
} from "./src/corpus-indexer.js";
import {
computeNextDreamingDelayMs,
createDreamingEngine,
normalizeDreamingConfig,
type DreamingConfig,
type DreamingEngine,
} from "./src/dreaming-engine.js";
// ============================================================================
// Configuration & Types
// ============================================================================
interface PluginConfig {
embedding: {
provider: "openai-compatible";
apiKey: SecretCredential | SecretCredential[];
model?: string;
baseURL?: string;
dimensions?: number;
requestDimensions?: number;
maxInputChars?: number;
omitDimensions?: boolean;
taskQuery?: string;
taskPassage?: string;
normalized?: boolean;
chunking?: boolean;
astChunking?: ChunkerAstConfig;
clientTimeoutMs?: number;
};
dbPath?: string;
storageMaintenance?: {
autoCleanup?: {
enabled?: boolean;
intervalHours?: number;
retentionDays?: number;
initialDelayMs?: number;
};
/** Seconds between checks for table updates committed by other processes
* (e.g. a CLI delete-bulk while this gateway holds a long-lived read
* handle). 0 = strong consistency (check every read, default). Unset
* disables the check entirely (matches the LanceDB SDK default). */
readConsistencyIntervalSeconds?: number;
};
redisUrl?: string;
locking?: {
redis?: {
enabled?: boolean;
url?: string;
keyPrefix?: string;
ttlMs?: number;
acquireTimeoutMs?: number;
retryDelayMs?: number;
connectTimeoutMs?: number;
};
};
autoCapture?: boolean;
autoRecall?: boolean;
autoRecallMinLength?: number;
autoRecallMinRepeated?: number;
/** If a memory's last auto-recall injection was more than this many ms ago,
* its bad_recall_count is reset to 0 on the next injection. 0 disables decay. Default: 86400000 (24h). */
autoRecallBadRecallDecayMs?: number;
/** When bad_recall_count reaches the suppression threshold, the memory is
* suppressed from auto-recall for this many ms from now. Default: 1800000 (30min). */
autoRecallSuppressionDurationMs?: number;
autoRecallTimeoutMs?: number;
/** Outer time budget for each startup health check phase (embedding, retrieval).
* Raise on hosts where a cold boot exceeds 8s; the checks run after startup
* and never block the gateway. Default: 8000. */
startupCheckTimeoutMs?: number;
autoRecallMaxItems?: number;
autoRecallMaxChars?: number;
autoRecallPerItemMaxChars?: number;
/** Max query string length before embedding search (safety valve). Default: 2000, range: 100-10000. */
autoRecallMaxQueryLength?: number;
/** Hard per-turn injection cap (safety valve). Overrides autoRecallMaxItems if lower. Default: 10. */
maxRecallPerTurn?: number;
recallMode?: "full" | "summary" | "adaptive" | "off";
/** Agent IDs excluded from auto-recall injection. Useful for background agents (e.g. memory-distiller, cron workers) whose output should not be contaminated by injected memory context. */
autoRecallExcludeAgents?: string[];
/** Agent IDs included in auto-recall injection (whitelist mode). When set, ONLY these agents receive auto-recall. Unresolved agent context falls back to 'main'. If both include and exclude are set, include wins. */
autoRecallIncludeAgents?: string[];
captureAssistant?: boolean;
retrieval?: {
mode?: "hybrid" | "vector";
vectorWeight?: number;
bm25Weight?: number;
minScore?: number;
rerank?: "cross-encoder" | "lightweight" | "none";
candidatePoolSize?: number;
rerankApiKey?: SecretCredential;
rerankModel?: string;
rerankEndpoint?: string;
/** Rerank API timeout in milliseconds (default: 5000). Increase for local/CPU-based rerank servers. */
rerankTimeoutMs?: number;
rerankProvider?:
| "jina"
| "siliconflow"
| "voyage"
| "pinecone"
| "dashscope"
| "tei";
recencyHalfLifeDays?: number;
recencyWeight?: number;
filterNoise?: boolean;
lengthNormAnchor?: number;
hardMinScore?: number;
timeDecayHalfLifeDays?: number;
reinforcementFactor?: number;
maxHalfLifeMultiplier?: number;
neighborEnrichment?: {
enabled?: boolean;
maxPerResult?: number;
};
/** Disable LanceDB native vector search and rank scanned rows with JS cosine. */
disableNativeCosine?: boolean;
};
decay?: {
recencyHalfLifeDays?: number;
recencyWeight?: number;
frequencyWeight?: number;
intrinsicWeight?: number;
staleThreshold?: number;
searchBoostMin?: number;
importanceModulation?: number;
betaCore?: number;
betaWorking?: number;
betaPeripheral?: number;
coreDecayFloor?: number;
workingDecayFloor?: number;
peripheralDecayFloor?: number;
};
tier?: {
coreAccessThreshold?: number;
coreCompositeThreshold?: number;
coreImportanceThreshold?: number;
peripheralCompositeThreshold?: number;
peripheralAgeDays?: number;
workingAccessThreshold?: number;
workingCompositeThreshold?: number;
};
// Smart extraction config
smartExtraction?: boolean;
llm?: {
auth?: "api-key" | "oauth";
apiKey?: SecretCredential;
model?: string;
baseURL?: string;
oauthProvider?: string;
oauthPath?: string;
timeoutMs?: number;
/** Reasoning effort for memory LLM calls (e.g. low | medium | high). Sent only when set; unset leaves the provider default. */
thinkLevel?: string;
};
extractMinMessages?: number;
extractMaxChars?: number;
batchChunkSize?: number;
scopes?: {
default?: string;
definitions?: Record<string, { description: string }>;
agentAccess?: Record<string, string[]>;
};
enableManagementTools?: boolean;
manualStoreSupersede?: boolean;
sessionStrategy?: SessionStrategy;
sessionMemory?: { enabled?: boolean; messageCount?: number };
selfImprovement?: {
enabled?: boolean;
beforeResetNote?: boolean;
skipSubagentBootstrap?: boolean;
ensureLearningFiles?: boolean;
maxEntries?: number;
};
canonicalCorpus?: CanonicalCorpusConfig;
dreaming?: DreamingConfig;
memoryReflection?: {
enabled?: boolean;
storeToLanceDB?: boolean;
writeLegacyCombined?: boolean;
injectMode?: ReflectionInjectMode;
agentId?: string;
model?: string;
messageCount?: number;
maxInputChars?: number;
timeoutMs?: number;
thinkLevel?: ReflectionThinkLevel;
errorReminderMaxEntries?: number;
dedupeErrorSignals?: boolean;
/** Cooldown in ms between reflection triggers for the same session. Default: 120000 (2 min). Set to 0 to disable. */
serialCooldownMs?: number;
/** Max concurrent reflection runs across all agents. Default: 1 (fully serialized, matching the previous behavior). Raise to let agents reflect in parallel. */
maxConcurrentRuns?: number;
/** Agent/session patterns excluded from reflection injection. Supports exact match, wildcard prefix (e.g. "pi-"), and "temp:*". */
excludeAgents?: string[];
/** Run the reflection distiller for group-chat sessions (session keys carrying a ":group:" or ":channel:" segment). Default: true. Set false to skip reflection generation on group channels. */
includeGroupChats?: boolean;
};
mdMirror?: { enabled?: boolean; dir?: string };
workspaceBoundary?: WorkspaceBoundaryConfig;
admissionControl?: AdmissionControlConfig;
memoryCompaction?: {
enabled?: boolean;
minAgeDays?: number;
similarityThreshold?: number;
minClusterSize?: number;
maxMemoriesToScan?: number;
cooldownHours?: number;
};
sessionCompression?: {
enabled?: boolean;
minScoreToKeep?: number;
};
extractionThrottle?: {
skipLowValue?: boolean;
maxExtractionsPerHour?: number;
};
recallPrefix?: {
/**
* Metadata field to use as the category label in auto-recall prefix lines.
* When set, the value of `metadata[categoryField]` replaces the built-in
* category in the `[category:scope]` prefix — if the field is present on
* the entry. Falls back to the built-in category when the field is absent.
*
* Useful for import-based workflows where entries carry a meaningful
* grouping label in a custom metadata field (e.g. "folder" for Apple Notes
* imports, "notebook" for Notion, "collection" for Obsidian).
*
* Default: unset — built-in category is used for all entries.
*
* @example
* recallPrefix: { categoryField: "folder" }
* // Entry with metadata.folder = "Goals" → prefix: [W][Goals:global]
* // Entry without metadata.folder → prefix: [W][preference:global]
*/
categoryField?: string;
};
declaredAgents?: Set<string>;
}
const SUPPORTED_SECRET_REF_SOURCES = ["env", "file"] as const;
type SecretRefSource = (typeof SUPPORTED_SECRET_REF_SOURCES)[number];
type SecretRefConfig = {
source: SecretRefSource;
provider?: string;
id: string;
};
type SecretCredential = string | SecretRefConfig;
type ReflectionThinkLevel = "off" | "minimal" | "low" | "medium" | "high";
type SessionStrategy = "memoryReflection" | "systemSessionMemory" | "none";
type ReflectionInjectMode = "inheritance-only" | "inheritance+derived";
// ============================================================================
// 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 getDefaultMdMirrorDir(): string {
const home = homedir();
return join(home, ".openclaw", "memory", "md-mirror");
}
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 isSecretRefConfig(value: unknown): value is SecretRefConfig {
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
const raw = value as Record<string, unknown>;
return isSupportedSecretRefSource(raw.source) &&
typeof raw.id === "string" && raw.id.trim().length > 0;
}
function isSupportedSecretRefSource(value: unknown): value is SecretRefSource {
return typeof value === "string" &&
(SUPPORTED_SECRET_REF_SOURCES as readonly string[]).includes(value.trim());
}
function isSecretCredential(value: unknown): value is SecretCredential {
return (typeof value === "string" && value.trim().length > 0) || isSecretRefConfig(value);
}
function describeSecretRef(ref: SecretRefConfig): string {
return `source=${ref.source}, id=${ref.id}`;
}
function resolveSecretRef(
api: Pick<OpenClawPluginApi, "resolvePath">,
ref: SecretRefConfig,
label: string,
): string {
const source = ref.source.trim() as SecretRefSource;
const id = ref.id.trim();
try {
if (source === "env") {
const value = process.env[id];
if (!value) throw new Error(`environment variable ${id} is not set`);
return value;
}
if (source === "file") {
const filePath = api.resolvePath(id);
const value = readFileSync(filePath, "utf8").trimEnd();
if (!value) throw new Error(`file ${filePath} is empty`);
return value;
}
const exhaustive: never = source;
throw new Error(`unsupported SecretRef source "${exhaustive}"`);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(`Failed to resolve SecretRef for ${label} (${describeSecretRef(ref)}): ${message}`);
}
}
function resolveSecretCredential(
api: Pick<OpenClawPluginApi, "resolvePath">,
value: SecretCredential,
label: string,
): string {
return typeof value === "string"
? resolveEnvVars(value)
: resolveSecretRef(api, value, label);
}
function resolveSecretCredentialArray(
api: Pick<OpenClawPluginApi, "resolvePath">,
value: SecretCredential | SecretCredential[],
label: string,
): string | string[] {
if (!Array.isArray(value)) return resolveSecretCredential(api, value, label);
return value.map((entry, index) => resolveSecretCredential(api, entry, `${label}[${index}]`));
}
function resolveFirstApiKey(api: Pick<OpenClawPluginApi, "resolvePath">, apiKey: SecretCredential | SecretCredential[]): string {
const key = Array.isArray(apiKey) ? apiKey[0] : apiKey;
if (!key) {
throw new Error("embedding.apiKey is empty");
}
return resolveSecretCredential(api, key, "embedding.apiKey");
}
function resolveOptionalEnvString(value: unknown): string | undefined {
const raw = asNonEmptyString(value);
return raw ? resolveEnvVars(raw) : undefined;
}
function resolveOptionalPathWithEnv(
api: Pick<OpenClawPluginApi, "resolvePath">,
value: string | undefined,
fallback: string,
): string {
const raw = typeof value === "string" && value.trim().length > 0 ? value.trim() : fallback;
return api.resolvePath(resolveEnvVars(raw));
}
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 parseAstChunkingConfig(value: unknown): ChunkerAstConfig | undefined {
if (value === undefined || value === null) return undefined;
if (typeof value !== "object" || Array.isArray(value)) return undefined;
const raw = value as Record<string, unknown>;
const config: ChunkerAstConfig = {};
if (typeof raw.enabled === "boolean") {
config.enabled = raw.enabled;
}
if (Array.isArray(raw.languages)) {
const allowed = new Set<CodeChunkLanguage>(["javascript", "typescript", "python"]);
const languages = raw.languages.filter((item): item is CodeChunkLanguage =>
typeof item === "string" && allowed.has(item as CodeChunkLanguage),
);
if (languages.length > 0) {
config.languages = languages;
}
}
return config;
}
// Like parsePositiveInt but allows 0. Used for fields where 0 is a meaningful
// "disabled" sentinel (e.g. autoRecallBadRecallDecayMs=0 disables decay).
function parseNonNegativeInt(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 clampInt(value: number, min: number, max: number): number {
if (!Number.isFinite(value)) return min;
return Math.min(max, Math.max(min, Math.floor(value)));
}
function getEffectiveAutoRecallMaxItems(config: PluginConfig): number {
const configMaxItems = clampInt(config.autoRecallMaxItems ?? 3, 1, 20);
const maxPerTurn = clampInt(config.maxRecallPerTurn ?? 10, 1, 50);
return Math.min(configMaxItems, maxPerTurn);
}
function getAutoRecallRetrieveLimit(autoRecallMaxItems: number): number {
return clampInt(Math.max(autoRecallMaxItems * 2, autoRecallMaxItems), 1, 20);
}
function getAutoRecallRerankInputLimit(retrieveLimit: number): number {
return clampInt(retrieveLimit, 1, 20) * 2;
}
function getAutoRecallRerankTimeoutMs(
config: PluginConfig,
retrievalConfig: RetrievalConfig,
autoRecallTimeoutMs: number,
): number | undefined {
if (retrievalConfig.rerank !== "cross-encoder" || !retrievalConfig.rerankApiKey) return undefined;
if (typeof config.retrieval?.rerankTimeoutMs === "number") return undefined;
if (!Number.isFinite(autoRecallTimeoutMs) || autoRecallTimeoutMs <= 0) return undefined;
const halfBudget = Math.floor(autoRecallTimeoutMs / 2);
if (halfBudget < 100) return 0;
if (autoRecallTimeoutMs <= 1_000) return halfBudget;
return clampInt(halfBudget, 500, 2_500);
}
export function buildAutoRecallRerankCostWarning(
config: PluginConfig,
retrievalConfig: RetrievalConfig = normalizeRetrievalConfig(
config.retrieval as RetrievalConfigInput | undefined,
),
): string | null {
if (config.autoRecall !== true || config.recallMode === "off") return null;
if (retrievalConfig.mode === "vector") return null;
if (retrievalConfig.rerank !== "cross-encoder" || !retrievalConfig.rerankApiKey) return null;
const autoRecallMaxItems = getEffectiveAutoRecallMaxItems(config);
const retrieveLimit = getAutoRecallRetrieveLimit(autoRecallMaxItems);
const rerankInputLimit = getAutoRecallRerankInputLimit(retrieveLimit);
if (rerankInputLimit <= autoRecallMaxItems) return null;
const provider = retrievalConfig.rerankProvider || "jina";
return (
`[memory-lancedb-pro] autoRecall=true with hybrid cross-encoder rerank (${provider}) can send up to ` +
`${rerankInputLimit} candidates to the reranker for each prompt while injecting at most ` +
`${autoRecallMaxItems} memories. External rerank cost follows the auto-recall rerank input window ` +
`(${retrieveLimit} retrieved items x2), not retrieval.candidatePoolSize or the final ` +
`autoRecallMaxItems injection cap. Lower autoRecallMaxItems or maxRecallPerTurn, set ` +
`retrieval.rerank to "lightweight" or "none", or raise autoRecallMinLength to reduce calls.`
);
}
function resolveLlmTimeoutMs(config: PluginConfig): number {
return parsePositiveInt(config.llm?.timeoutMs) ?? 30000;
}
/**
* Hook identity: an explicit agent id, else the id parsed out of the session
* key, else NULL. There is deliberately no "main" fallback. A synthesized
* identity passes agent-id validation (main is a declared agent) and then
* resolves MAIN's scopes, so an unattributable session would read and write
* main's private content. Callers must skip agent-specific work on null.
*/
function resolveHookAgentId(
explicitAgentId: string | undefined,
sessionKey: string | undefined,
): string | null {
const trimmedExplicit = explicitAgentId?.trim();
if (trimmedExplicit && trimmedExplicit.length > 0) return trimmedExplicit;
const fromSessionKey = parseAgentIdFromSessionKey(sessionKey)?.trim();
return fromSessionKey && fromSessionKey.length > 0 ? fromSessionKey : null;
}
// Detect when agentId came from a chat_id / user: source (e.g. "657229412030480397").
// These are numeric Discord/Telegram IDs mistakenly used as agent IDs and cause
// auto-recall to timeout. We skip them rather than block all pure-numeric IDs
// to avoid false positives for intentionally numeric agent names.
function isChatIdBasedAgentId(agentId: string): boolean {
return /^\d+$/.test(agentId); // pure digits = almost certainly a chat_id, not a real agent
}
/**
* Returns true when agentId is invalid — either empty/undefined, detected as a
* numeric chat_id, or not present in the openclaw.json declared agents list.
* Pass `declaredAgents` (from config.declaredAgents) for authoritative validation.
*/
export function isInvalidAgentIdFormat(
agentId: string | undefined,
declaredAgents?: Set<string>,
): boolean {
// Layer 1: empty/undefined/whitespace-only are all invalid
if (!agentId || (typeof agentId === "string" && !agentId.trim())) return true;
// Pure numeric IDs are almost always chat_id extractions, not real agent IDs.
if (isChatIdBasedAgentId(agentId)) return true;
// If we have a declared agents list, treat unknown IDs as invalid.
if (declaredAgents && declaredAgents.size > 0 && !declaredAgents.has(agentId)) {
return true;
}
return false;
}
function resolveSourceFromSessionKey(sessionKey: string | undefined): string {
const trimmed = sessionKey?.trim() ?? "";
const match = /^agent:[^:]+:([^:]+)/.exec(trimmed);
const source = match?.[1]?.trim();
return source || "unknown";
}
function summarizeAgentEndMessages(messages: unknown[]): string {
const roleCounts = new Map<string, number>();
let textBlocks = 0;
let stringContents = 0;
let arrayContents = 0;
for (const msg of messages) {
if (!msg || typeof msg !== "object") continue;
const msgObj = msg as Record<string, unknown>;
const role =
typeof msgObj.role === "string" && msgObj.role.trim().length > 0
? msgObj.role
: "unknown";
roleCounts.set(role, (roleCounts.get(role) ?? 0) + 1);
const content = msgObj.content;
if (typeof content === "string") {
stringContents++;
continue;
}
if (Array.isArray(content)) {
arrayContents++;
for (const block of content) {
if (
block &&
typeof block === "object" &&
(block as Record<string, unknown>).type === "text" &&
typeof (block as Record<string, unknown>).text === "string"
) {
textBlocks++;
}
}
}
}
const roles =
Array.from(roleCounts.entries())
.map(([role, count]) => `${role}:${count}`)
.join(", ") || "none";
return `messages=${messages.length}, roles=[${roles}], stringContents=${stringContents}, arrayContents=${arrayContents}, textBlocks=${textBlocks}`;
}
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.",
].join("\n");
const SELF_IMPROVEMENT_RESET_REMINDER_CONTEXT = [
"<self-improvement-reminder>",
"If anything was learned/corrected in the previous session, 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.",
"</self-improvement-reminder>",
].join("\n");
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_MAX_CONCURRENT_RUNS = 1;
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_SERIAL_GUARD_COOLDOWN_MS = 120_000;
const DEFAULT_REFLECTION_EMPTY_EVENT_GUARD_TTL_MS = 120_000;
const DEFAULT_REFLECTION_EMPTY_EVENT_GUARD_MAX_ENTRIES = 200;
const DEFAULT_REFLECTION_CACHE_TTL_MS = 15_000;
// After /new or /reset, the just-closed session may have generated fresh
// derived deltas. Keep those out of the immediately opened prompt window.
const DEFAULT_REFLECTION_BOUNDARY_DERIVED_SUPPRESSION_MS = 120_000;
const REFLECTION_FALLBACK_MARKER = "(fallback) Reflection generation failed; storing minimal pointer only.";
const DIAG_BUILD_TAG = "memory-lancedb-pro-diag-20260308-0058";
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 ReflectionDerivedSuppressionState = {
updatedAt: number;
until: number;
reason: string;
};
type ReflectionEmptyEventGuardEntry = {
updatedAt: number;
reason: string;
};
type EmbeddedPiRunner = (params: Record<string, unknown>) => Promise<unknown>;
const requireFromHere = createRequire(import.meta.url);
let embeddedPiRunnerPromise: Promise<EmbeddedPiRunner> | null = null;
// Circuit breaker for Layer 1: after 3 consecutive failures within 5min, skip Layer 1
const layer1FailureTimestamps: number[] = [];
const LAYER1_FAILURE_WINDOW_MS = 5 * 60 * 1000; // 5 minutes
const LAYER1_FAILURE_THRESHOLD = 3;
/** Reports a Layer 1 runner execution failure. Called by the caller when Layer 1 runner throws. */
export function reportLayer1Failure(): void {
const now = Date.now();
layer1FailureTimestamps.push(now);
// Keep only failures within the window
const cutoff = now - LAYER1_FAILURE_WINDOW_MS;
while (layer1FailureTimestamps.length > 0 && layer1FailureTimestamps[0] < cutoff) {
layer1FailureTimestamps.shift();
}
}
export function isLayer1CircuitOpen(): boolean {
const now = Date.now();
const cutoff = now - LAYER1_FAILURE_WINDOW_MS;
const recentFailures = layer1FailureTimestamps.filter((t) => t >= cutoff);
return recentFailures.length >= LAYER1_FAILURE_THRESHOLD;
}
export function toImportSpecifier(
value: string,
platform: NodeJS.Platform = process.platform,
): string {
const trimmed = value.trim();
if (!trimmed) return "";
if (trimmed.startsWith("file://")) return trimmed;
if (trimmed.startsWith("/")) return pathToFileURL(trimmed, { windows: false }).href;
// Handle Windows absolute paths (e.g. C:\Users\... or D:/Program Files/...) — PR #593
if (platform === 'win32' && /^[a-zA-Z]:[/\\]/.test(trimmed)) {
return pathToFileURL(trimmed, { windows: true }).href;
}
// Handle UNC paths (\\server\share or \\?\UNC\\server\share) — PR #593
// Regex breakdown: ^\\\\ = starts with \\
// [^\\]+ = server name (one or more non-backslash chars)
// \\[^\\]+ = \ + share name (one or more non-backslash chars)
// Examples matched: \\server\share, \\fileserver\company-share, \\?\UNC\server\share
// Examples NOT matched: C:\path (drive letter, handled above), /unix/path (POSIX)
if (platform === 'win32' && /^\\\\[^\\]+\\[^\\]+/.test(trimmed)) {
// Extended prefix \\?\UNC\\ means "long UNC name" — already normalized.
// Pass directly so we don't double-normalize (e.g. avoid \\?\UNC\\?\UNC\\...).
if (trimmed.startsWith('\\\\?\\UNC\\')) {
return pathToFileURL(trimmed, { windows: true }).href;
}
// Standard UNC: \\server\share -> \\?\UNC\\server\share -> file://server/share
// strip leading \\ (2 chars) -> server\share, then prefix \\?\UNC\\
const normalized = '\\\\?\\UNC\\' + trimmed.slice(2);
return pathToFileURL(normalized, { windows: true }).href;
}
return trimmed;
}
type ExtensionImportSpecifierOptions = {
platform?: NodeJS.Platform;
env?: NodeJS.ProcessEnv;
resolveOpenClawExtensionApi?: () => string;
};
export function getExtensionApiImportSpecifiers(
options: ExtensionImportSpecifierOptions = {},
): string[] {
const platform = options.platform ?? process.platform;
const env = options.env ?? process.env;
const envPath = env.OPENCLAW_EXTENSION_API_PATH?.trim();
const joinForPlatform = platform === "win32" ? winPath.join : join;
const specifiers: string[] = [];
if (envPath) specifiers.push(toImportSpecifier(envPath, platform));
specifiers.push("openclaw/dist/extensionAPI.js");
try {
const resolved = options.resolveOpenClawExtensionApi
? options.resolveOpenClawExtensionApi()
: requireFromHere.resolve("openclaw/dist/extensionAPI.js");
specifiers.push(toImportSpecifier(resolved, platform));
} catch {
// ignore resolve failures and continue fallback probing
}
if (platform === "win32") {
if (env.APPDATA) {
const windowsNpmPath = joinForPlatform(env.APPDATA, "npm", "node_modules", "openclaw", "dist", "extensionAPI.js");
specifiers.push(toImportSpecifier(windowsNpmPath, platform));
}
if (env.ProgramFiles) {
const windowsProgramFilesPath = joinForPlatform(env.ProgramFiles, "nodejs", "node_modules", "openclaw", "dist", "extensionAPI.js");
specifiers.push(toImportSpecifier(windowsProgramFilesPath, platform));
}
} else {
specifiers.push(toImportSpecifier("/usr/lib/node_modules/openclaw/dist/extensionAPI.js", platform));
specifiers.push(toImportSpecifier("/usr/local/lib/node_modules/openclaw/dist/extensionAPI.js", platform));
specifiers.push(toImportSpecifier("/opt/homebrew/lib/node_modules/openclaw/dist/extensionAPI.js", platform));
}
return [...new Set(specifiers.filter(Boolean))];
}
/**
* Layer 1: 新 SDK API — api.runtime.agent.runEmbeddedPiAgent (4.22+)
* Layer 2: 舊 extensionAPI.js dynamic import(4.24-4.26 SDK 仍保留)
* Layer 3: CLI fallback
*
* 遷移自 Bug 2(Issue #606):原本只使用 Layer 2,現改為 Try-New-First。
*/
// eslint-disable-next-line import/export
export async function loadEmbeddedPiRunner(api: OpenClawPluginApi): Promise<EmbeddedPiRunner> {
// Layer 1: 嘗試新 SDK API (with circuit breaker)
if (!isLayer1CircuitOpen()) {
const newApi = ((api as unknown as { runtime?: { agent?: Record<string, unknown> } }).runtime?.agent);
if (typeof newApi?.runEmbeddedPiAgent === "function") {
const runner = newApi.runEmbeddedPiAgent.bind(newApi);
// Bug 2 fix: 將 Layer 1 結果寫入 cache,避免後續並發呼叫時 Layer 2 覆蓋掉 Layer 1
embeddedPiRunnerPromise ??= Promise.resolve(runner as EmbeddedPiRunner);
return embeddedPiRunnerPromise;
}
}
// Layer 2: Fallback 舊 extensionAPI.js
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(" | ")}`
);
})();
}
// F2 fix: restore retry-on-failure semantics removed in PR716
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 {