@agentmemory/agentmemory 0.9.29 → 0.9.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/.env.example +83 -22
  2. package/AGENTS.md +17 -24
  3. package/README.md +447 -170
  4. package/dist/.env.example +83 -22
  5. package/dist/cli.d.mts.map +1 -1
  6. package/dist/cli.mjs +1221 -335
  7. package/dist/cli.mjs.map +1 -1
  8. package/dist/{connect-Qaeq15TQ.mjs → connect-B4_ca6BD.mjs} +30 -39
  9. package/dist/connect-B4_ca6BD.mjs.map +1 -0
  10. package/dist/docker-compose.yml +40 -14
  11. package/dist/hooks/_capture.d.mts +22 -0
  12. package/dist/hooks/_capture.d.mts.map +1 -0
  13. package/dist/hooks/_capture.mjs +908 -0
  14. package/dist/hooks/_capture.mjs.map +1 -0
  15. package/dist/hooks/antigravity-bridge.d.mts +1 -1
  16. package/dist/hooks/antigravity-bridge.d.mts.map +1 -1
  17. package/dist/hooks/antigravity-bridge.mjs +24 -15
  18. package/dist/hooks/antigravity-bridge.mjs.map +1 -1
  19. package/dist/hooks/notification.mjs +17 -25
  20. package/dist/hooks/notification.mjs.map +1 -1
  21. package/dist/hooks/post-commit.mjs +71 -1
  22. package/dist/hooks/post-commit.mjs.map +1 -1
  23. package/dist/hooks/post-tool-failure.mjs +59 -25
  24. package/dist/hooks/post-tool-failure.mjs.map +1 -1
  25. package/dist/hooks/post-tool-use.mjs +87 -35
  26. package/dist/hooks/post-tool-use.mjs.map +1 -1
  27. package/dist/hooks/pre-compact.mjs +83 -3
  28. package/dist/hooks/pre-compact.mjs.map +1 -1
  29. package/dist/hooks/pre-tool-use.mjs +71 -1
  30. package/dist/hooks/pre-tool-use.mjs.map +1 -1
  31. package/dist/hooks/prompt-submit.mjs +13 -21
  32. package/dist/hooks/prompt-submit.mjs.map +1 -1
  33. package/dist/hooks/session-end.mjs +25 -20
  34. package/dist/hooks/session-end.mjs.map +1 -1
  35. package/dist/hooks/session-start.mjs +80 -3
  36. package/dist/hooks/session-start.mjs.map +1 -1
  37. package/dist/hooks/stop.mjs +71 -1
  38. package/dist/hooks/stop.mjs.map +1 -1
  39. package/dist/hooks/subagent-start.mjs +16 -25
  40. package/dist/hooks/subagent-start.mjs.map +1 -1
  41. package/dist/hooks/subagent-stop.mjs +17 -25
  42. package/dist/hooks/subagent-stop.mjs.map +1 -1
  43. package/dist/hooks/task-completed.mjs +19 -27
  44. package/dist/hooks/task-completed.mjs.map +1 -1
  45. package/dist/iii-config.docker.yaml +10 -10
  46. package/dist/iii-config.yaml +3 -1
  47. package/dist/{image-refs-BKLmp_sD.mjs → image-refs-BaT-9oMU.mjs} +2 -2
  48. package/dist/image-refs-BaT-9oMU.mjs.map +1 -0
  49. package/dist/{image-refs-CJgZmb9X.mjs → image-refs-T_urbwHM.mjs} +3 -3
  50. package/dist/image-refs-T_urbwHM.mjs.map +1 -0
  51. package/dist/{keyed-mutex-DTHtcZrt.mjs → image-store-BsN4vyjr.mjs} +2 -14
  52. package/dist/image-store-BsN4vyjr.mjs.map +1 -0
  53. package/dist/index.mjs +12943 -6218
  54. package/dist/index.mjs.map +1 -1
  55. package/dist/{schema-BFZhNTF7.mjs → keyed-mutex-DchXsyfP.mjs} +28 -4
  56. package/dist/keyed-mutex-DchXsyfP.mjs.map +1 -0
  57. package/dist/secret-store-BnY3A50C.mjs +2348 -0
  58. package/dist/secret-store-BnY3A50C.mjs.map +1 -0
  59. package/dist/{src-G7yt8gGm.mjs → src-Jsq9LCeH.mjs} +5941 -2180
  60. package/dist/src-Jsq9LCeH.mjs.map +1 -0
  61. package/dist/{standalone-BqNJDJ04.mjs → standalone-DKCdrf1d.mjs} +39 -12
  62. package/dist/standalone-DKCdrf1d.mjs.map +1 -0
  63. package/dist/standalone.d.mts.map +1 -1
  64. package/dist/standalone.mjs +249 -14
  65. package/dist/standalone.mjs.map +1 -1
  66. package/dist/status-IRz7ta8-.mjs +2344 -0
  67. package/dist/status-IRz7ta8-.mjs.map +1 -0
  68. package/dist/viewer/index.html +7224 -2794
  69. package/docker-compose.yml +40 -14
  70. package/iii-config.docker.yaml +10 -10
  71. package/iii-config.yaml +3 -1
  72. package/integrations/pi/index.ts +2 -3
  73. package/integrations/pi/security.ts +52 -0
  74. package/package.json +13 -4
  75. package/plugin/.claude-plugin/plugin.json +2 -2
  76. package/plugin/.codex-plugin/plugin.json +26 -4
  77. package/plugin/.devin-plugin/plugin.json +1 -1
  78. package/plugin/.mcp.codex.json +12 -0
  79. package/plugin/.mcp.copilot.json +2 -7
  80. package/plugin/.mcp.json +2 -7
  81. package/plugin/assets/icon.svg +35 -0
  82. package/plugin/hooks/hooks.copilot.json +11 -11
  83. package/plugin/opencode/README.md +266 -30
  84. package/plugin/opencode/agentmemory-capture.ts +572 -3
  85. package/plugin/opencode/plugin.json +1 -1
  86. package/plugin/plugin.json +1 -1
  87. package/plugin/scripts/_capture.d.mts +22 -0
  88. package/plugin/scripts/_capture.d.mts.map +1 -0
  89. package/plugin/scripts/_capture.mjs +908 -0
  90. package/plugin/scripts/_capture.mjs.map +1 -0
  91. package/plugin/scripts/antigravity-bridge.d.mts +1 -1
  92. package/plugin/scripts/antigravity-bridge.d.mts.map +1 -1
  93. package/plugin/scripts/antigravity-bridge.mjs +24 -15
  94. package/plugin/scripts/antigravity-bridge.mjs.map +1 -1
  95. package/plugin/scripts/notification.mjs +17 -25
  96. package/plugin/scripts/notification.mjs.map +1 -1
  97. package/plugin/scripts/plugin-bridge.mjs +378 -0
  98. package/plugin/scripts/post-commit.mjs +71 -1
  99. package/plugin/scripts/post-commit.mjs.map +1 -1
  100. package/plugin/scripts/post-tool-failure.mjs +59 -25
  101. package/plugin/scripts/post-tool-failure.mjs.map +1 -1
  102. package/plugin/scripts/post-tool-use.mjs +87 -35
  103. package/plugin/scripts/post-tool-use.mjs.map +1 -1
  104. package/plugin/scripts/pre-compact.mjs +83 -3
  105. package/plugin/scripts/pre-compact.mjs.map +1 -1
  106. package/plugin/scripts/pre-tool-use.mjs +71 -1
  107. package/plugin/scripts/pre-tool-use.mjs.map +1 -1
  108. package/plugin/scripts/prompt-submit.mjs +13 -21
  109. package/plugin/scripts/prompt-submit.mjs.map +1 -1
  110. package/plugin/scripts/session-end.mjs +25 -20
  111. package/plugin/scripts/session-end.mjs.map +1 -1
  112. package/plugin/scripts/session-start.mjs +80 -3
  113. package/plugin/scripts/session-start.mjs.map +1 -1
  114. package/plugin/scripts/stop.mjs +71 -1
  115. package/plugin/scripts/stop.mjs.map +1 -1
  116. package/plugin/scripts/subagent-start.mjs +16 -25
  117. package/plugin/scripts/subagent-start.mjs.map +1 -1
  118. package/plugin/scripts/subagent-stop.mjs +17 -25
  119. package/plugin/scripts/subagent-stop.mjs.map +1 -1
  120. package/plugin/scripts/task-completed.mjs +19 -27
  121. package/plugin/scripts/task-completed.mjs.map +1 -1
  122. package/plugin/skills/_shared/TROUBLESHOOTING.md +22 -6
  123. package/plugin/skills/agentmemory-agents/REFERENCE.md +3 -3
  124. package/plugin/skills/agentmemory-config/REFERENCE.md +49 -1
  125. package/plugin/skills/agentmemory-config/SKILL.md +44 -7
  126. package/plugin/skills/agentmemory-mcp-tools/REFERENCE.md +1 -1
  127. package/plugin/skills/agentmemory-rest-api/REFERENCE.md +10 -2
  128. package/plugin/skills/handoff/SKILL.md +4 -2
  129. package/plugin/skills/memory-discipline/SKILL.md +13 -5
  130. package/dist/connect-Qaeq15TQ.mjs.map +0 -1
  131. package/dist/image-refs-BKLmp_sD.mjs.map +0 -1
  132. package/dist/image-refs-CJgZmb9X.mjs.map +0 -1
  133. package/dist/keyed-mutex-DTHtcZrt.mjs.map +0 -1
  134. package/dist/logger-BEB7pCI9.mjs +0 -43
  135. package/dist/logger-BEB7pCI9.mjs.map +0 -1
  136. package/dist/schema-BFZhNTF7.mjs.map +0 -1
  137. package/dist/src-G7yt8gGm.mjs.map +0 -1
  138. package/dist/standalone-BqNJDJ04.mjs.map +0 -1
  139. package/dist/tools-registry-BV_2bu7z.mjs +0 -1405
  140. package/dist/tools-registry-BV_2bu7z.mjs.map +0 -1
@@ -0,0 +1,2348 @@
1
+ import { o as generateId, r as KV, t as withKeyedLock } from "./keyed-mutex-DchXsyfP.mjs";
2
+ import { chmodSync, closeSync, existsSync, linkSync, mkdirSync, openSync, readFileSync, rmSync, unlinkSync, writeSync } from "node:fs";
3
+ import { basename, dirname, isAbsolute, join, resolve } from "node:path";
4
+ import { homedir } from "node:os";
5
+ import pc from "picocolors";
6
+ import { randomBytes } from "node:crypto";
7
+ import { readFile, stat } from "node:fs/promises";
8
+ //#region src/cli/engine-config.ts
9
+ const SEEDED_BUILTIN_WORKERS = [
10
+ "http",
11
+ "iii-http",
12
+ "state",
13
+ "iii-state",
14
+ "queue",
15
+ "iii-queue",
16
+ "pubsub",
17
+ "iii-pubsub",
18
+ "cron",
19
+ "iii-cron",
20
+ "iii-stream",
21
+ "iii-observability",
22
+ "iii-worker-manager"
23
+ ];
24
+ function configuredPersistDir(renderedConfig) {
25
+ const lines = renderedConfig.split("\n");
26
+ const block = workerBlock(lines, "configuration");
27
+ if (!block) return null;
28
+ for (let i = block.start + 1; i < block.end; i++) {
29
+ const match = lines[i].trim().match(/^directory:\s*(.+?)\s*$/);
30
+ if (match) return match[1].replace(/^(['"])(.*)\1$/, "$2");
31
+ }
32
+ return null;
33
+ }
34
+ const ENGINE_DEFAULT_SAVE_INTERVAL_MS = 5e3;
35
+ const ENGINE_FLUSH_MARGIN_MS = 1500;
36
+ function engineFlushWaitMs(stateBackend, configTexts) {
37
+ if (stateBackend === "redis") return 0;
38
+ return engineSaveIntervalMs(configTexts) + ENGINE_FLUSH_MARGIN_MS;
39
+ }
40
+ function captureDurableAfterMs(stateBackend, configTexts) {
41
+ if (stateBackend === "redis") return ENGINE_FLUSH_MARGIN_MS;
42
+ return engineSaveIntervalMs(configTexts) + ENGINE_FLUSH_MARGIN_MS;
43
+ }
44
+ function engineSaveIntervalMs(configTexts) {
45
+ const intervals = [];
46
+ for (const text of configTexts) {
47
+ const explicit = [...text.matchAll(/save_interval_ms:\s*(\d+)/g)].map((m) => parseInt(m[1], 10));
48
+ intervals.push(...explicit);
49
+ if ((text.match(/store_method:\s*file_based/g)?.length ?? 0) > explicit.length) intervals.push(ENGINE_DEFAULT_SAVE_INTERVAL_MS);
50
+ }
51
+ return intervals.length > 0 ? Math.max(...intervals) : ENGINE_DEFAULT_SAVE_INTERVAL_MS;
52
+ }
53
+ function engineStateConfigPaths(engineCwd, runtimePath) {
54
+ return [...persistedBuiltinConfigDirs(engineCwd, runtimePath).map((dir) => join(dir, "iii-state.yaml")), runtimePath];
55
+ }
56
+ function persistedBuiltinConfigDirs(engineCwd, configPath, renderedConfig) {
57
+ const dirs = [
58
+ join(engineCwd, "config"),
59
+ join(dirname(configPath), "config"),
60
+ join(engineCwd, "data", "configuration")
61
+ ];
62
+ const custom = renderedConfig ? configuredPersistDir(renderedConfig) : null;
63
+ if (custom) dirs.unshift(resolve(engineCwd, custom));
64
+ return [...new Set(dirs)];
65
+ }
66
+ function persistedBuiltinConfigPaths(engineCwd, configPath, renderedConfig) {
67
+ return persistedBuiltinConfigDirs(engineCwd, configPath, renderedConfig).flatMap((dir) => SEEDED_BUILTIN_WORKERS.map((id) => join(dir, `${id}.yaml`)));
68
+ }
69
+ function isPersistedBuiltinEntry(content, id) {
70
+ return content.split("\n").find((line) => line.trim() !== "")?.trim() === `id: ${id}`;
71
+ }
72
+ function clearPersistedBuiltinConfig(engineCwd, configPath, renderedConfig) {
73
+ const cleared = [];
74
+ for (const path of persistedBuiltinConfigPaths(engineCwd, configPath, renderedConfig)) try {
75
+ if (!isPersistedBuiltinEntry(readFileSync(path, "utf8"), basename(path, ".yaml"))) continue;
76
+ rmSync(path);
77
+ cleared.push(path);
78
+ } catch (err) {
79
+ if (err.code === "ENOENT") continue;
80
+ throw new Error(`could not remove persisted engine config ${path}: ${String(err)}`);
81
+ }
82
+ return cleared;
83
+ }
84
+ function yamlSingleQuote(value) {
85
+ return `'${value.replace(/'/g, "''")}'`;
86
+ }
87
+ function workerBlock(lines, name) {
88
+ const marker = `- name: ${name}`;
89
+ const start = lines.findIndex((line) => line.trim() === marker);
90
+ if (start === -1) return null;
91
+ const indent = lines[start].match(/^\s*/)?.[0] ?? "";
92
+ let end = lines.length;
93
+ for (let i = start + 1; i < lines.length; i++) {
94
+ const line = lines[i];
95
+ if (line.startsWith(indent) && line.trim().startsWith("- name: ")) {
96
+ end = i;
97
+ break;
98
+ }
99
+ }
100
+ return {
101
+ start,
102
+ end,
103
+ indent
104
+ };
105
+ }
106
+ function setWorkerPort(lines, name, port) {
107
+ let block = workerBlock(lines, name);
108
+ if (!block && name === "iii-worker-manager") {
109
+ const workersIndex = lines.findIndex((line) => line.trim() === "workers:");
110
+ if (workersIndex === -1) return;
111
+ lines.splice(workersIndex + 1, 0, " - name: iii-worker-manager", " config:", ` port: ${port}`, " host: 127.0.0.1");
112
+ return;
113
+ }
114
+ if (!block) return;
115
+ const portIndex = lines.findIndex((line, index) => index > block.start && index < block.end && line.trim().startsWith("port:"));
116
+ if (portIndex !== -1) {
117
+ lines[portIndex] = `${lines[portIndex].match(/^\s*/)?.[0] ?? `${block.indent} `}port: ${port}`;
118
+ return;
119
+ }
120
+ const configIndex = lines.findIndex((line, index) => index > block.start && index < block.end && line.trim() === "config:");
121
+ if (configIndex !== -1) {
122
+ const configIndent = lines[configIndex].match(/^\s*/)?.[0] ?? `${block.indent} `;
123
+ lines.splice(configIndex + 1, 0, `${configIndent} port: ${port}`);
124
+ }
125
+ }
126
+ function setFileStoreSaveInterval(lines, workerName, override) {
127
+ const block = workerBlock(lines, workerName);
128
+ if (!block) return;
129
+ const methodIndex = lines.findIndex((line, index) => index > block.start && index < block.end && line.trim() === "store_method: file_based");
130
+ if (methodIndex === -1) return;
131
+ const indent = lines[methodIndex].match(/^\s*/)?.[0] ?? "";
132
+ const intervalIndex = lines.findIndex((line, index) => index > block.start && index < block.end && line.trim().startsWith("save_interval_ms:"));
133
+ if (intervalIndex !== -1) {
134
+ if (override === void 0) return;
135
+ lines[intervalIndex] = `${lines[intervalIndex].match(/^\s*/)?.[0] ?? indent}save_interval_ms: ${override}`;
136
+ return;
137
+ }
138
+ lines.splice(methodIndex + 1, 0, `${indent}save_interval_ms: ${override ?? 2e3}`);
139
+ }
140
+ const REDIS_URL_ENV_REF = "${AGENTMEMORY_REDIS_URL}";
141
+ const UNSAFE_REDIS_URL_CHARS = /['\u0000-\u001f\u007f]/;
142
+ function replaceKvAdapterWithRedis(lines, workerName) {
143
+ const block = workerBlock(lines, workerName);
144
+ if (!block) throw new Error(`AGENTMEMORY_STATE_BACKEND=redis requires a "${workerName}" worker in the engine config, but none was found.`);
145
+ const adapterIndex = lines.findIndex((line, index) => index > block.start && index < block.end && line.trim() === "adapter:");
146
+ if (adapterIndex === -1) throw new Error(`AGENTMEMORY_STATE_BACKEND=redis requires an "adapter:" block under the "${workerName}" worker in the engine config, but none was found.`);
147
+ const adapterIndent = lines[adapterIndex].match(/^\s*/)?.[0] ?? "";
148
+ let end = block.end;
149
+ for (let i = adapterIndex + 1; i < block.end; i++) {
150
+ const line = lines[i];
151
+ if (line.trim() === "") continue;
152
+ if ((line.match(/^\s*/)?.[0] ?? "").length <= adapterIndent.length) {
153
+ end = i;
154
+ break;
155
+ }
156
+ }
157
+ const childIndent = `${adapterIndent} `;
158
+ const grandchildIndent = `${adapterIndent} `;
159
+ lines.splice(adapterIndex + 1, end - (adapterIndex + 1), `${childIndent}name: redis`, `${childIndent}config:`, `${grandchildIndent}redis_url: ${yamlSingleQuote(REDIS_URL_ENV_REF)}`);
160
+ }
161
+ function setManagedCorsOrigins(lines, restPort, viewerPort) {
162
+ const block = workerBlock(lines, "iii-http");
163
+ if (!block) return;
164
+ const originsIndex = lines.findIndex((line, index) => index > block.start && index < block.end && line.trim().startsWith("allowed_origins:"));
165
+ if (originsIndex === -1) return;
166
+ lines[originsIndex] = `${lines[originsIndex].match(/^\s*/)?.[0] ?? " "}allowed_origins: ["http://localhost:${restPort}", "http://localhost:${viewerPort}", "http://127.0.0.1:${restPort}", "http://127.0.0.1:${viewerPort}"]`;
167
+ }
168
+ function renderEngineConfig(template, options) {
169
+ if (options.stateBackend?.kind === "redis" && !options.stateBackend.redisUrl) throw new Error("AGENTMEMORY_STATE_BACKEND=redis requires AGENTMEMORY_REDIS_URL to be set (e.g. redis://localhost:6379).");
170
+ if (options.stateBackend?.kind === "redis" && UNSAFE_REDIS_URL_CHARS.test(options.stateBackend.redisUrl ?? "")) throw new Error("AGENTMEMORY_REDIS_URL contains a single quote or a control character, which breaks the engine config once the engine expands it. Percent-encode those characters in the URL (for example a single quote as %27).");
171
+ const rendered = template.replace("file_path: ./data/state_store.db", `file_path: ${yamlSingleQuote(join(options.dataDir, "state_store.db"))}`).replace("file_path: ./data/stream_store", `file_path: ${yamlSingleQuote(join(options.dataDir, "stream_store"))}`);
172
+ const usesRedis = options.stateBackend?.kind === "redis";
173
+ const lines = rendered.split("\n");
174
+ setFileStoreSaveInterval(lines, "iii-state", options.saveIntervalMs);
175
+ setFileStoreSaveInterval(lines, "iii-stream", options.saveIntervalMs);
176
+ if (options.ports) {
177
+ setWorkerPort(lines, "iii-http", options.ports.restPort);
178
+ setWorkerPort(lines, "iii-stream", options.ports.streamPort);
179
+ setWorkerPort(lines, "iii-worker-manager", options.ports.enginePort);
180
+ setManagedCorsOrigins(lines, options.ports.restPort, options.ports.viewerPort);
181
+ }
182
+ if (usesRedis) {
183
+ replaceKvAdapterWithRedis(lines, "iii-state");
184
+ replaceKvAdapterWithRedis(lines, "iii-stream");
185
+ }
186
+ return lines.join("\n");
187
+ }
188
+ //#endregion
189
+ //#region src/cli/engine-launch.ts
190
+ function agentmemoryHome(home) {
191
+ return join(home, ".agentmemory");
192
+ }
193
+ function runtimeConfigPath(dataDir) {
194
+ return join(dataDir, "iii-config.runtime.yaml");
195
+ }
196
+ function dockerProjectName(restPort) {
197
+ return `agentmemory-${restPort}`;
198
+ }
199
+ function dockerComposeArgs(composeFile, projectName, command) {
200
+ return [
201
+ "compose",
202
+ ...projectName ? ["-p", projectName] : [],
203
+ "-f",
204
+ composeFile,
205
+ ...command
206
+ ];
207
+ }
208
+ function isBundledConfig(configPath, packageDir) {
209
+ const resolved = resolve(configPath);
210
+ return resolved === resolve(join(packageDir, "iii-config.yaml")) || resolved === resolve(join(packageDir, "..", "iii-config.yaml"));
211
+ }
212
+ function resolveEngineCwd(configPath, invocationCwd, home, bundledConfig = false) {
213
+ if (bundledConfig) return agentmemoryHome(home);
214
+ return dirname(isAbsolute(configPath) ? configPath : resolve(invocationCwd, configPath));
215
+ }
216
+ function indentation(line) {
217
+ return line.length - line.trimStart().length;
218
+ }
219
+ function yamlScalar(value) {
220
+ const trimmed = value.trim();
221
+ const first = trimmed[0];
222
+ const last = trimmed.at(-1);
223
+ if (first === "\"" && last === "\"" || first === "'" && last === "'") return trimmed.slice(1, -1);
224
+ return trimmed;
225
+ }
226
+ function isAgentmemoryExecCommand(line, nodeBin, workerEntry) {
227
+ const match = line.match(/^\s*-\s+(.+?)\s*$/);
228
+ if (!match) return false;
229
+ const command = yamlScalar(match[1]).replaceAll("\\", "/");
230
+ return command === `${nodeBin} ${workerEntry}`.replaceAll("\\", "/") || /^(?:node|node\.exe)\s+\.\/dist\/index\.mjs$/.test(command) || /^(?:node|node\.exe)\s+dist\/index\.mjs$/.test(command);
231
+ }
232
+ function removeAgentmemoryExecCommand(raw, nodeBin, workerEntry) {
233
+ const lines = raw.split("\n");
234
+ const output = [];
235
+ let index = 0;
236
+ while (index < lines.length) {
237
+ const line = lines[index];
238
+ if (line.trim() !== "- name: iii-exec") {
239
+ output.push(line);
240
+ index++;
241
+ continue;
242
+ }
243
+ const blockIndent = indentation(line);
244
+ let blockEnd = index + 1;
245
+ while (blockEnd < lines.length) {
246
+ const candidate = lines[blockEnd];
247
+ if (candidate.trim() !== "") {
248
+ const candidateIndent = indentation(candidate);
249
+ if (candidateIndent < blockIndent || candidateIndent === blockIndent && candidate.trim().startsWith("- name: ")) break;
250
+ }
251
+ blockEnd++;
252
+ }
253
+ const block = lines.slice(index, blockEnd);
254
+ const execIndex = block.findIndex((candidate) => candidate.trim() === "exec:");
255
+ if (execIndex === -1) {
256
+ output.push(...block);
257
+ index = blockEnd;
258
+ continue;
259
+ }
260
+ const execIndent = indentation(block[execIndex]);
261
+ let execEnd = execIndex + 1;
262
+ while (execEnd < block.length) {
263
+ const candidate = block[execEnd];
264
+ if (candidate.trim() !== "" && indentation(candidate) <= execIndent) break;
265
+ execEnd++;
266
+ }
267
+ const beforeExec = block.slice(0, execIndex + 1);
268
+ const execLines = block.slice(execIndex + 1, execEnd);
269
+ const afterExec = block.slice(execEnd);
270
+ const remainingExecLines = execLines.filter((candidate) => !isAgentmemoryExecCommand(candidate, nodeBin, workerEntry));
271
+ const removed = remainingExecLines.length !== execLines.length;
272
+ const hasExecCommand = remainingExecLines.some((candidate) => /^\s*-\s+/.test(candidate) && indentation(candidate) > execIndent);
273
+ if (!removed) output.push(...block);
274
+ else if (hasExecCommand) output.push(...beforeExec, ...remainingExecLines, ...afterExec);
275
+ index = blockEnd;
276
+ }
277
+ return output.join("\n");
278
+ }
279
+ function rewriteBundledConfig(raw, home, nodeBin, workerEntry, options) {
280
+ return removeAgentmemoryExecCommand(renderEngineConfig(raw, {
281
+ dataDir: options?.dataDir ?? join(agentmemoryHome(home), "data"),
282
+ ...options?.ports ? { ports: options.ports } : {},
283
+ ...options?.stateBackend ? { stateBackend: options.stateBackend } : {},
284
+ ...options?.saveIntervalMs !== void 0 ? { saveIntervalMs: options.saveIntervalMs } : {}
285
+ }), nodeBin, workerEntry);
286
+ }
287
+ function legacyDataMigrations(invocationCwd, home, resolvedDataDir = join(agentmemoryHome(home), "data")) {
288
+ return [{
289
+ from: join(invocationCwd, "data", "state_store.db"),
290
+ to: join(resolvedDataDir, "state_store.db")
291
+ }, {
292
+ from: join(invocationCwd, "data", "stream_store"),
293
+ to: join(resolvedDataDir, "stream_store")
294
+ }];
295
+ }
296
+ function engineChildEnv(base, platform = process.platform) {
297
+ const env = {
298
+ ...base,
299
+ III_TELEMETRY_ENABLED: base["III_TELEMETRY_ENABLED"] ?? "false"
300
+ };
301
+ if (platform === "linux" && !base.MALLOC_ARENA_MAX) env.MALLOC_ARENA_MAX = "2";
302
+ return env;
303
+ }
304
+ function resolveLaunchRenderFailure(stateBackendKind, err) {
305
+ if (stateBackendKind !== "redis") return { fatal: false };
306
+ return {
307
+ fatal: true,
308
+ message: `Failed to render the Redis state backend into the engine config: ${err instanceof Error ? err.message : String(err)} Refusing to start the engine, since it would silently fall back to the file (or in-memory) store instead of Redis. Fix the config or unset AGENTMEMORY_STATE_BACKEND to use the default file store.`
309
+ };
310
+ }
311
+ const CREDENTIAL_URL_PATTERN = /:\/\/[^@\s/]*@/g;
312
+ function redactCredentialUrls(text) {
313
+ return text.replace(CREDENTIAL_URL_PATTERN, "://***@");
314
+ }
315
+ //#endregion
316
+ //#region src/logger.ts
317
+ function fmt(level, msg, fields) {
318
+ if (!fields || Object.keys(fields).length === 0) return `[agentmemory] ${level} ${msg}`;
319
+ try {
320
+ return `[agentmemory] ${level} ${msg} ${JSON.stringify(fields)}`;
321
+ } catch {
322
+ return `[agentmemory] ${level} ${msg}`;
323
+ }
324
+ }
325
+ function emit(level, msg, fields) {
326
+ try {
327
+ process.stderr.write(fmt(level, msg, fields) + "\n");
328
+ } catch {}
329
+ }
330
+ const logger = {
331
+ info(msg, fields) {
332
+ emit("info", msg, fields);
333
+ },
334
+ warn(msg, fields) {
335
+ emit("warn", msg, fields);
336
+ },
337
+ error(msg, fields) {
338
+ emit("error", msg, fields);
339
+ }
340
+ };
341
+ let bootVerbose = process.env["AGENTMEMORY_VERBOSE"] === "1" || process.env["AGENTMEMORY_VERBOSE"] === "true";
342
+ const bootBuffer = [];
343
+ function setBootVerbose(enabled) {
344
+ bootVerbose = enabled;
345
+ }
346
+ function bootLog(msg) {
347
+ if (bootVerbose) {
348
+ try {
349
+ process.stderr.write(`[agentmemory] ${msg}\n`);
350
+ } catch {}
351
+ return;
352
+ }
353
+ if (bootBuffer.length < 500) bootBuffer.push(msg);
354
+ }
355
+ function bootWarn(msg) {
356
+ try {
357
+ process.stderr.write(`[agentmemory] warn ${msg}\n`);
358
+ } catch {}
359
+ }
360
+ //#endregion
361
+ //#region src/config.ts
362
+ function safeParseInt(value, fallback) {
363
+ if (!value) return fallback;
364
+ const parsed = parseInt(value, 10);
365
+ return Number.isNaN(parsed) ? fallback : parsed;
366
+ }
367
+ const DATA_DIR = join(homedir(), ".agentmemory");
368
+ const ENV_FILE = join(DATA_DIR, ".env");
369
+ let warnPremiumModelShown = false;
370
+ let providerNoticeShown = false;
371
+ function writeProviderNoticeOnce(text) {
372
+ if (providerNoticeShown) return;
373
+ providerNoticeShown = true;
374
+ process.stderr.write(text);
375
+ }
376
+ let envFileCache;
377
+ function loadEnvFile() {
378
+ if (envFileCache) return envFileCache;
379
+ if (!existsSync(ENV_FILE)) {
380
+ envFileCache = {};
381
+ return envFileCache;
382
+ }
383
+ const content = readFileSync(ENV_FILE, "utf-8");
384
+ const vars = {};
385
+ for (const line of content.split("\n")) {
386
+ const trimmed = line.trim();
387
+ if (!trimmed || trimmed.startsWith("#")) continue;
388
+ const eqIdx = trimmed.indexOf("=");
389
+ if (eqIdx === -1) continue;
390
+ const key = trimmed.slice(0, eqIdx).trim();
391
+ let val = trimmed.slice(eqIdx + 1).trim();
392
+ const quoteChar = val[0] === "\"" || val[0] === "'" ? val[0] : "";
393
+ if (quoteChar) {
394
+ const closeIdx = val.indexOf(quoteChar, 1);
395
+ if (closeIdx !== -1) val = val.slice(1, closeIdx);
396
+ } else {
397
+ const hashIdx = val.indexOf(" #");
398
+ if (hashIdx !== -1) val = val.slice(0, hashIdx).trim();
399
+ }
400
+ vars[key] = val;
401
+ }
402
+ envFileCache = vars;
403
+ return envFileCache;
404
+ }
405
+ function hasRealValue(v) {
406
+ return typeof v === "string" && v.trim().length > 0;
407
+ }
408
+ function hydrateProcessEnvFromFile() {
409
+ for (const [k, v] of Object.entries(loadEnvFile())) if (process.env[k] === void 0) process.env[k] = v;
410
+ }
411
+ function detectProvider(env) {
412
+ const maxTokens = parseInt(env["MAX_TOKENS"] || "4096", 10);
413
+ if (hasRealValue(env["OPENAI_API_KEY"]) && env["OPENAI_API_KEY_FOR_LLM"] !== "false") return {
414
+ provider: "openai",
415
+ model: env["OPENAI_MODEL"] || "gpt-5.6-luna",
416
+ maxTokens,
417
+ baseURL: env["OPENAI_BASE_URL"]
418
+ };
419
+ if (hasRealValue(env["MINIMAX_API_KEY"])) return {
420
+ provider: "minimax",
421
+ model: env["MINIMAX_MODEL"] || "MiniMax-M3",
422
+ maxTokens
423
+ };
424
+ if (hasRealValue(env["ANTHROPIC_API_KEY"])) return {
425
+ provider: "anthropic",
426
+ model: env["ANTHROPIC_MODEL"] || "claude-sonnet-5",
427
+ maxTokens,
428
+ baseURL: env["ANTHROPIC_BASE_URL"]
429
+ };
430
+ if (hasRealValue(env["GEMINI_API_KEY"]) || hasRealValue(env["GOOGLE_API_KEY"])) {
431
+ if (!hasRealValue(env["GEMINI_API_KEY"]) && hasRealValue(env["GOOGLE_API_KEY"])) process.stderr.write("[agentmemory] GOOGLE_API_KEY detected — treating as GEMINI_API_KEY. Set GEMINI_API_KEY in ~/.agentmemory/.env to silence this warning.\n");
432
+ return {
433
+ provider: "gemini",
434
+ model: env["GEMINI_MODEL"] || "gemini-3.7-flash",
435
+ maxTokens
436
+ };
437
+ }
438
+ if (hasRealValue(env["OPENROUTER_API_KEY"])) {
439
+ const model = env["OPENROUTER_MODEL"] || "anthropic/claude-sonnet-5";
440
+ if (!warnPremiumModelShown && /sonnet|opus|gpt-5\.\d+-sol|gpt-4o(?!.*mini)|gpt-4-turbo/i.test(model) && env["AGENTMEMORY_SUPPRESS_COST_WARNING"] !== "1" && env["AGENTMEMORY_SUPPRESS_COST_WARNING"] !== "true") {
441
+ warnPremiumModelShown = true;
442
+ process.stderr.write(`[agentmemory] OPENROUTER_MODEL=${model} is in the premium tier. Background compression on this model can cost $5+/day under active use. Cheaper alternatives with comparable quality for memory compression: deepseek/deepseek-v4-flash-0731, deepseek/deepseek-v4-pro, qwen/qwen3-coder. See README "Cost-aware model selection" for the full table. Set AGENTMEMORY_SUPPRESS_COST_WARNING=1 to silence.\n`);
443
+ }
444
+ return {
445
+ provider: "openrouter",
446
+ model,
447
+ maxTokens
448
+ };
449
+ }
450
+ if (!(env["AGENTMEMORY_ALLOW_AGENT_SDK"] === "true")) {
451
+ writeProviderNoticeOnce(pc.dim("[agentmemory] No LLM provider key set — running zero-LLM: no LLM compression or summaries; search uses BM25 plus any configured embedding provider. Set EMBEDDING_PROVIDER=local for on-device semantic embeddings if none is configured. Set ANTHROPIC_API_KEY (or GEMINI/OPENAI/OPENROUTER/MINIMAX) in ~/.agentmemory/.env for LLM compression and summaries. Agent-SDK fallback stays off by default to avoid a Stop-hook recursion loop; opt in with AGENTMEMORY_AUTO_COMPRESS=true + AGENTMEMORY_ALLOW_AGENT_SDK=true.\n"));
452
+ return {
453
+ provider: "noop",
454
+ model: "noop",
455
+ maxTokens
456
+ };
457
+ }
458
+ writeProviderNoticeOnce("[agentmemory] WARNING: agent-sdk fallback enabled via AGENTMEMORY_ALLOW_AGENT_SDK=true. This spawns @anthropic-ai/claude-agent-sdk child sessions that can trigger the Stop-hook recursion loop. A SDK-child env marker is set to block re-entry, but prefer setting a real API key in ~/.agentmemory/.env instead.\n");
459
+ return {
460
+ provider: "agent-sdk",
461
+ model: "claude-sonnet-5",
462
+ maxTokens
463
+ };
464
+ }
465
+ function loadConfig() {
466
+ const env = getMergedEnv();
467
+ const provider = detectProvider(env);
468
+ const restPort = parseInt(env["III_REST_PORT"] || "3111", 10) || 3111;
469
+ const streamsPort = parseInt(env["III_STREAM_PORT"] || env["III_STREAMS_PORT"] || "", 10) || restPort + 1;
470
+ const viewerPort = parseInt(env["III_VIEWER_PORT"] || "", 10) || restPort + 2;
471
+ return {
472
+ engineUrl: env["III_ENGINE_URL"] || `ws://localhost:${parseInt(env["III_ENGINE_PORT"] || "", 10) || restPort + 46023}`,
473
+ restPort,
474
+ streamsPort,
475
+ viewerPort,
476
+ provider,
477
+ tokenBudget: safeParseInt(env["TOKEN_BUDGET"], 2e3),
478
+ maxObservationsPerSession: safeParseInt(env["MAX_OBS_PER_SESSION"], 500),
479
+ compressionModel: provider.model,
480
+ dataDir: DATA_DIR
481
+ };
482
+ }
483
+ function getMergedEnv(overrides) {
484
+ return {
485
+ ...loadEnvFile(),
486
+ ...process.env,
487
+ ...overrides
488
+ };
489
+ }
490
+ function getEnvVar(key) {
491
+ return getMergedEnv()[key];
492
+ }
493
+ function isSessionSweepEnabled() {
494
+ return getMergedEnv()["AGENTMEMORY_SESSION_SWEEP_ENABLED"] !== "false";
495
+ }
496
+ function getSessionSweepStaleHours() {
497
+ const raw = getMergedEnv()["AGENTMEMORY_SESSION_SWEEP_STALE_HOURS"];
498
+ if (!raw || !/^\d+$/.test(raw.trim())) return 24;
499
+ const parsed = parseInt(raw.trim(), 10);
500
+ return parsed > 0 ? parsed : 24;
501
+ }
502
+ function isGraphCompactOnBootEnabled() {
503
+ return getMergedEnv()["AGENTMEMORY_GRAPH_COMPACT_ON_BOOT"] !== "false";
504
+ }
505
+ function isDropStaleIndexEnabled() {
506
+ return getMergedEnv()["AGENTMEMORY_DROP_STALE_INDEX"] === "true";
507
+ }
508
+ const VALID_STATE_BACKENDS = new Set(["file", "redis"]);
509
+ function getStateBackend() {
510
+ const raw = (getMergedEnv()["AGENTMEMORY_STATE_BACKEND"] || "").trim().toLowerCase();
511
+ if (!raw) return "file";
512
+ if (!VALID_STATE_BACKENDS.has(raw)) throw new Error(`AGENTMEMORY_STATE_BACKEND="${raw}" is not a recognized state backend. Use "file" (the default) or "redis", or unset it to keep the default file store.`);
513
+ return raw;
514
+ }
515
+ function getRedisUrl() {
516
+ const value = getMergedEnv()["AGENTMEMORY_REDIS_URL"];
517
+ return hasRealValue(value) ? value.trim() : void 0;
518
+ }
519
+ function getAuditRetentionMonths() {
520
+ return safeParseInt(getMergedEnv()["AGENTMEMORY_AUDIT_RETENTION_MONTHS"], 0);
521
+ }
522
+ function getAuditMigrateMaxBytes() {
523
+ return safeParseInt(getMergedEnv()["AGENTMEMORY_AUDIT_MIGRATE_MAX_BYTES"], 32 * 1024 * 1024);
524
+ }
525
+ function detectLlmProviderKind(env = getMergedEnv()) {
526
+ if (hasRealValue(env["ANTHROPIC_API_KEY"]) || hasRealValue(env["GEMINI_API_KEY"]) || hasRealValue(env["GOOGLE_API_KEY"]) || hasRealValue(env["OPENROUTER_API_KEY"]) || hasRealValue(env["MINIMAX_API_KEY"]) || hasRealValue(env["OPENAI_API_KEY"]) && env["OPENAI_API_KEY_FOR_LLM"] !== "false" || env["AGENTMEMORY_ALLOW_AGENT_SDK"] === "true") return "llm";
527
+ return "noop";
528
+ }
529
+ function loadEmbeddingConfig() {
530
+ const env = getMergedEnv();
531
+ let bm25Weight = parseFloat(env["BM25_WEIGHT"] || "0.4");
532
+ let vectorWeight = parseFloat(env["VECTOR_WEIGHT"] || "0.6");
533
+ bm25Weight = isNaN(bm25Weight) || bm25Weight < 0 ? .4 : Math.min(bm25Weight, 1);
534
+ vectorWeight = isNaN(vectorWeight) || vectorWeight < 0 ? .6 : Math.min(vectorWeight, 1);
535
+ return {
536
+ provider: env["EMBEDDING_PROVIDER"] || void 0,
537
+ bm25Weight,
538
+ vectorWeight
539
+ };
540
+ }
541
+ function detectEmbeddingProvider(env) {
542
+ const source = env ?? getMergedEnv();
543
+ const forced = source["EMBEDDING_PROVIDER"];
544
+ if (forced) return forced;
545
+ if (source["GEMINI_API_KEY"]) return "gemini";
546
+ if (source["OPENAI_API_KEY"] || source["OPENAI_EMBEDDING_API_KEY"]) return "openai";
547
+ if (source["VOYAGE_API_KEY"]) return "voyage";
548
+ if (source["COHERE_API_KEY"]) return "cohere";
549
+ if (source["OPENROUTER_API_KEY"]) return "openrouter";
550
+ return null;
551
+ }
552
+ function loadClaudeBridgeConfig() {
553
+ const env = getMergedEnv();
554
+ const enabled = env["CLAUDE_MEMORY_BRIDGE"] === "true";
555
+ const projectPath = env["CLAUDE_PROJECT_PATH"] || "";
556
+ const lineBudget = safeParseInt(env["CLAUDE_MEMORY_LINE_BUDGET"], 200);
557
+ let memoryFilePath = "";
558
+ if (enabled && projectPath) {
559
+ const safePath = projectPath.replace(/[/\\]/g, "-");
560
+ memoryFilePath = join(homedir(), ".claude", "projects", safePath, "memory", "MEMORY.md");
561
+ }
562
+ return {
563
+ enabled,
564
+ projectPath,
565
+ memoryFilePath,
566
+ lineBudget
567
+ };
568
+ }
569
+ function loadTeamConfig() {
570
+ const env = getMergedEnv();
571
+ const teamId = env["TEAM_ID"];
572
+ const userId = env["USER_ID"];
573
+ if (!teamId || !userId) return null;
574
+ return {
575
+ teamId,
576
+ userId,
577
+ mode: env["TEAM_MODE"] === "shared" ? "shared" : "private"
578
+ };
579
+ }
580
+ function loadAgentScope() {
581
+ const env = getMergedEnv();
582
+ const raw = env["AGENT_ID"];
583
+ if (!raw) return null;
584
+ const agentId = raw.trim().slice(0, 128);
585
+ if (!agentId) return null;
586
+ return {
587
+ agentId,
588
+ mode: env["AGENTMEMORY_AGENT_SCOPE"] === "isolated" ? "isolated" : "shared"
589
+ };
590
+ }
591
+ function getAgentId() {
592
+ return loadAgentScope()?.agentId;
593
+ }
594
+ function isAgentScopeIsolated() {
595
+ return loadAgentScope()?.mode === "isolated";
596
+ }
597
+ const SNAPSHOT_INTERVAL_DEFAULT_SECONDS = 3600;
598
+ const MIN_SNAPSHOT_INTERVAL_SECONDS = 1;
599
+ function loadSnapshotConfig() {
600
+ const env = getMergedEnv();
601
+ const rawInterval = safeParseInt(env["SNAPSHOT_INTERVAL"], SNAPSHOT_INTERVAL_DEFAULT_SECONDS);
602
+ const interval = rawInterval >= MIN_SNAPSHOT_INTERVAL_SECONDS ? rawInterval : SNAPSHOT_INTERVAL_DEFAULT_SECONDS;
603
+ return {
604
+ enabled: env["SNAPSHOT_ENABLED"] === "true",
605
+ interval,
606
+ dir: env["SNAPSHOT_DIR"] || join(homedir(), ".agentmemory", "snapshots")
607
+ };
608
+ }
609
+ function isGraphExtractionEnabled() {
610
+ return getMergedEnv()["GRAPH_EXTRACTION_ENABLED"] === "true";
611
+ }
612
+ const FOLLOWUP_WINDOW_DEFAULT_SECONDS = 30;
613
+ function getFollowupWindowSeconds() {
614
+ return safeParseInt(getMergedEnv()["AGENTMEMORY_FOLLOWUP_WINDOW_SECONDS"], FOLLOWUP_WINDOW_DEFAULT_SECONDS);
615
+ }
616
+ const VIEWER_STREAM_MAX_DEFAULT = 500;
617
+ const VIEWER_STREAM_MAX_FLOOR = 200;
618
+ function parseExactInt(value, fallback) {
619
+ if (!value) return fallback;
620
+ const trimmed = value.trim();
621
+ if (!/^-?\d+$/.test(trimmed)) return fallback;
622
+ const parsed = Number(trimmed);
623
+ return Number.isSafeInteger(parsed) ? parsed : fallback;
624
+ }
625
+ function getViewerStreamMax() {
626
+ const parsed = parseExactInt(getMergedEnv()["AGENTMEMORY_VIEWER_STREAM_MAX"], VIEWER_STREAM_MAX_DEFAULT);
627
+ if (parsed < 0) return VIEWER_STREAM_MAX_DEFAULT;
628
+ return Math.max(parsed, VIEWER_STREAM_MAX_FLOOR);
629
+ }
630
+ function isConsolidationEnabled() {
631
+ const env = getMergedEnv();
632
+ const explicit = env["CONSOLIDATION_ENABLED"];
633
+ if (explicit === "false" || explicit === "0") return false;
634
+ if (explicit === "true" || explicit === "1") return true;
635
+ if ((env["AGENTMEMORY_PROVIDER"] || "").toLowerCase() === "noop") return false;
636
+ return detectLlmProviderKind(env) === "llm";
637
+ }
638
+ function isAutoCompressEnabled() {
639
+ return getMergedEnv()["AGENTMEMORY_AUTO_COMPRESS"] === "true";
640
+ }
641
+ function isContextInjectionEnabled() {
642
+ return getMergedEnv()["AGENTMEMORY_INJECT_CONTEXT"] === "true";
643
+ }
644
+ const CONSOLIDATION_INTERVAL_DEFAULT_MS = 72e5;
645
+ function getConsolidationIntervalMs() {
646
+ const raw = parseInt(process.env.CONSOLIDATION_INTERVAL_MS || String(72e5), 10);
647
+ return Number.isFinite(raw) && raw > 0 ? raw : CONSOLIDATION_INTERVAL_DEFAULT_MS;
648
+ }
649
+ function getConsolidationDecayDays() {
650
+ return safeParseInt(getMergedEnv()["CONSOLIDATION_DECAY_DAYS"], 30);
651
+ }
652
+ const CONSOLIDATION_COOLDOWN_DEFAULT_MS = 3e5;
653
+ function getConsolidationCooldownMs() {
654
+ const raw = safeParseInt(getMergedEnv()["AGENTMEMORY_CONSOLIDATION_COOLDOWN_MS"], CONSOLIDATION_COOLDOWN_DEFAULT_MS);
655
+ return raw >= 0 ? raw : CONSOLIDATION_COOLDOWN_DEFAULT_MS;
656
+ }
657
+ const INDEX_SAVE_INTERVAL_DEFAULT_MS = 6e5;
658
+ function getIndexSaveIntervalMs() {
659
+ const raw = safeParseInt(getMergedEnv()["AGENTMEMORY_INDEX_SAVE_INTERVAL_MS"], INDEX_SAVE_INTERVAL_DEFAULT_MS);
660
+ return raw > 0 ? raw : INDEX_SAVE_INTERVAL_DEFAULT_MS;
661
+ }
662
+ function getStateSaveIntervalMs() {
663
+ const raw = safeParseInt(getMergedEnv()["AGENTMEMORY_STATE_SAVE_INTERVAL_MS"], 0);
664
+ return raw > 0 ? raw : void 0;
665
+ }
666
+ function getVectorBucketSize() {
667
+ const raw = safeParseInt(getMergedEnv()["AGENTMEMORY_VECTOR_BUCKET_SIZE"], 500);
668
+ return raw > 0 ? raw : 500;
669
+ }
670
+ function getVectorBackfillMax() {
671
+ const raw = safeParseInt(getMergedEnv()["AGENTMEMORY_VECTOR_BACKFILL_MAX"], 500);
672
+ return raw > 0 ? raw : 500;
673
+ }
674
+ function isVectorBackfillAllEnabled() {
675
+ return getMergedEnv()["AGENTMEMORY_VECTOR_BACKFILL"] === "all";
676
+ }
677
+ function getStandalonePersistPath() {
678
+ return getMergedEnv()["STANDALONE_PERSIST_PATH"] || join(homedir(), ".agentmemory", "standalone.json");
679
+ }
680
+ const VALID_PROVIDERS = new Set([
681
+ "anthropic",
682
+ "gemini",
683
+ "openrouter",
684
+ "agent-sdk",
685
+ "minimax",
686
+ "openai"
687
+ ]);
688
+ function loadFallbackConfig() {
689
+ const env = getMergedEnv();
690
+ const raw = env["FALLBACK_PROVIDERS"] || "";
691
+ const allowAgentSdk = env["AGENTMEMORY_ALLOW_AGENT_SDK"] === "true";
692
+ return { providers: raw.split(",").map((p) => p.trim()).filter((p) => Boolean(p) && VALID_PROVIDERS.has(p)).filter((p) => {
693
+ if (p === "agent-sdk" && !allowAgentSdk) {
694
+ process.stderr.write("[agentmemory] Ignoring FALLBACK_PROVIDERS entry 'agent-sdk' (AGENTMEMORY_ALLOW_AGENT_SDK is not 'true'). The agent-sdk fallback can spawn Claude Agent SDK child sessions that trigger the Stop-hook recursion loop. Opt in explicitly with AGENTMEMORY_ALLOW_AGENT_SDK=true if this is intentional.\n");
695
+ return false;
696
+ }
697
+ return true;
698
+ }) };
699
+ }
700
+ //#endregion
701
+ //#region src/version.ts
702
+ const VERSION = "0.9.30";
703
+ const III_PINNED_VERSION = "0.22.1";
704
+ //#endregion
705
+ //#region src/mcp/tools-registry.ts
706
+ const CORE_TOOLS = [
707
+ {
708
+ name: "memory_recall",
709
+ description: "Search past session observations for relevant context. Use when you need to recall what happened in previous sessions, find past decisions, or look up how a file was modified before.",
710
+ inputSchema: {
711
+ type: "object",
712
+ properties: {
713
+ query: {
714
+ type: "string",
715
+ description: "Search query (keywords, file names, concepts)"
716
+ },
717
+ limit: {
718
+ type: "number",
719
+ description: "Max results to return (default 10)"
720
+ },
721
+ format: {
722
+ type: "string",
723
+ description: "Result format: full, compact, or narrative (default full)"
724
+ },
725
+ token_budget: {
726
+ type: "number",
727
+ description: "Optional token budget to trim returned results"
728
+ }
729
+ },
730
+ required: ["query"]
731
+ }
732
+ },
733
+ {
734
+ name: "memory_compress_file",
735
+ description: "Compress a markdown file to reduce token usage while preserving headings, URLs, and code blocks. Creates a .original.md backup before writing.",
736
+ inputSchema: {
737
+ type: "object",
738
+ properties: { filePath: {
739
+ type: "string",
740
+ description: "Path to the markdown file to compress"
741
+ } },
742
+ required: ["filePath"]
743
+ }
744
+ },
745
+ {
746
+ name: "memory_save",
747
+ description: "Explicitly save an important insight, decision, or pattern to long-term memory.",
748
+ inputSchema: {
749
+ type: "object",
750
+ properties: {
751
+ content: {
752
+ type: "string",
753
+ description: "The insight or decision to remember"
754
+ },
755
+ type: {
756
+ type: "string",
757
+ description: "Memory type: pattern, preference, architecture, bug, workflow, or fact"
758
+ },
759
+ concepts: {
760
+ type: "string",
761
+ description: "Comma-separated key concepts"
762
+ },
763
+ files: {
764
+ type: "string",
765
+ description: "Comma-separated relevant file paths"
766
+ },
767
+ project: {
768
+ type: "string",
769
+ description: "Stable canonical project identifier this memory belongs to (e.g. a slug, UUID, or registry key). Must match the value used when the session was started. Do not use filesystem paths or ad-hoc display names — those change across machines and will silently break project scoping."
770
+ },
771
+ agentId: {
772
+ type: "string",
773
+ description: "Agent identity to scope this memory to. When set, agent-scoped recall and search only surface it for the same agentId. Omit for shared memory."
774
+ }
775
+ },
776
+ required: ["content"]
777
+ }
778
+ },
779
+ {
780
+ name: "memory_file_history",
781
+ description: "Get past observations about specific files.",
782
+ inputSchema: {
783
+ type: "object",
784
+ properties: {
785
+ files: {
786
+ type: "string",
787
+ description: "Comma-separated file paths"
788
+ },
789
+ sessionId: {
790
+ type: "string",
791
+ description: "Current session ID to exclude"
792
+ }
793
+ },
794
+ required: ["files"]
795
+ }
796
+ },
797
+ {
798
+ name: "memory_patterns",
799
+ description: "Detect recurring patterns across sessions.",
800
+ inputSchema: {
801
+ type: "object",
802
+ properties: {
803
+ project: {
804
+ type: "string",
805
+ description: "Project path to analyze"
806
+ },
807
+ limit: {
808
+ type: "integer",
809
+ description: "Most recent sessions to scan (default 50, max 500)"
810
+ }
811
+ }
812
+ }
813
+ },
814
+ {
815
+ name: "memory_sessions",
816
+ description: "List recent sessions with their status and observation counts.",
817
+ inputSchema: {
818
+ type: "object",
819
+ properties: {}
820
+ }
821
+ },
822
+ {
823
+ name: "memory_smart_search",
824
+ description: "Hybrid semantic+keyword search with progressive disclosure.",
825
+ inputSchema: {
826
+ type: "object",
827
+ properties: {
828
+ query: {
829
+ type: "string",
830
+ description: "Search query"
831
+ },
832
+ expandIds: {
833
+ type: "string",
834
+ description: "Comma-separated observation IDs to expand"
835
+ },
836
+ limit: {
837
+ type: "number",
838
+ description: "Max results (default 10)"
839
+ }
840
+ },
841
+ required: ["query"]
842
+ }
843
+ },
844
+ {
845
+ name: "memory_vision_search",
846
+ description: "Cross-modal image search via CLIP embeddings. Pass queryText to find screenshots matching a description, or queryImageBase64/queryImageRef to find similar images. Requires AGENTMEMORY_IMAGE_EMBEDDINGS=true.",
847
+ inputSchema: {
848
+ type: "object",
849
+ properties: {
850
+ queryText: {
851
+ type: "string",
852
+ description: "Text query (e.g. 'login form with error banner')"
853
+ },
854
+ queryImageRef: {
855
+ type: "string",
856
+ description: "Absolute path to a stored image to match against"
857
+ },
858
+ queryImageBase64: {
859
+ type: "string",
860
+ description: "Raw base64 image bytes or data URL"
861
+ },
862
+ topK: {
863
+ type: "number",
864
+ description: "Max results (default 10, max 50)"
865
+ },
866
+ sessionId: {
867
+ type: "string",
868
+ description: "Filter to a single session"
869
+ }
870
+ }
871
+ }
872
+ },
873
+ {
874
+ name: "memory_timeline",
875
+ description: "Chronological observations around an anchor point.",
876
+ inputSchema: {
877
+ type: "object",
878
+ properties: {
879
+ anchor: {
880
+ type: "string",
881
+ description: "Anchor point: ISO date or keyword"
882
+ },
883
+ project: {
884
+ type: "string",
885
+ description: "Filter by project path"
886
+ },
887
+ before: {
888
+ type: "number",
889
+ description: "Observations before anchor (default 5)"
890
+ },
891
+ after: {
892
+ type: "number",
893
+ description: "Observations after anchor (default 5)"
894
+ }
895
+ },
896
+ required: ["anchor"]
897
+ }
898
+ },
899
+ {
900
+ name: "memory_profile",
901
+ description: "User/project profile with top concepts and file patterns.",
902
+ inputSchema: {
903
+ type: "object",
904
+ properties: {
905
+ project: {
906
+ type: "string",
907
+ description: "Project path"
908
+ },
909
+ refresh: {
910
+ type: "string",
911
+ description: "Set to 'true' to force rebuild"
912
+ }
913
+ },
914
+ required: ["project"]
915
+ }
916
+ },
917
+ {
918
+ name: "memory_export",
919
+ description: "Export all memory data as JSON.",
920
+ inputSchema: {
921
+ type: "object",
922
+ properties: {}
923
+ }
924
+ },
925
+ {
926
+ name: "memory_relations",
927
+ description: "Query the memory relationship graph.",
928
+ inputSchema: {
929
+ type: "object",
930
+ properties: {
931
+ memoryId: {
932
+ type: "string",
933
+ description: "Memory ID to find relations for"
934
+ },
935
+ maxHops: {
936
+ type: "number",
937
+ description: "Max traversal depth (default 2)"
938
+ },
939
+ minConfidence: {
940
+ type: "number",
941
+ description: "Min confidence (0-1, default 0)"
942
+ }
943
+ },
944
+ required: ["memoryId"]
945
+ }
946
+ },
947
+ {
948
+ name: "memory_commit_lookup",
949
+ description: "Look up the agent session(s) that produced a specific git commit, given its SHA. Returns the commit metadata and linked sessions.",
950
+ inputSchema: {
951
+ type: "object",
952
+ properties: { sha: {
953
+ type: "string",
954
+ description: "Full git commit SHA"
955
+ } },
956
+ required: ["sha"]
957
+ }
958
+ },
959
+ {
960
+ name: "memory_commits",
961
+ description: "List recent commits linked to agent sessions, optionally filtered by branch or repo.",
962
+ inputSchema: {
963
+ type: "object",
964
+ properties: {
965
+ branch: {
966
+ type: "string",
967
+ description: "Filter by branch name"
968
+ },
969
+ repo: {
970
+ type: "string",
971
+ description: "Filter by remote URL"
972
+ },
973
+ limit: {
974
+ type: "number",
975
+ description: "Max results (default 100, max 500)"
976
+ }
977
+ }
978
+ }
979
+ }
980
+ ];
981
+ const V040_TOOLS = [
982
+ {
983
+ name: "memory_claude_bridge_sync",
984
+ description: "Sync memory state to/from Claude Code's native MEMORY.md file.",
985
+ inputSchema: {
986
+ type: "object",
987
+ properties: { direction: {
988
+ type: "string",
989
+ description: "'read' to import from MEMORY.md, 'write' to export to MEMORY.md"
990
+ } },
991
+ required: ["direction"]
992
+ }
993
+ },
994
+ {
995
+ name: "memory_graph_query",
996
+ description: "Query the knowledge graph for entities and relationships.",
997
+ inputSchema: {
998
+ type: "object",
999
+ properties: {
1000
+ startNodeId: {
1001
+ type: "string",
1002
+ description: "Starting node ID for traversal"
1003
+ },
1004
+ nodeType: {
1005
+ type: "string",
1006
+ description: "Filter by node type"
1007
+ },
1008
+ maxDepth: {
1009
+ type: "number",
1010
+ description: "Max BFS depth (default 3, max 5)"
1011
+ },
1012
+ query: {
1013
+ type: "string",
1014
+ description: "Search nodes by name"
1015
+ }
1016
+ }
1017
+ }
1018
+ },
1019
+ {
1020
+ name: "memory_consolidate",
1021
+ description: "Run the 4-tier memory consolidation pipeline (working -> episodic -> semantic -> procedural).",
1022
+ inputSchema: {
1023
+ type: "object",
1024
+ properties: { tier: {
1025
+ type: "string",
1026
+ description: "Target tier: episodic, semantic, or procedural"
1027
+ } }
1028
+ }
1029
+ },
1030
+ {
1031
+ name: "memory_team_share",
1032
+ description: "Share a memory or observation with team members.",
1033
+ inputSchema: {
1034
+ type: "object",
1035
+ properties: {
1036
+ itemId: {
1037
+ type: "string",
1038
+ description: "ID of memory or observation to share"
1039
+ },
1040
+ itemType: {
1041
+ type: "string",
1042
+ description: "Type: observation, memory, or pattern"
1043
+ }
1044
+ },
1045
+ required: ["itemId", "itemType"]
1046
+ }
1047
+ },
1048
+ {
1049
+ name: "memory_team_feed",
1050
+ description: "Get recent shared items from all team members.",
1051
+ inputSchema: {
1052
+ type: "object",
1053
+ properties: { limit: {
1054
+ type: "number",
1055
+ description: "Max items (default 20)"
1056
+ } }
1057
+ }
1058
+ },
1059
+ {
1060
+ name: "memory_audit",
1061
+ description: "View the audit trail of memory operations.",
1062
+ inputSchema: {
1063
+ type: "object",
1064
+ properties: {
1065
+ operation: {
1066
+ type: "string",
1067
+ description: "Filter by operation type"
1068
+ },
1069
+ limit: {
1070
+ type: "number",
1071
+ description: "Max entries (default 50)"
1072
+ }
1073
+ }
1074
+ }
1075
+ },
1076
+ {
1077
+ name: "memory_governance_delete",
1078
+ description: "Delete specific memories with audit trail.",
1079
+ inputSchema: {
1080
+ type: "object",
1081
+ properties: {
1082
+ memoryIds: {
1083
+ type: "string",
1084
+ description: "Comma-separated memory IDs to delete"
1085
+ },
1086
+ reason: {
1087
+ type: "string",
1088
+ description: "Reason for deletion"
1089
+ }
1090
+ },
1091
+ required: ["memoryIds"]
1092
+ }
1093
+ },
1094
+ {
1095
+ name: "memory_snapshot_create",
1096
+ description: "Create a git-versioned snapshot of current memory state.",
1097
+ inputSchema: {
1098
+ type: "object",
1099
+ properties: { message: {
1100
+ type: "string",
1101
+ description: "Snapshot description"
1102
+ } }
1103
+ }
1104
+ }
1105
+ ];
1106
+ const V050_TOOLS = [
1107
+ {
1108
+ name: "memory_action_create",
1109
+ description: "Create an actionable work item with typed dependencies. Actions track what agents need to do and how work items relate to each other.",
1110
+ inputSchema: {
1111
+ type: "object",
1112
+ properties: {
1113
+ title: {
1114
+ type: "string",
1115
+ description: "Action title"
1116
+ },
1117
+ description: {
1118
+ type: "string",
1119
+ description: "Detailed description of the work"
1120
+ },
1121
+ priority: {
1122
+ type: "number",
1123
+ description: "Priority 1-10 (10 highest)"
1124
+ },
1125
+ project: {
1126
+ type: "string",
1127
+ description: "Project path"
1128
+ },
1129
+ tags: {
1130
+ type: "string",
1131
+ description: "Comma-separated tags"
1132
+ },
1133
+ parentId: {
1134
+ type: "string",
1135
+ description: "Parent action ID for hierarchical actions"
1136
+ },
1137
+ requires: {
1138
+ type: "string",
1139
+ description: "Comma-separated action IDs that must complete before this"
1140
+ }
1141
+ },
1142
+ required: ["title"]
1143
+ }
1144
+ },
1145
+ {
1146
+ name: "memory_action_update",
1147
+ description: "Update an action's status, priority, or details. Set status to 'done' to complete it and unblock dependent actions.",
1148
+ inputSchema: {
1149
+ type: "object",
1150
+ properties: {
1151
+ actionId: {
1152
+ type: "string",
1153
+ description: "Action ID to update"
1154
+ },
1155
+ status: {
1156
+ type: "string",
1157
+ description: "New status: pending, active, done, blocked, cancelled"
1158
+ },
1159
+ result: {
1160
+ type: "string",
1161
+ description: "Outcome description (when completing)"
1162
+ },
1163
+ priority: {
1164
+ type: "number",
1165
+ description: "New priority 1-10"
1166
+ }
1167
+ },
1168
+ required: ["actionId"]
1169
+ }
1170
+ },
1171
+ {
1172
+ name: "memory_frontier",
1173
+ description: "Get all unblocked actions ranked by priority and urgency. Returns the frontier of actionable work with no unsatisfied dependencies.",
1174
+ inputSchema: {
1175
+ type: "object",
1176
+ properties: {
1177
+ project: {
1178
+ type: "string",
1179
+ description: "Filter by project"
1180
+ },
1181
+ agentId: {
1182
+ type: "string",
1183
+ description: "Agent ID to check lease conflicts"
1184
+ },
1185
+ limit: {
1186
+ type: "number",
1187
+ description: "Max results (default 20)"
1188
+ }
1189
+ }
1190
+ }
1191
+ },
1192
+ {
1193
+ name: "memory_next",
1194
+ description: "Get the single most important next action to work on. Combines dependency resolution, priority, and recency into a score.",
1195
+ inputSchema: {
1196
+ type: "object",
1197
+ properties: {
1198
+ project: {
1199
+ type: "string",
1200
+ description: "Filter by project"
1201
+ },
1202
+ agentId: {
1203
+ type: "string",
1204
+ description: "Current agent ID"
1205
+ }
1206
+ }
1207
+ }
1208
+ },
1209
+ {
1210
+ name: "memory_lease",
1211
+ description: "Acquire, release, or renew an exclusive lease on an action. Prevents multiple agents from working on the same thing.",
1212
+ inputSchema: {
1213
+ type: "object",
1214
+ properties: {
1215
+ actionId: {
1216
+ type: "string",
1217
+ description: "Action ID"
1218
+ },
1219
+ agentId: {
1220
+ type: "string",
1221
+ description: "Agent claiming the action"
1222
+ },
1223
+ operation: {
1224
+ type: "string",
1225
+ description: "acquire, release, or renew"
1226
+ },
1227
+ result: {
1228
+ type: "string",
1229
+ description: "Result when releasing (marks action done)"
1230
+ },
1231
+ ttlMs: {
1232
+ type: "number",
1233
+ description: "Lease duration in ms (default 10min, max 1hr)"
1234
+ }
1235
+ },
1236
+ required: [
1237
+ "actionId",
1238
+ "agentId",
1239
+ "operation"
1240
+ ]
1241
+ }
1242
+ },
1243
+ {
1244
+ name: "memory_routine_run",
1245
+ description: "Instantiate a frozen workflow routine, creating actions for each step with proper dependencies.",
1246
+ inputSchema: {
1247
+ type: "object",
1248
+ properties: {
1249
+ routineId: {
1250
+ type: "string",
1251
+ description: "Routine template ID"
1252
+ },
1253
+ project: {
1254
+ type: "string",
1255
+ description: "Project context"
1256
+ },
1257
+ initiatedBy: {
1258
+ type: "string",
1259
+ description: "Agent starting the run"
1260
+ }
1261
+ },
1262
+ required: ["routineId"]
1263
+ }
1264
+ },
1265
+ {
1266
+ name: "memory_signal_send",
1267
+ description: "Send a message to another agent or broadcast. Supports threading, typed messages, and TTL expiration.",
1268
+ inputSchema: {
1269
+ type: "object",
1270
+ properties: {
1271
+ from: {
1272
+ type: "string",
1273
+ description: "Sender agent ID"
1274
+ },
1275
+ to: {
1276
+ type: "string",
1277
+ description: "Recipient agent ID (omit for broadcast)"
1278
+ },
1279
+ content: {
1280
+ type: "string",
1281
+ description: "Message content"
1282
+ },
1283
+ type: {
1284
+ type: "string",
1285
+ description: "Message type: info, request, response, alert, handoff"
1286
+ },
1287
+ replyTo: {
1288
+ type: "string",
1289
+ description: "Signal ID to reply to (auto-threads)"
1290
+ }
1291
+ },
1292
+ required: ["from", "content"]
1293
+ }
1294
+ },
1295
+ {
1296
+ name: "memory_signal_read",
1297
+ description: "Read messages for an agent. Marks delivered messages as read.",
1298
+ inputSchema: {
1299
+ type: "object",
1300
+ properties: {
1301
+ agentId: {
1302
+ type: "string",
1303
+ description: "Agent to read messages for"
1304
+ },
1305
+ unreadOnly: {
1306
+ type: "string",
1307
+ description: "Set to 'true' for unread only"
1308
+ },
1309
+ threadId: {
1310
+ type: "string",
1311
+ description: "Filter by conversation thread"
1312
+ },
1313
+ limit: {
1314
+ type: "number",
1315
+ description: "Max messages (default 50)"
1316
+ }
1317
+ },
1318
+ required: ["agentId"]
1319
+ }
1320
+ },
1321
+ {
1322
+ name: "memory_checkpoint",
1323
+ description: "Create or resolve an external checkpoint (CI result, approval, deploy status) that gates action progress.",
1324
+ inputSchema: {
1325
+ type: "object",
1326
+ properties: {
1327
+ operation: {
1328
+ type: "string",
1329
+ description: "create, resolve, or list"
1330
+ },
1331
+ name: {
1332
+ type: "string",
1333
+ description: "Checkpoint name (for create)"
1334
+ },
1335
+ checkpointId: {
1336
+ type: "string",
1337
+ description: "Checkpoint ID (for resolve)"
1338
+ },
1339
+ status: {
1340
+ type: "string",
1341
+ description: "passed or failed (for resolve)"
1342
+ },
1343
+ type: {
1344
+ type: "string",
1345
+ description: "Checkpoint type: ci, approval, deploy, external, timer"
1346
+ },
1347
+ linkedActionIds: {
1348
+ type: "string",
1349
+ description: "Comma-separated action IDs this checkpoint gates (for create)"
1350
+ }
1351
+ },
1352
+ required: ["operation"]
1353
+ }
1354
+ },
1355
+ {
1356
+ name: "memory_mesh_sync",
1357
+ description: "Sync memories and actions with peer agentmemory instances for multi-agent collaboration.",
1358
+ inputSchema: {
1359
+ type: "object",
1360
+ properties: {
1361
+ peerId: {
1362
+ type: "string",
1363
+ description: "Specific peer ID (omit for all)"
1364
+ },
1365
+ direction: {
1366
+ type: "string",
1367
+ description: "push, pull, or both (default both)"
1368
+ }
1369
+ }
1370
+ }
1371
+ }
1372
+ ];
1373
+ const V051_TOOLS = [
1374
+ {
1375
+ name: "memory_sentinel_create",
1376
+ description: "Create an event-driven sentinel that watches for conditions (webhook, timer, threshold, pattern, approval) and auto-unblocks gated actions when triggered.",
1377
+ inputSchema: {
1378
+ type: "object",
1379
+ properties: {
1380
+ name: {
1381
+ type: "string",
1382
+ description: "Sentinel name"
1383
+ },
1384
+ type: {
1385
+ type: "string",
1386
+ description: "Type: webhook, timer, threshold, pattern, approval, custom"
1387
+ },
1388
+ config: {
1389
+ type: "string",
1390
+ description: "JSON config (timer: {durationMs}, threshold: {metric,operator,value}, pattern: {pattern}, webhook: {path})"
1391
+ },
1392
+ linkedActionIds: {
1393
+ type: "string",
1394
+ description: "Comma-separated action IDs to gate"
1395
+ },
1396
+ expiresInMs: {
1397
+ type: "number",
1398
+ description: "Auto-expire after ms"
1399
+ }
1400
+ },
1401
+ required: ["name", "type"]
1402
+ }
1403
+ },
1404
+ {
1405
+ name: "memory_sentinel_trigger",
1406
+ description: "Externally fire a sentinel, providing an optional result payload. Unblocks any gated actions.",
1407
+ inputSchema: {
1408
+ type: "object",
1409
+ properties: {
1410
+ sentinelId: {
1411
+ type: "string",
1412
+ description: "Sentinel ID to trigger"
1413
+ },
1414
+ result: {
1415
+ type: "string",
1416
+ description: "JSON result payload"
1417
+ }
1418
+ },
1419
+ required: ["sentinelId"]
1420
+ }
1421
+ },
1422
+ {
1423
+ name: "memory_sketch_create",
1424
+ description: "Create an ephemeral action graph for exploratory work. Auto-expires after TTL. Can be promoted to permanent actions or discarded.",
1425
+ inputSchema: {
1426
+ type: "object",
1427
+ properties: {
1428
+ title: {
1429
+ type: "string",
1430
+ description: "Sketch title"
1431
+ },
1432
+ description: {
1433
+ type: "string",
1434
+ description: "What this sketch explores"
1435
+ },
1436
+ expiresInMs: {
1437
+ type: "number",
1438
+ description: "TTL in ms (default 1 hour)"
1439
+ },
1440
+ project: {
1441
+ type: "string",
1442
+ description: "Project context"
1443
+ }
1444
+ },
1445
+ required: ["title"]
1446
+ }
1447
+ },
1448
+ {
1449
+ name: "memory_sketch_promote",
1450
+ description: "Promote a sketch's ephemeral actions to permanent actions. Makes the exploratory work official.",
1451
+ inputSchema: {
1452
+ type: "object",
1453
+ properties: {
1454
+ sketchId: {
1455
+ type: "string",
1456
+ description: "Sketch ID to promote"
1457
+ },
1458
+ project: {
1459
+ type: "string",
1460
+ description: "Override project for promoted actions"
1461
+ }
1462
+ },
1463
+ required: ["sketchId"]
1464
+ }
1465
+ },
1466
+ {
1467
+ name: "memory_crystallize",
1468
+ description: "Compress completed action chains into compact crystal digests using LLM summarization. Extracts narrative, key outcomes, files affected, and lessons.",
1469
+ inputSchema: {
1470
+ type: "object",
1471
+ properties: {
1472
+ actionIds: {
1473
+ type: "string",
1474
+ description: "Comma-separated completed action IDs to crystallize"
1475
+ },
1476
+ project: {
1477
+ type: "string",
1478
+ description: "Project context"
1479
+ },
1480
+ sessionId: {
1481
+ type: "string",
1482
+ description: "Session context"
1483
+ }
1484
+ },
1485
+ required: ["actionIds"]
1486
+ }
1487
+ },
1488
+ {
1489
+ name: "memory_diagnose",
1490
+ description: "Run health checks across all subsystems (actions, leases, sentinels, sketches, signals, sessions, memories, mesh). Identifies stuck, orphaned, and inconsistent state.",
1491
+ inputSchema: {
1492
+ type: "object",
1493
+ properties: { categories: {
1494
+ type: "string",
1495
+ description: "Comma-separated categories to check (default all)"
1496
+ } }
1497
+ }
1498
+ },
1499
+ {
1500
+ name: "memory_heal",
1501
+ description: "Auto-fix all fixable issues found by diagnostics. Unblocks stuck actions, expires stale leases, cleans up orphaned data.",
1502
+ inputSchema: {
1503
+ type: "object",
1504
+ properties: {
1505
+ categories: {
1506
+ type: "string",
1507
+ description: "Comma-separated categories to heal (default all)"
1508
+ },
1509
+ dryRun: {
1510
+ type: "string",
1511
+ description: "Set to 'true' for dry run (report but don't fix)"
1512
+ }
1513
+ }
1514
+ }
1515
+ },
1516
+ {
1517
+ name: "memory_facet_tag",
1518
+ description: "Attach a structured tag (dimension:value) to an action, memory, or observation for multi-dimensional categorization.",
1519
+ inputSchema: {
1520
+ type: "object",
1521
+ properties: {
1522
+ targetId: {
1523
+ type: "string",
1524
+ description: "ID of the target to tag"
1525
+ },
1526
+ targetType: {
1527
+ type: "string",
1528
+ description: "Type: action, memory, or observation"
1529
+ },
1530
+ dimension: {
1531
+ type: "string",
1532
+ description: "Tag dimension (e.g., priority, team, status)"
1533
+ },
1534
+ value: {
1535
+ type: "string",
1536
+ description: "Tag value (e.g., urgent, backend, reviewed)"
1537
+ }
1538
+ },
1539
+ required: [
1540
+ "targetId",
1541
+ "targetType",
1542
+ "dimension",
1543
+ "value"
1544
+ ]
1545
+ }
1546
+ },
1547
+ {
1548
+ name: "memory_facet_query",
1549
+ description: "Query targets by facet tags with AND/OR logic. Find all actions tagged priority:urgent AND team:backend.",
1550
+ inputSchema: {
1551
+ type: "object",
1552
+ properties: {
1553
+ matchAll: {
1554
+ type: "string",
1555
+ description: "Comma-separated dimension:value pairs (AND logic)"
1556
+ },
1557
+ matchAny: {
1558
+ type: "string",
1559
+ description: "Comma-separated dimension:value pairs (OR logic)"
1560
+ },
1561
+ targetType: {
1562
+ type: "string",
1563
+ description: "Filter by type: action, memory, or observation"
1564
+ }
1565
+ }
1566
+ }
1567
+ }
1568
+ ];
1569
+ const V061_TOOLS = [{
1570
+ name: "memory_verify",
1571
+ description: "Verify a memory or observation by tracing its citation chain back to source observations and session context. Returns provenance information including confidence scores.",
1572
+ inputSchema: {
1573
+ type: "object",
1574
+ properties: { id: {
1575
+ type: "string",
1576
+ description: "Memory ID or observation ID to verify"
1577
+ } },
1578
+ required: ["id"]
1579
+ }
1580
+ }];
1581
+ const V070_TOOLS = [
1582
+ {
1583
+ name: "memory_lesson_save",
1584
+ description: "Save a lesson learned from this session. Lessons have confidence scores that strengthen when reinforced and decay when not used. Duplicate content auto-strengthens the existing lesson.",
1585
+ inputSchema: {
1586
+ type: "object",
1587
+ properties: {
1588
+ content: {
1589
+ type: "string",
1590
+ description: "The lesson learned (what worked, what to avoid, when to use X approach)"
1591
+ },
1592
+ context: {
1593
+ type: "string",
1594
+ description: "When/where this lesson applies"
1595
+ },
1596
+ confidence: {
1597
+ type: "number",
1598
+ description: "Initial confidence 0.0-1.0 (default 0.5)"
1599
+ },
1600
+ project: {
1601
+ type: "string",
1602
+ description: "Project this lesson is about"
1603
+ },
1604
+ tags: {
1605
+ type: "string",
1606
+ description: "Comma-separated tags"
1607
+ }
1608
+ },
1609
+ required: ["content"]
1610
+ }
1611
+ },
1612
+ {
1613
+ name: "memory_lesson_recall",
1614
+ description: "Search lessons by query. Returns lessons sorted by confidence and recency. Use to check what the agent has learned before making decisions.",
1615
+ inputSchema: {
1616
+ type: "object",
1617
+ properties: {
1618
+ query: {
1619
+ type: "string",
1620
+ description: "Search query"
1621
+ },
1622
+ project: {
1623
+ type: "string",
1624
+ description: "Filter by project"
1625
+ },
1626
+ minConfidence: {
1627
+ type: "number",
1628
+ description: "Minimum confidence threshold (default 0.1)"
1629
+ },
1630
+ limit: {
1631
+ type: "number",
1632
+ description: "Max results (default 10)"
1633
+ }
1634
+ },
1635
+ required: ["query"]
1636
+ }
1637
+ },
1638
+ {
1639
+ name: "memory_lesson_delete",
1640
+ description: "Soft-delete a lesson by id. Deleted lessons are excluded from recall and list; re-saving the same content creates a fresh lesson.",
1641
+ inputSchema: {
1642
+ type: "object",
1643
+ properties: { lessonId: {
1644
+ type: "string",
1645
+ description: "The lesson id (lsn_...)"
1646
+ } },
1647
+ required: ["lessonId"]
1648
+ }
1649
+ },
1650
+ {
1651
+ name: "memory_obsidian_export",
1652
+ description: "Export memories, lessons, and crystals as Obsidian-compatible Markdown files with YAML frontmatter and wikilinks for graph view.",
1653
+ inputSchema: {
1654
+ type: "object",
1655
+ properties: {
1656
+ vaultDir: {
1657
+ type: "string",
1658
+ description: "Output directory (default ~/.agentmemory/vault/)"
1659
+ },
1660
+ types: {
1661
+ type: "string",
1662
+ description: "Comma-separated types to export: memories,lessons,crystals,sessions (default all)"
1663
+ }
1664
+ }
1665
+ }
1666
+ }
1667
+ ];
1668
+ const V073_TOOLS = [{
1669
+ name: "memory_reflect",
1670
+ description: "Traverse the knowledge graph, group related memories by concept clusters, and synthesize higher-order insights via LLM. Returns new and reinforced insights.",
1671
+ inputSchema: {
1672
+ type: "object",
1673
+ properties: {
1674
+ project: {
1675
+ type: "string",
1676
+ description: "Filter by project"
1677
+ },
1678
+ maxClusters: {
1679
+ type: "number",
1680
+ description: "Max concept clusters to process (default 10, max 20)"
1681
+ }
1682
+ }
1683
+ }
1684
+ }, {
1685
+ name: "memory_insight_list",
1686
+ description: "List synthesized insights — higher-order observations derived from patterns across memories, lessons, and crystals.",
1687
+ inputSchema: {
1688
+ type: "object",
1689
+ properties: {
1690
+ project: {
1691
+ type: "string",
1692
+ description: "Filter by project"
1693
+ },
1694
+ minConfidence: {
1695
+ type: "number",
1696
+ description: "Minimum confidence threshold (default 0)"
1697
+ },
1698
+ limit: {
1699
+ type: "number",
1700
+ description: "Max results (default 50)"
1701
+ }
1702
+ }
1703
+ }
1704
+ }];
1705
+ const V010_SLOTS_TOOLS = [
1706
+ {
1707
+ name: "memory_slot_list",
1708
+ description: "List all memory slots (pinned + project + global). Slots are editable, size-limited memory units the agent can read and modify across sessions.",
1709
+ inputSchema: {
1710
+ type: "object",
1711
+ properties: {}
1712
+ }
1713
+ },
1714
+ {
1715
+ name: "memory_slot_get",
1716
+ description: "Read a single slot by label.",
1717
+ inputSchema: {
1718
+ type: "object",
1719
+ properties: { label: {
1720
+ type: "string",
1721
+ description: "Slot label (e.g. 'persona', 'pending_items')"
1722
+ } },
1723
+ required: ["label"]
1724
+ }
1725
+ },
1726
+ {
1727
+ name: "memory_slot_create",
1728
+ description: "Create a new slot. Reject if a slot with the same label already exists.",
1729
+ inputSchema: {
1730
+ type: "object",
1731
+ properties: {
1732
+ label: {
1733
+ type: "string",
1734
+ description: "Slot label — lowercase, starts with letter, [a-z0-9_]"
1735
+ },
1736
+ content: {
1737
+ type: "string",
1738
+ description: "Initial content (default empty)"
1739
+ },
1740
+ sizeLimit: {
1741
+ type: "number",
1742
+ description: "Max chars (default 2000, hard cap 20000)"
1743
+ },
1744
+ description: {
1745
+ type: "string",
1746
+ description: "What this slot is for"
1747
+ },
1748
+ pinned: {
1749
+ type: "string",
1750
+ description: "'false' to exclude from context injection; default true"
1751
+ },
1752
+ scope: {
1753
+ type: "string",
1754
+ description: "'project' (default) or 'global' (shared across projects)"
1755
+ }
1756
+ },
1757
+ required: ["label"]
1758
+ }
1759
+ },
1760
+ {
1761
+ name: "memory_slot_append",
1762
+ description: "Append text to an existing slot. Fails with 413 if the append would exceed the slot's sizeLimit — agent must compact via memory_slot_replace first.",
1763
+ inputSchema: {
1764
+ type: "object",
1765
+ properties: {
1766
+ label: {
1767
+ type: "string",
1768
+ description: "Slot label"
1769
+ },
1770
+ text: {
1771
+ type: "string",
1772
+ description: "Text to append"
1773
+ }
1774
+ },
1775
+ required: ["label", "text"]
1776
+ }
1777
+ },
1778
+ {
1779
+ name: "memory_slot_replace",
1780
+ description: "Replace slot content in place. Fails if content exceeds sizeLimit.",
1781
+ inputSchema: {
1782
+ type: "object",
1783
+ properties: {
1784
+ label: {
1785
+ type: "string",
1786
+ description: "Slot label"
1787
+ },
1788
+ content: {
1789
+ type: "string",
1790
+ description: "New full content"
1791
+ }
1792
+ },
1793
+ required: ["label", "content"]
1794
+ }
1795
+ },
1796
+ {
1797
+ name: "memory_slot_delete",
1798
+ description: "Delete a slot. Seeded default slots can be deleted unless marked readOnly.",
1799
+ inputSchema: {
1800
+ type: "object",
1801
+ properties: { label: {
1802
+ type: "string",
1803
+ description: "Slot label"
1804
+ } },
1805
+ required: ["label"]
1806
+ }
1807
+ }
1808
+ ];
1809
+ const ESSENTIAL_TOOLS = new Set([
1810
+ "memory_save",
1811
+ "memory_recall",
1812
+ "memory_consolidate",
1813
+ "memory_smart_search",
1814
+ "memory_sessions",
1815
+ "memory_diagnose",
1816
+ "memory_lesson_save",
1817
+ "memory_reflect"
1818
+ ]);
1819
+ function getAllTools() {
1820
+ return [
1821
+ ...CORE_TOOLS,
1822
+ ...V040_TOOLS,
1823
+ ...V050_TOOLS,
1824
+ ...V051_TOOLS,
1825
+ ...V061_TOOLS,
1826
+ ...V070_TOOLS,
1827
+ ...V073_TOOLS,
1828
+ ...V010_SLOTS_TOOLS
1829
+ ];
1830
+ }
1831
+ function getVisibleTools() {
1832
+ if ((process.env["AGENTMEMORY_TOOLS"] || "all") === "core") return getAllTools().filter((t) => ESSENTIAL_TOOLS.has(t.name));
1833
+ return getAllTools();
1834
+ }
1835
+ //#endregion
1836
+ //#region src/functions/audit.ts
1837
+ const AUDIT_MIGRATE_FUNCTION_ID = "mem::audit-migrate";
1838
+ const AUDIT_MIGRATION_COPY_CONCURRENCY = 32;
1839
+ const AUDIT_MIGRATION_DELETE_CONCURRENCY = 8;
1840
+ const AUDIT_MONTHS_LOCK = KV.auditMonths;
1841
+ const AUDIT_MIGRATION_LOCK = "mem:audit:migration-lock";
1842
+ const AUDIT_MIGRATION_STATE_KEY = "migration";
1843
+ const AUDIT_MIGRATION_DELETE_WAIT_INTERVALS = 2;
1844
+ const STATE_STORE_DIR_NAME = "state_store.db";
1845
+ function sleep(ms) {
1846
+ return new Promise((resolve) => setTimeout(resolve, ms));
1847
+ }
1848
+ function encodeStateIndexSegment(index) {
1849
+ let out = "";
1850
+ for (const byte of Buffer.from(index, "utf8")) {
1851
+ const ch = String.fromCharCode(byte);
1852
+ out += /^[A-Za-z0-9\-_.]$/.test(ch) ? ch : `%${byte.toString(16).toUpperCase().padStart(2, "0")}`;
1853
+ }
1854
+ return out;
1855
+ }
1856
+ function legacyAuditStateFilePath(dataDir) {
1857
+ return join(dataDir, STATE_STORE_DIR_NAME, `${encodeStateIndexSegment(KV.audit)}.bin`);
1858
+ }
1859
+ async function probeLegacyAuditFile() {
1860
+ const dataDir = getEnvVar("AGENTMEMORY_DATA_DIR");
1861
+ if (!dataDir) return {
1862
+ safe: false,
1863
+ reason: "unreadable"
1864
+ };
1865
+ const storeDir = join(dataDir, STATE_STORE_DIR_NAME);
1866
+ try {
1867
+ await stat(storeDir);
1868
+ } catch {
1869
+ return {
1870
+ safe: false,
1871
+ reason: "unreadable"
1872
+ };
1873
+ }
1874
+ let fileStat;
1875
+ try {
1876
+ fileStat = await stat(legacyAuditStateFilePath(dataDir));
1877
+ } catch (err) {
1878
+ if (err.code === "ENOENT") return {
1879
+ safe: true,
1880
+ empty: true
1881
+ };
1882
+ return {
1883
+ safe: false,
1884
+ reason: "unreadable"
1885
+ };
1886
+ }
1887
+ if (fileStat.size > getAuditMigrateMaxBytes()) return {
1888
+ safe: false,
1889
+ reason: "too-large",
1890
+ sizeBytes: fileStat.size
1891
+ };
1892
+ return {
1893
+ safe: true,
1894
+ empty: false,
1895
+ sizeBytes: fileStat.size
1896
+ };
1897
+ }
1898
+ async function probeLegacyAuditScope(kv) {
1899
+ let rows;
1900
+ try {
1901
+ rows = await kv.list(KV.audit);
1902
+ } catch {
1903
+ return {
1904
+ safe: false,
1905
+ reason: "unreadable"
1906
+ };
1907
+ }
1908
+ if (!Array.isArray(rows) || rows.length === 0) return {
1909
+ safe: true,
1910
+ empty: true
1911
+ };
1912
+ const sizeBytes = Buffer.byteLength(JSON.stringify(rows), "utf8");
1913
+ if (sizeBytes > getAuditMigrateMaxBytes()) return {
1914
+ safe: false,
1915
+ reason: "too-large",
1916
+ sizeBytes
1917
+ };
1918
+ return {
1919
+ safe: true,
1920
+ empty: false,
1921
+ sizeBytes
1922
+ };
1923
+ }
1924
+ async function auditMigrationDeleteDelayMs() {
1925
+ const dataDir = getEnvVar("AGENTMEMORY_DATA_DIR");
1926
+ if (!dataDir) return ENGINE_DEFAULT_SAVE_INTERVAL_MS * AUDIT_MIGRATION_DELETE_WAIT_INTERVALS;
1927
+ const configTexts = [];
1928
+ for (const path of engineStateConfigPaths(join(homedir(), ".agentmemory"), runtimeConfigPath(dataDir))) try {
1929
+ configTexts.push(await readFile(path, "utf-8"));
1930
+ } catch {}
1931
+ return engineSaveIntervalMs(configTexts) * AUDIT_MIGRATION_DELETE_WAIT_INTERVALS;
1932
+ }
1933
+ async function readAuditMigrationState(kv) {
1934
+ return kv.get(KV.auditMonths, AUDIT_MIGRATION_STATE_KEY);
1935
+ }
1936
+ async function writeAuditMigrationState(kv, state) {
1937
+ await kv.set(KV.auditMonths, AUDIT_MIGRATION_STATE_KEY, state);
1938
+ }
1939
+ function auditMonthOf(timestamp) {
1940
+ const parsed = new Date(timestamp);
1941
+ return (Number.isNaN(parsed.getTime()) ? (/* @__PURE__ */ new Date()).toISOString() : parsed.toISOString()).slice(0, 7);
1942
+ }
1943
+ function monthStartMs(month) {
1944
+ const [year, mon] = month.split("-").map(Number);
1945
+ return Date.UTC(year, mon - 1, 1);
1946
+ }
1947
+ function monthEndMs(month) {
1948
+ const [year, mon] = month.split("-").map(Number);
1949
+ return Date.UTC(year, mon, 1) - 1;
1950
+ }
1951
+ function monthNMonthsAgo(count) {
1952
+ const now = /* @__PURE__ */ new Date();
1953
+ return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - count, 1)).toISOString().slice(0, 7);
1954
+ }
1955
+ async function readAuditMonthIndex(kv) {
1956
+ return (await kv.get(KV.auditMonths, "index"))?.months ?? [];
1957
+ }
1958
+ async function markAuditMonth(kv, month) {
1959
+ await withKeyedLock(AUDIT_MONTHS_LOCK, async () => {
1960
+ const months = await readAuditMonthIndex(kv);
1961
+ if (months.includes(month)) return;
1962
+ const next = [...months, month].sort();
1963
+ await kv.set(KV.auditMonths, "index", { months: next });
1964
+ });
1965
+ }
1966
+ async function listAuditMonthsDesc(kv) {
1967
+ return [...await readAuditMonthIndex(kv)].sort().reverse();
1968
+ }
1969
+ let auditRecordedListener = null;
1970
+ function setAuditRecordedListener(listener) {
1971
+ auditRecordedListener = listener;
1972
+ }
1973
+ async function recordAudit(kv, operation, functionId, targetIds, details = {}, qualityScore, userId) {
1974
+ const entry = {
1975
+ id: generateId("aud"),
1976
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1977
+ operation,
1978
+ userId,
1979
+ functionId,
1980
+ targetIds,
1981
+ details,
1982
+ qualityScore
1983
+ };
1984
+ const month = auditMonthOf(entry.timestamp);
1985
+ await kv.set(KV.auditMonth(month), entry.id, entry);
1986
+ await markAuditMonth(kv, month);
1987
+ try {
1988
+ auditRecordedListener?.(entry);
1989
+ } catch {}
1990
+ return entry;
1991
+ }
1992
+ async function safeAudit(kv, operation, functionId, targetIds, details = {}, qualityScore, userId) {
1993
+ try {
1994
+ await recordAudit(kv, operation, functionId, targetIds, details, qualityScore, userId);
1995
+ } catch (err) {
1996
+ try {
1997
+ logger.warn("audit write failed", {
1998
+ functionId,
1999
+ operation,
2000
+ targetIds,
2001
+ error: err instanceof Error ? err.message : String(err)
2002
+ });
2003
+ } catch {}
2004
+ }
2005
+ }
2006
+ async function queryAudit(kv, filter) {
2007
+ const limit = filter?.limit || 100;
2008
+ let fromMs;
2009
+ if (filter?.dateFrom) {
2010
+ fromMs = new Date(filter.dateFrom).getTime();
2011
+ if (Number.isNaN(fromMs)) throw new Error(`Invalid dateFrom: ${filter.dateFrom}`);
2012
+ }
2013
+ const query = filter?.query?.trim().toLowerCase();
2014
+ let toMs;
2015
+ if (filter?.dateTo) {
2016
+ toMs = new Date(filter.dateTo).getTime();
2017
+ if (Number.isNaN(toMs)) throw new Error(`Invalid dateTo: ${filter.dateTo}`);
2018
+ }
2019
+ const matches = (entry) => {
2020
+ if (filter?.operation && entry.operation !== filter.operation) return false;
2021
+ const t = new Date(entry.timestamp).getTime();
2022
+ if (fromMs !== void 0 && t < fromMs) return false;
2023
+ if (toMs !== void 0 && t > toMs) return false;
2024
+ if (query && ![entry.functionId, ...entry.targetIds || []].some((v) => String(v || "").toLowerCase().includes(query))) return false;
2025
+ return true;
2026
+ };
2027
+ const seenIds = /* @__PURE__ */ new Set();
2028
+ const collected = [];
2029
+ const addIfNew = (row) => {
2030
+ if (seenIds.has(row.id)) return;
2031
+ seenIds.add(row.id);
2032
+ if (matches(row)) collected.push(row);
2033
+ };
2034
+ const months = await listAuditMonthsDesc(kv);
2035
+ for (const month of months) {
2036
+ if (collected.length >= limit) break;
2037
+ if (toMs !== void 0 && monthStartMs(month) > toMs) continue;
2038
+ if (fromMs !== void 0 && monthEndMs(month) < fromMs) break;
2039
+ const rows = await kv.list(KV.auditMonth(month));
2040
+ for (const row of rows) addIfNew(row);
2041
+ }
2042
+ let legacyFrozen = false;
2043
+ let legacyFrozenBytes;
2044
+ if (collected.length < limit) {
2045
+ const migrationState = await readAuditMigrationState(kv);
2046
+ if (migrationState?.safeToListLegacy) {
2047
+ const legacyRows = await kv.list(KV.audit);
2048
+ for (const row of legacyRows) addIfNew(row);
2049
+ } else if (migrationState?.status === "too-large" || migrationState?.status === "unreadable") {
2050
+ legacyFrozen = true;
2051
+ legacyFrozenBytes = migrationState.legacySizeBytes;
2052
+ }
2053
+ }
2054
+ collected.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());
2055
+ return {
2056
+ entries: collected.slice(0, limit),
2057
+ legacyFrozen,
2058
+ legacyFrozenBytes
2059
+ };
2060
+ }
2061
+ async function inParallel(items, concurrency, work) {
2062
+ let next = 0;
2063
+ const runners = Array.from({ length: Math.min(concurrency, items.length) }, async () => {
2064
+ while (next < items.length) {
2065
+ const item = items[next++];
2066
+ await work(item);
2067
+ }
2068
+ });
2069
+ await Promise.all(runners);
2070
+ }
2071
+ async function startAuditMigration(kv, deps = {}) {
2072
+ const onRedis = kv.backend === "redis";
2073
+ const runProbe = deps.probe ?? (onRedis ? () => probeLegacyAuditScope(kv) : probeLegacyAuditFile);
2074
+ const runDeleteDelayMs = deps.deleteDelayMs ?? (onRedis ? async () => 0 : auditMigrationDeleteDelayMs);
2075
+ const marker = await readAuditMigrationState(kv);
2076
+ if (marker?.status === "done") return;
2077
+ const probe = await runProbe();
2078
+ if (probe.safe && probe.empty) {
2079
+ await writeAuditMigrationState(kv, {
2080
+ status: "done",
2081
+ safeToListLegacy: true,
2082
+ legacySizeBytes: 0,
2083
+ migrated: marker?.migrated ?? 0,
2084
+ purged: marker?.purged ?? 0,
2085
+ summaryWritten: marker?.summaryWritten ?? true,
2086
+ checkedAt: (/* @__PURE__ */ new Date()).toISOString()
2087
+ });
2088
+ return;
2089
+ }
2090
+ if (!probe.safe) {
2091
+ await writeAuditMigrationState(kv, {
2092
+ status: probe.reason,
2093
+ safeToListLegacy: false,
2094
+ legacySizeBytes: probe.reason === "too-large" ? probe.sizeBytes : marker?.legacySizeBytes,
2095
+ migrated: marker?.migrated ?? 0,
2096
+ purged: marker?.purged ?? 0,
2097
+ summaryWritten: marker?.summaryWritten ?? false,
2098
+ checkedAt: (/* @__PURE__ */ new Date()).toISOString()
2099
+ });
2100
+ logger.warn("legacy audit log left frozen; migration only reads it locally and under a size cap", {
2101
+ reason: probe.reason,
2102
+ sizeBytes: probe.reason === "too-large" ? probe.sizeBytes : void 0
2103
+ });
2104
+ return;
2105
+ }
2106
+ let migrated = marker?.migrated ?? 0;
2107
+ let purged = marker?.purged ?? 0;
2108
+ if (marker?.status !== "copied") {
2109
+ let legacy;
2110
+ try {
2111
+ legacy = await kv.list(KV.audit);
2112
+ } catch (err) {
2113
+ logger.warn("audit migration could not read the legacy audit log", { error: err instanceof Error ? err.message : String(err) });
2114
+ return;
2115
+ }
2116
+ if (legacy.length === 0) {
2117
+ await writeAuditMigrationState(kv, {
2118
+ status: "done",
2119
+ safeToListLegacy: true,
2120
+ legacySizeBytes: 0,
2121
+ migrated,
2122
+ purged,
2123
+ summaryWritten: marker?.summaryWritten ?? true,
2124
+ checkedAt: (/* @__PURE__ */ new Date()).toISOString()
2125
+ });
2126
+ return;
2127
+ }
2128
+ const seen = /* @__PURE__ */ new Set();
2129
+ const deduped = legacy.filter((entry) => {
2130
+ if (seen.has(entry.id)) return false;
2131
+ seen.add(entry.id);
2132
+ return true;
2133
+ });
2134
+ const kept = deduped.filter((entry) => entry.operation !== "index_persist");
2135
+ purged = deduped.length - kept.length;
2136
+ migrated = kept.length;
2137
+ try {
2138
+ const months = /* @__PURE__ */ new Set();
2139
+ await inParallel(kept, AUDIT_MIGRATION_COPY_CONCURRENCY, async (entry) => {
2140
+ const month = auditMonthOf(entry.timestamp);
2141
+ await kv.set(KV.auditMonth(month), entry.id, entry);
2142
+ months.add(month);
2143
+ });
2144
+ for (const month of months) await markAuditMonth(kv, month);
2145
+ } catch (err) {
2146
+ logger.warn("audit migration stopped before finishing the copy pass; it resumes on the next boot", { error: err instanceof Error ? err.message : String(err) });
2147
+ return;
2148
+ }
2149
+ await writeAuditMigrationState(kv, {
2150
+ status: "copied",
2151
+ safeToListLegacy: false,
2152
+ legacySizeBytes: probe.sizeBytes,
2153
+ migrated,
2154
+ purged,
2155
+ summaryWritten: false,
2156
+ checkedAt: (/* @__PURE__ */ new Date()).toISOString()
2157
+ });
2158
+ }
2159
+ await sleep(await runDeleteDelayMs());
2160
+ let remaining;
2161
+ try {
2162
+ remaining = await kv.list(KV.audit);
2163
+ } catch (err) {
2164
+ logger.warn("audit migration could not re-read the legacy audit log before deleting; it resumes on the next boot", { error: err instanceof Error ? err.message : String(err) });
2165
+ return;
2166
+ }
2167
+ try {
2168
+ await inParallel(remaining.slice().reverse(), AUDIT_MIGRATION_DELETE_CONCURRENCY, async (entry) => {
2169
+ await kv.delete(KV.audit, entry.id);
2170
+ });
2171
+ } catch (err) {
2172
+ logger.warn("audit migration stopped before finishing the delete pass; it resumes on the next boot", { error: err instanceof Error ? err.message : String(err) });
2173
+ return;
2174
+ }
2175
+ await withKeyedLock(AUDIT_MIGRATION_LOCK, async () => {
2176
+ if ((await readAuditMigrationState(kv))?.summaryWritten) return;
2177
+ if (purged > 0) await safeAudit(kv, "audit_migrate", AUDIT_MIGRATE_FUNCTION_ID, [], {
2178
+ reason: "index_persist rows predate opt-in auditing",
2179
+ purged,
2180
+ migrated
2181
+ });
2182
+ await writeAuditMigrationState(kv, {
2183
+ status: "done",
2184
+ safeToListLegacy: true,
2185
+ legacySizeBytes: 0,
2186
+ migrated,
2187
+ purged,
2188
+ summaryWritten: true,
2189
+ checkedAt: (/* @__PURE__ */ new Date()).toISOString()
2190
+ });
2191
+ });
2192
+ logger.info("audit log moved to monthly scopes", {
2193
+ migrated,
2194
+ purged
2195
+ });
2196
+ }
2197
+ async function runAuditRetentionSweep(kv, retentionMonths) {
2198
+ if (!Number.isFinite(retentionMonths) || retentionMonths <= 0) return {
2199
+ droppedMonths: [],
2200
+ droppedRows: 0
2201
+ };
2202
+ const months = await readAuditMonthIndex(kv);
2203
+ const cutoff = monthNMonthsAgo(retentionMonths);
2204
+ const toDrop = months.filter((month) => month < cutoff).sort();
2205
+ if (toDrop.length === 0) return {
2206
+ droppedMonths: [],
2207
+ droppedRows: 0
2208
+ };
2209
+ let droppedRows = 0;
2210
+ for (const month of toDrop) {
2211
+ const rows = await kv.list(KV.auditMonth(month));
2212
+ for (const row of rows.slice().reverse()) {
2213
+ await kv.delete(KV.auditMonth(month), row.id);
2214
+ droppedRows++;
2215
+ }
2216
+ }
2217
+ await withKeyedLock(AUDIT_MONTHS_LOCK, async () => {
2218
+ const remaining = (await readAuditMonthIndex(kv)).filter((month) => !toDrop.includes(month)).sort();
2219
+ await kv.set(KV.auditMonths, "index", { months: remaining });
2220
+ });
2221
+ return {
2222
+ droppedMonths: toDrop,
2223
+ droppedRows
2224
+ };
2225
+ }
2226
+ //#endregion
2227
+ //#region src/secret-store.ts
2228
+ const SECRET_KEY = "AGENTMEMORY_SECRET";
2229
+ function agentmemoryHomeDir() {
2230
+ return join(homedir(), ".agentmemory");
2231
+ }
2232
+ function secretFilePath() {
2233
+ return join(agentmemoryHomeDir(), "secret");
2234
+ }
2235
+ function usable(value) {
2236
+ if (typeof value !== "string") return "";
2237
+ const trimmed = value.trim();
2238
+ if (!trimmed) return "";
2239
+ if (trimmed.startsWith("${") && trimmed.endsWith("}")) return "";
2240
+ return trimmed;
2241
+ }
2242
+ function unquote(value) {
2243
+ const quote = value[0];
2244
+ if ((quote === "\"" || quote === "'") && value.length > 1) {
2245
+ const close = value.indexOf(quote, 1);
2246
+ if (close !== -1) return value.slice(1, close);
2247
+ }
2248
+ const hash = value.indexOf(" #");
2249
+ return hash === -1 ? value : value.slice(0, hash).trim();
2250
+ }
2251
+ function readEnvFileSecret() {
2252
+ let content;
2253
+ try {
2254
+ content = readFileSync(join(agentmemoryHomeDir(), ".env"), "utf-8");
2255
+ } catch {
2256
+ return "";
2257
+ }
2258
+ if (typeof content !== "string") return "";
2259
+ let found = "";
2260
+ for (const line of content.split("\n")) {
2261
+ const trimmed = line.trim();
2262
+ if (trimmed.startsWith("#")) continue;
2263
+ const eq = trimmed.indexOf("=");
2264
+ if (eq === -1) continue;
2265
+ if (trimmed.slice(0, eq).replace(/^export\s+/, "").trim() !== SECRET_KEY) continue;
2266
+ found = usable(unquote(trimmed.slice(eq + 1).trim()));
2267
+ }
2268
+ return found;
2269
+ }
2270
+ function readStoredSecret() {
2271
+ try {
2272
+ return usable(readFileSync(secretFilePath(), "utf-8"));
2273
+ } catch {
2274
+ return "";
2275
+ }
2276
+ }
2277
+ function explicitSecret(env = process.env) {
2278
+ return usable(env[SECRET_KEY]) || readEnvFileSecret();
2279
+ }
2280
+ function isLoopbackUrl(url) {
2281
+ let hostname;
2282
+ try {
2283
+ hostname = new URL(url).hostname.toLowerCase();
2284
+ } catch {
2285
+ return false;
2286
+ }
2287
+ const bare = hostname.replace(/^\[|\]$/g, "");
2288
+ return bare === "localhost" || bare === "::1" || /^127(?:\.\d{1,3}){3}$/.test(bare);
2289
+ }
2290
+ function resolveClientSecret(baseUrl, env = process.env) {
2291
+ const fromEnv = usable(env[SECRET_KEY]);
2292
+ if (fromEnv) return fromEnv;
2293
+ if (!isLoopbackUrl(baseUrl)) return "";
2294
+ return readEnvFileSecret() || readStoredSecret();
2295
+ }
2296
+ function ensureServerSecret(env = process.env) {
2297
+ const configured = explicitSecret(env);
2298
+ if (configured) return {
2299
+ secret: configured,
2300
+ source: "env"
2301
+ };
2302
+ const stored = readStoredSecret();
2303
+ if (stored) return {
2304
+ secret: stored,
2305
+ source: "file"
2306
+ };
2307
+ const generated = randomBytes(32).toString("hex");
2308
+ const path = secretFilePath();
2309
+ mkdirSync(agentmemoryHomeDir(), {
2310
+ recursive: true,
2311
+ mode: 448
2312
+ });
2313
+ const staging = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
2314
+ const fd = openSync(staging, "wx", 384);
2315
+ try {
2316
+ writeSync(fd, `${generated}\n`);
2317
+ } finally {
2318
+ closeSync(fd);
2319
+ }
2320
+ try {
2321
+ chmodSync(staging, 384);
2322
+ linkSync(staging, path);
2323
+ } catch (err) {
2324
+ if (err.code !== "EEXIST") throw err;
2325
+ const raced = readStoredSecret();
2326
+ if (!raced) throw err;
2327
+ return {
2328
+ secret: raced,
2329
+ source: "file"
2330
+ };
2331
+ } finally {
2332
+ try {
2333
+ unlinkSync(staging);
2334
+ } catch {}
2335
+ }
2336
+ return {
2337
+ secret: generated,
2338
+ source: "generated"
2339
+ };
2340
+ }
2341
+ function bearerHeaders(baseUrl, env = process.env) {
2342
+ const secret = resolveClientSecret(baseUrl, env);
2343
+ return secret ? { Authorization: `Bearer ${secret}` } : {};
2344
+ }
2345
+ //#endregion
2346
+ export { bootWarn as $, getStandalonePersistPath as A, isContextInjectionEnabled as B, getConsolidationDecayDays as C, getIndexSaveIntervalMs as D, getFollowupWindowSeconds as E, getViewerStreamMax as F, isVectorBackfillAllEnabled as G, isGraphCompactOnBootEnabled as H, hydrateProcessEnvFromFile as I, loadEmbeddingConfig as J, loadClaudeBridgeConfig as K, isAgentScopeIsolated as L, getStateSaveIntervalMs as M, getVectorBackfillMax as N, getRedisUrl as O, getVectorBucketSize as P, bootLog as Q, isAutoCompressEnabled as R, getConsolidationCooldownMs as S, getEnvVar as T, isGraphExtractionEnabled as U, isDropStaleIndexEnabled as V, isSessionSweepEnabled as W, loadSnapshotConfig as X, loadFallbackConfig as Y, loadTeamConfig as Z, VERSION as _, secretFilePath as a, isBundledConfig as at, getAgentId as b, recordAudit as c, resolveEngineCwd as ct, setAuditRecordedListener as d, runtimeConfigPath as dt, logger as et, startAuditMigration as f, captureDurableAfterMs as ft, III_PINNED_VERSION as g, renderEngineConfig as gt, getVisibleTools as h, engineStateConfigPaths as ht, resolveClientSecret as i, engineChildEnv as it, getStateBackend as j, getSessionSweepStaleHours as k, runAuditRetentionSweep as l, resolveLaunchRenderFailure as lt, getAllTools as m, engineFlushWaitMs as mt, ensureServerSecret as n, dockerComposeArgs as nt, AUDIT_MIGRATION_STATE_KEY as o, legacyDataMigrations as ot, ESSENTIAL_TOOLS as p, clearPersistedBuiltinConfig as pt, loadConfig as q, explicitSecret as r, dockerProjectName as rt, queryAudit as s, redactCredentialUrls as st, bearerHeaders as t, setBootVerbose as tt, safeAudit as u, rewriteBundledConfig as ut, detectEmbeddingProvider as v, getConsolidationIntervalMs as w, getAuditRetentionMonths as x, detectLlmProviderKind as y, isConsolidationEnabled as z };
2347
+
2348
+ //# sourceMappingURL=secret-store-BnY3A50C.mjs.map