@bitkyc08/opencodex 2.91.0 → 2.93.0-preview.20261027

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 (360) hide show
  1. package/bin/ocx.mjs +47 -8
  2. package/gui/dist/assets/App-CJZoq-uF.js +58 -0
  3. package/gui/dist/assets/{Tray-BuLy7hL1.js → Tray-BWQPcgZn.js} +1 -1
  4. package/gui/dist/assets/index-DRe8Hhfz.css +1 -0
  5. package/gui/dist/assets/index-Xfct8owH.js +94 -0
  6. package/gui/dist/assets/quota-summary-DxToX1rV.js +1 -0
  7. package/gui/dist/index.html +2 -2
  8. package/gui/dist/provider-icons/workbuddy-color.svg +29 -0
  9. package/package.json +8 -7
  10. package/src/adapters/anthropic.ts +28 -5
  11. package/src/adapters/coding-agent/batch-dispatcher.ts +122 -0
  12. package/src/adapters/coding-agent/profile.ts +54 -16
  13. package/src/adapters/coding-agent/turn.ts +30 -2
  14. package/src/adapters/command-code.ts +114 -7
  15. package/src/adapters/cursor/native-exec-fs.ts +11 -9
  16. package/src/adapters/devin/live-models.ts +4 -0
  17. package/src/adapters/google-vertex-endpoint.ts +9 -1
  18. package/src/adapters/google-vertex-key-project.ts +223 -0
  19. package/src/adapters/google-wire-compiler.ts +1 -2
  20. package/src/adapters/google.ts +13 -3
  21. package/src/adapters/kiro/reasoning.ts +2 -0
  22. package/src/adapters/kiro-refusal.ts +6 -1
  23. package/src/adapters/kiro-wire.ts +1 -1
  24. package/src/adapters/openai-chat/messages.ts +8 -2
  25. package/src/adapters/openai-chat/passthrough.ts +35 -14
  26. package/src/adapters/openai-chat/reasoning-replay.ts +27 -16
  27. package/src/adapters/openai-chat/reasoning-wire.ts +117 -8
  28. package/src/adapters/openai-chat/required-tool-result.ts +64 -0
  29. package/src/adapters/openai-chat/tool-name-registry.ts +3 -1
  30. package/src/adapters/openai-chat.ts +9 -10
  31. package/src/adapters/openai-responses/passthrough.ts +7 -4
  32. package/src/adapters/openai-responses/reasoning.ts +13 -0
  33. package/src/adapters/openai-responses/request-strips.ts +60 -0
  34. package/src/adapters/qoder/adapter.ts +129 -8
  35. package/src/adapters/qoder/scaffold-guard.ts +5 -0
  36. package/src/adapters/reasoning-controls.ts +16 -0
  37. package/src/adapters/registry.ts +5 -0
  38. package/src/adapters/tool-call-id.ts +1 -3
  39. package/src/adapters/workbuddy-schema.ts +61 -0
  40. package/src/adapters/workbuddy.ts +68 -0
  41. package/src/bridge/errors.ts +27 -0
  42. package/src/bridge/response-json.ts +1 -1
  43. package/src/bridge/sse.ts +1 -1
  44. package/src/bridge.ts +1 -1
  45. package/src/chat/inbound.ts +4 -1
  46. package/src/chat/outbound.ts +20 -6
  47. package/src/chat/reasoning-details.ts +28 -5
  48. package/src/claude/desktop-first-party.ts +54 -4
  49. package/src/claude/desktop-picker.ts +11 -8
  50. package/src/claude/first-party-settings.ts +3 -1
  51. package/src/claude/inbound.ts +2 -1
  52. package/src/claude/intercept/local-ca.ts +2 -1
  53. package/src/claude/intercept/picker-ca-cleanup.ts +4 -2
  54. package/src/claude/intercept/picker-ca-startup.ts +3 -1
  55. package/src/claude/intercept/picker-models.ts +6 -3
  56. package/src/claude/intercept/picker-runtime.ts +3 -2
  57. package/src/claude/intercept/runtime.ts +6 -3
  58. package/src/claude/model-info.ts +31 -8
  59. package/src/cli/account-api.ts +11 -0
  60. package/src/cli/capabilities-agents-routing.ts +3 -3
  61. package/src/cli/capabilities-base.ts +7 -1
  62. package/src/cli/capabilities-observe-system.ts +10 -0
  63. package/src/cli/claude-desktop.ts +9 -8
  64. package/src/cli/claude.ts +3 -2
  65. package/src/cli/codex-cli-update.ts +8 -0
  66. package/src/cli/codex-shim-autorestore.ts +9 -0
  67. package/src/cli/combo-result.ts +13 -0
  68. package/src/cli/combo-stats.ts +3 -0
  69. package/src/cli/combo.ts +83 -41
  70. package/src/cli/cross-home-owner.ts +13 -1
  71. package/src/cli/dispatch.ts +25 -6
  72. package/src/cli/ensure-desired-integrations.ts +8 -6
  73. package/src/cli/export-command.ts +4 -1
  74. package/src/cli/help.ts +2 -1
  75. package/src/cli/index.ts +45 -45
  76. package/src/cli/integration-plan-dto.ts +4 -0
  77. package/src/cli/launcher-context.ts +49 -2
  78. package/src/cli/link.ts +45 -32
  79. package/src/cli/opencode.ts +20 -9
  80. package/src/cli/provider.ts +2 -1
  81. package/src/cli/registry.ts +6 -4
  82. package/src/cli/root.ts +9 -0
  83. package/src/cli/status.ts +59 -1
  84. package/src/cli/stop-restore.ts +113 -0
  85. package/src/cli/sync-expectation.ts +60 -0
  86. package/src/cli/uninstall-integrations.ts +41 -7
  87. package/src/cli/usage-compare.ts +68 -12
  88. package/src/client/connect.ts +40 -3
  89. package/src/client/link-home.ts +10 -1
  90. package/src/client/link-ingress.ts +1 -1
  91. package/src/client/link-readiness.ts +97 -0
  92. package/src/client/link-relay-transport.ts +79 -11
  93. package/src/client/link-relay.ts +74 -15
  94. package/src/client/link-tunnel.ts +45 -18
  95. package/src/client/machine-api.ts +3 -1
  96. package/src/client/machine-listener.ts +20 -2
  97. package/src/client/runtime.ts +20 -2
  98. package/src/client/sync-expectation.ts +118 -0
  99. package/src/clients/config-export/agent-clients.ts +96 -0
  100. package/src/clients/config-export/contracts.ts +25 -7
  101. package/src/clients/config-export/qoder.ts +38 -23
  102. package/src/clients/config-export/reasoning-metadata.ts +55 -8
  103. package/src/clients/config-export.ts +12 -0
  104. package/src/clients/lazycodex.ts +7 -2
  105. package/src/clients/reasoning-controls.ts +49 -0
  106. package/src/codex/account-store.ts +17 -3
  107. package/src/codex/app-server-restart-service.ts +6 -5
  108. package/src/codex/auth-api/account-identity.ts +14 -0
  109. package/src/codex/auth-api/account-list.ts +29 -2
  110. package/src/codex/auth-api/http.ts +13 -0
  111. package/src/codex/auth-api/main-account-probe.ts +2 -2
  112. package/src/codex/auth-api/pool-mode-gate.ts +16 -3
  113. package/src/codex/auth-api/pool-quota-probe.ts +15 -0
  114. package/src/codex/auth-context.ts +15 -12
  115. package/src/codex/catalog/build-entries.ts +22 -0
  116. package/src/codex/catalog/configured-tiers.ts +70 -0
  117. package/src/codex/catalog/effort.ts +52 -11
  118. package/src/codex/catalog/gather-capture.ts +5 -2
  119. package/src/codex/catalog/heal-observation.ts +155 -13
  120. package/src/codex/catalog/metadata.ts +6 -0
  121. package/src/codex/catalog/model-hints.ts +60 -11
  122. package/src/codex/catalog/model-visibility.ts +3 -2
  123. package/src/codex/catalog/native-models.ts +18 -3
  124. package/src/codex/catalog/parsing.ts +10 -8
  125. package/src/codex/catalog/pinned-models.ts +2 -1
  126. package/src/codex/catalog/provider-models.ts +18 -13
  127. package/src/codex/catalog/retained-sync.ts +2 -1
  128. package/src/codex/catalog/routed-gather.ts +19 -20
  129. package/src/codex/catalog/write-audit.ts +3 -2
  130. package/src/codex/catalog-self-heal.ts +43 -23
  131. package/src/codex/chatgpt-refresh-failure.ts +6 -2
  132. package/src/codex/cli-install-provenance.ts +418 -0
  133. package/src/codex/cli-installation-targets.ts +5 -1
  134. package/src/codex/cli-update-plan.ts +43 -16
  135. package/src/codex/collision-identity.ts +30 -5
  136. package/src/codex/convergence.ts +4 -3
  137. package/src/codex/data/roster-pinned-models.json +177 -1
  138. package/src/codex/desired-state.ts +6 -1
  139. package/src/codex/desktop-app/picker-freshness.ts +10 -8
  140. package/src/codex/desktop-compatibility/installed-build.ts +88 -12
  141. package/src/codex/desktop-compatibility/runtime.ts +29 -5
  142. package/src/codex/desktop-compatibility/usage-activation.ts +2 -1
  143. package/src/codex/desktop-compatibility/usage-controller.ts +9 -1
  144. package/src/codex/desktop-compatibility/windows-certificate-trust.ts +46 -12
  145. package/src/codex/inject/config-toml.ts +0 -18
  146. package/src/codex/inject/plan.ts +18 -3
  147. package/src/codex/inject/remove.ts +6 -2
  148. package/src/codex/inject.ts +1 -1
  149. package/src/codex/journal.ts +61 -1
  150. package/src/codex/model-entitlements.ts +1 -1
  151. package/src/codex/native-main-owner.ts +27 -1
  152. package/src/codex/native-profile-store.ts +2 -1
  153. package/src/codex/pool-credit-policy.ts +35 -1
  154. package/src/codex/pool-refresh-backoff.ts +3 -1
  155. package/src/codex/quota-types.ts +3 -0
  156. package/src/codex/quota.ts +24 -4
  157. package/src/codex/role-auto-assign.ts +6 -2
  158. package/src/codex/subagent-defaults.ts +49 -4
  159. package/src/codex/user-identity.ts +35 -6
  160. package/src/codex/windows-current-sid.ts +162 -0
  161. package/src/combos/failover.ts +17 -2
  162. package/src/combos/jev-decision-contract.ts +22 -1
  163. package/src/combos/jev-quota-activation.ts +5 -1
  164. package/src/combos/jev-quota-route.ts +1 -1
  165. package/src/combos/jev-quota.ts +9 -1
  166. package/src/combos/jev-service-exchange.ts +3 -1
  167. package/src/combos/jev-session-pin-config.ts +51 -0
  168. package/src/combos/jev.ts +101 -9
  169. package/src/combos/resolve.ts +45 -1
  170. package/src/combos/types.ts +43 -0
  171. package/src/config/load-degrade.ts +5 -0
  172. package/src/config/paths.ts +19 -3
  173. package/src/config/pending-teardown.ts +22 -1
  174. package/src/config/provider-validation.ts +22 -4
  175. package/src/config/removed-opencode-free.ts +11 -0
  176. package/src/config/schema/leaf-validators.ts +6 -0
  177. package/src/generated/compatibility-version.json +467 -311
  178. package/src/generated/model-metadata.ts +5 -5
  179. package/src/images/loop.ts +16 -2
  180. package/src/integrations/catalog-refresh.ts +1 -1
  181. package/src/integrations/hermes-profiles.ts +251 -0
  182. package/src/integrations/merge.ts +8 -0
  183. package/src/integrations/mutation-plan.ts +19 -4
  184. package/src/integrations/registry.ts +5 -0
  185. package/src/integrations/state.ts +36 -1
  186. package/src/integrations/writer.ts +18 -4
  187. package/src/lib/bun-path-runtime.mjs +2 -1
  188. package/src/lib/decision-quota-sink.ts +10 -0
  189. package/src/lib/errors.ts +62 -0
  190. package/src/lib/eventstream-decoder.ts +81 -37
  191. package/src/lib/opaque-proxy-tunnel.ts +32 -8
  192. package/src/lib/pinned-http.ts +35 -2
  193. package/src/lib/process-control.ts +13 -1
  194. package/src/lib/socks5-fetch.ts +59 -64
  195. package/src/lib/socks5-upload-waiter.ts +50 -0
  196. package/src/lib/sse-decoder.ts +7 -2
  197. package/src/lib/state-store-sweeper.ts +40 -14
  198. package/src/lib/translator-budget.ts +4 -4
  199. package/src/lib/upstream-retry.ts +4 -1
  200. package/src/lib/windows-native-principal-worker.ts +14 -0
  201. package/src/lib/windows-native-principal.ts +188 -0
  202. package/src/lib/windows-secret-acl.ts +39 -3
  203. package/src/lib/windows-user-principal.ts +62 -18
  204. package/src/link/diagnostics.ts +193 -0
  205. package/src/link/relay-auth.ts +6 -0
  206. package/src/link/ssh-config.ts +35 -3
  207. package/src/link/status-projection.ts +39 -0
  208. package/src/link/supervisor.ts +45 -12
  209. package/src/link/tunnel-history.ts +109 -0
  210. package/src/link/tunnel-state.ts +80 -17
  211. package/src/messaging/remote-files.ts +24 -1
  212. package/src/oauth/generic-account-failover.ts +91 -7
  213. package/src/oauth/index.ts +15 -0
  214. package/src/oauth/model-discovery-auth.ts +5 -0
  215. package/src/oauth/store.ts +4 -1
  216. package/src/oauth/token-guardian.ts +7 -0
  217. package/src/oauth/types.ts +9 -0
  218. package/src/oauth/workbuddy.ts +139 -0
  219. package/src/providers/account-quota-disk.ts +12 -4
  220. package/src/providers/antigravity-quota-identity.ts +37 -0
  221. package/src/providers/base-url-choices.ts +8 -5
  222. package/src/providers/codebuddy-models.ts +6 -0
  223. package/src/providers/codex-capacity.ts +3 -1
  224. package/src/providers/derive.ts +51 -3
  225. package/src/providers/kiro-models.ts +3 -0
  226. package/src/providers/mimo-thinking.ts +12 -0
  227. package/src/providers/model-discovery.ts +2 -0
  228. package/src/providers/model-rename-fields.ts +2 -0
  229. package/src/providers/model-rename-migration.ts +10 -0
  230. package/src/providers/openai-sidecar-credit.ts +2 -2
  231. package/src/providers/quota/account-cache.ts +3 -2
  232. package/src/providers/quota/antigravity.ts +25 -14
  233. package/src/providers/quota/report-cache.ts +13 -4
  234. package/src/providers/quota/vendor-probes-key.ts +60 -0
  235. package/src/providers/quota/workbuddy.ts +83 -0
  236. package/src/providers/quota-decision-antigravity.ts +64 -0
  237. package/src/providers/quota-decision-publication.ts +11 -0
  238. package/src/providers/quota-decision-snapshot.ts +21 -4
  239. package/src/providers/quota-types.ts +2 -0
  240. package/src/providers/quota.ts +3 -1
  241. package/src/providers/reasoning-capabilities.ts +76 -0
  242. package/src/providers/registry/entries-core.ts +23 -12
  243. package/src/providers/registry/entries-extended.ts +83 -27
  244. package/src/providers/registry/model-ids.ts +5 -0
  245. package/src/providers/registry/model-seeds.ts +120 -56
  246. package/src/providers/registry/types.ts +29 -2
  247. package/src/providers/resolved-model-policy.ts +30 -10
  248. package/src/providers/routed-config.ts +24 -1
  249. package/src/providers/stale-model-roster-migration.ts +123 -18
  250. package/src/providers/workbuddy-credit-balance.ts +81 -0
  251. package/src/providers/workbuddy-models.ts +37 -0
  252. package/src/providers/workbuddy.ts +60 -0
  253. package/src/remote-control/workspace-pi-runtime.ts +11 -6
  254. package/src/responses/compaction-summary.ts +45 -0
  255. package/src/responses/muse-tool-name-alias.ts +1 -2
  256. package/src/responses/parser.ts +3 -2
  257. package/src/responses/reasoning-replay-cache.ts +18 -14
  258. package/src/responses/schema.ts +1 -0
  259. package/src/responses/thought-signature-replay.ts +10 -2
  260. package/src/router.ts +2 -0
  261. package/src/routing/analytics.ts +2 -3
  262. package/src/routing/capability.ts +8 -2
  263. package/src/routing/fallback-policy.ts +3 -3
  264. package/src/routing/history/ingest.ts +28 -3
  265. package/src/server/auth-cors.ts +4 -2
  266. package/src/server/chat-completions.ts +21 -1
  267. package/src/server/chat-native-eligibility.ts +7 -0
  268. package/src/server/chat-native-reasoning.ts +24 -7
  269. package/src/server/chat-native.ts +13 -2
  270. package/src/server/claude-messages.ts +3 -0
  271. package/src/server/direct-local-http.ts +5 -2
  272. package/src/server/effort-policy.ts +5 -1
  273. package/src/server/index/link-relay-sessions.ts +9 -5
  274. package/src/server/index/live-sideband.ts +18 -15
  275. package/src/server/index/optional-listeners.ts +4 -0
  276. package/src/server/index/serve-options.ts +5 -4
  277. package/src/server/local-management-read-client.ts +3 -1
  278. package/src/server/management/agent-settings-routes.ts +27 -15
  279. package/src/server/management/combo-routes.ts +14 -4
  280. package/src/server/management/config-routes.ts +2 -2
  281. package/src/server/management/decision-discovery.ts +12 -2
  282. package/src/server/management/hermes-profile-routes.ts +156 -0
  283. package/src/server/management/integration-routes.ts +85 -24
  284. package/src/server/management/link-routes.ts +5 -2
  285. package/src/server/management/model-routes.ts +2 -2
  286. package/src/server/management/model-row-export-metadata.ts +25 -6
  287. package/src/server/management/model-rows.ts +15 -20
  288. package/src/server/management/native-integration-routes.ts +11 -8
  289. package/src/server/management/provider-routes.ts +1 -1
  290. package/src/server/management/route-registry.ts +4 -0
  291. package/src/server/management-api.ts +5 -0
  292. package/src/server/models-capabilities.ts +21 -3
  293. package/src/server/port-reclaim.ts +51 -9
  294. package/src/server/request-log-conversation.ts +49 -0
  295. package/src/server/request-log.ts +2 -0
  296. package/src/server/responses/adapter-delivery.ts +11 -1
  297. package/src/server/responses/adapter-dispatch.ts +2 -2
  298. package/src/server/responses/anthropic-thinking-recovery.ts +1 -0
  299. package/src/server/responses/codex-ws-exchange.ts +39 -9
  300. package/src/server/responses/codex-ws-session.ts +38 -4
  301. package/src/server/responses/codex-ws-wire.ts +6 -1
  302. package/src/server/responses/combo-required-tool-contract.ts +103 -0
  303. package/src/server/responses/combo-stream-preflight.ts +8 -1
  304. package/src/server/responses/compact.ts +14 -5
  305. package/src/server/responses/context-overflow.ts +8 -1
  306. package/src/server/responses/core-combo-failure.ts +10 -0
  307. package/src/server/responses/core-combo.ts +74 -44
  308. package/src/server/responses/core-lifetime.ts +5 -2
  309. package/src/server/responses/core-normalize.ts +17 -4
  310. package/src/server/responses/core-opaque-recovery.ts +1 -0
  311. package/src/server/responses/core-options.ts +7 -0
  312. package/src/server/responses/core-replay.ts +2 -1
  313. package/src/server/responses/jev-combo-choice.ts +39 -0
  314. package/src/server/responses/jev-session-pin.ts +203 -0
  315. package/src/server/responses/main-hard-lock-routing.ts +60 -44
  316. package/src/server/responses/passthrough-delivery.ts +44 -2
  317. package/src/server/responses/policy-fallback.ts +6 -1
  318. package/src/server/responses/request-compression.ts +12 -7
  319. package/src/server/responses/request-prepare.ts +32 -7
  320. package/src/server/responses/request-sidecar-auth.ts +2 -0
  321. package/src/server/responses/request-transport.ts +25 -6
  322. package/src/server/responses/response-effects.ts +22 -10
  323. package/src/server/responses/run-turn-execution.ts +2 -4
  324. package/src/server/responses/sidecar-execution.ts +13 -7
  325. package/src/server/responses-phase-inference.ts +267 -0
  326. package/src/server/sse-payload-rewrite.ts +14 -1
  327. package/src/server/stop-teardown.ts +36 -1
  328. package/src/server/ws-bridge.ts +1 -1
  329. package/src/service/definition.ts +20 -8
  330. package/src/service/desktop-supervision.d.mts +7 -4
  331. package/src/service/desktop-supervision.mjs +90 -13
  332. package/src/service/ownership-mutation-lease.mjs +21 -7
  333. package/src/types/config.ts +14 -2
  334. package/src/types/provider.ts +29 -7
  335. package/src/types/request.ts +11 -0
  336. package/src/types/wire.ts +1 -0
  337. package/src/types.ts +1 -0
  338. package/src/update/bind-probe.ts +29 -0
  339. package/src/update/codex-cli-update-launch-policy.d.mts +9 -0
  340. package/src/update/codex-cli-update-launch-policy.mjs +30 -0
  341. package/src/update/job.ts +10 -29
  342. package/src/update/npm-install-job.ps1 +173 -0
  343. package/src/update/npm-install.mjs +70 -0
  344. package/src/update/stop-contract.d.mts +1 -0
  345. package/src/update/stop-contract.mjs +14 -0
  346. package/src/update/stop-decision.d.mts +1 -1
  347. package/src/update/stop-decision.mjs +13 -3
  348. package/src/update/teardown-handover.ts +166 -0
  349. package/src/update/transactional-install.d.mts +14 -3
  350. package/src/update/transactional-install.mjs +33 -7
  351. package/src/usage/expected-prices.ts +64 -31
  352. package/src/usage/jev-stats.ts +54 -14
  353. package/src/usage/timeline.ts +19 -9
  354. package/src/vision/eligibility.ts +15 -5
  355. package/src/vision/plan.ts +2 -2
  356. package/src/web-search/loop.ts +16 -2
  357. package/gui/dist/assets/App-nZ34cR5G.js +0 -58
  358. package/gui/dist/assets/index-DGXS51sp.js +0 -94
  359. package/gui/dist/assets/index-DPeB9HpV.css +0 -1
  360. package/gui/dist/assets/quota-summary-DO1Sx5TM.js +0 -1
@@ -0,0 +1,162 @@
1
+ /**
2
+ * The effective process token's SID, read in-process on Windows x64.
3
+ *
4
+ * The PowerShell helper this replaces is correct but slow to start: a cold
5
+ * `powershell.exe` on a loaded runner spent more than the 30s lookup budget
6
+ * before evaluating one constant of the process token, and `ocx service install`
7
+ * refused (#7544). Widening that budget again would only move the line. The SID
8
+ * itself costs three advapi32 calls, so the x64 path asks the OS directly and the
9
+ * helper keeps running only where `bun:ffi` cannot (Windows ARM64).
10
+ *
11
+ * The answer is the PROCESS token's user. `WindowsIdentity.GetCurrent()` would
12
+ * prefer a thread impersonation token, but nothing in this process impersonates,
13
+ * so the two agree; the process token is also what Task Scheduler and the ACL
14
+ * code grant to.
15
+ *
16
+ * Fail-closed is preserved: when the native API is available and fails, the
17
+ * lookup throws and the caller refuses. It never falls back to the helper, whose
18
+ * environment the native path exists to avoid depending on.
19
+ */
20
+ import { dlopen, ptr, read, type Pointer } from "bun:ffi";
21
+ import { win32 } from "node:path";
22
+ import { resolveTrustedWindowsSystemDirectory } from "../lib/windows-elevation";
23
+
24
+ const TOKEN_QUERY = 0x0008;
25
+ const TOKEN_USER_INFORMATION_CLASS = 1;
26
+ /**
27
+ * TOKEN_USER is one SID_AND_ATTRIBUTES (an 8-byte SID pointer and a 4-byte
28
+ * attribute word, padded to 16) followed by the SID it points at. A SID is at
29
+ * most SECURITY_MAX_SID_SIZE (68) bytes, so 256 bytes always suffices and a
30
+ * larger reported length is treated as a malformed answer.
31
+ */
32
+ const TOKEN_USER_BUFFER_BYTES = 256;
33
+ const TOKEN_USER_HEADER_BYTES = 16;
34
+ /** "S-1-" plus at most 15 sub-authorities of up to 10 digits each, with room to spare. */
35
+ const MAX_SID_STRING_CODE_UNITS = 256;
36
+ const SID_PATTERN = /^S-1-(?:\d+-)+\d+$/i;
37
+
38
+ export interface WindowsTokenSidApi {
39
+ /** OpenProcessToken(GetCurrentProcess(), access, &token). Non-zero BOOL is success. */
40
+ openProcessToken(desiredAccess: number, token: BigUint64Array): number;
41
+ /** GetTokenInformation(token, class, buffer, buffer.length, &returnLength). */
42
+ getTokenInformation(
43
+ token: bigint,
44
+ informationClass: number,
45
+ buffer: Uint8Array,
46
+ returnLength: Uint32Array,
47
+ ): number;
48
+ /** ConvertSidToStringSidW(sid, &string). The string is LocalAlloc'd on success. */
49
+ convertSidToStringSid(sidAddress: number, output: BigUint64Array): number;
50
+ readCodeUnit(address: number, byteOffset: number): number;
51
+ localFree(address: number): void;
52
+ closeHandle(token: bigint): void;
53
+ }
54
+
55
+ function lookupError(detail: string): Error {
56
+ return new Error(`Windows effective-account token lookup ${detail}.`);
57
+ }
58
+
59
+ function readSidString(api: WindowsTokenSidApi, address: number): string {
60
+ const units: number[] = [];
61
+ for (let index = 0; index < MAX_SID_STRING_CODE_UNITS; index += 1) {
62
+ const unit = api.readCodeUnit(address, index * 2);
63
+ if (unit === 0) return String.fromCharCode(...units);
64
+ units.push(unit);
65
+ }
66
+ throw lookupError("returned an unterminated SID");
67
+ }
68
+
69
+ /** Same token user the PowerShell helper reports, without starting a process. */
70
+ export function readWindowsCurrentSid(api: WindowsTokenSidApi): string {
71
+ const tokenOutput = new BigUint64Array(1);
72
+ if (api.openProcessToken(TOKEN_QUERY, tokenOutput) === 0 || tokenOutput[0] === 0n) {
73
+ throw lookupError("could not open the process token");
74
+ }
75
+ const token = tokenOutput[0]!;
76
+ let stringAddress = 0;
77
+ try {
78
+ // Keep `buffer` referenced until the conversion returns: the SID pointer
79
+ // inside it points back into this same allocation.
80
+ const buffer = new Uint8Array(TOKEN_USER_BUFFER_BYTES);
81
+ const returnLength = new Uint32Array(1);
82
+ if (api.getTokenInformation(token, TOKEN_USER_INFORMATION_CLASS, buffer, returnLength) === 0) {
83
+ throw lookupError("could not read the token user");
84
+ }
85
+ const length = returnLength[0]!;
86
+ if (length <= TOKEN_USER_HEADER_BYTES || length > buffer.byteLength) {
87
+ throw lookupError("returned a malformed token user");
88
+ }
89
+ const sidAddress = Number(
90
+ new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength).getBigUint64(0, true),
91
+ );
92
+ if (!Number.isSafeInteger(sidAddress) || sidAddress <= 0) {
93
+ throw lookupError("returned a null SID");
94
+ }
95
+ const stringOutput = new BigUint64Array(1);
96
+ const converted = api.convertSidToStringSid(sidAddress, stringOutput);
97
+ const candidate = Number(stringOutput[0]);
98
+ if (converted === 0 || !Number.isSafeInteger(candidate) || candidate <= 0) {
99
+ throw lookupError("could not format the SID");
100
+ }
101
+ stringAddress = candidate;
102
+ const sid = readSidString(api, stringAddress);
103
+ if (!SID_PATTERN.test(sid)) throw lookupError("returned an invalid SID");
104
+ return sid.toUpperCase();
105
+ } finally {
106
+ if (stringAddress > 0) api.localFree(stringAddress);
107
+ api.closeHandle(token);
108
+ }
109
+ }
110
+
111
+ let nativeLookup: (() => string) | null | undefined;
112
+
113
+ function loadNativeLookup(): (() => string) | null {
114
+ if (nativeLookup !== undefined) return nativeLookup;
115
+ if (process.platform !== "win32" || process.arch !== "x64") return null;
116
+ try {
117
+ const systemDirectory = resolveTrustedWindowsSystemDirectory();
118
+ const advapi = dlopen(win32.join(systemDirectory, "advapi32.dll"), {
119
+ OpenProcessToken: { args: ["u64", "u32", "ptr"], returns: "i32" },
120
+ GetTokenInformation: { args: ["u64", "u32", "ptr", "u32", "ptr"], returns: "i32" },
121
+ ConvertSidToStringSidW: { args: ["ptr", "ptr"], returns: "i32" },
122
+ });
123
+ let kernel;
124
+ try {
125
+ kernel = dlopen(win32.join(systemDirectory, "kernel32.dll"), {
126
+ GetCurrentProcess: { args: [], returns: "u64" },
127
+ CloseHandle: { args: ["u64"], returns: "i32" },
128
+ LocalFree: { args: ["ptr"], returns: "ptr" },
129
+ });
130
+ } catch (error) {
131
+ advapi.close();
132
+ throw error;
133
+ }
134
+ const api: WindowsTokenSidApi = {
135
+ openProcessToken: (access, token) => advapi.symbols.OpenProcessToken(
136
+ kernel.symbols.GetCurrentProcess(), access, ptr(token),
137
+ ),
138
+ getTokenInformation: (token, informationClass, buffer, returnLength) =>
139
+ advapi.symbols.GetTokenInformation(
140
+ token, informationClass, ptr(buffer), buffer.byteLength, ptr(returnLength),
141
+ ),
142
+ convertSidToStringSid: (sidAddress, output) => advapi.symbols.ConvertSidToStringSidW(
143
+ sidAddress as Pointer, ptr(output),
144
+ ),
145
+ readCodeUnit: (address, offset) => read.u16(address as Pointer, offset),
146
+ localFree: address => { kernel.symbols.LocalFree(address as Pointer); },
147
+ closeHandle: token => { kernel.symbols.CloseHandle(token); },
148
+ };
149
+ nativeLookup = () => readWindowsCurrentSid(api);
150
+ } catch {
151
+ nativeLookup = null;
152
+ }
153
+ return nativeLookup;
154
+ }
155
+
156
+ /** Unsupported FFI keeps the bounded trusted helper; an OS API failure still refuses. */
157
+ export function resolveWindowsCurrentSid(
158
+ powershellLookup: () => string,
159
+ lookup: (() => string) | null = loadNativeLookup(),
160
+ ): string {
161
+ return lookup ? lookup() : powershellLookup();
162
+ }
@@ -313,7 +313,8 @@ export function sweepExpiredComboTargetCooldowns(now = Date.now()): number {
313
313
  return removed;
314
314
  }
315
315
 
316
- export function clearComboTargetCooldowns(comboId?: string): void {
316
+ /** Clear all cooldowns, one combo, or only the supplied target keys within that combo. */
317
+ export function clearComboTargetCooldowns(comboId?: string, targetKeys?: Iterable<string>): void {
317
318
  if (comboId === undefined) {
318
319
  targetCooldowns.clear();
319
320
  liveComboTargets.clear();
@@ -321,6 +322,10 @@ export function clearComboTargetCooldowns(comboId?: string): void {
321
322
  return;
322
323
  }
323
324
  const prefix = `${comboId}\0`;
325
+ if (targetKeys !== undefined) {
326
+ for (const key of targetKeys) targetCooldowns.delete(`${prefix}${key}`);
327
+ return;
328
+ }
324
329
  for (const key of targetCooldowns.keys()) {
325
330
  if (key.startsWith(prefix)) targetCooldowns.delete(key);
326
331
  }
@@ -773,7 +778,13 @@ export function codexAccountModelRefusal(
773
778
  export function comboFailureDecision(
774
779
  status: number,
775
780
  message: string,
776
- options?: { code?: string | null; codexModelRefusal?: CodexAccountModelRefusal; failedAdapter?: string },
781
+ options?: {
782
+ code?: string | null;
783
+ codexModelRefusal?: CodexAccountModelRefusal;
784
+ failedAdapter?: string;
785
+ /** The caller proved the failure is an adapter-normalized plan refusal (`isModelNotInPlanRefusal`). */
786
+ verifiedPlanRefusal?: boolean;
787
+ },
777
788
  ): ComboFailureDecision {
778
789
  if (status === 499) return "stop";
779
790
  if (message.toLowerCase().includes("origin_rejected")) return "stop";
@@ -846,6 +857,10 @@ export function comboFailureDecision(
846
857
  if (["model_not_found", "model_unavailable", "unsupported_model", "unsupported_input_modality"].includes(failureCode)) {
847
858
  return "hop";
848
859
  }
860
+ // So is a plan refusal (#7684): this account's plan excludes THIS model, and it cools only the
861
+ // refused target because `comboFailureCooldownScope` reads a 400 as target-scoped. Unlike the
862
+ // codes above it is honoured only with caller-supplied provenance, never from the code alone.
863
+ if (failureCode === "model_not_in_plan" && options?.verifiedPlanRefusal === true) return "hop";
849
864
  if (modelRefusal === "refusal") return "hop";
850
865
  // `free_rate_limited` no longer routes through `isProviderScopedQuotaCap` (it is a
851
866
  // per-request cap, not provider-wide evidence), so keep its hop verdict explicit here.
@@ -38,6 +38,27 @@ export function isSystemOneEndpoint(baseUrl: string): boolean {
38
38
  */
39
39
  export function jevDecisionEndpointUrl(baseUrl: string): string {
40
40
  const raw = baseUrl.trim();
41
- const stripped = raw.replace(/\/+$/, "");
41
+ let stripped = raw.replace(/\/+$/, "");
42
+ try {
43
+ const parsed = new URL(raw);
44
+ if (parsed.hostname === "ai-gateway.vercel.sh") {
45
+ if (!stripped.endsWith("/decisions")) {
46
+ stripped = stripped.replace(/\/systemone$/, "").replace(/\/+$/, "") + "/decisions";
47
+ }
48
+ return stripped;
49
+ }
50
+ } catch {
51
+ return stripped.endsWith("/systemone") ? stripped : raw;
52
+ }
42
53
  return stripped.endsWith("/systemone") ? stripped : raw;
43
54
  }
55
+
56
+ /** Check if endpoint path targets /decisions or Vercel AI Gateway */
57
+ export function isDecisionsEndpoint(url: string): boolean {
58
+ try {
59
+ const parsed = new URL(url.trim());
60
+ return parsed.hostname === "ai-gateway.vercel.sh";
61
+ } catch {
62
+ return false;
63
+ }
64
+ }
@@ -15,9 +15,10 @@
15
15
  */
16
16
  import {
17
17
  clearDecisionAccountQuotas, invalidateDecisionKeyQuotas, observeDecisionKeyCredential, publishDecisionAccountQuota,
18
- publishDecisionKeyQuota, publishDecisionQuotaRoster, readLoadedDecisionKeyQuota, readLoadedDecisionQuotaPool,
18
+ publishDecisionKeyQuota, publishDecisionQuotaRoster, readLoadedDecisionKeyQuota, readLoadedDecisionQuotaPool, replaceDecisionKeyQuotas,
19
19
  setDecisionAccountUsable, withdrawDecisionQuotaRoster,
20
20
  } from "../providers/quota-decision-snapshot";
21
+ import { captureAntigravityReceipt, observeAntigravityQuotaStore, replaceAntigravityQuotas } from "../providers/quota-decision-antigravity";
21
22
  import { registerDecisionQuotaSink, type DecisionQuotaSink, type MainDecisionRow } from "../lib/decision-quota-sink";
22
23
  import { registerLiveConfigObserver } from "../lib/state-store-registrations";
23
24
  import { getConfigDir } from "../config/paths";
@@ -32,6 +33,7 @@ const POOL_PROVIDERS = ["anthropic", "codex", "codex-main"] as const;
32
33
 
33
34
  /** Project an auth store the owner already read into the secret-free Anthropic roster (primary pool only); a failure withdraws so the pool reads as unknown. The generation is a one-way digest of the credential, never the credential itself. */
34
35
  function publishAuthDecisionQuotaRoster(store: AuthStore): void {
36
+ observeAntigravityQuotaStore(store);
35
37
  try {
36
38
  publishDecisionQuotaRoster("anthropic", (store.anthropic?.accounts ?? []).map(row => ({
37
39
  id: row.id,
@@ -82,6 +84,8 @@ const snapshotSink: DecisionQuotaSink = {
82
84
  mainRosterChanged: row => publishMainRow(row),
83
85
  readKeyQuota: readLoadedDecisionKeyQuota,
84
86
  readPool: readLoadedDecisionQuotaPool,
87
+ captureAntigravityReceipt,
88
+ replaceCollectedQuotas: (keys, oauth) => { replaceDecisionKeyQuotas(keys); replaceAntigravityQuotas(oauth); },
85
89
  };
86
90
 
87
91
  let active: { detach: () => void; root: string } | undefined;
@@ -7,7 +7,7 @@ export function jevQuotaCandidates(options: ResolveJevDecisionOptions): readonly
7
7
  const tiers = normalizeJevQuotaTiers(options.decisionQuotaTiers) ?? JEV_QUOTA_DEFAULT_TIERS;
8
8
  const now = (options.now ?? Date.now)();
9
9
  return options.candidates.map(candidate => ({ ...candidate,
10
- quota: jevQuotaSignalForTarget(options.config, candidate.provider, candidate.model, now, tiers) }));
10
+ quota: candidate.quotaIdentity === null ? { tier: "unknown" as const } : jevQuotaSignalForTarget(options.config, candidate.quotaIdentity?.provider ?? candidate.provider, candidate.quotaIdentity?.model ?? candidate.model, now, tiers) }));
11
11
  }
12
12
  /** Attach the per-tier quota summary to a decision when any candidate carried quota evidence. */
13
13
  export function withJevQuotaSummary(decision: JevDecision, candidates: readonly JevCandidate[]): JevDecision {
@@ -6,6 +6,7 @@ import type { DecisionQuotaWindow } from "../providers/quota-decision-snapshot";
6
6
  import { readLoadedDecisionKeyQuota, readLoadedDecisionQuotaPool } from "../lib/decision-quota-sink";
7
7
  import { isCanonicalOpenAiForwardProvider } from "../providers/openai-tiers-destination";
8
8
  import { providerCodexAccountMode } from "../providers/registry";
9
+ import { isAntigravityArgonIdentity } from "../providers/antigravity-quota-identity";
9
10
  import { NATIVE_RESERVE_MODEL } from "../codex/catalog/native-models";
10
11
  import { isSelectableCodexPoolAccount, MAIN_CODEX_ACCOUNT_ID } from "../codex/account-id";
11
12
  import { JEV_QUOTA_DEFAULT_TIERS, jevQuotaRank, jevQuotaTier, type JevQuotaTier, type ResolvedJevQuotaTiers, type JevQuotaDecisionSummary } from "./jev-quota-config";
@@ -18,11 +19,18 @@ export interface JevQuotaSignal {
18
19
  }
19
20
  /** Build the signal used when evidence is missing, stale or invalid; it ties healthy. */
20
21
  const unknown = (): JevQuotaSignal => ({ tier: "unknown" });
22
+ /** Antigravity quota buckets are metered per model family; Gemini and Claude/3P draw from separate counters. */
23
+ function antigravityFamily(model: string): DecisionQuotaWindow["family"] {
24
+ const id = model.toLowerCase();
25
+ if (isAntigravityArgonIdentity(id)) return undefined;
26
+ return id.startsWith("gemini-") ? "gem" : id.startsWith("claude-") ? "cla" : undefined;
27
+ }
21
28
  /** Reduce decision quota windows to the worst applicable window for a model, ignoring cold, stale, future, invalid or reset-expired rows. */
22
29
  export function jevQuotaSignalFromWindows(windows: readonly DecisionQuotaWindow[] | undefined, model: string, now: number, tiers = JEV_QUOTA_DEFAULT_TIERS): JevQuotaSignal {
23
30
  let worst: DecisionQuotaWindow | undefined;
24
31
  for (const row of windows ?? []) {
25
- if (!["5h", "weekly", "monthly"].includes(row.window) && anthropicModelFamily(model)?.toLowerCase() !== row.window) continue;
32
+ if (row.family !== undefined) { if (row.family !== antigravityFamily(model)) continue; }
33
+ else if (!["5h", "weekly", "monthly"].includes(row.window) && anthropicModelFamily(model)?.toLowerCase() !== row.window) continue;
26
34
  if (!Number.isFinite(now) || now < 0 || !Number.isFinite(row.observedAt) || row.observedAt < 0 || row.observedAt > now
27
35
  || now - row.observedAt > JEV_QUOTA_SIGNAL_MAX_AGE_MS || !Number.isFinite(row.percent) || row.percent < 0 || row.percent > 100
28
36
  || row.resetAt !== undefined && (!Number.isFinite(row.resetAt) || row.resetAt < 0 || row.resetAt <= now)) continue;
@@ -12,6 +12,7 @@ import { providerMatchesRegistryTransport } from "../providers/registry";
12
12
  import type { OcxConfig, OcxProviderConfig } from "../types";
13
13
  import type { JevDecision, ResolveJevDecisionOptions } from "./jev";
14
14
  import {
15
+ isDecisionsEndpoint,
15
16
  isSystemOneEndpoint,
16
17
  jevDecisionEndpointUrl,
17
18
  JEV_DECISION_TIMEOUT_DEFAULT_MS,
@@ -48,6 +49,7 @@ export type JevServiceExchangeOptions = Pick<ResolveJevDecisionOptions,
48
49
  export interface JevDecisionEndpointShape {
49
50
  model: string;
50
51
  descriptiveCriteria: boolean;
52
+ url?: string;
51
53
  }
52
54
 
53
55
  /** The decision deadline: the configured value when in bounds, otherwise the four-second default. */
@@ -208,7 +210,7 @@ export async function exchangeJevDecision<T>(
208
210
  if (endpoint === null) return { gate: "invalid" };
209
211
  if (!endpoint) return { gate: "missing_key" };
210
212
 
211
- const request = prepareRequestBody(prepare, { model: endpoint.model, descriptiveCriteria: endpoint.descriptiveCriteria });
213
+ const request = prepareRequestBody(prepare, { model: endpoint.model, descriptiveCriteria: endpoint.descriptiveCriteria, ...(isDecisionsEndpoint(endpoint.url) ? { url: endpoint.url } : {}) });
212
214
  if (options.signal?.aborted) throw options.signal.reason;
213
215
  if ("gate" in request) return request;
214
216
  const requestBody = request.body;
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Opt-in JEV session pin settings (#7525). Dependency-free so combo validation, the management
3
+ * API and the CLI share one grammar and one range.
4
+ */
5
+
6
+ /** Shortest idle window a pin may be configured with. */
7
+ export const JEV_SESSION_PIN_TTL_MIN_MS = 60_000;
8
+ /** Longest idle window a pin may be configured with (one day). */
9
+ export const JEV_SESSION_PIN_TTL_MAX_MS = 86_400_000;
10
+
11
+ export interface JevSessionPinConfig {
12
+ /** Idle window after the last successful pinned turn; a quieter session is decided afresh. */
13
+ ttlMs: number;
14
+ }
15
+
16
+ /**
17
+ * Closed persisted vocabulary: `session` marks a turn that reused its pin; every other value names
18
+ * why an existing pin was released before a fresh decision.
19
+ */
20
+ export const JEV_SESSION_PIN_REASONS = [
21
+ "session",
22
+ "expired",
23
+ "config_changed",
24
+ "target_unavailable",
25
+ "effort_unavailable",
26
+ "quota_nearly_exhausted",
27
+ ] as const;
28
+ export type JevSessionPinReason = (typeof JEV_SESSION_PIN_REASONS)[number];
29
+ export type JevSessionPinRelease = Exclude<JevSessionPinReason, "session">;
30
+
31
+ /** The canonical pin setting, or undefined for anything that is not exactly `{ ttlMs }` in range. */
32
+ export function normalizeJevSessionPin(value: unknown): JevSessionPinConfig | undefined {
33
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
34
+ const keys = Object.keys(value);
35
+ if (keys.length !== 1 || keys[0] !== "ttlMs") return undefined;
36
+ const ttlMs = (value as { ttlMs?: unknown }).ttlMs;
37
+ return typeof ttlMs === "number" && Number.isSafeInteger(ttlMs)
38
+ && ttlMs >= JEV_SESSION_PIN_TTL_MIN_MS && ttlMs <= JEV_SESSION_PIN_TTL_MAX_MS
39
+ ? { ttlMs }
40
+ : undefined;
41
+ }
42
+
43
+ const DURATION_UNITS_MS: Readonly<Record<string, number>> = { ms: 1, s: 1_000, m: 60_000, h: 3_600_000 };
44
+
45
+ /** Parse `90s`, `20m`, `1h` or bare milliseconds into an in-range TTL, else undefined. */
46
+ export function parseJevSessionPinDuration(raw: string): number | undefined {
47
+ const match = /^(\d{1,9})(ms|s|m|h)?$/.exec(raw.trim());
48
+ if (!match) return undefined;
49
+ const ttlMs = Number(match[1]) * DURATION_UNITS_MS[match[2] ?? "ms"]!;
50
+ return ttlMs >= JEV_SESSION_PIN_TTL_MIN_MS && ttlMs <= JEV_SESSION_PIN_TTL_MAX_MS ? ttlMs : undefined;
51
+ }
package/src/combos/jev.ts CHANGED
@@ -8,6 +8,7 @@ import {
8
8
  JEV_MAX_CANDIDATE_FIELD_CHARS,
9
9
  } from "./types";
10
10
 
11
+ import { isDecisionsEndpoint } from "./jev-decision-contract";
11
12
  import {
12
13
  exchangeJevDecision,
13
14
  JEV_PROVIDER_ID,
@@ -25,6 +26,8 @@ export const JEV_MAX_CANDIDATES = 64;
25
26
  /** Ollama's System One choice questions accept 2..26 options; other services share the floor. */
26
27
  const SELF_HOSTED_MIN_OPTIONS = 2;
27
28
  const SELF_HOSTED_MAX_OPTIONS = 26;
29
+ const DECISIONS_MIN_OPTIONS = 2;
30
+ const DECISIONS_MAX_OPTIONS = 255;
28
31
 
29
32
  const TASK_CHARS = 500;
30
33
  const TASK_HEAD_CHARS = 320;
@@ -80,6 +83,8 @@ export interface JevCandidate {
80
83
  /** Optional operator note sent as decision evidence for this target only. */
81
84
  modelProfile?: string;
82
85
  quota?: JevQuotaSignal;
86
+ /** Internal native identity from ordinary routing; never replaces the configured allowlist. */
87
+ quotaIdentity?: { provider: string; model: string } | null;
83
88
  }
84
89
 
85
90
  /**
@@ -107,6 +112,10 @@ export interface JevDecision {
107
112
  confidence?: number;
108
113
  chosenProbability?: number;
109
114
  usage?: Record<string, number>;
115
+ /** Set when an opt-in session pin (#7525) supplied this decision without asking the backend. */
116
+ pinned?: true;
117
+ /** `session` with `pinned`; otherwise why an existing session pin was released first. */
118
+ pinReason?: import("./jev-session-pin-config").JevSessionPinReason;
110
119
  }
111
120
 
112
121
  export interface ResolveJevDecisionOptions {
@@ -564,19 +573,46 @@ export function parseJevDecision(
564
573
  payload: unknown,
565
574
  candidates: readonly JevCandidate[],
566
575
  ): Pick<JevDecision, "targetKey" | "effort" | "confidence" | "chosenProbability" | "usage"> {
567
- if (!isRecord(payload) || !isRecord(payload.answers) || !isRecord(payload.answers.route)) {
576
+ if (!isRecord(payload)) {
577
+ throw new Error("missing JEV route decision");
578
+ }
579
+ let answer: Record<string, unknown> | undefined;
580
+ if (isRecord(payload.answers) && isRecord(payload.answers.route)) {
581
+ answer = payload.answers.route as Record<string, unknown>;
582
+ } else if (Array.isArray(payload.answers)) {
583
+ const routeAnswers = payload.answers.filter((a): a is Record<string, unknown> => isRecord(a) && a.name === "route");
584
+ if (routeAnswers.length === 1) {
585
+ answer = routeAnswers[0];
586
+ } else if (routeAnswers.length > 1) {
587
+ throw new Error("duplicate JEV route decision");
588
+ }
589
+ }
590
+ if (!answer) {
568
591
  throw new Error("missing JEV route decision");
569
592
  }
570
- const answer = payload.answers.route;
571
593
  const options = candidateOptions(candidates);
572
- if (typeof answer.choice !== "string" || !options.has(answer.choice)) {
594
+ const choiceValue = typeof answer.choice === "string" ? answer.choice : (typeof answer.value === "string" ? answer.value : undefined);
595
+ if (!choiceValue || !options.has(choiceValue)) {
573
596
  throw new Error("unknown JEV route choice");
574
597
  }
575
598
 
576
599
  let chosenProbability: number | undefined;
577
600
  if (answer.probabilities !== undefined) {
578
- const probabilities = answer.probabilities;
579
- if (!isRecord(probabilities)) throw new Error("invalid JEV route probabilities");
601
+ let probabilities: Record<string, unknown>;
602
+ if (Array.isArray(answer.probabilities)) {
603
+ probabilities = {};
604
+ for (const item of answer.probabilities) {
605
+ if (!isRecord(item)) throw new Error("invalid JEV route probabilities");
606
+ const k = typeof item.choice === "string" ? item.choice : (typeof item.value === "string" ? item.value : undefined);
607
+ if (!k) throw new Error("invalid JEV route probabilities");
608
+ if (Object.hasOwn(probabilities, k)) throw new Error("invalid JEV route probabilities");
609
+ probabilities[k] = item.probability;
610
+ }
611
+ } else if (isRecord(answer.probabilities)) {
612
+ probabilities = answer.probabilities as Record<string, unknown>;
613
+ } else {
614
+ throw new Error("invalid JEV route probabilities");
615
+ }
580
616
  const expected = [...options.keys()].sort();
581
617
  const actual = Object.keys(probabilities).sort();
582
618
  if (expected.length !== actual.length || expected.some((key, index) => key !== actual[index])) {
@@ -587,7 +623,7 @@ export function parseJevDecision(
587
623
  throw new Error("invalid JEV route probabilities");
588
624
  }
589
625
  const numeric = values as number[];
590
- const selected = probabilities[answer.choice] as number;
626
+ const selected = probabilities[choiceValue] as number;
591
627
  if (Math.abs(numeric.reduce((sum, value) => sum + value, 0) - 1) > 0.02
592
628
  || selected < Math.max(...numeric) - 1e-6) {
593
629
  throw new Error("inconsistent JEV route distribution");
@@ -595,7 +631,7 @@ export function parseJevDecision(
595
631
  chosenProbability = selected;
596
632
  }
597
633
 
598
- const option = options.get(answer.choice)!;
634
+ const option = options.get(choiceValue)!;
599
635
  const confidence = typeof answer.confidence === "number"
600
636
  && Number.isFinite(answer.confidence)
601
637
  && answer.confidence >= 0
@@ -628,6 +664,31 @@ export function fallbackDecision(
628
664
  * Every operational or response failure returns the supplied first-eligible fallback. A caller
629
665
  * abort is the exception: request cancellation remains cancellation and is rethrown by identity.
630
666
  */
667
+ function formatDecisionsInput(state: Record<string, unknown>): string {
668
+ const parts: string[] = [];
669
+ if (typeof state.task === "string" && state.task.trim()) {
670
+ parts.push(`Task: ${state.task.trim()}`);
671
+ }
672
+ if (isRecord(state.signals)) {
673
+ const sigs: string[] = [];
674
+ if (state.signals.has_image === true) sigs.push("has_image");
675
+ if (state.signals.tool_history === true) sigs.push("tool_history");
676
+ if (sigs.length > 0) parts.push(`Signals: ${sigs.join(", ")}`);
677
+ }
678
+ if (typeof state.previous_assistant === "string" && state.previous_assistant.trim()) {
679
+ parts.push(`Recent Assistant: ${state.previous_assistant.trim()}`);
680
+ }
681
+ if (isRecord(state.step) && state.step.type === "tool_step") {
682
+ const step = state.step;
683
+ const toolName = isRecord(step.tool_call) && typeof step.tool_call.name === "string" ? step.tool_call.name : "";
684
+ const toolOutput = typeof step.last_tool_output_tail === "string" ? step.last_tool_output_tail : "";
685
+ if (toolName || toolOutput) {
686
+ parts.push(`Recent Tool Call: ${toolName}\nTool Output: ${toolOutput}`.trim());
687
+ }
688
+ }
689
+ return parts.length > 0 ? parts.join("\n\n") : JSON.stringify(state);
690
+ }
691
+
631
692
  export async function resolveJevDecision(options: ResolveJevDecisionOptions): Promise<JevDecision> {
632
693
  const now = options.now ?? Date.now;
633
694
  const startedAt = now();
@@ -641,15 +702,46 @@ export async function resolveJevDecision(options: ResolveJevDecisionOptions): Pr
641
702
 
642
703
  let candidates = options.candidates;
643
704
  const exchanged = await exchangeJevDecision(options, (endpoint) => {
644
- if (endpoint.descriptiveCriteria) {
705
+ const isDecisions = Boolean(endpoint.url && isDecisionsEndpoint(endpoint.url));
706
+ const optionCount = candidateOptions(options.candidates).size;
707
+ if (isDecisions) {
708
+ if (optionCount < DECISIONS_MIN_OPTIONS) return "no_choices";
709
+ if (optionCount > DECISIONS_MAX_OPTIONS) return "invalid";
710
+ } else if (endpoint.descriptiveCriteria) {
645
711
  // Self-hosted choice questions accept 2..26 options; decide locally instead of spending a
646
712
  // round-trip on a request the service will refuse.
647
- const optionCount = candidateOptions(options.candidates).size;
648
713
  if (optionCount < SELF_HOSTED_MIN_OPTIONS) return "no_choices";
649
714
  if (optionCount > SELF_HOSTED_MAX_OPTIONS) return "invalid";
650
715
  }
651
716
  const state = buildJevState(options.body, options.candidates);
652
717
  if (!hasJevDecisionState(state)) return "no_state";
718
+ if (isDecisions && endpoint.url) {
719
+ const payload = boundedJevQuotaPayload(jevQuotaCandidates(options), rows => {
720
+ const routeOptions = candidateOptions(rows);
721
+ return JSON.stringify({
722
+ model: endpoint.model,
723
+ input: formatDecisionsInput(state),
724
+ questions: [
725
+ {
726
+ name: "route",
727
+ type: "choice",
728
+ instructions: "Which target AND reasoning effort together best fit the next model call? Select sufficient capability and reasoning for a correct next step while avoiding unnecessary resource use.",
729
+ choices: [...routeOptions.entries()].map(([choice, opt]) => {
730
+ const cand = rows.find(r => r.key === opt.targetKey);
731
+ const desc = criterionDescription(opt.criterion, cand?.quota);
732
+ const note = cand?.modelProfile?.trim();
733
+ return {
734
+ value: choice,
735
+ description: note ? `${desc} (${note})` : desc,
736
+ };
737
+ }),
738
+ },
739
+ ],
740
+ });
741
+ }, REQUEST_LIMIT);
742
+ candidates = payload.candidates;
743
+ return { body: payload.body };
744
+ }
653
745
  const payload = boundedJevQuotaPayload(jevQuotaCandidates(options), rows => JSON.stringify({
654
746
  model: endpoint.model, state,
655
747
  questions: buildJevRouteQuestion(rows, { descriptiveCriteria: endpoint.descriptiveCriteria }),