@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
@@ -0,0 +1,99 @@
1
+ import type { DecisionBatch } from './decision/types.js';
2
+ import { type AdaptiveRoutingConfig, type EfficiencyReason, type PoolClass, type PoolEntry } from './efficiency.js';
3
+ /**
4
+ * Pool routing: the second adaptive-routing strategy (`strategy: 'pool'`).
5
+ *
6
+ * The configuration lists pairs (provider, model, thinking level), each with a quality score and an optional cost the
7
+ * user supplies. A task is given a class, the class sets the score a pair must reach, and among the pairs that reach
8
+ * it the router picks the lowest effective cost: the pair's cost divided by its subscription's standing, so a unit
9
+ * spent on a subscription behind its pace counts for more and one on a subscription with allowance to spare for less.
10
+ * Subscription usage never lowers the score a task must reach: it only changes which pair serves it. Nothing here
11
+ * reads a file or the network; usage readings are passed in, and a provider with no reading is never held back.
12
+ */
13
+ /** One usage window of a subscription, as its provider reports it. */
14
+ export interface QuotaWindow {
15
+ /** Share of the window's allowance already used, 0 to 100. */
16
+ usedPercent: number;
17
+ /** When the window resets, in milliseconds since the epoch. */
18
+ resetsAt?: number;
19
+ /** The whole length of the window in seconds, from the provider; never guessed from a label. */
20
+ windowSeconds?: number;
21
+ }
22
+ /** Usage windows by provider id. A provider with no entry has no known limit. */
23
+ export type QuotaReadings = Readonly<Record<string, readonly QuotaWindow[] | undefined>>;
24
+ export interface PoolTarget {
25
+ provider: string;
26
+ model: string;
27
+ effort?: PoolEntry['effort'];
28
+ }
29
+ export interface PoolDecisionInput {
30
+ task: string;
31
+ routing: AdaptiveRoutingConfig & {
32
+ enabled: boolean;
33
+ maxEscalations: number;
34
+ };
35
+ baseline: {
36
+ provider: string;
37
+ model: string;
38
+ effort?: string;
39
+ };
40
+ node: {
41
+ provider?: string;
42
+ model?: string;
43
+ };
44
+ modelPinned?: boolean;
45
+ hints?: DecisionBatch;
46
+ configured: {
47
+ id: string;
48
+ model?: string;
49
+ models?: readonly string[];
50
+ }[];
51
+ quota?: QuotaReadings;
52
+ /** With `candidates: all`: the thinking levels a provider's model takes. Without it every scored level is a pair. */
53
+ levels?: (provider: string, model: string) => readonly string[] | undefined;
54
+ /** Milliseconds since the epoch; defaults to the current time. */
55
+ now?: number;
56
+ /** A class named by the caller (a parent agent naming one for its subagent) instead of classifying the task. */
57
+ declaredClass?: PoolClass;
58
+ previous?: {
59
+ poolClass: PoolClass;
60
+ reason?: string;
61
+ escalations: number;
62
+ };
63
+ }
64
+ export interface PoolDecision {
65
+ poolClass?: PoolClass;
66
+ target?: PoolTarget;
67
+ /** The target differs from the pair the node would have run. */
68
+ applied: boolean;
69
+ reason: EfficiencyReason;
70
+ evidence: 'policy' | 'pinned' | 'hint' | 'lexical' | 'declared' | 'escalation' | 'none';
71
+ /** Pairs that reach the class score, and how many of those the usage reserve held back. */
72
+ candidates: number;
73
+ blocked: number;
74
+ /** The chosen pair's subscription standing, when its usage was known. */
75
+ standing?: number;
76
+ /** With `candidates: all`: the configured models left out because they have no score yet. */
77
+ unscored?: number;
78
+ }
79
+ export declare const DEFAULT_POOL_RESERVE_PERCENT = 5;
80
+ export declare const DEFAULT_POOL_NEAR_TIE_PERCENT = 10;
81
+ export declare function isPoolClass(value: unknown): value is PoolClass;
82
+ export declare function poolClassScore(routing: Pick<AdaptiveRoutingConfig, 'classScores'>, poolClass: PoolClass): number;
83
+ /**
84
+ * Where a subscription stands: `blocked` when any live window has no more than the reserve left, and `standing` as
85
+ * the share of allowance left divided by the share of the window left (1 is on pace, above 1 is ahead). The pace
86
+ * comes from windows of a day or longer whose length and reset time are both known; the tightest one counts.
87
+ */
88
+ export declare function quotaStanding(windows: readonly QuotaWindow[] | undefined, now: number, reservePercent: number): {
89
+ blocked: boolean;
90
+ standing?: number;
91
+ };
92
+ /** The class of a task from the evidence at hand, or undefined when nothing is decisive. */
93
+ export declare function classifyPoolClass(task: string, hints: DecisionBatch | undefined): {
94
+ poolClass: PoolClass;
95
+ evidence: 'hint' | 'lexical';
96
+ reason: EfficiencyReason;
97
+ } | undefined;
98
+ /** Decide the pair for one attempt. A target is named only when a configured pair reaches the class score. */
99
+ export declare function decidePoolModel(input: PoolDecisionInput): PoolDecision;
@@ -0,0 +1,136 @@
1
+ import { DecisionPolicy } from './decision/DecisionPolicy.js';
2
+ import { DEFAULT_POOL_CLASS_SCORES, POOL_CLASSES, poolEntries } from './efficiency.js';
3
+ import { MECHANICAL_MAX_CHARS, MECHANICAL_WORDS, RISK_WORDS } from './model-tiers.js';
4
+ export const DEFAULT_POOL_RESERVE_PERCENT = 5;
5
+ export const DEFAULT_POOL_NEAR_TIE_PERCENT = 10;
6
+ /** A window shorter than this (a session window) can hold a pair back when nearly empty but does not set the pace. */
7
+ const SHORT_WINDOW_SECONDS = 86_400;
8
+ /** The lowest standing a cost is divided by: a subscription far behind its pace makes a pair at most ten times dearer. */
9
+ const MIN_STANDING = 0.1;
10
+ const MAX_STANDING = 10;
11
+ const ESCALATION_REASONS = new Set(['repeatedToolFailure', 'maxIterations', 'maxCompletionRepairs', 'Prepared-step metadata allowance exhausted']);
12
+ export function isPoolClass(value) {
13
+ return typeof value === 'string' && POOL_CLASSES.includes(value);
14
+ }
15
+ export function poolClassScore(routing, poolClass) {
16
+ return routing.classScores?.[poolClass] ?? DEFAULT_POOL_CLASS_SCORES[poolClass];
17
+ }
18
+ function nextPoolClass(poolClass) {
19
+ const index = POOL_CLASSES.indexOf(poolClass);
20
+ return index >= 0 && index < POOL_CLASSES.length - 1 ? POOL_CLASSES[index + 1] : undefined;
21
+ }
22
+ /**
23
+ * Where a subscription stands: `blocked` when any live window has no more than the reserve left, and `standing` as
24
+ * the share of allowance left divided by the share of the window left (1 is on pace, above 1 is ahead). The pace
25
+ * comes from windows of a day or longer whose length and reset time are both known; the tightest one counts.
26
+ */
27
+ export function quotaStanding(windows, now, reservePercent) {
28
+ let blocked = false;
29
+ let standing;
30
+ for (const window of windows ?? []) {
31
+ if (!Number.isFinite(window.usedPercent))
32
+ continue;
33
+ // A window whose reset time has passed describes an allowance that no longer exists.
34
+ if (window.resetsAt !== undefined && window.resetsAt <= now)
35
+ continue;
36
+ const remaining = Math.min(100, Math.max(0, 100 - window.usedPercent));
37
+ if (remaining <= reservePercent)
38
+ blocked = true;
39
+ if (window.resetsAt === undefined || window.windowSeconds === undefined || window.windowSeconds < SHORT_WINDOW_SECONDS)
40
+ continue;
41
+ const timeLeft = Math.min(1, Math.max(0.01, (window.resetsAt - now) / (window.windowSeconds * 1000)));
42
+ const pace = Math.min(MAX_STANDING, remaining / 100 / timeLeft);
43
+ standing = standing === undefined ? pace : Math.min(standing, pace);
44
+ }
45
+ return { blocked, ...(standing === undefined ? {} : { standing }) };
46
+ }
47
+ /** The class of a task from the evidence at hand, or undefined when nothing is decisive. */
48
+ export function classifyPoolClass(task, hints) {
49
+ const risk = hints !== undefined && (DecisionPolicy.boolean(hints, 'security_sensitive') === true || DecisionPolicy.boolean(hints, 'architecture_affecting') === true);
50
+ const complexity = hints ? DecisionPolicy.score(hints, 'task_complexity') : undefined;
51
+ if (risk)
52
+ return { poolClass: 'deep', evidence: 'hint', reason: 'risk' };
53
+ if (RISK_WORDS.test(task))
54
+ return { poolClass: 'deep', evidence: 'lexical', reason: 'risk' };
55
+ if (complexity !== undefined && complexity >= 0.8)
56
+ return { poolClass: 'deep', evidence: 'hint', reason: 'deep' };
57
+ const short = task.length <= MECHANICAL_MAX_CHARS;
58
+ if (short && MECHANICAL_WORDS.test(task) && (complexity === undefined || complexity <= 0.4))
59
+ return { poolClass: 'routine', evidence: 'lexical', reason: 'routine' };
60
+ if (complexity !== undefined && complexity <= 0.25 && short)
61
+ return { poolClass: 'quick', evidence: 'hint', reason: 'quick' };
62
+ if (complexity !== undefined)
63
+ return { poolClass: 'standard', evidence: 'hint', reason: 'standard' };
64
+ return undefined;
65
+ }
66
+ function configuredTarget(entry, configured) {
67
+ const provider = configured.find(item => item.id === entry.provider);
68
+ if (!provider)
69
+ return undefined;
70
+ const model = entry.model ?? provider.model;
71
+ if (!model)
72
+ return undefined;
73
+ if (entry.model !== undefined && provider.models?.length && !provider.models.includes(entry.model) && provider.model !== entry.model)
74
+ return undefined;
75
+ return { provider: provider.id, model, ...(entry.effort === undefined ? {} : { effort: entry.effort }) };
76
+ }
77
+ /** Decide the pair for one attempt. A target is named only when a configured pair reaches the class score. */
78
+ export function decidePoolModel(input) {
79
+ const kept = { applied: false, reason: 'baseline', evidence: 'none', candidates: 0, blocked: 0 };
80
+ const routing = input.routing;
81
+ if (!routing.enabled || routing.strategy !== 'pool')
82
+ return { ...kept, reason: 'unconfigured', evidence: 'policy' };
83
+ const { entries, unscored } = poolEntries(routing, input.configured, input.levels);
84
+ const counted = unscored > 0 ? { unscored } : {};
85
+ if (!entries.length)
86
+ return { ...kept, ...counted, reason: 'unconfigured', evidence: 'policy' };
87
+ if (input.node.provider !== undefined || input.node.model !== undefined || input.modelPinned)
88
+ return { ...kept, reason: 'pinned', evidence: 'pinned' };
89
+ let poolClass;
90
+ let reason;
91
+ let evidence;
92
+ if (input.previous) {
93
+ const { poolClass: ran, reason: why, escalations } = input.previous;
94
+ const failed = why !== undefined && ESCALATION_REASONS.has(why);
95
+ const higher = failed && escalations < routing.maxEscalations ? nextPoolClass(ran) : undefined;
96
+ poolClass = higher ?? ran;
97
+ reason = higher ? 'escalated' : failed ? 'escalation_limit' : 'baseline';
98
+ evidence = 'escalation';
99
+ }
100
+ else if (input.declaredClass) {
101
+ poolClass = input.declaredClass;
102
+ reason = input.declaredClass;
103
+ evidence = 'declared';
104
+ }
105
+ else {
106
+ const classified = classifyPoolClass(input.task, input.hints);
107
+ if (!classified)
108
+ return { ...kept, reason: 'low_confidence' };
109
+ ({ poolClass, reason, evidence } = classified);
110
+ }
111
+ const needed = poolClassScore(routing, poolClass);
112
+ const sufficient = entries.flatMap(entry => {
113
+ const target = entry.quality >= needed ? configuredTarget(entry, input.configured) : undefined;
114
+ return target ? [{ entry, target }] : [];
115
+ });
116
+ if (!sufficient.length)
117
+ return { ...kept, ...counted, poolClass, reason: 'no_candidate', evidence };
118
+ const now = input.now ?? Date.now();
119
+ const reserve = routing.quota?.reservePercent ?? DEFAULT_POOL_RESERVE_PERCENT;
120
+ const open = sufficient.map(item => ({ ...item, ...quotaStanding(input.quota?.[item.target.provider], now, reserve) })).filter(item => !item.blocked);
121
+ const blocked = sufficient.length - open.length;
122
+ if (!open.length)
123
+ return { ...kept, ...counted, poolClass, reason: 'quota_reserve', evidence, candidates: sufficient.length, blocked };
124
+ // A pair's cost stands for the allowance one task uses on its subscription, and the standing says what that
125
+ // allowance is worth now: the cost is divided by it. Unknown usage is on pace (1), neither preferred nor avoided.
126
+ // With no cost given, a higher score is taken to cost more, so the lowest sufficient pair wins.
127
+ const cost = (item) => (item.entry.cost ?? item.entry.quality) / Math.max(MIN_STANDING, item.standing ?? 1);
128
+ const cheapest = Math.min(...open.map(cost));
129
+ const nearTie = 1 + (routing.quota?.nearTiePercent ?? DEFAULT_POOL_NEAR_TIE_PERCENT) / 100;
130
+ const chosen = open.filter(item => cost(item) <= cheapest * nearTie)
131
+ .reduce((first, next) => (next.standing ?? 1) > (first.standing ?? 1) ? next : first);
132
+ const { target } = chosen;
133
+ const applied = target.provider !== input.baseline.provider || target.model !== input.baseline.model
134
+ || (target.effort !== undefined && target.effort !== input.baseline.effort);
135
+ return { poolClass, target, applied, reason, evidence, candidates: sufficient.length, blocked, ...counted, ...(chosen.standing === undefined ? {} : { standing: chosen.standing }) };
136
+ }
@@ -1,5 +1,6 @@
1
1
  import { configuredModelSnapshot } from '../model-metadata.js';
2
2
  import { ANDORRA_SESSION_ID, findProviderById, ProviderRequestError, REASONING_EFFORTS, RetryableProviderError, supportsReasoningEffort } from '../providers.js';
3
+ import { ProviderTurnTimeoutError } from '../provider-turn-deadline.js';
3
4
  import { redactSecrets } from '../memory/redaction.js';
4
5
  import { RELAY_DELTA_LIMIT_BYTES, RELAY_FAILURE_CODE, RELAY_PAYLOAD_LIMIT_BYTES } from './remote.js';
5
6
  /** At most this many relayed requests of one machine are in hand at once, generating or waiting to be delivered; another is left for a later announce. */
@@ -77,6 +78,10 @@ function failureOf(error) {
77
78
  const message = shownMessage(error);
78
79
  if (!(error instanceof ProviderRequestError))
79
80
  return { message, kind: 'other' };
81
+ if (error instanceof ProviderTurnTimeoutError) {
82
+ const { phase, limitMs, elapsedMs, lastProgressAgeMs } = error;
83
+ return { message, kind: 'provider-request', code: 'provider_timeout', timeout: { phase, limitMs, elapsedMs, lastProgressAgeMs } };
84
+ }
80
85
  const code = typeof error.telemetryCode === 'string' && RELAY_FAILURE_CODE.test(error.telemetryCode) ? error.telemetryCode : undefined;
81
86
  return {
82
87
  message, kind: error instanceof RetryableProviderError ? 'retryable' : 'provider-request',
@@ -1,4 +1,5 @@
1
1
  import { type ProviderConfig } from '../providers.js';
2
+ import { type ProviderTurnTiming } from '../provider-turn-deadline.js';
2
3
  import type { Message, ModelAdapter, ModelRequestContext, ModelResponse, ModelRetry, ToolSchema } from '../types.js';
3
4
  /** One model request's JSON payload may be this large; with its envelope it stays under the relay's 16 MiB frame. */
4
5
  export declare const RELAY_PAYLOAD_LIMIT_BYTES: number;
@@ -39,6 +40,7 @@ export interface RelayFailure {
39
40
  kind: RelayErrorKind;
40
41
  contextOverflow?: true;
41
42
  code?: string;
43
+ timeout?: ProviderTurnTiming;
42
44
  }
43
45
  /** The form a relayed failure's telemetry code must have. */
44
46
  export declare const RELAY_FAILURE_CODE: RegExp;
@@ -1,5 +1,6 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { ProviderRequestError, RetryableProviderError } from '../providers.js';
3
+ import { ProviderTurnTimeoutError, readProviderTurnTiming } from '../provider-turn-deadline.js';
3
4
  /** One model request's JSON payload may be this large; with its envelope it stays under the relay's 16 MiB frame. */
4
5
  export const RELAY_PAYLOAD_LIMIT_BYTES = 12 * 1024 * 1024;
5
6
  /** An unclaimed request is announced again this often, so a desktop that attaches later still sees it. */
@@ -46,6 +47,9 @@ function boundedDelta(delta) {
46
47
  function failure(error) {
47
48
  const message = typeof error?.message === 'string' && error.message.trim() ? error.message : 'The model request failed on your computer.';
48
49
  const code = typeof error?.code === 'string' && RELAY_FAILURE_CODE.test(error.code) ? error.code : undefined;
50
+ const timing = error?.kind === 'provider-request' && code === 'provider_timeout' ? readProviderTurnTiming(error.timeout) : undefined;
51
+ if (timing)
52
+ return new ProviderTurnTimeoutError(timing.phase, timing.limitMs, timing.elapsedMs, timing.lastProgressAgeMs);
49
53
  let failed;
50
54
  if (error?.kind === 'retryable')
51
55
  failed = new RetryableProviderError(message);
@@ -1,5 +1,5 @@
1
1
  import type { DecisionBatch } from './decision/types.js';
2
- import { type AdaptiveRoutingConfig, type EfficiencyReason, type ModelPricing, type ModelTier } from './efficiency.js';
2
+ import { type AdaptiveRoutingConfig, type EfficiencyReason, type ModelPricing, type ModelTier, type PoolEffort } from './efficiency.js';
3
3
  import type { Usage } from './types.js';
4
4
  export interface TierDecisionInput {
5
5
  task: string;
@@ -27,17 +27,32 @@ export interface TierDecisionInput {
27
27
  reason?: string;
28
28
  escalations: number;
29
29
  };
30
+ /** The thinking levels a provider's model takes. Without it every scored level can be chosen. */
31
+ levels?: (provider: string, model: string) => readonly string[] | undefined;
30
32
  }
31
33
  export interface TierDecision {
32
34
  tier?: ModelTier;
35
+ /** `effort` is the tier's thinking level: the one the tier names, or the one chosen from the model's scores. */
33
36
  target?: {
34
37
  provider: string;
35
38
  model: string;
39
+ effort?: PoolEffort;
36
40
  };
37
41
  applied: boolean;
38
42
  reason: EfficiencyReason;
39
43
  evidence: 'policy' | 'pinned' | 'hint' | 'lexical' | 'escalation' | 'none';
40
44
  }
45
+ export declare const RISK_WORDS: RegExp;
46
+ export declare const MECHANICAL_WORDS: RegExp;
47
+ export declare const MECHANICAL_MAX_CHARS = 400;
48
+ /**
49
+ * The thinking level a tier's model runs at, from its scores: the cheapest scored level that reaches the tier's
50
+ * score, or the best-scored level when none reaches it. Undefined when no level the model takes is scored.
51
+ */
52
+ export declare function tierEffort(routing: Pick<AdaptiveRoutingConfig, 'scores' | 'classScores'>, tier: ModelTier, target: {
53
+ provider: string;
54
+ model: string;
55
+ }, levels?: (provider: string, model: string) => readonly string[] | undefined): PoolEffort | undefined;
41
56
  export declare function classifyTier(task: string, hints: DecisionBatch | undefined): {
42
57
  tier: ModelTier;
43
58
  evidence: 'hint' | 'lexical';
@@ -1,9 +1,31 @@
1
1
  import { DecisionPolicy } from './decision/DecisionPolicy.js';
2
- import { MODEL_TIERS } from './efficiency.js';
3
- const RISK_WORDS = /\b(security|auth(?:entication|orization|n)?|credential|secret|token|crypt|permission|sandbox|race condition|deadlock|memory leak|crash|segfault|corrupt|data loss|architecture|architectural|redesign|migration|migrate|concurrency|thread|lock|regression|flaky|intermittent|nondeterministic|root cause)\b/i;
4
- const MECHANICAL_WORDS = /\b(rename|typo|comment|docstring|jsdoc|format(?:ting)?|reformat|prettier|lint(?: fix)?|bump (?:the )?version|changelog|readme|whitespace|trailing|reorder imports|sort imports|unused import|remove unused|add (?:a )?log|console\.log|copyright|license header|spelling|wording)\b/i;
5
- const MECHANICAL_MAX_CHARS = 400;
2
+ import { DEFAULT_POOL_CLASS_SCORES, MODEL_TIERS, POOL_EFFORTS, poolScoreKey } from './efficiency.js';
3
+ export const RISK_WORDS = /\b(security|auth(?:entication|orization|n)?|credential|secret|token|crypt|permission|sandbox|race condition|deadlock|memory leak|crash|segfault|corrupt|data loss|architecture|architectural|redesign|migration|migrate|concurrency|thread|lock|regression|flaky|intermittent|nondeterministic|root cause)\b/i;
4
+ export const MECHANICAL_WORDS = /\b(rename|typo|comment|docstring|jsdoc|format(?:ting)?|reformat|prettier|lint(?: fix)?|bump (?:the )?version|changelog|readme|whitespace|trailing|reorder imports|sort imports|unused import|remove unused|add (?:a )?log|console\.log|copyright|license header|spelling|wording)\b/i;
5
+ export const MECHANICAL_MAX_CHARS = 400;
6
6
  const ESCALATION_REASONS = new Set(['repeatedToolFailure', 'maxIterations', 'maxCompletionRepairs', 'Prepared-step metadata allowance exhausted']);
7
+ /** The class whose score a tier's thinking level must reach. */
8
+ const TIER_CLASS = { economy: 'quick', balanced: 'standard', premium: 'deep' };
9
+ /**
10
+ * The thinking level a tier's model runs at, from its scores: the cheapest scored level that reaches the tier's
11
+ * score, or the best-scored level when none reaches it. Undefined when no level the model takes is scored.
12
+ */
13
+ export function tierEffort(routing, tier, target, levels) {
14
+ const key = poolScoreKey(target.provider, target.model);
15
+ const score = routing.scores && Object.hasOwn(routing.scores, key) ? routing.scores[key] : undefined;
16
+ const taken = levels?.(target.provider, target.model);
17
+ const scored = POOL_EFFORTS.flatMap(effort => {
18
+ const pair = score?.efforts?.[effort];
19
+ return pair && (taken === undefined || taken.includes(effort)) ? [{ effort, quality: pair.quality, cost: pair.cost ?? pair.quality }] : [];
20
+ });
21
+ if (!scored.length)
22
+ return undefined;
23
+ const needed = routing.classScores?.[TIER_CLASS[tier]] ?? DEFAULT_POOL_CLASS_SCORES[TIER_CLASS[tier]];
24
+ const reaching = scored.filter(item => item.quality >= needed);
25
+ if (!reaching.length)
26
+ return scored.reduce((best, next) => next.quality > best.quality ? next : best).effort;
27
+ return reaching.reduce((best, next) => next.cost < best.cost ? next : best).effort;
28
+ }
7
29
  function configuredTarget(target, configured) {
8
30
  if (!target)
9
31
  return undefined;
@@ -15,7 +37,7 @@ function configuredTarget(target, configured) {
15
37
  return undefined;
16
38
  if (target.model !== undefined && provider.models?.length && !provider.models.includes(target.model) && provider.model !== target.model)
17
39
  return undefined;
18
- return { provider: provider.id, model };
40
+ return { provider: provider.id, model, ...(target.effort === undefined ? {} : { effort: target.effort }) };
19
41
  }
20
42
  function nextTier(tier) {
21
43
  const index = MODEL_TIERS.indexOf(tier);
@@ -46,9 +68,11 @@ export function decideModelTier(input) {
46
68
  if (input.node.provider !== undefined || input.node.model !== undefined || input.modelPinned)
47
69
  return { ...baseline, reason: 'pinned', evidence: 'pinned' };
48
70
  const resolve = (tier, reason, evidence) => {
49
- const target = configuredTarget(input.routing.tiers?.[tier], input.configured);
50
- if (!target)
71
+ const found = configuredTarget(input.routing.tiers?.[tier], input.configured);
72
+ if (!found)
51
73
  return { ...baseline, tier, reason: 'unconfigured', evidence };
74
+ const effort = found.effort ?? tierEffort(input.routing, tier, found, input.levels);
75
+ const target = effort === undefined ? found : { ...found, effort };
52
76
  const differs = target.provider !== input.baseline.provider || target.model !== input.baseline.model;
53
77
  return { tier, target, applied: differs, reason, evidence };
54
78
  };
@@ -7,6 +7,7 @@ import { resolveCliExecutable } from './cli-executable.js';
7
7
  import { stopProcessTree } from './cli-process.js';
8
8
  import { resolveTrustedTaskkill } from './shell.js';
9
9
  import { allowanceInstruction, boundTextStep, parseStructuredStep, STRUCTURED_STEP_PROMPT, STRUCTURED_STEP_SCHEMA, structuredStepPrompt, TEXT_STEP_PROMPT } from './structured-step.js';
10
+ import { DEFAULT_WHOLE_RESPONSE_MS, withProviderTurnDeadline } from './provider-turn-deadline.js';
10
11
  export const OPENCODE_BASE_URL = 'https://opencode.ai';
11
12
  export const OPENCODE_EXECUTABLE = {
12
13
  names: ['opencode'], overrideEnv: 'ANDORRA_OPENCODE_PATH', homeDirectories: [join('.opencode', 'bin')],
@@ -15,7 +16,6 @@ export const OPENCODE_EXECUTABLE = {
15
16
  };
16
17
  const START_TIMEOUT_MS = 60_000;
17
18
  const IDLE_STOP_MS = 5 * 60_000;
18
- const REQUEST_TIMEOUT_MS = 10 * 60_000;
19
19
  const CATALOG_TIMEOUT_MS = 30_000;
20
20
  const RETRY_POLL_MS = 2_000;
21
21
  const STRUCTURED_AGENT = 'andorra';
@@ -245,66 +245,69 @@ export function createOpenCodeCliAdapter(_config, dependencies = {}) {
245
245
  if (auxiliary && request.tools.length)
246
246
  throw new Error('OpenCode cannot apply an auxiliary output allowance to tool-bearing requests.');
247
247
  const { providerID, modelID } = splitModel(request.model);
248
- const signal = AbortSignal.any([request.signal, AbortSignal.timeout(REQUEST_TIMEOUT_MS)]);
249
- const created = await server().request('/session', { method: 'POST', body: { title: 'Andorra model step' }, signal });
250
- const sessionId = object(created.body)?.id;
251
- if (created.status !== 200 || typeof sessionId !== 'string' || !/^[\w-]{1,200}$/.test(sessionId))
252
- throw new Error('OpenCode could not open a session.');
253
- const parts = [{ type: 'text', text: structuredStepPrompt(request) }];
254
- request.messages.forEach((message, index) => message.images?.forEach((image, imageIndex) => {
255
- parts.push({ type: 'text', text: `Image ${imageIndex + 1} from conversation message ${index + 1}:` }, { type: 'file', mime: image.mimeType, url: `data:${image.mimeType};base64,${image.data}`, filename: `image-${index + 1}-${imageIndex + 1}` });
256
- }));
257
- const watch = new AbortController();
258
- let retried;
259
- const poll = (async () => {
260
- while (!watch.signal.aborted) {
261
- await new Promise(resolve => setTimeout(resolve, dependencies.retryPollMs ?? RETRY_POLL_MS));
262
- if (watch.signal.aborted)
263
- return;
264
- const status = await server().request('/session/status', { signal: AbortSignal.any([signal, watch.signal]) }).catch(() => undefined);
265
- const state = object(object(status?.body)?.[sessionId]);
266
- if (state?.type === 'retry') {
267
- retried = note(state.message) ?? 'the provider asked to retry later';
268
- watch.abort();
269
- return;
248
+ return withProviderTurnDeadline(request.signal, async (deadline) => {
249
+ const { signal } = deadline;
250
+ const created = await server().request('/session', { method: 'POST', body: { title: 'Andorra model step' }, signal });
251
+ const sessionId = object(created.body)?.id;
252
+ if (created.status !== 200 || typeof sessionId !== 'string' || !/^[\w-]{1,200}$/.test(sessionId))
253
+ throw new Error('OpenCode could not open a session.');
254
+ const parts = [{ type: 'text', text: structuredStepPrompt(request) }];
255
+ request.messages.forEach((message, index) => message.images?.forEach((image, imageIndex) => {
256
+ parts.push({ type: 'text', text: `Image ${imageIndex + 1} from conversation message ${index + 1}:` }, { type: 'file', mime: image.mimeType, url: `data:${image.mimeType};base64,${image.data}`, filename: `image-${index + 1}-${imageIndex + 1}` });
257
+ }));
258
+ const watch = new AbortController();
259
+ let retried;
260
+ const poll = (async () => {
261
+ while (!watch.signal.aborted) {
262
+ await new Promise(resolve => setTimeout(resolve, dependencies.retryPollMs ?? RETRY_POLL_MS));
263
+ if (watch.signal.aborted)
264
+ return;
265
+ const status = await server().request('/session/status', { signal: AbortSignal.any([signal, watch.signal]) }).catch(() => undefined);
266
+ const state = object(object(status?.body)?.[sessionId]);
267
+ if (state?.type === 'retry') {
268
+ retried = note(state.message) ?? 'the provider asked to retry later';
269
+ watch.abort();
270
+ return;
271
+ }
270
272
  }
271
- }
272
- })();
273
- const stopped = AbortSignal.any([signal, watch.signal]);
274
- try {
275
- request.onRequest?.();
276
- let reply;
273
+ })();
274
+ const stopped = AbortSignal.any([signal, watch.signal]);
277
275
  try {
278
- reply = await server().request(`/session/${sessionId}/message`, { method: 'POST', signal: stopped, body: {
279
- model: { providerID, modelID }, agent: auxiliary ? TEXT_AGENT : STRUCTURED_AGENT, parts,
280
- ...(auxiliary ? { system: allowanceInstruction(request.maxTokens) } : {}),
281
- ...(auxiliary ? {} : { format: { type: 'json_schema', schema: STRUCTURED_STEP_SCHEMA, retryCount: 1 } }),
282
- } });
283
- }
284
- catch (error) {
276
+ deadline.waitForResponse();
277
+ request.onRequest?.();
278
+ let reply;
279
+ try {
280
+ reply = await server().request(`/session/${sessionId}/message`, { method: 'POST', signal: stopped, body: {
281
+ model: { providerID, modelID }, agent: auxiliary ? TEXT_AGENT : STRUCTURED_AGENT, parts,
282
+ ...(auxiliary ? { system: allowanceInstruction(request.maxTokens) } : {}),
283
+ ...(auxiliary ? {} : { format: { type: 'json_schema', schema: STRUCTURED_STEP_SCHEMA, retryCount: 1 } }),
284
+ } });
285
+ }
286
+ catch (error) {
287
+ if (retried)
288
+ throw new Error(`OpenCode request failed: ${retried}`);
289
+ throw error;
290
+ }
285
291
  if (retried)
286
292
  throw new Error(`OpenCode request failed: ${retried}`);
287
- throw error;
293
+ if (reply.status !== 200)
294
+ throw upstreamFailure(object(reply.body), providerID);
295
+ const response = parseOpenCodeReply(reply.body, request.tools, providerID, !auxiliary);
296
+ if (!auxiliary)
297
+ return response;
298
+ const visible = reply.body.info?.tokens?.output;
299
+ return boundTextStep(response, request.maxTokens, Number.isSafeInteger(visible) ? visible : undefined);
288
300
  }
289
- if (retried)
290
- throw new Error(`OpenCode request failed: ${retried}`);
291
- if (reply.status !== 200)
292
- throw upstreamFailure(object(reply.body), providerID);
293
- const response = parseOpenCodeReply(reply.body, request.tools, providerID, !auxiliary);
294
- if (!auxiliary)
295
- return response;
296
- const visible = reply.body.info?.tokens?.output;
297
- return boundTextStep(response, request.maxTokens, Number.isSafeInteger(visible) ? visible : undefined);
298
- }
299
- finally {
300
- const interrupted = stopped.aborted;
301
- watch.abort();
302
- await poll;
303
- const cleanup = AbortSignal.timeout(10_000);
304
- if (interrupted)
305
- await server().request(`/session/${sessionId}/abort`, { method: 'POST', signal: cleanup }).catch(() => { });
306
- await server().request(`/session/${sessionId}`, { method: 'DELETE', signal: cleanup }).catch(() => { });
307
- }
301
+ finally {
302
+ const interrupted = stopped.aborted;
303
+ watch.abort();
304
+ await poll;
305
+ const cleanup = AbortSignal.timeout(10_000);
306
+ if (interrupted)
307
+ await server().request(`/session/${sessionId}/abort`, { method: 'POST', signal: cleanup }).catch(() => { });
308
+ await server().request(`/session/${sessionId}`, { method: 'DELETE', signal: cleanup }).catch(() => { });
309
+ }
310
+ }, { responseMs: DEFAULT_WHOLE_RESPONSE_MS });
308
311
  },
309
312
  };
310
313
  }
@@ -1,3 +1,4 @@
1
+ import { createProviderTurnDeadline, ProviderTurnTimeoutError } from './provider-turn-deadline.js';
1
2
  import { createHash, randomUUID } from 'node:crypto';
2
3
  import { loadEngineStreams } from './engine-streams.js';
3
4
  import { andorraNormalizeContext } from '../vendor/engine/runtime/ai/utils/transcript.js';
@@ -208,15 +209,13 @@ export function createOpenCodeAdapter(config, dependencies = {}) {
208
209
  ...(protocol === 'openai-completions' ? { compat: { supportsDeveloperRole: false, supportsStore: false,
209
210
  supportsMidConvoSystemMessages: true, requiresReasoningContentOnAssistantMessages: true } } : {}) };
210
211
  const timeoutMs = config.streamIdleTimeoutMs ?? config.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
211
- const deadline = new AbortController();
212
- const signal = AbortSignal.any([request.signal, deadline.signal]);
213
- let timer;
214
- const refresh = () => { clearTimeout(timer); if (timeoutMs > 0)
215
- timer = setTimeout(() => deadline.abort(), timeoutMs); };
212
+ const deadline = createProviderTurnDeadline(request.signal, { startupMs: timeoutMs, idleMs: timeoutMs,
213
+ ...(timeoutMs === 0 ? { totalMs: 0 } : {}) });
214
+ const { signal } = deadline;
216
215
  let wire = '', transportError;
217
216
  let cancelBody = async () => { };
218
217
  const send = async (body) => {
219
- refresh();
218
+ deadline.waitForResponse();
220
219
  request.onRequest?.();
221
220
  const headers = { 'content-type': 'application/json', 'user-agent': 'andorra-code/0.1', 'x-opencode-session': session };
222
221
  if (protocol === 'anthropic-messages') {
@@ -285,7 +284,7 @@ export function createOpenCodeAdapter(config, dependencies = {}) {
285
284
  let size = 0, ended = false;
286
285
  const decoder = new TextDecoder('utf-8', { fatal: true });
287
286
  let controller;
288
- const finish = () => { ended = true; clearTimeout(timer); signal.removeEventListener('abort', abort); };
287
+ const finish = () => { ended = true; signal.removeEventListener('abort', abort); };
289
288
  cancelBody = async () => { if (!ended) {
290
289
  finish();
291
290
  await reader.cancel().catch(() => { });
@@ -313,7 +312,6 @@ export function createOpenCodeAdapter(config, dependencies = {}) {
313
312
  if ((size += chunk.value.byteLength) > OUTPUT_LIMIT)
314
313
  throw new Error('OpenCode Go response exceeds the 4 MiB limit.');
315
314
  wire += decoder.decode(chunk.value, { stream: true });
316
- refresh();
317
315
  value.enqueue(chunk.value);
318
316
  }
319
317
  catch (error) {
@@ -335,7 +333,7 @@ export function createOpenCodeAdapter(config, dependencies = {}) {
335
333
  try {
336
334
  let result;
337
335
  if (protocol === 'google-generative-ai')
338
- result = await googleResponse(request, model, send, effort, providerTools, codec);
336
+ result = await googleResponse(request, model, send, effort, providerTools, codec, deadline.progress);
339
337
  else {
340
338
  const nativeRequest = { ...request, messages: request.messages.map(message => {
341
339
  const saved = message.providerContinuation;
@@ -353,6 +351,8 @@ export function createOpenCodeAdapter(config, dependencies = {}) {
353
351
  const stream = protocol === 'openai-completions' ? chatStream(model, context, options)
354
352
  : protocol === 'openai-responses' ? responsesStream(model, context, options) : messagesStream(model, context, options);
355
353
  for await (const event of stream) {
354
+ if ((event.type === 'text_delta' || event.type === 'thinking_delta' || event.type === 'toolcall_delta') && event.delta)
355
+ deadline.progress();
356
356
  if (event.type === 'text_delta')
357
357
  request.onText?.(event.delta);
358
358
  if (event.type === 'thinking_delta')
@@ -386,8 +386,8 @@ export function createOpenCodeAdapter(config, dependencies = {}) {
386
386
  catch (error) {
387
387
  if (request.signal.aborted)
388
388
  throw new Error('OpenCode Go request cancelled.');
389
- if (deadline.signal.aborted)
390
- throw new Error('OpenCode Go request timed out.');
389
+ if (signal.reason instanceof ProviderTurnTimeoutError)
390
+ throw signal.reason;
391
391
  if (error instanceof ProviderRequestError)
392
392
  throw error;
393
393
  if (error instanceof Error && /^OpenCode Go (?:response exceeds|returned)/.test(error.message))
@@ -395,7 +395,7 @@ export function createOpenCodeAdapter(config, dependencies = {}) {
395
395
  throw new Error('OpenCode Go request failed. Check the Go connection and model availability.');
396
396
  }
397
397
  finally {
398
- clearTimeout(timer);
398
+ deadline.dispose();
399
399
  await cancelBody();
400
400
  }
401
401
  },
@@ -413,7 +413,7 @@ function engineResponse(output, provider, model) {
413
413
  usage: { inputTokens: counter(output.usage.input) + counter(output.usage.cacheRead) + counter(output.usage.cacheWrite),
414
414
  outputTokens: counter(output.usage.output), cacheRead: counter(output.usage.cacheRead), cacheWrite: counter(output.usage.cacheWrite), requests: 1 } };
415
415
  }
416
- async function googleResponse(request, model, send, effort, providerTools, codec) {
416
+ async function googleResponse(request, model, send, effort, providerTools, codec, progress) {
417
417
  const engineMessages = toEngineMessages(request, model, codec);
418
418
  for (const [index, message] of engineMessages.entries())
419
419
  if (message.role === 'assistant') {
@@ -475,6 +475,8 @@ async function googleResponse(request, model, send, effort, providerTools, codec
475
475
  object(part);
476
476
  parts.push(part);
477
477
  if (typeof part.text === 'string') {
478
+ if (part.text)
479
+ progress();
478
480
  if (part.thought) {
479
481
  thoughts.push(part.text);
480
482
  request.onReasoning?.(part.text);
@@ -491,6 +493,7 @@ async function googleResponse(request, model, send, effort, providerTools, codec
491
493
  if (typeof call.name !== 'string' || !call.name)
492
494
  malformed();
493
495
  calls.push({ id, name: call.name, arguments: JSON.stringify(object(call.args ?? {})) });
496
+ progress();
494
497
  }
495
498
  }
496
499
  };