@causyne/agent 1.20.121 → 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 (256) 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 +6 -2
  14. package/src/agent/errorClassifier.ts +6 -2
  15. package/src/agentLoop.js +11 -5
  16. package/src/agentLoop.ts +11 -5
  17. package/src/approvalGrants.js +19 -7
  18. package/src/approvalGrants.ts +20 -7
  19. package/src/approvalPolicy.js +48 -15
  20. package/src/approvalPolicy.ts +46 -15
  21. package/src/autoUpdate.js +5 -2
  22. package/src/autoUpdate.ts +5 -2
  23. package/src/browser/causyneBrowser.js +3 -2
  24. package/src/browser/causyneBrowser.ts +3 -2
  25. package/src/browser/searchProviders.js +1 -1
  26. package/src/browser/searchProviders.ts +1 -1
  27. package/src/config.js +287 -250
  28. package/src/config.ts +342 -0
  29. package/src/configVault.js +84 -17
  30. package/src/configVault.ts +77 -17
  31. package/src/continuum/compactor.js +2 -1
  32. package/src/continuum/compactor.ts +2 -1
  33. package/src/continuum/sanitizer.js +10 -3
  34. package/src/continuum/sanitizer.ts +9 -3
  35. package/src/continuum/ui/continuumPickerView.js +3 -2
  36. package/src/continuum/ui/continuumPickerView.ts +3 -2
  37. package/src/cortex/vectorDb.js +26 -15
  38. package/src/cortex/vectorDb.ts +26 -16
  39. package/src/creative/liveBridge.js +7 -5
  40. package/src/creative/liveBridge.ts +7 -5
  41. package/src/creative/studioScripts.js +16 -5
  42. package/src/creative/studioScripts.ts +14 -5
  43. package/src/decisionPolicy.js +16 -4
  44. package/src/decisionPolicy.ts +14 -4
  45. package/src/documentEngine/antiSlopAuditor.js +10 -5
  46. package/src/documentEngine/antiSlopAuditor.ts +11 -5
  47. package/src/documentEngine/documentForge.js +47 -15
  48. package/src/documentEngine/documentForge.ts +43 -14
  49. package/src/engines/design.js +2 -1
  50. package/src/engines/design.ts +2 -1
  51. package/src/engines/film.js +4 -4
  52. package/src/engines/film.ts +2 -2
  53. package/src/engines/light.js +2 -1
  54. package/src/engines/light.ts +2 -1
  55. package/src/engines/registry.js +1 -1
  56. package/src/engines/registry.ts +1 -1
  57. package/src/engines/reverseHarness.js +4 -3
  58. package/src/engines/reverseHarness.ts +4 -3
  59. package/src/headlessCli.js +2 -1
  60. package/src/headlessCli.ts +2 -1
  61. package/src/historyPruner.js +3 -2
  62. package/src/historyPruner.ts +3 -2
  63. package/src/hooks.js +3 -0
  64. package/src/hooks.ts +3 -0
  65. package/src/implementationPlan.js +21 -11
  66. package/src/implementationPlan.ts +21 -11
  67. package/src/infra/atomicWriter.js +4 -1
  68. package/src/infra/atomicWriter.ts +4 -1
  69. package/src/launchIntent.js +1 -1
  70. package/src/launchIntent.ts +1 -1
  71. package/src/memory/scopedFacts.js +1 -1
  72. package/src/memory/scopedFacts.ts +1 -1
  73. package/src/memory/symbolFolder.js +1 -1
  74. package/src/memory/symbolFolder.ts +1 -1
  75. package/src/modelRouter.js +1 -1
  76. package/src/modelRouter.ts +1 -1
  77. package/src/observer/evidence.js +10 -4
  78. package/src/observer/evidence.ts +10 -4
  79. package/src/osKeychain.js +62 -8
  80. package/src/osKeychain.ts +50 -8
  81. package/src/perception.js +3 -2
  82. package/src/perception.ts +3 -2
  83. package/src/planCache.js +2 -2
  84. package/src/planCache.ts +2 -2
  85. package/src/pluginsFactory/pluginsFactory.js +19 -11
  86. package/src/pluginsFactory/pluginsFactory.ts +18 -11
  87. package/src/promptMentions.js +2 -2
  88. package/src/promptMentions.ts +2 -2
  89. package/src/providers/acp.js +1 -1
  90. package/src/providers/acp.ts +1 -1
  91. package/src/providers/anthropic.js +327 -401
  92. package/src/providers/anthropic.ts +386 -0
  93. package/src/providers/antigravity.js +10 -4
  94. package/src/providers/antigravity.ts +10 -4
  95. package/src/providers/base.js +221 -319
  96. package/src/providers/base.ts +340 -0
  97. package/src/providers/byokHttp.js +58 -15
  98. package/src/providers/byokHttp.ts +59 -16
  99. package/src/providers/byokStream.js +142 -51
  100. package/src/providers/byokStream.ts +146 -42
  101. package/src/providers/dashscope-byok.js +97 -89
  102. package/src/providers/dashscope-byok.ts +114 -0
  103. package/src/providers/deepseek.js +73 -72
  104. package/src/providers/deepseek.ts +99 -0
  105. package/src/providers/factory.js +35 -28
  106. package/src/providers/factory.ts +40 -0
  107. package/src/providers/gemini.js +227 -278
  108. package/src/providers/gemini.ts +261 -0
  109. package/src/providers/loopGuard.js +9 -5
  110. package/src/providers/loopGuard.ts +10 -5
  111. package/src/providers/moonshot.js +70 -72
  112. package/src/providers/moonshot.ts +93 -0
  113. package/src/providers/muse.js +82 -152
  114. package/src/providers/muse.ts +122 -0
  115. package/src/providers/ollama.js +114 -106
  116. package/src/providers/ollama.ts +135 -0
  117. package/src/providers/openai-compatible.js +113 -96
  118. package/src/providers/openai-compatible.ts +139 -0
  119. package/src/providers/openai.js +22 -15
  120. package/src/providers/openai.ts +30 -0
  121. package/src/providers/openrouter.js +136 -74
  122. package/src/providers/openrouter.ts +133 -72
  123. package/src/providers/pi.js +6 -0
  124. package/src/providers/pi.ts +6 -0
  125. package/src/providers/qwen-byok.js +96 -87
  126. package/src/providers/qwen-byok.ts +113 -0
  127. package/src/providers/toolContracts.js +40 -14
  128. package/src/providers/toolContracts.ts +35 -14
  129. package/src/providers/wireNormalizer.js +78 -11
  130. package/src/providers/wireNormalizer.ts +68 -12
  131. package/src/providers/xai.js +73 -72
  132. package/src/providers/xai.ts +97 -0
  133. package/src/reliability/assetEvidence.js +4 -2
  134. package/src/reliability/assetEvidence.ts +4 -2
  135. package/src/sandbox.js +489 -554
  136. package/src/sandbox.ts +552 -0
  137. package/src/sandboxPolicy.js +95 -16
  138. package/src/sandboxPolicy.ts +97 -16
  139. package/src/sessionJournal.js +8 -3
  140. package/src/sessionJournal.ts +9 -3
  141. package/src/skills/skillResourceSafety.js +19 -8
  142. package/src/skills/skillResourceSafety.ts +16 -7
  143. package/src/skillsManager.js +3 -3
  144. package/src/skillsManager.ts +3 -3
  145. package/src/smartToolsUse.js +28 -4
  146. package/src/smartToolsUse.ts +29 -7
  147. package/src/stallGuard.js +45 -22
  148. package/src/stallGuard.ts +46 -22
  149. package/src/subagentJournal.js +6 -4
  150. package/src/subagentJournal.ts +6 -4
  151. package/src/textDiff.js +6 -1
  152. package/src/textDiff.ts +6 -1
  153. package/src/timeMachine.js +7 -1
  154. package/src/timeMachine.ts +7 -1
  155. package/src/tokenTracker.js +43 -28
  156. package/src/tokenTracker.ts +44 -30
  157. package/src/toolPacks.js +3 -1
  158. package/src/toolPacks.ts +3 -1
  159. package/src/tools/archive.js +245 -35
  160. package/src/tools/archive.ts +244 -35
  161. package/src/tools/computerUse.js +7 -3
  162. package/src/tools/computerUse.ts +7 -3
  163. package/src/tools/creativeApps.js +13 -8
  164. package/src/tools/creativeApps.ts +22 -9
  165. package/src/tools/deferredMcpSearch.js +26 -14
  166. package/src/tools/deferredMcpSearch.ts +26 -14
  167. package/src/tools/desktopOpen.js +69 -10
  168. package/src/tools/desktopOpen.ts +70 -11
  169. package/src/tools/documentForge.js +167 -82
  170. package/src/tools/documentForge.ts +169 -84
  171. package/src/tools/fsEdit.js +101 -30
  172. package/src/tools/fsEdit.ts +105 -32
  173. package/src/tools/fsFind.js +8 -5
  174. package/src/tools/fsFind.ts +7 -4
  175. package/src/tools/fsRead.js +119 -13
  176. package/src/tools/fsRead.ts +124 -13
  177. package/src/tools/fsWrite.js +17 -5
  178. package/src/tools/fsWrite.ts +17 -7
  179. package/src/tools/generateMediaViaApi.js +82 -19
  180. package/src/tools/generateMediaViaApi.ts +80 -19
  181. package/src/tools/memoryRecall.js +62 -11
  182. package/src/tools/memoryRecall.ts +70 -13
  183. package/src/tools/memoryWrite.js +27 -14
  184. package/src/tools/memoryWrite.ts +30 -14
  185. package/src/tools/multiEdit.js +100 -30
  186. package/src/tools/multiEdit.ts +104 -32
  187. package/src/tools/nativeEngine.js +33 -18
  188. package/src/tools/nativeEngine.ts +31 -18
  189. package/src/tools/openSourceToolProvisioner.js +49 -14
  190. package/src/tools/openSourceToolProvisioner.ts +54 -15
  191. package/src/tools/osSandbox.js +54 -14
  192. package/src/tools/osSandbox.ts +48 -14
  193. package/src/tools/payloadSanitizer.js +40 -8
  194. package/src/tools/payloadSanitizer.ts +39 -8
  195. package/src/tools/peerAgent.js +96 -34
  196. package/src/tools/peerAgent.ts +114 -37
  197. package/src/tools/pluginsFactory.js +38 -6
  198. package/src/tools/pluginsFactory.ts +42 -6
  199. package/src/tools/readNativeSkill.js +10 -8
  200. package/src/tools/readNativeSkill.ts +10 -8
  201. package/src/tools/requestDecision.js +10 -3
  202. package/src/tools/requestDecision.ts +10 -3
  203. package/src/tools/resolveAutomator.js +91 -17
  204. package/src/tools/resolveAutomator.ts +102 -17
  205. package/src/tools/reverseEngineering.js +168 -41
  206. package/src/tools/reverseEngineering.ts +161 -41
  207. package/src/tools/sysRun.js +69 -29
  208. package/src/tools/sysRun.ts +66 -24
  209. package/src/tools/toolDispatch.js +24 -1
  210. package/src/tools/toolDispatch.ts +21 -1
  211. package/src/tools/toolOutputStore.js +62 -23
  212. package/src/tools/toolOutputStore.ts +56 -23
  213. package/src/tools/toolScanner.js +13 -10
  214. package/src/tools/toolScanner.ts +13 -10
  215. package/src/tools/toolSelfRepair.js +94 -28
  216. package/src/tools/toolSelfRepair.ts +96 -28
  217. package/src/tools/uiForge.js +71 -6
  218. package/src/tools/uiForge.ts +74 -6
  219. package/src/tools/viewImage.js +62 -17
  220. package/src/tools/viewImage.ts +57 -12
  221. package/src/tools/visionInspector.js +15 -3
  222. package/src/tools/visionInspector.ts +15 -3
  223. package/src/tools/walkerSafety.js +2 -0
  224. package/src/tools/walkerSafety.ts +1 -0
  225. package/src/tools/webFetch.js +105 -10
  226. package/src/tools/webFetch.ts +105 -11
  227. package/src/tui/banner.js +3 -2
  228. package/src/tui/banner.ts +3 -2
  229. package/src/tui/consoleGuard.js +12 -4
  230. package/src/tui/consoleGuard.ts +9 -4
  231. package/src/tui/messageInteraction.js +2 -3
  232. package/src/tui/messageInteraction.ts +2 -3
  233. package/src/tui/modelPicker.js +1 -0
  234. package/src/tui/modelPicker.ts +1 -0
  235. package/src/tui/overlay.js +3 -1
  236. package/src/tui/overlay.ts +3 -1
  237. package/src/tui/sessionPicker.js +3 -2
  238. package/src/tui/sessionPicker.ts +3 -2
  239. package/src/tui/sessionPickerView.js +7 -1
  240. package/src/tui/sessionPickerView.ts +6 -1
  241. package/src/tui/toolOutputNormalizer.js +2 -3
  242. package/src/tui/toolOutputNormalizer.ts +4 -3
  243. package/src/tui/viewport.js +4 -4
  244. package/src/tui/viewport.ts +5 -5
  245. package/src/tui/workspaceIdentity.js +2 -1
  246. package/src/tui/workspaceIdentity.ts +2 -1
  247. package/src/uncertainty.js +8 -3
  248. package/src/uncertainty.ts +8 -3
  249. package/src/utils/paths.js +8 -5
  250. package/src/utils/paths.ts +9 -7
  251. package/src/vfeTracker.js +9 -3
  252. package/src/vfeTracker.ts +9 -3
  253. package/src/config.d.ts +0 -2
  254. package/src/providers/base.d.ts +0 -94
  255. package/src/providers/factory.d.ts +0 -1
  256. package/src/sandbox.d.ts +0 -1
@@ -12,6 +12,7 @@
12
12
  * - Graceful fallback when an upstream proxy returns non-streaming JSON
13
13
  */
14
14
 
15
+ import { safeParseJsonObject } from './wireNormalizer.js';
15
16
  import {
16
17
  MAX_PROVIDER_ERROR_BYTES,
17
18
  MAX_PROVIDER_JSON_BYTES,
@@ -49,8 +50,8 @@ function getHeader(response: Response, name: string): string {
49
50
  }
50
51
 
51
52
  function isJsonContentType(contentType: string): boolean {
52
- const lower = contentType.toLowerCase();
53
- return lower.includes('application/json') || lower.includes('+json');
53
+ const mediaType = (contentType.split(';')[0] ?? '').trim().toLowerCase();
54
+ return mediaType === 'application/json' || mediaType.endsWith('+json');
54
55
  }
55
56
 
56
57
  function isRecord(value: unknown): value is Record<string, unknown> {
@@ -112,8 +113,9 @@ async function openHardenedStream(
112
113
  options.maxBytes ?? MAX_PROVIDER_JSON_BYTES,
113
114
  { truncate: false, label: options.providerLabel }
114
115
  );
116
+ const cleanText = rawText.charCodeAt(0) === 0xfeff ? rawText.slice(1) : rawText;
115
117
  try {
116
- const parsed: unknown = JSON.parse(rawText);
118
+ const parsed: unknown = JSON.parse(cleanText);
117
119
  return { mode: 'json', data: isRecord(parsed) ? parsed : {} };
118
120
  } catch {
119
121
  const preview = redactProviderSecrets(rawText.slice(0, 240), options.secrets);
@@ -138,54 +140,78 @@ async function consumeSseStream(
138
140
  response: Response,
139
141
  providerLabel: string,
140
142
  maxBytes: number,
141
- onEvent: (event: SseEvent) => void
143
+ onEvent: (event: SseEvent) => void,
144
+ signal?: AbortSignal | undefined
142
145
  ): Promise<void> {
146
+ const safeMaxBytes = typeof maxBytes === 'number' && Number.isFinite(maxBytes) && maxBytes >= 1
147
+ ? Math.floor(maxBytes)
148
+ : MAX_PROVIDER_JSON_BYTES;
143
149
  const reader = response.body!.getReader();
144
150
  const decoder = new TextDecoder('utf-8');
145
151
  let buffer = '';
146
152
  let totalBytes = 0;
147
153
  let currentEvent = '';
148
154
  let dataLines: string[] = [];
155
+ let sawFirstLine = false;
156
+
157
+ let eventBytes = 0;
149
158
 
150
159
  const flushEvent = (): void => {
151
160
  if (dataLines.length === 0) {
152
161
  currentEvent = '';
162
+ eventBytes = 0;
153
163
  return;
154
164
  }
155
165
  const payload = dataLines.join('\n');
156
166
  const eventName = currentEvent || 'message';
157
167
  currentEvent = '';
158
168
  dataLines = [];
169
+ eventBytes = 0;
159
170
  onEvent({ event: eventName, data: payload });
160
171
  };
161
172
 
162
173
  const processLine = (rawLine: string): void => {
163
- const line = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine;
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;
164
180
  if (line === '') {
165
181
  flushEvent();
166
182
  return;
167
183
  }
168
184
  if (line.startsWith(':')) return; // SSE comment / keep-alive
169
185
  if (line.startsWith('event:')) {
170
- currentEvent = line.slice(6).trim();
186
+ const val = line.slice(6);
187
+ currentEvent = (val.startsWith(' ') ? val.slice(1) : val).trim();
171
188
  return;
172
189
  }
173
190
  if (line.startsWith('data:')) {
174
191
  const value = line.slice(5);
175
- dataLines.push(value.startsWith(' ') ? value.slice(1) : value);
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);
176
198
  }
177
199
  };
178
200
 
179
201
  try {
180
202
  while (true) {
203
+ if (signal?.aborted) {
204
+ await reader.cancel().catch(() => {});
205
+ throw signal.reason ?? new DOMException('Aborted', 'AbortError');
206
+ }
181
207
  const { done, value } = await reader.read();
182
208
  if (done) break;
183
209
  if (!value) continue;
184
210
 
185
211
  totalBytes += value.byteLength;
186
- if (totalBytes > maxBytes) {
212
+ if (totalBytes > safeMaxBytes) {
187
213
  await reader.cancel().catch(() => {});
188
- throw new Error(`${providerLabel} stream exceeded maximum allowed size (${maxBytes} bytes).`);
214
+ throw new Error(`${providerLabel} stream exceeded maximum allowed size (${safeMaxBytes} bytes).`);
189
215
  }
190
216
 
191
217
  buffer += decoder.decode(value, { stream: true });
@@ -219,15 +245,20 @@ async function consumeNdjsonStream(
219
245
  response: Response,
220
246
  providerLabel: string,
221
247
  maxBytes: number,
222
- onObject: (obj: Record<string, unknown>) => void
248
+ onObject: (obj: Record<string, unknown>) => void,
249
+ signal?: AbortSignal | undefined
223
250
  ): Promise<void> {
251
+ const safeMaxBytes = typeof maxBytes === 'number' && Number.isFinite(maxBytes) && maxBytes >= 1
252
+ ? Math.floor(maxBytes)
253
+ : MAX_PROVIDER_JSON_BYTES;
224
254
  const reader = response.body!.getReader();
225
255
  const decoder = new TextDecoder('utf-8');
226
256
  let buffer = '';
227
257
  let totalBytes = 0;
228
258
 
229
259
  const processLine = (rawLine: string): void => {
230
- const trimmed = rawLine.trim();
260
+ const stripped = rawLine.charCodeAt(0) === 0xfeff ? rawLine.slice(1) : rawLine;
261
+ const trimmed = stripped.trim();
231
262
  if (!trimmed) return;
232
263
  try {
233
264
  const parsed: unknown = JSON.parse(trimmed);
@@ -239,14 +270,18 @@ async function consumeNdjsonStream(
239
270
 
240
271
  try {
241
272
  while (true) {
273
+ if (signal?.aborted) {
274
+ await reader.cancel().catch(() => {});
275
+ throw signal.reason ?? new DOMException('Aborted', 'AbortError');
276
+ }
242
277
  const { done, value } = await reader.read();
243
278
  if (done) break;
244
279
  if (!value) continue;
245
280
 
246
281
  totalBytes += value.byteLength;
247
- if (totalBytes > maxBytes) {
282
+ if (totalBytes > safeMaxBytes) {
248
283
  await reader.cancel().catch(() => {});
249
- throw new Error(`${providerLabel} stream exceeded maximum allowed size (${maxBytes} bytes).`);
284
+ throw new Error(`${providerLabel} stream exceeded maximum allowed size (${safeMaxBytes} bytes).`);
250
285
  }
251
286
 
252
287
  buffer += decoder.decode(value, { stream: true });
@@ -297,6 +332,13 @@ export async function streamOpenAICompatibleChat(
297
332
  });
298
333
 
299
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
+ }
300
342
  const choices = Array.isArray(opened.data.choices) ? opened.data.choices : [];
301
343
  const first = isRecord(choices[0]) ? choices[0] : null;
302
344
  const message = first && isRecord(first.message) ? first.message : null;
@@ -365,13 +407,34 @@ export async function streamOpenAICompatibleChat(
365
407
  if (typeof delta.content === 'string' && delta.content.length > 0) {
366
408
  content += delta.content;
367
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
+ }
368
417
  }
369
418
 
370
419
  if (Array.isArray(delta.tool_calls)) {
371
420
  for (let pos = 0; pos < delta.tool_calls.length; pos++) {
372
421
  const tc = delta.tool_calls[pos];
373
422
  if (!isRecord(tc)) continue;
374
- const idx = typeof tc.index === 'number' && Number.isInteger(tc.index) ? tc.index : pos;
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
+ }
375
438
  let entry = toolCallMap.get(idx);
376
439
  if (!entry) {
377
440
  entry = { id: '', type: 'function', function: { name: '', arguments: '' } };
@@ -388,7 +451,8 @@ export async function streamOpenAICompatibleChat(
388
451
  }
389
452
  }
390
453
  }
391
- }
454
+ },
455
+ options.signal
392
456
  );
393
457
  } finally {
394
458
  opened.cleanup();
@@ -434,6 +498,14 @@ export async function streamAnthropicMessages(
434
498
  });
435
499
 
436
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
+ }
437
509
  const blocks = Array.isArray(opened.data.content) ? opened.data.content : [];
438
510
  for (const block of blocks) {
439
511
  if (!isRecord(block)) continue;
@@ -457,6 +529,13 @@ export async function streamAnthropicMessages(
457
529
  cache_read_input_tokens: 0,
458
530
  cache_creation_input_tokens: 0
459
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
+ };
460
539
 
461
540
  try {
462
541
  await consumeSseStream(
@@ -486,24 +565,21 @@ export async function streamAnthropicMessages(
486
565
  }
487
566
 
488
567
  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;
568
+ applyUsage(parsed.message.usage);
494
569
  return;
495
570
  }
496
571
 
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;
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
+ }
503
579
  return;
504
580
  }
505
581
 
506
- if (eventType === 'content_block_start' && typeof parsed.index === 'number' && isRecord(parsed.content_block)) {
582
+ if (eventType === 'content_block_start' && typeof parsed.index === 'number' && Number.isInteger(parsed.index) && parsed.index >= 0 && isRecord(parsed.content_block)) {
507
583
  const initial = { ...parsed.content_block };
508
584
  if (initial.type === 'text' && typeof initial.text === 'string' && initial.text) {
509
585
  options.onChunk?.(initial.text);
@@ -532,7 +608,8 @@ export async function streamAnthropicMessages(
532
608
  acc.partialJson += delta.partial_json;
533
609
  }
534
610
  }
535
- }
611
+ },
612
+ options.signal
536
613
  );
537
614
  } finally {
538
615
  opened.cleanup();
@@ -542,19 +619,15 @@ export async function streamAnthropicMessages(
542
619
  .sort((a, b) => a[0] - b[0])
543
620
  .map(([, acc]) => {
544
621
  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
622
+ const recovered = safeParseJsonObject(acc.partialJson);
623
+ if (Object.keys(recovered).length > 0) {
624
+ acc.block.input = recovered;
552
625
  }
553
626
  }
554
627
  return acc.block;
555
628
  });
556
629
 
557
- return { content: contentBlocks, usage };
630
+ return { content: contentBlocks, usage, ...(stopReason ? { stop_reason: stopReason } : {}) };
558
631
  }
559
632
 
560
633
  /**
@@ -563,6 +636,7 @@ export async function streamAnthropicMessages(
563
636
  */
564
637
  export function buildGeminiStreamUrl(generateContentUrl: string): string {
565
638
  const parsed = new URL(generateContentUrl);
639
+ parsed.searchParams.delete('key');
566
640
  if (parsed.pathname.endsWith(':generateContent')) {
567
641
  parsed.pathname = `${parsed.pathname.slice(0, -':generateContent'.length)}:streamGenerateContent`;
568
642
  }
@@ -590,6 +664,13 @@ export async function streamGeminiGenerateContent(
590
664
  });
591
665
 
592
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
+ }
593
674
  const candidates = Array.isArray(opened.data.candidates) ? opened.data.candidates : [];
594
675
  const first = isRecord(candidates[0]) ? candidates[0] : null;
595
676
  const content = first && isRecord(first.content) ? first.content : null;
@@ -611,6 +692,8 @@ export async function streamGeminiGenerateContent(
611
692
  let reasoningContent = '';
612
693
  const functionCallParts: Array<Record<string, unknown>> = [];
613
694
  let usageMetadata: Record<string, unknown> | undefined;
695
+ let promptFeedback: Record<string, unknown> | undefined;
696
+ let finishReason: string | undefined;
614
697
  let sawCandidate = false;
615
698
 
616
699
  try {
@@ -640,11 +723,15 @@ export async function streamGeminiGenerateContent(
640
723
  if (isRecord(parsed.usageMetadata)) {
641
724
  usageMetadata = parsed.usageMetadata;
642
725
  }
726
+ if (isRecord(parsed.promptFeedback)) {
727
+ promptFeedback = parsed.promptFeedback;
728
+ }
643
729
 
644
730
  const candidates = Array.isArray(parsed.candidates) ? parsed.candidates : [];
645
731
  const first = isRecord(candidates[0]) ? candidates[0] : null;
646
732
  if (!first) return;
647
733
  sawCandidate = true;
734
+ if (typeof first.finishReason === 'string') finishReason = first.finishReason;
648
735
 
649
736
  const content = isRecord(first.content) ? first.content : null;
650
737
  const parts = content && Array.isArray(content.parts) ? content.parts : [];
@@ -659,10 +746,14 @@ export async function streamGeminiGenerateContent(
659
746
  options.onChunk?.(part.text);
660
747
  }
661
748
  } else if (isRecord(part.functionCall)) {
662
- functionCallParts.push({ functionCall: 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);
663
753
  }
664
754
  }
665
- }
755
+ },
756
+ options.signal
666
757
  );
667
758
  } finally {
668
759
  opened.cleanup();
@@ -673,8 +764,9 @@ export async function streamGeminiGenerateContent(
673
764
  finalParts.push(...functionCallParts);
674
765
 
675
766
  return {
676
- candidates: sawCandidate ? [{ content: { role: 'model', parts: finalParts } }] : [],
767
+ candidates: sawCandidate ? [{ content: { role: 'model', parts: finalParts }, ...(finishReason ? { finishReason } : {}) }] : [],
677
768
  ...(usageMetadata ? { usageMetadata } : {}),
769
+ ...(promptFeedback ? { promptFeedback } : {}),
678
770
  ...(reasoningContent ? { reasoningContent } : {})
679
771
  };
680
772
  }
@@ -702,6 +794,13 @@ export async function streamOllamaChat(
702
794
  });
703
795
 
704
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
+ }
705
804
  const msg = isRecord(opened.data.message) ? opened.data.message : null;
706
805
  if (msg) {
707
806
  if (typeof msg.thinking === 'string' && msg.thinking) options.onReasoningChunk?.(msg.thinking);
@@ -725,6 +824,10 @@ export async function streamOllamaChat(
725
824
  if (typeof chunk.error === 'string' && chunk.error) {
726
825
  throw new Error(`${options.providerLabel} stream error: ${redactProviderSecrets(chunk.error, options.secrets)}`);
727
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
+ }
728
831
  const msg = isRecord(chunk.message) ? chunk.message : null;
729
832
  if (msg) {
730
833
  if (typeof msg.thinking === 'string' && msg.thinking.length > 0) {
@@ -739,9 +842,10 @@ export async function streamOllamaChat(
739
842
  toolCalls.push(...msg.tool_calls);
740
843
  }
741
844
  }
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
- }
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
745
849
  );
746
850
  } finally {
747
851
  opened.cleanup();
@@ -3,98 +3,106 @@ import { DEFAULT_MODEL_BY_PROVIDER } from '../modelCatalogue.js';
3
3
  import { LLMProvider } from './base.js';
4
4
  import { scanAndAdaptToolsForProvider } from '../tools/toolScanner.js';
5
5
  import { normalizeOpenAIChatChoiceResponse } from './wireNormalizer.js';
6
- import {
7
- requireApiKey,
8
- resolveTemperature,
9
- safeProviderFetchJson
10
- } from './byokHttp.js';
6
+ import { requireApiKey, resolveTemperature, safeProviderFetchJson } from './byokHttp.js';
11
7
  import { streamOpenAICompatibleChat, wantsStreaming } from './byokStream.js';
12
-
13
- // Direct DashScope API connection for BYOK (unlike dashscope.js which is the proxy for Free Demo)
14
8
  export class DashscopeByokProvider extends LLMProvider {
15
- constructor(config) {
16
- super(config);
17
- // Use International/Singapore endpoint by default, allow override via config
18
- let url = config.baseUrl || 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions';
19
- if (url.endsWith('/v1')) url += '/chat/completions';
20
- else if (url.endsWith('/v1/')) url += 'chat/completions';
21
-
22
- this.baseUrl = url;
23
- this.allowInsecureHttp = config.allowInsecureHttp === true;
24
- this.model = canonicalModelId(config.model || DEFAULT_MODEL_BY_PROVIDER['dashscope-byok']);
25
- this.apiKey = config.apiKey;
26
- this.visionModels = ['-vl-', '-vl', 'qwen3.6', 'qwen3.7', 'kimi-k2.5', 'kimi-k2.7'];
27
- // Qwen exposes audio on the omni and dedicated audio families only; the
28
- // -vl- vision models are image-in, text-out and reject an audio block.
29
- this.audioModels = ['-omni', 'qwen-audio', 'qwen2-audio'];
30
- }
31
-
32
- async chat(messages, options = {}) {
33
- const apiKey = requireApiKey(this.apiKey, 'Qwen DashScope');
34
- const activeModel = this.model || DEFAULT_MODEL_BY_PROVIDER['dashscope-byok'] || 'qwen3.7-plus';
35
-
36
- const sanitizedMessages = this.prepareMessages(messages);
37
-
38
- const payload = {
39
- model: activeModel,
40
- messages: sanitizedMessages,
41
- temperature: resolveTemperature(options.temperature, 0.1),
42
- };
43
-
44
- if (options.jsonMode) {
45
- payload.response_format = { type: 'json_object' };
46
- }
47
-
48
- let freeFormPaths = new Map();
49
- if (options.tools && options.tools.length > 0) {
50
- const scanReport = scanAndAdaptToolsForProvider(options.tools, 'dashscope');
51
- payload.tools = scanReport.adaptedTools;
52
- payload.tool_choice = "auto";
53
- freeFormPaths = scanReport.freeFormPaths;
9
+ allowInsecureHttp;
10
+ constructor(config = {}) {
11
+ super(config);
12
+ let url = (typeof config.baseUrl === 'string' ? config.baseUrl.trim() : '') || 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions';
13
+ try {
14
+ const parsed = new URL(url);
15
+ if (parsed.pathname.endsWith('/v1')) {
16
+ parsed.pathname += '/chat/completions';
17
+ url = parsed.toString();
18
+ }
19
+ else if (parsed.pathname.endsWith('/v1/')) {
20
+ parsed.pathname += 'chat/completions';
21
+ url = parsed.toString();
22
+ }
23
+ }
24
+ catch {
25
+ if (url.endsWith('/v1'))
26
+ url += '/chat/completions';
27
+ else if (url.endsWith('/v1/'))
28
+ url += 'chat/completions';
29
+ }
30
+ this.baseUrl = url;
31
+ this.allowInsecureHttp = config.allowInsecureHttp === true;
32
+ this.model = String(canonicalModelId(config.model || DEFAULT_MODEL_BY_PROVIDER['dashscope-byok']) || '');
33
+ this.apiKey = config.apiKey;
34
+ this.visionModels = ['-vl-', '-vl', 'qwen3.6', 'qwen3.7', 'kimi-k2.5', 'kimi-k2.7'];
35
+ this.audioModels = ['-omni', 'qwen-audio', 'qwen2-audio'];
54
36
  }
55
-
56
- const requestOpts = {
57
- url: this.baseUrl,
58
- method: 'POST',
59
- headers: {
60
- 'Content-Type': 'application/json',
61
- 'Authorization': `Bearer ${apiKey}`
62
- },
63
- signal: options.signal,
64
- timeoutMs: options.timeoutMs,
65
- providerLabel: 'Qwen DashScope',
66
- secrets: [apiKey],
67
- hasApiKey: true,
68
- allowInsecureHttp: this.allowInsecureHttp,
69
- onHttpError: ({ status }) => {
70
- // Enterprise Error Handling: Detect Workspace-bound API Key configuration errors
71
- if (status === 401 && apiKey.startsWith('sk-ws-') && !this.baseUrl.includes('ws-')) {
72
- throw new Error(`\n[QWEN WORKSPACE CONFIGURATION ERROR]\n\nYou are using a Workspace-bound API Key (starts with sk-ws-), but you haven't configured your Workspace Base URL!\n\nAlibaba requires a specific URL for these keys.\n\nHOW TO FIX THIS:\n1. Open your computer terminal.\n2. Run command: causyne-agent config\n3. When asked for 'Custom Base URL', paste your Workspace URL from Alibaba (e.g. https://{Your-Workspace-ID}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions).\n\nAlternatively, use a Standard API Key (starts with sk-) which does not require a custom URL.`);
37
+ async chat(messages, options = {}) {
38
+ const apiKey = requireApiKey(this.apiKey, 'Qwen DashScope');
39
+ const activeModel = String(canonicalModelId(this.model || DEFAULT_MODEL_BY_PROVIDER['dashscope-byok'] || 'qwen3.7-plus') || 'qwen3.7-plus');
40
+ const sanitizedMessages = this.prepareMessages(messages);
41
+ const payload = {
42
+ model: activeModel,
43
+ messages: sanitizedMessages,
44
+ temperature: resolveTemperature(options.temperature, 0.1)
45
+ };
46
+ if (typeof options.maxTokens === 'number' && Number.isFinite(options.maxTokens) && options.maxTokens >= 1) {
47
+ payload['max_tokens'] = Math.floor(options.maxTokens);
73
48
  }
74
- }
75
- };
76
-
77
- const data = wantsStreaming(options)
78
- ? await streamOpenAICompatibleChat({
79
- ...requestOpts,
80
- payload,
81
- onChunk: options.onChunk,
82
- onReasoningChunk: options.onReasoningChunk
83
- })
84
- : await safeProviderFetchJson({
85
- ...requestOpts,
86
- body: JSON.stringify(payload)
49
+ if (options.jsonMode) {
50
+ payload['response_format'] = { type: 'json_object' };
51
+ }
52
+ let freeFormPaths = new Map();
53
+ if (options.tools && options.tools.length > 0) {
54
+ const scanReport = scanAndAdaptToolsForProvider(options.tools, 'dashscope');
55
+ payload['tools'] = scanReport.adaptedTools;
56
+ payload['tool_choice'] = 'auto';
57
+ freeFormPaths = scanReport.freeFormPaths;
58
+ }
59
+ const endpoint = this.baseUrl || 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions';
60
+ const requestOpts = {
61
+ url: endpoint,
62
+ method: 'POST',
63
+ headers: {
64
+ 'Content-Type': 'application/json',
65
+ 'Authorization': `Bearer ${apiKey}`
66
+ },
67
+ signal: options.signal,
68
+ timeoutMs: options.timeoutMs,
69
+ providerLabel: 'Qwen DashScope',
70
+ secrets: [apiKey],
71
+ hasApiKey: true,
72
+ allowInsecureHttp: this.allowInsecureHttp,
73
+ onHttpError: ({ status }) => {
74
+ let hostHasWorkspace = false;
75
+ try {
76
+ hostHasWorkspace = new URL(endpoint).hostname.includes('ws-');
77
+ }
78
+ catch {
79
+ hostHasWorkspace = false;
80
+ }
81
+ if (status === 401 && apiKey.startsWith('sk-ws-') && !hostHasWorkspace) {
82
+ throw new Error('\n[QWEN WORKSPACE CONFIGURATION ERROR]\n\nYou are using a Workspace-bound API Key (starts with sk-ws-), but you have not configured your Workspace Base URL.\n\nAlibaba requires a specific URL for these keys.\n\nHOW TO FIX THIS:\n1. Open your computer terminal.\n2. Run command: causyne config\n3. When asked for Custom Base URL, paste your Workspace URL from Alibaba (e.g. https://{Your-Workspace-ID}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions).\n\nAlternatively, use a Standard API Key (starts with sk-) which does not require a custom URL.');
83
+ }
84
+ }
85
+ };
86
+ const data = wantsStreaming(options)
87
+ ? await streamOpenAICompatibleChat({
88
+ ...requestOpts,
89
+ payload,
90
+ onChunk: options.onChunk,
91
+ onReasoningChunk: options.onReasoningChunk
92
+ })
93
+ : await safeProviderFetchJson({
94
+ ...requestOpts,
95
+ body: JSON.stringify(payload)
96
+ });
97
+ const normalized = normalizeOpenAIChatChoiceResponse(data, {
98
+ prefix: 'call_dashscope',
99
+ freeFormPaths
87
100
  });
88
- const normalized = normalizeOpenAIChatChoiceResponse(data, {
89
- prefix: 'call_dashscope',
90
- freeFormPaths
91
- });
92
-
93
- return {
94
- content: normalized.content,
95
- toolCalls: normalized.toolCalls,
96
- reasoningContent: normalized.reasoningContent,
97
- usage: this.normalizeUsage(normalized.rawUsage)
98
- };
99
- }
101
+ return {
102
+ content: normalized.content,
103
+ toolCalls: normalized.toolCalls,
104
+ reasoningContent: normalized.reasoningContent,
105
+ usage: this.normalizeUsage(normalized.rawUsage)
106
+ };
107
+ }
100
108
  }