@agentmemory/agentmemory 0.7.2 → 0.7.3

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 (217) hide show
  1. package/AGENTS.md +2 -2
  2. package/README.md +41 -68
  3. package/dist/cli.mjs +3 -3
  4. package/dist/index.mjs +3 -2
  5. package/dist/index.mjs.map +1 -1
  6. package/dist/{src-1fTKFEtN.mjs → src-sYZDDbiA.mjs} +4 -3
  7. package/dist/src-sYZDDbiA.mjs.map +1 -0
  8. package/dist/standalone.mjs +1 -1
  9. package/dist/standalone.mjs.map +1 -1
  10. package/package.json +10 -1
  11. package/plugin/.claude-plugin/plugin.json +1 -1
  12. package/plugin/scripts/notification.d.mts +1 -0
  13. package/plugin/scripts/notification.mjs.map +1 -0
  14. package/plugin/scripts/post-tool-failure.d.mts +1 -0
  15. package/plugin/scripts/post-tool-failure.mjs.map +1 -0
  16. package/plugin/scripts/post-tool-use.d.mts +1 -0
  17. package/plugin/scripts/post-tool-use.mjs.map +1 -0
  18. package/plugin/scripts/pre-compact.d.mts +1 -0
  19. package/plugin/scripts/pre-compact.mjs.map +1 -0
  20. package/plugin/scripts/pre-tool-use.d.mts +1 -0
  21. package/plugin/scripts/pre-tool-use.mjs.map +1 -0
  22. package/plugin/scripts/prompt-submit.d.mts +1 -0
  23. package/plugin/scripts/prompt-submit.mjs.map +1 -0
  24. package/plugin/scripts/session-end.d.mts +1 -0
  25. package/plugin/scripts/session-end.mjs.map +1 -0
  26. package/plugin/scripts/session-start.d.mts +1 -0
  27. package/plugin/scripts/session-start.mjs.map +1 -0
  28. package/plugin/scripts/stop.d.mts +1 -0
  29. package/plugin/scripts/stop.mjs.map +1 -0
  30. package/plugin/scripts/subagent-start.d.mts +1 -0
  31. package/plugin/scripts/subagent-start.mjs.map +1 -0
  32. package/plugin/scripts/subagent-stop.d.mts +1 -0
  33. package/plugin/scripts/subagent-stop.mjs.map +1 -0
  34. package/plugin/scripts/task-completed.d.mts +1 -0
  35. package/plugin/scripts/task-completed.mjs.map +1 -0
  36. package/.claude-plugin/marketplace.json +0 -14
  37. package/.github/workflows/ci.yml +0 -22
  38. package/.github/workflows/publish.yml +0 -28
  39. package/assets/banner.png +0 -0
  40. package/assets/demo.gif +0 -0
  41. package/assets/demo.mp4 +0 -0
  42. package/benchmark/QUALITY.md +0 -73
  43. package/benchmark/REAL-EMBEDDINGS.md +0 -67
  44. package/benchmark/SCALE.md +0 -110
  45. package/benchmark/dataset.ts +0 -293
  46. package/benchmark/quality-eval.ts +0 -643
  47. package/benchmark/real-embeddings-eval.ts +0 -405
  48. package/benchmark/scale-eval.ts +0 -398
  49. package/dist/src-1fTKFEtN.mjs.map +0 -1
  50. package/src/auth.ts +0 -12
  51. package/src/cli.ts +0 -251
  52. package/src/config.ts +0 -221
  53. package/src/eval/metrics-store.ts +0 -65
  54. package/src/eval/quality.ts +0 -51
  55. package/src/eval/schemas.ts +0 -124
  56. package/src/eval/self-correct.ts +0 -28
  57. package/src/eval/validator.ts +0 -31
  58. package/src/functions/actions.ts +0 -288
  59. package/src/functions/audit.ts +0 -61
  60. package/src/functions/auto-forget.ts +0 -169
  61. package/src/functions/branch-aware.ts +0 -169
  62. package/src/functions/cascade.ts +0 -80
  63. package/src/functions/checkpoints.ts +0 -209
  64. package/src/functions/claude-bridge.ts +0 -161
  65. package/src/functions/compress.ts +0 -194
  66. package/src/functions/consolidate.ts +0 -212
  67. package/src/functions/consolidation-pipeline.ts +0 -258
  68. package/src/functions/context.ts +0 -169
  69. package/src/functions/crystallize.ts +0 -293
  70. package/src/functions/dedup.ts +0 -57
  71. package/src/functions/diagnostics.ts +0 -785
  72. package/src/functions/enrich.ts +0 -132
  73. package/src/functions/evict.ts +0 -163
  74. package/src/functions/export-import.ts +0 -508
  75. package/src/functions/facets.ts +0 -248
  76. package/src/functions/file-index.ts +0 -106
  77. package/src/functions/flow-compress.ts +0 -214
  78. package/src/functions/frontier.ts +0 -196
  79. package/src/functions/governance.ts +0 -131
  80. package/src/functions/graph-retrieval.ts +0 -277
  81. package/src/functions/graph.ts +0 -275
  82. package/src/functions/leases.ts +0 -216
  83. package/src/functions/lessons.ts +0 -253
  84. package/src/functions/mesh.ts +0 -434
  85. package/src/functions/migrate.ts +0 -165
  86. package/src/functions/observe.ts +0 -144
  87. package/src/functions/obsidian-export.ts +0 -310
  88. package/src/functions/patterns.ts +0 -138
  89. package/src/functions/privacy.ts +0 -39
  90. package/src/functions/profile.ts +0 -155
  91. package/src/functions/query-expansion.ts +0 -186
  92. package/src/functions/relations.ts +0 -237
  93. package/src/functions/remember.ts +0 -162
  94. package/src/functions/retention.ts +0 -235
  95. package/src/functions/routines.ts +0 -289
  96. package/src/functions/search.ts +0 -80
  97. package/src/functions/sentinels.ts +0 -417
  98. package/src/functions/signals.ts +0 -186
  99. package/src/functions/sketches.ts +0 -274
  100. package/src/functions/sliding-window.ts +0 -257
  101. package/src/functions/smart-search.ts +0 -115
  102. package/src/functions/snapshot.ts +0 -219
  103. package/src/functions/summarize.ts +0 -155
  104. package/src/functions/team.ts +0 -147
  105. package/src/functions/temporal-graph.ts +0 -476
  106. package/src/functions/timeline.ts +0 -138
  107. package/src/functions/verify.ts +0 -117
  108. package/src/health/monitor.ts +0 -110
  109. package/src/health/thresholds.ts +0 -73
  110. package/src/hooks/notification.ts +0 -52
  111. package/src/hooks/post-tool-failure.ts +0 -58
  112. package/src/hooks/post-tool-use.ts +0 -62
  113. package/src/hooks/pre-compact.ts +0 -60
  114. package/src/hooks/pre-tool-use.ts +0 -72
  115. package/src/hooks/prompt-submit.ts +0 -46
  116. package/src/hooks/session-end.ts +0 -71
  117. package/src/hooks/session-start.ts +0 -48
  118. package/src/hooks/stop.ts +0 -39
  119. package/src/hooks/subagent-start.ts +0 -49
  120. package/src/hooks/subagent-stop.ts +0 -54
  121. package/src/hooks/task-completed.ts +0 -54
  122. package/src/index.ts +0 -342
  123. package/src/mcp/in-memory-kv.ts +0 -61
  124. package/src/mcp/server.ts +0 -1455
  125. package/src/mcp/standalone.ts +0 -177
  126. package/src/mcp/tools-registry.ts +0 -769
  127. package/src/mcp/transport.ts +0 -91
  128. package/src/prompts/compression.ts +0 -67
  129. package/src/prompts/consolidation.ts +0 -48
  130. package/src/prompts/graph-extraction.ts +0 -35
  131. package/src/prompts/summary.ts +0 -38
  132. package/src/prompts/xml.ts +0 -26
  133. package/src/providers/agent-sdk.ts +0 -34
  134. package/src/providers/anthropic.ts +0 -35
  135. package/src/providers/circuit-breaker.ts +0 -82
  136. package/src/providers/embedding/cohere.ts +0 -46
  137. package/src/providers/embedding/gemini.ts +0 -54
  138. package/src/providers/embedding/index.ts +0 -39
  139. package/src/providers/embedding/local.ts +0 -52
  140. package/src/providers/embedding/openai.ts +0 -45
  141. package/src/providers/embedding/openrouter.ts +0 -51
  142. package/src/providers/embedding/voyage.ts +0 -46
  143. package/src/providers/fallback-chain.ts +0 -31
  144. package/src/providers/index.ts +0 -84
  145. package/src/providers/openrouter.ts +0 -71
  146. package/src/providers/resilient.ts +0 -37
  147. package/src/state/hybrid-search.ts +0 -295
  148. package/src/state/index-persistence.ts +0 -63
  149. package/src/state/keyed-mutex.ts +0 -18
  150. package/src/state/kv.ts +0 -33
  151. package/src/state/schema.ts +0 -71
  152. package/src/state/search-index.ts +0 -245
  153. package/src/state/stemmer.ts +0 -104
  154. package/src/state/synonyms.ts +0 -63
  155. package/src/state/vector-index.ts +0 -130
  156. package/src/telemetry/setup.ts +0 -116
  157. package/src/triggers/api.ts +0 -1904
  158. package/src/triggers/events.ts +0 -71
  159. package/src/types.ts +0 -769
  160. package/src/version.ts +0 -1
  161. package/src/viewer/index.html +0 -2556
  162. package/src/viewer/server.ts +0 -207
  163. package/src/xenova.d.ts +0 -3
  164. package/test/actions.test.ts +0 -490
  165. package/test/audit.test.ts +0 -108
  166. package/test/auto-forget.test.ts +0 -188
  167. package/test/cascade.test.ts +0 -277
  168. package/test/checkpoints.test.ts +0 -493
  169. package/test/circuit-breaker.test.ts +0 -107
  170. package/test/claude-bridge.test.ts +0 -178
  171. package/test/confidence.test.ts +0 -247
  172. package/test/consistency.test.ts +0 -61
  173. package/test/consolidation-pipeline.test.ts +0 -251
  174. package/test/crystallize.test.ts +0 -521
  175. package/test/diagnostics.test.ts +0 -638
  176. package/test/embedding-provider.test.ts +0 -49
  177. package/test/enrich.test.ts +0 -209
  178. package/test/eval.test.ts +0 -300
  179. package/test/export-import.test.ts +0 -251
  180. package/test/facets.test.ts +0 -448
  181. package/test/fallback-chain.test.ts +0 -93
  182. package/test/frontier.test.ts +0 -485
  183. package/test/governance.test.ts +0 -147
  184. package/test/graph-retrieval.test.ts +0 -186
  185. package/test/graph.test.ts +0 -160
  186. package/test/helpers/mocks.ts +0 -40
  187. package/test/hybrid-search.test.ts +0 -145
  188. package/test/index-persistence.test.ts +0 -124
  189. package/test/integration.test.ts +0 -265
  190. package/test/leases.test.ts +0 -399
  191. package/test/mcp-prompts.test.ts +0 -218
  192. package/test/mcp-resources.test.ts +0 -286
  193. package/test/mcp-standalone.test.ts +0 -113
  194. package/test/mesh.test.ts +0 -700
  195. package/test/privacy.test.ts +0 -87
  196. package/test/profile.test.ts +0 -161
  197. package/test/query-expansion.test.ts +0 -154
  198. package/test/relations.test.ts +0 -198
  199. package/test/retention.test.ts +0 -245
  200. package/test/routines.test.ts +0 -497
  201. package/test/schema-fingerprint.test.ts +0 -81
  202. package/test/schema.test.ts +0 -42
  203. package/test/search-index.test.ts +0 -128
  204. package/test/sentinels.test.ts +0 -626
  205. package/test/signals.test.ts +0 -410
  206. package/test/sketches.test.ts +0 -549
  207. package/test/sliding-window.test.ts +0 -199
  208. package/test/smart-search.test.ts +0 -169
  209. package/test/snapshot.test.ts +0 -165
  210. package/test/team.test.ts +0 -156
  211. package/test/temporal-graph.test.ts +0 -378
  212. package/test/timeline.test.ts +0 -148
  213. package/test/vector-index.test.ts +0 -79
  214. package/test/verify.test.ts +0 -209
  215. package/test/xml.test.ts +0 -65
  216. package/tsconfig.json +0 -22
  217. package/tsdown.config.ts +0 -62
package/src/auth.ts DELETED
@@ -1,12 +0,0 @@
1
- import { timingSafeEqual, createHmac, randomBytes } from "node:crypto";
2
-
3
- const hmacKey = randomBytes(32);
4
-
5
- export function timingSafeCompare(a: string, b: string): boolean {
6
- const hmacA = createHmac("sha256", hmacKey).update(a).digest();
7
- const hmacB = createHmac("sha256", hmacKey).update(b).digest();
8
- return timingSafeEqual(hmacA, hmacB);
9
- }
10
-
11
- export const VIEWER_CSP =
12
- "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self' ws://localhost:* wss://localhost:*; img-src 'self'; font-src 'self'";
package/src/cli.ts DELETED
@@ -1,251 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- import { spawn, execFileSync, execSync } from "node:child_process";
4
- import { existsSync } from "node:fs";
5
- import { join, dirname } from "node:path";
6
- import { fileURLToPath } from "node:url";
7
- import * as p from "@clack/prompts";
8
-
9
- const __dirname = dirname(fileURLToPath(import.meta.url));
10
- const args = process.argv.slice(2);
11
-
12
- if (args.includes("--help") || args.includes("-h")) {
13
- console.log(`
14
- agentmemory — persistent memory for AI coding agents
15
-
16
- Usage: agentmemory [options]
17
-
18
- Options:
19
- --help, -h Show this help
20
- --tools all|core Tool visibility (default: core = 7 tools)
21
- --no-engine Skip auto-starting iii-engine
22
- --port <N> Override REST port (default: 3111)
23
-
24
- Environment:
25
- AGENTMEMORY_TOOLS=all Expose all 41 MCP tools
26
- AGENTMEMORY_SECRET=xxx Auth secret for REST/MCP
27
- CONSOLIDATION_ENABLED=true Enable auto-consolidation (off by default)
28
- OBSIDIAN_AUTO_EXPORT=true Auto-export on consolidation
29
-
30
- Quick start:
31
- npx @agentmemory/agentmemory # installs iii if missing, starts everything
32
- npx agentmemory-mcp # standalone MCP server (no engine needed)
33
- `);
34
- process.exit(0);
35
- }
36
-
37
- const toolsIdx = args.indexOf("--tools");
38
- if (toolsIdx !== -1 && args[toolsIdx + 1]) {
39
- process.env["AGENTMEMORY_TOOLS"] = args[toolsIdx + 1];
40
- }
41
-
42
- const portIdx = args.indexOf("--port");
43
- if (portIdx !== -1 && args[portIdx + 1]) {
44
- process.env["III_REST_PORT"] = args[portIdx + 1];
45
- }
46
-
47
- const skipEngine = args.includes("--no-engine");
48
-
49
- function getRestPort(): number {
50
- return parseInt(process.env["III_REST_PORT"] || "3111", 10) || 3111;
51
- }
52
-
53
- async function isEngineRunning(): Promise<boolean> {
54
- try {
55
- const res = await fetch(`http://localhost:${getRestPort()}/agentmemory/livez`, {
56
- signal: AbortSignal.timeout(2000),
57
- });
58
- return res.ok;
59
- } catch {
60
- return false;
61
- }
62
- }
63
-
64
- function findIiiConfig(): string {
65
- const candidates = [
66
- join(__dirname, "iii-config.yaml"),
67
- join(__dirname, "..", "iii-config.yaml"),
68
- join(process.cwd(), "iii-config.yaml"),
69
- ];
70
- for (const c of candidates) {
71
- if (existsSync(c)) return c;
72
- }
73
- return "";
74
- }
75
-
76
- function whichBinary(name: string): string | null {
77
- const cmd = process.platform === "win32" ? "where" : "which";
78
- try {
79
- return execFileSync(cmd, [name], { encoding: "utf-8" }).trim().split("\n")[0];
80
- } catch {
81
- return null;
82
- }
83
- }
84
-
85
- async function installIii(): Promise<boolean> {
86
- if (process.platform === "win32") {
87
- p.log.warn("Automatic iii-engine install is not supported on Windows.");
88
- p.log.info("Install manually: https://iii.dev/docs");
89
- return false;
90
- }
91
-
92
- const curlBin = whichBinary("curl");
93
- if (!curlBin) {
94
- p.log.warn("curl not found — cannot auto-install iii-engine.");
95
- return false;
96
- }
97
-
98
- const shouldInstall = await p.confirm({
99
- message: "iii-engine is not installed. Install it now?",
100
- initialValue: true,
101
- });
102
-
103
- if (p.isCancel(shouldInstall) || !shouldInstall) {
104
- return false;
105
- }
106
-
107
- const s = p.spinner();
108
- s.start("Installing iii-engine...");
109
-
110
- try {
111
- execSync("curl -fsSL https://install.iii.dev/iii/main/install.sh | sh", {
112
- stdio: ["pipe", "pipe", "pipe"],
113
- timeout: 120000,
114
- });
115
-
116
- const installed = whichBinary("iii");
117
- if (installed) {
118
- s.stop("iii-engine installed successfully");
119
- return true;
120
- }
121
-
122
- s.stop("Installation completed but iii not found in PATH");
123
- p.log.warn("You may need to restart your shell or add iii to your PATH.");
124
-
125
- const iiiPaths = [
126
- join(process.env["HOME"] || "", ".local", "bin", "iii"),
127
- "/usr/local/bin/iii",
128
- ];
129
- for (const iiiPath of iiiPaths) {
130
- if (existsSync(iiiPath)) {
131
- p.log.info(`Found iii at: ${iiiPath}`);
132
- process.env["PATH"] = `${dirname(iiiPath)}:${process.env["PATH"]}`;
133
- return true;
134
- }
135
- }
136
-
137
- return false;
138
- } catch (err) {
139
- s.stop("Failed to install iii-engine");
140
- p.log.error(err instanceof Error ? err.message : String(err));
141
- return false;
142
- }
143
- }
144
-
145
- async function startEngine(): Promise<boolean> {
146
- const configPath = findIiiConfig();
147
- let iiiBin = whichBinary("iii");
148
-
149
- if (!iiiBin) {
150
- const installed = await installIii();
151
- if (installed) {
152
- iiiBin = whichBinary("iii");
153
- }
154
- }
155
-
156
- if (iiiBin && configPath) {
157
- const s = p.spinner();
158
- s.start(`Starting iii-engine: ${iiiBin}`);
159
- const child = spawn(iiiBin, ["--config", configPath], {
160
- detached: true,
161
- stdio: "ignore",
162
- });
163
- child.unref();
164
- s.stop("iii-engine process started");
165
- return true;
166
- }
167
-
168
- const dockerBin = whichBinary("docker");
169
- const dockerCompose = join(__dirname, "..", "docker-compose.yml");
170
- const dcExists = existsSync(dockerCompose) || existsSync(join(process.cwd(), "docker-compose.yml"));
171
-
172
- if (dockerBin && dcExists) {
173
- const composeFile = existsSync(dockerCompose) ? dockerCompose : join(process.cwd(), "docker-compose.yml");
174
- const s = p.spinner();
175
- s.start("Starting iii-engine via Docker...");
176
- const child = spawn(dockerBin, ["compose", "-f", composeFile, "up", "-d"], {
177
- detached: true,
178
- stdio: "ignore",
179
- });
180
- child.unref();
181
- s.stop("Docker compose started");
182
- return true;
183
- }
184
-
185
- return false;
186
- }
187
-
188
- async function waitForEngine(timeoutMs: number): Promise<boolean> {
189
- const start = Date.now();
190
- while (Date.now() - start < timeoutMs) {
191
- if (await isEngineRunning()) return true;
192
- await new Promise((r) => setTimeout(r, 500));
193
- }
194
- return false;
195
- }
196
-
197
- async function main() {
198
- p.intro("agentmemory");
199
-
200
- if (skipEngine) {
201
- p.log.info("Skipping engine check (--no-engine)");
202
- await import("./index.js");
203
- return;
204
- }
205
-
206
- if (await isEngineRunning()) {
207
- p.log.success("iii-engine is running");
208
- await import("./index.js");
209
- return;
210
- }
211
-
212
- const started = await startEngine();
213
- if (!started) {
214
- p.log.error("Could not start iii-engine.");
215
- p.note(
216
- [
217
- "Install iii-engine (pick one):",
218
- " curl -fsSL https://install.iii.dev/iii/main/install.sh | sh",
219
- " cargo install iii-engine",
220
- "",
221
- "Or use Docker:",
222
- " docker pull iiidev/iii:latest",
223
- "",
224
- "Docs: https://iii.dev/docs",
225
- "",
226
- "Or skip with: agentmemory --no-engine",
227
- ].join("\n"),
228
- "Setup required",
229
- );
230
- process.exit(1);
231
- }
232
-
233
- const s = p.spinner();
234
- s.start("Waiting for iii-engine to be ready...");
235
-
236
- const ready = await waitForEngine(15000);
237
- if (!ready) {
238
- const port = getRestPort();
239
- s.stop("iii-engine did not become ready within 15s");
240
- p.log.error(`Check that ports ${port}, ${port + 1}, 49134 are available.`);
241
- process.exit(1);
242
- }
243
-
244
- s.stop("iii-engine is ready");
245
- await import("./index.js");
246
- }
247
-
248
- main().catch((err) => {
249
- p.log.error(err instanceof Error ? err.message : String(err));
250
- process.exit(1);
251
- });
package/src/config.ts DELETED
@@ -1,221 +0,0 @@
1
- import { existsSync, readFileSync } from "node:fs";
2
- import { join } from "node:path";
3
- import { homedir } from "node:os";
4
- import type {
5
- AgentMemoryConfig,
6
- ProviderConfig,
7
- EmbeddingConfig,
8
- FallbackConfig,
9
- ClaudeBridgeConfig,
10
- TeamConfig,
11
- } from "./types.js";
12
-
13
- function safeParseInt(value: string | undefined, fallback: number): number {
14
- if (!value) return fallback;
15
- const parsed = parseInt(value, 10);
16
- return Number.isNaN(parsed) ? fallback : parsed;
17
- }
18
-
19
- const DATA_DIR = join(homedir(), ".agentmemory");
20
- const ENV_FILE = join(DATA_DIR, ".env");
21
-
22
- function loadEnvFile(): Record<string, string> {
23
- if (!existsSync(ENV_FILE)) return {};
24
- const content = readFileSync(ENV_FILE, "utf-8");
25
- const vars: Record<string, string> = {};
26
- for (const line of content.split("\n")) {
27
- const trimmed = line.trim();
28
- if (!trimmed || trimmed.startsWith("#")) continue;
29
- const eqIdx = trimmed.indexOf("=");
30
- if (eqIdx === -1) continue;
31
- const key = trimmed.slice(0, eqIdx).trim();
32
- let val = trimmed.slice(eqIdx + 1).trim();
33
- if (
34
- (val.startsWith('"') && val.endsWith('"')) ||
35
- (val.startsWith("'") && val.endsWith("'"))
36
- ) {
37
- val = val.slice(1, -1);
38
- }
39
- vars[key] = val;
40
- }
41
- return vars;
42
- }
43
-
44
- function detectProvider(env: Record<string, string>): ProviderConfig {
45
- const maxTokens = parseInt(env["MAX_TOKENS"] || "4096", 10);
46
-
47
- if (env["ANTHROPIC_API_KEY"]) {
48
- return {
49
- provider: "anthropic",
50
- model: env["ANTHROPIC_MODEL"] || "claude-sonnet-4-20250514",
51
- maxTokens,
52
- };
53
- }
54
- if (env["GEMINI_API_KEY"]) {
55
- return {
56
- provider: "gemini",
57
- model: env["GEMINI_MODEL"] || "gemini-2.0-flash",
58
- maxTokens,
59
- };
60
- }
61
- if (env["OPENROUTER_API_KEY"]) {
62
- return {
63
- provider: "openrouter",
64
- model: env["OPENROUTER_MODEL"] || "anthropic/claude-sonnet-4-20250514",
65
- maxTokens,
66
- };
67
- }
68
- return {
69
- provider: "agent-sdk",
70
- model: "claude-sonnet-4-20250514",
71
- maxTokens: 4096,
72
- };
73
- }
74
-
75
- export function loadConfig(): AgentMemoryConfig {
76
- const env = getMergedEnv();
77
-
78
- const provider = detectProvider(env);
79
-
80
- return {
81
- engineUrl: env["III_ENGINE_URL"] || "ws://localhost:49134",
82
- restPort: parseInt(env["III_REST_PORT"] || "3111", 10) || 3111,
83
- streamsPort: parseInt(env["III_STREAMS_PORT"] || "3112", 10) || 3112,
84
- provider,
85
- tokenBudget: safeParseInt(env["TOKEN_BUDGET"], 2000),
86
- maxObservationsPerSession: safeParseInt(env["MAX_OBS_PER_SESSION"], 500),
87
- compressionModel: provider.model,
88
- dataDir: DATA_DIR,
89
- };
90
- }
91
-
92
- function getMergedEnv(
93
- overrides?: Record<string, string>,
94
- ): Record<string, string> {
95
- const fileEnv = loadEnvFile();
96
- return { ...fileEnv, ...process.env, ...overrides } as Record<string, string>;
97
- }
98
-
99
- export function getEnvVar(key: string): string | undefined {
100
- return getMergedEnv()[key];
101
- }
102
-
103
- export function loadEmbeddingConfig(): EmbeddingConfig {
104
- const env = getMergedEnv();
105
- let bm25Weight = parseFloat(env["BM25_WEIGHT"] || "0.4");
106
- let vectorWeight = parseFloat(env["VECTOR_WEIGHT"] || "0.6");
107
- bm25Weight =
108
- isNaN(bm25Weight) || bm25Weight < 0 ? 0.4 : Math.min(bm25Weight, 1);
109
- vectorWeight =
110
- isNaN(vectorWeight) || vectorWeight < 0 ? 0.6 : Math.min(vectorWeight, 1);
111
- return {
112
- provider: env["EMBEDDING_PROVIDER"] || undefined,
113
- bm25Weight,
114
- vectorWeight,
115
- };
116
- }
117
-
118
- export function detectEmbeddingProvider(
119
- env?: Record<string, string>,
120
- ): string | null {
121
- const source = env ?? getMergedEnv();
122
- const forced = source["EMBEDDING_PROVIDER"];
123
- if (forced) return forced;
124
-
125
- if (source["GEMINI_API_KEY"]) return "gemini";
126
- if (source["OPENAI_API_KEY"]) return "openai";
127
- if (source["VOYAGE_API_KEY"]) return "voyage";
128
- if (source["COHERE_API_KEY"]) return "cohere";
129
- if (source["OPENROUTER_API_KEY"]) return "openrouter";
130
- return null;
131
- }
132
-
133
- export function loadClaudeBridgeConfig(): ClaudeBridgeConfig {
134
- const env = getMergedEnv();
135
- const enabled = env["CLAUDE_MEMORY_BRIDGE"] === "true";
136
- const projectPath = env["CLAUDE_PROJECT_PATH"] || "";
137
- const lineBudget = safeParseInt(env["CLAUDE_MEMORY_LINE_BUDGET"], 200);
138
- let memoryFilePath = "";
139
- if (enabled && projectPath) {
140
- const safePath = projectPath.replace(/[/\\]/g, "-").replace(/^-/, "");
141
- memoryFilePath = join(
142
- homedir(),
143
- ".claude",
144
- "projects",
145
- safePath,
146
- "memory",
147
- "MEMORY.md",
148
- );
149
- }
150
- return { enabled, projectPath, memoryFilePath, lineBudget };
151
- }
152
-
153
- export function loadTeamConfig(): TeamConfig | null {
154
- const env = getMergedEnv();
155
- const teamId = env["TEAM_ID"];
156
- const userId = env["USER_ID"];
157
- if (!teamId || !userId) return null;
158
- const mode = env["TEAM_MODE"] === "shared" ? "shared" : "private";
159
- return { teamId, userId, mode };
160
- }
161
-
162
- export function loadSnapshotConfig(): {
163
- enabled: boolean;
164
- interval: number;
165
- dir: string;
166
- } {
167
- const env = getMergedEnv();
168
- return {
169
- enabled: env["SNAPSHOT_ENABLED"] === "true",
170
- interval: safeParseInt(env["SNAPSHOT_INTERVAL"], 3600),
171
- dir: env["SNAPSHOT_DIR"] || join(homedir(), ".agentmemory", "snapshots"),
172
- };
173
- }
174
-
175
- export function isGraphExtractionEnabled(): boolean {
176
- return getMergedEnv()["GRAPH_EXTRACTION_ENABLED"] === "true";
177
- }
178
-
179
- export function getGraphBatchSize(): number {
180
- return safeParseInt(getMergedEnv()["GRAPH_EXTRACTION_BATCH_SIZE"], 10);
181
- }
182
-
183
- export function isConsolidationEnabled(): boolean {
184
- return getMergedEnv()["CONSOLIDATION_ENABLED"] === "true";
185
- }
186
-
187
- export function getConsolidationDecayDays(): number {
188
- return safeParseInt(getMergedEnv()["CONSOLIDATION_DECAY_DAYS"], 30);
189
- }
190
-
191
- export function isStandaloneMcp(): boolean {
192
- return getMergedEnv()["STANDALONE_MCP"] === "true";
193
- }
194
-
195
- export function getStandalonePersistPath(): string {
196
- const env = getMergedEnv();
197
- return (
198
- env["STANDALONE_PERSIST_PATH"] ||
199
- join(homedir(), ".agentmemory", "standalone.json")
200
- );
201
- }
202
-
203
- const VALID_PROVIDERS = new Set([
204
- "anthropic",
205
- "gemini",
206
- "openrouter",
207
- "agent-sdk",
208
- ]);
209
-
210
- export function loadFallbackConfig(): FallbackConfig {
211
- const env = getMergedEnv();
212
- const raw = env["FALLBACK_PROVIDERS"] || "";
213
- const providers = raw
214
- .split(",")
215
- .map((p) => p.trim())
216
- .filter(
217
- (p): p is FallbackConfig["providers"][number] =>
218
- Boolean(p) && VALID_PROVIDERS.has(p),
219
- );
220
- return { providers };
221
- }
@@ -1,65 +0,0 @@
1
- import type { FunctionMetrics } from "../types.js";
2
- import type { StateKV } from "../state/kv.js";
3
- import { KV } from "../state/schema.js";
4
-
5
- export class MetricsStore {
6
- private cache = new Map<string, FunctionMetrics>();
7
- private qualityCallCounts = new Map<string, number>();
8
-
9
- constructor(private kv: StateKV) {}
10
-
11
- async record(
12
- functionId: string,
13
- latencyMs: number,
14
- success: boolean,
15
- qualityScore?: number,
16
- ): Promise<void> {
17
- let m = this.cache.get(functionId);
18
- if (!m) {
19
- m = (await this.kv.get<FunctionMetrics>(KV.metrics, functionId)) ?? {
20
- functionId,
21
- totalCalls: 0,
22
- successCount: 0,
23
- failureCount: 0,
24
- avgLatencyMs: 0,
25
- avgQualityScore: 0,
26
- };
27
- }
28
-
29
- const prev = m.totalCalls;
30
- m.totalCalls += 1;
31
- m.avgLatencyMs = (m.avgLatencyMs * prev + latencyMs) / m.totalCalls;
32
- if (success) {
33
- m.successCount += 1;
34
- } else {
35
- m.failureCount += 1;
36
- }
37
- if (qualityScore !== undefined) {
38
- const prevQualityCalls = this.qualityCallCounts.get(functionId) || 0;
39
- m.avgQualityScore =
40
- (m.avgQualityScore * prevQualityCalls + qualityScore) /
41
- (prevQualityCalls + 1);
42
- this.qualityCallCounts.set(functionId, prevQualityCalls + 1);
43
- }
44
-
45
- this.cache.set(functionId, m);
46
- await this.kv.set(KV.metrics, functionId, m).catch(() => {});
47
- }
48
-
49
- async get(functionId: string): Promise<FunctionMetrics | null> {
50
- return (
51
- this.cache.get(functionId) ??
52
- (await this.kv.get<FunctionMetrics>(KV.metrics, functionId))
53
- );
54
- }
55
-
56
- async getAll(): Promise<FunctionMetrics[]> {
57
- const kvMetrics = await this.kv
58
- .list<FunctionMetrics>(KV.metrics)
59
- .catch(() => []);
60
- const merged = new Map<string, FunctionMetrics>();
61
- for (const m of kvMetrics) merged.set(m.functionId, m);
62
- for (const [id, m] of this.cache) merged.set(id, m);
63
- return Array.from(merged.values());
64
- }
65
- }
@@ -1,51 +0,0 @@
1
- export function scoreCompression(obs: {
2
- type?: string;
3
- title?: string;
4
- facts?: string[];
5
- narrative?: string;
6
- concepts?: string[];
7
- importance?: number;
8
- }): number {
9
- let score = 0;
10
- if (obs.facts && obs.facts.length > 0) score += 25;
11
- if (obs.facts && obs.facts.length >= 3) score += 10;
12
- if (obs.narrative && obs.narrative.length >= 20) score += 20;
13
- if (obs.narrative && obs.narrative.length >= 50) score += 5;
14
- if (obs.title && obs.title.length >= 5 && obs.title.length <= 120) score += 15;
15
- if (obs.concepts && obs.concepts.length > 0) score += 15;
16
- if (obs.importance && obs.importance >= 1 && obs.importance <= 10) score += 10;
17
- return Math.min(100, score);
18
- }
19
-
20
- export function scoreSummary(summary: {
21
- title?: string;
22
- narrative?: string;
23
- keyDecisions?: string[];
24
- filesModified?: string[];
25
- concepts?: string[];
26
- }): number {
27
- let score = 0;
28
- if (summary.title && summary.title.length >= 5) score += 20;
29
- if (summary.narrative && summary.narrative.length >= 20) score += 25;
30
- if (summary.narrative && summary.narrative.length >= 100) score += 5;
31
- if (summary.keyDecisions && summary.keyDecisions.length > 0) score += 20;
32
- if (summary.filesModified && summary.filesModified.length > 0) score += 15;
33
- if (summary.concepts && summary.concepts.length > 0) score += 15;
34
- return Math.min(100, score);
35
- }
36
-
37
- export function scoreContextRelevance(
38
- context: string,
39
- project: string,
40
- ): number {
41
- let score = 0;
42
- if (context.length > 0) score += 20;
43
- if (project && context.toLowerCase().includes(project.toLowerCase())) score += 20;
44
- if (context.includes("<")) score += 15;
45
- const sectionCount = (context.match(/<\w+>/g) || []).length;
46
- if (sectionCount >= 2) score += 15;
47
- if (sectionCount >= 4) score += 10;
48
- if (context.length >= 100) score += 10;
49
- if (context.length >= 500) score += 10;
50
- return Math.min(100, score);
51
- }