@andorra-labs/code 0.1.17 → 0.1.19

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 (313) hide show
  1. package/dist/src/account-jev-savings.d.ts +4 -0
  2. package/dist/src/account-jev-savings.js +92 -0
  3. package/dist/src/acp-agent.js +2 -2
  4. package/dist/src/agent-execution.js +441 -53
  5. package/dist/src/agent-mcp.js +7 -1
  6. package/dist/src/agent-modifiers.js +5 -7
  7. package/dist/src/analytics.d.ts +19 -1
  8. package/dist/src/analytics.js +9 -1
  9. package/dist/src/andorra/entry.js +15 -6
  10. package/dist/src/andorra/errors.js +3 -0
  11. package/dist/src/andorra/hosted.d.ts +8 -0
  12. package/dist/src/andorra/hosted.js +22 -3
  13. package/dist/src/andorra/streams.d.ts +49 -0
  14. package/dist/src/andorra/streams.js +98 -0
  15. package/dist/src/antigravity-acp.d.ts +28 -0
  16. package/dist/src/antigravity-acp.js +150 -0
  17. package/dist/src/antigravity-terminal.d.ts +2 -0
  18. package/dist/src/antigravity-terminal.js +214 -0
  19. package/dist/src/app-server/adaptive-routing-settings.d.ts +37 -0
  20. package/dist/src/app-server/adaptive-routing-settings.js +69 -0
  21. package/dist/src/app-server/artifact.d.ts +14 -0
  22. package/dist/src/app-server/artifact.js +46 -0
  23. package/dist/src/app-server/legal-protocol.d.ts +33 -0
  24. package/dist/src/app-server/legal-protocol.js +16 -0
  25. package/dist/src/app-server/protocol.d.ts +34 -3
  26. package/dist/src/app-server/protocol.js +3 -1
  27. package/dist/src/app-server/telemetry-protocol.d.ts +53 -0
  28. package/dist/src/app-server/telemetry-protocol.js +2 -0
  29. package/dist/src/app-server/telemetry.d.ts +38 -0
  30. package/dist/src/app-server/telemetry.js +163 -0
  31. package/dist/src/app-server/workspace.d.ts +21 -0
  32. package/dist/src/app-server/workspace.js +192 -10
  33. package/dist/src/app-server.d.ts +82 -26
  34. package/dist/src/app-server.js +1573 -417
  35. package/dist/src/attachments.d.ts +10 -0
  36. package/dist/src/attachments.js +102 -7
  37. package/dist/src/auth/AuthManager.d.ts +11 -2
  38. package/dist/src/auth/AuthManager.js +56 -13
  39. package/dist/src/auth/index.d.ts +5 -1
  40. package/dist/src/auth/index.js +8 -1
  41. package/dist/src/auth/lifecycle.d.ts +13 -0
  42. package/dist/src/auth/lifecycle.js +109 -0
  43. package/dist/src/auth/store.d.ts +1 -0
  44. package/dist/src/auth/store.js +12 -0
  45. package/dist/src/auth/types.d.ts +12 -0
  46. package/dist/src/automation-runner.js +2 -0
  47. package/dist/src/automation-service.js +7 -2
  48. package/dist/src/automation-tool.js +2 -1
  49. package/dist/src/benchmark-scores.d.ts +88 -0
  50. package/dist/src/benchmark-scores.js +302 -0
  51. package/dist/src/bridge/command.js +16 -1
  52. package/dist/src/bridge/control.d.ts +3 -1
  53. package/dist/src/bridge/control.js +9 -3
  54. package/dist/src/bridge/engines.d.ts +2 -0
  55. package/dist/src/bridge/engines.js +9 -0
  56. package/dist/src/bridge/github.d.ts +108 -0
  57. package/dist/src/bridge/github.js +378 -0
  58. package/dist/src/bridge/host-ops.d.ts +3 -3
  59. package/dist/src/bridge/host-ops.js +14 -2
  60. package/dist/src/bridge/host.d.ts +2 -0
  61. package/dist/src/bridge/host.js +70 -16
  62. package/dist/src/bridge/protocol.d.ts +1 -0
  63. package/dist/src/bridge/protocol.js +1 -0
  64. package/dist/src/browser-panel-tool.d.ts +12 -0
  65. package/dist/src/browser-panel-tool.js +30 -3
  66. package/dist/src/browser-runner.js +53 -62
  67. package/dist/src/browser-server.js +10 -4
  68. package/dist/src/browser-session.d.ts +14 -0
  69. package/dist/src/browser-session.js +57 -12
  70. package/dist/src/browser-view.d.ts +40 -1
  71. package/dist/src/browser-view.js +163 -9
  72. package/dist/src/browser-window-style.d.ts +27 -0
  73. package/dist/src/browser-window-style.js +244 -0
  74. package/dist/src/bug-report-attachments.d.ts +48 -0
  75. package/dist/src/bug-report-attachments.js +327 -0
  76. package/dist/src/bug-report.d.ts +23 -3
  77. package/dist/src/bug-report.js +72 -9
  78. package/dist/src/claude-provider.d.ts +1 -0
  79. package/dist/src/claude-provider.js +77 -36
  80. package/dist/src/cli.d.ts +1 -3
  81. package/dist/src/cli.js +245 -62
  82. package/dist/src/codex-provider.d.ts +1 -0
  83. package/dist/src/codex-provider.js +44 -8
  84. package/dist/src/coding-tools.d.ts +1 -0
  85. package/dist/src/coding-tools.js +28 -7
  86. package/dist/src/command-screens.d.ts +1 -1
  87. package/dist/src/command-screens.js +2 -2
  88. package/dist/src/commands.d.ts +9 -2
  89. package/dist/src/commands.js +69 -64
  90. package/dist/src/completion.js +13 -7
  91. package/dist/src/config.d.ts +14 -3
  92. package/dist/src/config.js +57 -17
  93. package/dist/src/context-budget.d.ts +11 -2
  94. package/dist/src/context-budget.js +38 -4
  95. package/dist/src/context-compaction.d.ts +10 -8
  96. package/dist/src/context-compaction.js +23 -24
  97. package/dist/src/deadline.js +1 -1
  98. package/dist/src/decision/DecisionEngine.d.ts +2 -0
  99. package/dist/src/decision/DecisionManager.d.ts +16 -0
  100. package/dist/src/decision/DecisionManager.js +75 -2
  101. package/dist/src/decision/applyTaskKind.d.ts +8 -0
  102. package/dist/src/decision/applyTaskKind.js +53 -0
  103. package/dist/src/decision/applyToolMenu.js +6 -2
  104. package/dist/src/decision/hostedPolicy.js +6 -3
  105. package/dist/src/decision/optimizationPolicy.d.ts +10 -0
  106. package/dist/src/decision/optimizationPolicy.js +23 -3
  107. package/dist/src/decision/providers/AndorraDecisionProvider.d.ts +4 -1
  108. package/dist/src/decision/providers/AndorraDecisionProvider.js +29 -7
  109. package/dist/src/decision/providers/index.js +1 -1
  110. package/dist/src/decision/taskKind.d.ts +52 -0
  111. package/dist/src/decision/taskKind.js +76 -0
  112. package/dist/src/decision/toolFamilies.js +1 -1
  113. package/dist/src/decision/types.d.ts +3 -1
  114. package/dist/src/default-graph.js +1 -1
  115. package/dist/src/efficiency.d.ts +80 -1
  116. package/dist/src/efficiency.js +119 -4
  117. package/dist/src/effort-routing.d.ts +27 -0
  118. package/dist/src/effort-routing.js +34 -0
  119. package/dist/src/evidence.d.ts +110 -0
  120. package/dist/src/evidence.js +195 -0
  121. package/dist/src/extensions.d.ts +2 -0
  122. package/dist/src/extensions.js +30 -20
  123. package/dist/src/github-app/agent-writes.d.ts +1 -1
  124. package/dist/src/github-app/agent-writes.js +1 -1
  125. package/dist/src/github-app/client.d.ts +19 -0
  126. package/dist/src/github-app/client.js +21 -1
  127. package/dist/src/github-app/event-source.d.ts +0 -5
  128. package/dist/src/github-app/event-source.js +1 -31
  129. package/dist/src/github-app/metrics.d.ts +2 -5
  130. package/dist/src/github-app/metrics.js +2 -14
  131. package/dist/src/github-app/review-loop.d.ts +5 -5
  132. package/dist/src/github-app/review-loop.js +1 -1
  133. package/dist/src/github-app/review-node.d.ts +2 -2
  134. package/dist/src/github-app/triggers.d.ts +3 -3
  135. package/dist/src/github-names.d.ts +7 -0
  136. package/dist/src/github-names.js +7 -0
  137. package/dist/src/glob-search.d.ts +1 -0
  138. package/dist/src/glob-search.js +3 -0
  139. package/dist/src/google-provider.d.ts +5 -28
  140. package/dist/src/google-provider.js +6 -141
  141. package/dist/src/graph-editor-session.d.ts +1 -0
  142. package/dist/src/graph-editor-session.js +2 -0
  143. package/dist/src/graph-health.js +3 -1
  144. package/dist/src/graph-preview.d.ts +2 -0
  145. package/dist/src/graph-preview.js +1 -0
  146. package/dist/src/graph-runner.js +20 -14
  147. package/dist/src/graph-selection.d.ts +3 -1
  148. package/dist/src/graph-selection.js +2 -2
  149. package/dist/src/graph-server.d.ts +8 -1
  150. package/dist/src/graph-server.js +49 -12
  151. package/dist/src/graph-sync.d.ts +2 -1
  152. package/dist/src/graph-sync.js +13 -0
  153. package/dist/src/graph-ui/app.js +49 -8
  154. package/dist/src/graph-ui/index.html +1 -1
  155. package/dist/src/graphs.d.ts +23 -1
  156. package/dist/src/graphs.js +58 -7
  157. package/dist/src/grok-provider.js +17 -14
  158. package/dist/src/hardened-runtime.js +39 -25
  159. package/dist/src/jev-savings.d.ts +4 -0
  160. package/dist/src/jev-savings.js +13 -0
  161. package/dist/src/legal/client.d.ts +25 -0
  162. package/dist/src/legal/client.js +47 -0
  163. package/dist/src/legal/command.d.ts +13 -0
  164. package/dist/src/legal/command.js +98 -0
  165. package/dist/src/legal/documents.d.ts +2 -0
  166. package/dist/src/legal/documents.js +14 -0
  167. package/dist/src/legal/gate.d.ts +13 -0
  168. package/dist/src/legal/gate.js +96 -0
  169. package/dist/src/legal/manifest.d.ts +21 -0
  170. package/dist/src/legal/manifest.js +23 -0
  171. package/dist/src/legal/receipt.d.ts +13 -0
  172. package/dist/src/legal/receipt.js +137 -0
  173. package/dist/src/legal/release.d.ts +27 -0
  174. package/dist/src/legal/release.js +28 -0
  175. package/dist/src/managed-sign-in.d.ts +0 -1
  176. package/dist/src/managed-sign-in.js +0 -13
  177. package/dist/src/membership.d.ts +27 -1
  178. package/dist/src/membership.js +139 -7
  179. package/dist/src/model-health-cache.js +1 -1
  180. package/dist/src/model-metadata.js +3 -7
  181. package/dist/src/model-override.d.ts +2 -1
  182. package/dist/src/model-override.js +9 -0
  183. package/dist/src/model-pool.d.ts +99 -0
  184. package/dist/src/model-pool.js +136 -0
  185. package/dist/src/model-relay/local.js +5 -0
  186. package/dist/src/model-relay/remote.d.ts +2 -0
  187. package/dist/src/model-relay/remote.js +4 -0
  188. package/dist/src/model-tiers.d.ts +16 -1
  189. package/dist/src/model-tiers.js +31 -7
  190. package/dist/src/opencode-cli-provider.js +59 -56
  191. package/dist/src/opencode-provider.js +16 -13
  192. package/dist/src/permissions.d.ts +5 -0
  193. package/dist/src/permissions.js +7 -0
  194. package/dist/src/plan-pass.js +2 -1
  195. package/dist/src/pool-scores.d.ts +45 -0
  196. package/dist/src/pool-scores.js +40 -0
  197. package/dist/src/provider-connection.js +3 -17
  198. package/dist/src/provider-engine.d.ts +13 -1
  199. package/dist/src/provider-engine.js +116 -12
  200. package/dist/src/provider-request-error.d.ts +8 -0
  201. package/dist/src/provider-request-error.js +12 -0
  202. package/dist/src/provider-settings.d.ts +1 -1
  203. package/dist/src/provider-settings.js +36 -18
  204. package/dist/src/provider-turn-deadline.d.ts +39 -0
  205. package/dist/src/provider-turn-deadline.js +139 -0
  206. package/dist/src/providers.d.ts +8 -9
  207. package/dist/src/providers.js +211 -150
  208. package/dist/src/pull-request-merge.d.ts +1 -8
  209. package/dist/src/pull-request-merge.js +0 -4
  210. package/dist/src/pull-requests.d.ts +83 -57
  211. package/dist/src/pull-requests.js +266 -225
  212. package/dist/src/qa/runtime/ProcessManager.d.ts +5 -1
  213. package/dist/src/qa/runtime/ProcessManager.js +9 -3
  214. package/dist/src/react-runtime.js +245 -71
  215. package/dist/src/reasoning-probe-cloud.d.ts +10 -0
  216. package/dist/src/reasoning-probe-cloud.js +209 -0
  217. package/dist/src/remote/engine-pool.d.ts +3 -0
  218. package/dist/src/remote/engine-pool.js +88 -21
  219. package/dist/src/remote/recovery.d.ts +6 -0
  220. package/dist/src/remote/recovery.js +37 -0
  221. package/dist/src/run-records.d.ts +13 -3
  222. package/dist/src/run-records.js +59 -34
  223. package/dist/src/runtime.d.ts +47 -2
  224. package/dist/src/runtime.js +33 -7
  225. package/dist/src/session-summary.d.ts +8 -0
  226. package/dist/src/session-summary.js +34 -0
  227. package/dist/src/sessions.d.ts +32 -0
  228. package/dist/src/sessions.js +65 -3
  229. package/dist/src/shell.js +6 -0
  230. package/dist/src/side-panel.js +36 -2
  231. package/dist/src/sign-in-detection.d.ts +1 -1
  232. package/dist/src/sign-in-detection.js +4 -10
  233. package/dist/src/sign-in-offer.js +1 -1
  234. package/dist/src/skill-commands.js +1 -1
  235. package/dist/src/skills/bundled/bug-report/SKILL.md +51 -7
  236. package/dist/src/skills/bundled/graph-manager/SKILL.md +2 -2
  237. package/dist/src/skills/bundled/graph-manager/patterns.md +13 -19
  238. package/dist/src/skills/bundled/provenance.json +3 -3
  239. package/dist/src/subagent-run.js +50 -50
  240. package/dist/src/subscription-usage.d.ts +50 -0
  241. package/dist/src/subscription-usage.js +92 -0
  242. package/dist/src/task-checkout.d.ts +157 -0
  243. package/dist/src/task-checkout.js +628 -0
  244. package/dist/src/telemetry/access.d.ts +18 -0
  245. package/dist/src/telemetry/access.js +43 -0
  246. package/dist/src/telemetry/aggregate.d.ts +18 -2
  247. package/dist/src/telemetry/aggregate.js +22 -9
  248. package/dist/src/telemetry/capture-core.d.ts +33 -14
  249. package/dist/src/telemetry/capture-core.js +124 -25
  250. package/dist/src/telemetry/capture.d.ts +3 -2
  251. package/dist/src/telemetry/capture.js +21 -1
  252. package/dist/src/telemetry/decision-capture.js +4 -0
  253. package/dist/src/telemetry/emitter.d.ts +6 -7
  254. package/dist/src/telemetry/emitter.js +124 -29
  255. package/dist/src/telemetry/gate.d.ts +41 -2
  256. package/dist/src/telemetry/gate.js +89 -4
  257. package/dist/src/telemetry/home.d.ts +1 -0
  258. package/dist/src/telemetry/home.js +20 -0
  259. package/dist/src/telemetry/identity.d.ts +6 -3
  260. package/dist/src/telemetry/identity.js +19 -6
  261. package/dist/src/telemetry/lifecycle.d.ts +8 -0
  262. package/dist/src/telemetry/lifecycle.js +76 -0
  263. package/dist/src/telemetry/outbox.d.ts +13 -8
  264. package/dist/src/telemetry/outbox.js +68 -12
  265. package/dist/src/telemetry/permission-command.d.ts +38 -0
  266. package/dist/src/telemetry/permission-command.js +208 -0
  267. package/dist/src/telemetry/permission.d.ts +168 -0
  268. package/dist/src/telemetry/permission.js +662 -0
  269. package/dist/src/telemetry/record-installation.d.ts +1 -0
  270. package/dist/src/telemetry/record-installation.js +9 -0
  271. package/dist/src/telemetry/region-data.d.ts +12 -0
  272. package/dist/src/telemetry/region-data.js +1314 -0
  273. package/dist/src/telemetry/region.d.ts +34 -0
  274. package/dist/src/telemetry/region.js +87 -0
  275. package/dist/src/telemetry/run-privacy.d.ts +11 -0
  276. package/dist/src/telemetry/run-privacy.js +165 -0
  277. package/dist/src/telemetry/schema.d.ts +27 -6
  278. package/dist/src/telemetry/schema.js +109 -14
  279. package/dist/src/telemetry/state.d.ts +11 -7
  280. package/dist/src/telemetry/state.js +39 -6
  281. package/dist/src/telemetry/surface.d.ts +20 -3
  282. package/dist/src/telemetry/surface.js +71 -15
  283. package/dist/src/telemetry/uploader.d.ts +6 -11
  284. package/dist/src/telemetry/uploader.js +72 -46
  285. package/dist/src/telemetry/uploads.d.ts +5 -1
  286. package/dist/src/telemetry/uploads.js +25 -6
  287. package/dist/src/telemetry/version.d.ts +5 -0
  288. package/dist/src/telemetry/version.js +34 -0
  289. package/dist/src/telemetry/workspace.d.ts +4 -1
  290. package/dist/src/telemetry/workspace.js +18 -3
  291. package/dist/src/terminal-ui.d.ts +3 -0
  292. package/dist/src/terminal-ui.js +48 -6
  293. package/dist/src/test-edit-guard.d.ts +30 -0
  294. package/dist/src/test-edit-guard.js +167 -2
  295. package/dist/src/thinking-level-detect.d.ts +13 -0
  296. package/dist/src/thinking-level-detect.js +52 -0
  297. package/dist/src/thinking-levels.d.ts +30 -0
  298. package/dist/src/thinking-levels.js +131 -0
  299. package/dist/src/timers.d.ts +3 -0
  300. package/dist/src/todos.d.ts +2 -1
  301. package/dist/src/todos.js +24 -4
  302. package/dist/src/tool-argument-coercion.d.ts +7 -0
  303. package/dist/src/tool-argument-coercion.js +49 -0
  304. package/dist/src/tool-catalog.d.ts +2 -2
  305. package/dist/src/tool-catalog.js +1 -1
  306. package/dist/src/tools.js +67 -22
  307. package/dist/src/transcript.js +3 -2
  308. package/dist/src/types.d.ts +48 -1
  309. package/dist/src/update.js +4 -0
  310. package/dist/src/usage-analytics.d.ts +7 -0
  311. package/dist/src/usage-analytics.js +85 -13
  312. package/dist/telemetry-consent-v1 +1 -0
  313. package/package.json +97 -96
@@ -9,13 +9,15 @@ import { createOpenCodeCliAdapter } from './opencode-cli-provider.js';
9
9
  import { providerAuthHeaders } from './anthropic-credentials.js';
10
10
  import { ANDORRA_UNAVAILABLE_MESSAGE, andorraBaseUrl } from './andorra/endpoint.js';
11
11
  import { andorraRefusal } from './andorra/errors.js';
12
+ import { andorraRequestStarted } from './andorra/streams.js';
12
13
  import { generateEngineResponse, isEngineContextOverflow } from './provider-engine.js';
13
14
  import { estimateStreamedTokens } from './token-rate.js';
14
15
  import { textOnlyAdapter } from './image-input.js';
16
+ import { reportedModel } from './telemetry/schema.js';
15
17
  export { acceptsImages } from './image-input.js';
16
18
  export const REASONING_EFFORTS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
17
19
  /** Provider types whose requests carry a thinking-effort override. */
18
- export const REASONING_EFFORT_PROVIDER_TYPES = ['openai-compatible', 'opencode-go', 'anthropic', 'relayed'];
20
+ export const REASONING_EFFORT_PROVIDER_TYPES = ['openai-compatible', 'opencode-go', 'anthropic', 'relayed', 'codex', 'claude', 'andorra'];
19
21
  export function supportsReasoningEffort(type) {
20
22
  return REASONING_EFFORT_PROVIDER_TYPES.includes(type);
21
23
  }
@@ -32,7 +34,7 @@ export function assertRequestTimeout(provider) {
32
34
  if (value === undefined)
33
35
  return;
34
36
  if (isSignInProviderType(provider.type))
35
- throw new Error(`${SIGN_IN_PRODUCT[provider.type]} providers bound each request at ten minutes; requestTimeoutMs is not supported`);
37
+ throw new Error(`${SIGN_IN_PRODUCT[provider.type]} providers use built-in turn deadlines; requestTimeoutMs is not supported`);
36
38
  if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0 || value > MAX_REQUEST_TIMEOUT_MS) {
37
39
  throw new Error(`Provider requestTimeoutMs must be 0 (no timeout) or an integer of milliseconds up to ${MAX_REQUEST_TIMEOUT_MS}`);
38
40
  }
@@ -42,7 +44,7 @@ export function assertStreamIdleTimeout(provider) {
42
44
  if (value === undefined)
43
45
  return;
44
46
  if (isSignInProviderType(provider.type))
45
- throw new Error(`${SIGN_IN_PRODUCT[provider.type]} providers bound each request at ten minutes; streamIdleTimeoutMs is not supported`);
47
+ throw new Error(`${SIGN_IN_PRODUCT[provider.type]} providers use built-in turn deadlines; streamIdleTimeoutMs is not supported`);
46
48
  if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0 || value > MAX_REQUEST_TIMEOUT_MS) {
47
49
  throw new Error(`Provider streamIdleTimeoutMs must be 0 (no bound) or an integer of milliseconds up to ${MAX_REQUEST_TIMEOUT_MS}`);
48
50
  }
@@ -248,18 +250,9 @@ const MALFORMED_RESPONSE_RETRY_DELAYS_MS = [250, 250, 500, 1_000, 2_000];
248
250
  const MALFORMED_RESPONSE_MESSAGE = 'Provider returned a malformed response.';
249
251
  // The longest Retry-After a provider may ask for; it is not tied to the backoff above.
250
252
  const MAX_AUTOMATIC_RETRY_AFTER_MS = 120_000;
251
- export class ProviderRequestError extends Error {
252
- contextOverflow;
253
- /** The system error code behind a connection that could not be made; recorded with the failure, never part of the message. */
254
- connectionCause;
255
- /** What kind of failure this was, for telemetry (`provider_timeout`, `http_429`); never shown and never part of the message. */
256
- telemetryCode;
257
- constructor(message, contextOverflow = false) {
258
- super(message);
259
- this.contextOverflow = contextOverflow;
260
- this.name = 'Error';
261
- }
262
- }
253
+ import { ProviderRequestError } from './provider-request-error.js';
254
+ import { createProviderTurnDeadline, DEFAULT_TURN_TOTAL_MS, DEFAULT_WHOLE_RESPONSE_MS, ProviderTurnTimeoutError } from './provider-turn-deadline.js';
255
+ export { ProviderRequestError };
263
256
  function coded(error, code) { error.telemetryCode = code; return error; }
264
257
  /**
265
258
  * The telemetry error code for an error that ended a run: a provider failure's code, a record-only
@@ -477,7 +470,25 @@ function checkCalls(calls, completionAdvertised) {
477
470
  }
478
471
  return calls;
479
472
  }
480
- function wholeBodyCompletion(data, requests, completionAdvertised) {
473
+ /** The format of the `reasoning_details` entries Andorra's router writes for a model served through Anthropic's Messages API. */
474
+ const ROUTER_REASONING_FORMAT = 'anthropic-messages-v1';
475
+ function isRouterReasoningDetail(value) {
476
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
477
+ return false;
478
+ const entry = value;
479
+ return entry.type === 'reasoning.encrypted' && entry.format === ROUTER_REASONING_FORMAT && typeof entry.data === 'string'
480
+ && Number.isSafeInteger(entry.index) && entry.index >= 0;
481
+ }
482
+ /** The router's own entries from an answer's `reasoning_details`, as received; entries in any other format are left out. */
483
+ function routerReasoningDetails(value) {
484
+ return Array.isArray(value) ? value.filter(isRouterReasoningDetail).map(entry => structuredClone(entry)) : [];
485
+ }
486
+ function routerReasoningContinuation(owner, details) {
487
+ return owner && details.length
488
+ ? { providerContinuation: { api: 'openai-completions', provider: owner.provider, model: owner.model, thinking: [], reasoningDetails: details } }
489
+ : {};
490
+ }
491
+ function wholeBodyCompletion(data, requests, completionAdvertised, router) {
481
492
  if (!Array.isArray(data.choices) || data.choices.length !== 1)
482
493
  return malformed();
483
494
  const choice = record(data.choices[0]), message = record(choice.message);
@@ -492,12 +503,15 @@ function wholeBodyCompletion(data, requests, completionAdvertised) {
492
503
  const reasoningText = [message.reasoning_content, message.reasoning, message.reasoning_text]
493
504
  .find((value) => typeof value === 'string' && value.length > 0)
494
505
  ?? (typeof message.reasoning_content === 'string' ? message.reasoning_content : undefined);
495
- const reasoning = reasoningText !== undefined ? { reasoningContent: reasoningText } : {};
506
+ const continuation = routerReasoningContinuation(router, routerReasoningDetails(message.reasoning_details));
507
+ const servedModel = reportedModel(data.model);
508
+ const modelEvidence = servedModel ? { servedModel } : {};
509
+ const reasoning = { ...(reasoningText !== undefined ? { reasoningContent: reasoningText } : {}), ...continuation };
496
510
  const text = [message.content, message.refusal].filter((value) => typeof value === 'string' && value.length > 0).join('\n');
497
511
  if (message.tool_calls != null && !Array.isArray(message.tool_calls))
498
512
  return malformed();
499
513
  if (choice.finish_reason === 'length' || choice.finish_reason === 'content_filter') {
500
- return { text, toolCalls: [], usage: { ...usage(data.usage, false), requests }, stopReason: choice.finish_reason };
514
+ return { text, toolCalls: [], usage: { ...usage(data.usage, false), requests }, stopReason: choice.finish_reason, ...continuation, ...modelEvidence };
501
515
  }
502
516
  const calls = (message.tool_calls ?? []).map(raw => {
503
517
  const call = record(raw), fn = record(call.function);
@@ -511,7 +525,7 @@ function wholeBodyCompletion(data, requests, completionAdvertised) {
511
525
  });
512
526
  if ((choice.finish_reason === 'tool_calls' && !calls.length) || (message.content == null && message.refusal == null && !calls.length))
513
527
  return malformed();
514
- return { text, toolCalls: checkCalls(calls, completionAdvertised), usage: { ...usage(data.usage, false), requests }, stopReason: nonempty(choice.finish_reason), ...reasoning };
528
+ return { text, toolCalls: checkCalls(calls, completionAdvertised), usage: { ...usage(data.usage, false), requests }, stopReason: nonempty(choice.finish_reason), ...reasoning, ...modelEvidence };
515
529
  }
516
530
  const DECODE_HEAD_BURST_MS = 50;
517
531
  export function createDecodeWindow(now = Date.now) {
@@ -538,8 +552,10 @@ export function createDecodeWindow(now = Date.now) {
538
552
  },
539
553
  };
540
554
  }
541
- function createStreamAccumulator(onReasoning, now = Date.now) {
555
+ function createStreamAccumulator(onReasoning, now = Date.now, router, onProgress) {
542
556
  let content = '', refusal, reasoning = '', finishReason, chunkUsage;
557
+ // The router sends every entry in one chunk just before the finish chunk; appending also keeps a list sent in parts.
558
+ const routerDetails = [];
543
559
  let sawChoice = false, sawText = false;
544
560
  const decode = createDecodeWindow(now);
545
561
  const blankCalls = createBlankToolCallGuard();
@@ -551,7 +567,7 @@ function createStreamAccumulator(onReasoning, now = Date.now) {
551
567
  return malformed();
552
568
  return value;
553
569
  };
554
- const stampOutput = (text) => decode.stamp(text);
570
+ const stampOutput = (text) => { decode.stamp(text); onProgress?.(); };
555
571
  const decodeWindow = () => decode.measure();
556
572
  return {
557
573
  get completed() { return sawChoice && finishReason !== undefined; },
@@ -614,11 +630,14 @@ function createStreamAccumulator(onReasoning, now = Date.now) {
614
630
  if (refusalDelta)
615
631
  stampOutput(refusalDelta);
616
632
  }
633
+ if (router)
634
+ routerDetails.push(...routerReasoningDetails(delta.reasoning_details));
617
635
  if (delta.tool_calls === undefined)
618
636
  return;
619
637
  if (!Array.isArray(delta.tool_calls))
620
638
  return malformed();
621
639
  let callText = '';
640
+ let sawCallId = false;
622
641
  for (const raw of delta.tool_calls) {
623
642
  const fragment = record(raw);
624
643
  if (typeof fragment.index !== 'number' || !Number.isSafeInteger(fragment.index) || fragment.index < 0)
@@ -637,8 +656,10 @@ function createStreamAccumulator(onReasoning, now = Date.now) {
637
656
  call = { index: fragment.index, id: '', name: '', arguments: '' };
638
657
  fragments.push(call);
639
658
  }
640
- if (typeof fragment.id === 'string')
659
+ if (typeof fragment.id === 'string') {
641
660
  call.id += fragment.id;
661
+ sawCallId ||= !!fragment.id.trim();
662
+ }
642
663
  if (typeof fn.name === 'string') {
643
664
  call.name += fn.name;
644
665
  callText += fn.name;
@@ -649,8 +670,10 @@ function createStreamAccumulator(onReasoning, now = Date.now) {
649
670
  }
650
671
  }
651
672
  if (delta.tool_calls.length > 0) {
652
- stampOutput(callText);
653
673
  blankCalls.fragment(callText);
674
+ decode.stamp(callText);
675
+ if (sawCallId || callText.trim())
676
+ onProgress?.();
654
677
  }
655
678
  },
656
679
  finish(requests, completionAdvertised) {
@@ -658,8 +681,9 @@ function createStreamAccumulator(onReasoning, now = Date.now) {
658
681
  return malformed();
659
682
  const body = [content, refusal].filter((value) => typeof value === 'string' && value.length > 0).join('\n');
660
683
  const measured = decodeWindow();
684
+ const continuation = routerReasoningContinuation(router, routerDetails);
661
685
  if (finishReason === 'length' || finishReason === 'content_filter') {
662
- return { text: body, toolCalls: [], usage: { ...usage(chunkUsage, false), requests, ...(measured === undefined ? {} : { decodeMs: measured }) }, stopReason: finishReason };
686
+ return { text: body, toolCalls: [], usage: { ...usage(chunkUsage, false), requests, ...(measured === undefined ? {} : { decodeMs: measured }) }, stopReason: finishReason, ...continuation };
663
687
  }
664
688
  const calls = [...fragments].sort((a, b) => a.index - b.index).map(fragment => {
665
689
  const name = nonempty(fragment.name);
@@ -668,11 +692,11 @@ function createStreamAccumulator(onReasoning, now = Date.now) {
668
692
  });
669
693
  if ((finishReason === 'tool_calls' && !calls.length) || (!sawText && refusal === undefined && !calls.length))
670
694
  return malformed();
671
- return { text: body, toolCalls: checkCalls(calls, completionAdvertised), usage: { ...usage(chunkUsage, false), requests, ...(measured === undefined ? {} : { decodeMs: measured }) }, stopReason: nonempty(finishReason), ...(reasoning ? { reasoningContent: reasoning } : {}) };
695
+ return { text: body, toolCalls: checkCalls(calls, completionAdvertised), usage: { ...usage(chunkUsage, false), requests, ...(measured === undefined ? {} : { decodeMs: measured }) }, stopReason: nonempty(finishReason), ...(reasoning ? { reasoningContent: reasoning } : {}), ...continuation };
672
696
  },
673
697
  };
674
698
  }
675
- function createAnthropicStreamAccumulator(now = Date.now) {
699
+ function createAnthropicStreamAccumulator(now = Date.now, onProgress) {
676
700
  const blocks = new Map();
677
701
  let started = false, stopped = false, finishReason;
678
702
  const decode = createDecodeWindow(now);
@@ -720,6 +744,8 @@ function createAnthropicStreamAccumulator(now = Date.now) {
720
744
  return malformed();
721
745
  blocks.set(event.index, { type, stopped: false, text: type === 'text' ? input.text : '', fragments: '', sawInputDelta: false,
722
746
  ...(type === 'tool_use' ? { id: nonempty(input.id), name: nonempty(input.name), input: record(input.input) } : {}) });
747
+ if (type === 'tool_use' || (type === 'text' && input.text) || (type === 'thinking' && typeof input.thinking === 'string' && input.thinking))
748
+ onProgress?.();
723
749
  return;
724
750
  }
725
751
  if (event.type === 'content_block_delta') {
@@ -729,29 +755,39 @@ function createAnthropicStreamAccumulator(now = Date.now) {
729
755
  return malformed();
730
756
  block.fragments += delta.partial_json;
731
757
  block.sawInputDelta = true;
732
- if (delta.partial_json)
758
+ if (delta.partial_json) {
733
759
  stampOutput(delta.partial_json);
760
+ if (delta.partial_json.trim())
761
+ onProgress?.();
762
+ }
734
763
  }
735
764
  else if (block.type === 'text' && delta.type === 'text_delta') {
736
765
  if (typeof delta.text !== 'string')
737
766
  return malformed();
738
767
  block.text += delta.text;
739
- if (delta.text)
768
+ if (delta.text) {
740
769
  stampOutput(delta.text);
770
+ onProgress?.();
771
+ }
741
772
  }
742
773
  else if (block.type === 'thinking' && ['thinking_delta', 'signature_delta'].includes(String(delta.type))) {
743
774
  const piece = delta[delta.type === 'thinking_delta' ? 'thinking' : 'signature'];
744
775
  if (typeof piece !== 'string')
745
776
  return malformed();
746
- if (piece && delta.type === 'thinking_delta')
777
+ if (piece && delta.type === 'thinking_delta') {
747
778
  stampOutput(piece);
779
+ onProgress?.();
780
+ }
748
781
  }
749
782
  else
750
783
  return malformed();
751
784
  return;
752
785
  }
753
786
  if (event.type === 'content_block_stop') {
754
- blockAt(event.index).stopped = true;
787
+ const block = blockAt(event.index);
788
+ block.stopped = true;
789
+ if (block.type === 'tool_use')
790
+ onProgress?.();
755
791
  return;
756
792
  }
757
793
  if (event.type === 'message_delta') {
@@ -795,8 +831,8 @@ function createProviderAdapter(config, options = {}) {
795
831
  // A relayed provider's model is on the desktop: only the run's model relay can reach it.
796
832
  if (config.type === 'relayed')
797
833
  throw new Error('A relayed provider needs a run.');
798
- if (config.reasoningEffort !== undefined && (!['openai-compatible', 'opencode-go', 'anthropic'].includes(config.type) || !REASONING_EFFORTS.includes(config.reasoningEffort)))
799
- throw new Error('Reasoning effort overrides require an OpenAI-compatible, OpenCode Go or Anthropic provider and a supported effort value.');
834
+ if (config.reasoningEffort !== undefined && (!supportsReasoningEffort(config.type) || !REASONING_EFFORTS.includes(config.reasoningEffort)))
835
+ throw new Error('Reasoning effort overrides require a provider that supports them and a supported effort value.');
800
836
  assertRequestTimeout(config);
801
837
  assertStreamIdleTimeout(config);
802
838
  assertProviderCredentials(config);
@@ -807,7 +843,7 @@ function createProviderAdapter(config, options = {}) {
807
843
  if (config.type === 'grok')
808
844
  return createGrokAdapter(config);
809
845
  if (config.type === 'google')
810
- return createGoogleAdapter(config);
846
+ return createGoogleAdapter();
811
847
  if (config.type === 'opencode')
812
848
  return createOpenCodeCliAdapter(config);
813
849
  if (config.type === 'opencode-go')
@@ -832,10 +868,11 @@ function createProviderAdapter(config, options = {}) {
832
868
  const requestTimeoutMs = config.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
833
869
  const listingTimeoutMs = requestTimeoutMs > 0 ? Math.min(requestTimeoutMs, MODEL_LISTING_TIMEOUT_MS) : MODEL_LISTING_TIMEOUT_MS;
834
870
  const inferenceTimeoutMs = config.streamIdleTimeoutMs ?? requestTimeoutMs;
835
- async function send(path, signal, body, timeoutMs, inference = false, forceRefresh = false) {
871
+ const wholeResponseMs = config.streamIdleTimeoutMs ?? config.requestTimeoutMs ?? DEFAULT_WHOLE_RESPONSE_MS;
872
+ async function send(path, signal, body, timeoutMs, turn, forceRefresh = false, extraHeaders = {}) {
836
873
  if (signal.aborted)
837
874
  cancelled();
838
- const authDeadline = timeoutMs > 0 ? AbortSignal.timeout(timeoutMs) : undefined;
875
+ const authDeadline = !turn && timeoutMs > 0 ? AbortSignal.timeout(timeoutMs) : undefined;
839
876
  let credential;
840
877
  try {
841
878
  credential = await providerAuthHeaders(config, { forceRefresh, signal: authDeadline ? AbortSignal.any([signal, authDeadline]) : signal });
@@ -847,22 +884,21 @@ function createProviderAdapter(config, options = {}) {
847
884
  throw coded(new RetryableProviderError('Provider request timed out.'), 'provider_timeout');
848
885
  throw error;
849
886
  }
850
- const headers = { 'content-type': 'application/json', ...sessionHeader, ...credential };
887
+ if (signal.aborted)
888
+ cancelled();
889
+ if (authDeadline?.aborted)
890
+ throw coded(new RetryableProviderError('Provider request timed out.'), 'provider_timeout');
891
+ const headers = { 'content-type': 'application/json', ...sessionHeader, ...extraHeaders, ...credential };
851
892
  const key = headers['x-api-key'] ?? headers.authorization?.replace(/^Bearer /, '');
852
- const idle = inference && timeoutMs > 0 ? new AbortController() : undefined;
853
- let timer;
854
- const refresh = () => {
855
- if (!idle || idle.signal.aborted)
856
- return;
857
- clearTimeout(timer);
858
- timer = setTimeout(() => idle.abort(new DOMException('Provider request timed out.', 'TimeoutError')), timeoutMs);
859
- };
860
- let dispose = () => { clearTimeout(timer); };
861
- const deadline = idle?.signal ?? (timeoutMs > 0 ? AbortSignal.timeout(timeoutMs) : undefined);
893
+ const deadline = !turn && timeoutMs > 0 ? AbortSignal.timeout(timeoutMs) : undefined;
862
894
  const combined = deadline ? AbortSignal.any([signal, deadline]) : signal;
863
895
  const serializedBody = body === undefined ? undefined : JSON.stringify(body);
864
- refresh();
896
+ const requestedWhole = body?.stream === false;
897
+ turn?.waitForResponse(requestedWhole ? wholeResponseMs : inferenceTimeoutMs);
865
898
  let response;
899
+ // Counted from here to the end of the answer, which is as long as the router holds the account's place for it.
900
+ const requestDone = andorra && turn ? andorraRequestStarted() : () => { };
901
+ let dispose = requestDone;
866
902
  try {
867
903
  response = await fetch(`${base.href.replace(/\/$/, '')}/${path}`, {
868
904
  method: body === undefined ? 'GET' : 'POST', headers, redirect: 'error', signal: combined,
@@ -890,7 +926,7 @@ function createProviderAdapter(config, options = {}) {
890
926
  if (response.status === 401 && config.anthropicAuth === 'console' && !forceRefresh) {
891
927
  dispose();
892
928
  await response.body?.cancel().catch(() => { });
893
- return send(path, signal, body, timeoutMs, inference, true);
929
+ return send(path, signal, body, timeoutMs, turn, true, extraHeaders);
894
930
  }
895
931
  if (!response.ok) {
896
932
  try {
@@ -919,13 +955,15 @@ function createProviderAdapter(config, options = {}) {
919
955
  dispose();
920
956
  }
921
957
  }
922
- if (inference && response.body) {
923
- refresh();
958
+ if (turn && response.body) {
959
+ if (!requestedWhole && wholeResponseMs !== inferenceTimeoutMs && !response.headers.get('content-type')?.toLowerCase().includes('text/event-stream')) {
960
+ turn.waitForResponse(wholeResponseMs, true);
961
+ }
924
962
  const reader = response.body.getReader();
925
963
  let ended = false;
926
964
  const cleanup = () => {
927
- clearTimeout(timer);
928
965
  combined.removeEventListener('abort', abort);
966
+ requestDone();
929
967
  };
930
968
  const cancelReader = () => { void reader.cancel().catch(() => { }).finally(() => reader.releaseLock()); };
931
969
  let streamController;
@@ -956,8 +994,6 @@ function createProviderAdapter(config, options = {}) {
956
994
  controller.close();
957
995
  }
958
996
  else {
959
- if (chunk.value.byteLength)
960
- refresh();
961
997
  controller.enqueue(chunk.value);
962
998
  }
963
999
  }
@@ -987,7 +1023,9 @@ function createProviderAdapter(config, options = {}) {
987
1023
  };
988
1024
  response = new Response(stream, { status: response.status, statusText: response.statusText, headers: response.headers });
989
1025
  }
990
- return { response, deadline, dispose };
1026
+ const authMode = credential['x-api-key'] ? 'api-key'
1027
+ : credential.authorization ? (andorra || config.anthropicAuth === 'console' ? 'linked-account' : 'api-key') : undefined;
1028
+ return { response, deadline, dispose, authMode };
991
1029
  }
992
1030
  async function request(path, signal, body, timeoutMs = requestTimeoutMs, onRequest) {
993
1031
  onRequest?.();
@@ -1005,7 +1043,7 @@ function createProviderAdapter(config, options = {}) {
1005
1043
  return malformed();
1006
1044
  }
1007
1045
  }
1008
- async function withRetries(attempt, signal, onRetry, prepareRetry) {
1046
+ async function withRetries(attempt, signal, onRetry, prepareRetry, canRetry) {
1009
1047
  for (let retry = 0;; retry++) {
1010
1048
  if (signal.aborted)
1011
1049
  cancelled();
@@ -1015,7 +1053,7 @@ function createProviderAdapter(config, options = {}) {
1015
1053
  catch (error) {
1016
1054
  if (signal.aborted)
1017
1055
  cancelled();
1018
- if (!(error instanceof RetryableProviderError))
1056
+ if (!(error instanceof RetryableProviderError) || canRetry?.() === false)
1019
1057
  throw error;
1020
1058
  prepareRetry?.(error);
1021
1059
  if (retry >= error.maxRetries)
@@ -1042,120 +1080,143 @@ function createProviderAdapter(config, options = {}) {
1042
1080
  async generate(input) {
1043
1081
  const { model, tools, signal, onRetry, onRequest } = input;
1044
1082
  let requests = 0;
1045
- let deadline;
1083
+ let madeProgress = false;
1084
+ const turn = createProviderTurnDeadline(signal, { startupMs: inferenceTimeoutMs, idleMs: inferenceTimeoutMs,
1085
+ totalMs: inferenceTimeoutMs === 0 ? 0 : Math.max(DEFAULT_TURN_TOTAL_MS, inferenceTimeoutMs, wholeResponseMs) });
1086
+ // Record validated events before buffering can hide output behind a later stream error.
1087
+ const onProgress = () => { madeProgress = true; turn.progress(); };
1046
1088
  let dispose;
1089
+ let authMode;
1047
1090
  let forceNonStreaming = preferNonStreaming;
1048
1091
  let currentRequestNonStreaming = false;
1049
1092
  const advertised = tools.some(tool => tool.name === COMPLETION_TOOL);
1093
+ // Only Andorra's router writes `reasoning_details` this client sends back; another provider's are not kept.
1094
+ const router = andorra ? { provider: config.id, model } : undefined;
1095
+ // The router places Claude's moving cache breakpoint itself; told how many trailing messages this client rewrites
1096
+ // every request, it keeps the breakpoint before them so the next request reads it.
1097
+ const tailHeader = andorra && Number.isSafeInteger(input.mutableTail) && input.mutableTail > 0
1098
+ ? { 'x-andorra-mutable-tail': String(input.mutableTail) } : {};
1050
1099
  try {
1051
- const result = await withRetries(() => generateEngineResponse(input, {
1052
- providerId: config.id, baseUrl: base.href.replace(/\/$/, ''), anthropic,
1053
- contextWindow: model === config.model ? config.contextWindow ?? 128_000 : 128_000,
1054
- reasoningEffort: model === config.model ? config.reasoningEffort : undefined,
1055
- // DeepSeek takes an empty string. Andorra's router rejects an empty one like an absent one (HTTP 400,
1056
- // "Missing required parameter: 'messages[n].reasoning_content'") and takes a single space.
1057
- ...(andorra ? { missingReasoning: ' ' } : base.origin === 'https://api.deepseek.com' ? { missingReasoning: '' } : {}),
1058
- async send(body) {
1059
- deadline = undefined;
1060
- dispose?.();
1061
- dispose = undefined;
1062
- requests++;
1063
- onRequest?.();
1064
- currentRequestNonStreaming = forceNonStreaming || preferNonStreaming;
1065
- const requestBody = currentRequestNonStreaming
1066
- ? (() => { const plain = { ...body }; delete plain.stream_options; plain.stream = false; return plain; })()
1067
- : body;
1068
- const sent = await send(anthropic ? 'messages' : 'chat/completions', signal, requestBody, inferenceTimeoutMs, true);
1069
- deadline = sent.deadline;
1070
- dispose = sent.dispose;
1071
- return sent.response;
1072
- },
1073
- async parseWhole(response) {
1074
- let data;
1075
- try {
1076
- data = record(await boundedJson(response));
1077
- }
1078
- catch (error) {
1079
- if (signal.aborted)
1080
- cancelled();
1081
- if (deadline?.aborted)
1082
- throw coded(new RetryableProviderError('Provider request timed out.'), 'provider_timeout');
1083
- if (error instanceof ResponseTooLargeError || error instanceof RetryableProviderError)
1084
- throw error;
1085
- return malformed();
1086
- }
1087
- if (!anthropic)
1088
- return wholeBodyCompletion(data, requests, advertised);
1089
- if (!Array.isArray(data.content) || !data.content.length)
1090
- return malformed();
1091
- const text = [], calls = [];
1092
- const thinking = [];
1093
- for (const raw of data.content) {
1094
- const block = record(raw);
1095
- if (block.type === 'text') {
1096
- if (typeof block.text !== 'string')
1097
- return malformed();
1098
- text.push(block.text);
1099
- }
1100
- else if (block.type === 'tool_use') {
1101
- calls.push({ id: nonempty(block.id), name: nonempty(block.name), arguments: JSON.stringify(record(block.input)) });
1100
+ const attempt = () => {
1101
+ turn.startup();
1102
+ return generateEngineResponse({ ...input, signal: turn.signal }, {
1103
+ providerId: config.id, baseUrl: base.href.replace(/\/$/, ''), anthropic,
1104
+ contextWindow: model === config.model ? config.contextWindow ?? 128_000 : 128_000,
1105
+ reasoningEffort: model === config.model ? config.reasoningEffort : undefined,
1106
+ // DeepSeek takes an empty string. Andorra's router rejects an empty one like an absent one (HTTP 400,
1107
+ // "Missing required parameter: 'messages[n].reasoning_content'") and takes a single space.
1108
+ ...(andorra ? { missingReasoning: ' ' } : base.origin === 'https://api.deepseek.com' ? { missingReasoning: '' } : {}),
1109
+ async send(body) {
1110
+ dispose?.();
1111
+ dispose = undefined;
1112
+ requests++;
1113
+ onRequest?.();
1114
+ currentRequestNonStreaming = forceNonStreaming || preferNonStreaming;
1115
+ const requestBody = currentRequestNonStreaming
1116
+ ? (() => { const plain = { ...body }; delete plain.stream_options; plain.stream = false; return plain; })()
1117
+ : body;
1118
+ const sent = await send(anthropic ? 'messages' : 'chat/completions', turn.signal, requestBody, inferenceTimeoutMs, turn, false, tailHeader);
1119
+ dispose = sent.dispose;
1120
+ authMode = sent.authMode;
1121
+ return sent.response;
1122
+ },
1123
+ async parseWhole(response) {
1124
+ let data;
1125
+ try {
1126
+ data = record(await boundedJson(response));
1102
1127
  }
1103
- else if (block.type === 'thinking') {
1104
- if (typeof block.thinking !== 'string' || typeof block.signature !== 'string')
1105
- return malformed();
1106
- thinking.push({ type: 'thinking', thinking: block.thinking, thinkingSignature: block.signature });
1128
+ catch (error) {
1129
+ if (signal.aborted)
1130
+ cancelled();
1131
+ turn.signal.throwIfAborted();
1132
+ if (error instanceof ResponseTooLargeError || error instanceof RetryableProviderError)
1133
+ throw error;
1134
+ return malformed();
1107
1135
  }
1108
- else if (block.type === 'redacted_thinking') {
1109
- if (typeof block.data !== 'string')
1136
+ if (!anthropic)
1137
+ return wholeBodyCompletion(data, requests, advertised, router);
1138
+ if (!Array.isArray(data.content) || !data.content.length)
1139
+ return malformed();
1140
+ const text = [], calls = [];
1141
+ const thinking = [];
1142
+ for (const raw of data.content) {
1143
+ const block = record(raw);
1144
+ if (block.type === 'text') {
1145
+ if (typeof block.text !== 'string')
1146
+ return malformed();
1147
+ text.push(block.text);
1148
+ }
1149
+ else if (block.type === 'tool_use') {
1150
+ calls.push({ id: nonempty(block.id), name: nonempty(block.name), arguments: JSON.stringify(record(block.input)) });
1151
+ }
1152
+ else if (block.type === 'thinking') {
1153
+ if (typeof block.thinking !== 'string' || typeof block.signature !== 'string')
1154
+ return malformed();
1155
+ thinking.push({ type: 'thinking', thinking: block.thinking, thinkingSignature: block.signature });
1156
+ }
1157
+ else if (block.type === 'redacted_thinking') {
1158
+ if (typeof block.data !== 'string')
1159
+ return malformed();
1160
+ thinking.push({ type: 'thinking', thinking: '[Reasoning redacted]', thinkingSignature: block.data, redacted: true });
1161
+ }
1162
+ else
1110
1163
  return malformed();
1111
- thinking.push({ type: 'thinking', thinking: '[Reasoning redacted]', thinkingSignature: block.data, redacted: true });
1112
1164
  }
1113
- else
1165
+ const stopReason = nonempty(data.stop_reason);
1166
+ if (stopReason === 'tool_use' && !calls.length)
1114
1167
  return malformed();
1115
- }
1116
- const stopReason = nonempty(data.stop_reason);
1117
- if (stopReason === 'tool_use' && !calls.length)
1118
- return malformed();
1119
- return { text: text.join('\n'), toolCalls: stopReason === 'max_tokens' ? [] : checkCalls(calls, advertised),
1120
- usage: { ...usage(data.usage, true), requests }, stopReason: stopReason === 'max_tokens' ? 'length' : stopReason,
1121
- ...(thinking.length ? { providerContinuation: { api: 'anthropic-messages', provider: config.id, model, thinking } } : {}) };
1122
- },
1123
- checkCalls: calls => checkCalls(calls, advertised),
1124
- streamReadError: () => coded(new RetryableProviderError('Provider connection failed while reading its response.'), 'stream_interrupted'),
1125
- streamMalformedError: () => new MalformedStreamProviderError(),
1126
- streamingDisabled: () => currentRequestNonStreaming,
1127
- ...(anthropic ? { streamValidator() {
1128
- const validator = createAnthropicStreamAccumulator();
1129
- return { event: validator.event, finish: () => validator.finish(requests, advertised) };
1130
- } } : { streamValidator() {
1131
- const validator = createStreamAccumulator(() => { });
1132
- return { event: validator.event, finish() {
1133
- if (!validator.completed)
1134
- throw coded(new RetryableProviderError('Provider closed the stream before the response completed.'), 'stream_interrupted');
1135
- return validator.finish(requests, advertised);
1136
- } };
1137
- } }),
1138
- }).catch(error => {
1139
- if (signal.aborted)
1140
- cancelled();
1141
- if (deadline?.aborted)
1142
- throw coded(new RetryableProviderError('Provider request timed out.'), 'provider_timeout');
1143
- if (error instanceof Error && !(error instanceof RetryableProviderError) && error.message === MALFORMED_RESPONSE_MESSAGE)
1144
- throw new MalformedResponseProviderError();
1145
- throw error;
1146
- }).finally(() => { dispose?.(); dispose = undefined; }), signal, onRetry, error => {
1168
+ const servedModel = reportedModel(data.model);
1169
+ return { text: text.join('\n'), toolCalls: stopReason === 'max_tokens' ? [] : checkCalls(calls, advertised),
1170
+ usage: { ...usage(data.usage, true), requests }, stopReason: stopReason === 'max_tokens' ? 'length' : stopReason,
1171
+ ...(servedModel ? { servedModel } : {}),
1172
+ ...(thinking.length ? { providerContinuation: { api: 'anthropic-messages', provider: config.id, model, thinking } } : {}) };
1173
+ },
1174
+ checkCalls: calls => checkCalls(calls, advertised),
1175
+ streamReadError: () => coded(new RetryableProviderError('Provider connection failed while reading its response.'), 'stream_interrupted'),
1176
+ streamMalformedError: () => new MalformedStreamProviderError(),
1177
+ streamingDisabled: () => currentRequestNonStreaming,
1178
+ ...(anthropic ? { streamValidator() {
1179
+ const validator = createAnthropicStreamAccumulator(Date.now, onProgress);
1180
+ return { event: validator.event, finish: () => validator.finish(requests, advertised) };
1181
+ } } : { streamValidator() {
1182
+ const validator = createStreamAccumulator(() => { }, Date.now, router, onProgress);
1183
+ return { event: validator.event, finish() {
1184
+ if (!validator.completed)
1185
+ throw coded(new RetryableProviderError('Provider closed the stream before the response completed.'), 'stream_interrupted');
1186
+ return validator.finish(requests, advertised);
1187
+ } };
1188
+ } }),
1189
+ }).catch(error => {
1190
+ if (signal.aborted)
1191
+ cancelled();
1192
+ turn.signal.throwIfAborted();
1193
+ if (error instanceof Error && !(error instanceof RetryableProviderError) && error.message === MALFORMED_RESPONSE_MESSAGE)
1194
+ throw new MalformedResponseProviderError();
1195
+ throw error;
1196
+ }).finally(() => { dispose?.(); dispose = undefined; });
1197
+ };
1198
+ const result = await withRetries(attempt, turn.signal, onRetry, error => {
1199
+ turn.pause();
1147
1200
  if (error instanceof MalformedStreamProviderError) {
1148
1201
  forceNonStreaming = true;
1149
1202
  preferNonStreaming = true;
1150
1203
  }
1151
- });
1152
- return { ...result, usage: { ...result.usage, requests } };
1204
+ }, () => !madeProgress);
1205
+ turn.signal.throwIfAborted();
1206
+ return { ...result, usage: { ...result.usage, requests }, ...(authMode ? { authMode } : {}) };
1153
1207
  }
1154
1208
  catch (error) {
1209
+ if (!signal.aborted && turn.signal.reason instanceof ProviderTurnTimeoutError)
1210
+ throw turn.signal.reason;
1211
+ if (signal.aborted)
1212
+ cancelled();
1155
1213
  if (error instanceof ProviderRequestError)
1156
1214
  throw error;
1157
1215
  throw new ProviderRequestError(error instanceof Error ? error.message : 'Provider request failed.');
1158
1216
  }
1217
+ finally {
1218
+ turn.dispose();
1219
+ }
1159
1220
  },
1160
1221
  async listModels(signal) {
1161
1222
  const ids = [];