@causyne/agent 1.20.120 → 1.20.122

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 (276) hide show
  1. package/README.md +3 -3
  2. package/package.json +1 -1
  3. package/src/acp/agentCatalog.js +81 -26
  4. package/src/acp/agentCatalog.ts +73 -29
  5. package/src/acp/client.js +210 -53
  6. package/src/acp/client.ts +202 -52
  7. package/src/acp/peerProfiles.js +55 -22
  8. package/src/acp/peerProfiles.ts +51 -22
  9. package/src/acp/protocol.js +37 -8
  10. package/src/acp/protocol.ts +30 -8
  11. package/src/acp/server.js +123 -25
  12. package/src/acp/server.ts +124 -24
  13. package/src/agent/errorClassifier.js +117 -0
  14. package/src/agent/errorClassifier.ts +165 -0
  15. package/src/agent/promptIntent.js +200 -0
  16. package/src/agent/promptIntent.ts +203 -0
  17. package/src/agent/toolArgValidator.js +97 -0
  18. package/src/agent/toolArgValidator.ts +112 -0
  19. package/src/agentLoop.js +33 -344
  20. package/src/agentLoop.ts +51 -352
  21. package/src/approvalGrants.js +19 -7
  22. package/src/approvalGrants.ts +20 -7
  23. package/src/approvalPolicy.js +48 -15
  24. package/src/approvalPolicy.ts +46 -15
  25. package/src/autoUpdate.js +116 -10
  26. package/src/autoUpdate.ts +149 -10
  27. package/src/browser/causyneBrowser.js +3 -2
  28. package/src/browser/causyneBrowser.ts +3 -2
  29. package/src/browser/searchProviders.js +1 -1
  30. package/src/browser/searchProviders.ts +1 -1
  31. package/src/cliMode.js +16 -2
  32. package/src/commands.js +10 -9
  33. package/src/config.js +288 -272
  34. package/src/config.ts +342 -0
  35. package/src/configVault.js +271 -0
  36. package/src/configVault.ts +273 -0
  37. package/src/continuum/compactor.js +2 -1
  38. package/src/continuum/compactor.ts +2 -1
  39. package/src/continuum/sanitizer.js +10 -3
  40. package/src/continuum/sanitizer.ts +9 -3
  41. package/src/continuum/ui/continuumPickerView.js +3 -2
  42. package/src/continuum/ui/continuumPickerView.ts +3 -2
  43. package/src/core/contextCompactor.js +70 -11
  44. package/src/core/contextCompactor.ts +83 -11
  45. package/src/cortex/vectorDb.js +26 -15
  46. package/src/cortex/vectorDb.ts +26 -16
  47. package/src/creative/liveBridge.js +7 -5
  48. package/src/creative/liveBridge.ts +7 -5
  49. package/src/creative/studioScripts.js +16 -5
  50. package/src/creative/studioScripts.ts +14 -5
  51. package/src/decisionPolicy.js +16 -4
  52. package/src/decisionPolicy.ts +14 -4
  53. package/src/documentEngine/antiSlopAuditor.js +10 -5
  54. package/src/documentEngine/antiSlopAuditor.ts +11 -5
  55. package/src/documentEngine/documentForge.js +47 -15
  56. package/src/documentEngine/documentForge.ts +43 -14
  57. package/src/dynamicCatalogue.js +42 -73
  58. package/src/dynamicCatalogue.ts +74 -60
  59. package/src/engines/design.js +2 -1
  60. package/src/engines/design.ts +2 -1
  61. package/src/engines/film.js +4 -4
  62. package/src/engines/film.ts +2 -2
  63. package/src/engines/light.js +2 -1
  64. package/src/engines/light.ts +2 -1
  65. package/src/engines/registry.js +1 -1
  66. package/src/engines/registry.ts +1 -1
  67. package/src/engines/reverseHarness.js +4 -3
  68. package/src/engines/reverseHarness.ts +4 -3
  69. package/src/entrypoint.js +77 -4
  70. package/src/headlessCli.js +305 -0
  71. package/src/headlessCli.ts +381 -0
  72. package/src/historyPruner.js +3 -2
  73. package/src/historyPruner.ts +3 -2
  74. package/src/hooks.js +3 -0
  75. package/src/hooks.ts +3 -0
  76. package/src/implementationPlan.js +21 -11
  77. package/src/implementationPlan.ts +21 -11
  78. package/src/infra/atomicWriter.js +4 -1
  79. package/src/infra/atomicWriter.ts +4 -1
  80. package/src/launchIntent.js +1 -1
  81. package/src/launchIntent.ts +1 -1
  82. package/src/mcp/mcpClient.js +38 -11
  83. package/src/mcp/mcpClient.ts +44 -11
  84. package/src/mcp/mcpRegistry.js +2 -5
  85. package/src/mcp/mcpRegistry.ts +2 -5
  86. package/src/mcp/mcpSecurity.js +189 -0
  87. package/src/mcp/mcpSecurity.ts +190 -0
  88. package/src/memory/scopedFacts.js +1 -1
  89. package/src/memory/scopedFacts.ts +1 -1
  90. package/src/memory/symbolFolder.js +1 -1
  91. package/src/memory/symbolFolder.ts +1 -1
  92. package/src/modelRouter.js +1 -1
  93. package/src/modelRouter.ts +1 -1
  94. package/src/observer/evidence.js +10 -4
  95. package/src/observer/evidence.ts +10 -4
  96. package/src/osKeychain.js +263 -0
  97. package/src/osKeychain.ts +287 -0
  98. package/src/perception.js +3 -2
  99. package/src/perception.ts +3 -2
  100. package/src/planCache.js +2 -2
  101. package/src/planCache.ts +2 -2
  102. package/src/pluginsFactory/pluginsFactory.js +19 -11
  103. package/src/pluginsFactory/pluginsFactory.ts +18 -11
  104. package/src/promptMentions.js +2 -2
  105. package/src/promptMentions.ts +2 -2
  106. package/src/providers/acp.js +1 -1
  107. package/src/providers/acp.ts +1 -1
  108. package/src/providers/anthropic.js +328 -385
  109. package/src/providers/anthropic.ts +386 -0
  110. package/src/providers/antigravity.js +10 -4
  111. package/src/providers/antigravity.ts +10 -4
  112. package/src/providers/base.js +221 -319
  113. package/src/providers/base.ts +340 -0
  114. package/src/providers/byokHttp.js +397 -0
  115. package/src/providers/byokHttp.ts +497 -0
  116. package/src/providers/byokStream.js +748 -0
  117. package/src/providers/byokStream.ts +863 -0
  118. package/src/providers/dashscope-byok.js +98 -81
  119. package/src/providers/dashscope-byok.ts +114 -0
  120. package/src/providers/deepseek.js +74 -64
  121. package/src/providers/deepseek.ts +99 -0
  122. package/src/providers/factory.js +35 -28
  123. package/src/providers/factory.ts +40 -0
  124. package/src/providers/gemini.js +229 -253
  125. package/src/providers/gemini.ts +261 -0
  126. package/src/providers/loopGuard.js +9 -5
  127. package/src/providers/loopGuard.ts +10 -5
  128. package/src/providers/moonshot.js +71 -64
  129. package/src/providers/moonshot.ts +93 -0
  130. package/src/providers/muse.js +82 -152
  131. package/src/providers/muse.ts +122 -0
  132. package/src/providers/ollama.js +116 -93
  133. package/src/providers/ollama.ts +135 -0
  134. package/src/providers/openai-compatible.js +114 -65
  135. package/src/providers/openai-compatible.ts +139 -0
  136. package/src/providers/openai.js +22 -15
  137. package/src/providers/openai.ts +30 -0
  138. package/src/providers/openrouter.js +194 -98
  139. package/src/providers/openrouter.ts +202 -97
  140. package/src/providers/pi.js +6 -0
  141. package/src/providers/pi.ts +6 -0
  142. package/src/providers/qwen-byok.js +97 -71
  143. package/src/providers/qwen-byok.ts +113 -0
  144. package/src/providers/toolContracts.js +40 -14
  145. package/src/providers/toolContracts.ts +35 -14
  146. package/src/providers/wireNormalizer.js +78 -11
  147. package/src/providers/wireNormalizer.ts +68 -12
  148. package/src/providers/xai.js +74 -64
  149. package/src/providers/xai.ts +97 -0
  150. package/src/reliability/assetEvidence.js +4 -2
  151. package/src/reliability/assetEvidence.ts +4 -2
  152. package/src/sandbox.js +486 -530
  153. package/src/sandbox.ts +552 -0
  154. package/src/sandboxPolicy.js +1287 -0
  155. package/src/sandboxPolicy.ts +1381 -0
  156. package/src/sessionJournal.js +55 -3
  157. package/src/sessionJournal.ts +58 -3
  158. package/src/skills/skillResourceSafety.js +19 -8
  159. package/src/skills/skillResourceSafety.ts +16 -7
  160. package/src/skillsManager.js +3 -3
  161. package/src/skillsManager.ts +3 -3
  162. package/src/smartToolsUse.js +28 -4
  163. package/src/smartToolsUse.ts +29 -7
  164. package/src/stallGuard.js +45 -22
  165. package/src/stallGuard.ts +46 -22
  166. package/src/subagentJournal.js +6 -4
  167. package/src/subagentJournal.ts +6 -4
  168. package/src/textDiff.js +6 -1
  169. package/src/textDiff.ts +6 -1
  170. package/src/timeMachine.js +7 -1
  171. package/src/timeMachine.ts +7 -1
  172. package/src/tokenTracker.js +43 -28
  173. package/src/tokenTracker.ts +44 -30
  174. package/src/toolPacks.js +3 -1
  175. package/src/toolPacks.ts +3 -1
  176. package/src/tools/archive.js +245 -35
  177. package/src/tools/archive.ts +244 -35
  178. package/src/tools/computerUse.js +7 -3
  179. package/src/tools/computerUse.ts +7 -3
  180. package/src/tools/creativeApps.js +13 -8
  181. package/src/tools/creativeApps.ts +22 -9
  182. package/src/tools/deferredMcpSearch.js +26 -14
  183. package/src/tools/deferredMcpSearch.ts +26 -14
  184. package/src/tools/desktopOpen.js +69 -10
  185. package/src/tools/desktopOpen.ts +70 -11
  186. package/src/tools/documentForge.js +167 -82
  187. package/src/tools/documentForge.ts +169 -84
  188. package/src/tools/fsEdit.js +101 -30
  189. package/src/tools/fsEdit.ts +105 -32
  190. package/src/tools/fsFind.js +8 -5
  191. package/src/tools/fsFind.ts +7 -4
  192. package/src/tools/fsRead.js +119 -13
  193. package/src/tools/fsRead.ts +124 -13
  194. package/src/tools/fsWrite.js +17 -5
  195. package/src/tools/fsWrite.ts +17 -7
  196. package/src/tools/generateMediaViaApi.js +82 -19
  197. package/src/tools/generateMediaViaApi.ts +80 -19
  198. package/src/tools/memoryRecall.js +62 -11
  199. package/src/tools/memoryRecall.ts +70 -13
  200. package/src/tools/memoryWrite.js +27 -14
  201. package/src/tools/memoryWrite.ts +30 -14
  202. package/src/tools/multiEdit.js +100 -30
  203. package/src/tools/multiEdit.ts +104 -32
  204. package/src/tools/nativeEngine.js +33 -18
  205. package/src/tools/nativeEngine.ts +31 -18
  206. package/src/tools/openSourceToolProvisioner.js +49 -14
  207. package/src/tools/openSourceToolProvisioner.ts +54 -15
  208. package/src/tools/osSandbox.js +513 -0
  209. package/src/tools/osSandbox.ts +588 -0
  210. package/src/tools/payloadSanitizer.js +40 -8
  211. package/src/tools/payloadSanitizer.ts +39 -8
  212. package/src/tools/peerAgent.js +96 -34
  213. package/src/tools/peerAgent.ts +114 -37
  214. package/src/tools/persistentShell.js +8 -3
  215. package/src/tools/pluginsFactory.js +38 -6
  216. package/src/tools/pluginsFactory.ts +42 -6
  217. package/src/tools/readNativeSkill.js +10 -8
  218. package/src/tools/readNativeSkill.ts +10 -8
  219. package/src/tools/requestDecision.js +10 -3
  220. package/src/tools/requestDecision.ts +10 -3
  221. package/src/tools/resolveAutomator.js +91 -17
  222. package/src/tools/resolveAutomator.ts +102 -17
  223. package/src/tools/reverseEngineering.js +168 -41
  224. package/src/tools/reverseEngineering.ts +161 -41
  225. package/src/tools/subprocessEnv.js +197 -0
  226. package/src/tools/subprocessEnv.ts +212 -0
  227. package/src/tools/sysRun.js +108 -35
  228. package/src/tools/sysRun.ts +119 -31
  229. package/src/tools/toolDispatch.js +24 -1
  230. package/src/tools/toolDispatch.ts +21 -1
  231. package/src/tools/toolOutputStore.js +62 -23
  232. package/src/tools/toolOutputStore.ts +56 -23
  233. package/src/tools/toolScanner.js +13 -10
  234. package/src/tools/toolScanner.ts +13 -10
  235. package/src/tools/toolSelfRepair.js +94 -28
  236. package/src/tools/toolSelfRepair.ts +96 -28
  237. package/src/tools/uiForge.js +71 -6
  238. package/src/tools/uiForge.ts +74 -6
  239. package/src/tools/viewImage.js +62 -17
  240. package/src/tools/viewImage.ts +57 -12
  241. package/src/tools/visionInspector.js +15 -3
  242. package/src/tools/visionInspector.ts +15 -3
  243. package/src/tools/walkerSafety.js +2 -0
  244. package/src/tools/walkerSafety.ts +1 -0
  245. package/src/tools/webFetch.js +105 -10
  246. package/src/tools/webFetch.ts +105 -11
  247. package/src/tui/banner.js +3 -2
  248. package/src/tui/banner.ts +3 -2
  249. package/src/tui/consoleGuard.js +12 -4
  250. package/src/tui/consoleGuard.ts +9 -4
  251. package/src/tui/messageInteraction.js +2 -3
  252. package/src/tui/messageInteraction.ts +2 -3
  253. package/src/tui/modelPicker.js +1 -0
  254. package/src/tui/modelPicker.ts +1 -0
  255. package/src/tui/overlay.js +3 -1
  256. package/src/tui/overlay.ts +3 -1
  257. package/src/tui/sessionPicker.js +3 -2
  258. package/src/tui/sessionPicker.ts +3 -2
  259. package/src/tui/sessionPickerView.js +7 -1
  260. package/src/tui/sessionPickerView.ts +6 -1
  261. package/src/tui/toolOutputNormalizer.js +2 -3
  262. package/src/tui/toolOutputNormalizer.ts +4 -3
  263. package/src/tui/viewport.js +4 -4
  264. package/src/tui/viewport.ts +5 -5
  265. package/src/tui/workspaceIdentity.js +2 -1
  266. package/src/tui/workspaceIdentity.ts +2 -1
  267. package/src/uncertainty.js +8 -3
  268. package/src/uncertainty.ts +8 -3
  269. package/src/utils/paths.js +8 -5
  270. package/src/utils/paths.ts +9 -7
  271. package/src/vfeTracker.js +9 -3
  272. package/src/vfeTracker.ts +9 -3
  273. package/src/config.d.ts +0 -2
  274. package/src/providers/base.d.ts +0 -94
  275. package/src/providers/factory.d.ts +0 -1
  276. package/src/sandbox.d.ts +0 -1
@@ -0,0 +1,863 @@
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 { safeParseJsonObject } from './wireNormalizer.js';
16
+ import {
17
+ MAX_PROVIDER_ERROR_BYTES,
18
+ MAX_PROVIDER_JSON_BYTES,
19
+ MAX_SSE_BUFFER_BYTES,
20
+ ProviderHttpError,
21
+ parseRetryAfterMs,
22
+ readBoundedResponseText,
23
+ redactProviderSecrets,
24
+ safeProviderFetch,
25
+ type SafeProviderFetchJsonOptions
26
+ } from './byokHttp.js';
27
+
28
+ export interface ByokStreamCallbacks {
29
+ onChunk?: ((delta: string) => void) | undefined;
30
+ onReasoningChunk?: ((delta: string) => void) | undefined;
31
+ }
32
+
33
+ export interface StreamFetchOptions extends SafeProviderFetchJsonOptions {
34
+ onChunk?: ((delta: string) => void) | undefined;
35
+ onReasoningChunk?: ((delta: string) => void) | undefined;
36
+ }
37
+
38
+ export function wantsStreaming(options: unknown): boolean {
39
+ if (!options || typeof options !== 'object') return false;
40
+ const candidate = options as { onChunk?: unknown; onReasoningChunk?: unknown };
41
+ return typeof candidate.onChunk === 'function' || typeof candidate.onReasoningChunk === 'function';
42
+ }
43
+
44
+ function getHeader(response: Response, name: string): string {
45
+ const headers = (response as unknown as { headers?: { get?: (k: string) => string | null } }).headers;
46
+ if (headers && typeof headers.get === 'function') {
47
+ return headers.get(name) ?? '';
48
+ }
49
+ return '';
50
+ }
51
+
52
+ function isJsonContentType(contentType: string): boolean {
53
+ const mediaType = (contentType.split(';')[0] ?? '').trim().toLowerCase();
54
+ return mediaType === 'application/json' || mediaType.endsWith('+json');
55
+ }
56
+
57
+ function isRecord(value: unknown): value is Record<string, unknown> {
58
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
59
+ }
60
+
61
+ async function openHardenedStream(
62
+ options: StreamFetchOptions
63
+ ): Promise<
64
+ | { mode: 'json'; data: Record<string, unknown> }
65
+ | { mode: 'stream'; response: Response; cleanup: () => void }
66
+ > {
67
+ const { response, cleanup } = await safeProviderFetch(options);
68
+
69
+ if (!response.ok) {
70
+ try {
71
+ const rawError = await readBoundedResponseText(
72
+ response,
73
+ options.maxErrorBytes ?? MAX_PROVIDER_ERROR_BYTES,
74
+ { truncate: true, label: options.providerLabel }
75
+ ).catch(() => '');
76
+ const cleanError = redactProviderSecrets(rawError, options.secrets);
77
+ const retryAfterMs = parseRetryAfterMs(getHeader(response, 'retry-after') || null);
78
+
79
+ if (options.onHttpError) {
80
+ options.onHttpError({
81
+ status: response.status,
82
+ errorText: cleanError,
83
+ retryAfterMs,
84
+ response
85
+ });
86
+ }
87
+
88
+ const retryNote = retryAfterMs !== undefined
89
+ ? ` (retry after ${Math.ceil(retryAfterMs / 1000)}s)`
90
+ : '';
91
+ throw new ProviderHttpError(
92
+ `${options.providerLabel} API Error (${response.status})${retryNote}: ${cleanError}`,
93
+ { status: response.status, retryAfterMs }
94
+ );
95
+ } finally {
96
+ cleanup();
97
+ }
98
+ }
99
+
100
+ const contentType = getHeader(response, 'content-type');
101
+ const hasStreamReader = Boolean(response.body && typeof response.body.getReader === 'function');
102
+
103
+ // If the endpoint responded with regular JSON (or a minimal unit-test mock without a stream),
104
+ // parse it safely rather than failing stream consumption.
105
+ if (!hasStreamReader || isJsonContentType(contentType)) {
106
+ try {
107
+ if (!hasStreamReader && typeof response.text !== 'function' && typeof response.json === 'function') {
108
+ const parsed = await response.json();
109
+ return { mode: 'json', data: isRecord(parsed) ? parsed : {} };
110
+ }
111
+ const rawText = await readBoundedResponseText(
112
+ response,
113
+ options.maxBytes ?? MAX_PROVIDER_JSON_BYTES,
114
+ { truncate: false, label: options.providerLabel }
115
+ );
116
+ const cleanText = rawText.charCodeAt(0) === 0xfeff ? rawText.slice(1) : rawText;
117
+ try {
118
+ const parsed: unknown = JSON.parse(cleanText);
119
+ return { mode: 'json', data: isRecord(parsed) ? parsed : {} };
120
+ } catch {
121
+ const preview = redactProviderSecrets(rawText.slice(0, 240), options.secrets);
122
+ throw new Error(
123
+ `${options.providerLabel} returned a non-JSON response (HTTP ${response.status}): ${preview}`
124
+ );
125
+ }
126
+ } finally {
127
+ cleanup();
128
+ }
129
+ }
130
+
131
+ return { mode: 'stream', response, cleanup };
132
+ }
133
+
134
+ interface SseEvent {
135
+ event: string;
136
+ data: string;
137
+ }
138
+
139
+ async function consumeSseStream(
140
+ response: Response,
141
+ providerLabel: string,
142
+ maxBytes: number,
143
+ onEvent: (event: SseEvent) => void,
144
+ signal?: AbortSignal | undefined
145
+ ): Promise<void> {
146
+ const safeMaxBytes = typeof maxBytes === 'number' && Number.isFinite(maxBytes) && maxBytes >= 1
147
+ ? Math.floor(maxBytes)
148
+ : MAX_PROVIDER_JSON_BYTES;
149
+ const reader = response.body!.getReader();
150
+ const decoder = new TextDecoder('utf-8');
151
+ let buffer = '';
152
+ let totalBytes = 0;
153
+ let currentEvent = '';
154
+ let dataLines: string[] = [];
155
+ let sawFirstLine = false;
156
+
157
+ let eventBytes = 0;
158
+
159
+ const flushEvent = (): void => {
160
+ if (dataLines.length === 0) {
161
+ currentEvent = '';
162
+ eventBytes = 0;
163
+ return;
164
+ }
165
+ const payload = dataLines.join('\n');
166
+ const eventName = currentEvent || 'message';
167
+ currentEvent = '';
168
+ dataLines = [];
169
+ eventBytes = 0;
170
+ onEvent({ event: eventName, data: payload });
171
+ };
172
+
173
+ const processLine = (rawLine: string): void => {
174
+ let stripped = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine;
175
+ if (!sawFirstLine) {
176
+ sawFirstLine = true;
177
+ if (stripped.charCodeAt(0) === 0xfeff) stripped = stripped.slice(1);
178
+ }
179
+ const line = stripped;
180
+ if (line === '') {
181
+ flushEvent();
182
+ return;
183
+ }
184
+ if (line.startsWith(':')) return; // SSE comment / keep-alive
185
+ if (line.startsWith('event:')) {
186
+ const val = line.slice(6);
187
+ currentEvent = (val.startsWith(' ') ? val.slice(1) : val).trim();
188
+ return;
189
+ }
190
+ if (line.startsWith('data:')) {
191
+ const value = line.slice(5);
192
+ const entry = value.startsWith(' ') ? value.slice(1) : value;
193
+ eventBytes += Buffer.byteLength(entry, 'utf8') + 1;
194
+ if (eventBytes > MAX_SSE_BUFFER_BYTES) {
195
+ throw new Error(`${providerLabel} SSE event payload exceeded safety limit (${MAX_SSE_BUFFER_BYTES} bytes).`);
196
+ }
197
+ dataLines.push(entry);
198
+ }
199
+ };
200
+
201
+ try {
202
+ while (true) {
203
+ if (signal?.aborted) {
204
+ await reader.cancel().catch(() => {});
205
+ throw signal.reason ?? new DOMException('Aborted', 'AbortError');
206
+ }
207
+ const { done, value } = await reader.read();
208
+ if (done) break;
209
+ if (!value) continue;
210
+
211
+ totalBytes += value.byteLength;
212
+ if (totalBytes > safeMaxBytes) {
213
+ await reader.cancel().catch(() => {});
214
+ throw new Error(`${providerLabel} stream exceeded maximum allowed size (${safeMaxBytes} bytes).`);
215
+ }
216
+
217
+ buffer += decoder.decode(value, { stream: true });
218
+ if (Buffer.byteLength(buffer, 'utf8') > MAX_SSE_BUFFER_BYTES) {
219
+ await reader.cancel().catch(() => {});
220
+ throw new Error(`${providerLabel} SSE event buffer exceeded safety limit (${MAX_SSE_BUFFER_BYTES} bytes).`);
221
+ }
222
+
223
+ let newlineIdx = buffer.indexOf('\n');
224
+ while (newlineIdx !== -1) {
225
+ const line = buffer.slice(0, newlineIdx);
226
+ buffer = buffer.slice(newlineIdx + 1);
227
+ processLine(line);
228
+ newlineIdx = buffer.indexOf('\n');
229
+ }
230
+ }
231
+
232
+ buffer += decoder.decode();
233
+ if (buffer.length > 0) {
234
+ for (const tailLine of buffer.split('\n')) {
235
+ processLine(tailLine);
236
+ }
237
+ }
238
+ flushEvent();
239
+ } finally {
240
+ reader.releaseLock();
241
+ }
242
+ }
243
+
244
+ async function consumeNdjsonStream(
245
+ response: Response,
246
+ providerLabel: string,
247
+ maxBytes: number,
248
+ onObject: (obj: Record<string, unknown>) => void,
249
+ signal?: AbortSignal | undefined
250
+ ): Promise<void> {
251
+ const safeMaxBytes = typeof maxBytes === 'number' && Number.isFinite(maxBytes) && maxBytes >= 1
252
+ ? Math.floor(maxBytes)
253
+ : MAX_PROVIDER_JSON_BYTES;
254
+ const reader = response.body!.getReader();
255
+ const decoder = new TextDecoder('utf-8');
256
+ let buffer = '';
257
+ let totalBytes = 0;
258
+
259
+ const processLine = (rawLine: string): void => {
260
+ const stripped = rawLine.charCodeAt(0) === 0xfeff ? rawLine.slice(1) : rawLine;
261
+ const trimmed = stripped.trim();
262
+ if (!trimmed) return;
263
+ try {
264
+ const parsed: unknown = JSON.parse(trimmed);
265
+ if (isRecord(parsed)) onObject(parsed);
266
+ } catch {
267
+ // Ignore malformed trailing fragments
268
+ }
269
+ };
270
+
271
+ try {
272
+ while (true) {
273
+ if (signal?.aborted) {
274
+ await reader.cancel().catch(() => {});
275
+ throw signal.reason ?? new DOMException('Aborted', 'AbortError');
276
+ }
277
+ const { done, value } = await reader.read();
278
+ if (done) break;
279
+ if (!value) continue;
280
+
281
+ totalBytes += value.byteLength;
282
+ if (totalBytes > safeMaxBytes) {
283
+ await reader.cancel().catch(() => {});
284
+ throw new Error(`${providerLabel} stream exceeded maximum allowed size (${safeMaxBytes} bytes).`);
285
+ }
286
+
287
+ buffer += decoder.decode(value, { stream: true });
288
+ if (Buffer.byteLength(buffer, 'utf8') > MAX_SSE_BUFFER_BYTES) {
289
+ await reader.cancel().catch(() => {});
290
+ throw new Error(`${providerLabel} NDJSON line buffer exceeded safety limit (${MAX_SSE_BUFFER_BYTES} bytes).`);
291
+ }
292
+
293
+ let newlineIdx = buffer.indexOf('\n');
294
+ while (newlineIdx !== -1) {
295
+ const line = buffer.slice(0, newlineIdx);
296
+ buffer = buffer.slice(newlineIdx + 1);
297
+ processLine(line);
298
+ newlineIdx = buffer.indexOf('\n');
299
+ }
300
+ }
301
+
302
+ buffer += decoder.decode();
303
+ if (buffer.trim()) {
304
+ processLine(buffer);
305
+ }
306
+ } finally {
307
+ reader.releaseLock();
308
+ }
309
+ }
310
+
311
+ /**
312
+ * Streams an OpenAI-compatible `/chat/completions` request via SSE and returns
313
+ * a standard OpenAI chat-completion JSON shape (`choices[0].message` + `usage`)
314
+ * so callers reuse the exact same `normalizeOpenAIChatChoiceResponse` pipeline.
315
+ */
316
+ export async function streamOpenAICompatibleChat(
317
+ options: Omit<StreamFetchOptions, 'body'> & { payload: Record<string, unknown> }
318
+ ): Promise<Record<string, unknown>> {
319
+ const streamPayload: Record<string, unknown> = {
320
+ ...options.payload,
321
+ stream: true,
322
+ stream_options: { include_usage: true }
323
+ };
324
+
325
+ const opened = await openHardenedStream({
326
+ ...options,
327
+ headers: {
328
+ Accept: 'text/event-stream, application/json',
329
+ ...(options.headers ?? {})
330
+ },
331
+ body: JSON.stringify(streamPayload)
332
+ });
333
+
334
+ if (opened.mode === 'json') {
335
+ if (isRecord(opened.data.error)) {
336
+ const msg = redactProviderSecrets(
337
+ typeof opened.data.error.message === 'string' ? opened.data.error.message : JSON.stringify(opened.data.error),
338
+ options.secrets
339
+ );
340
+ throw new Error(`${options.providerLabel} stream error: ${msg}`);
341
+ }
342
+ const choices = Array.isArray(opened.data.choices) ? opened.data.choices : [];
343
+ const first = isRecord(choices[0]) ? choices[0] : null;
344
+ const message = first && isRecord(first.message) ? first.message : null;
345
+ if (message) {
346
+ const reasoning = typeof message.reasoning_content === 'string'
347
+ ? message.reasoning_content
348
+ : (typeof message.reasoning === 'string' ? message.reasoning : '');
349
+ if (reasoning && options.onReasoningChunk) options.onReasoningChunk(reasoning);
350
+ if (typeof message.content === 'string' && message.content && options.onChunk) {
351
+ options.onChunk(message.content);
352
+ }
353
+ }
354
+ return opened.data;
355
+ }
356
+
357
+ let content = '';
358
+ let reasoningContent = '';
359
+ let usage: Record<string, unknown> | undefined;
360
+ let finishReason: string | null = null;
361
+ const toolCallMap = new Map<number, { id: string; type: 'function'; function: { name: string; arguments: string } }>();
362
+
363
+ try {
364
+ await consumeSseStream(
365
+ opened.response,
366
+ options.providerLabel,
367
+ options.maxBytes ?? MAX_PROVIDER_JSON_BYTES,
368
+ ({ data }) => {
369
+ const trimmed = data.trim();
370
+ if (!trimmed || trimmed === '[DONE]') return;
371
+ let parsed: unknown;
372
+ try {
373
+ parsed = JSON.parse(trimmed);
374
+ } catch {
375
+ return;
376
+ }
377
+ if (!isRecord(parsed)) return;
378
+
379
+ if (isRecord(parsed.error)) {
380
+ const msg = redactProviderSecrets(
381
+ typeof parsed.error.message === 'string' ? parsed.error.message : JSON.stringify(parsed.error),
382
+ options.secrets
383
+ );
384
+ throw new Error(`${options.providerLabel} stream error: ${msg}`);
385
+ }
386
+
387
+ if (isRecord(parsed.usage)) {
388
+ usage = parsed.usage;
389
+ }
390
+
391
+ const choices = Array.isArray(parsed.choices) ? parsed.choices : [];
392
+ const first = isRecord(choices[0]) ? choices[0] : null;
393
+ if (!first) return;
394
+ if (typeof first.finish_reason === 'string') finishReason = first.finish_reason;
395
+
396
+ const delta = isRecord(first.delta) ? first.delta : null;
397
+ if (!delta) return;
398
+
399
+ const rChunk = typeof delta.reasoning_content === 'string'
400
+ ? delta.reasoning_content
401
+ : (typeof delta.reasoning === 'string' ? delta.reasoning : '');
402
+ if (rChunk) {
403
+ reasoningContent += rChunk;
404
+ options.onReasoningChunk?.(rChunk);
405
+ }
406
+
407
+ if (typeof delta.content === 'string' && delta.content.length > 0) {
408
+ content += delta.content;
409
+ options.onChunk?.(delta.content);
410
+ } else if (Array.isArray(delta.content)) {
411
+ for (const part of delta.content) {
412
+ if (isRecord(part) && typeof part.text === 'string' && part.text.length > 0) {
413
+ content += part.text;
414
+ options.onChunk?.(part.text);
415
+ }
416
+ }
417
+ }
418
+
419
+ if (Array.isArray(delta.tool_calls)) {
420
+ for (let pos = 0; pos < delta.tool_calls.length; pos++) {
421
+ const tc = delta.tool_calls[pos];
422
+ if (!isRecord(tc)) continue;
423
+ let idx: number;
424
+ if (typeof tc.index === 'number' && Number.isInteger(tc.index) && tc.index >= 0) {
425
+ idx = tc.index;
426
+ } else if (typeof tc.id === 'string' && tc.id) {
427
+ const match = [...toolCallMap.entries()].find(([, item]) => item.id === tc.id);
428
+ if (match) {
429
+ idx = match[0];
430
+ } else if (toolCallMap.get(pos)?.id && toolCallMap.get(pos)?.id !== tc.id) {
431
+ idx = Math.max(-1, ...toolCallMap.keys()) + 1;
432
+ } else {
433
+ idx = pos;
434
+ }
435
+ } else {
436
+ idx = pos;
437
+ }
438
+ let entry = toolCallMap.get(idx);
439
+ if (!entry) {
440
+ entry = { id: '', type: 'function', function: { name: '', arguments: '' } };
441
+ toolCallMap.set(idx, entry);
442
+ }
443
+ if (typeof tc.id === 'string' && tc.id) entry.id = tc.id;
444
+ if (isRecord(tc.function)) {
445
+ if (typeof tc.function.name === 'string' && tc.function.name) {
446
+ entry.function.name += tc.function.name;
447
+ }
448
+ if (typeof tc.function.arguments === 'string' && tc.function.arguments) {
449
+ entry.function.arguments += tc.function.arguments;
450
+ }
451
+ }
452
+ }
453
+ }
454
+ },
455
+ options.signal
456
+ );
457
+ } finally {
458
+ opened.cleanup();
459
+ }
460
+
461
+ const orderedToolCalls = [...toolCallMap.entries()]
462
+ .sort((a, b) => a[0] - b[0])
463
+ .map(([, tc]) => tc);
464
+
465
+ const message: Record<string, unknown> = {
466
+ role: 'assistant',
467
+ content
468
+ };
469
+ if (reasoningContent) message.reasoning_content = reasoningContent;
470
+ if (orderedToolCalls.length > 0) message.tool_calls = orderedToolCalls;
471
+
472
+ return {
473
+ choices: [{ index: 0, message, finish_reason: finishReason }],
474
+ ...(usage ? { usage } : {})
475
+ };
476
+ }
477
+
478
+ /**
479
+ * Streams an Anthropic `/v1/messages` request via SSE and reconstructs the
480
+ * canonical Anthropic Messages JSON response (`content` blocks including signed
481
+ * `thinking` blocks, `tool_use` inputs, and full cache-aware `usage`).
482
+ */
483
+ export async function streamAnthropicMessages(
484
+ options: Omit<StreamFetchOptions, 'body'> & { payload: Record<string, unknown> }
485
+ ): Promise<Record<string, unknown>> {
486
+ const streamPayload: Record<string, unknown> = {
487
+ ...options.payload,
488
+ stream: true
489
+ };
490
+
491
+ const opened = await openHardenedStream({
492
+ ...options,
493
+ headers: {
494
+ Accept: 'text/event-stream, application/json',
495
+ ...(options.headers ?? {})
496
+ },
497
+ body: JSON.stringify(streamPayload)
498
+ });
499
+
500
+ if (opened.mode === 'json') {
501
+ if (opened.data.type === 'error' || isRecord(opened.data.error)) {
502
+ const errObj = isRecord(opened.data.error) ? opened.data.error : opened.data;
503
+ const msg = redactProviderSecrets(
504
+ typeof errObj.message === 'string' ? errObj.message : JSON.stringify(errObj),
505
+ options.secrets
506
+ );
507
+ throw new Error(`${options.providerLabel} stream error: ${msg}`);
508
+ }
509
+ const blocks = Array.isArray(opened.data.content) ? opened.data.content : [];
510
+ for (const block of blocks) {
511
+ if (!isRecord(block)) continue;
512
+ if (block.type === 'thinking' && typeof block.thinking === 'string' && block.thinking) {
513
+ options.onReasoningChunk?.(block.thinking);
514
+ } else if (block.type === 'text' && typeof block.text === 'string' && block.text) {
515
+ options.onChunk?.(block.text);
516
+ }
517
+ }
518
+ return opened.data;
519
+ }
520
+
521
+ interface BlockAccumulator {
522
+ block: Record<string, unknown>;
523
+ partialJson: string;
524
+ }
525
+ const blockMap = new Map<number, BlockAccumulator>();
526
+ const usage: Record<string, number> = {
527
+ input_tokens: 0,
528
+ output_tokens: 0,
529
+ cache_read_input_tokens: 0,
530
+ cache_creation_input_tokens: 0
531
+ };
532
+ let stopReason: string | undefined;
533
+ const applyUsage = (u: Record<string, unknown>): void => {
534
+ if (typeof u.input_tokens === 'number' && Number.isFinite(u.input_tokens) && u.input_tokens >= 0) usage.input_tokens = u.input_tokens;
535
+ if (typeof u.output_tokens === 'number' && Number.isFinite(u.output_tokens) && u.output_tokens >= 0) usage.output_tokens = u.output_tokens;
536
+ if (typeof u.cache_read_input_tokens === 'number' && Number.isFinite(u.cache_read_input_tokens) && u.cache_read_input_tokens >= 0) usage.cache_read_input_tokens = u.cache_read_input_tokens;
537
+ if (typeof u.cache_creation_input_tokens === 'number' && Number.isFinite(u.cache_creation_input_tokens) && u.cache_creation_input_tokens >= 0) usage.cache_creation_input_tokens = u.cache_creation_input_tokens;
538
+ };
539
+
540
+ try {
541
+ await consumeSseStream(
542
+ opened.response,
543
+ options.providerLabel,
544
+ options.maxBytes ?? MAX_PROVIDER_JSON_BYTES,
545
+ ({ data }) => {
546
+ const trimmed = data.trim();
547
+ if (!trimmed) return;
548
+ let parsed: unknown;
549
+ try {
550
+ parsed = JSON.parse(trimmed);
551
+ } catch {
552
+ return;
553
+ }
554
+ if (!isRecord(parsed)) return;
555
+
556
+ const eventType = typeof parsed.type === 'string' ? parsed.type : '';
557
+
558
+ if (eventType === 'error') {
559
+ const errObj = isRecord(parsed.error) ? parsed.error : parsed;
560
+ const msg = redactProviderSecrets(
561
+ typeof errObj.message === 'string' ? errObj.message : JSON.stringify(errObj),
562
+ options.secrets
563
+ );
564
+ throw new Error(`${options.providerLabel} stream error: ${msg}`);
565
+ }
566
+
567
+ if (eventType === 'message_start' && isRecord(parsed.message) && isRecord(parsed.message.usage)) {
568
+ applyUsage(parsed.message.usage);
569
+ return;
570
+ }
571
+
572
+ if (eventType === 'message_delta') {
573
+ if (isRecord(parsed.delta) && typeof parsed.delta.stop_reason === 'string') {
574
+ stopReason = parsed.delta.stop_reason;
575
+ }
576
+ if (isRecord(parsed.usage)) {
577
+ applyUsage(parsed.usage);
578
+ }
579
+ return;
580
+ }
581
+
582
+ if (eventType === 'content_block_start' && typeof parsed.index === 'number' && Number.isInteger(parsed.index) && parsed.index >= 0 && isRecord(parsed.content_block)) {
583
+ const initial = { ...parsed.content_block };
584
+ if (initial.type === 'text' && typeof initial.text === 'string' && initial.text) {
585
+ options.onChunk?.(initial.text);
586
+ } else if (initial.type === 'thinking' && typeof initial.thinking === 'string' && initial.thinking) {
587
+ options.onReasoningChunk?.(initial.thinking);
588
+ }
589
+ blockMap.set(parsed.index, { block: initial, partialJson: '' });
590
+ return;
591
+ }
592
+
593
+ if (eventType === 'content_block_delta' && typeof parsed.index === 'number' && isRecord(parsed.delta)) {
594
+ const acc = blockMap.get(parsed.index);
595
+ if (!acc) return;
596
+ const delta = parsed.delta;
597
+ const deltaType = typeof delta.type === 'string' ? delta.type : '';
598
+
599
+ if (deltaType === 'text_delta' && typeof delta.text === 'string') {
600
+ acc.block.text = `${typeof acc.block.text === 'string' ? acc.block.text : ''}${delta.text}`;
601
+ if (delta.text) options.onChunk?.(delta.text);
602
+ } else if (deltaType === 'thinking_delta' && typeof delta.thinking === 'string') {
603
+ acc.block.thinking = `${typeof acc.block.thinking === 'string' ? acc.block.thinking : ''}${delta.thinking}`;
604
+ if (delta.thinking) options.onReasoningChunk?.(delta.thinking);
605
+ } else if (deltaType === 'signature_delta' && typeof delta.signature === 'string') {
606
+ acc.block.signature = `${typeof acc.block.signature === 'string' ? acc.block.signature : ''}${delta.signature}`;
607
+ } else if (deltaType === 'input_json_delta' && typeof delta.partial_json === 'string') {
608
+ acc.partialJson += delta.partial_json;
609
+ }
610
+ }
611
+ },
612
+ options.signal
613
+ );
614
+ } finally {
615
+ opened.cleanup();
616
+ }
617
+
618
+ const contentBlocks = [...blockMap.entries()]
619
+ .sort((a, b) => a[0] - b[0])
620
+ .map(([, acc]) => {
621
+ if (acc.block.type === 'tool_use' && acc.partialJson.trim().length > 0) {
622
+ const recovered = safeParseJsonObject(acc.partialJson);
623
+ if (Object.keys(recovered).length > 0) {
624
+ acc.block.input = recovered;
625
+ }
626
+ }
627
+ return acc.block;
628
+ });
629
+
630
+ return { content: contentBlocks, usage, ...(stopReason ? { stop_reason: stopReason } : {}) };
631
+ }
632
+
633
+ /**
634
+ * Converts a Gemini `:generateContent` endpoint URL to `:streamGenerateContent?alt=sse`
635
+ * while preserving the host, model path, and avoiding any API key in the query string.
636
+ */
637
+ export function buildGeminiStreamUrl(generateContentUrl: string): string {
638
+ const parsed = new URL(generateContentUrl);
639
+ parsed.searchParams.delete('key');
640
+ if (parsed.pathname.endsWith(':generateContent')) {
641
+ parsed.pathname = `${parsed.pathname.slice(0, -':generateContent'.length)}:streamGenerateContent`;
642
+ }
643
+ parsed.searchParams.set('alt', 'sse');
644
+ return parsed.toString();
645
+ }
646
+
647
+ /**
648
+ * Streams a Gemini `:streamGenerateContent?alt=sse` response and reconstructs
649
+ * the standard Gemini response (`candidates[0].content.parts`, `usageMetadata`,
650
+ * plus optional accumulated `reasoningContent` from `thought: true` parts).
651
+ */
652
+ export async function streamGeminiGenerateContent(
653
+ options: Omit<StreamFetchOptions, 'body'> & { payload: Record<string, unknown> }
654
+ ): Promise<Record<string, unknown> & { reasoningContent?: string }> {
655
+ const streamUrl = buildGeminiStreamUrl(options.url);
656
+ const opened = await openHardenedStream({
657
+ ...options,
658
+ url: streamUrl,
659
+ headers: {
660
+ Accept: 'text/event-stream, application/json',
661
+ ...(options.headers ?? {})
662
+ },
663
+ body: JSON.stringify(options.payload)
664
+ });
665
+
666
+ if (opened.mode === 'json') {
667
+ if (isRecord(opened.data.error)) {
668
+ const msg = redactProviderSecrets(
669
+ typeof opened.data.error.message === 'string' ? opened.data.error.message : JSON.stringify(opened.data.error),
670
+ options.secrets
671
+ );
672
+ throw new Error(`${options.providerLabel} stream error: ${msg}`);
673
+ }
674
+ const candidates = Array.isArray(opened.data.candidates) ? opened.data.candidates : [];
675
+ const first = isRecord(candidates[0]) ? candidates[0] : null;
676
+ const content = first && isRecord(first.content) ? first.content : null;
677
+ const parts = content && Array.isArray(content.parts) ? content.parts : [];
678
+ let reasoning = '';
679
+ for (const part of parts) {
680
+ if (!isRecord(part) || typeof part.text !== 'string' || !part.text) continue;
681
+ if (part.thought === true) {
682
+ reasoning += part.text;
683
+ options.onReasoningChunk?.(part.text);
684
+ } else {
685
+ options.onChunk?.(part.text);
686
+ }
687
+ }
688
+ return reasoning ? { ...opened.data, reasoningContent: reasoning } : opened.data;
689
+ }
690
+
691
+ let textContent = '';
692
+ let reasoningContent = '';
693
+ const functionCallParts: Array<Record<string, unknown>> = [];
694
+ let usageMetadata: Record<string, unknown> | undefined;
695
+ let promptFeedback: Record<string, unknown> | undefined;
696
+ let finishReason: string | undefined;
697
+ let sawCandidate = false;
698
+
699
+ try {
700
+ await consumeSseStream(
701
+ opened.response,
702
+ options.providerLabel,
703
+ options.maxBytes ?? MAX_PROVIDER_JSON_BYTES,
704
+ ({ data }) => {
705
+ const trimmed = data.trim();
706
+ if (!trimmed || trimmed === '[DONE]') return;
707
+ let parsed: unknown;
708
+ try {
709
+ parsed = JSON.parse(trimmed);
710
+ } catch {
711
+ return;
712
+ }
713
+ if (!isRecord(parsed)) return;
714
+
715
+ if (isRecord(parsed.error)) {
716
+ const msg = redactProviderSecrets(
717
+ typeof parsed.error.message === 'string' ? parsed.error.message : JSON.stringify(parsed.error),
718
+ options.secrets
719
+ );
720
+ throw new Error(`${options.providerLabel} stream error: ${msg}`);
721
+ }
722
+
723
+ if (isRecord(parsed.usageMetadata)) {
724
+ usageMetadata = parsed.usageMetadata;
725
+ }
726
+ if (isRecord(parsed.promptFeedback)) {
727
+ promptFeedback = parsed.promptFeedback;
728
+ }
729
+
730
+ const candidates = Array.isArray(parsed.candidates) ? parsed.candidates : [];
731
+ const first = isRecord(candidates[0]) ? candidates[0] : null;
732
+ if (!first) return;
733
+ sawCandidate = true;
734
+ if (typeof first.finishReason === 'string') finishReason = first.finishReason;
735
+
736
+ const content = isRecord(first.content) ? first.content : null;
737
+ const parts = content && Array.isArray(content.parts) ? content.parts : [];
738
+ for (const part of parts) {
739
+ if (!isRecord(part)) continue;
740
+ if (typeof part.text === 'string' && part.text.length > 0) {
741
+ if (part.thought === true) {
742
+ reasoningContent += part.text;
743
+ options.onReasoningChunk?.(part.text);
744
+ } else {
745
+ textContent += part.text;
746
+ options.onChunk?.(part.text);
747
+ }
748
+ } else if (isRecord(part.functionCall)) {
749
+ const fcPart: Record<string, unknown> = { functionCall: part.functionCall };
750
+ const sig = typeof part.thoughtSignature === 'string' ? part.thoughtSignature : (typeof part.thought_signature === 'string' ? part.thought_signature : undefined);
751
+ if (sig) fcPart.thoughtSignature = sig;
752
+ functionCallParts.push(fcPart);
753
+ }
754
+ }
755
+ },
756
+ options.signal
757
+ );
758
+ } finally {
759
+ opened.cleanup();
760
+ }
761
+
762
+ const finalParts: Array<Record<string, unknown>> = [];
763
+ if (textContent) finalParts.push({ text: textContent });
764
+ finalParts.push(...functionCallParts);
765
+
766
+ return {
767
+ candidates: sawCandidate ? [{ content: { role: 'model', parts: finalParts }, ...(finishReason ? { finishReason } : {}) }] : [],
768
+ ...(usageMetadata ? { usageMetadata } : {}),
769
+ ...(promptFeedback ? { promptFeedback } : {}),
770
+ ...(reasoningContent ? { reasoningContent } : {})
771
+ };
772
+ }
773
+
774
+ /**
775
+ * Streams an Ollama `/api/chat` request via NDJSON (`stream: true`) and returns
776
+ * the standard Ollama response shape (`message.content`, `message.thinking`,
777
+ * `message.tool_calls`, `prompt_eval_count`, `eval_count`).
778
+ */
779
+ export async function streamOllamaChat(
780
+ options: Omit<StreamFetchOptions, 'body'> & { payload: Record<string, unknown> }
781
+ ): Promise<Record<string, unknown>> {
782
+ const streamPayload: Record<string, unknown> = {
783
+ ...options.payload,
784
+ stream: true
785
+ };
786
+
787
+ const opened = await openHardenedStream({
788
+ ...options,
789
+ headers: {
790
+ Accept: 'application/x-ndjson, application/json',
791
+ ...(options.headers ?? {})
792
+ },
793
+ body: JSON.stringify(streamPayload)
794
+ });
795
+
796
+ if (opened.mode === 'json') {
797
+ if (typeof opened.data.error === 'string' && opened.data.error) {
798
+ throw new Error(`${options.providerLabel} stream error: ${redactProviderSecrets(opened.data.error, options.secrets)}`);
799
+ }
800
+ if (isRecord(opened.data.error)) {
801
+ const errMsg = typeof opened.data.error.message === 'string' ? opened.data.error.message : JSON.stringify(opened.data.error);
802
+ throw new Error(`${options.providerLabel} stream error: ${redactProviderSecrets(errMsg, options.secrets)}`);
803
+ }
804
+ const msg = isRecord(opened.data.message) ? opened.data.message : null;
805
+ if (msg) {
806
+ if (typeof msg.thinking === 'string' && msg.thinking) options.onReasoningChunk?.(msg.thinking);
807
+ if (typeof msg.content === 'string' && msg.content) options.onChunk?.(msg.content);
808
+ }
809
+ return opened.data;
810
+ }
811
+
812
+ let content = '';
813
+ let thinking = '';
814
+ const toolCalls: unknown[] = [];
815
+ let promptEvalCount = 0;
816
+ let evalCount = 0;
817
+
818
+ try {
819
+ await consumeNdjsonStream(
820
+ opened.response,
821
+ options.providerLabel,
822
+ options.maxBytes ?? MAX_PROVIDER_JSON_BYTES,
823
+ (chunk) => {
824
+ if (typeof chunk.error === 'string' && chunk.error) {
825
+ throw new Error(`${options.providerLabel} stream error: ${redactProviderSecrets(chunk.error, options.secrets)}`);
826
+ }
827
+ if (isRecord(chunk.error)) {
828
+ const errMsg = typeof chunk.error.message === 'string' ? chunk.error.message : JSON.stringify(chunk.error);
829
+ throw new Error(`${options.providerLabel} stream error: ${redactProviderSecrets(errMsg, options.secrets)}`);
830
+ }
831
+ const msg = isRecord(chunk.message) ? chunk.message : null;
832
+ if (msg) {
833
+ if (typeof msg.thinking === 'string' && msg.thinking.length > 0) {
834
+ thinking += msg.thinking;
835
+ options.onReasoningChunk?.(msg.thinking);
836
+ }
837
+ if (typeof msg.content === 'string' && msg.content.length > 0) {
838
+ content += msg.content;
839
+ options.onChunk?.(msg.content);
840
+ }
841
+ if (Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0) {
842
+ toolCalls.push(...msg.tool_calls);
843
+ }
844
+ }
845
+ if (typeof chunk.prompt_eval_count === 'number' && Number.isFinite(chunk.prompt_eval_count) && chunk.prompt_eval_count >= 0) promptEvalCount = chunk.prompt_eval_count;
846
+ if (typeof chunk.eval_count === 'number' && Number.isFinite(chunk.eval_count) && chunk.eval_count >= 0) evalCount = chunk.eval_count;
847
+ },
848
+ options.signal
849
+ );
850
+ } finally {
851
+ opened.cleanup();
852
+ }
853
+
854
+ const message: Record<string, unknown> = { role: 'assistant', content };
855
+ if (thinking) message.thinking = thinking;
856
+ if (toolCalls.length > 0) message.tool_calls = toolCalls;
857
+
858
+ return {
859
+ message,
860
+ prompt_eval_count: promptEvalCount,
861
+ eval_count: evalCount
862
+ };
863
+ }