@agentmemory/agentmemory 0.7.0
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.
- package/.claude-plugin/marketplace.json +14 -0
- package/.github/workflows/ci.yml +22 -0
- package/.github/workflows/publish.yml +28 -0
- package/AGENTS.md +113 -0
- package/LICENSE +190 -0
- package/README.md +828 -0
- package/assets/banner.png +0 -0
- package/assets/demo.gif +0 -0
- package/assets/demo.mp4 +0 -0
- package/benchmark/QUALITY.md +73 -0
- package/benchmark/REAL-EMBEDDINGS.md +67 -0
- package/benchmark/SCALE.md +110 -0
- package/benchmark/dataset.ts +293 -0
- package/benchmark/quality-eval.ts +643 -0
- package/benchmark/real-embeddings-eval.ts +405 -0
- package/benchmark/scale-eval.ts +398 -0
- package/dist/cli.d.mts +1 -0
- package/dist/cli.mjs +137 -0
- package/dist/cli.mjs.map +1 -0
- package/dist/docker-compose.yml +14 -0
- package/dist/hooks/notification.d.mts +1 -0
- package/dist/hooks/notification.mjs +45 -0
- package/dist/hooks/notification.mjs.map +1 -0
- package/dist/hooks/post-tool-failure.d.mts +1 -0
- package/dist/hooks/post-tool-failure.mjs +45 -0
- package/dist/hooks/post-tool-failure.mjs.map +1 -0
- package/dist/hooks/post-tool-use.d.mts +1 -0
- package/dist/hooks/post-tool-use.mjs +53 -0
- package/dist/hooks/post-tool-use.mjs.map +1 -0
- package/dist/hooks/pre-compact.d.mts +1 -0
- package/dist/hooks/pre-compact.mjs +50 -0
- package/dist/hooks/pre-compact.mjs.map +1 -0
- package/dist/hooks/pre-tool-use.d.mts +1 -0
- package/dist/hooks/pre-tool-use.mjs +69 -0
- package/dist/hooks/pre-tool-use.mjs.map +1 -0
- package/dist/hooks/prompt-submit.d.mts +1 -0
- package/dist/hooks/prompt-submit.mjs +40 -0
- package/dist/hooks/prompt-submit.mjs.map +1 -0
- package/dist/hooks/session-end.d.mts +1 -0
- package/dist/hooks/session-end.mjs +61 -0
- package/dist/hooks/session-end.mjs.map +1 -0
- package/dist/hooks/session-start.d.mts +1 -0
- package/dist/hooks/session-start.mjs +42 -0
- package/dist/hooks/session-start.mjs.map +1 -0
- package/dist/hooks/stop.d.mts +1 -0
- package/dist/hooks/stop.mjs +33 -0
- package/dist/hooks/stop.mjs.map +1 -0
- package/dist/hooks/subagent-start.d.mts +1 -0
- package/dist/hooks/subagent-start.mjs +43 -0
- package/dist/hooks/subagent-start.mjs.map +1 -0
- package/dist/hooks/subagent-stop.d.mts +1 -0
- package/dist/hooks/subagent-stop.mjs +45 -0
- package/dist/hooks/subagent-stop.mjs.map +1 -0
- package/dist/hooks/task-completed.d.mts +1 -0
- package/dist/hooks/task-completed.mjs +46 -0
- package/dist/hooks/task-completed.mjs.map +1 -0
- package/dist/iii-config.yaml +51 -0
- package/dist/index.d.mts +2 -0
- package/dist/index.mjs +13776 -0
- package/dist/index.mjs.map +1 -0
- package/dist/src-QxitMPfJ.mjs +13775 -0
- package/dist/src-QxitMPfJ.mjs.map +1 -0
- package/dist/standalone.d.mts +1 -0
- package/dist/standalone.mjs +1155 -0
- package/dist/standalone.mjs.map +1 -0
- package/dist/transformers-BX_tgxdO.mjs +38684 -0
- package/dist/transformers-BX_tgxdO.mjs.map +1 -0
- package/dist/transformers-KMm1i9no.mjs +38683 -0
- package/dist/transformers-KMm1i9no.mjs.map +1 -0
- package/docker-compose.yml +14 -0
- package/iii-config.yaml +51 -0
- package/package.json +59 -0
- package/plugin/.claude-plugin/plugin.json +10 -0
- package/plugin/hooks/hooks.json +77 -0
- package/plugin/scripts/diagnostics.mjs +551 -0
- package/plugin/scripts/notification.mjs +45 -0
- package/plugin/scripts/post-tool-failure.mjs +45 -0
- package/plugin/scripts/post-tool-use.mjs +53 -0
- package/plugin/scripts/pre-compact.mjs +50 -0
- package/plugin/scripts/pre-tool-use.mjs +69 -0
- package/plugin/scripts/prompt-submit.mjs +40 -0
- package/plugin/scripts/session-end.mjs +61 -0
- package/plugin/scripts/session-start.mjs +42 -0
- package/plugin/scripts/stop.mjs +33 -0
- package/plugin/scripts/subagent-start.mjs +43 -0
- package/plugin/scripts/subagent-stop.mjs +45 -0
- package/plugin/scripts/task-completed.mjs +46 -0
- package/plugin/skills/forget/SKILL.md +32 -0
- package/plugin/skills/recall/SKILL.md +18 -0
- package/plugin/skills/remember/SKILL.md +25 -0
- package/plugin/skills/session-history/SKILL.md +17 -0
- package/src/auth.ts +12 -0
- package/src/cli.ts +159 -0
- package/src/config.ts +221 -0
- package/src/eval/metrics-store.ts +65 -0
- package/src/eval/quality.ts +51 -0
- package/src/eval/schemas.ts +124 -0
- package/src/eval/self-correct.ts +28 -0
- package/src/eval/validator.ts +31 -0
- package/src/functions/actions.ts +288 -0
- package/src/functions/audit.ts +61 -0
- package/src/functions/auto-forget.ts +169 -0
- package/src/functions/branch-aware.ts +169 -0
- package/src/functions/cascade.ts +80 -0
- package/src/functions/checkpoints.ts +209 -0
- package/src/functions/claude-bridge.ts +161 -0
- package/src/functions/compress.ts +194 -0
- package/src/functions/consolidate.ts +212 -0
- package/src/functions/consolidation-pipeline.ts +258 -0
- package/src/functions/context.ts +169 -0
- package/src/functions/crystallize.ts +293 -0
- package/src/functions/dedup.ts +57 -0
- package/src/functions/diagnostics.ts +785 -0
- package/src/functions/enrich.ts +132 -0
- package/src/functions/evict.ts +163 -0
- package/src/functions/export-import.ts +508 -0
- package/src/functions/facets.ts +248 -0
- package/src/functions/file-index.ts +106 -0
- package/src/functions/flow-compress.ts +214 -0
- package/src/functions/frontier.ts +196 -0
- package/src/functions/governance.ts +131 -0
- package/src/functions/graph-retrieval.ts +277 -0
- package/src/functions/graph.ts +275 -0
- package/src/functions/leases.ts +216 -0
- package/src/functions/lessons.ts +253 -0
- package/src/functions/mesh.ts +434 -0
- package/src/functions/migrate.ts +165 -0
- package/src/functions/observe.ts +144 -0
- package/src/functions/obsidian-export.ts +310 -0
- package/src/functions/patterns.ts +138 -0
- package/src/functions/privacy.ts +39 -0
- package/src/functions/profile.ts +155 -0
- package/src/functions/query-expansion.ts +186 -0
- package/src/functions/relations.ts +237 -0
- package/src/functions/remember.ts +162 -0
- package/src/functions/retention.ts +235 -0
- package/src/functions/routines.ts +289 -0
- package/src/functions/search.ts +80 -0
- package/src/functions/sentinels.ts +417 -0
- package/src/functions/signals.ts +186 -0
- package/src/functions/sketches.ts +274 -0
- package/src/functions/sliding-window.ts +257 -0
- package/src/functions/smart-search.ts +115 -0
- package/src/functions/snapshot.ts +219 -0
- package/src/functions/summarize.ts +155 -0
- package/src/functions/team.ts +147 -0
- package/src/functions/temporal-graph.ts +476 -0
- package/src/functions/timeline.ts +138 -0
- package/src/functions/verify.ts +117 -0
- package/src/health/monitor.ts +110 -0
- package/src/health/thresholds.ts +73 -0
- package/src/hooks/notification.ts +52 -0
- package/src/hooks/post-tool-failure.ts +58 -0
- package/src/hooks/post-tool-use.ts +62 -0
- package/src/hooks/pre-compact.ts +60 -0
- package/src/hooks/pre-tool-use.ts +72 -0
- package/src/hooks/prompt-submit.ts +46 -0
- package/src/hooks/session-end.ts +71 -0
- package/src/hooks/session-start.ts +48 -0
- package/src/hooks/stop.ts +39 -0
- package/src/hooks/subagent-start.ts +49 -0
- package/src/hooks/subagent-stop.ts +54 -0
- package/src/hooks/task-completed.ts +54 -0
- package/src/index.ts +342 -0
- package/src/mcp/in-memory-kv.ts +61 -0
- package/src/mcp/server.ts +1455 -0
- package/src/mcp/standalone.ts +177 -0
- package/src/mcp/tools-registry.ts +769 -0
- package/src/mcp/transport.ts +91 -0
- package/src/prompts/compression.ts +67 -0
- package/src/prompts/consolidation.ts +48 -0
- package/src/prompts/graph-extraction.ts +35 -0
- package/src/prompts/summary.ts +38 -0
- package/src/prompts/xml.ts +26 -0
- package/src/providers/agent-sdk.ts +34 -0
- package/src/providers/anthropic.ts +35 -0
- package/src/providers/circuit-breaker.ts +82 -0
- package/src/providers/embedding/cohere.ts +46 -0
- package/src/providers/embedding/gemini.ts +54 -0
- package/src/providers/embedding/index.ts +39 -0
- package/src/providers/embedding/local.ts +52 -0
- package/src/providers/embedding/openai.ts +45 -0
- package/src/providers/embedding/openrouter.ts +51 -0
- package/src/providers/embedding/voyage.ts +46 -0
- package/src/providers/fallback-chain.ts +31 -0
- package/src/providers/index.ts +84 -0
- package/src/providers/openrouter.ts +71 -0
- package/src/providers/resilient.ts +37 -0
- package/src/state/hybrid-search.ts +295 -0
- package/src/state/index-persistence.ts +63 -0
- package/src/state/keyed-mutex.ts +18 -0
- package/src/state/kv.ts +33 -0
- package/src/state/schema.ts +71 -0
- package/src/state/search-index.ts +245 -0
- package/src/state/stemmer.ts +104 -0
- package/src/state/synonyms.ts +63 -0
- package/src/state/vector-index.ts +130 -0
- package/src/telemetry/setup.ts +116 -0
- package/src/triggers/api.ts +1904 -0
- package/src/triggers/events.ts +71 -0
- package/src/types.ts +769 -0
- package/src/version.ts +1 -0
- package/src/viewer/index.html +2497 -0
- package/src/viewer/server.ts +207 -0
- package/src/xenova.d.ts +3 -0
- package/test/actions.test.ts +490 -0
- package/test/audit.test.ts +108 -0
- package/test/auto-forget.test.ts +188 -0
- package/test/cascade.test.ts +277 -0
- package/test/checkpoints.test.ts +493 -0
- package/test/circuit-breaker.test.ts +107 -0
- package/test/claude-bridge.test.ts +178 -0
- package/test/confidence.test.ts +247 -0
- package/test/consistency.test.ts +61 -0
- package/test/consolidation-pipeline.test.ts +251 -0
- package/test/crystallize.test.ts +521 -0
- package/test/diagnostics.test.ts +638 -0
- package/test/embedding-provider.test.ts +49 -0
- package/test/enrich.test.ts +209 -0
- package/test/eval.test.ts +300 -0
- package/test/export-import.test.ts +251 -0
- package/test/facets.test.ts +448 -0
- package/test/fallback-chain.test.ts +93 -0
- package/test/frontier.test.ts +485 -0
- package/test/governance.test.ts +147 -0
- package/test/graph-retrieval.test.ts +186 -0
- package/test/graph.test.ts +160 -0
- package/test/helpers/mocks.ts +40 -0
- package/test/hybrid-search.test.ts +145 -0
- package/test/index-persistence.test.ts +124 -0
- package/test/integration.test.ts +265 -0
- package/test/leases.test.ts +399 -0
- package/test/mcp-prompts.test.ts +218 -0
- package/test/mcp-resources.test.ts +286 -0
- package/test/mcp-standalone.test.ts +113 -0
- package/test/mesh.test.ts +700 -0
- package/test/privacy.test.ts +87 -0
- package/test/profile.test.ts +161 -0
- package/test/query-expansion.test.ts +154 -0
- package/test/relations.test.ts +198 -0
- package/test/retention.test.ts +245 -0
- package/test/routines.test.ts +497 -0
- package/test/schema-fingerprint.test.ts +81 -0
- package/test/schema.test.ts +42 -0
- package/test/search-index.test.ts +128 -0
- package/test/sentinels.test.ts +626 -0
- package/test/signals.test.ts +410 -0
- package/test/sketches.test.ts +549 -0
- package/test/sliding-window.test.ts +199 -0
- package/test/smart-search.test.ts +169 -0
- package/test/snapshot.test.ts +165 -0
- package/test/team.test.ts +156 -0
- package/test/temporal-graph.test.ts +378 -0
- package/test/timeline.test.ts +148 -0
- package/test/vector-index.test.ts +79 -0
- package/test/verify.test.ts +209 -0
- package/test/xml.test.ts +65 -0
- package/tsconfig.json +22 -0
- package/tsdown.config.ts +62 -0
package/src/cli.ts
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import { spawn, execFileSync } from "node:child_process";
|
|
4
|
+
import { existsSync } from "node:fs";
|
|
5
|
+
import { join, dirname } from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
|
|
8
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
9
|
+
|
|
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 # auto-starts iii-engine, runs worker
|
|
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 startEngine(): Promise<boolean> {
|
|
86
|
+
const configPath = findIiiConfig();
|
|
87
|
+
|
|
88
|
+
const iiiBin = whichBinary("iii");
|
|
89
|
+
if (iiiBin && configPath) {
|
|
90
|
+
console.log(`[agentmemory] Starting iii-engine: ${iiiBin} --config ${configPath}`);
|
|
91
|
+
const child = spawn(iiiBin, ["--config", configPath], {
|
|
92
|
+
detached: true,
|
|
93
|
+
stdio: "ignore",
|
|
94
|
+
});
|
|
95
|
+
child.unref();
|
|
96
|
+
return true;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const dockerCompose = join(__dirname, "..", "docker-compose.yml");
|
|
100
|
+
const dcExists = existsSync(dockerCompose) || existsSync(join(process.cwd(), "docker-compose.yml"));
|
|
101
|
+
const dockerBin = whichBinary("docker");
|
|
102
|
+
|
|
103
|
+
if (dockerBin && dcExists) {
|
|
104
|
+
const composeFile = existsSync(dockerCompose) ? dockerCompose : join(process.cwd(), "docker-compose.yml");
|
|
105
|
+
console.log(`[agentmemory] Starting iii-engine via Docker...`);
|
|
106
|
+
const child = spawn(dockerBin, ["compose", "-f", composeFile, "up", "-d"], {
|
|
107
|
+
detached: true,
|
|
108
|
+
stdio: "ignore",
|
|
109
|
+
});
|
|
110
|
+
child.unref();
|
|
111
|
+
return true;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
return false;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async function waitForEngine(timeoutMs: number): Promise<boolean> {
|
|
118
|
+
const start = Date.now();
|
|
119
|
+
while (Date.now() - start < timeoutMs) {
|
|
120
|
+
if (await isEngineRunning()) return true;
|
|
121
|
+
await new Promise((r) => setTimeout(r, 500));
|
|
122
|
+
}
|
|
123
|
+
return false;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function main() {
|
|
127
|
+
if (!skipEngine && !(await isEngineRunning())) {
|
|
128
|
+
const started = await startEngine();
|
|
129
|
+
if (!started) {
|
|
130
|
+
console.error(`
|
|
131
|
+
[agentmemory] iii-engine is not running and could not be auto-started.
|
|
132
|
+
|
|
133
|
+
Install one of:
|
|
134
|
+
1. iii CLI: npm install -g iii-engine
|
|
135
|
+
2. Docker: docker compose up -d (with docker-compose.yml)
|
|
136
|
+
|
|
137
|
+
Or run with --no-engine to connect to a remote engine.
|
|
138
|
+
`);
|
|
139
|
+
process.exit(1);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
console.log(`[agentmemory] Waiting for iii-engine to start...`);
|
|
143
|
+
const ready = await waitForEngine(15000);
|
|
144
|
+
if (!ready) {
|
|
145
|
+
const port = getRestPort();
|
|
146
|
+
console.error(`[agentmemory] iii-engine did not become ready within 15s.`);
|
|
147
|
+
console.error(`[agentmemory] Check that ports ${port}, ${port + 1}, 49134 are available.`);
|
|
148
|
+
process.exit(1);
|
|
149
|
+
}
|
|
150
|
+
console.log(`[agentmemory] iii-engine is ready.`);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
await import("./index.js");
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
main().catch((err) => {
|
|
157
|
+
console.error(`[agentmemory] Fatal:`, err);
|
|
158
|
+
process.exit(1);
|
|
159
|
+
});
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
|
|
3
|
+
const HookTypeEnum = z.enum([
|
|
4
|
+
"session_start",
|
|
5
|
+
"prompt_submit",
|
|
6
|
+
"pre_tool_use",
|
|
7
|
+
"post_tool_use",
|
|
8
|
+
"post_tool_failure",
|
|
9
|
+
"pre_compact",
|
|
10
|
+
"subagent_start",
|
|
11
|
+
"subagent_stop",
|
|
12
|
+
"notification",
|
|
13
|
+
"task_completed",
|
|
14
|
+
"stop",
|
|
15
|
+
"session_end",
|
|
16
|
+
]);
|
|
17
|
+
|
|
18
|
+
const ObservationTypeEnum = z.enum([
|
|
19
|
+
"file_read",
|
|
20
|
+
"file_write",
|
|
21
|
+
"file_edit",
|
|
22
|
+
"command_run",
|
|
23
|
+
"search",
|
|
24
|
+
"web_fetch",
|
|
25
|
+
"conversation",
|
|
26
|
+
"error",
|
|
27
|
+
"decision",
|
|
28
|
+
"discovery",
|
|
29
|
+
"subagent",
|
|
30
|
+
"notification",
|
|
31
|
+
"task",
|
|
32
|
+
"other",
|
|
33
|
+
]);
|
|
34
|
+
|
|
35
|
+
export const ObserveInputSchema = z.object({
|
|
36
|
+
hookType: HookTypeEnum,
|
|
37
|
+
sessionId: z.string().min(1),
|
|
38
|
+
project: z.string().min(1),
|
|
39
|
+
cwd: z.string().min(1),
|
|
40
|
+
timestamp: z.string().min(1),
|
|
41
|
+
data: z.unknown(),
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
export const CompressOutputSchema = z.object({
|
|
45
|
+
type: ObservationTypeEnum,
|
|
46
|
+
title: z.string().min(1).max(120),
|
|
47
|
+
subtitle: z.string().optional(),
|
|
48
|
+
facts: z.array(z.string()).min(1),
|
|
49
|
+
narrative: z.string().min(10),
|
|
50
|
+
concepts: z.array(z.string()),
|
|
51
|
+
files: z.array(z.string()),
|
|
52
|
+
importance: z.number().int().min(1).max(10),
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
export const SummaryOutputSchema = z.object({
|
|
56
|
+
title: z.string().min(1),
|
|
57
|
+
narrative: z.string().min(20),
|
|
58
|
+
keyDecisions: z.array(z.string()),
|
|
59
|
+
filesModified: z.array(z.string()),
|
|
60
|
+
concepts: z.array(z.string()),
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
export const SearchInputSchema = z.object({
|
|
64
|
+
query: z.string().min(1),
|
|
65
|
+
limit: z.number().int().positive().optional(),
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
export const ContextInputSchema = z.object({
|
|
69
|
+
sessionId: z.string().min(1),
|
|
70
|
+
project: z.string().min(1),
|
|
71
|
+
budget: z.number().positive().optional(),
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
export const RememberInputSchema = z.object({
|
|
75
|
+
content: z.string().min(1),
|
|
76
|
+
type: z
|
|
77
|
+
.enum(["pattern", "preference", "architecture", "bug", "workflow", "fact"])
|
|
78
|
+
.optional(),
|
|
79
|
+
concepts: z.array(z.string()).optional(),
|
|
80
|
+
files: z.array(z.string()).optional(),
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
export const SmartSearchInputSchema = z.object({
|
|
84
|
+
query: z.string().optional(),
|
|
85
|
+
expandIds: z.array(z.string()).optional(),
|
|
86
|
+
limit: z.number().int().positive().optional(),
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
export const TimelineInputSchema = z.object({
|
|
90
|
+
anchor: z.string().min(1),
|
|
91
|
+
project: z.string().optional(),
|
|
92
|
+
before: z.number().int().nonnegative().optional(),
|
|
93
|
+
after: z.number().int().nonnegative().optional(),
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
export const ProfileInputSchema = z.object({
|
|
97
|
+
project: z.string().min(1),
|
|
98
|
+
refresh: z.boolean().optional(),
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
export const RelateInputSchema = z.object({
|
|
102
|
+
sourceId: z.string().min(1),
|
|
103
|
+
targetId: z.string().min(1),
|
|
104
|
+
type: z.enum(["supersedes", "extends", "derives", "contradicts", "related"]),
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
export const EvolveInputSchema = z.object({
|
|
108
|
+
memoryId: z.string().min(1),
|
|
109
|
+
newContent: z.string().min(1),
|
|
110
|
+
newTitle: z.string().optional(),
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
export const ExportImportInputSchema = z.object({
|
|
114
|
+
exportData: z.object({
|
|
115
|
+
version: z.union([z.literal("0.3.0"), z.literal("0.4.0")]),
|
|
116
|
+
exportedAt: z.string(),
|
|
117
|
+
sessions: z.array(z.unknown()),
|
|
118
|
+
observations: z.record(z.string(), z.array(z.unknown())),
|
|
119
|
+
memories: z.array(z.unknown()),
|
|
120
|
+
summaries: z.array(z.unknown()),
|
|
121
|
+
profiles: z.array(z.unknown()).optional(),
|
|
122
|
+
}),
|
|
123
|
+
strategy: z.enum(["merge", "replace", "skip"]).optional(),
|
|
124
|
+
});
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { MemoryProvider } from "../types.js";
|
|
2
|
+
|
|
3
|
+
const STRICTER_SUFFIX = `
|
|
4
|
+
|
|
5
|
+
IMPORTANT: Your previous response was invalid. Please ensure your output strictly follows the required XML format. Every required field must be present with valid values.`;
|
|
6
|
+
|
|
7
|
+
export async function compressWithRetry(
|
|
8
|
+
provider: MemoryProvider,
|
|
9
|
+
systemPrompt: string,
|
|
10
|
+
userPrompt: string,
|
|
11
|
+
validator: (response: string) => { valid: boolean; errors?: string[] },
|
|
12
|
+
maxRetries = 1,
|
|
13
|
+
): Promise<{ response: string; retried: boolean }> {
|
|
14
|
+
const first = await provider.compress(systemPrompt, userPrompt);
|
|
15
|
+
const result = validator(first);
|
|
16
|
+
if (result.valid) return { response: first, retried: false };
|
|
17
|
+
|
|
18
|
+
for (let i = 0; i < maxRetries; i++) {
|
|
19
|
+
const retry = await provider.compress(
|
|
20
|
+
systemPrompt + STRICTER_SUFFIX,
|
|
21
|
+
userPrompt,
|
|
22
|
+
);
|
|
23
|
+
const retryResult = validator(retry);
|
|
24
|
+
if (retryResult.valid) return { response: retry, retried: true };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
return { response: first, retried: true };
|
|
28
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { z } from "zod";
|
|
2
|
+
import type { EvalResult } from "../types.js";
|
|
3
|
+
|
|
4
|
+
export function validateInput<T>(
|
|
5
|
+
schema: z.ZodType<T>,
|
|
6
|
+
data: unknown,
|
|
7
|
+
functionId: string,
|
|
8
|
+
): { valid: true; data: T } | { valid: false; result: EvalResult } {
|
|
9
|
+
const parsed = schema.safeParse(data);
|
|
10
|
+
if (parsed.success) {
|
|
11
|
+
return { valid: true, data: parsed.data };
|
|
12
|
+
}
|
|
13
|
+
return {
|
|
14
|
+
valid: false,
|
|
15
|
+
result: {
|
|
16
|
+
valid: false,
|
|
17
|
+
errors: parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`),
|
|
18
|
+
qualityScore: 0,
|
|
19
|
+
latencyMs: 0,
|
|
20
|
+
functionId,
|
|
21
|
+
},
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function validateOutput<T>(
|
|
26
|
+
schema: z.ZodType<T>,
|
|
27
|
+
data: unknown,
|
|
28
|
+
functionId: string,
|
|
29
|
+
): { valid: true; data: T } | { valid: false; result: EvalResult } {
|
|
30
|
+
return validateInput(schema, data, functionId);
|
|
31
|
+
}
|