@causyne/agent 1.20.120 → 1.20.121

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 (59) hide show
  1. package/package.json +1 -1
  2. package/src/agent/errorClassifier.js +113 -0
  3. package/src/agent/errorClassifier.ts +161 -0
  4. package/src/agent/promptIntent.js +200 -0
  5. package/src/agent/promptIntent.ts +203 -0
  6. package/src/agent/toolArgValidator.js +97 -0
  7. package/src/agent/toolArgValidator.ts +112 -0
  8. package/src/agentLoop.js +22 -339
  9. package/src/agentLoop.ts +40 -347
  10. package/src/autoUpdate.js +111 -8
  11. package/src/autoUpdate.ts +144 -8
  12. package/src/cliMode.js +16 -2
  13. package/src/commands.js +10 -9
  14. package/src/config.js +42 -63
  15. package/src/configVault.js +204 -0
  16. package/src/configVault.ts +213 -0
  17. package/src/core/contextCompactor.js +70 -11
  18. package/src/core/contextCompactor.ts +83 -11
  19. package/src/dynamicCatalogue.js +42 -73
  20. package/src/dynamicCatalogue.ts +74 -60
  21. package/src/entrypoint.js +77 -4
  22. package/src/headlessCli.js +304 -0
  23. package/src/headlessCli.ts +380 -0
  24. package/src/mcp/mcpClient.js +38 -11
  25. package/src/mcp/mcpClient.ts +44 -11
  26. package/src/mcp/mcpRegistry.js +2 -5
  27. package/src/mcp/mcpRegistry.ts +2 -5
  28. package/src/mcp/mcpSecurity.js +189 -0
  29. package/src/mcp/mcpSecurity.ts +190 -0
  30. package/src/osKeychain.js +209 -0
  31. package/src/osKeychain.ts +245 -0
  32. package/src/providers/anthropic.js +28 -11
  33. package/src/providers/byokHttp.js +354 -0
  34. package/src/providers/byokHttp.ts +454 -0
  35. package/src/providers/byokStream.js +657 -0
  36. package/src/providers/byokStream.ts +759 -0
  37. package/src/providers/dashscope-byok.js +34 -25
  38. package/src/providers/deepseek.js +31 -22
  39. package/src/providers/gemini.js +40 -13
  40. package/src/providers/moonshot.js +31 -22
  41. package/src/providers/muse.js +10 -10
  42. package/src/providers/ollama.js +25 -10
  43. package/src/providers/openai-compatible.js +46 -14
  44. package/src/providers/openrouter.js +63 -29
  45. package/src/providers/openrouter.ts +73 -29
  46. package/src/providers/qwen-byok.js +33 -16
  47. package/src/providers/xai.js +31 -22
  48. package/src/sandbox.js +77 -56
  49. package/src/sandboxPolicy.js +1208 -0
  50. package/src/sandboxPolicy.ts +1300 -0
  51. package/src/sessionJournal.js +47 -0
  52. package/src/sessionJournal.ts +49 -0
  53. package/src/tools/osSandbox.js +473 -0
  54. package/src/tools/osSandbox.ts +554 -0
  55. package/src/tools/persistentShell.js +8 -3
  56. package/src/tools/subprocessEnv.js +197 -0
  57. package/src/tools/subprocessEnv.ts +212 -0
  58. package/src/tools/sysRun.js +39 -6
  59. package/src/tools/sysRun.ts +53 -7
@@ -0,0 +1,759 @@
1
+ /**
2
+ * Causyne Agent — Hardened Real-Time SSE & NDJSON Streaming for BYOK Providers
3
+ *
4
+ * Brings real-time token & reasoning streaming (`onChunk`, `onReasoningChunk`)
5
+ * to all BYOK providers (OpenAI / OpenAI-Compatible / Muse, Anthropic, Gemini,
6
+ * DeepSeek, xAI, Moonshot, Qwen, DashScope, and Ollama) while inheriting every
7
+ * transport guarantee from `byokHttp.ts`:
8
+ * - Endpoint URL validation & `redirect: 'error'`
9
+ * - Cooperative AbortSignal (`Esc` / `/stop`) + bounded timeout
10
+ * - Strict SSE/NDJSON line buffer cap (4 MiB) & total stream cap (32 MiB)
11
+ * - Secret redaction, ANSI sanitization & `Retry-After` preservation
12
+ * - Graceful fallback when an upstream proxy returns non-streaming JSON
13
+ */
14
+
15
+ import {
16
+ MAX_PROVIDER_ERROR_BYTES,
17
+ MAX_PROVIDER_JSON_BYTES,
18
+ MAX_SSE_BUFFER_BYTES,
19
+ ProviderHttpError,
20
+ parseRetryAfterMs,
21
+ readBoundedResponseText,
22
+ redactProviderSecrets,
23
+ safeProviderFetch,
24
+ type SafeProviderFetchJsonOptions
25
+ } from './byokHttp.js';
26
+
27
+ export interface ByokStreamCallbacks {
28
+ onChunk?: ((delta: string) => void) | undefined;
29
+ onReasoningChunk?: ((delta: string) => void) | undefined;
30
+ }
31
+
32
+ export interface StreamFetchOptions extends SafeProviderFetchJsonOptions {
33
+ onChunk?: ((delta: string) => void) | undefined;
34
+ onReasoningChunk?: ((delta: string) => void) | undefined;
35
+ }
36
+
37
+ export function wantsStreaming(options: unknown): boolean {
38
+ if (!options || typeof options !== 'object') return false;
39
+ const candidate = options as { onChunk?: unknown; onReasoningChunk?: unknown };
40
+ return typeof candidate.onChunk === 'function' || typeof candidate.onReasoningChunk === 'function';
41
+ }
42
+
43
+ function getHeader(response: Response, name: string): string {
44
+ const headers = (response as unknown as { headers?: { get?: (k: string) => string | null } }).headers;
45
+ if (headers && typeof headers.get === 'function') {
46
+ return headers.get(name) ?? '';
47
+ }
48
+ return '';
49
+ }
50
+
51
+ function isJsonContentType(contentType: string): boolean {
52
+ const lower = contentType.toLowerCase();
53
+ return lower.includes('application/json') || lower.includes('+json');
54
+ }
55
+
56
+ function isRecord(value: unknown): value is Record<string, unknown> {
57
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
58
+ }
59
+
60
+ async function openHardenedStream(
61
+ options: StreamFetchOptions
62
+ ): Promise<
63
+ | { mode: 'json'; data: Record<string, unknown> }
64
+ | { mode: 'stream'; response: Response; cleanup: () => void }
65
+ > {
66
+ const { response, cleanup } = await safeProviderFetch(options);
67
+
68
+ if (!response.ok) {
69
+ try {
70
+ const rawError = await readBoundedResponseText(
71
+ response,
72
+ options.maxErrorBytes ?? MAX_PROVIDER_ERROR_BYTES,
73
+ { truncate: true, label: options.providerLabel }
74
+ ).catch(() => '');
75
+ const cleanError = redactProviderSecrets(rawError, options.secrets);
76
+ const retryAfterMs = parseRetryAfterMs(getHeader(response, 'retry-after') || null);
77
+
78
+ if (options.onHttpError) {
79
+ options.onHttpError({
80
+ status: response.status,
81
+ errorText: cleanError,
82
+ retryAfterMs,
83
+ response
84
+ });
85
+ }
86
+
87
+ const retryNote = retryAfterMs !== undefined
88
+ ? ` (retry after ${Math.ceil(retryAfterMs / 1000)}s)`
89
+ : '';
90
+ throw new ProviderHttpError(
91
+ `${options.providerLabel} API Error (${response.status})${retryNote}: ${cleanError}`,
92
+ { status: response.status, retryAfterMs }
93
+ );
94
+ } finally {
95
+ cleanup();
96
+ }
97
+ }
98
+
99
+ const contentType = getHeader(response, 'content-type');
100
+ const hasStreamReader = Boolean(response.body && typeof response.body.getReader === 'function');
101
+
102
+ // If the endpoint responded with regular JSON (or a minimal unit-test mock without a stream),
103
+ // parse it safely rather than failing stream consumption.
104
+ if (!hasStreamReader || isJsonContentType(contentType)) {
105
+ try {
106
+ if (!hasStreamReader && typeof response.text !== 'function' && typeof response.json === 'function') {
107
+ const parsed = await response.json();
108
+ return { mode: 'json', data: isRecord(parsed) ? parsed : {} };
109
+ }
110
+ const rawText = await readBoundedResponseText(
111
+ response,
112
+ options.maxBytes ?? MAX_PROVIDER_JSON_BYTES,
113
+ { truncate: false, label: options.providerLabel }
114
+ );
115
+ try {
116
+ const parsed: unknown = JSON.parse(rawText);
117
+ return { mode: 'json', data: isRecord(parsed) ? parsed : {} };
118
+ } catch {
119
+ const preview = redactProviderSecrets(rawText.slice(0, 240), options.secrets);
120
+ throw new Error(
121
+ `${options.providerLabel} returned a non-JSON response (HTTP ${response.status}): ${preview}`
122
+ );
123
+ }
124
+ } finally {
125
+ cleanup();
126
+ }
127
+ }
128
+
129
+ return { mode: 'stream', response, cleanup };
130
+ }
131
+
132
+ interface SseEvent {
133
+ event: string;
134
+ data: string;
135
+ }
136
+
137
+ async function consumeSseStream(
138
+ response: Response,
139
+ providerLabel: string,
140
+ maxBytes: number,
141
+ onEvent: (event: SseEvent) => void
142
+ ): Promise<void> {
143
+ const reader = response.body!.getReader();
144
+ const decoder = new TextDecoder('utf-8');
145
+ let buffer = '';
146
+ let totalBytes = 0;
147
+ let currentEvent = '';
148
+ let dataLines: string[] = [];
149
+
150
+ const flushEvent = (): void => {
151
+ if (dataLines.length === 0) {
152
+ currentEvent = '';
153
+ return;
154
+ }
155
+ const payload = dataLines.join('\n');
156
+ const eventName = currentEvent || 'message';
157
+ currentEvent = '';
158
+ dataLines = [];
159
+ onEvent({ event: eventName, data: payload });
160
+ };
161
+
162
+ const processLine = (rawLine: string): void => {
163
+ const line = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine;
164
+ if (line === '') {
165
+ flushEvent();
166
+ return;
167
+ }
168
+ if (line.startsWith(':')) return; // SSE comment / keep-alive
169
+ if (line.startsWith('event:')) {
170
+ currentEvent = line.slice(6).trim();
171
+ return;
172
+ }
173
+ if (line.startsWith('data:')) {
174
+ const value = line.slice(5);
175
+ dataLines.push(value.startsWith(' ') ? value.slice(1) : value);
176
+ }
177
+ };
178
+
179
+ try {
180
+ while (true) {
181
+ const { done, value } = await reader.read();
182
+ if (done) break;
183
+ if (!value) continue;
184
+
185
+ totalBytes += value.byteLength;
186
+ if (totalBytes > maxBytes) {
187
+ await reader.cancel().catch(() => {});
188
+ throw new Error(`${providerLabel} stream exceeded maximum allowed size (${maxBytes} bytes).`);
189
+ }
190
+
191
+ buffer += decoder.decode(value, { stream: true });
192
+ if (Buffer.byteLength(buffer, 'utf8') > MAX_SSE_BUFFER_BYTES) {
193
+ await reader.cancel().catch(() => {});
194
+ throw new Error(`${providerLabel} SSE event buffer exceeded safety limit (${MAX_SSE_BUFFER_BYTES} bytes).`);
195
+ }
196
+
197
+ let newlineIdx = buffer.indexOf('\n');
198
+ while (newlineIdx !== -1) {
199
+ const line = buffer.slice(0, newlineIdx);
200
+ buffer = buffer.slice(newlineIdx + 1);
201
+ processLine(line);
202
+ newlineIdx = buffer.indexOf('\n');
203
+ }
204
+ }
205
+
206
+ buffer += decoder.decode();
207
+ if (buffer.length > 0) {
208
+ for (const tailLine of buffer.split('\n')) {
209
+ processLine(tailLine);
210
+ }
211
+ }
212
+ flushEvent();
213
+ } finally {
214
+ reader.releaseLock();
215
+ }
216
+ }
217
+
218
+ async function consumeNdjsonStream(
219
+ response: Response,
220
+ providerLabel: string,
221
+ maxBytes: number,
222
+ onObject: (obj: Record<string, unknown>) => void
223
+ ): Promise<void> {
224
+ const reader = response.body!.getReader();
225
+ const decoder = new TextDecoder('utf-8');
226
+ let buffer = '';
227
+ let totalBytes = 0;
228
+
229
+ const processLine = (rawLine: string): void => {
230
+ const trimmed = rawLine.trim();
231
+ if (!trimmed) return;
232
+ try {
233
+ const parsed: unknown = JSON.parse(trimmed);
234
+ if (isRecord(parsed)) onObject(parsed);
235
+ } catch {
236
+ // Ignore malformed trailing fragments
237
+ }
238
+ };
239
+
240
+ try {
241
+ while (true) {
242
+ const { done, value } = await reader.read();
243
+ if (done) break;
244
+ if (!value) continue;
245
+
246
+ totalBytes += value.byteLength;
247
+ if (totalBytes > maxBytes) {
248
+ await reader.cancel().catch(() => {});
249
+ throw new Error(`${providerLabel} stream exceeded maximum allowed size (${maxBytes} bytes).`);
250
+ }
251
+
252
+ buffer += decoder.decode(value, { stream: true });
253
+ if (Buffer.byteLength(buffer, 'utf8') > MAX_SSE_BUFFER_BYTES) {
254
+ await reader.cancel().catch(() => {});
255
+ throw new Error(`${providerLabel} NDJSON line buffer exceeded safety limit (${MAX_SSE_BUFFER_BYTES} bytes).`);
256
+ }
257
+
258
+ let newlineIdx = buffer.indexOf('\n');
259
+ while (newlineIdx !== -1) {
260
+ const line = buffer.slice(0, newlineIdx);
261
+ buffer = buffer.slice(newlineIdx + 1);
262
+ processLine(line);
263
+ newlineIdx = buffer.indexOf('\n');
264
+ }
265
+ }
266
+
267
+ buffer += decoder.decode();
268
+ if (buffer.trim()) {
269
+ processLine(buffer);
270
+ }
271
+ } finally {
272
+ reader.releaseLock();
273
+ }
274
+ }
275
+
276
+ /**
277
+ * Streams an OpenAI-compatible `/chat/completions` request via SSE and returns
278
+ * a standard OpenAI chat-completion JSON shape (`choices[0].message` + `usage`)
279
+ * so callers reuse the exact same `normalizeOpenAIChatChoiceResponse` pipeline.
280
+ */
281
+ export async function streamOpenAICompatibleChat(
282
+ options: Omit<StreamFetchOptions, 'body'> & { payload: Record<string, unknown> }
283
+ ): Promise<Record<string, unknown>> {
284
+ const streamPayload: Record<string, unknown> = {
285
+ ...options.payload,
286
+ stream: true,
287
+ stream_options: { include_usage: true }
288
+ };
289
+
290
+ const opened = await openHardenedStream({
291
+ ...options,
292
+ headers: {
293
+ Accept: 'text/event-stream, application/json',
294
+ ...(options.headers ?? {})
295
+ },
296
+ body: JSON.stringify(streamPayload)
297
+ });
298
+
299
+ if (opened.mode === 'json') {
300
+ const choices = Array.isArray(opened.data.choices) ? opened.data.choices : [];
301
+ const first = isRecord(choices[0]) ? choices[0] : null;
302
+ const message = first && isRecord(first.message) ? first.message : null;
303
+ if (message) {
304
+ const reasoning = typeof message.reasoning_content === 'string'
305
+ ? message.reasoning_content
306
+ : (typeof message.reasoning === 'string' ? message.reasoning : '');
307
+ if (reasoning && options.onReasoningChunk) options.onReasoningChunk(reasoning);
308
+ if (typeof message.content === 'string' && message.content && options.onChunk) {
309
+ options.onChunk(message.content);
310
+ }
311
+ }
312
+ return opened.data;
313
+ }
314
+
315
+ let content = '';
316
+ let reasoningContent = '';
317
+ let usage: Record<string, unknown> | undefined;
318
+ let finishReason: string | null = null;
319
+ const toolCallMap = new Map<number, { id: string; type: 'function'; function: { name: string; arguments: string } }>();
320
+
321
+ try {
322
+ await consumeSseStream(
323
+ opened.response,
324
+ options.providerLabel,
325
+ options.maxBytes ?? MAX_PROVIDER_JSON_BYTES,
326
+ ({ data }) => {
327
+ const trimmed = data.trim();
328
+ if (!trimmed || trimmed === '[DONE]') return;
329
+ let parsed: unknown;
330
+ try {
331
+ parsed = JSON.parse(trimmed);
332
+ } catch {
333
+ return;
334
+ }
335
+ if (!isRecord(parsed)) return;
336
+
337
+ if (isRecord(parsed.error)) {
338
+ const msg = redactProviderSecrets(
339
+ typeof parsed.error.message === 'string' ? parsed.error.message : JSON.stringify(parsed.error),
340
+ options.secrets
341
+ );
342
+ throw new Error(`${options.providerLabel} stream error: ${msg}`);
343
+ }
344
+
345
+ if (isRecord(parsed.usage)) {
346
+ usage = parsed.usage;
347
+ }
348
+
349
+ const choices = Array.isArray(parsed.choices) ? parsed.choices : [];
350
+ const first = isRecord(choices[0]) ? choices[0] : null;
351
+ if (!first) return;
352
+ if (typeof first.finish_reason === 'string') finishReason = first.finish_reason;
353
+
354
+ const delta = isRecord(first.delta) ? first.delta : null;
355
+ if (!delta) return;
356
+
357
+ const rChunk = typeof delta.reasoning_content === 'string'
358
+ ? delta.reasoning_content
359
+ : (typeof delta.reasoning === 'string' ? delta.reasoning : '');
360
+ if (rChunk) {
361
+ reasoningContent += rChunk;
362
+ options.onReasoningChunk?.(rChunk);
363
+ }
364
+
365
+ if (typeof delta.content === 'string' && delta.content.length > 0) {
366
+ content += delta.content;
367
+ options.onChunk?.(delta.content);
368
+ }
369
+
370
+ if (Array.isArray(delta.tool_calls)) {
371
+ for (let pos = 0; pos < delta.tool_calls.length; pos++) {
372
+ const tc = delta.tool_calls[pos];
373
+ if (!isRecord(tc)) continue;
374
+ const idx = typeof tc.index === 'number' && Number.isInteger(tc.index) ? tc.index : pos;
375
+ let entry = toolCallMap.get(idx);
376
+ if (!entry) {
377
+ entry = { id: '', type: 'function', function: { name: '', arguments: '' } };
378
+ toolCallMap.set(idx, entry);
379
+ }
380
+ if (typeof tc.id === 'string' && tc.id) entry.id = tc.id;
381
+ if (isRecord(tc.function)) {
382
+ if (typeof tc.function.name === 'string' && tc.function.name) {
383
+ entry.function.name += tc.function.name;
384
+ }
385
+ if (typeof tc.function.arguments === 'string' && tc.function.arguments) {
386
+ entry.function.arguments += tc.function.arguments;
387
+ }
388
+ }
389
+ }
390
+ }
391
+ }
392
+ );
393
+ } finally {
394
+ opened.cleanup();
395
+ }
396
+
397
+ const orderedToolCalls = [...toolCallMap.entries()]
398
+ .sort((a, b) => a[0] - b[0])
399
+ .map(([, tc]) => tc);
400
+
401
+ const message: Record<string, unknown> = {
402
+ role: 'assistant',
403
+ content
404
+ };
405
+ if (reasoningContent) message.reasoning_content = reasoningContent;
406
+ if (orderedToolCalls.length > 0) message.tool_calls = orderedToolCalls;
407
+
408
+ return {
409
+ choices: [{ index: 0, message, finish_reason: finishReason }],
410
+ ...(usage ? { usage } : {})
411
+ };
412
+ }
413
+
414
+ /**
415
+ * Streams an Anthropic `/v1/messages` request via SSE and reconstructs the
416
+ * canonical Anthropic Messages JSON response (`content` blocks including signed
417
+ * `thinking` blocks, `tool_use` inputs, and full cache-aware `usage`).
418
+ */
419
+ export async function streamAnthropicMessages(
420
+ options: Omit<StreamFetchOptions, 'body'> & { payload: Record<string, unknown> }
421
+ ): Promise<Record<string, unknown>> {
422
+ const streamPayload: Record<string, unknown> = {
423
+ ...options.payload,
424
+ stream: true
425
+ };
426
+
427
+ const opened = await openHardenedStream({
428
+ ...options,
429
+ headers: {
430
+ Accept: 'text/event-stream, application/json',
431
+ ...(options.headers ?? {})
432
+ },
433
+ body: JSON.stringify(streamPayload)
434
+ });
435
+
436
+ if (opened.mode === 'json') {
437
+ const blocks = Array.isArray(opened.data.content) ? opened.data.content : [];
438
+ for (const block of blocks) {
439
+ if (!isRecord(block)) continue;
440
+ if (block.type === 'thinking' && typeof block.thinking === 'string' && block.thinking) {
441
+ options.onReasoningChunk?.(block.thinking);
442
+ } else if (block.type === 'text' && typeof block.text === 'string' && block.text) {
443
+ options.onChunk?.(block.text);
444
+ }
445
+ }
446
+ return opened.data;
447
+ }
448
+
449
+ interface BlockAccumulator {
450
+ block: Record<string, unknown>;
451
+ partialJson: string;
452
+ }
453
+ const blockMap = new Map<number, BlockAccumulator>();
454
+ const usage: Record<string, number> = {
455
+ input_tokens: 0,
456
+ output_tokens: 0,
457
+ cache_read_input_tokens: 0,
458
+ cache_creation_input_tokens: 0
459
+ };
460
+
461
+ try {
462
+ await consumeSseStream(
463
+ opened.response,
464
+ options.providerLabel,
465
+ options.maxBytes ?? MAX_PROVIDER_JSON_BYTES,
466
+ ({ data }) => {
467
+ const trimmed = data.trim();
468
+ if (!trimmed) return;
469
+ let parsed: unknown;
470
+ try {
471
+ parsed = JSON.parse(trimmed);
472
+ } catch {
473
+ return;
474
+ }
475
+ if (!isRecord(parsed)) return;
476
+
477
+ const eventType = typeof parsed.type === 'string' ? parsed.type : '';
478
+
479
+ if (eventType === 'error') {
480
+ const errObj = isRecord(parsed.error) ? parsed.error : parsed;
481
+ const msg = redactProviderSecrets(
482
+ typeof errObj.message === 'string' ? errObj.message : JSON.stringify(errObj),
483
+ options.secrets
484
+ );
485
+ throw new Error(`${options.providerLabel} stream error: ${msg}`);
486
+ }
487
+
488
+ if (eventType === 'message_start' && isRecord(parsed.message) && isRecord(parsed.message.usage)) {
489
+ const u = parsed.message.usage;
490
+ if (typeof u.input_tokens === 'number') usage.input_tokens = u.input_tokens;
491
+ if (typeof u.output_tokens === 'number') usage.output_tokens = u.output_tokens;
492
+ if (typeof u.cache_read_input_tokens === 'number') usage.cache_read_input_tokens = u.cache_read_input_tokens;
493
+ if (typeof u.cache_creation_input_tokens === 'number') usage.cache_creation_input_tokens = u.cache_creation_input_tokens;
494
+ return;
495
+ }
496
+
497
+ if (eventType === 'message_delta' && isRecord(parsed.usage)) {
498
+ const u = parsed.usage;
499
+ if (typeof u.input_tokens === 'number') usage.input_tokens = u.input_tokens;
500
+ if (typeof u.output_tokens === 'number') usage.output_tokens = u.output_tokens;
501
+ if (typeof u.cache_read_input_tokens === 'number') usage.cache_read_input_tokens = u.cache_read_input_tokens;
502
+ if (typeof u.cache_creation_input_tokens === 'number') usage.cache_creation_input_tokens = u.cache_creation_input_tokens;
503
+ return;
504
+ }
505
+
506
+ if (eventType === 'content_block_start' && typeof parsed.index === 'number' && isRecord(parsed.content_block)) {
507
+ const initial = { ...parsed.content_block };
508
+ if (initial.type === 'text' && typeof initial.text === 'string' && initial.text) {
509
+ options.onChunk?.(initial.text);
510
+ } else if (initial.type === 'thinking' && typeof initial.thinking === 'string' && initial.thinking) {
511
+ options.onReasoningChunk?.(initial.thinking);
512
+ }
513
+ blockMap.set(parsed.index, { block: initial, partialJson: '' });
514
+ return;
515
+ }
516
+
517
+ if (eventType === 'content_block_delta' && typeof parsed.index === 'number' && isRecord(parsed.delta)) {
518
+ const acc = blockMap.get(parsed.index);
519
+ if (!acc) return;
520
+ const delta = parsed.delta;
521
+ const deltaType = typeof delta.type === 'string' ? delta.type : '';
522
+
523
+ if (deltaType === 'text_delta' && typeof delta.text === 'string') {
524
+ acc.block.text = `${typeof acc.block.text === 'string' ? acc.block.text : ''}${delta.text}`;
525
+ if (delta.text) options.onChunk?.(delta.text);
526
+ } else if (deltaType === 'thinking_delta' && typeof delta.thinking === 'string') {
527
+ acc.block.thinking = `${typeof acc.block.thinking === 'string' ? acc.block.thinking : ''}${delta.thinking}`;
528
+ if (delta.thinking) options.onReasoningChunk?.(delta.thinking);
529
+ } else if (deltaType === 'signature_delta' && typeof delta.signature === 'string') {
530
+ acc.block.signature = `${typeof acc.block.signature === 'string' ? acc.block.signature : ''}${delta.signature}`;
531
+ } else if (deltaType === 'input_json_delta' && typeof delta.partial_json === 'string') {
532
+ acc.partialJson += delta.partial_json;
533
+ }
534
+ }
535
+ }
536
+ );
537
+ } finally {
538
+ opened.cleanup();
539
+ }
540
+
541
+ const contentBlocks = [...blockMap.entries()]
542
+ .sort((a, b) => a[0] - b[0])
543
+ .map(([, acc]) => {
544
+ if (acc.block.type === 'tool_use' && acc.partialJson.trim().length > 0) {
545
+ try {
546
+ const parsedInput: unknown = JSON.parse(acc.partialJson);
547
+ if (isRecord(parsedInput)) {
548
+ acc.block.input = parsedInput;
549
+ }
550
+ } catch {
551
+ // Keep existing input object if partial JSON could not be parsed
552
+ }
553
+ }
554
+ return acc.block;
555
+ });
556
+
557
+ return { content: contentBlocks, usage };
558
+ }
559
+
560
+ /**
561
+ * Converts a Gemini `:generateContent` endpoint URL to `:streamGenerateContent?alt=sse`
562
+ * while preserving the host, model path, and avoiding any API key in the query string.
563
+ */
564
+ export function buildGeminiStreamUrl(generateContentUrl: string): string {
565
+ const parsed = new URL(generateContentUrl);
566
+ if (parsed.pathname.endsWith(':generateContent')) {
567
+ parsed.pathname = `${parsed.pathname.slice(0, -':generateContent'.length)}:streamGenerateContent`;
568
+ }
569
+ parsed.searchParams.set('alt', 'sse');
570
+ return parsed.toString();
571
+ }
572
+
573
+ /**
574
+ * Streams a Gemini `:streamGenerateContent?alt=sse` response and reconstructs
575
+ * the standard Gemini response (`candidates[0].content.parts`, `usageMetadata`,
576
+ * plus optional accumulated `reasoningContent` from `thought: true` parts).
577
+ */
578
+ export async function streamGeminiGenerateContent(
579
+ options: Omit<StreamFetchOptions, 'body'> & { payload: Record<string, unknown> }
580
+ ): Promise<Record<string, unknown> & { reasoningContent?: string }> {
581
+ const streamUrl = buildGeminiStreamUrl(options.url);
582
+ const opened = await openHardenedStream({
583
+ ...options,
584
+ url: streamUrl,
585
+ headers: {
586
+ Accept: 'text/event-stream, application/json',
587
+ ...(options.headers ?? {})
588
+ },
589
+ body: JSON.stringify(options.payload)
590
+ });
591
+
592
+ if (opened.mode === 'json') {
593
+ const candidates = Array.isArray(opened.data.candidates) ? opened.data.candidates : [];
594
+ const first = isRecord(candidates[0]) ? candidates[0] : null;
595
+ const content = first && isRecord(first.content) ? first.content : null;
596
+ const parts = content && Array.isArray(content.parts) ? content.parts : [];
597
+ let reasoning = '';
598
+ for (const part of parts) {
599
+ if (!isRecord(part) || typeof part.text !== 'string' || !part.text) continue;
600
+ if (part.thought === true) {
601
+ reasoning += part.text;
602
+ options.onReasoningChunk?.(part.text);
603
+ } else {
604
+ options.onChunk?.(part.text);
605
+ }
606
+ }
607
+ return reasoning ? { ...opened.data, reasoningContent: reasoning } : opened.data;
608
+ }
609
+
610
+ let textContent = '';
611
+ let reasoningContent = '';
612
+ const functionCallParts: Array<Record<string, unknown>> = [];
613
+ let usageMetadata: Record<string, unknown> | undefined;
614
+ let sawCandidate = false;
615
+
616
+ try {
617
+ await consumeSseStream(
618
+ opened.response,
619
+ options.providerLabel,
620
+ options.maxBytes ?? MAX_PROVIDER_JSON_BYTES,
621
+ ({ data }) => {
622
+ const trimmed = data.trim();
623
+ if (!trimmed || trimmed === '[DONE]') return;
624
+ let parsed: unknown;
625
+ try {
626
+ parsed = JSON.parse(trimmed);
627
+ } catch {
628
+ return;
629
+ }
630
+ if (!isRecord(parsed)) return;
631
+
632
+ if (isRecord(parsed.error)) {
633
+ const msg = redactProviderSecrets(
634
+ typeof parsed.error.message === 'string' ? parsed.error.message : JSON.stringify(parsed.error),
635
+ options.secrets
636
+ );
637
+ throw new Error(`${options.providerLabel} stream error: ${msg}`);
638
+ }
639
+
640
+ if (isRecord(parsed.usageMetadata)) {
641
+ usageMetadata = parsed.usageMetadata;
642
+ }
643
+
644
+ const candidates = Array.isArray(parsed.candidates) ? parsed.candidates : [];
645
+ const first = isRecord(candidates[0]) ? candidates[0] : null;
646
+ if (!first) return;
647
+ sawCandidate = true;
648
+
649
+ const content = isRecord(first.content) ? first.content : null;
650
+ const parts = content && Array.isArray(content.parts) ? content.parts : [];
651
+ for (const part of parts) {
652
+ if (!isRecord(part)) continue;
653
+ if (typeof part.text === 'string' && part.text.length > 0) {
654
+ if (part.thought === true) {
655
+ reasoningContent += part.text;
656
+ options.onReasoningChunk?.(part.text);
657
+ } else {
658
+ textContent += part.text;
659
+ options.onChunk?.(part.text);
660
+ }
661
+ } else if (isRecord(part.functionCall)) {
662
+ functionCallParts.push({ functionCall: part.functionCall });
663
+ }
664
+ }
665
+ }
666
+ );
667
+ } finally {
668
+ opened.cleanup();
669
+ }
670
+
671
+ const finalParts: Array<Record<string, unknown>> = [];
672
+ if (textContent) finalParts.push({ text: textContent });
673
+ finalParts.push(...functionCallParts);
674
+
675
+ return {
676
+ candidates: sawCandidate ? [{ content: { role: 'model', parts: finalParts } }] : [],
677
+ ...(usageMetadata ? { usageMetadata } : {}),
678
+ ...(reasoningContent ? { reasoningContent } : {})
679
+ };
680
+ }
681
+
682
+ /**
683
+ * Streams an Ollama `/api/chat` request via NDJSON (`stream: true`) and returns
684
+ * the standard Ollama response shape (`message.content`, `message.thinking`,
685
+ * `message.tool_calls`, `prompt_eval_count`, `eval_count`).
686
+ */
687
+ export async function streamOllamaChat(
688
+ options: Omit<StreamFetchOptions, 'body'> & { payload: Record<string, unknown> }
689
+ ): Promise<Record<string, unknown>> {
690
+ const streamPayload: Record<string, unknown> = {
691
+ ...options.payload,
692
+ stream: true
693
+ };
694
+
695
+ const opened = await openHardenedStream({
696
+ ...options,
697
+ headers: {
698
+ Accept: 'application/x-ndjson, application/json',
699
+ ...(options.headers ?? {})
700
+ },
701
+ body: JSON.stringify(streamPayload)
702
+ });
703
+
704
+ if (opened.mode === 'json') {
705
+ const msg = isRecord(opened.data.message) ? opened.data.message : null;
706
+ if (msg) {
707
+ if (typeof msg.thinking === 'string' && msg.thinking) options.onReasoningChunk?.(msg.thinking);
708
+ if (typeof msg.content === 'string' && msg.content) options.onChunk?.(msg.content);
709
+ }
710
+ return opened.data;
711
+ }
712
+
713
+ let content = '';
714
+ let thinking = '';
715
+ const toolCalls: unknown[] = [];
716
+ let promptEvalCount = 0;
717
+ let evalCount = 0;
718
+
719
+ try {
720
+ await consumeNdjsonStream(
721
+ opened.response,
722
+ options.providerLabel,
723
+ options.maxBytes ?? MAX_PROVIDER_JSON_BYTES,
724
+ (chunk) => {
725
+ if (typeof chunk.error === 'string' && chunk.error) {
726
+ throw new Error(`${options.providerLabel} stream error: ${redactProviderSecrets(chunk.error, options.secrets)}`);
727
+ }
728
+ const msg = isRecord(chunk.message) ? chunk.message : null;
729
+ if (msg) {
730
+ if (typeof msg.thinking === 'string' && msg.thinking.length > 0) {
731
+ thinking += msg.thinking;
732
+ options.onReasoningChunk?.(msg.thinking);
733
+ }
734
+ if (typeof msg.content === 'string' && msg.content.length > 0) {
735
+ content += msg.content;
736
+ options.onChunk?.(msg.content);
737
+ }
738
+ if (Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0) {
739
+ toolCalls.push(...msg.tool_calls);
740
+ }
741
+ }
742
+ if (typeof chunk.prompt_eval_count === 'number') promptEvalCount = chunk.prompt_eval_count;
743
+ if (typeof chunk.eval_count === 'number') evalCount = chunk.eval_count;
744
+ }
745
+ );
746
+ } finally {
747
+ opened.cleanup();
748
+ }
749
+
750
+ const message: Record<string, unknown> = { role: 'assistant', content };
751
+ if (thinking) message.thinking = thinking;
752
+ if (toolCalls.length > 0) message.tool_calls = toolCalls;
753
+
754
+ return {
755
+ message,
756
+ prompt_eval_count: promptEvalCount,
757
+ eval_count: evalCount
758
+ };
759
+ }