memorix 1.1.7 → 1.1.9

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 (185) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/CLAUDE.md +6 -1
  3. package/README.md +21 -0
  4. package/README.zh-CN.md +21 -0
  5. package/TEAM.md +86 -86
  6. package/dist/cli/index.js +852 -214
  7. package/dist/cli/index.js.map +1 -1
  8. package/dist/dashboard/static/index.html +201 -201
  9. package/dist/dashboard/static/style.css +3584 -3584
  10. package/dist/index.js +129 -62
  11. package/dist/index.js.map +1 -1
  12. package/dist/memcode-runtime/CHANGELOG.md +22 -0
  13. package/dist/memcode-runtime/package.json +4 -4
  14. package/dist/sdk.js +129 -62
  15. package/dist/sdk.js.map +1 -1
  16. package/docs/AGENT_OPERATOR_PLAYBOOK.md +18 -0
  17. package/docs/API_REFERENCE.md +2 -0
  18. package/docs/CONFIGURATION.md +18 -0
  19. package/docs/DESIGN_DECISIONS.md +357 -357
  20. package/docs/SETUP.md +10 -0
  21. package/docs/dev-log/progress.txt +23 -30
  22. package/package.json +1 -1
  23. package/src/audit/index.ts +156 -156
  24. package/src/cli/commands/agent-integrations.ts +623 -0
  25. package/src/cli/commands/audit-list.ts +89 -89
  26. package/src/cli/commands/background.ts +659 -659
  27. package/src/cli/commands/cleanup.ts +255 -255
  28. package/src/cli/commands/codegraph.ts +4 -0
  29. package/src/cli/commands/config-get.ts +9 -2
  30. package/src/cli/commands/doctor.ts +26 -0
  31. package/src/cli/commands/formation.ts +48 -48
  32. package/src/cli/commands/git-hook-install.ts +111 -111
  33. package/src/cli/commands/handoff.ts +66 -66
  34. package/src/cli/commands/hooks-status.ts +63 -63
  35. package/src/cli/commands/ingest-commit.ts +153 -153
  36. package/src/cli/commands/ingest-image.ts +73 -73
  37. package/src/cli/commands/ingest-log.ts +180 -180
  38. package/src/cli/commands/ingest.ts +44 -44
  39. package/src/cli/commands/integrate-shared.ts +15 -15
  40. package/src/cli/commands/lock.ts +96 -96
  41. package/src/cli/commands/message.ts +121 -121
  42. package/src/cli/commands/poll.ts +70 -70
  43. package/src/cli/commands/purge-all-memory.ts +85 -85
  44. package/src/cli/commands/purge-project-memory.ts +83 -83
  45. package/src/cli/commands/reasoning.ts +132 -132
  46. package/src/cli/commands/repair.ts +60 -0
  47. package/src/cli/commands/retention.ts +108 -108
  48. package/src/cli/commands/serve-shared.ts +118 -118
  49. package/src/cli/commands/setup.ts +3 -3
  50. package/src/cli/commands/skills.ts +123 -123
  51. package/src/cli/commands/task.ts +192 -192
  52. package/src/cli/commands/transfer.ts +73 -73
  53. package/src/cli/commands/uninstall-project-artifacts.ts +85 -85
  54. package/src/cli/index.ts +3 -1
  55. package/src/cli/tui/ChatView.tsx +234 -234
  56. package/src/cli/tui/CommandBar.tsx +312 -312
  57. package/src/cli/tui/ContextRail.tsx +118 -118
  58. package/src/cli/tui/HeaderBar.tsx +72 -72
  59. package/src/cli/tui/LogoBanner.tsx +51 -51
  60. package/src/cli/tui/Panels.tsx +632 -632
  61. package/src/cli/tui/Sidebar.tsx +179 -179
  62. package/src/cli/tui/chat-service.ts +742 -742
  63. package/src/cli/tui/data.ts +547 -547
  64. package/src/cli/tui/index.ts +41 -41
  65. package/src/cli/tui/markdown-render.tsx +371 -371
  66. package/src/cli/tui/theme.ts +178 -178
  67. package/src/cli/tui/use-mouse.ts +157 -157
  68. package/src/cli/tui/useNavigation.ts +56 -56
  69. package/src/cli/update-checker.ts +211 -211
  70. package/src/cli/version.ts +7 -7
  71. package/src/cli/workbench.ts +1 -1
  72. package/src/codegraph/auto-context.ts +6 -0
  73. package/src/codegraph/context-pack.ts +7 -6
  74. package/src/codegraph/exclude.ts +47 -0
  75. package/src/codegraph/lite-provider.ts +5 -24
  76. package/src/codegraph/project-context.ts +13 -15
  77. package/src/compact/token-budget.ts +74 -74
  78. package/src/config/behavior.ts +59 -59
  79. package/src/config/resolved-config.ts +6 -0
  80. package/src/config/toml-loader.ts +4 -0
  81. package/src/config/yaml-loader.ts +7 -0
  82. package/src/dashboard/project-classification.ts +64 -64
  83. package/src/dashboard/static/index.html +201 -201
  84. package/src/dashboard/static/style.css +3584 -3584
  85. package/src/embedding/fastembed-provider.ts +142 -142
  86. package/src/embedding/transformers-provider.ts +111 -111
  87. package/src/git/extractor.ts +209 -209
  88. package/src/git/hooks-path.ts +85 -85
  89. package/src/git/noise-filter.ts +210 -210
  90. package/src/hooks/installers/index.ts +4 -4
  91. package/src/hooks/official-skills.ts +1 -1
  92. package/src/hooks/pattern-detector.ts +173 -173
  93. package/src/hooks/rules/memorix-agent-rules.md +2 -2
  94. package/src/hooks/significance-filter.ts +250 -250
  95. package/src/llm/memory-manager.ts +328 -328
  96. package/src/llm/provider.ts +885 -885
  97. package/src/llm/quality.ts +248 -248
  98. package/src/memory/attribution-guard.ts +249 -249
  99. package/src/memory/auto-relations.ts +107 -107
  100. package/src/memory/consolidation.ts +302 -302
  101. package/src/memory/disclosure-policy.ts +141 -141
  102. package/src/memory/entity-extractor.ts +197 -197
  103. package/src/memory/formation/evaluate.ts +217 -217
  104. package/src/memory/formation/extract.ts +361 -361
  105. package/src/memory/formation/index.ts +417 -417
  106. package/src/memory/formation/resolve.ts +344 -344
  107. package/src/memory/formation/types.ts +315 -315
  108. package/src/memory/freshness.ts +122 -122
  109. package/src/memory/graph.ts +197 -197
  110. package/src/memory/refs.ts +94 -94
  111. package/src/memory/retention.ts +433 -433
  112. package/src/memory/secret-filter.ts +79 -79
  113. package/src/memory/session.ts +523 -523
  114. package/src/multimodal/image-loader.ts +143 -143
  115. package/src/orchestrate/adapters/claude-stream.ts +192 -192
  116. package/src/orchestrate/adapters/claude.ts +111 -111
  117. package/src/orchestrate/adapters/codex-stream.ts +134 -134
  118. package/src/orchestrate/adapters/codex.ts +41 -41
  119. package/src/orchestrate/adapters/gemini-stream.ts +166 -166
  120. package/src/orchestrate/adapters/gemini.ts +42 -42
  121. package/src/orchestrate/adapters/index.ts +73 -73
  122. package/src/orchestrate/adapters/opencode-stream.ts +143 -143
  123. package/src/orchestrate/adapters/opencode.ts +47 -47
  124. package/src/orchestrate/adapters/spawn-helper.ts +286 -286
  125. package/src/orchestrate/adapters/types.ts +77 -77
  126. package/src/orchestrate/capability-router.ts +284 -284
  127. package/src/orchestrate/context-compact.ts +188 -188
  128. package/src/orchestrate/cost-tracker.ts +219 -219
  129. package/src/orchestrate/error-recovery.ts +191 -191
  130. package/src/orchestrate/evidence.ts +140 -140
  131. package/src/orchestrate/ledger.ts +110 -110
  132. package/src/orchestrate/memorix-bridge.ts +380 -380
  133. package/src/orchestrate/output-budget.ts +80 -80
  134. package/src/orchestrate/permission.ts +152 -152
  135. package/src/orchestrate/pipeline-trace.ts +131 -131
  136. package/src/orchestrate/prompt-builder.ts +155 -155
  137. package/src/orchestrate/ring-buffer.ts +37 -37
  138. package/src/orchestrate/task-graph.ts +389 -389
  139. package/src/orchestrate/verify-gate.ts +219 -219
  140. package/src/orchestrate/worktree.ts +232 -232
  141. package/src/project/aliases.ts +374 -374
  142. package/src/project/detector.ts +268 -268
  143. package/src/rules/adapters/claude-code.ts +99 -99
  144. package/src/rules/adapters/codex.ts +97 -97
  145. package/src/rules/adapters/copilot.ts +124 -124
  146. package/src/rules/adapters/cursor.ts +114 -114
  147. package/src/rules/adapters/kiro.ts +126 -126
  148. package/src/rules/adapters/trae.ts +56 -56
  149. package/src/rules/adapters/windsurf.ts +83 -83
  150. package/src/rules/syncer.ts +235 -235
  151. package/src/sdk.ts +327 -327
  152. package/src/search/intent-detector.ts +289 -289
  153. package/src/search/query-expansion.ts +52 -52
  154. package/src/server/formation-timeout.ts +27 -27
  155. package/src/server.ts +3 -0
  156. package/src/skills/mini-skills.ts +386 -386
  157. package/src/store/chat-store.ts +119 -119
  158. package/src/store/file-lock.ts +100 -100
  159. package/src/store/graph-store.ts +249 -249
  160. package/src/store/mini-skill-store.ts +349 -349
  161. package/src/store/obs-store.ts +255 -255
  162. package/src/store/orama-store.ts +15 -8
  163. package/src/store/persistence-json.ts +212 -212
  164. package/src/store/persistence.ts +291 -291
  165. package/src/store/project-affinity.ts +195 -195
  166. package/src/store/session-store.ts +259 -259
  167. package/src/store/sqlite-store.ts +339 -339
  168. package/src/team/event-bus.ts +76 -76
  169. package/src/team/file-locks.ts +173 -173
  170. package/src/team/handoff.ts +167 -167
  171. package/src/team/messages.ts +203 -203
  172. package/src/team/poll.ts +132 -132
  173. package/src/team/tasks.ts +211 -211
  174. package/src/wiki/generator.ts +237 -237
  175. package/src/wiki/knowledge-graph.ts +334 -334
  176. package/src/wiki/types.ts +85 -85
  177. package/src/workspace/mcp-adapters/codex.ts +191 -191
  178. package/src/workspace/mcp-adapters/copilot.ts +105 -105
  179. package/src/workspace/mcp-adapters/cursor.ts +53 -53
  180. package/src/workspace/mcp-adapters/kiro.ts +64 -64
  181. package/src/workspace/mcp-adapters/opencode.ts +123 -123
  182. package/src/workspace/mcp-adapters/trae.ts +134 -134
  183. package/src/workspace/mcp-adapters/windsurf.ts +91 -91
  184. package/src/workspace/sanitizer.ts +60 -60
  185. 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
+ }