@agentmemory/agentmemory 0.7.2 → 0.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (217) hide show
  1. package/AGENTS.md +2 -2
  2. package/README.md +41 -68
  3. package/dist/cli.mjs +3 -3
  4. package/dist/index.mjs +3 -2
  5. package/dist/index.mjs.map +1 -1
  6. package/dist/{src-1fTKFEtN.mjs → src-sYZDDbiA.mjs} +4 -3
  7. package/dist/src-sYZDDbiA.mjs.map +1 -0
  8. package/dist/standalone.mjs +1 -1
  9. package/dist/standalone.mjs.map +1 -1
  10. package/package.json +10 -1
  11. package/plugin/.claude-plugin/plugin.json +1 -1
  12. package/plugin/scripts/notification.d.mts +1 -0
  13. package/plugin/scripts/notification.mjs.map +1 -0
  14. package/plugin/scripts/post-tool-failure.d.mts +1 -0
  15. package/plugin/scripts/post-tool-failure.mjs.map +1 -0
  16. package/plugin/scripts/post-tool-use.d.mts +1 -0
  17. package/plugin/scripts/post-tool-use.mjs.map +1 -0
  18. package/plugin/scripts/pre-compact.d.mts +1 -0
  19. package/plugin/scripts/pre-compact.mjs.map +1 -0
  20. package/plugin/scripts/pre-tool-use.d.mts +1 -0
  21. package/plugin/scripts/pre-tool-use.mjs.map +1 -0
  22. package/plugin/scripts/prompt-submit.d.mts +1 -0
  23. package/plugin/scripts/prompt-submit.mjs.map +1 -0
  24. package/plugin/scripts/session-end.d.mts +1 -0
  25. package/plugin/scripts/session-end.mjs.map +1 -0
  26. package/plugin/scripts/session-start.d.mts +1 -0
  27. package/plugin/scripts/session-start.mjs.map +1 -0
  28. package/plugin/scripts/stop.d.mts +1 -0
  29. package/plugin/scripts/stop.mjs.map +1 -0
  30. package/plugin/scripts/subagent-start.d.mts +1 -0
  31. package/plugin/scripts/subagent-start.mjs.map +1 -0
  32. package/plugin/scripts/subagent-stop.d.mts +1 -0
  33. package/plugin/scripts/subagent-stop.mjs.map +1 -0
  34. package/plugin/scripts/task-completed.d.mts +1 -0
  35. package/plugin/scripts/task-completed.mjs.map +1 -0
  36. package/.claude-plugin/marketplace.json +0 -14
  37. package/.github/workflows/ci.yml +0 -22
  38. package/.github/workflows/publish.yml +0 -28
  39. package/assets/banner.png +0 -0
  40. package/assets/demo.gif +0 -0
  41. package/assets/demo.mp4 +0 -0
  42. package/benchmark/QUALITY.md +0 -73
  43. package/benchmark/REAL-EMBEDDINGS.md +0 -67
  44. package/benchmark/SCALE.md +0 -110
  45. package/benchmark/dataset.ts +0 -293
  46. package/benchmark/quality-eval.ts +0 -643
  47. package/benchmark/real-embeddings-eval.ts +0 -405
  48. package/benchmark/scale-eval.ts +0 -398
  49. package/dist/src-1fTKFEtN.mjs.map +0 -1
  50. package/src/auth.ts +0 -12
  51. package/src/cli.ts +0 -251
  52. package/src/config.ts +0 -221
  53. package/src/eval/metrics-store.ts +0 -65
  54. package/src/eval/quality.ts +0 -51
  55. package/src/eval/schemas.ts +0 -124
  56. package/src/eval/self-correct.ts +0 -28
  57. package/src/eval/validator.ts +0 -31
  58. package/src/functions/actions.ts +0 -288
  59. package/src/functions/audit.ts +0 -61
  60. package/src/functions/auto-forget.ts +0 -169
  61. package/src/functions/branch-aware.ts +0 -169
  62. package/src/functions/cascade.ts +0 -80
  63. package/src/functions/checkpoints.ts +0 -209
  64. package/src/functions/claude-bridge.ts +0 -161
  65. package/src/functions/compress.ts +0 -194
  66. package/src/functions/consolidate.ts +0 -212
  67. package/src/functions/consolidation-pipeline.ts +0 -258
  68. package/src/functions/context.ts +0 -169
  69. package/src/functions/crystallize.ts +0 -293
  70. package/src/functions/dedup.ts +0 -57
  71. package/src/functions/diagnostics.ts +0 -785
  72. package/src/functions/enrich.ts +0 -132
  73. package/src/functions/evict.ts +0 -163
  74. package/src/functions/export-import.ts +0 -508
  75. package/src/functions/facets.ts +0 -248
  76. package/src/functions/file-index.ts +0 -106
  77. package/src/functions/flow-compress.ts +0 -214
  78. package/src/functions/frontier.ts +0 -196
  79. package/src/functions/governance.ts +0 -131
  80. package/src/functions/graph-retrieval.ts +0 -277
  81. package/src/functions/graph.ts +0 -275
  82. package/src/functions/leases.ts +0 -216
  83. package/src/functions/lessons.ts +0 -253
  84. package/src/functions/mesh.ts +0 -434
  85. package/src/functions/migrate.ts +0 -165
  86. package/src/functions/observe.ts +0 -144
  87. package/src/functions/obsidian-export.ts +0 -310
  88. package/src/functions/patterns.ts +0 -138
  89. package/src/functions/privacy.ts +0 -39
  90. package/src/functions/profile.ts +0 -155
  91. package/src/functions/query-expansion.ts +0 -186
  92. package/src/functions/relations.ts +0 -237
  93. package/src/functions/remember.ts +0 -162
  94. package/src/functions/retention.ts +0 -235
  95. package/src/functions/routines.ts +0 -289
  96. package/src/functions/search.ts +0 -80
  97. package/src/functions/sentinels.ts +0 -417
  98. package/src/functions/signals.ts +0 -186
  99. package/src/functions/sketches.ts +0 -274
  100. package/src/functions/sliding-window.ts +0 -257
  101. package/src/functions/smart-search.ts +0 -115
  102. package/src/functions/snapshot.ts +0 -219
  103. package/src/functions/summarize.ts +0 -155
  104. package/src/functions/team.ts +0 -147
  105. package/src/functions/temporal-graph.ts +0 -476
  106. package/src/functions/timeline.ts +0 -138
  107. package/src/functions/verify.ts +0 -117
  108. package/src/health/monitor.ts +0 -110
  109. package/src/health/thresholds.ts +0 -73
  110. package/src/hooks/notification.ts +0 -52
  111. package/src/hooks/post-tool-failure.ts +0 -58
  112. package/src/hooks/post-tool-use.ts +0 -62
  113. package/src/hooks/pre-compact.ts +0 -60
  114. package/src/hooks/pre-tool-use.ts +0 -72
  115. package/src/hooks/prompt-submit.ts +0 -46
  116. package/src/hooks/session-end.ts +0 -71
  117. package/src/hooks/session-start.ts +0 -48
  118. package/src/hooks/stop.ts +0 -39
  119. package/src/hooks/subagent-start.ts +0 -49
  120. package/src/hooks/subagent-stop.ts +0 -54
  121. package/src/hooks/task-completed.ts +0 -54
  122. package/src/index.ts +0 -342
  123. package/src/mcp/in-memory-kv.ts +0 -61
  124. package/src/mcp/server.ts +0 -1455
  125. package/src/mcp/standalone.ts +0 -177
  126. package/src/mcp/tools-registry.ts +0 -769
  127. package/src/mcp/transport.ts +0 -91
  128. package/src/prompts/compression.ts +0 -67
  129. package/src/prompts/consolidation.ts +0 -48
  130. package/src/prompts/graph-extraction.ts +0 -35
  131. package/src/prompts/summary.ts +0 -38
  132. package/src/prompts/xml.ts +0 -26
  133. package/src/providers/agent-sdk.ts +0 -34
  134. package/src/providers/anthropic.ts +0 -35
  135. package/src/providers/circuit-breaker.ts +0 -82
  136. package/src/providers/embedding/cohere.ts +0 -46
  137. package/src/providers/embedding/gemini.ts +0 -54
  138. package/src/providers/embedding/index.ts +0 -39
  139. package/src/providers/embedding/local.ts +0 -52
  140. package/src/providers/embedding/openai.ts +0 -45
  141. package/src/providers/embedding/openrouter.ts +0 -51
  142. package/src/providers/embedding/voyage.ts +0 -46
  143. package/src/providers/fallback-chain.ts +0 -31
  144. package/src/providers/index.ts +0 -84
  145. package/src/providers/openrouter.ts +0 -71
  146. package/src/providers/resilient.ts +0 -37
  147. package/src/state/hybrid-search.ts +0 -295
  148. package/src/state/index-persistence.ts +0 -63
  149. package/src/state/keyed-mutex.ts +0 -18
  150. package/src/state/kv.ts +0 -33
  151. package/src/state/schema.ts +0 -71
  152. package/src/state/search-index.ts +0 -245
  153. package/src/state/stemmer.ts +0 -104
  154. package/src/state/synonyms.ts +0 -63
  155. package/src/state/vector-index.ts +0 -130
  156. package/src/telemetry/setup.ts +0 -116
  157. package/src/triggers/api.ts +0 -1904
  158. package/src/triggers/events.ts +0 -71
  159. package/src/types.ts +0 -769
  160. package/src/version.ts +0 -1
  161. package/src/viewer/index.html +0 -2556
  162. package/src/viewer/server.ts +0 -207
  163. package/src/xenova.d.ts +0 -3
  164. package/test/actions.test.ts +0 -490
  165. package/test/audit.test.ts +0 -108
  166. package/test/auto-forget.test.ts +0 -188
  167. package/test/cascade.test.ts +0 -277
  168. package/test/checkpoints.test.ts +0 -493
  169. package/test/circuit-breaker.test.ts +0 -107
  170. package/test/claude-bridge.test.ts +0 -178
  171. package/test/confidence.test.ts +0 -247
  172. package/test/consistency.test.ts +0 -61
  173. package/test/consolidation-pipeline.test.ts +0 -251
  174. package/test/crystallize.test.ts +0 -521
  175. package/test/diagnostics.test.ts +0 -638
  176. package/test/embedding-provider.test.ts +0 -49
  177. package/test/enrich.test.ts +0 -209
  178. package/test/eval.test.ts +0 -300
  179. package/test/export-import.test.ts +0 -251
  180. package/test/facets.test.ts +0 -448
  181. package/test/fallback-chain.test.ts +0 -93
  182. package/test/frontier.test.ts +0 -485
  183. package/test/governance.test.ts +0 -147
  184. package/test/graph-retrieval.test.ts +0 -186
  185. package/test/graph.test.ts +0 -160
  186. package/test/helpers/mocks.ts +0 -40
  187. package/test/hybrid-search.test.ts +0 -145
  188. package/test/index-persistence.test.ts +0 -124
  189. package/test/integration.test.ts +0 -265
  190. package/test/leases.test.ts +0 -399
  191. package/test/mcp-prompts.test.ts +0 -218
  192. package/test/mcp-resources.test.ts +0 -286
  193. package/test/mcp-standalone.test.ts +0 -113
  194. package/test/mesh.test.ts +0 -700
  195. package/test/privacy.test.ts +0 -87
  196. package/test/profile.test.ts +0 -161
  197. package/test/query-expansion.test.ts +0 -154
  198. package/test/relations.test.ts +0 -198
  199. package/test/retention.test.ts +0 -245
  200. package/test/routines.test.ts +0 -497
  201. package/test/schema-fingerprint.test.ts +0 -81
  202. package/test/schema.test.ts +0 -42
  203. package/test/search-index.test.ts +0 -128
  204. package/test/sentinels.test.ts +0 -626
  205. package/test/signals.test.ts +0 -410
  206. package/test/sketches.test.ts +0 -549
  207. package/test/sliding-window.test.ts +0 -199
  208. package/test/smart-search.test.ts +0 -169
  209. package/test/snapshot.test.ts +0 -165
  210. package/test/team.test.ts +0 -156
  211. package/test/temporal-graph.test.ts +0 -378
  212. package/test/timeline.test.ts +0 -148
  213. package/test/vector-index.test.ts +0 -79
  214. package/test/verify.test.ts +0 -209
  215. package/test/xml.test.ts +0 -65
  216. package/tsconfig.json +0 -22
  217. package/tsdown.config.ts +0 -62
@@ -1,45 +0,0 @@
1
- import type { EmbeddingProvider } from "../../types.js";
2
- import { getEnvVar } from "../../config.js";
3
-
4
- const API_URL = "https://api.openai.com/v1/embeddings";
5
-
6
- export class OpenAIEmbeddingProvider implements EmbeddingProvider {
7
- readonly name = "openai";
8
- readonly dimensions = 1536;
9
- private apiKey: string;
10
-
11
- constructor(apiKey?: string) {
12
- this.apiKey = apiKey || getEnvVar("OPENAI_API_KEY") || "";
13
- if (!this.apiKey) throw new Error("OPENAI_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: "text-embedding-3-small",
30
- input: texts,
31
- }),
32
- });
33
-
34
- if (!response.ok) {
35
- const err = await response.text();
36
- throw new Error(`OpenAI embedding failed (${response.status}): ${err}`);
37
- }
38
-
39
- const data = (await response.json()) as {
40
- data: Array<{ embedding: number[] }>;
41
- };
42
-
43
- return data.data.map((d) => new Float32Array(d.embedding));
44
- }
45
- }
@@ -1,51 +0,0 @@
1
- import type { EmbeddingProvider } from "../../types.js";
2
- import { getEnvVar } from "../../config.js";
3
-
4
- const API_URL = "https://openrouter.ai/api/v1/embeddings";
5
-
6
- export class OpenRouterEmbeddingProvider implements EmbeddingProvider {
7
- readonly name = "openrouter";
8
- readonly dimensions = 1536;
9
- private apiKey: string;
10
- private model: string;
11
-
12
- constructor(apiKey?: string) {
13
- this.apiKey = apiKey || getEnvVar("OPENROUTER_API_KEY") || "";
14
- if (!this.apiKey) throw new Error("OPENROUTER_API_KEY is required");
15
- this.model =
16
- getEnvVar("OPENROUTER_EMBEDDING_MODEL") ||
17
- "openai/text-embedding-3-small";
18
- }
19
-
20
- async embed(text: string): Promise<Float32Array> {
21
- const [result] = await this.embedBatch([text]);
22
- return result;
23
- }
24
-
25
- async embedBatch(texts: string[]): Promise<Float32Array[]> {
26
- const response = await fetch(API_URL, {
27
- method: "POST",
28
- headers: {
29
- Authorization: `Bearer ${this.apiKey}`,
30
- "Content-Type": "application/json",
31
- },
32
- body: JSON.stringify({
33
- model: this.model,
34
- input: texts,
35
- }),
36
- });
37
-
38
- if (!response.ok) {
39
- const err = await response.text();
40
- throw new Error(
41
- `OpenRouter embedding failed (${response.status}): ${err}`,
42
- );
43
- }
44
-
45
- const data = (await response.json()) as {
46
- data: Array<{ embedding: number[] }>;
47
- };
48
-
49
- return data.data.map((d) => new Float32Array(d.embedding));
50
- }
51
- }
@@ -1,46 +0,0 @@
1
- import type { EmbeddingProvider } from "../../types.js";
2
- import { getEnvVar } from "../../config.js";
3
-
4
- const API_URL = "https://api.voyageai.com/v1/embeddings";
5
-
6
- export class VoyageEmbeddingProvider implements EmbeddingProvider {
7
- readonly name = "voyage";
8
- readonly dimensions = 1024;
9
- private apiKey: string;
10
-
11
- constructor(apiKey?: string) {
12
- this.apiKey = apiKey || getEnvVar("VOYAGE_API_KEY") || "";
13
- if (!this.apiKey) throw new Error("VOYAGE_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: "voyage-code-3",
30
- input: texts,
31
- input_type: "document",
32
- }),
33
- });
34
-
35
- if (!response.ok) {
36
- const err = await response.text();
37
- throw new Error(`Voyage embedding failed (${response.status}): ${err}`);
38
- }
39
-
40
- const data = (await response.json()) as {
41
- data: Array<{ embedding: number[] }>;
42
- };
43
-
44
- return data.data.map((d) => new Float32Array(d.embedding));
45
- }
46
- }
@@ -1,31 +0,0 @@
1
- import type { MemoryProvider } from "../types.js";
2
-
3
- export class FallbackChainProvider implements MemoryProvider {
4
- name: string;
5
-
6
- constructor(private providers: MemoryProvider[]) {
7
- this.name = `fallback(${providers.map((p) => p.name).join(" -> ")})`;
8
- }
9
-
10
- async compress(systemPrompt: string, userPrompt: string): Promise<string> {
11
- return this.tryAll((p) => p.compress(systemPrompt, userPrompt));
12
- }
13
-
14
- async summarize(systemPrompt: string, userPrompt: string): Promise<string> {
15
- return this.tryAll((p) => p.summarize(systemPrompt, userPrompt));
16
- }
17
-
18
- private async tryAll(
19
- fn: (p: MemoryProvider) => Promise<string>,
20
- ): Promise<string> {
21
- let lastError: Error | null = null;
22
- for (const provider of this.providers) {
23
- try {
24
- return await fn(provider);
25
- } catch (err) {
26
- lastError = err instanceof Error ? err : new Error(String(err));
27
- }
28
- }
29
- throw lastError || new Error("No providers available");
30
- }
31
- }
@@ -1,84 +0,0 @@
1
- import type {
2
- MemoryProvider,
3
- ProviderConfig,
4
- FallbackConfig,
5
- } from "../types.js";
6
- import { AgentSDKProvider } from "./agent-sdk.js";
7
- import { AnthropicProvider } from "./anthropic.js";
8
- import { OpenRouterProvider } from "./openrouter.js";
9
- import { ResilientProvider } from "./resilient.js";
10
- import { FallbackChainProvider } from "./fallback-chain.js";
11
- import { getEnvVar } from "../config.js";
12
-
13
- export { createEmbeddingProvider } from "./embedding/index.js";
14
-
15
- function requireEnvVar(key: string): string {
16
- const value = getEnvVar(key);
17
- if (!value) {
18
- throw new Error(
19
- `Missing required environment variable: ${key}. Set it in ~/.agentmemory/.env or as an environment variable.`,
20
- );
21
- }
22
- return value;
23
- }
24
-
25
- export function createProvider(config: ProviderConfig): ResilientProvider {
26
- return new ResilientProvider(createBaseProvider(config));
27
- }
28
-
29
- export function createFallbackProvider(
30
- config: ProviderConfig,
31
- fallbackConfig: FallbackConfig,
32
- ): ResilientProvider {
33
- if (fallbackConfig.providers.length === 0) {
34
- return createProvider(config);
35
- }
36
-
37
- const providers: MemoryProvider[] = [createBaseProvider(config)];
38
- for (const providerType of fallbackConfig.providers) {
39
- if (providerType === config.provider) continue;
40
- try {
41
- const fbConfig: ProviderConfig = {
42
- provider: providerType,
43
- model: config.model,
44
- maxTokens: config.maxTokens,
45
- };
46
- providers.push(createBaseProvider(fbConfig));
47
- } catch {
48
- // skip unavailable fallback providers
49
- }
50
- }
51
-
52
- if (providers.length > 1) {
53
- return new ResilientProvider(new FallbackChainProvider(providers));
54
- }
55
- return new ResilientProvider(providers[0]);
56
- }
57
-
58
- function createBaseProvider(config: ProviderConfig): MemoryProvider {
59
- switch (config.provider) {
60
- case "anthropic":
61
- return new AnthropicProvider(
62
- requireEnvVar("ANTHROPIC_API_KEY"),
63
- config.model,
64
- config.maxTokens,
65
- );
66
- case "gemini":
67
- return new OpenRouterProvider(
68
- requireEnvVar("GEMINI_API_KEY"),
69
- config.model,
70
- config.maxTokens,
71
- "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions",
72
- );
73
- case "openrouter":
74
- return new OpenRouterProvider(
75
- requireEnvVar("OPENROUTER_API_KEY"),
76
- config.model,
77
- config.maxTokens,
78
- "https://openrouter.ai/api/v1/chat/completions",
79
- );
80
- case "agent-sdk":
81
- default:
82
- return new AgentSDKProvider();
83
- }
84
- }
@@ -1,71 +0,0 @@
1
- import type { MemoryProvider } from "../types.js";
2
-
3
- export class OpenRouterProvider implements MemoryProvider {
4
- name: string;
5
- private apiKey: string;
6
- private model: string;
7
- private maxTokens: number;
8
- private baseUrl: string;
9
-
10
- constructor(
11
- apiKey: string,
12
- model: string,
13
- maxTokens: number,
14
- baseUrl: string,
15
- ) {
16
- this.apiKey = apiKey;
17
- this.model = model;
18
- this.maxTokens = maxTokens;
19
- this.baseUrl = baseUrl;
20
- this.name = baseUrl.includes("openrouter") ? "openrouter" : "gemini";
21
- }
22
-
23
- async compress(systemPrompt: string, userPrompt: string): Promise<string> {
24
- return this.call(systemPrompt, userPrompt);
25
- }
26
-
27
- async summarize(systemPrompt: string, userPrompt: string): Promise<string> {
28
- return this.call(systemPrompt, userPrompt);
29
- }
30
-
31
- private async call(
32
- systemPrompt: string,
33
- userPrompt: string,
34
- ): Promise<string> {
35
- const response = await fetch(this.baseUrl, {
36
- method: "POST",
37
- headers: {
38
- "Content-Type": "application/json",
39
- Authorization: `Bearer ${this.apiKey}`,
40
- ...(this.baseUrl.includes("openrouter")
41
- ? { "HTTP-Referer": "https://github.com/rohitg00/agentmemory" }
42
- : {}),
43
- },
44
- body: JSON.stringify({
45
- model: this.model,
46
- max_tokens: this.maxTokens,
47
- messages: [
48
- { role: "system", content: systemPrompt },
49
- { role: "user", content: userPrompt },
50
- ],
51
- }),
52
- });
53
-
54
- if (!response.ok) {
55
- const text = await response.text();
56
- throw new Error(`${this.name} API error (${response.status}): ${text}`);
57
- }
58
-
59
- const data = (await response.json()) as Record<string, unknown>;
60
- const choices = data.choices as
61
- | Array<{ message: { content: string } }>
62
- | undefined;
63
- const content = choices?.[0]?.message?.content;
64
- if (!content) {
65
- throw new Error(
66
- `${this.name} returned unexpected response: ${JSON.stringify(data).slice(0, 200)}`,
67
- );
68
- }
69
- return content;
70
- }
71
- }
@@ -1,37 +0,0 @@
1
- import type { MemoryProvider, CircuitBreakerState } from "../types.js";
2
- import { CircuitBreaker } from "./circuit-breaker.js";
3
-
4
- export class ResilientProvider implements MemoryProvider {
5
- private breaker = new CircuitBreaker();
6
- name: string;
7
-
8
- constructor(private inner: MemoryProvider) {
9
- this.name = `resilient(${inner.name})`;
10
- }
11
-
12
- private async call(fn: () => Promise<string>): Promise<string> {
13
- if (!this.breaker.isAllowed) {
14
- throw new Error("circuit_breaker_open");
15
- }
16
- try {
17
- const result = await fn();
18
- this.breaker.recordSuccess();
19
- return result;
20
- } catch (err) {
21
- this.breaker.recordFailure();
22
- throw err;
23
- }
24
- }
25
-
26
- async compress(systemPrompt: string, userPrompt: string): Promise<string> {
27
- return this.call(() => this.inner.compress(systemPrompt, userPrompt));
28
- }
29
-
30
- async summarize(systemPrompt: string, userPrompt: string): Promise<string> {
31
- return this.call(() => this.inner.summarize(systemPrompt, userPrompt));
32
- }
33
-
34
- get circuitState(): CircuitBreakerState {
35
- return this.breaker.getState();
36
- }
37
- }
@@ -1,295 +0,0 @@
1
- import { SearchIndex } from "./search-index.js";
2
- import { VectorIndex } from "./vector-index.js";
3
- import type {
4
- EmbeddingProvider,
5
- HybridSearchResult,
6
- CompressedObservation,
7
- QueryExpansion,
8
- } from "../types.js";
9
- import type { StateKV } from "./kv.js";
10
- import { KV } from "./schema.js";
11
- import {
12
- GraphRetrieval,
13
- type GraphRetrievalResult,
14
- } from "../functions/graph-retrieval.js";
15
- import { extractEntitiesFromQuery } from "../functions/query-expansion.js";
16
-
17
- const RRF_K = 60;
18
-
19
- export class HybridSearch {
20
- private graphRetrieval: GraphRetrieval;
21
-
22
- constructor(
23
- private bm25: SearchIndex,
24
- private vector: VectorIndex | null,
25
- private embeddingProvider: EmbeddingProvider | null,
26
- private kv: StateKV,
27
- private bm25Weight = 0.4,
28
- private vectorWeight = 0.6,
29
- private graphWeight = 0.3,
30
- ) {
31
- this.graphRetrieval = new GraphRetrieval(kv);
32
- }
33
-
34
- async search(query: string, limit = 20): Promise<HybridSearchResult[]> {
35
- return this.tripleStreamSearch(query, limit);
36
- }
37
-
38
- async searchWithExpansion(
39
- query: string,
40
- limit: number,
41
- expansion: QueryExpansion,
42
- ): Promise<HybridSearchResult[]> {
43
- const allQueries = [
44
- query,
45
- ...expansion.reformulations,
46
- ...expansion.temporalConcretizations,
47
- ];
48
-
49
- const allEntities = [
50
- ...expansion.entityExtractions,
51
- ...extractEntitiesFromQuery(query),
52
- ];
53
-
54
- const resultSets = await Promise.all(
55
- allQueries.map((q) => this.tripleStreamSearch(q, limit, allEntities)),
56
- );
57
-
58
- const merged = new Map<string, HybridSearchResult>();
59
- for (const results of resultSets) {
60
- for (const r of results) {
61
- const existing = merged.get(r.observation.id);
62
- if (!existing || r.combinedScore > existing.combinedScore) {
63
- merged.set(r.observation.id, r);
64
- }
65
- }
66
- }
67
-
68
- return Array.from(merged.values())
69
- .sort((a, b) => b.combinedScore - a.combinedScore)
70
- .slice(0, limit);
71
- }
72
-
73
- private async tripleStreamSearch(
74
- query: string,
75
- limit: number,
76
- entityHints?: string[],
77
- ): Promise<HybridSearchResult[]> {
78
- const bm25Results = this.bm25.search(query, limit * 2);
79
-
80
- let vectorResults: Array<{
81
- obsId: string;
82
- sessionId: string;
83
- score: number;
84
- }> = [];
85
- let queryEmbedding: Float32Array | null = null;
86
-
87
- if (this.vector && this.embeddingProvider && this.vector.size > 0) {
88
- try {
89
- queryEmbedding = await this.embeddingProvider.embed(query);
90
- vectorResults = this.vector.search(queryEmbedding, limit * 2);
91
- } catch {
92
- // fall through to BM25-only
93
- }
94
- }
95
-
96
- const entities =
97
- entityHints && entityHints.length > 0
98
- ? entityHints
99
- : extractEntitiesFromQuery(query);
100
- let graphResults: GraphRetrievalResult[] = [];
101
- if (entities.length > 0) {
102
- try {
103
- graphResults = await this.graphRetrieval.searchByEntities(
104
- entities,
105
- 2,
106
- limit,
107
- );
108
- } catch {
109
- // graph search is best-effort
110
- }
111
- }
112
-
113
- const topVectorObs = vectorResults.slice(0, 5).map((r) => r.obsId);
114
- if (topVectorObs.length > 0) {
115
- try {
116
- const expansionResults =
117
- await this.graphRetrieval.expandFromChunks(topVectorObs, 1, 5);
118
- graphResults = [...graphResults, ...expansionResults];
119
- } catch {
120
- // expansion is best-effort
121
- }
122
- }
123
-
124
- const scores = new Map<
125
- string,
126
- {
127
- bm25Rank: number;
128
- vectorRank: number;
129
- graphRank: number;
130
- sessionId: string;
131
- bm25Score: number;
132
- vectorScore: number;
133
- graphScore: number;
134
- graphContext?: string;
135
- }
136
- >();
137
-
138
- bm25Results.forEach((r, i) => {
139
- scores.set(r.obsId, {
140
- bm25Rank: i + 1,
141
- vectorRank: Infinity,
142
- graphRank: Infinity,
143
- sessionId: r.sessionId,
144
- bm25Score: r.score,
145
- vectorScore: 0,
146
- graphScore: 0,
147
- });
148
- });
149
-
150
- vectorResults.forEach((r, i) => {
151
- const existing = scores.get(r.obsId);
152
- if (existing) {
153
- existing.vectorRank = i + 1;
154
- existing.vectorScore = r.score;
155
- } else {
156
- scores.set(r.obsId, {
157
- bm25Rank: Infinity,
158
- vectorRank: i + 1,
159
- graphRank: Infinity,
160
- sessionId: r.sessionId,
161
- bm25Score: 0,
162
- vectorScore: r.score,
163
- graphScore: 0,
164
- });
165
- }
166
- });
167
-
168
- graphResults.forEach((r, i) => {
169
- const existing = scores.get(r.obsId);
170
- if (existing) {
171
- existing.graphRank = Math.min(existing.graphRank, i + 1);
172
- existing.graphScore = Math.max(existing.graphScore, r.score);
173
- if (r.graphContext && !existing.graphContext) {
174
- existing.graphContext = r.graphContext;
175
- }
176
- } else {
177
- scores.set(r.obsId, {
178
- bm25Rank: Infinity,
179
- vectorRank: Infinity,
180
- graphRank: i + 1,
181
- sessionId: r.sessionId,
182
- bm25Score: 0,
183
- vectorScore: 0,
184
- graphScore: r.score,
185
- graphContext: r.graphContext,
186
- });
187
- }
188
- });
189
-
190
- const hasVector = vectorResults.length > 0;
191
- const hasGraph = graphResults.length > 0;
192
-
193
- let effectiveBm25W = this.bm25Weight;
194
- let effectiveVectorW = hasVector ? this.vectorWeight : 0;
195
- let effectiveGraphW = hasGraph ? this.graphWeight : 0;
196
-
197
- const totalW = effectiveBm25W + effectiveVectorW + effectiveGraphW;
198
- if (totalW > 0) {
199
- effectiveBm25W /= totalW;
200
- effectiveVectorW /= totalW;
201
- effectiveGraphW /= totalW;
202
- }
203
-
204
- const combined = Array.from(scores.entries()).map(([obsId, s]) => ({
205
- obsId,
206
- sessionId: s.sessionId,
207
- bm25Score: s.bm25Score,
208
- vectorScore: s.vectorScore,
209
- graphScore: s.graphScore,
210
- graphContext: s.graphContext,
211
- combinedScore:
212
- effectiveBm25W * (1 / (RRF_K + s.bm25Rank)) +
213
- effectiveVectorW * (1 / (RRF_K + s.vectorRank)) +
214
- effectiveGraphW * (1 / (RRF_K + s.graphRank)),
215
- }));
216
-
217
- combined.sort((a, b) => b.combinedScore - a.combinedScore);
218
- const diversified = this.diversifyBySession(combined, limit);
219
- return this.enrichResults(diversified, limit);
220
- }
221
-
222
- private diversifyBySession(
223
- results: Array<{
224
- obsId: string;
225
- sessionId: string;
226
- bm25Score: number;
227
- vectorScore: number;
228
- graphScore: number;
229
- combinedScore: number;
230
- graphContext?: string;
231
- }>,
232
- limit: number,
233
- maxPerSession = 3,
234
- ): typeof results {
235
- const selected: typeof results = [];
236
- const sessionCounts = new Map<string, number>();
237
-
238
- for (const r of results) {
239
- const count = sessionCounts.get(r.sessionId) || 0;
240
- if (count >= maxPerSession) continue;
241
- selected.push(r);
242
- sessionCounts.set(r.sessionId, count + 1);
243
- if (selected.length >= limit) break;
244
- }
245
-
246
- if (selected.length < limit) {
247
- for (const r of results) {
248
- if (selected.length >= limit) break;
249
- if (!selected.some(s => s.obsId === r.obsId)) {
250
- selected.push(r);
251
- }
252
- }
253
- }
254
-
255
- return selected;
256
- }
257
-
258
- private async enrichResults(
259
- results: Array<{
260
- obsId: string;
261
- sessionId: string;
262
- bm25Score: number;
263
- vectorScore: number;
264
- graphScore: number;
265
- combinedScore: number;
266
- graphContext?: string;
267
- }>,
268
- limit: number,
269
- ): Promise<HybridSearchResult[]> {
270
- const sliced = results.slice(0, limit);
271
- const observations = await Promise.all(
272
- sliced.map((r) =>
273
- this.kv
274
- .get<CompressedObservation>(KV.observations(r.sessionId), r.obsId)
275
- .catch(() => null),
276
- ),
277
- );
278
- const enriched: HybridSearchResult[] = [];
279
- for (let i = 0; i < sliced.length; i++) {
280
- const obs = observations[i];
281
- if (obs) {
282
- enriched.push({
283
- observation: obs,
284
- bm25Score: sliced[i].bm25Score,
285
- vectorScore: sliced[i].vectorScore,
286
- graphScore: sliced[i].graphScore,
287
- combinedScore: sliced[i].combinedScore,
288
- sessionId: sliced[i].sessionId,
289
- graphContext: sliced[i].graphContext,
290
- });
291
- }
292
- }
293
- return enriched;
294
- }
295
- }