@agentmemory/agentmemory 0.7.0 → 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 (218) hide show
  1. package/AGENTS.md +2 -2
  2. package/README.md +76 -82
  3. package/dist/cli.mjs +99 -32
  4. package/dist/cli.mjs.map +1 -1
  5. package/dist/index.mjs +4 -2
  6. package/dist/index.mjs.map +1 -1
  7. package/dist/{src-QxitMPfJ.mjs → src-sYZDDbiA.mjs} +5 -3
  8. package/dist/src-sYZDDbiA.mjs.map +1 -0
  9. package/dist/standalone.mjs +1 -1
  10. package/dist/standalone.mjs.map +1 -1
  11. package/package.json +11 -1
  12. package/plugin/.claude-plugin/plugin.json +1 -1
  13. package/plugin/scripts/notification.d.mts +1 -0
  14. package/plugin/scripts/notification.mjs.map +1 -0
  15. package/plugin/scripts/post-tool-failure.d.mts +1 -0
  16. package/plugin/scripts/post-tool-failure.mjs.map +1 -0
  17. package/plugin/scripts/post-tool-use.d.mts +1 -0
  18. package/plugin/scripts/post-tool-use.mjs.map +1 -0
  19. package/plugin/scripts/pre-compact.d.mts +1 -0
  20. package/plugin/scripts/pre-compact.mjs.map +1 -0
  21. package/plugin/scripts/pre-tool-use.d.mts +1 -0
  22. package/plugin/scripts/pre-tool-use.mjs.map +1 -0
  23. package/plugin/scripts/prompt-submit.d.mts +1 -0
  24. package/plugin/scripts/prompt-submit.mjs.map +1 -0
  25. package/plugin/scripts/session-end.d.mts +1 -0
  26. package/plugin/scripts/session-end.mjs.map +1 -0
  27. package/plugin/scripts/session-start.d.mts +1 -0
  28. package/plugin/scripts/session-start.mjs.map +1 -0
  29. package/plugin/scripts/stop.d.mts +1 -0
  30. package/plugin/scripts/stop.mjs.map +1 -0
  31. package/plugin/scripts/subagent-start.d.mts +1 -0
  32. package/plugin/scripts/subagent-start.mjs.map +1 -0
  33. package/plugin/scripts/subagent-stop.d.mts +1 -0
  34. package/plugin/scripts/subagent-stop.mjs.map +1 -0
  35. package/plugin/scripts/task-completed.d.mts +1 -0
  36. package/plugin/scripts/task-completed.mjs.map +1 -0
  37. package/.claude-plugin/marketplace.json +0 -14
  38. package/.github/workflows/ci.yml +0 -22
  39. package/.github/workflows/publish.yml +0 -28
  40. package/assets/banner.png +0 -0
  41. package/assets/demo.gif +0 -0
  42. package/assets/demo.mp4 +0 -0
  43. package/benchmark/QUALITY.md +0 -73
  44. package/benchmark/REAL-EMBEDDINGS.md +0 -67
  45. package/benchmark/SCALE.md +0 -110
  46. package/benchmark/dataset.ts +0 -293
  47. package/benchmark/quality-eval.ts +0 -643
  48. package/benchmark/real-embeddings-eval.ts +0 -405
  49. package/benchmark/scale-eval.ts +0 -398
  50. package/dist/src-QxitMPfJ.mjs.map +0 -1
  51. package/src/auth.ts +0 -12
  52. package/src/cli.ts +0 -159
  53. package/src/config.ts +0 -221
  54. package/src/eval/metrics-store.ts +0 -65
  55. package/src/eval/quality.ts +0 -51
  56. package/src/eval/schemas.ts +0 -124
  57. package/src/eval/self-correct.ts +0 -28
  58. package/src/eval/validator.ts +0 -31
  59. package/src/functions/actions.ts +0 -288
  60. package/src/functions/audit.ts +0 -61
  61. package/src/functions/auto-forget.ts +0 -169
  62. package/src/functions/branch-aware.ts +0 -169
  63. package/src/functions/cascade.ts +0 -80
  64. package/src/functions/checkpoints.ts +0 -209
  65. package/src/functions/claude-bridge.ts +0 -161
  66. package/src/functions/compress.ts +0 -194
  67. package/src/functions/consolidate.ts +0 -212
  68. package/src/functions/consolidation-pipeline.ts +0 -258
  69. package/src/functions/context.ts +0 -169
  70. package/src/functions/crystallize.ts +0 -293
  71. package/src/functions/dedup.ts +0 -57
  72. package/src/functions/diagnostics.ts +0 -785
  73. package/src/functions/enrich.ts +0 -132
  74. package/src/functions/evict.ts +0 -163
  75. package/src/functions/export-import.ts +0 -508
  76. package/src/functions/facets.ts +0 -248
  77. package/src/functions/file-index.ts +0 -106
  78. package/src/functions/flow-compress.ts +0 -214
  79. package/src/functions/frontier.ts +0 -196
  80. package/src/functions/governance.ts +0 -131
  81. package/src/functions/graph-retrieval.ts +0 -277
  82. package/src/functions/graph.ts +0 -275
  83. package/src/functions/leases.ts +0 -216
  84. package/src/functions/lessons.ts +0 -253
  85. package/src/functions/mesh.ts +0 -434
  86. package/src/functions/migrate.ts +0 -165
  87. package/src/functions/observe.ts +0 -144
  88. package/src/functions/obsidian-export.ts +0 -310
  89. package/src/functions/patterns.ts +0 -138
  90. package/src/functions/privacy.ts +0 -39
  91. package/src/functions/profile.ts +0 -155
  92. package/src/functions/query-expansion.ts +0 -186
  93. package/src/functions/relations.ts +0 -237
  94. package/src/functions/remember.ts +0 -162
  95. package/src/functions/retention.ts +0 -235
  96. package/src/functions/routines.ts +0 -289
  97. package/src/functions/search.ts +0 -80
  98. package/src/functions/sentinels.ts +0 -417
  99. package/src/functions/signals.ts +0 -186
  100. package/src/functions/sketches.ts +0 -274
  101. package/src/functions/sliding-window.ts +0 -257
  102. package/src/functions/smart-search.ts +0 -115
  103. package/src/functions/snapshot.ts +0 -219
  104. package/src/functions/summarize.ts +0 -155
  105. package/src/functions/team.ts +0 -147
  106. package/src/functions/temporal-graph.ts +0 -476
  107. package/src/functions/timeline.ts +0 -138
  108. package/src/functions/verify.ts +0 -117
  109. package/src/health/monitor.ts +0 -110
  110. package/src/health/thresholds.ts +0 -73
  111. package/src/hooks/notification.ts +0 -52
  112. package/src/hooks/post-tool-failure.ts +0 -58
  113. package/src/hooks/post-tool-use.ts +0 -62
  114. package/src/hooks/pre-compact.ts +0 -60
  115. package/src/hooks/pre-tool-use.ts +0 -72
  116. package/src/hooks/prompt-submit.ts +0 -46
  117. package/src/hooks/session-end.ts +0 -71
  118. package/src/hooks/session-start.ts +0 -48
  119. package/src/hooks/stop.ts +0 -39
  120. package/src/hooks/subagent-start.ts +0 -49
  121. package/src/hooks/subagent-stop.ts +0 -54
  122. package/src/hooks/task-completed.ts +0 -54
  123. package/src/index.ts +0 -342
  124. package/src/mcp/in-memory-kv.ts +0 -61
  125. package/src/mcp/server.ts +0 -1455
  126. package/src/mcp/standalone.ts +0 -177
  127. package/src/mcp/tools-registry.ts +0 -769
  128. package/src/mcp/transport.ts +0 -91
  129. package/src/prompts/compression.ts +0 -67
  130. package/src/prompts/consolidation.ts +0 -48
  131. package/src/prompts/graph-extraction.ts +0 -35
  132. package/src/prompts/summary.ts +0 -38
  133. package/src/prompts/xml.ts +0 -26
  134. package/src/providers/agent-sdk.ts +0 -34
  135. package/src/providers/anthropic.ts +0 -35
  136. package/src/providers/circuit-breaker.ts +0 -82
  137. package/src/providers/embedding/cohere.ts +0 -46
  138. package/src/providers/embedding/gemini.ts +0 -54
  139. package/src/providers/embedding/index.ts +0 -39
  140. package/src/providers/embedding/local.ts +0 -52
  141. package/src/providers/embedding/openai.ts +0 -45
  142. package/src/providers/embedding/openrouter.ts +0 -51
  143. package/src/providers/embedding/voyage.ts +0 -46
  144. package/src/providers/fallback-chain.ts +0 -31
  145. package/src/providers/index.ts +0 -84
  146. package/src/providers/openrouter.ts +0 -71
  147. package/src/providers/resilient.ts +0 -37
  148. package/src/state/hybrid-search.ts +0 -295
  149. package/src/state/index-persistence.ts +0 -63
  150. package/src/state/keyed-mutex.ts +0 -18
  151. package/src/state/kv.ts +0 -33
  152. package/src/state/schema.ts +0 -71
  153. package/src/state/search-index.ts +0 -245
  154. package/src/state/stemmer.ts +0 -104
  155. package/src/state/synonyms.ts +0 -63
  156. package/src/state/vector-index.ts +0 -130
  157. package/src/telemetry/setup.ts +0 -116
  158. package/src/triggers/api.ts +0 -1904
  159. package/src/triggers/events.ts +0 -71
  160. package/src/types.ts +0 -769
  161. package/src/version.ts +0 -1
  162. package/src/viewer/index.html +0 -2497
  163. package/src/viewer/server.ts +0 -207
  164. package/src/xenova.d.ts +0 -3
  165. package/test/actions.test.ts +0 -490
  166. package/test/audit.test.ts +0 -108
  167. package/test/auto-forget.test.ts +0 -188
  168. package/test/cascade.test.ts +0 -277
  169. package/test/checkpoints.test.ts +0 -493
  170. package/test/circuit-breaker.test.ts +0 -107
  171. package/test/claude-bridge.test.ts +0 -178
  172. package/test/confidence.test.ts +0 -247
  173. package/test/consistency.test.ts +0 -61
  174. package/test/consolidation-pipeline.test.ts +0 -251
  175. package/test/crystallize.test.ts +0 -521
  176. package/test/diagnostics.test.ts +0 -638
  177. package/test/embedding-provider.test.ts +0 -49
  178. package/test/enrich.test.ts +0 -209
  179. package/test/eval.test.ts +0 -300
  180. package/test/export-import.test.ts +0 -251
  181. package/test/facets.test.ts +0 -448
  182. package/test/fallback-chain.test.ts +0 -93
  183. package/test/frontier.test.ts +0 -485
  184. package/test/governance.test.ts +0 -147
  185. package/test/graph-retrieval.test.ts +0 -186
  186. package/test/graph.test.ts +0 -160
  187. package/test/helpers/mocks.ts +0 -40
  188. package/test/hybrid-search.test.ts +0 -145
  189. package/test/index-persistence.test.ts +0 -124
  190. package/test/integration.test.ts +0 -265
  191. package/test/leases.test.ts +0 -399
  192. package/test/mcp-prompts.test.ts +0 -218
  193. package/test/mcp-resources.test.ts +0 -286
  194. package/test/mcp-standalone.test.ts +0 -113
  195. package/test/mesh.test.ts +0 -700
  196. package/test/privacy.test.ts +0 -87
  197. package/test/profile.test.ts +0 -161
  198. package/test/query-expansion.test.ts +0 -154
  199. package/test/relations.test.ts +0 -198
  200. package/test/retention.test.ts +0 -245
  201. package/test/routines.test.ts +0 -497
  202. package/test/schema-fingerprint.test.ts +0 -81
  203. package/test/schema.test.ts +0 -42
  204. package/test/search-index.test.ts +0 -128
  205. package/test/sentinels.test.ts +0 -626
  206. package/test/signals.test.ts +0 -410
  207. package/test/sketches.test.ts +0 -549
  208. package/test/sliding-window.test.ts +0 -199
  209. package/test/smart-search.test.ts +0 -169
  210. package/test/snapshot.test.ts +0 -165
  211. package/test/team.test.ts +0 -156
  212. package/test/temporal-graph.test.ts +0 -378
  213. package/test/timeline.test.ts +0 -148
  214. package/test/vector-index.test.ts +0 -79
  215. package/test/verify.test.ts +0 -209
  216. package/test/xml.test.ts +0 -65
  217. package/tsconfig.json +0 -22
  218. package/tsdown.config.ts +0 -62
@@ -1,91 +0,0 @@
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
- }
@@ -1,67 +0,0 @@
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
- }
@@ -1,48 +0,0 @@
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
- }
@@ -1,35 +0,0 @@
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
- }
@@ -1,38 +0,0 @@
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
- }
@@ -1,26 +0,0 @@
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
- }
@@ -1,34 +0,0 @@
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
- }
@@ -1,35 +0,0 @@
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
- }
@@ -1,82 +0,0 @@
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
- }
@@ -1,46 +0,0 @@
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
- }
@@ -1,54 +0,0 @@
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
- }
@@ -1,39 +0,0 @@
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
- }
@@ -1,52 +0,0 @@
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
- }