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