memorix 1.2.0 → 1.2.2

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 (212) hide show
  1. package/CHANGELOG.md +30 -1
  2. package/README.md +18 -4
  3. package/README.zh-CN.md +18 -4
  4. package/TEAM.md +86 -86
  5. package/dist/cli/index.js +15919 -14055
  6. package/dist/cli/index.js.map +1 -1
  7. package/dist/index.js +1997 -1021
  8. package/dist/index.js.map +1 -1
  9. package/dist/maintenance-runner.d.ts +1 -1
  10. package/dist/maintenance-runner.js +8481 -8005
  11. package/dist/maintenance-runner.js.map +1 -1
  12. package/dist/memcode-runtime/CHANGELOG.md +30 -1
  13. package/dist/sdk.d.ts +7 -2
  14. package/dist/sdk.js +2022 -1024
  15. package/dist/sdk.js.map +1 -1
  16. package/dist/types.d.ts +49 -1
  17. package/dist/types.js.map +1 -1
  18. package/docs/1.2.2-MEMORY-CONTROL-PLANE.md +434 -0
  19. package/docs/AGENT_OPERATOR_PLAYBOOK.md +4 -0
  20. package/docs/API_REFERENCE.md +27 -5
  21. package/docs/DESIGN_DECISIONS.md +357 -357
  22. package/docs/DEVELOPMENT.md +4 -0
  23. package/docs/README.md +1 -1
  24. package/docs/SETUP.md +7 -1
  25. package/docs/dev-log/progress.txt +91 -11
  26. package/docs/knowledge/workflows/memorix-release.md +57 -0
  27. package/package.json +1 -1
  28. package/plugins/codex/memorix/.codex-plugin/plugin.json +1 -1
  29. package/src/audit/index.ts +156 -156
  30. package/src/cli/command-guide.ts +192 -0
  31. package/src/cli/commands/audit-list.ts +89 -89
  32. package/src/cli/commands/audit.ts +9 -4
  33. package/src/cli/commands/background.ts +659 -659
  34. package/src/cli/commands/cleanup.ts +5 -1
  35. package/src/cli/commands/codegraph.ts +17 -8
  36. package/src/cli/commands/context.ts +3 -2
  37. package/src/cli/commands/doctor.ts +4 -2
  38. package/src/cli/commands/explain.ts +9 -3
  39. package/src/cli/commands/formation.ts +48 -48
  40. package/src/cli/commands/git-hook-install.ts +111 -111
  41. package/src/cli/commands/handoff.ts +75 -61
  42. package/src/cli/commands/hooks-status.ts +63 -63
  43. package/src/cli/commands/identity.ts +116 -0
  44. package/src/cli/commands/ingest-commit.ts +153 -153
  45. package/src/cli/commands/ingest-image.ts +71 -69
  46. package/src/cli/commands/ingest-log.ts +180 -180
  47. package/src/cli/commands/ingest.ts +44 -44
  48. package/src/cli/commands/integrate-shared.ts +15 -15
  49. package/src/cli/commands/knowledge.ts +40 -0
  50. package/src/cli/commands/lock.ts +93 -92
  51. package/src/cli/commands/memory.ts +58 -21
  52. package/src/cli/commands/message.ts +123 -118
  53. package/src/cli/commands/operator-shared.ts +98 -3
  54. package/src/cli/commands/poll.ts +74 -64
  55. package/src/cli/commands/purge-all-memory.ts +85 -85
  56. package/src/cli/commands/purge-project-memory.ts +83 -83
  57. package/src/cli/commands/reasoning.ts +135 -121
  58. package/src/cli/commands/retention.ts +9 -4
  59. package/src/cli/commands/serve-http.ts +22 -43
  60. package/src/cli/commands/serve-shared.ts +118 -118
  61. package/src/cli/commands/session.ts +29 -3
  62. package/src/cli/commands/setup.ts +9 -3
  63. package/src/cli/commands/skills.ts +124 -119
  64. package/src/cli/commands/status.ts +4 -3
  65. package/src/cli/commands/task.ts +193 -184
  66. package/src/cli/commands/team.ts +14 -10
  67. package/src/cli/commands/transfer.ts +108 -55
  68. package/src/cli/commands/uninstall-project-artifacts.ts +85 -85
  69. package/src/cli/identity.ts +89 -0
  70. package/src/cli/index.ts +96 -19
  71. package/src/cli/invocation.ts +115 -0
  72. package/src/cli/tui/ChatView.tsx +234 -234
  73. package/src/cli/tui/CommandBar.tsx +312 -312
  74. package/src/cli/tui/ContextRail.tsx +118 -118
  75. package/src/cli/tui/HeaderBar.tsx +72 -72
  76. package/src/cli/tui/LogoBanner.tsx +51 -51
  77. package/src/cli/tui/Sidebar.tsx +179 -179
  78. package/src/cli/tui/chat-service.ts +41 -18
  79. package/src/cli/tui/data.ts +23 -44
  80. package/src/cli/tui/index.ts +41 -41
  81. package/src/cli/tui/markdown-render.tsx +371 -371
  82. package/src/cli/tui/operator-context.ts +60 -0
  83. package/src/cli/tui/use-mouse.ts +157 -157
  84. package/src/cli/tui/useNavigation.ts +56 -56
  85. package/src/cli/tui/views/MemoryView.tsx +10 -8
  86. package/src/cli/update-checker.ts +211 -211
  87. package/src/cli/version.ts +7 -7
  88. package/src/cli/workbench.ts +1 -1
  89. package/src/codegraph/auto-context.ts +34 -17
  90. package/src/codegraph/context-pack.ts +1 -0
  91. package/src/codegraph/current-facts.ts +19 -1
  92. package/src/codegraph/project-context.ts +2 -0
  93. package/src/codegraph/task-lens.ts +49 -5
  94. package/src/compact/engine.ts +26 -10
  95. package/src/compact/index-format.ts +25 -2
  96. package/src/compact/token-budget.ts +74 -74
  97. package/src/dashboard/project-classification.ts +64 -64
  98. package/src/dashboard/server.ts +58 -52
  99. package/src/embedding/fastembed-provider.ts +142 -142
  100. package/src/embedding/transformers-provider.ts +111 -111
  101. package/src/git/extractor.ts +209 -209
  102. package/src/git/hooks-path.ts +85 -85
  103. package/src/hooks/admission.ts +117 -0
  104. package/src/hooks/handler.ts +98 -91
  105. package/src/hooks/pattern-detector.ts +173 -173
  106. package/src/hooks/significance-filter.ts +250 -250
  107. package/src/knowledge/claims.ts +51 -1
  108. package/src/knowledge/context-assembly.ts +97 -0
  109. package/src/knowledge/types.ts +1 -0
  110. package/src/knowledge/workflows.ts +34 -3
  111. package/src/knowledge/workset.ts +179 -10
  112. package/src/llm/memory-manager.ts +328 -328
  113. package/src/llm/provider.ts +885 -885
  114. package/src/llm/quality.ts +248 -248
  115. package/src/memory/admission.ts +57 -0
  116. package/src/memory/attribution-guard.ts +249 -249
  117. package/src/memory/auto-relations.ts +21 -0
  118. package/src/memory/consolidation.ts +13 -2
  119. package/src/memory/disclosure-policy.ts +140 -135
  120. package/src/memory/entity-extractor.ts +197 -197
  121. package/src/memory/export-import.ts +11 -3
  122. package/src/memory/formation/evaluate.ts +217 -217
  123. package/src/memory/formation/extract.ts +361 -361
  124. package/src/memory/formation/index.ts +417 -417
  125. package/src/memory/formation/resolve.ts +344 -344
  126. package/src/memory/formation/types.ts +315 -315
  127. package/src/memory/freshness.ts +122 -122
  128. package/src/memory/graph-context.ts +8 -2
  129. package/src/memory/graph-scope.ts +46 -0
  130. package/src/memory/graph.ts +197 -197
  131. package/src/memory/observations.ts +162 -4
  132. package/src/memory/quality-audit.ts +2 -0
  133. package/src/memory/refs.ts +94 -94
  134. package/src/memory/retention.ts +22 -2
  135. package/src/memory/secret-filter.ts +79 -79
  136. package/src/memory/session.ts +5 -2
  137. package/src/memory/visibility.ts +80 -0
  138. package/src/multimodal/image-loader.ts +143 -143
  139. package/src/orchestrate/adapters/claude-stream.ts +192 -192
  140. package/src/orchestrate/adapters/claude.ts +111 -111
  141. package/src/orchestrate/adapters/codex-stream.ts +134 -134
  142. package/src/orchestrate/adapters/codex.ts +41 -41
  143. package/src/orchestrate/adapters/gemini-stream.ts +166 -166
  144. package/src/orchestrate/adapters/gemini.ts +42 -42
  145. package/src/orchestrate/adapters/index.ts +73 -73
  146. package/src/orchestrate/adapters/opencode-stream.ts +143 -143
  147. package/src/orchestrate/adapters/opencode.ts +47 -47
  148. package/src/orchestrate/adapters/spawn-helper.ts +286 -286
  149. package/src/orchestrate/adapters/types.ts +77 -77
  150. package/src/orchestrate/capability-router.ts +284 -284
  151. package/src/orchestrate/context-compact.ts +188 -188
  152. package/src/orchestrate/cost-tracker.ts +219 -219
  153. package/src/orchestrate/error-recovery.ts +191 -191
  154. package/src/orchestrate/evidence.ts +140 -140
  155. package/src/orchestrate/ledger.ts +110 -110
  156. package/src/orchestrate/memorix-bridge.ts +378 -340
  157. package/src/orchestrate/output-budget.ts +80 -80
  158. package/src/orchestrate/permission.ts +152 -152
  159. package/src/orchestrate/pipeline-trace.ts +131 -131
  160. package/src/orchestrate/prompt-builder.ts +155 -155
  161. package/src/orchestrate/ring-buffer.ts +37 -37
  162. package/src/orchestrate/task-graph.ts +389 -389
  163. package/src/orchestrate/verify-gate.ts +33 -10
  164. package/src/orchestrate/worktree.ts +232 -232
  165. package/src/project/aliases.ts +374 -374
  166. package/src/project/detector.ts +268 -268
  167. package/src/rules/adapters/claude-code.ts +99 -99
  168. package/src/rules/adapters/codex.ts +97 -97
  169. package/src/rules/adapters/copilot.ts +124 -124
  170. package/src/rules/adapters/cursor.ts +114 -114
  171. package/src/rules/adapters/kiro.ts +126 -126
  172. package/src/rules/adapters/trae.ts +56 -56
  173. package/src/rules/adapters/windsurf.ts +83 -83
  174. package/src/rules/syncer.ts +235 -235
  175. package/src/runtime/control-plane-maintenance.ts +1 -0
  176. package/src/runtime/isolated-maintenance.ts +1 -0
  177. package/src/runtime/lifecycle.ts +18 -0
  178. package/src/runtime/maintenance-jobs.ts +1 -0
  179. package/src/runtime/maintenance-runner.ts +2 -0
  180. package/src/runtime/project-maintenance.ts +89 -0
  181. package/src/sdk.ts +334 -304
  182. package/src/search/intent-detector.ts +289 -289
  183. package/src/search/query-expansion.ts +52 -52
  184. package/src/server/formation-timeout.ts +27 -27
  185. package/src/server.ts +334 -93
  186. package/src/skills/mini-skills.ts +386 -386
  187. package/src/store/chat-store.ts +119 -119
  188. package/src/store/graph-store.ts +249 -249
  189. package/src/store/mini-skill-store.ts +349 -349
  190. package/src/store/orama-store.ts +61 -6
  191. package/src/store/persistence-json.ts +212 -212
  192. package/src/store/persistence.ts +291 -291
  193. package/src/store/project-affinity.ts +195 -195
  194. package/src/store/sqlite-db.ts +23 -1
  195. package/src/store/sqlite-store.ts +12 -2
  196. package/src/team/event-bus.ts +76 -76
  197. package/src/team/file-locks.ts +173 -173
  198. package/src/team/handoff.ts +168 -161
  199. package/src/team/messages.ts +203 -203
  200. package/src/team/poll.ts +132 -132
  201. package/src/team/tasks.ts +211 -211
  202. package/src/types.ts +51 -0
  203. package/src/wiki/generator.ts +2 -0
  204. package/src/workspace/mcp-adapters/codex.ts +191 -191
  205. package/src/workspace/mcp-adapters/copilot.ts +105 -105
  206. package/src/workspace/mcp-adapters/cursor.ts +53 -53
  207. package/src/workspace/mcp-adapters/kiro.ts +64 -64
  208. package/src/workspace/mcp-adapters/opencode.ts +123 -123
  209. package/src/workspace/mcp-adapters/trae.ts +134 -134
  210. package/src/workspace/mcp-adapters/windsurf.ts +91 -91
  211. package/src/workspace/sanitizer.ts +60 -60
  212. package/src/workspace/workflow-sync.ts +131 -131
@@ -1,13 +1,13 @@
1
- /**
2
- * LLM Provider
3
- *
4
- * Abstraction layer for LLM-enhanced memory management.
5
- * Supports OpenAI-compatible APIs (OpenAI, Anthropic via proxy, local models).
6
- *
7
- * This is the optional "premium" path — Memorix works without it,
8
- * but with an LLM configured, memory quality approaches Mem0/Cipher level.
9
- */
10
-
1
+ /**
2
+ * LLM Provider
3
+ *
4
+ * Abstraction layer for LLM-enhanced memory management.
5
+ * Supports OpenAI-compatible APIs (OpenAI, Anthropic via proxy, local models).
6
+ *
7
+ * This is the optional "premium" path — Memorix works without it,
8
+ * but with an LLM configured, memory quality approaches Mem0/Cipher level.
9
+ */
10
+
11
11
  import {
12
12
  getAgentLLMApiKey,
13
13
  getAgentLLMBaseUrl,
@@ -18,878 +18,878 @@ import {
18
18
  getLLMModel,
19
19
  getLLMProvider,
20
20
  } from '../config.js';
21
-
22
- export interface LLMConfig {
23
- provider: 'openai' | 'anthropic' | 'openrouter' | 'custom';
24
- apiKey: string;
25
- model?: string;
26
- baseUrl?: string;
27
- }
28
-
29
- const LLM_TIMEOUT_DEFAULT_MS = 30_000;
30
- const LLM_TIMEOUT_MIN_MS = 1_000;
31
- const LLM_TIMEOUT_MAX_MS = 300_000;
32
- const MAX_LLM_RESPONSE_BYTES = 2 * 1024 * 1024;
33
-
34
- /**
35
- * Parse and validate MEMORIX_LLM_TIMEOUT_MS environment variable.
36
- * - Must be a valid integer in the range 1000–300000ms.
37
- * - Non-integer or out-of-range values log a warning and fall back to the default.
38
- * Default: 30000ms (30s) — allows for proxy routing and cold starts.
39
- */
40
- export function parseLLMTimeoutMs(raw: string | undefined): number {
41
- if (raw === undefined || raw.trim() === '') return LLM_TIMEOUT_DEFAULT_MS;
42
- const parsed = Number(raw);
43
- if (!Number.isInteger(parsed) || Number.isNaN(parsed)) {
44
- console.warn(
45
- `[memorix] MEMORIX_LLM_TIMEOUT_MS="${raw}" is invalid (must be a positive integer between ${LLM_TIMEOUT_MIN_MS}–${LLM_TIMEOUT_MAX_MS}ms). Using default ${LLM_TIMEOUT_DEFAULT_MS}ms.`,
46
- );
47
- return LLM_TIMEOUT_DEFAULT_MS;
48
- }
49
- if (parsed < LLM_TIMEOUT_MIN_MS) return LLM_TIMEOUT_MIN_MS;
50
- if (parsed > LLM_TIMEOUT_MAX_MS) return LLM_TIMEOUT_MAX_MS;
51
- return parsed;
52
- }
53
-
54
- const LLM_CALL_TIMEOUT_MS = parseLLMTimeoutMs(process.env.MEMORIX_LLM_TIMEOUT_MS);
55
-
56
- export interface LLMResponse {
57
- content: string;
58
- usage?: { promptTokens: number; completionTokens: number };
59
- }
60
-
61
- /** A single tool call requested by the LLM */
62
- export interface ToolCall {
63
- id: string;
64
- name: string;
65
- arguments: string; // JSON string
66
- }
67
-
68
- /** Response from callLLMWithTools — may contain text, tool calls, or both */
69
- export interface LLMToolResponse {
70
- content: string;
71
- toolCalls: ToolCall[];
72
- stopReason: 'end_turn' | 'tool_use' | 'stop' | 'unknown';
73
- usage?: { promptTokens: number; completionTokens: number };
74
- }
75
-
76
- /** Streaming event from callLLMWithToolsStream */
77
- export type LLMStreamEvent =
78
- | { type: 'text'; content: string }
79
- | { type: 'tool_call'; toolCall: ToolCall }
80
- | { type: 'done'; response: LLMToolResponse };
81
-
82
- async function readResponseText(response: Response, signal?: AbortSignal, maxBytes = MAX_LLM_RESPONSE_BYTES): Promise<string> {
83
- const contentLength = response.headers.get('content-length');
84
- if (contentLength && Number(contentLength) > maxBytes) {
85
- throw new Error(`LLM response too large (${contentLength} bytes)`);
86
- }
87
-
88
- const reader = response.body?.getReader();
89
- if (!reader) {
90
- signal?.throwIfAborted();
91
- return response.text();
92
- }
93
-
94
- const decoder = new TextDecoder();
95
- const chunks: string[] = [];
96
- let bytesRead = 0;
97
- const abortReader = () => {
98
- void reader.cancel(signal?.reason).catch(() => undefined);
99
- };
100
-
101
- signal?.addEventListener('abort', abortReader, { once: true });
102
-
103
- try {
104
- while (true) {
105
- signal?.throwIfAborted();
106
- const { value, done } = await reader.read();
107
- if (done) break;
108
- signal?.throwIfAborted();
109
- if (!value) continue;
110
- bytesRead += value.byteLength;
111
- if (bytesRead > maxBytes) {
112
- await reader.cancel('response too large').catch(() => undefined);
113
- throw new Error(`LLM response exceeded ${maxBytes} bytes`);
114
- }
115
- chunks.push(decoder.decode(value, { stream: true }));
116
- }
117
-
118
- chunks.push(decoder.decode());
119
- signal?.throwIfAborted();
120
- return chunks.join('');
121
- } finally {
122
- signal?.removeEventListener('abort', abortReader);
123
- reader.releaseLock();
124
- }
125
- }
126
-
127
- async function readResponseJson<T>(response: Response, signal?: AbortSignal, maxBytes = MAX_LLM_RESPONSE_BYTES): Promise<T> {
128
- const text = await readResponseText(response, signal, maxBytes);
129
- return JSON.parse(text) as T;
130
- }
131
-
132
- /**
133
- * Call the LLM with tools in streaming mode.
134
- * Yields text chunks as they arrive, then a final 'done' event with the complete response.
135
- * Tool calls are accumulated and yielded at the end.
136
- */
137
- export async function* callLLMWithToolsStream(
138
- messages: ChatMessage[],
139
- tools: ToolDefinition[],
140
- ): AsyncGenerator<LLMStreamEvent, void, undefined> {
141
- if (!currentConfig) {
142
- throw new Error('LLM not configured. Set MEMORIX_LLM_API_KEY or OPENAI_API_KEY.');
143
- }
144
-
145
- if (currentConfig.provider === 'anthropic') {
146
- yield* callAnthropicWithToolsStream(messages, tools);
147
- return;
148
- }
149
-
150
- yield* callOpenAIWithToolsStream(messages, tools);
151
- }
152
-
153
- /** Tool definition for LLM function calling */
154
- export interface ToolDefinition {
155
- name: string;
156
- description: string;
157
- parameters: Record<string, unknown>; // JSON Schema object
158
- }
159
-
160
- /** Chat message for multi-turn tool-use conversations */
161
- export interface ChatMessage {
162
- role: 'system' | 'user' | 'assistant' | 'tool';
163
- content: string;
164
- toolCallId?: string; // for role='tool': which call this result is for
165
- toolCalls?: ToolCall[]; // for role='assistant': tool calls made
166
- name?: string; // for role='tool': function name
167
- }
168
-
169
- /** Provider defaults per provider type */
170
- const PROVIDER_DEFAULTS: Record<string, { baseUrl: string; model: string }> = {
171
- openai: { baseUrl: 'https://api.openai.com/v1', model: 'gpt-4.1-nano' },
172
- anthropic: { baseUrl: 'https://api.anthropic.com/v1', model: 'claude-3-5-haiku-latest' },
173
- openrouter: { baseUrl: 'https://openrouter.ai/api/v1', model: 'openai/gpt-4.1-nano' },
174
- custom: { baseUrl: 'http://localhost:11434/v1', model: 'llama3' },
175
- };
176
-
177
- let currentConfig: LLMConfig | null = null;
178
-
179
- export type LLMConfigScope = 'memory' | 'agent';
180
-
181
- export interface InitLLMOptions {
182
- scope?: LLMConfigScope;
183
- }
184
-
185
- /**
186
- * Initialize the LLM provider from environment variables.
187
- * Returns null if no API key is configured — Memorix gracefully degrades.
188
- */
189
- export function initLLM(options: InitLLMOptions = {}): LLMConfig | null {
190
- const scope = options.scope ?? 'memory';
191
- const apiKey = scope === 'agent' ? getAgentLLMApiKey() : getLLMApiKey();
192
- if (!apiKey) {
193
- currentConfig = null;
194
- return null;
195
- }
196
-
197
- const provider = (scope === 'agent' ? getAgentLLMProvider() : getLLMProvider()) as LLMConfig['provider'];
198
- const defaults = PROVIDER_DEFAULTS[provider] ?? PROVIDER_DEFAULTS.openai;
199
-
200
- currentConfig = {
201
- provider,
202
- apiKey,
203
- model: scope === 'agent' ? getAgentLLMModel(defaults.model) : getLLMModel(defaults.model),
204
- baseUrl: scope === 'agent' ? getAgentLLMBaseUrl(defaults.baseUrl) : getLLMBaseUrl(defaults.baseUrl),
205
- };
206
-
207
- return currentConfig;
208
- }
209
-
210
- /**
211
- * Check if LLM is available.
212
- */
213
- export function isLLMEnabled(): boolean {
214
- return currentConfig !== null;
215
- }
216
-
217
- /**
218
- * Get current LLM config (for display/debug).
219
- */
220
- export function getLLMConfig(): LLMConfig | null {
221
- return currentConfig;
222
- }
223
-
224
- /**
225
- * Set LLM config directly (for testing or programmatic use).
226
- */
227
- export function setLLMConfig(config: LLMConfig | null): void {
228
- currentConfig = config;
229
- }
230
-
231
- /**
232
- * Call the LLM with a prompt.
233
- * Uses OpenAI-compatible chat completions API (works with OpenRouter, Ollama, etc.)
234
- *
235
- * For Anthropic, we use their Messages API directly.
236
- */
237
- export async function callLLM(
238
- systemPrompt: string,
239
- userMessage: string,
240
- ): Promise<LLMResponse> {
241
- if (!currentConfig) {
242
- throw new Error('LLM not configured. Set MEMORIX_LLM_API_KEY or OPENAI_API_KEY.');
243
- }
244
-
245
- if (currentConfig.provider === 'anthropic') {
246
- return callAnthropic(systemPrompt, userMessage);
247
- }
248
-
249
- return callOpenAICompatible(systemPrompt, userMessage);
250
- }
251
-
252
- /**
253
- * OpenAI-compatible API call (works with OpenAI, OpenRouter, Ollama, etc.)
254
- */
255
- async function callOpenAICompatible(
256
- systemPrompt: string,
257
- userMessage: string,
258
- ): Promise<LLMResponse> {
259
- const config = currentConfig!;
260
- // Auto-fix: append /v1 if baseUrl doesn't end with it (common user mistake)
261
- let base = config.baseUrl!.replace(/\/+$/, '');
262
- if (!base.endsWith('/v1')) base += '/v1';
263
- const url = `${base}/chat/completions`;
264
-
265
- const response = await fetch(url, {
266
- signal: AbortSignal.timeout(LLM_CALL_TIMEOUT_MS),
267
- method: 'POST',
268
- headers: {
269
- 'Content-Type': 'application/json',
270
- 'Authorization': `Bearer ${config.apiKey}`,
271
- },
272
- body: JSON.stringify({
273
- model: config.model,
274
- messages: [
275
- { role: 'system', content: systemPrompt },
276
- { role: 'user', content: userMessage },
277
- ],
278
- temperature: 0.1,
279
- max_tokens: 1024,
280
- }),
281
- });
282
-
283
- if (!response.ok) {
284
- const error = await readResponseText(response, undefined, 64 * 1024).catch(() => 'unknown error');
285
- throw new Error(`LLM API error (${response.status}): ${error}`);
286
- }
287
-
288
- const data = await readResponseJson<{
289
- choices: Array<{ message: { content: string } }>;
290
- usage?: { prompt_tokens: number; completion_tokens: number };
291
- }>(response);
292
-
293
- return {
294
- content: data.choices[0]?.message?.content ?? '',
295
- usage: data.usage ? {
296
- promptTokens: data.usage.prompt_tokens,
297
- completionTokens: data.usage.completion_tokens,
298
- } : undefined,
299
- };
300
- }
301
-
302
- /**
303
- * Anthropic Messages API call.
304
- */
305
- async function callAnthropic(
306
- systemPrompt: string,
307
- userMessage: string,
308
- ): Promise<LLMResponse> {
309
- const config = currentConfig!;
310
- const url = `${config.baseUrl}/messages`;
311
-
312
- const response = await fetch(url, {
313
- signal: AbortSignal.timeout(LLM_CALL_TIMEOUT_MS),
314
- method: 'POST',
315
- headers: {
316
- 'Content-Type': 'application/json',
317
- 'x-api-key': config.apiKey,
318
- 'anthropic-version': '2023-06-01',
319
- },
320
- body: JSON.stringify({
321
- model: config.model,
322
- system: systemPrompt,
323
- messages: [
324
- { role: 'user', content: userMessage },
325
- ],
326
- temperature: 0.1,
327
- max_tokens: 1024,
328
- }),
329
- });
330
-
331
- if (!response.ok) {
332
- const error = await readResponseText(response, undefined, 64 * 1024).catch(() => 'unknown error');
333
- throw new Error(`Anthropic API error (${response.status}): ${error}`);
334
- }
335
-
336
- const data = await readResponseJson<{
337
- content: Array<{ text: string }>;
338
- usage?: { input_tokens: number; output_tokens: number };
339
- }>(response);
340
-
341
- return {
342
- content: data.content[0]?.text ?? '',
343
- usage: data.usage ? {
344
- promptTokens: data.usage.input_tokens,
345
- completionTokens: data.usage.output_tokens,
346
- } : undefined,
347
- };
348
- }
349
-
350
- /**
351
- * Call the LLM with tool definitions (agentic harness pattern).
352
- *
353
- * The LLM can decide to call tools or respond directly.
354
- * Returns structured response with tool_calls for the agentic loop.
355
- */
356
- export async function callLLMWithTools(
357
- messages: ChatMessage[],
358
- tools: ToolDefinition[],
359
- signal?: AbortSignal,
360
- ): Promise<LLMToolResponse> {
361
- if (!currentConfig) {
362
- throw new Error('LLM not configured. Set MEMORIX_LLM_API_KEY or OPENAI_API_KEY.');
363
- }
364
-
365
- if (currentConfig.provider === 'anthropic') {
366
- return callAnthropicWithTools(messages, tools, signal);
367
- }
368
-
369
- return callOpenAIWithTools(messages, tools, signal);
370
- }
371
-
372
- /**
373
- * OpenAI-compatible tool calling (works with OpenAI, OpenRouter, Ollama, etc.)
374
- */
375
- async function callOpenAIWithTools(
376
- messages: ChatMessage[],
377
- tools: ToolDefinition[],
378
- signal?: AbortSignal,
379
- ): Promise<LLMToolResponse> {
380
- const config = currentConfig!;
381
- let base = config.baseUrl!.replace(/\/+$/, '');
382
- if (!base.endsWith('/v1')) base += '/v1';
383
- const url = `${base}/chat/completions`;
384
-
385
- // Convert ChatMessage[] to OpenAI format
386
- const openaiMessages: Array<Record<string, unknown>> = messages.map((msg) => {
387
- if (msg.role === 'tool') {
388
- return { role: 'tool', content: msg.content, tool_call_id: msg.toolCallId };
389
- }
390
- if (msg.role === 'assistant' && msg.toolCalls && msg.toolCalls.length > 0) {
391
- return {
392
- role: 'assistant',
393
- content: msg.content || null,
394
- tool_calls: msg.toolCalls.map((tc) => ({
395
- id: tc.id,
396
- type: 'function',
397
- function: { name: tc.name, arguments: tc.arguments },
398
- })),
399
- };
400
- }
401
- return { role: msg.role, content: msg.content };
402
- });
403
-
404
- const openaiTools = tools.map((t) => ({
405
- type: 'function' as const,
406
- function: { name: t.name, description: t.description, parameters: t.parameters },
407
- }));
408
-
409
- const fetchSignal = signal
410
- ? AbortSignal.any([signal, AbortSignal.timeout(LLM_CALL_TIMEOUT_MS)])
411
- : AbortSignal.timeout(LLM_CALL_TIMEOUT_MS);
412
-
413
- const response = await fetch(url, {
414
- signal: fetchSignal,
415
- method: 'POST',
416
- headers: {
417
- 'Content-Type': 'application/json',
418
- 'Authorization': `Bearer ${config.apiKey}`,
419
- },
420
- body: JSON.stringify({
421
- model: config.model,
422
- messages: openaiMessages,
423
- tools: openaiTools.length > 0 ? openaiTools : undefined,
424
- temperature: 0.3,
425
- max_tokens: 2048,
426
- }),
427
- });
428
-
429
- if (!response.ok) {
430
- const error = await readResponseText(response, signal, 64 * 1024).catch(() => 'unknown error');
431
- throw new Error(`LLM tool-call API error (${response.status}): ${error}`);
432
- }
433
-
434
- const data = await readResponseJson<{
435
- choices: Array<{
436
- message: {
437
- content: string | null;
438
- tool_calls?: Array<{
439
- id: string;
440
- type: string;
441
- function: { name: string; arguments: string };
442
- }>;
443
- };
444
- finish_reason: string;
445
- }>;
446
- usage?: { prompt_tokens: number; completion_tokens: number };
447
- }>(response, signal);
448
-
449
- const choice = data.choices[0];
450
- const content = choice?.message?.content ?? '';
451
- const toolCalls: ToolCall[] = (choice?.message?.tool_calls ?? []).map((tc: { id: string; function: { name: string; arguments: string } }) => ({
452
- id: tc.id,
453
- name: tc.function.name,
454
- arguments: tc.function.arguments,
455
- }));
456
-
457
- const stopReason = choice?.finish_reason === 'tool_calls' ? 'tool_use'
458
- : choice?.finish_reason === 'stop' ? 'stop'
459
- : 'unknown';
460
-
461
- return {
462
- content,
463
- toolCalls,
464
- stopReason,
465
- usage: data.usage ? {
466
- promptTokens: data.usage.prompt_tokens,
467
- completionTokens: data.usage.completion_tokens,
468
- } : undefined,
469
- };
470
- }
471
-
472
- /**
473
- * Anthropic tool calling (Messages API with tool_use).
474
- */
475
- async function callAnthropicWithTools(
476
- messages: ChatMessage[],
477
- tools: ToolDefinition[],
478
- signal?: AbortSignal,
479
- ): Promise<LLMToolResponse> {
480
- const config = currentConfig!;
481
- const url = `${config.baseUrl}/messages`;
482
-
483
- // Separate system message from the rest
484
- const systemContent = messages.find((m) => m.role === 'system')?.content ?? '';
485
- const nonSystemMessages = messages.filter((m) => m.role !== 'system');
486
-
487
- // Convert to Anthropic message format
488
- const anthropicMessages: Array<Record<string, unknown>> = [];
489
- for (const msg of nonSystemMessages) {
490
- if (msg.role === 'user') {
491
- anthropicMessages.push({ role: 'user', content: msg.content });
492
- } else if (msg.role === 'assistant') {
493
- const contentBlocks: Array<Record<string, unknown>> = [];
494
- if (msg.content) contentBlocks.push({ type: 'text', text: msg.content });
495
- if (msg.toolCalls) {
496
- for (const tc of msg.toolCalls) {
497
- contentBlocks.push({
498
- type: 'tool_use',
499
- id: tc.id,
500
- name: tc.name,
501
- input: JSON.parse(tc.arguments),
502
- });
503
- }
504
- }
505
- anthropicMessages.push({ role: 'assistant', content: contentBlocks });
506
- } else if (msg.role === 'tool') {
507
- anthropicMessages.push({
508
- role: 'user',
509
- content: [{
510
- type: 'tool_result',
511
- tool_use_id: msg.toolCallId,
512
- content: msg.content,
513
- }],
514
- });
515
- }
516
- }
517
-
518
- const anthropicTools = tools.map((t) => ({
519
- name: t.name,
520
- description: t.description,
521
- input_schema: t.parameters,
522
- }));
523
-
524
- const fetchSignal = signal
525
- ? AbortSignal.any([signal, AbortSignal.timeout(LLM_CALL_TIMEOUT_MS)])
526
- : AbortSignal.timeout(LLM_CALL_TIMEOUT_MS);
527
-
528
- const response = await fetch(url, {
529
- signal: fetchSignal,
530
- method: 'POST',
531
- headers: {
532
- 'Content-Type': 'application/json',
533
- 'x-api-key': config.apiKey,
534
- 'anthropic-version': '2023-06-01',
535
- },
536
- body: JSON.stringify({
537
- model: config.model,
538
- system: systemContent,
539
- messages: anthropicMessages,
540
- tools: anthropicTools.length > 0 ? anthropicTools : undefined,
541
- temperature: 0.3,
542
- max_tokens: 2048,
543
- }),
544
- });
545
-
546
- if (!response.ok) {
547
- const error = await readResponseText(response, signal, 64 * 1024).catch(() => 'unknown error');
548
- throw new Error(`Anthropic tool-call API error (${response.status}): ${error}`);
549
- }
550
-
551
- const data = await readResponseJson<{
552
- content: Array<{ type: string; text?: string; id?: string; name?: string; input?: unknown }>;
553
- stop_reason: string;
554
- usage?: { input_tokens: number; output_tokens: number };
555
- }>(response, signal);
556
-
557
- let content = '';
558
- const toolCalls: ToolCall[] = [];
559
- for (const block of data.content) {
560
- if (block.type === 'text' && block.text) {
561
- content += block.text;
562
- } else if (block.type === 'tool_use' && block.id && block.name) {
563
- toolCalls.push({
564
- id: block.id,
565
- name: block.name,
566
- arguments: JSON.stringify(block.input ?? {}),
567
- });
568
- }
569
- }
570
-
571
- const stopReason = data.stop_reason === 'tool_use' ? 'tool_use'
572
- : data.stop_reason === 'end_turn' ? 'end_turn'
573
- : 'unknown';
574
-
575
- return {
576
- content,
577
- toolCalls,
578
- stopReason,
579
- usage: data.usage ? {
580
- promptTokens: data.usage.input_tokens,
581
- completionTokens: data.usage.output_tokens,
582
- } : undefined,
583
- };
584
- }
585
-
586
- // ── Streaming implementations ────────────────────────────────────
587
-
588
- /**
589
- * OpenAI-compatible streaming with tool support.
590
- * Parses SSE chunks, yields text deltas, accumulates tool calls.
591
- */
592
- async function* callOpenAIWithToolsStream(
593
- messages: ChatMessage[],
594
- tools: ToolDefinition[],
595
- ): AsyncGenerator<LLMStreamEvent, void, undefined> {
596
- const config = currentConfig!;
597
- let base = config.baseUrl!.replace(/\/+$/, '');
598
- if (!base.endsWith('/v1')) base += '/v1';
599
- const url = `${base}/chat/completions`;
600
-
601
- const openaiMessages: Array<Record<string, unknown>> = messages.map((msg) => {
602
- if (msg.role === 'tool') {
603
- return { role: 'tool', content: msg.content, tool_call_id: msg.toolCallId };
604
- }
605
- if (msg.role === 'assistant' && msg.toolCalls && msg.toolCalls.length > 0) {
606
- return {
607
- role: 'assistant',
608
- content: msg.content || null,
609
- tool_calls: msg.toolCalls.map((tc) => ({
610
- id: tc.id,
611
- type: 'function',
612
- function: { name: tc.name, arguments: tc.arguments },
613
- })),
614
- };
615
- }
616
- return { role: msg.role, content: msg.content };
617
- });
618
-
619
- const openaiTools = tools.map((t) => ({
620
- type: 'function' as const,
621
- function: { name: t.name, description: t.description, parameters: t.parameters },
622
- }));
623
-
624
- const response = await fetch(url, {
625
- signal: AbortSignal.timeout(LLM_CALL_TIMEOUT_MS * 2), // longer timeout for streaming
626
- method: 'POST',
627
- headers: {
628
- 'Content-Type': 'application/json',
629
- 'Authorization': `Bearer ${config.apiKey}`,
630
- },
631
- body: JSON.stringify({
632
- model: config.model,
633
- messages: openaiMessages,
634
- tools: openaiTools.length > 0 ? openaiTools : undefined,
635
- temperature: 0.3,
636
- max_tokens: 2048,
637
- stream: true,
638
- }),
639
- });
640
-
641
- if (!response.ok) {
642
- const error = await response.text().catch(() => 'unknown error');
643
- throw new Error(`LLM streaming API error (${response.status}): ${error}`);
644
- }
645
-
646
- // Parse SSE stream
647
- const reader = response.body?.getReader();
648
- if (!reader) throw new Error('No response body for streaming');
649
-
650
- const decoder = new TextDecoder();
651
- let fullContent = '';
652
- const toolCallMap = new Map<number, { id: string; name: string; arguments: string }>();
653
- let finishReason = 'unknown';
654
- let buffer = '';
655
-
656
- try {
657
- while (true) {
658
- const { done, value } = await reader.read();
659
- if (done) break;
660
-
661
- buffer += decoder.decode(value, { stream: true });
662
- const lines = buffer.split('\n');
663
- buffer = lines.pop() ?? ''; // keep incomplete line in buffer
664
-
665
- for (const line of lines) {
666
- const trimmed = line.trim();
667
- if (!trimmed || trimmed === 'data: [DONE]') continue;
668
- if (!trimmed.startsWith('data: ')) continue;
669
-
670
- try {
671
- const chunk = JSON.parse(trimmed.slice(6));
672
- const delta = chunk.choices?.[0]?.delta;
673
- if (!delta) continue;
674
-
675
- // Text content
676
- if (delta.content) {
677
- fullContent += delta.content;
678
- yield { type: 'text' as const, content: delta.content };
679
- }
680
-
681
- // Tool call deltas — accumulate
682
- if (delta.tool_calls) {
683
- for (const tc of delta.tool_calls) {
684
- const idx = tc.index ?? 0;
685
- if (!toolCallMap.has(idx)) {
686
- toolCallMap.set(idx, {
687
- id: tc.id ?? '',
688
- name: tc.function?.name ?? '',
689
- arguments: tc.function?.arguments ?? '',
690
- });
691
- } else {
692
- const existing = toolCallMap.get(idx)!;
693
- if (tc.id) existing.id = tc.id;
694
- if (tc.function?.name) existing.name = tc.function.name;
695
- if (tc.function?.arguments) existing.arguments += tc.function.arguments;
696
- }
697
- }
698
- }
699
-
700
- // Finish reason
701
- if (chunk.choices?.[0]?.finish_reason) {
702
- finishReason = chunk.choices[0].finish_reason;
703
- }
704
- } catch {
705
- // Skip malformed JSON chunks
706
- }
707
- }
708
- }
709
- } finally {
710
- reader.releaseLock();
711
- }
712
-
713
- const toolCalls = [...toolCallMap.values()].map((tc) => ({
714
- id: tc.id,
715
- name: tc.name,
716
- arguments: tc.arguments,
717
- }));
718
-
719
- // Yield tool_call events
720
- for (const tc of toolCalls) {
721
- yield { type: 'tool_call' as const, toolCall: tc };
722
- }
723
-
724
- const stopReason = finishReason === 'tool_calls' ? 'tool_use'
725
- : finishReason === 'stop' ? 'stop'
726
- : 'unknown';
727
-
728
- yield {
729
- type: 'done' as const,
730
- response: {
731
- content: fullContent,
732
- toolCalls,
733
- stopReason,
734
- },
735
- };
736
- }
737
-
738
- /**
739
- * Anthropic streaming with tool support.
740
- * Parses SSE events, yields text deltas, accumulates tool_use blocks.
741
- */
742
- async function* callAnthropicWithToolsStream(
743
- messages: ChatMessage[],
744
- tools: ToolDefinition[],
745
- ): AsyncGenerator<LLMStreamEvent, void, undefined> {
746
- const config = currentConfig!;
747
- const url = `${config.baseUrl}/messages`;
748
-
749
- const systemContent = messages.find((m) => m.role === 'system')?.content ?? '';
750
- const nonSystemMessages = messages.filter((m) => m.role !== 'system');
751
-
752
- const anthropicMessages: Array<Record<string, unknown>> = [];
753
- for (const msg of nonSystemMessages) {
754
- if (msg.role === 'user') {
755
- anthropicMessages.push({ role: 'user', content: msg.content });
756
- } else if (msg.role === 'assistant') {
757
- const contentBlocks: Array<Record<string, unknown>> = [];
758
- if (msg.content) contentBlocks.push({ type: 'text', text: msg.content });
759
- if (msg.toolCalls) {
760
- for (const tc of msg.toolCalls) {
761
- contentBlocks.push({
762
- type: 'tool_use',
763
- id: tc.id,
764
- name: tc.name,
765
- input: JSON.parse(tc.arguments),
766
- });
767
- }
768
- }
769
- anthropicMessages.push({ role: 'assistant', content: contentBlocks });
770
- } else if (msg.role === 'tool') {
771
- anthropicMessages.push({
772
- role: 'user',
773
- content: [{
774
- type: 'tool_result',
775
- tool_use_id: msg.toolCallId,
776
- content: msg.content,
777
- }],
778
- });
779
- }
780
- }
781
-
782
- const anthropicTools = tools.map((t) => ({
783
- name: t.name,
784
- description: t.description,
785
- input_schema: t.parameters,
786
- }));
787
-
788
- const response = await fetch(url, {
789
- signal: AbortSignal.timeout(LLM_CALL_TIMEOUT_MS * 2),
790
- method: 'POST',
791
- headers: {
792
- 'Content-Type': 'application/json',
793
- 'x-api-key': config.apiKey,
794
- 'anthropic-version': '2023-06-01',
795
- },
796
- body: JSON.stringify({
797
- model: config.model,
798
- system: systemContent,
799
- messages: anthropicMessages,
800
- tools: anthropicTools.length > 0 ? anthropicTools : undefined,
801
- temperature: 0.3,
802
- max_tokens: 2048,
803
- stream: true,
804
- }),
805
- });
806
-
807
- if (!response.ok) {
808
- const error = await response.text().catch(() => 'unknown error');
809
- throw new Error(`Anthropic streaming API error (${response.status}): ${error}`);
810
- }
811
-
812
- const reader = response.body?.getReader();
813
- if (!reader) throw new Error('No response body for streaming');
814
-
815
- const decoder = new TextDecoder();
816
- let fullContent = '';
817
- const toolCalls: ToolCall[] = [];
818
- let currentToolId = '';
819
- let currentToolName = '';
820
- let currentToolInput = '';
821
- let stopReason = 'unknown';
822
- let buffer = '';
823
-
824
- try {
825
- while (true) {
826
- const { done, value } = await reader.read();
827
- if (done) break;
828
-
829
- buffer += decoder.decode(value, { stream: true });
830
- const lines = buffer.split('\n');
831
- buffer = lines.pop() ?? '';
832
-
833
- for (const line of lines) {
834
- const trimmed = line.trim();
835
- if (!trimmed.startsWith('data: ')) continue;
836
-
837
- try {
838
- const event = JSON.parse(trimmed.slice(6));
839
-
840
- if (event.type === 'content_block_delta') {
841
- const delta = event.delta;
842
- if (delta?.type === 'text_delta' && delta.text) {
843
- fullContent += delta.text;
844
- yield { type: 'text' as const, content: delta.text };
845
- } else if (delta?.type === 'input_json_delta' && delta.partial_json) {
846
- currentToolInput += delta.partial_json;
847
- }
848
- } else if (event.type === 'content_block_start') {
849
- const block = event.content_block;
850
- if (block?.type === 'tool_use') {
851
- currentToolId = block.id ?? '';
852
- currentToolName = block.name ?? '';
853
- currentToolInput = '';
854
- }
855
- } else if (event.type === 'content_block_stop') {
856
- // Finalize current tool call
857
- if (currentToolId && currentToolName) {
858
- const tc: ToolCall = {
859
- id: currentToolId,
860
- name: currentToolName,
861
- arguments: currentToolInput || '{}',
862
- };
863
- toolCalls.push(tc);
864
- yield { type: 'tool_call' as const, toolCall: tc };
865
- currentToolId = '';
866
- currentToolName = '';
867
- currentToolInput = '';
868
- }
869
- } else if (event.type === 'message_delta') {
870
- if (event.delta?.stop_reason) {
871
- stopReason = event.delta.stop_reason;
872
- }
873
- }
874
- } catch {
875
- // Skip malformed JSON
876
- }
877
- }
878
- }
879
- } finally {
880
- reader.releaseLock();
881
- }
882
-
883
- const mappedStopReason = stopReason === 'tool_use' ? 'tool_use'
884
- : stopReason === 'end_turn' ? 'end_turn'
885
- : 'unknown';
886
-
887
- yield {
888
- type: 'done' as const,
889
- response: {
890
- content: fullContent,
891
- toolCalls,
892
- stopReason: mappedStopReason,
893
- },
894
- };
895
- }
21
+
22
+ export interface LLMConfig {
23
+ provider: 'openai' | 'anthropic' | 'openrouter' | 'custom';
24
+ apiKey: string;
25
+ model?: string;
26
+ baseUrl?: string;
27
+ }
28
+
29
+ const LLM_TIMEOUT_DEFAULT_MS = 30_000;
30
+ const LLM_TIMEOUT_MIN_MS = 1_000;
31
+ const LLM_TIMEOUT_MAX_MS = 300_000;
32
+ const MAX_LLM_RESPONSE_BYTES = 2 * 1024 * 1024;
33
+
34
+ /**
35
+ * Parse and validate MEMORIX_LLM_TIMEOUT_MS environment variable.
36
+ * - Must be a valid integer in the range 1000–300000ms.
37
+ * - Non-integer or out-of-range values log a warning and fall back to the default.
38
+ * Default: 30000ms (30s) — allows for proxy routing and cold starts.
39
+ */
40
+ export function parseLLMTimeoutMs(raw: string | undefined): number {
41
+ if (raw === undefined || raw.trim() === '') return LLM_TIMEOUT_DEFAULT_MS;
42
+ const parsed = Number(raw);
43
+ if (!Number.isInteger(parsed) || Number.isNaN(parsed)) {
44
+ console.warn(
45
+ `[memorix] MEMORIX_LLM_TIMEOUT_MS="${raw}" is invalid (must be a positive integer between ${LLM_TIMEOUT_MIN_MS}–${LLM_TIMEOUT_MAX_MS}ms). Using default ${LLM_TIMEOUT_DEFAULT_MS}ms.`,
46
+ );
47
+ return LLM_TIMEOUT_DEFAULT_MS;
48
+ }
49
+ if (parsed < LLM_TIMEOUT_MIN_MS) return LLM_TIMEOUT_MIN_MS;
50
+ if (parsed > LLM_TIMEOUT_MAX_MS) return LLM_TIMEOUT_MAX_MS;
51
+ return parsed;
52
+ }
53
+
54
+ const LLM_CALL_TIMEOUT_MS = parseLLMTimeoutMs(process.env.MEMORIX_LLM_TIMEOUT_MS);
55
+
56
+ export interface LLMResponse {
57
+ content: string;
58
+ usage?: { promptTokens: number; completionTokens: number };
59
+ }
60
+
61
+ /** A single tool call requested by the LLM */
62
+ export interface ToolCall {
63
+ id: string;
64
+ name: string;
65
+ arguments: string; // JSON string
66
+ }
67
+
68
+ /** Response from callLLMWithTools — may contain text, tool calls, or both */
69
+ export interface LLMToolResponse {
70
+ content: string;
71
+ toolCalls: ToolCall[];
72
+ stopReason: 'end_turn' | 'tool_use' | 'stop' | 'unknown';
73
+ usage?: { promptTokens: number; completionTokens: number };
74
+ }
75
+
76
+ /** Streaming event from callLLMWithToolsStream */
77
+ export type LLMStreamEvent =
78
+ | { type: 'text'; content: string }
79
+ | { type: 'tool_call'; toolCall: ToolCall }
80
+ | { type: 'done'; response: LLMToolResponse };
81
+
82
+ async function readResponseText(response: Response, signal?: AbortSignal, maxBytes = MAX_LLM_RESPONSE_BYTES): Promise<string> {
83
+ const contentLength = response.headers.get('content-length');
84
+ if (contentLength && Number(contentLength) > maxBytes) {
85
+ throw new Error(`LLM response too large (${contentLength} bytes)`);
86
+ }
87
+
88
+ const reader = response.body?.getReader();
89
+ if (!reader) {
90
+ signal?.throwIfAborted();
91
+ return response.text();
92
+ }
93
+
94
+ const decoder = new TextDecoder();
95
+ const chunks: string[] = [];
96
+ let bytesRead = 0;
97
+ const abortReader = () => {
98
+ void reader.cancel(signal?.reason).catch(() => undefined);
99
+ };
100
+
101
+ signal?.addEventListener('abort', abortReader, { once: true });
102
+
103
+ try {
104
+ while (true) {
105
+ signal?.throwIfAborted();
106
+ const { value, done } = await reader.read();
107
+ if (done) break;
108
+ signal?.throwIfAborted();
109
+ if (!value) continue;
110
+ bytesRead += value.byteLength;
111
+ if (bytesRead > maxBytes) {
112
+ await reader.cancel('response too large').catch(() => undefined);
113
+ throw new Error(`LLM response exceeded ${maxBytes} bytes`);
114
+ }
115
+ chunks.push(decoder.decode(value, { stream: true }));
116
+ }
117
+
118
+ chunks.push(decoder.decode());
119
+ signal?.throwIfAborted();
120
+ return chunks.join('');
121
+ } finally {
122
+ signal?.removeEventListener('abort', abortReader);
123
+ reader.releaseLock();
124
+ }
125
+ }
126
+
127
+ async function readResponseJson<T>(response: Response, signal?: AbortSignal, maxBytes = MAX_LLM_RESPONSE_BYTES): Promise<T> {
128
+ const text = await readResponseText(response, signal, maxBytes);
129
+ return JSON.parse(text) as T;
130
+ }
131
+
132
+ /**
133
+ * Call the LLM with tools in streaming mode.
134
+ * Yields text chunks as they arrive, then a final 'done' event with the complete response.
135
+ * Tool calls are accumulated and yielded at the end.
136
+ */
137
+ export async function* callLLMWithToolsStream(
138
+ messages: ChatMessage[],
139
+ tools: ToolDefinition[],
140
+ ): AsyncGenerator<LLMStreamEvent, void, undefined> {
141
+ if (!currentConfig) {
142
+ throw new Error('LLM not configured. Set MEMORIX_LLM_API_KEY or OPENAI_API_KEY.');
143
+ }
144
+
145
+ if (currentConfig.provider === 'anthropic') {
146
+ yield* callAnthropicWithToolsStream(messages, tools);
147
+ return;
148
+ }
149
+
150
+ yield* callOpenAIWithToolsStream(messages, tools);
151
+ }
152
+
153
+ /** Tool definition for LLM function calling */
154
+ export interface ToolDefinition {
155
+ name: string;
156
+ description: string;
157
+ parameters: Record<string, unknown>; // JSON Schema object
158
+ }
159
+
160
+ /** Chat message for multi-turn tool-use conversations */
161
+ export interface ChatMessage {
162
+ role: 'system' | 'user' | 'assistant' | 'tool';
163
+ content: string;
164
+ toolCallId?: string; // for role='tool': which call this result is for
165
+ toolCalls?: ToolCall[]; // for role='assistant': tool calls made
166
+ name?: string; // for role='tool': function name
167
+ }
168
+
169
+ /** Provider defaults per provider type */
170
+ const PROVIDER_DEFAULTS: Record<string, { baseUrl: string; model: string }> = {
171
+ openai: { baseUrl: 'https://api.openai.com/v1', model: 'gpt-4.1-nano' },
172
+ anthropic: { baseUrl: 'https://api.anthropic.com/v1', model: 'claude-3-5-haiku-latest' },
173
+ openrouter: { baseUrl: 'https://openrouter.ai/api/v1', model: 'openai/gpt-4.1-nano' },
174
+ custom: { baseUrl: 'http://localhost:11434/v1', model: 'llama3' },
175
+ };
176
+
177
+ let currentConfig: LLMConfig | null = null;
178
+
179
+ export type LLMConfigScope = 'memory' | 'agent';
180
+
181
+ export interface InitLLMOptions {
182
+ scope?: LLMConfigScope;
183
+ }
184
+
185
+ /**
186
+ * Initialize the LLM provider from environment variables.
187
+ * Returns null if no API key is configured — Memorix gracefully degrades.
188
+ */
189
+ export function initLLM(options: InitLLMOptions = {}): LLMConfig | null {
190
+ const scope = options.scope ?? 'memory';
191
+ const apiKey = scope === 'agent' ? getAgentLLMApiKey() : getLLMApiKey();
192
+ if (!apiKey) {
193
+ currentConfig = null;
194
+ return null;
195
+ }
196
+
197
+ const provider = (scope === 'agent' ? getAgentLLMProvider() : getLLMProvider()) as LLMConfig['provider'];
198
+ const defaults = PROVIDER_DEFAULTS[provider] ?? PROVIDER_DEFAULTS.openai;
199
+
200
+ currentConfig = {
201
+ provider,
202
+ apiKey,
203
+ model: scope === 'agent' ? getAgentLLMModel(defaults.model) : getLLMModel(defaults.model),
204
+ baseUrl: scope === 'agent' ? getAgentLLMBaseUrl(defaults.baseUrl) : getLLMBaseUrl(defaults.baseUrl),
205
+ };
206
+
207
+ return currentConfig;
208
+ }
209
+
210
+ /**
211
+ * Check if LLM is available.
212
+ */
213
+ export function isLLMEnabled(): boolean {
214
+ return currentConfig !== null;
215
+ }
216
+
217
+ /**
218
+ * Get current LLM config (for display/debug).
219
+ */
220
+ export function getLLMConfig(): LLMConfig | null {
221
+ return currentConfig;
222
+ }
223
+
224
+ /**
225
+ * Set LLM config directly (for testing or programmatic use).
226
+ */
227
+ export function setLLMConfig(config: LLMConfig | null): void {
228
+ currentConfig = config;
229
+ }
230
+
231
+ /**
232
+ * Call the LLM with a prompt.
233
+ * Uses OpenAI-compatible chat completions API (works with OpenRouter, Ollama, etc.)
234
+ *
235
+ * For Anthropic, we use their Messages API directly.
236
+ */
237
+ export async function callLLM(
238
+ systemPrompt: string,
239
+ userMessage: string,
240
+ ): Promise<LLMResponse> {
241
+ if (!currentConfig) {
242
+ throw new Error('LLM not configured. Set MEMORIX_LLM_API_KEY or OPENAI_API_KEY.');
243
+ }
244
+
245
+ if (currentConfig.provider === 'anthropic') {
246
+ return callAnthropic(systemPrompt, userMessage);
247
+ }
248
+
249
+ return callOpenAICompatible(systemPrompt, userMessage);
250
+ }
251
+
252
+ /**
253
+ * OpenAI-compatible API call (works with OpenAI, OpenRouter, Ollama, etc.)
254
+ */
255
+ async function callOpenAICompatible(
256
+ systemPrompt: string,
257
+ userMessage: string,
258
+ ): Promise<LLMResponse> {
259
+ const config = currentConfig!;
260
+ // Auto-fix: append /v1 if baseUrl doesn't end with it (common user mistake)
261
+ let base = config.baseUrl!.replace(/\/+$/, '');
262
+ if (!base.endsWith('/v1')) base += '/v1';
263
+ const url = `${base}/chat/completions`;
264
+
265
+ const response = await fetch(url, {
266
+ signal: AbortSignal.timeout(LLM_CALL_TIMEOUT_MS),
267
+ method: 'POST',
268
+ headers: {
269
+ 'Content-Type': 'application/json',
270
+ 'Authorization': `Bearer ${config.apiKey}`,
271
+ },
272
+ body: JSON.stringify({
273
+ model: config.model,
274
+ messages: [
275
+ { role: 'system', content: systemPrompt },
276
+ { role: 'user', content: userMessage },
277
+ ],
278
+ temperature: 0.1,
279
+ max_tokens: 1024,
280
+ }),
281
+ });
282
+
283
+ if (!response.ok) {
284
+ const error = await readResponseText(response, undefined, 64 * 1024).catch(() => 'unknown error');
285
+ throw new Error(`LLM API error (${response.status}): ${error}`);
286
+ }
287
+
288
+ const data = await readResponseJson<{
289
+ choices: Array<{ message: { content: string } }>;
290
+ usage?: { prompt_tokens: number; completion_tokens: number };
291
+ }>(response);
292
+
293
+ return {
294
+ content: data.choices[0]?.message?.content ?? '',
295
+ usage: data.usage ? {
296
+ promptTokens: data.usage.prompt_tokens,
297
+ completionTokens: data.usage.completion_tokens,
298
+ } : undefined,
299
+ };
300
+ }
301
+
302
+ /**
303
+ * Anthropic Messages API call.
304
+ */
305
+ async function callAnthropic(
306
+ systemPrompt: string,
307
+ userMessage: string,
308
+ ): Promise<LLMResponse> {
309
+ const config = currentConfig!;
310
+ const url = `${config.baseUrl}/messages`;
311
+
312
+ const response = await fetch(url, {
313
+ signal: AbortSignal.timeout(LLM_CALL_TIMEOUT_MS),
314
+ method: 'POST',
315
+ headers: {
316
+ 'Content-Type': 'application/json',
317
+ 'x-api-key': config.apiKey,
318
+ 'anthropic-version': '2023-06-01',
319
+ },
320
+ body: JSON.stringify({
321
+ model: config.model,
322
+ system: systemPrompt,
323
+ messages: [
324
+ { role: 'user', content: userMessage },
325
+ ],
326
+ temperature: 0.1,
327
+ max_tokens: 1024,
328
+ }),
329
+ });
330
+
331
+ if (!response.ok) {
332
+ const error = await readResponseText(response, undefined, 64 * 1024).catch(() => 'unknown error');
333
+ throw new Error(`Anthropic API error (${response.status}): ${error}`);
334
+ }
335
+
336
+ const data = await readResponseJson<{
337
+ content: Array<{ text: string }>;
338
+ usage?: { input_tokens: number; output_tokens: number };
339
+ }>(response);
340
+
341
+ return {
342
+ content: data.content[0]?.text ?? '',
343
+ usage: data.usage ? {
344
+ promptTokens: data.usage.input_tokens,
345
+ completionTokens: data.usage.output_tokens,
346
+ } : undefined,
347
+ };
348
+ }
349
+
350
+ /**
351
+ * Call the LLM with tool definitions (agentic harness pattern).
352
+ *
353
+ * The LLM can decide to call tools or respond directly.
354
+ * Returns structured response with tool_calls for the agentic loop.
355
+ */
356
+ export async function callLLMWithTools(
357
+ messages: ChatMessage[],
358
+ tools: ToolDefinition[],
359
+ signal?: AbortSignal,
360
+ ): Promise<LLMToolResponse> {
361
+ if (!currentConfig) {
362
+ throw new Error('LLM not configured. Set MEMORIX_LLM_API_KEY or OPENAI_API_KEY.');
363
+ }
364
+
365
+ if (currentConfig.provider === 'anthropic') {
366
+ return callAnthropicWithTools(messages, tools, signal);
367
+ }
368
+
369
+ return callOpenAIWithTools(messages, tools, signal);
370
+ }
371
+
372
+ /**
373
+ * OpenAI-compatible tool calling (works with OpenAI, OpenRouter, Ollama, etc.)
374
+ */
375
+ async function callOpenAIWithTools(
376
+ messages: ChatMessage[],
377
+ tools: ToolDefinition[],
378
+ signal?: AbortSignal,
379
+ ): Promise<LLMToolResponse> {
380
+ const config = currentConfig!;
381
+ let base = config.baseUrl!.replace(/\/+$/, '');
382
+ if (!base.endsWith('/v1')) base += '/v1';
383
+ const url = `${base}/chat/completions`;
384
+
385
+ // Convert ChatMessage[] to OpenAI format
386
+ const openaiMessages: Array<Record<string, unknown>> = messages.map((msg) => {
387
+ if (msg.role === 'tool') {
388
+ return { role: 'tool', content: msg.content, tool_call_id: msg.toolCallId };
389
+ }
390
+ if (msg.role === 'assistant' && msg.toolCalls && msg.toolCalls.length > 0) {
391
+ return {
392
+ role: 'assistant',
393
+ content: msg.content || null,
394
+ tool_calls: msg.toolCalls.map((tc) => ({
395
+ id: tc.id,
396
+ type: 'function',
397
+ function: { name: tc.name, arguments: tc.arguments },
398
+ })),
399
+ };
400
+ }
401
+ return { role: msg.role, content: msg.content };
402
+ });
403
+
404
+ const openaiTools = tools.map((t) => ({
405
+ type: 'function' as const,
406
+ function: { name: t.name, description: t.description, parameters: t.parameters },
407
+ }));
408
+
409
+ const fetchSignal = signal
410
+ ? AbortSignal.any([signal, AbortSignal.timeout(LLM_CALL_TIMEOUT_MS)])
411
+ : AbortSignal.timeout(LLM_CALL_TIMEOUT_MS);
412
+
413
+ const response = await fetch(url, {
414
+ signal: fetchSignal,
415
+ method: 'POST',
416
+ headers: {
417
+ 'Content-Type': 'application/json',
418
+ 'Authorization': `Bearer ${config.apiKey}`,
419
+ },
420
+ body: JSON.stringify({
421
+ model: config.model,
422
+ messages: openaiMessages,
423
+ tools: openaiTools.length > 0 ? openaiTools : undefined,
424
+ temperature: 0.3,
425
+ max_tokens: 2048,
426
+ }),
427
+ });
428
+
429
+ if (!response.ok) {
430
+ const error = await readResponseText(response, signal, 64 * 1024).catch(() => 'unknown error');
431
+ throw new Error(`LLM tool-call API error (${response.status}): ${error}`);
432
+ }
433
+
434
+ const data = await readResponseJson<{
435
+ choices: Array<{
436
+ message: {
437
+ content: string | null;
438
+ tool_calls?: Array<{
439
+ id: string;
440
+ type: string;
441
+ function: { name: string; arguments: string };
442
+ }>;
443
+ };
444
+ finish_reason: string;
445
+ }>;
446
+ usage?: { prompt_tokens: number; completion_tokens: number };
447
+ }>(response, signal);
448
+
449
+ const choice = data.choices[0];
450
+ const content = choice?.message?.content ?? '';
451
+ const toolCalls: ToolCall[] = (choice?.message?.tool_calls ?? []).map((tc: { id: string; function: { name: string; arguments: string } }) => ({
452
+ id: tc.id,
453
+ name: tc.function.name,
454
+ arguments: tc.function.arguments,
455
+ }));
456
+
457
+ const stopReason = choice?.finish_reason === 'tool_calls' ? 'tool_use'
458
+ : choice?.finish_reason === 'stop' ? 'stop'
459
+ : 'unknown';
460
+
461
+ return {
462
+ content,
463
+ toolCalls,
464
+ stopReason,
465
+ usage: data.usage ? {
466
+ promptTokens: data.usage.prompt_tokens,
467
+ completionTokens: data.usage.completion_tokens,
468
+ } : undefined,
469
+ };
470
+ }
471
+
472
+ /**
473
+ * Anthropic tool calling (Messages API with tool_use).
474
+ */
475
+ async function callAnthropicWithTools(
476
+ messages: ChatMessage[],
477
+ tools: ToolDefinition[],
478
+ signal?: AbortSignal,
479
+ ): Promise<LLMToolResponse> {
480
+ const config = currentConfig!;
481
+ const url = `${config.baseUrl}/messages`;
482
+
483
+ // Separate system message from the rest
484
+ const systemContent = messages.find((m) => m.role === 'system')?.content ?? '';
485
+ const nonSystemMessages = messages.filter((m) => m.role !== 'system');
486
+
487
+ // Convert to Anthropic message format
488
+ const anthropicMessages: Array<Record<string, unknown>> = [];
489
+ for (const msg of nonSystemMessages) {
490
+ if (msg.role === 'user') {
491
+ anthropicMessages.push({ role: 'user', content: msg.content });
492
+ } else if (msg.role === 'assistant') {
493
+ const contentBlocks: Array<Record<string, unknown>> = [];
494
+ if (msg.content) contentBlocks.push({ type: 'text', text: msg.content });
495
+ if (msg.toolCalls) {
496
+ for (const tc of msg.toolCalls) {
497
+ contentBlocks.push({
498
+ type: 'tool_use',
499
+ id: tc.id,
500
+ name: tc.name,
501
+ input: JSON.parse(tc.arguments),
502
+ });
503
+ }
504
+ }
505
+ anthropicMessages.push({ role: 'assistant', content: contentBlocks });
506
+ } else if (msg.role === 'tool') {
507
+ anthropicMessages.push({
508
+ role: 'user',
509
+ content: [{
510
+ type: 'tool_result',
511
+ tool_use_id: msg.toolCallId,
512
+ content: msg.content,
513
+ }],
514
+ });
515
+ }
516
+ }
517
+
518
+ const anthropicTools = tools.map((t) => ({
519
+ name: t.name,
520
+ description: t.description,
521
+ input_schema: t.parameters,
522
+ }));
523
+
524
+ const fetchSignal = signal
525
+ ? AbortSignal.any([signal, AbortSignal.timeout(LLM_CALL_TIMEOUT_MS)])
526
+ : AbortSignal.timeout(LLM_CALL_TIMEOUT_MS);
527
+
528
+ const response = await fetch(url, {
529
+ signal: fetchSignal,
530
+ method: 'POST',
531
+ headers: {
532
+ 'Content-Type': 'application/json',
533
+ 'x-api-key': config.apiKey,
534
+ 'anthropic-version': '2023-06-01',
535
+ },
536
+ body: JSON.stringify({
537
+ model: config.model,
538
+ system: systemContent,
539
+ messages: anthropicMessages,
540
+ tools: anthropicTools.length > 0 ? anthropicTools : undefined,
541
+ temperature: 0.3,
542
+ max_tokens: 2048,
543
+ }),
544
+ });
545
+
546
+ if (!response.ok) {
547
+ const error = await readResponseText(response, signal, 64 * 1024).catch(() => 'unknown error');
548
+ throw new Error(`Anthropic tool-call API error (${response.status}): ${error}`);
549
+ }
550
+
551
+ const data = await readResponseJson<{
552
+ content: Array<{ type: string; text?: string; id?: string; name?: string; input?: unknown }>;
553
+ stop_reason: string;
554
+ usage?: { input_tokens: number; output_tokens: number };
555
+ }>(response, signal);
556
+
557
+ let content = '';
558
+ const toolCalls: ToolCall[] = [];
559
+ for (const block of data.content) {
560
+ if (block.type === 'text' && block.text) {
561
+ content += block.text;
562
+ } else if (block.type === 'tool_use' && block.id && block.name) {
563
+ toolCalls.push({
564
+ id: block.id,
565
+ name: block.name,
566
+ arguments: JSON.stringify(block.input ?? {}),
567
+ });
568
+ }
569
+ }
570
+
571
+ const stopReason = data.stop_reason === 'tool_use' ? 'tool_use'
572
+ : data.stop_reason === 'end_turn' ? 'end_turn'
573
+ : 'unknown';
574
+
575
+ return {
576
+ content,
577
+ toolCalls,
578
+ stopReason,
579
+ usage: data.usage ? {
580
+ promptTokens: data.usage.input_tokens,
581
+ completionTokens: data.usage.output_tokens,
582
+ } : undefined,
583
+ };
584
+ }
585
+
586
+ // ── Streaming implementations ────────────────────────────────────
587
+
588
+ /**
589
+ * OpenAI-compatible streaming with tool support.
590
+ * Parses SSE chunks, yields text deltas, accumulates tool calls.
591
+ */
592
+ async function* callOpenAIWithToolsStream(
593
+ messages: ChatMessage[],
594
+ tools: ToolDefinition[],
595
+ ): AsyncGenerator<LLMStreamEvent, void, undefined> {
596
+ const config = currentConfig!;
597
+ let base = config.baseUrl!.replace(/\/+$/, '');
598
+ if (!base.endsWith('/v1')) base += '/v1';
599
+ const url = `${base}/chat/completions`;
600
+
601
+ const openaiMessages: Array<Record<string, unknown>> = messages.map((msg) => {
602
+ if (msg.role === 'tool') {
603
+ return { role: 'tool', content: msg.content, tool_call_id: msg.toolCallId };
604
+ }
605
+ if (msg.role === 'assistant' && msg.toolCalls && msg.toolCalls.length > 0) {
606
+ return {
607
+ role: 'assistant',
608
+ content: msg.content || null,
609
+ tool_calls: msg.toolCalls.map((tc) => ({
610
+ id: tc.id,
611
+ type: 'function',
612
+ function: { name: tc.name, arguments: tc.arguments },
613
+ })),
614
+ };
615
+ }
616
+ return { role: msg.role, content: msg.content };
617
+ });
618
+
619
+ const openaiTools = tools.map((t) => ({
620
+ type: 'function' as const,
621
+ function: { name: t.name, description: t.description, parameters: t.parameters },
622
+ }));
623
+
624
+ const response = await fetch(url, {
625
+ signal: AbortSignal.timeout(LLM_CALL_TIMEOUT_MS * 2), // longer timeout for streaming
626
+ method: 'POST',
627
+ headers: {
628
+ 'Content-Type': 'application/json',
629
+ 'Authorization': `Bearer ${config.apiKey}`,
630
+ },
631
+ body: JSON.stringify({
632
+ model: config.model,
633
+ messages: openaiMessages,
634
+ tools: openaiTools.length > 0 ? openaiTools : undefined,
635
+ temperature: 0.3,
636
+ max_tokens: 2048,
637
+ stream: true,
638
+ }),
639
+ });
640
+
641
+ if (!response.ok) {
642
+ const error = await response.text().catch(() => 'unknown error');
643
+ throw new Error(`LLM streaming API error (${response.status}): ${error}`);
644
+ }
645
+
646
+ // Parse SSE stream
647
+ const reader = response.body?.getReader();
648
+ if (!reader) throw new Error('No response body for streaming');
649
+
650
+ const decoder = new TextDecoder();
651
+ let fullContent = '';
652
+ const toolCallMap = new Map<number, { id: string; name: string; arguments: string }>();
653
+ let finishReason = 'unknown';
654
+ let buffer = '';
655
+
656
+ try {
657
+ while (true) {
658
+ const { done, value } = await reader.read();
659
+ if (done) break;
660
+
661
+ buffer += decoder.decode(value, { stream: true });
662
+ const lines = buffer.split('\n');
663
+ buffer = lines.pop() ?? ''; // keep incomplete line in buffer
664
+
665
+ for (const line of lines) {
666
+ const trimmed = line.trim();
667
+ if (!trimmed || trimmed === 'data: [DONE]') continue;
668
+ if (!trimmed.startsWith('data: ')) continue;
669
+
670
+ try {
671
+ const chunk = JSON.parse(trimmed.slice(6));
672
+ const delta = chunk.choices?.[0]?.delta;
673
+ if (!delta) continue;
674
+
675
+ // Text content
676
+ if (delta.content) {
677
+ fullContent += delta.content;
678
+ yield { type: 'text' as const, content: delta.content };
679
+ }
680
+
681
+ // Tool call deltas — accumulate
682
+ if (delta.tool_calls) {
683
+ for (const tc of delta.tool_calls) {
684
+ const idx = tc.index ?? 0;
685
+ if (!toolCallMap.has(idx)) {
686
+ toolCallMap.set(idx, {
687
+ id: tc.id ?? '',
688
+ name: tc.function?.name ?? '',
689
+ arguments: tc.function?.arguments ?? '',
690
+ });
691
+ } else {
692
+ const existing = toolCallMap.get(idx)!;
693
+ if (tc.id) existing.id = tc.id;
694
+ if (tc.function?.name) existing.name = tc.function.name;
695
+ if (tc.function?.arguments) existing.arguments += tc.function.arguments;
696
+ }
697
+ }
698
+ }
699
+
700
+ // Finish reason
701
+ if (chunk.choices?.[0]?.finish_reason) {
702
+ finishReason = chunk.choices[0].finish_reason;
703
+ }
704
+ } catch {
705
+ // Skip malformed JSON chunks
706
+ }
707
+ }
708
+ }
709
+ } finally {
710
+ reader.releaseLock();
711
+ }
712
+
713
+ const toolCalls = [...toolCallMap.values()].map((tc) => ({
714
+ id: tc.id,
715
+ name: tc.name,
716
+ arguments: tc.arguments,
717
+ }));
718
+
719
+ // Yield tool_call events
720
+ for (const tc of toolCalls) {
721
+ yield { type: 'tool_call' as const, toolCall: tc };
722
+ }
723
+
724
+ const stopReason = finishReason === 'tool_calls' ? 'tool_use'
725
+ : finishReason === 'stop' ? 'stop'
726
+ : 'unknown';
727
+
728
+ yield {
729
+ type: 'done' as const,
730
+ response: {
731
+ content: fullContent,
732
+ toolCalls,
733
+ stopReason,
734
+ },
735
+ };
736
+ }
737
+
738
+ /**
739
+ * Anthropic streaming with tool support.
740
+ * Parses SSE events, yields text deltas, accumulates tool_use blocks.
741
+ */
742
+ async function* callAnthropicWithToolsStream(
743
+ messages: ChatMessage[],
744
+ tools: ToolDefinition[],
745
+ ): AsyncGenerator<LLMStreamEvent, void, undefined> {
746
+ const config = currentConfig!;
747
+ const url = `${config.baseUrl}/messages`;
748
+
749
+ const systemContent = messages.find((m) => m.role === 'system')?.content ?? '';
750
+ const nonSystemMessages = messages.filter((m) => m.role !== 'system');
751
+
752
+ const anthropicMessages: Array<Record<string, unknown>> = [];
753
+ for (const msg of nonSystemMessages) {
754
+ if (msg.role === 'user') {
755
+ anthropicMessages.push({ role: 'user', content: msg.content });
756
+ } else if (msg.role === 'assistant') {
757
+ const contentBlocks: Array<Record<string, unknown>> = [];
758
+ if (msg.content) contentBlocks.push({ type: 'text', text: msg.content });
759
+ if (msg.toolCalls) {
760
+ for (const tc of msg.toolCalls) {
761
+ contentBlocks.push({
762
+ type: 'tool_use',
763
+ id: tc.id,
764
+ name: tc.name,
765
+ input: JSON.parse(tc.arguments),
766
+ });
767
+ }
768
+ }
769
+ anthropicMessages.push({ role: 'assistant', content: contentBlocks });
770
+ } else if (msg.role === 'tool') {
771
+ anthropicMessages.push({
772
+ role: 'user',
773
+ content: [{
774
+ type: 'tool_result',
775
+ tool_use_id: msg.toolCallId,
776
+ content: msg.content,
777
+ }],
778
+ });
779
+ }
780
+ }
781
+
782
+ const anthropicTools = tools.map((t) => ({
783
+ name: t.name,
784
+ description: t.description,
785
+ input_schema: t.parameters,
786
+ }));
787
+
788
+ const response = await fetch(url, {
789
+ signal: AbortSignal.timeout(LLM_CALL_TIMEOUT_MS * 2),
790
+ method: 'POST',
791
+ headers: {
792
+ 'Content-Type': 'application/json',
793
+ 'x-api-key': config.apiKey,
794
+ 'anthropic-version': '2023-06-01',
795
+ },
796
+ body: JSON.stringify({
797
+ model: config.model,
798
+ system: systemContent,
799
+ messages: anthropicMessages,
800
+ tools: anthropicTools.length > 0 ? anthropicTools : undefined,
801
+ temperature: 0.3,
802
+ max_tokens: 2048,
803
+ stream: true,
804
+ }),
805
+ });
806
+
807
+ if (!response.ok) {
808
+ const error = await response.text().catch(() => 'unknown error');
809
+ throw new Error(`Anthropic streaming API error (${response.status}): ${error}`);
810
+ }
811
+
812
+ const reader = response.body?.getReader();
813
+ if (!reader) throw new Error('No response body for streaming');
814
+
815
+ const decoder = new TextDecoder();
816
+ let fullContent = '';
817
+ const toolCalls: ToolCall[] = [];
818
+ let currentToolId = '';
819
+ let currentToolName = '';
820
+ let currentToolInput = '';
821
+ let stopReason = 'unknown';
822
+ let buffer = '';
823
+
824
+ try {
825
+ while (true) {
826
+ const { done, value } = await reader.read();
827
+ if (done) break;
828
+
829
+ buffer += decoder.decode(value, { stream: true });
830
+ const lines = buffer.split('\n');
831
+ buffer = lines.pop() ?? '';
832
+
833
+ for (const line of lines) {
834
+ const trimmed = line.trim();
835
+ if (!trimmed.startsWith('data: ')) continue;
836
+
837
+ try {
838
+ const event = JSON.parse(trimmed.slice(6));
839
+
840
+ if (event.type === 'content_block_delta') {
841
+ const delta = event.delta;
842
+ if (delta?.type === 'text_delta' && delta.text) {
843
+ fullContent += delta.text;
844
+ yield { type: 'text' as const, content: delta.text };
845
+ } else if (delta?.type === 'input_json_delta' && delta.partial_json) {
846
+ currentToolInput += delta.partial_json;
847
+ }
848
+ } else if (event.type === 'content_block_start') {
849
+ const block = event.content_block;
850
+ if (block?.type === 'tool_use') {
851
+ currentToolId = block.id ?? '';
852
+ currentToolName = block.name ?? '';
853
+ currentToolInput = '';
854
+ }
855
+ } else if (event.type === 'content_block_stop') {
856
+ // Finalize current tool call
857
+ if (currentToolId && currentToolName) {
858
+ const tc: ToolCall = {
859
+ id: currentToolId,
860
+ name: currentToolName,
861
+ arguments: currentToolInput || '{}',
862
+ };
863
+ toolCalls.push(tc);
864
+ yield { type: 'tool_call' as const, toolCall: tc };
865
+ currentToolId = '';
866
+ currentToolName = '';
867
+ currentToolInput = '';
868
+ }
869
+ } else if (event.type === 'message_delta') {
870
+ if (event.delta?.stop_reason) {
871
+ stopReason = event.delta.stop_reason;
872
+ }
873
+ }
874
+ } catch {
875
+ // Skip malformed JSON
876
+ }
877
+ }
878
+ }
879
+ } finally {
880
+ reader.releaseLock();
881
+ }
882
+
883
+ const mappedStopReason = stopReason === 'tool_use' ? 'tool_use'
884
+ : stopReason === 'end_turn' ? 'end_turn'
885
+ : 'unknown';
886
+
887
+ yield {
888
+ type: 'done' as const,
889
+ response: {
890
+ content: fullContent,
891
+ toolCalls,
892
+ stopReason: mappedStopReason,
893
+ },
894
+ };
895
+ }