@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
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { createInterface } from "node:readline";
|
|
2
|
+
|
|
3
|
+
export interface JsonRpcRequest {
|
|
4
|
+
jsonrpc: "2.0";
|
|
5
|
+
id: string | number;
|
|
6
|
+
method: string;
|
|
7
|
+
params?: Record<string, unknown>;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export interface JsonRpcResponse {
|
|
11
|
+
jsonrpc: "2.0";
|
|
12
|
+
id: string | number;
|
|
13
|
+
result?: unknown;
|
|
14
|
+
error?: { code: number; message: string; data?: unknown };
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export type RequestHandler = (
|
|
18
|
+
method: string,
|
|
19
|
+
params: Record<string, unknown>,
|
|
20
|
+
) => Promise<unknown>;
|
|
21
|
+
|
|
22
|
+
export function createStdioTransport(handler: RequestHandler): {
|
|
23
|
+
start: () => void;
|
|
24
|
+
stop: () => void;
|
|
25
|
+
} {
|
|
26
|
+
let rl: ReturnType<typeof createInterface> | null = null;
|
|
27
|
+
|
|
28
|
+
const onLine = async (line: string) => {
|
|
29
|
+
const trimmed = line.trim();
|
|
30
|
+
if (!trimmed) return;
|
|
31
|
+
|
|
32
|
+
let parsed: unknown;
|
|
33
|
+
try {
|
|
34
|
+
parsed = JSON.parse(trimmed);
|
|
35
|
+
} catch {
|
|
36
|
+
const error: JsonRpcResponse = {
|
|
37
|
+
jsonrpc: "2.0",
|
|
38
|
+
id: null as unknown as number,
|
|
39
|
+
error: { code: -32700, message: "Parse error" },
|
|
40
|
+
};
|
|
41
|
+
process.stdout.write(JSON.stringify(error) + "\n");
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const request = parsed as JsonRpcRequest;
|
|
46
|
+
if (
|
|
47
|
+
!request ||
|
|
48
|
+
request.jsonrpc !== "2.0" ||
|
|
49
|
+
typeof request.method !== "string"
|
|
50
|
+
) {
|
|
51
|
+
const error: JsonRpcResponse = {
|
|
52
|
+
jsonrpc: "2.0",
|
|
53
|
+
id: request?.id ?? (null as unknown as number),
|
|
54
|
+
error: { code: -32600, message: "Invalid Request" },
|
|
55
|
+
};
|
|
56
|
+
process.stdout.write(JSON.stringify(error) + "\n");
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
try {
|
|
61
|
+
const result = await handler(request.method, request.params || {});
|
|
62
|
+
const response: JsonRpcResponse = {
|
|
63
|
+
jsonrpc: "2.0",
|
|
64
|
+
id: request.id,
|
|
65
|
+
result,
|
|
66
|
+
};
|
|
67
|
+
process.stdout.write(JSON.stringify(response) + "\n");
|
|
68
|
+
} catch (err) {
|
|
69
|
+
const response: JsonRpcResponse = {
|
|
70
|
+
jsonrpc: "2.0",
|
|
71
|
+
id: request.id,
|
|
72
|
+
error: {
|
|
73
|
+
code: -32603,
|
|
74
|
+
message: err instanceof Error ? err.message : String(err),
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
process.stdout.write(JSON.stringify(response) + "\n");
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
return {
|
|
82
|
+
start() {
|
|
83
|
+
rl = createInterface({ input: process.stdin });
|
|
84
|
+
rl.on("line", onLine);
|
|
85
|
+
},
|
|
86
|
+
stop() {
|
|
87
|
+
rl?.close();
|
|
88
|
+
rl = null;
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
export const COMPRESSION_SYSTEM = `You are a memory compression engine for an AI coding agent. Your job is to extract the essential information from a tool usage observation and compress it into structured data.
|
|
2
|
+
|
|
3
|
+
Output EXACTLY this XML format with no additional text:
|
|
4
|
+
|
|
5
|
+
<observation>
|
|
6
|
+
<type>one of: file_read, file_write, file_edit, command_run, search, web_fetch, conversation, error, decision, discovery, subagent, notification, task, other</type>
|
|
7
|
+
<title>Short descriptive title (max 80 chars)</title>
|
|
8
|
+
<subtitle>One-line context (optional)</subtitle>
|
|
9
|
+
<facts>
|
|
10
|
+
<fact>Specific factual detail 1</fact>
|
|
11
|
+
<fact>Specific factual detail 2</fact>
|
|
12
|
+
</facts>
|
|
13
|
+
<narrative>2-3 sentence summary of what happened and why it matters</narrative>
|
|
14
|
+
<concepts>
|
|
15
|
+
<concept>technical concept or pattern</concept>
|
|
16
|
+
</concepts>
|
|
17
|
+
<files>
|
|
18
|
+
<file>path/to/file</file>
|
|
19
|
+
</files>
|
|
20
|
+
<importance>1-10 scale, 10 being critical architectural decision</importance>
|
|
21
|
+
</observation>
|
|
22
|
+
|
|
23
|
+
Rules:
|
|
24
|
+
- Be concise but preserve ALL technically relevant details
|
|
25
|
+
- File paths must be exact
|
|
26
|
+
- Importance: 1-3 for routine reads, 4-6 for edits/commands, 7-9 for architectural decisions, 10 for breaking changes
|
|
27
|
+
- Concepts should be reusable search terms (e.g., "React hooks", "SQL migration", "auth middleware")
|
|
28
|
+
- Strip any secrets, tokens, or credentials from the output`;
|
|
29
|
+
|
|
30
|
+
export function buildCompressionPrompt(observation: {
|
|
31
|
+
hookType: string;
|
|
32
|
+
toolName?: string;
|
|
33
|
+
toolInput?: unknown;
|
|
34
|
+
toolOutput?: unknown;
|
|
35
|
+
userPrompt?: string;
|
|
36
|
+
timestamp: string;
|
|
37
|
+
}): string {
|
|
38
|
+
const parts = [
|
|
39
|
+
`Timestamp: ${observation.timestamp}`,
|
|
40
|
+
`Hook: ${observation.hookType}`,
|
|
41
|
+
];
|
|
42
|
+
|
|
43
|
+
if (observation.toolName) parts.push(`Tool: ${observation.toolName}`);
|
|
44
|
+
if (observation.toolInput) {
|
|
45
|
+
const input =
|
|
46
|
+
typeof observation.toolInput === "string"
|
|
47
|
+
? observation.toolInput
|
|
48
|
+
: JSON.stringify(observation.toolInput, null, 2);
|
|
49
|
+
parts.push(`Input:\n${truncate(input, 4000)}`);
|
|
50
|
+
}
|
|
51
|
+
if (observation.toolOutput) {
|
|
52
|
+
const output =
|
|
53
|
+
typeof observation.toolOutput === "string"
|
|
54
|
+
? observation.toolOutput
|
|
55
|
+
: JSON.stringify(observation.toolOutput, null, 2);
|
|
56
|
+
parts.push(`Output:\n${truncate(output, 4000)}`);
|
|
57
|
+
}
|
|
58
|
+
if (observation.userPrompt) {
|
|
59
|
+
parts.push(`User prompt:\n${truncate(observation.userPrompt, 2000)}`);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
return parts.join("\n\n");
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function truncate(s: string, max: number): string {
|
|
66
|
+
return s.length > max ? s.slice(0, max) + "\n[...truncated]" : s;
|
|
67
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
export const SEMANTIC_MERGE_SYSTEM = `You are a memory consolidation engine. Given overlapping episodic memories (session summaries), extract stable factual knowledge.
|
|
2
|
+
|
|
3
|
+
Output format (XML):
|
|
4
|
+
<facts>
|
|
5
|
+
<fact confidence="0.0-1.0">Concise factual statement</fact>
|
|
6
|
+
</facts>
|
|
7
|
+
|
|
8
|
+
Rules:
|
|
9
|
+
- Extract only facts that appear in 2+ episodes or are highly confident
|
|
10
|
+
- Confidence reflects how well-supported the fact is across episodes
|
|
11
|
+
- Combine overlapping information into single concise facts
|
|
12
|
+
- Skip ephemeral details (specific error messages, temporary states)`;
|
|
13
|
+
|
|
14
|
+
export function buildSemanticMergePrompt(
|
|
15
|
+
episodes: Array<{ title: string; narrative: string; concepts: string[] }>,
|
|
16
|
+
): string {
|
|
17
|
+
const items = episodes
|
|
18
|
+
.map(
|
|
19
|
+
(e, i) =>
|
|
20
|
+
`[Episode ${i + 1}]\nTitle: ${e.title}\nNarrative: ${e.narrative}\nConcepts: ${e.concepts.join(", ")}`,
|
|
21
|
+
)
|
|
22
|
+
.join("\n\n");
|
|
23
|
+
return `Consolidate these episodic memories into stable facts:\n\n${items}`;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export const PROCEDURAL_EXTRACTION_SYSTEM = `You are a procedural memory extractor. Given repeated patterns and workflows observed across sessions, extract reusable procedures.
|
|
27
|
+
|
|
28
|
+
Output format (XML):
|
|
29
|
+
<procedures>
|
|
30
|
+
<procedure name="short descriptive name" trigger="when to use this procedure">
|
|
31
|
+
<step>Step 1 description</step>
|
|
32
|
+
<step>Step 2 description</step>
|
|
33
|
+
</procedure>
|
|
34
|
+
</procedures>
|
|
35
|
+
|
|
36
|
+
Rules:
|
|
37
|
+
- Only extract procedures observed 2+ times
|
|
38
|
+
- Steps should be concrete and actionable
|
|
39
|
+
- Trigger condition should be specific enough to match automatically`;
|
|
40
|
+
|
|
41
|
+
export function buildProceduralExtractionPrompt(
|
|
42
|
+
patterns: Array<{ content: string; frequency: number }>,
|
|
43
|
+
): string {
|
|
44
|
+
const items = patterns
|
|
45
|
+
.map((p, i) => `[Pattern ${i + 1}] (seen ${p.frequency}x)\n${p.content}`)
|
|
46
|
+
.join("\n\n");
|
|
47
|
+
return `Extract reusable procedures from these recurring patterns:\n\n${items}`;
|
|
48
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
export const GRAPH_EXTRACTION_SYSTEM = `You are a knowledge graph extraction engine. Given a compressed observation from a coding session, extract entities and relationships.
|
|
2
|
+
|
|
3
|
+
Output format (XML):
|
|
4
|
+
<entities>
|
|
5
|
+
<entity type="file|function|concept|error|decision|pattern|library|person" name="exact name">
|
|
6
|
+
<property key="key">value</property>
|
|
7
|
+
</entity>
|
|
8
|
+
</entities>
|
|
9
|
+
<relationships>
|
|
10
|
+
<relationship type="uses|imports|modifies|causes|fixes|depends_on|related_to" source="entity name" target="entity name" weight="0.1-1.0"/>
|
|
11
|
+
</relationships>
|
|
12
|
+
|
|
13
|
+
Rules:
|
|
14
|
+
- Extract concrete entities only (real file paths, function names, library names)
|
|
15
|
+
- Use the most specific type available
|
|
16
|
+
- Weight relationships by how strong/direct the connection is
|
|
17
|
+
- If no entities found, output empty tags`;
|
|
18
|
+
|
|
19
|
+
export function buildGraphExtractionPrompt(
|
|
20
|
+
observations: Array<{
|
|
21
|
+
title: string;
|
|
22
|
+
narrative: string;
|
|
23
|
+
concepts: string[];
|
|
24
|
+
files: string[];
|
|
25
|
+
type: string;
|
|
26
|
+
}>,
|
|
27
|
+
): string {
|
|
28
|
+
const items = observations
|
|
29
|
+
.map(
|
|
30
|
+
(o, i) =>
|
|
31
|
+
`[${i + 1}] Type: ${o.type}\nTitle: ${o.title}\nNarrative: ${o.narrative}\nConcepts: ${(o.concepts ?? []).join(", ")}\nFiles: ${(o.files ?? []).join(", ")}`,
|
|
32
|
+
)
|
|
33
|
+
.join("\n\n");
|
|
34
|
+
return `Extract entities and relationships from these observations:\n\n${items}`;
|
|
35
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
export const SUMMARY_SYSTEM = `You are a session summarizer for an AI coding agent's memory system. Given all compressed observations from a coding session, produce a concise session summary.
|
|
2
|
+
|
|
3
|
+
Output EXACTLY this XML format with no additional text:
|
|
4
|
+
|
|
5
|
+
<summary>
|
|
6
|
+
<title>Short session title (max 100 chars)</title>
|
|
7
|
+
<narrative>3-5 sentence narrative of what was accomplished</narrative>
|
|
8
|
+
<decisions>
|
|
9
|
+
<decision>Key technical decision made</decision>
|
|
10
|
+
</decisions>
|
|
11
|
+
<files>
|
|
12
|
+
<file>path/to/modified/file</file>
|
|
13
|
+
</files>
|
|
14
|
+
<concepts>
|
|
15
|
+
<concept>key concept from session</concept>
|
|
16
|
+
</concepts>
|
|
17
|
+
</summary>
|
|
18
|
+
|
|
19
|
+
Rules:
|
|
20
|
+
- Focus on outcomes, not individual tool calls
|
|
21
|
+
- Highlight decisions and their rationale
|
|
22
|
+
- List all files that were created or modified
|
|
23
|
+
- Concepts should be searchable terms for future context retrieval`
|
|
24
|
+
|
|
25
|
+
export function buildSummaryPrompt(observations: Array<{
|
|
26
|
+
type: string
|
|
27
|
+
title: string
|
|
28
|
+
facts: string[]
|
|
29
|
+
narrative: string
|
|
30
|
+
files: string[]
|
|
31
|
+
concepts: string[]
|
|
32
|
+
}>): string {
|
|
33
|
+
const lines = observations.map((obs, i) => {
|
|
34
|
+
const facts = obs.facts.map((f) => ` - ${f}`).join('\n')
|
|
35
|
+
return `[${i + 1}] ${obs.type}: ${obs.title}\n${obs.narrative}\nFacts:\n${facts}\nFiles: ${obs.files.join(', ')}`
|
|
36
|
+
})
|
|
37
|
+
return `Session observations (${observations.length} total):\n\n${lines.join('\n\n---\n\n')}`
|
|
38
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
const VALID_TAG = /^[a-zA-Z_][a-zA-Z0-9_-]*$/;
|
|
2
|
+
|
|
3
|
+
export function getXmlTag(xml: string, tag: string): string {
|
|
4
|
+
if (!VALID_TAG.test(tag)) return "";
|
|
5
|
+
const match = xml.match(new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`));
|
|
6
|
+
return match ? match[1].trim() : "";
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function getXmlChildren(
|
|
10
|
+
xml: string,
|
|
11
|
+
parentTag: string,
|
|
12
|
+
childTag: string,
|
|
13
|
+
): string[] {
|
|
14
|
+
if (!VALID_TAG.test(parentTag) || !VALID_TAG.test(childTag)) return [];
|
|
15
|
+
const parentMatch = xml.match(
|
|
16
|
+
new RegExp(`<${parentTag}>([\\s\\S]*?)</${parentTag}>`),
|
|
17
|
+
);
|
|
18
|
+
if (!parentMatch) return [];
|
|
19
|
+
const items: string[] = [];
|
|
20
|
+
const re = new RegExp(`<${childTag}>([\\s\\S]*?)</${childTag}>`, "g");
|
|
21
|
+
let m;
|
|
22
|
+
while ((m = re.exec(parentMatch[1])) !== null) {
|
|
23
|
+
items.push(m[1].trim());
|
|
24
|
+
}
|
|
25
|
+
return items;
|
|
26
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { MemoryProvider } from '../types.js'
|
|
2
|
+
|
|
3
|
+
export class AgentSDKProvider implements MemoryProvider {
|
|
4
|
+
name = 'agent-sdk'
|
|
5
|
+
|
|
6
|
+
async compress(systemPrompt: string, userPrompt: string): Promise<string> {
|
|
7
|
+
return this.query(systemPrompt, userPrompt)
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
async summarize(systemPrompt: string, userPrompt: string): Promise<string> {
|
|
11
|
+
return this.query(systemPrompt, userPrompt)
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
private async query(systemPrompt: string, userPrompt: string): Promise<string> {
|
|
15
|
+
const { query } = await import('@anthropic-ai/claude-agent-sdk')
|
|
16
|
+
|
|
17
|
+
const messages = query({
|
|
18
|
+
prompt: userPrompt,
|
|
19
|
+
options: {
|
|
20
|
+
systemPrompt,
|
|
21
|
+
maxTurns: 1,
|
|
22
|
+
allowedTools: [],
|
|
23
|
+
},
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
let result = ''
|
|
27
|
+
for await (const msg of messages) {
|
|
28
|
+
if (msg.type === 'result') {
|
|
29
|
+
result = typeof msg.result === 'string' ? msg.result : JSON.stringify(msg.result)
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return result
|
|
33
|
+
}
|
|
34
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import Anthropic from '@anthropic-ai/sdk'
|
|
2
|
+
import type { MemoryProvider } from '../types.js'
|
|
3
|
+
|
|
4
|
+
export class AnthropicProvider implements MemoryProvider {
|
|
5
|
+
name = 'anthropic'
|
|
6
|
+
private client: Anthropic
|
|
7
|
+
private model: string
|
|
8
|
+
private maxTokens: number
|
|
9
|
+
|
|
10
|
+
constructor(apiKey: string, model: string, maxTokens: number) {
|
|
11
|
+
this.client = new Anthropic({ apiKey })
|
|
12
|
+
this.model = model
|
|
13
|
+
this.maxTokens = maxTokens
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
async compress(systemPrompt: string, userPrompt: string): Promise<string> {
|
|
17
|
+
return this.call(systemPrompt, userPrompt)
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async summarize(systemPrompt: string, userPrompt: string): Promise<string> {
|
|
21
|
+
return this.call(systemPrompt, userPrompt)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
private async call(systemPrompt: string, userPrompt: string): Promise<string> {
|
|
25
|
+
const response = await this.client.messages.create({
|
|
26
|
+
model: this.model,
|
|
27
|
+
max_tokens: this.maxTokens,
|
|
28
|
+
system: systemPrompt,
|
|
29
|
+
messages: [{ role: 'user', content: userPrompt }],
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
const textBlock = response.content.find((b) => b.type === 'text')
|
|
33
|
+
return textBlock?.text ?? ''
|
|
34
|
+
}
|
|
35
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import type { CircuitBreakerState } from "../types.js";
|
|
2
|
+
|
|
3
|
+
interface CircuitBreakerOptions {
|
|
4
|
+
failureThreshold?: number;
|
|
5
|
+
failureWindowMs?: number;
|
|
6
|
+
recoveryTimeoutMs?: number;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
function positiveFinite(val: number | undefined, fallback: number): number {
|
|
10
|
+
return Number.isFinite(val) && val! > 0 ? val! : fallback;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export class CircuitBreaker {
|
|
14
|
+
private state: "closed" | "open" | "half-open" = "closed";
|
|
15
|
+
private failures = 0;
|
|
16
|
+
private lastFailureAt: number | null = null;
|
|
17
|
+
private openedAt: number | null = null;
|
|
18
|
+
|
|
19
|
+
private readonly failureThreshold: number;
|
|
20
|
+
private readonly failureWindowMs: number;
|
|
21
|
+
private readonly recoveryTimeoutMs: number;
|
|
22
|
+
|
|
23
|
+
constructor(opts?: CircuitBreakerOptions) {
|
|
24
|
+
this.failureThreshold = Math.max(
|
|
25
|
+
1,
|
|
26
|
+
Math.floor(positiveFinite(opts?.failureThreshold, 3)),
|
|
27
|
+
);
|
|
28
|
+
this.failureWindowMs = positiveFinite(opts?.failureWindowMs, 60_000);
|
|
29
|
+
this.recoveryTimeoutMs = positiveFinite(opts?.recoveryTimeoutMs, 30_000);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
get isAllowed(): boolean {
|
|
33
|
+
if (this.state === "closed") return true;
|
|
34
|
+
if (this.state === "open") {
|
|
35
|
+
if (
|
|
36
|
+
this.openedAt &&
|
|
37
|
+
Date.now() - this.openedAt >= this.recoveryTimeoutMs
|
|
38
|
+
) {
|
|
39
|
+
this.state = "half-open";
|
|
40
|
+
return true;
|
|
41
|
+
}
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
return true;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
recordSuccess(): void {
|
|
48
|
+
if (this.state === "half-open") {
|
|
49
|
+
this.state = "closed";
|
|
50
|
+
this.failures = 0;
|
|
51
|
+
this.lastFailureAt = null;
|
|
52
|
+
this.openedAt = null;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
recordFailure(): void {
|
|
57
|
+
const now = Date.now();
|
|
58
|
+
if (this.state === "half-open") {
|
|
59
|
+
this.state = "open";
|
|
60
|
+
this.openedAt = now;
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
if (this.lastFailureAt && now - this.lastFailureAt > this.failureWindowMs) {
|
|
64
|
+
this.failures = 0;
|
|
65
|
+
}
|
|
66
|
+
this.failures += 1;
|
|
67
|
+
this.lastFailureAt = now;
|
|
68
|
+
if (this.failures >= this.failureThreshold) {
|
|
69
|
+
this.state = "open";
|
|
70
|
+
this.openedAt = now;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
getState(): CircuitBreakerState {
|
|
75
|
+
return {
|
|
76
|
+
state: this.state,
|
|
77
|
+
failures: this.failures,
|
|
78
|
+
lastFailureAt: this.lastFailureAt,
|
|
79
|
+
openedAt: this.openedAt,
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { EmbeddingProvider } from "../../types.js";
|
|
2
|
+
import { getEnvVar } from "../../config.js";
|
|
3
|
+
|
|
4
|
+
const API_URL = "https://api.cohere.ai/v1/embed";
|
|
5
|
+
|
|
6
|
+
export class CohereEmbeddingProvider implements EmbeddingProvider {
|
|
7
|
+
readonly name = "cohere";
|
|
8
|
+
readonly dimensions = 1024;
|
|
9
|
+
private apiKey: string;
|
|
10
|
+
|
|
11
|
+
constructor(apiKey?: string) {
|
|
12
|
+
this.apiKey = apiKey || getEnvVar("COHERE_API_KEY") || "";
|
|
13
|
+
if (!this.apiKey) throw new Error("COHERE_API_KEY is required");
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
async embed(text: string): Promise<Float32Array> {
|
|
17
|
+
const [result] = await this.embedBatch([text]);
|
|
18
|
+
return result;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async embedBatch(texts: string[]): Promise<Float32Array[]> {
|
|
22
|
+
const response = await fetch(API_URL, {
|
|
23
|
+
method: "POST",
|
|
24
|
+
headers: {
|
|
25
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
26
|
+
"Content-Type": "application/json",
|
|
27
|
+
},
|
|
28
|
+
body: JSON.stringify({
|
|
29
|
+
model: "embed-english-v3.0",
|
|
30
|
+
texts,
|
|
31
|
+
input_type: "search_document",
|
|
32
|
+
}),
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
if (!response.ok) {
|
|
36
|
+
const err = await response.text();
|
|
37
|
+
throw new Error(`Cohere embedding failed (${response.status}): ${err}`);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const data = (await response.json()) as {
|
|
41
|
+
embeddings: number[][];
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
return data.embeddings.map((e) => new Float32Array(e));
|
|
45
|
+
}
|
|
46
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { EmbeddingProvider } from "../../types.js";
|
|
2
|
+
import { getEnvVar } from "../../config.js";
|
|
3
|
+
|
|
4
|
+
const BATCH_LIMIT = 100;
|
|
5
|
+
const API_BASE = "https://generativelanguage.googleapis.com/v1beta/models/text-embedding-004:batchEmbedContent";
|
|
6
|
+
|
|
7
|
+
export class GeminiEmbeddingProvider implements EmbeddingProvider {
|
|
8
|
+
readonly name = "gemini";
|
|
9
|
+
readonly dimensions = 768;
|
|
10
|
+
private apiKey: string;
|
|
11
|
+
|
|
12
|
+
constructor(apiKey?: string) {
|
|
13
|
+
this.apiKey = apiKey || getEnvVar("GEMINI_API_KEY") || "";
|
|
14
|
+
if (!this.apiKey) throw new Error("GEMINI_API_KEY is required");
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
async embed(text: string): Promise<Float32Array> {
|
|
18
|
+
const [result] = await this.embedBatch([text]);
|
|
19
|
+
return result;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async embedBatch(texts: string[]): Promise<Float32Array[]> {
|
|
23
|
+
const results: Float32Array[] = [];
|
|
24
|
+
|
|
25
|
+
for (let i = 0; i < texts.length; i += BATCH_LIMIT) {
|
|
26
|
+
const chunk = texts.slice(i, i + BATCH_LIMIT);
|
|
27
|
+
const response = await fetch(`${API_BASE}?key=${this.apiKey}`, {
|
|
28
|
+
method: "POST",
|
|
29
|
+
headers: { "Content-Type": "application/json" },
|
|
30
|
+
body: JSON.stringify({
|
|
31
|
+
requests: chunk.map((t) => ({
|
|
32
|
+
model: "models/text-embedding-004",
|
|
33
|
+
content: { parts: [{ text: t }] },
|
|
34
|
+
})),
|
|
35
|
+
}),
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
if (!response.ok) {
|
|
39
|
+
const err = await response.text();
|
|
40
|
+
throw new Error(`Gemini embedding failed (${response.status}): ${err}`);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const data = (await response.json()) as {
|
|
44
|
+
embeddings: Array<{ values: number[] }>;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
for (const emb of data.embeddings) {
|
|
48
|
+
results.push(new Float32Array(emb.values));
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
return results;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { EmbeddingProvider } from "../../types.js";
|
|
2
|
+
import { detectEmbeddingProvider, getEnvVar } from "../../config.js";
|
|
3
|
+
import { GeminiEmbeddingProvider } from "./gemini.js";
|
|
4
|
+
import { OpenAIEmbeddingProvider } from "./openai.js";
|
|
5
|
+
import { VoyageEmbeddingProvider } from "./voyage.js";
|
|
6
|
+
import { CohereEmbeddingProvider } from "./cohere.js";
|
|
7
|
+
import { OpenRouterEmbeddingProvider } from "./openrouter.js";
|
|
8
|
+
import { LocalEmbeddingProvider } from "./local.js";
|
|
9
|
+
|
|
10
|
+
export {
|
|
11
|
+
GeminiEmbeddingProvider,
|
|
12
|
+
OpenAIEmbeddingProvider,
|
|
13
|
+
VoyageEmbeddingProvider,
|
|
14
|
+
CohereEmbeddingProvider,
|
|
15
|
+
OpenRouterEmbeddingProvider,
|
|
16
|
+
LocalEmbeddingProvider,
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export function createEmbeddingProvider(): EmbeddingProvider | null {
|
|
20
|
+
const detected = detectEmbeddingProvider();
|
|
21
|
+
if (!detected) return null;
|
|
22
|
+
|
|
23
|
+
switch (detected) {
|
|
24
|
+
case "gemini":
|
|
25
|
+
return new GeminiEmbeddingProvider(getEnvVar("GEMINI_API_KEY")!);
|
|
26
|
+
case "openai":
|
|
27
|
+
return new OpenAIEmbeddingProvider(getEnvVar("OPENAI_API_KEY")!);
|
|
28
|
+
case "voyage":
|
|
29
|
+
return new VoyageEmbeddingProvider(getEnvVar("VOYAGE_API_KEY")!);
|
|
30
|
+
case "cohere":
|
|
31
|
+
return new CohereEmbeddingProvider(getEnvVar("COHERE_API_KEY")!);
|
|
32
|
+
case "openrouter":
|
|
33
|
+
return new OpenRouterEmbeddingProvider(getEnvVar("OPENROUTER_API_KEY")!);
|
|
34
|
+
case "local":
|
|
35
|
+
return new LocalEmbeddingProvider();
|
|
36
|
+
default:
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { EmbeddingProvider } from "../../types.js";
|
|
2
|
+
|
|
3
|
+
type Pipeline = (
|
|
4
|
+
task: string,
|
|
5
|
+
model: string,
|
|
6
|
+
) => Promise<
|
|
7
|
+
(
|
|
8
|
+
texts: string[],
|
|
9
|
+
options: { pooling: string; normalize: boolean },
|
|
10
|
+
) => Promise<{ tolist: () => number[][] }>
|
|
11
|
+
>;
|
|
12
|
+
|
|
13
|
+
export class LocalEmbeddingProvider implements EmbeddingProvider {
|
|
14
|
+
readonly name = "local";
|
|
15
|
+
readonly dimensions = 384;
|
|
16
|
+
private extractor: Awaited<ReturnType<Pipeline>> | null = null;
|
|
17
|
+
|
|
18
|
+
async embed(text: string): Promise<Float32Array> {
|
|
19
|
+
const [result] = await this.embedBatch([text]);
|
|
20
|
+
return result;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
async embedBatch(texts: string[]): Promise<Float32Array[]> {
|
|
24
|
+
const extractor = await this.getExtractor();
|
|
25
|
+
const output = await extractor(texts, {
|
|
26
|
+
pooling: "mean",
|
|
27
|
+
normalize: true,
|
|
28
|
+
});
|
|
29
|
+
const vectors = output.tolist();
|
|
30
|
+
return vectors.map((v: number[]) => new Float32Array(v));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
private async getExtractor() {
|
|
34
|
+
if (this.extractor) return this.extractor;
|
|
35
|
+
|
|
36
|
+
let transformers: { pipeline: Pipeline };
|
|
37
|
+
try {
|
|
38
|
+
// @ts-ignore - optional peer dependency
|
|
39
|
+
transformers = await import("@xenova/transformers");
|
|
40
|
+
} catch {
|
|
41
|
+
throw new Error(
|
|
42
|
+
"Install @xenova/transformers for local embeddings: npm install @xenova/transformers",
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
this.extractor = await transformers.pipeline(
|
|
47
|
+
"feature-extraction",
|
|
48
|
+
"Xenova/all-MiniLM-L6-v2",
|
|
49
|
+
);
|
|
50
|
+
return this.extractor;
|
|
51
|
+
}
|
|
52
|
+
}
|