@bitkyc08/opencodex 2.96.0 → 2.98.0-preview.20261107

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 (465) hide show
  1. package/bin/ocx.mjs +215 -20
  2. package/gui/dist/assets/App-6TFtZsUF.css +1 -0
  3. package/gui/dist/assets/App-B8_sOxoz.js +59 -0
  4. package/gui/dist/assets/Tray-DpWEp6ee.js +1 -0
  5. package/gui/dist/assets/WantedSansVariable.split.0-Dwvb1WRx.woff2 +0 -0
  6. package/gui/dist/assets/WantedSansVariable.split.1-1wKD2RxI.woff2 +0 -0
  7. package/gui/dist/assets/WantedSansVariable.split.10-CAKA6LIP.woff2 +0 -0
  8. package/gui/dist/assets/WantedSansVariable.split.11-k5H85R4b.woff2 +0 -0
  9. package/gui/dist/assets/WantedSansVariable.split.12-BHboLsUv.woff2 +0 -0
  10. package/gui/dist/assets/WantedSansVariable.split.13-9GV377ix.woff2 +0 -0
  11. package/gui/dist/assets/WantedSansVariable.split.14-DovDXnrj.woff2 +0 -0
  12. package/gui/dist/assets/WantedSansVariable.split.15-DTdykCig.woff2 +0 -0
  13. package/gui/dist/assets/WantedSansVariable.split.16-CKz2ccgK.woff2 +0 -0
  14. package/gui/dist/assets/WantedSansVariable.split.17-Z2RD_KRZ.woff2 +0 -0
  15. package/gui/dist/assets/WantedSansVariable.split.18-BcKtfonJ.woff2 +0 -0
  16. package/gui/dist/assets/WantedSansVariable.split.19-DEQPOSZn.woff2 +0 -0
  17. package/gui/dist/assets/WantedSansVariable.split.2-DryboyuA.woff2 +0 -0
  18. package/gui/dist/assets/WantedSansVariable.split.20-Bia5JMls.woff2 +0 -0
  19. package/gui/dist/assets/WantedSansVariable.split.21-Cr4jFw-E.woff2 +0 -0
  20. package/gui/dist/assets/WantedSansVariable.split.22-DjjB69TZ.woff2 +0 -0
  21. package/gui/dist/assets/WantedSansVariable.split.23-CvUzJskt.woff2 +0 -0
  22. package/gui/dist/assets/WantedSansVariable.split.24-i_eMg5ox.woff2 +0 -0
  23. package/gui/dist/assets/WantedSansVariable.split.25-2aKHwPX-.woff2 +0 -0
  24. package/gui/dist/assets/WantedSansVariable.split.26-B6wXoCEL.woff2 +0 -0
  25. package/gui/dist/assets/WantedSansVariable.split.27-D4h1WfGM.woff2 +0 -0
  26. package/gui/dist/assets/WantedSansVariable.split.28-kvRPCStd.woff2 +0 -0
  27. package/gui/dist/assets/WantedSansVariable.split.29-DHAiwleD.woff2 +0 -0
  28. package/gui/dist/assets/WantedSansVariable.split.3-7H--eyZi.woff2 +0 -0
  29. package/gui/dist/assets/WantedSansVariable.split.30-C66cfAY2.woff2 +0 -0
  30. package/gui/dist/assets/WantedSansVariable.split.31-FDmtiNim.woff2 +0 -0
  31. package/gui/dist/assets/WantedSansVariable.split.32-DouHt2Dd.woff2 +0 -0
  32. package/gui/dist/assets/WantedSansVariable.split.33-B8HVvkJX.woff2 +0 -0
  33. package/gui/dist/assets/WantedSansVariable.split.34-BtkRu1FN.woff2 +0 -0
  34. package/gui/dist/assets/WantedSansVariable.split.35-DBylQbtk.woff2 +0 -0
  35. package/gui/dist/assets/WantedSansVariable.split.36-Sg089Kgh.woff2 +0 -0
  36. package/gui/dist/assets/WantedSansVariable.split.37-CYtvbriS.woff2 +0 -0
  37. package/gui/dist/assets/WantedSansVariable.split.38-DKkSLf8Z.woff2 +0 -0
  38. package/gui/dist/assets/WantedSansVariable.split.39-CecotKZD.woff2 +0 -0
  39. package/gui/dist/assets/WantedSansVariable.split.4-Bv8O3ZMb.woff2 +0 -0
  40. package/gui/dist/assets/WantedSansVariable.split.40-DdCvkmOU.woff2 +0 -0
  41. package/gui/dist/assets/WantedSansVariable.split.41-ESn674Hc.woff2 +0 -0
  42. package/gui/dist/assets/WantedSansVariable.split.42-DL9V7NNV.woff2 +0 -0
  43. package/gui/dist/assets/WantedSansVariable.split.43-yipO0cyk.woff2 +0 -0
  44. package/gui/dist/assets/WantedSansVariable.split.44-6rTmLZhm.woff2 +0 -0
  45. package/gui/dist/assets/WantedSansVariable.split.45-BJAj8lrm.woff2 +0 -0
  46. package/gui/dist/assets/WantedSansVariable.split.46-BDTzMn2c.woff2 +0 -0
  47. package/gui/dist/assets/WantedSansVariable.split.47-Bxd4wGgi.woff2 +0 -0
  48. package/gui/dist/assets/WantedSansVariable.split.48-DxnFBLnH.woff2 +0 -0
  49. package/gui/dist/assets/WantedSansVariable.split.49-DnVD0aOD.woff2 +0 -0
  50. package/gui/dist/assets/WantedSansVariable.split.5-B1wI2pp5.woff2 +0 -0
  51. package/gui/dist/assets/WantedSansVariable.split.50-D9JlkZd6.woff2 +0 -0
  52. package/gui/dist/assets/WantedSansVariable.split.51-D9Vw6Bu3.woff2 +0 -0
  53. package/gui/dist/assets/WantedSansVariable.split.52-ClEJk4kn.woff2 +0 -0
  54. package/gui/dist/assets/WantedSansVariable.split.53-BSXU0vh-.woff2 +0 -0
  55. package/gui/dist/assets/WantedSansVariable.split.54-EcuxkR9v.woff2 +0 -0
  56. package/gui/dist/assets/WantedSansVariable.split.55-CYiFhQX8.woff2 +0 -0
  57. package/gui/dist/assets/WantedSansVariable.split.56--Gk9g8BK.woff2 +0 -0
  58. package/gui/dist/assets/WantedSansVariable.split.57-DnkOPZcy.woff2 +0 -0
  59. package/gui/dist/assets/WantedSansVariable.split.58-9MB8504z.woff2 +0 -0
  60. package/gui/dist/assets/WantedSansVariable.split.59-ByxIsN72.woff2 +0 -0
  61. package/gui/dist/assets/WantedSansVariable.split.6-Bmk0dRVw.woff2 +0 -0
  62. package/gui/dist/assets/WantedSansVariable.split.60-Bxwx_aWQ.woff2 +0 -0
  63. package/gui/dist/assets/WantedSansVariable.split.61-DA2z5sm7.woff2 +0 -0
  64. package/gui/dist/assets/WantedSansVariable.split.62-C5iJPJZn.woff2 +0 -0
  65. package/gui/dist/assets/WantedSansVariable.split.63-DAqrmaEc.woff2 +0 -0
  66. package/gui/dist/assets/WantedSansVariable.split.64-BgXFsljb.woff2 +0 -0
  67. package/gui/dist/assets/WantedSansVariable.split.65-DKiWujvu.woff2 +0 -0
  68. package/gui/dist/assets/WantedSansVariable.split.66-8po4vUZ4.woff2 +0 -0
  69. package/gui/dist/assets/WantedSansVariable.split.67-Cy5qyI9O.woff2 +0 -0
  70. package/gui/dist/assets/WantedSansVariable.split.68-BKny7Fy3.woff2 +0 -0
  71. package/gui/dist/assets/WantedSansVariable.split.69-B4VU4u_b.woff2 +0 -0
  72. package/gui/dist/assets/WantedSansVariable.split.7-BuqwNpgA.woff2 +0 -0
  73. package/gui/dist/assets/WantedSansVariable.split.70-BCd4n346.woff2 +0 -0
  74. package/gui/dist/assets/WantedSansVariable.split.71-CkQppaWn.woff2 +0 -0
  75. package/gui/dist/assets/WantedSansVariable.split.72-Db7vaoFs.woff2 +0 -0
  76. package/gui/dist/assets/WantedSansVariable.split.73-DI80TYWl.woff2 +0 -0
  77. package/gui/dist/assets/WantedSansVariable.split.74-tMCtDAHB.woff2 +0 -0
  78. package/gui/dist/assets/WantedSansVariable.split.75-Ciw0D5WG.woff2 +0 -0
  79. package/gui/dist/assets/WantedSansVariable.split.76-DoLjFgp-.woff2 +0 -0
  80. package/gui/dist/assets/WantedSansVariable.split.77-CpT2uvMy.woff2 +0 -0
  81. package/gui/dist/assets/WantedSansVariable.split.78-CkcJ4iZ1.woff2 +0 -0
  82. package/gui/dist/assets/WantedSansVariable.split.79-DsOUJjEM.woff2 +0 -0
  83. package/gui/dist/assets/WantedSansVariable.split.8-DsjypPd6.woff2 +0 -0
  84. package/gui/dist/assets/WantedSansVariable.split.80-C0VwHTte.woff2 +0 -0
  85. package/gui/dist/assets/WantedSansVariable.split.81-DTelu57i.woff2 +0 -0
  86. package/gui/dist/assets/WantedSansVariable.split.82-BiMndGN1.woff2 +0 -0
  87. package/gui/dist/assets/WantedSansVariable.split.83-CVcC6eDG.woff2 +0 -0
  88. package/gui/dist/assets/WantedSansVariable.split.84-DlhZVt_O.woff2 +0 -0
  89. package/gui/dist/assets/WantedSansVariable.split.85-S8I2D3pA.woff2 +0 -0
  90. package/gui/dist/assets/WantedSansVariable.split.86-DozXXpH5.woff2 +0 -0
  91. package/gui/dist/assets/WantedSansVariable.split.87-Dsn0Vuuo.woff2 +0 -0
  92. package/gui/dist/assets/WantedSansVariable.split.88-iNwxxDCr.woff2 +0 -0
  93. package/gui/dist/assets/WantedSansVariable.split.89-B63u_9CZ.woff2 +0 -0
  94. package/gui/dist/assets/WantedSansVariable.split.9-Bi3IzpMI.woff2 +0 -0
  95. package/gui/dist/assets/WantedSansVariable.split.90-ByeH1Pqf.woff2 +0 -0
  96. package/gui/dist/assets/WantedSansVariable.split.91-UQLlagpm.woff2 +0 -0
  97. package/gui/dist/assets/brand-mark-VPhzz-WE.js +1 -0
  98. package/gui/dist/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
  99. package/gui/dist/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
  100. package/gui/dist/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
  101. package/gui/dist/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
  102. package/gui/dist/assets/geist-mono-cyrillic-ext-wght-normal-X_5orZeX.woff2 +0 -0
  103. package/gui/dist/assets/geist-mono-cyrillic-wght-normal-DiZS0aHC.woff2 +0 -0
  104. package/gui/dist/assets/geist-mono-latin-ext-wght-normal-Bwz-egvJ.woff2 +0 -0
  105. package/gui/dist/assets/geist-mono-latin-wght-normal-XN7g48iV.woff2 +0 -0
  106. package/gui/dist/assets/geist-mono-symbols2-wght-normal-CO5SzqOn.woff2 +0 -0
  107. package/gui/dist/assets/geist-mono-vietnamese-wght-normal-DadHysG0.woff2 +0 -0
  108. package/gui/dist/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
  109. package/gui/dist/assets/index-5REODpG3.css +2 -0
  110. package/gui/dist/assets/index-BWKBeK77.js +94 -0
  111. package/gui/dist/assets/segment-thumb-features-BQYzrze9.js +1 -0
  112. package/gui/dist/classic/assets/App-Bz65x1J6.js +58 -0
  113. package/gui/dist/{assets/Tray-BOPQyDbH.js → classic/assets/Tray-kk7mdO6I.js} +1 -1
  114. package/gui/dist/classic/assets/index-Dp2j8bSc.js +94 -0
  115. package/gui/dist/classic/assets/quota-summary-CvamtHjB.js +1 -0
  116. package/gui/dist/classic/index.html +47 -0
  117. package/gui/dist/favicon.png +0 -0
  118. package/gui/dist/favicon.svg +14 -0
  119. package/gui/dist/index.html +15 -2
  120. package/package.json +1 -1
  121. package/src/adapters/anthropic.ts +17 -8
  122. package/src/adapters/command-code.ts +15 -16
  123. package/src/adapters/cursor/transport-retry.ts +2 -2
  124. package/src/adapters/devin/cloud-direct/chat.ts +15 -6
  125. package/src/adapters/google.ts +7 -7
  126. package/src/adapters/kiro/adapter.ts +18 -3
  127. package/src/adapters/kiro/conversation.ts +8 -8
  128. package/src/adapters/kiro/payload.ts +45 -12
  129. package/src/adapters/kiro/stream.ts +230 -14
  130. package/src/adapters/kiro/structured-output-json.ts +191 -0
  131. package/src/adapters/kiro/structured-output-schema.ts +542 -0
  132. package/src/adapters/kiro/structured-output.ts +367 -0
  133. package/src/adapters/kiro-constants.ts +24 -1
  134. package/src/adapters/kiro-events.ts +31 -1
  135. package/src/adapters/kiro-retry.ts +3 -3
  136. package/src/adapters/kiro-tools.ts +14 -9
  137. package/src/adapters/kiro-wire.ts +9 -5
  138. package/src/adapters/ollama-native.ts +11 -1
  139. package/src/adapters/openai-chat/messages.ts +58 -5
  140. package/src/adapters/openai-chat/mistral-image-limit.ts +50 -0
  141. package/src/adapters/openai-chat/passthrough.ts +5 -3
  142. package/src/adapters/openai-chat/tool-schema.ts +83 -13
  143. package/src/adapters/openai-responses/empty-assistant.ts +15 -3
  144. package/src/adapters/openai-responses/opengateway-input.ts +18 -6
  145. package/src/adapters/openai-responses/passthrough.ts +5 -4
  146. package/src/adapters/openai-responses/reasoning.ts +9 -4
  147. package/src/adapters/openai-responses/request-strips.ts +1 -1
  148. package/src/adapters/openai-responses/tool-output-recovery.ts +79 -0
  149. package/src/adapters/physical-send.ts +3 -3
  150. package/src/adapters/qoder/live-models.ts +115 -1
  151. package/src/adapters/zed-openai-stream.ts +2 -1
  152. package/src/bridge/errors.ts +11 -2
  153. package/src/bridge/response-json.ts +2 -1
  154. package/src/bridge/sse.ts +14 -6
  155. package/src/chat/failure-verdict.ts +21 -0
  156. package/src/chat/outbound.ts +139 -21
  157. package/src/claude/failure-verdict.ts +21 -0
  158. package/src/claude/inbound-content-options.ts +15 -2
  159. package/src/claude/inbound-model-options.ts +2 -1
  160. package/src/claude/inbound-records.ts +2 -0
  161. package/src/claude/inbound.ts +17 -11
  162. package/src/claude/outbound.ts +98 -22
  163. package/src/cli/capabilities-access-remote.ts +13 -0
  164. package/src/cli/capabilities-base.ts +26 -3
  165. package/src/cli/capabilities-command.ts +12 -3
  166. package/src/cli/capabilities-provider-models.ts +3 -3
  167. package/src/cli/capability-contracts.ts +2 -0
  168. package/src/cli/codex-launch-auth.ts +30 -1
  169. package/src/cli/codex-launcher.ts +12 -5
  170. package/src/cli/codex-shim-autorestore.ts +12 -4
  171. package/src/cli/config-command.ts +11 -2
  172. package/src/cli/connect.ts +17 -2
  173. package/src/cli/dispatch.ts +14 -177
  174. package/src/cli/doctor.ts +95 -7
  175. package/src/cli/help.ts +2 -2
  176. package/src/cli/index.ts +17 -8
  177. package/src/cli/link-apply-restart.ts +9 -2
  178. package/src/cli/link.ts +1 -1
  179. package/src/cli/models.ts +124 -38
  180. package/src/cli/registry.ts +12 -4
  181. package/src/cli/restart-failure.ts +17 -0
  182. package/src/cli/root.ts +8 -0
  183. package/src/cli/stop-approval.ts +2 -2
  184. package/src/cli/sync-command.ts +243 -0
  185. package/src/cli/sync-fanout-process.ts +92 -0
  186. package/src/cli/sync-fanout.ts +161 -0
  187. package/src/cli/sync-flags.ts +10 -0
  188. package/src/cli/sync-link-status.ts +39 -0
  189. package/src/cli/sync-update-guard.ts +18 -0
  190. package/src/cli/system-restart-client.ts +5 -0
  191. package/src/cli/uninstall-client-state.ts +12 -1
  192. package/src/cli/update-restart-child.ts +13 -3
  193. package/src/cli/update-restart-home.ts +6 -3
  194. package/src/cli/update-restart.ts +36 -19
  195. package/src/client/connect.ts +35 -15
  196. package/src/client/hub-client.ts +5 -0
  197. package/src/client/link-home.ts +3 -2
  198. package/src/client/link-management-relay.ts +39 -2
  199. package/src/client/link-readiness.ts +3 -1
  200. package/src/client/machine-api.ts +2 -1
  201. package/src/client/machine-listener.ts +10 -0
  202. package/src/client/orphan-token-recovery.ts +322 -0
  203. package/src/client/restore-ownership.ts +19 -1
  204. package/src/client/runtime-restart.ts +12 -4
  205. package/src/client/runtime.ts +40 -11
  206. package/src/client/stop-routing.ts +62 -0
  207. package/src/client/sync-runtime.ts +65 -0
  208. package/src/clients/config-export.ts +32 -3
  209. package/src/codex/auth-context.ts +49 -103
  210. package/src/codex/catalog/antigravity-discovery.ts +16 -5
  211. package/src/codex/catalog/provider-models.ts +18 -12
  212. package/src/codex/forward-transport-headers.ts +35 -6
  213. package/src/codex/inject/config-toml.ts +88 -0
  214. package/src/codex/inject/multi-agent-v2.ts +30 -4
  215. package/src/codex/inject/plan.ts +34 -7
  216. package/src/codex/inject-coordination.ts +11 -0
  217. package/src/codex/inject.ts +18 -7
  218. package/src/codex/lineage.ts +13 -7
  219. package/src/codex/native-profile-api.ts +27 -1
  220. package/src/codex/quota.ts +22 -6
  221. package/src/codex/request-owned-affinity-key.ts +11 -0
  222. package/src/codex/request-owned-affinity.ts +118 -0
  223. package/src/codex/request-owned-main-pin.ts +86 -0
  224. package/src/codex/role-capability.ts +52 -41
  225. package/src/codex/routing/active-account.ts +13 -5
  226. package/src/codex/routing/selection.ts +40 -1
  227. package/src/codex/routing/thread-affinity-store.ts +916 -0
  228. package/src/codex/routing/thread-affinity.ts +90 -12
  229. package/src/codex/shim-diagnostics.ts +7 -0
  230. package/src/codex/shim-legacy-record.ts +290 -0
  231. package/src/codex/shim-windows-refresh.ts +9 -2
  232. package/src/codex/shim-wrapper-write.ts +7 -0
  233. package/src/codex/shim.ts +80 -21
  234. package/src/codex/toml-source-lines.ts +72 -13
  235. package/src/combos/failover.ts +6 -109
  236. package/src/combos/request.ts +2 -2
  237. package/src/combos/resolve.ts +29 -11
  238. package/src/config/diagnostics.ts +9 -9
  239. package/src/config/load-degrade.ts +27 -27
  240. package/src/config/process-state.ts +5 -0
  241. package/src/config/provider-validation.ts +9 -2
  242. package/src/config/removed-opencode-free-backup.ts +6 -3
  243. package/src/config/schema/leaf-validators.ts +1 -0
  244. package/src/config/tracked-runtime-inspection.ts +3 -3
  245. package/src/generated/compatibility-version.json +595 -255
  246. package/src/images/loop.ts +4 -3
  247. package/src/lib/client-error-body.ts +215 -0
  248. package/src/lib/client-retry-after.ts +66 -0
  249. package/src/lib/config-ownership-removal.ts +422 -0
  250. package/src/lib/config-ownership.ts +650 -81
  251. package/src/lib/context-overflow-verdict.ts +113 -0
  252. package/src/lib/crash-guard.ts +4 -2
  253. package/src/lib/desktop-cli-handoff.d.mts +4 -5
  254. package/src/lib/desktop-cli-handoff.mjs +18 -17
  255. package/src/lib/empty-tool-catalog.ts +25 -3
  256. package/src/lib/error-destination.ts +47 -0
  257. package/src/lib/errors.ts +1 -0
  258. package/src/lib/failure-detail.ts +66 -0
  259. package/src/lib/local-management-capability.ts +3 -1
  260. package/src/lib/messages-error-body.ts +162 -0
  261. package/src/lib/messages-sse-error-presentation.ts +93 -0
  262. package/src/lib/model-identity.ts +44 -0
  263. package/src/lib/passive-read.ts +9 -4
  264. package/src/lib/private-sqlite-path.ts +124 -0
  265. package/src/lib/response-service-tier.ts +17 -0
  266. package/src/lib/retry-after.ts +3 -0
  267. package/src/lib/socks5-fetch.ts +21 -9
  268. package/src/lib/spend-ledger-owner.ts +43 -4
  269. package/src/lib/upstream-condition.ts +142 -0
  270. package/src/lib/upstream-retry.ts +95 -12
  271. package/src/lib/windows-owner-acl.ts +22 -9
  272. package/src/lib/winsw.ts +5 -5
  273. package/src/lib/workflow-budget.ts +3 -1
  274. package/src/link/remote-platform.ts +14 -0
  275. package/src/link/remote-windows.ts +51 -9
  276. package/src/link/ssh-argv.ts +63 -10
  277. package/src/oauth/generic-account-failover.ts +13 -11
  278. package/src/oauth/index.ts +42 -73
  279. package/src/oauth/oauth-errors.ts +67 -0
  280. package/src/oauth/store.ts +21 -11
  281. package/src/protocols/codecs/messages-ir.ts +15 -9
  282. package/src/protocols/codecs/ollama.ts +197 -0
  283. package/src/protocols/encoders/adapter-events.ts +30 -7
  284. package/src/protocols/encoders/chat.ts +18 -10
  285. package/src/protocols/encoders/messages.ts +72 -28
  286. package/src/protocols/trace.ts +18 -0
  287. package/src/providers/antigravity-models.ts +45 -12
  288. package/src/providers/fastwire.ts +3 -2
  289. package/src/providers/free-directory.ts +2 -2
  290. package/src/providers/quota/anthropic-usage-windows.ts +13 -3
  291. package/src/providers/quota/vendor-probes-key.ts +60 -24
  292. package/src/providers/reasoning-metadata.ts +2 -1
  293. package/src/providers/registry/entries-extended.ts +9 -0
  294. package/src/providers/request-pacing.ts +3 -2
  295. package/src/reasoning-effort.ts +7 -2
  296. package/src/remote/hub-usage.ts +3 -0
  297. package/src/responses/apply-patch-envelope.ts +45 -19
  298. package/src/responses/compaction-history-framing.ts +5 -1
  299. package/src/responses/freeform-wrapper-scan.ts +5 -3
  300. package/src/responses/progressive-freeform-input.ts +354 -45
  301. package/src/routing/fallback-policy.ts +3 -1
  302. package/src/server/admission-model-scope.ts +17 -6
  303. package/src/server/admitted-http-turn.ts +57 -0
  304. package/src/server/anthropic-rate-limit-headers.ts +75 -3
  305. package/src/server/auth-cors.ts +5 -0
  306. package/src/server/chat-completions.ts +45 -20
  307. package/src/server/chat-native-sse.ts +52 -7
  308. package/src/server/chat-native.ts +60 -35
  309. package/src/server/claude-bridge-pool-session.ts +59 -0
  310. package/src/server/claude-messages.ts +174 -84
  311. package/src/server/context-history.ts +5 -1
  312. package/src/server/gui-static.ts +4 -1
  313. package/src/server/hub-usage.ts +7 -2
  314. package/src/server/inbound-body-admission.ts +11 -4
  315. package/src/server/index/link-management.ts +8 -0
  316. package/src/server/index/ollama-routes.ts +91 -0
  317. package/src/server/index/serve-options.ts +44 -24
  318. package/src/server/index/startup-warnings.ts +5 -12
  319. package/src/server/index/websocket-handler.ts +5 -2
  320. package/src/server/index.ts +6 -36
  321. package/src/server/inference/client-encoder-delivery.ts +9 -3
  322. package/src/server/json-serialized-bytes.ts +44 -0
  323. package/src/server/management/agent-settings-routes.ts +24 -21
  324. package/src/server/management/codex-cli-update-routes.ts +2 -1
  325. package/src/server/management/logs-usage-routes.ts +89 -4
  326. package/src/server/management/provider-routes.ts +2 -22
  327. package/src/server/management/qoder-provider-probe.ts +105 -0
  328. package/src/server/management/route-registry.ts +4 -1
  329. package/src/server/management/usage-aggregate-cache.ts +15 -5
  330. package/src/server/management/usage-source-facets.ts +38 -0
  331. package/src/server/messages-native-scope.ts +2 -1
  332. package/src/server/messages-native-tool-guard.ts +12 -4
  333. package/src/server/messages-native.ts +123 -47
  334. package/src/server/messages-response-headers.ts +25 -11
  335. package/src/server/messages-shared.ts +99 -65
  336. package/src/server/messages-sse-error-filter.ts +199 -0
  337. package/src/server/native-final-log.ts +93 -0
  338. package/src/server/ollama-inbound.ts +349 -0
  339. package/src/server/ollama-native-paths.ts +21 -0
  340. package/src/server/ollama-route-policy.ts +73 -0
  341. package/src/server/relay.ts +22 -3
  342. package/src/server/request-decompress.ts +4 -2
  343. package/src/server/request-log-failure-attribution.ts +22 -0
  344. package/src/server/request-log-failure-detail.ts +80 -0
  345. package/src/server/request-log-terminal-status.ts +4 -2
  346. package/src/server/request-log.ts +91 -42
  347. package/src/server/response-log-body.ts +6 -1
  348. package/src/server/responses/account-change-state.ts +17 -6
  349. package/src/server/responses/adapter-continuation.ts +17 -6
  350. package/src/server/responses/adapter-delivery.ts +17 -10
  351. package/src/server/responses/adapter-dispatch.ts +32 -31
  352. package/src/server/responses/anthropic-thinking-recovery.ts +3 -0
  353. package/src/server/responses/codex-auth-error.ts +24 -19
  354. package/src/server/responses/codex-ws-exchange.ts +11 -8
  355. package/src/server/responses/codex-ws-metadata.ts +94 -21
  356. package/src/server/responses/codex-ws-request.ts +3 -1
  357. package/src/server/responses/codex-ws-wire.ts +19 -3
  358. package/src/server/responses/compact.ts +57 -24
  359. package/src/server/responses/compaction-recovery.ts +4 -2
  360. package/src/server/responses/compaction-routing.ts +9 -4
  361. package/src/server/responses/core-auth.ts +32 -14
  362. package/src/server/responses/core-codex-account.ts +17 -6
  363. package/src/server/responses/core-combo-failure.ts +7 -1
  364. package/src/server/responses/core-combo-native.ts +2 -1
  365. package/src/server/responses/core-combo.ts +43 -27
  366. package/src/server/responses/core-errors.ts +24 -21
  367. package/src/server/responses/core-lifetime.ts +6 -3
  368. package/src/server/responses/core-normalize.ts +1 -0
  369. package/src/server/responses/core-options.ts +9 -0
  370. package/src/server/responses/core-pipeline.ts +4 -3
  371. package/src/server/responses/empty-completion-guard.ts +4 -1
  372. package/src/server/responses/fetch-helpers.ts +7 -1
  373. package/src/server/responses/input-admission.ts +28 -2
  374. package/src/server/responses/native-injection.ts +1 -1
  375. package/src/server/responses/native-response-json.ts +13 -4
  376. package/src/server/responses/native-response-output.ts +1 -2
  377. package/src/server/responses/non-replayable-error.ts +2 -1
  378. package/src/server/responses/pacing-overload.ts +3 -2
  379. package/src/server/responses/passthrough-delivery.ts +55 -14
  380. package/src/server/responses/passthrough-dispatch.ts +20 -18
  381. package/src/server/responses/passthrough-error.ts +9 -9
  382. package/src/server/responses/policy-fallback.ts +2 -1
  383. package/src/server/responses/request-prepare.ts +69 -48
  384. package/src/server/responses/request-transport.ts +36 -31
  385. package/src/server/responses/response-effects.ts +3 -2
  386. package/src/server/responses/run-turn-execution.ts +6 -6
  387. package/src/server/responses/sidecar-execution.ts +16 -12
  388. package/src/server/responses/spend-storage-error.ts +2 -1
  389. package/src/server/responses/terminal-guard.ts +30 -0
  390. package/src/server/responses/ws-upstream.ts +9 -0
  391. package/src/server/responses-custom-tool-repair.ts +14 -3
  392. package/src/server/responses-terminal-repair.ts +5 -2
  393. package/src/server/responses-undeclared-tool-guard.ts +39 -16
  394. package/src/server/restart-replacement.ts +3 -1
  395. package/src/server/safe-response-headers.ts +162 -13
  396. package/src/server/sse-payload-rewrite.ts +23 -11
  397. package/src/server/turn-state-handles.ts +164 -0
  398. package/src/server/workflow-refusal.ts +2 -1
  399. package/src/server/ws-bridge.ts +4 -0
  400. package/src/service/definition.ts +36 -4
  401. package/src/service/launchd.ts +89 -32
  402. package/src/service/logging.ts +34 -7
  403. package/src/service/ownership-mutation-lease.d.mts +11 -2
  404. package/src/service/ownership-mutation-lease.mjs +53 -11
  405. package/src/service/plist-xml.ts +59 -0
  406. package/src/service/state.ts +8 -0
  407. package/src/service/systemd-env.ts +2 -0
  408. package/src/service/systemd.ts +31 -7
  409. package/src/service/windows-taskxml.ts +16 -7
  410. package/src/service-manager-probe.ts +4 -10
  411. package/src/types/config.ts +2 -0
  412. package/src/types/provider.ts +2 -0
  413. package/src/types/request.ts +13 -1
  414. package/src/update/config-preflight.ts +48 -0
  415. package/src/update/index.ts +148 -26
  416. package/src/update/npm-install.d.mts +8 -0
  417. package/src/update/npm-install.mjs +20 -1
  418. package/src/update/orchestrated-admission.d.mts +4 -0
  419. package/src/update/orchestrated-admission.mjs +12 -0
  420. package/src/update/orchestrated-arguments.d.mts +12 -0
  421. package/src/update/orchestrated-arguments.mjs +64 -0
  422. package/src/update/orchestrated-child.d.mts +12 -0
  423. package/src/update/orchestrated-child.mjs +70 -0
  424. package/src/update/orchestrated-entry.ts +234 -0
  425. package/src/update/orchestrated-identity-probe-entry.ts +20 -0
  426. package/src/update/orchestrated-identity.ts +53 -0
  427. package/src/update/orchestrated-live-identity.ts +48 -0
  428. package/src/update/orchestrated-node-driver.mjs +99 -0
  429. package/src/update/orchestrated-outcome.d.mts +21 -0
  430. package/src/update/orchestrated-outcome.mjs +40 -0
  431. package/src/update/orchestrated-plan.ts +49 -0
  432. package/src/update/orchestrated-pnpm.d.mts +8 -0
  433. package/src/update/orchestrated-pnpm.mjs +33 -0
  434. package/src/update/orchestrated-session.d.mts +37 -0
  435. package/src/update/orchestrated-session.mjs +264 -0
  436. package/src/update/orchestrated-token.d.mts +10 -0
  437. package/src/update/orchestrated-token.mjs +21 -0
  438. package/src/update/orchestrated-token.ts +3 -0
  439. package/src/update/orchestrated-tree.d.mts +1 -0
  440. package/src/update/orchestrated-tree.mjs +14 -0
  441. package/src/update/pnpm-global-install.d.mts +6 -0
  442. package/src/update/pnpm-global-install.mjs +9 -2
  443. package/src/update/posix-install-supervisor-entry.mjs +6 -0
  444. package/src/update/posix-install-supervisor.d.mts +10 -0
  445. package/src/update/posix-install-supervisor.mjs +88 -0
  446. package/src/update/sync-update-mutex.d.mts +10 -0
  447. package/src/update/sync-update-mutex.mjs +164 -0
  448. package/src/update/sync-update-mutex.ts +1 -0
  449. package/src/update/test-home-guard.mjs +33 -0
  450. package/src/update/transactional-install.mjs +2 -2
  451. package/src/usage/client.ts +43 -0
  452. package/src/usage/error-detail.ts +225 -0
  453. package/src/usage/log.ts +64 -27
  454. package/src/usage/source-facets.ts +51 -0
  455. package/src/usage/source-filter.ts +65 -0
  456. package/src/usage/summary.ts +50 -8
  457. package/src/web-search/anthropic-executor.ts +105 -24
  458. package/src/web-search/executor.ts +5 -3
  459. package/src/web-search/loop.ts +33 -6
  460. package/src/web-search/progress-stream.ts +64 -5
  461. package/gui/dist/assets/App-bwugJRKn.js +0 -58
  462. package/gui/dist/assets/index-ebuVUtB7.js +0 -94
  463. package/gui/dist/assets/quota-summary-6HsrHQAy.js +0 -1
  464. /package/gui/dist/{assets → classic/assets}/App-B4j-Txmb.css +0 -0
  465. /package/gui/dist/{assets → classic/assets}/index-CHWwDo9L.css +0 -0
@@ -144,7 +144,7 @@ export type OAuthActiveTokenObservation =
144
144
 
145
145
  const MAX_OAUTH_TOKEN_REFRESH_FLIGHTS = 32;
146
146
  const OAUTH_TOKEN_REFRESH_FLIGHT_STALE_MS = 120_000;
147
- interface OAuthTokenRefreshFlight extends OAuthRefreshFlightEvidence { promise: Promise<OAuthAccessSnapshot>; startedAt: number; abort: AbortController; settled?: boolean; retirementDeferredLogged?: boolean }
147
+ interface OAuthTokenRefreshFlight extends OAuthRefreshFlightEvidence { promise: Promise<OAuthAccessSnapshot>; startedAt: number; abort: AbortController; settled?: boolean; retirementDeferredLogged?: boolean; requireUsable?: boolean }
148
148
  const tokenRefreshes = new Map<string, OAuthTokenRefreshFlight>();
149
149
  export class OAuthTokenRefreshBusyError extends Error {
150
150
  readonly code = "OAUTH_TOKEN_REFRESH_BUSY";
@@ -156,6 +156,8 @@ export class OAuthTokenRefreshStaleError extends Error {
156
156
  readonly retryable = true;
157
157
  constructor() { super("OAuth token refresh owner became stale"); this.name = "OAuthTokenRefreshStaleError"; }
158
158
  }
159
+ /** Known pre-dispatch cancellation; independent waiters may acquire a new owner. */
160
+ class OAuthDiscoveryRefreshCancelledError extends OAuthTokenRefreshStaleError {}
159
161
 
160
162
  /** Focused owner-identity tests only. Synthetic owners retain no account data. */
161
163
  export function seedOAuthTokenRefreshFlightsForTests(rows: Array<{ key: string; startedAt?: number; flightId?: string; dispatched?: boolean }>): {
@@ -187,9 +189,9 @@ export function seedOAuthTokenRefreshFlightsForTests(rows: Array<{ key: string;
187
189
  }
188
190
  const XAI_PERMANENT_FAILURE_TTL_MS=30_000;
189
191
  const permanentRefreshFailures=new Map<string,number>();
190
- interface XaiRefreshDeps { intentLock?:ReturnType<typeof createOAuthRefreshIntentLock>; now?:()=>number; afterPrePersistRead?:()=>void|Promise<void>; signal?: AbortSignal }
192
+ interface XaiRefreshDeps { intentLock?:ReturnType<typeof createOAuthRefreshIntentLock>; now?:()=>number; afterPrePersistRead?:()=>void|Promise<void>; signal?: AbortSignal; requireUsableAccount?: boolean }
191
193
  interface AnthropicRefreshDeps { resolveIdentity?: AnthropicIdentityResolver; intentLock?:ReturnType<typeof createOAuthRefreshIntentLock>; now?:()=>number; afterPrePersistRead?:()=>void|Promise<void>; signal?: AbortSignal; flight?: OAuthRefreshFlightEvidence; replacedStaleFlight?: OAuthRefreshFlightEvidence }
192
- interface GenericRefreshDeps { intentLock?:ReturnType<typeof createOAuthRefreshIntentLock>; afterPrePersistRead?:()=>void|Promise<void>; signal?: AbortSignal }
194
+ interface GenericRefreshDeps { intentLock?:ReturnType<typeof createOAuthRefreshIntentLock>; afterPrePersistRead?:()=>void|Promise<void>; signal?: AbortSignal; authorityCurrent?: () => boolean; requireUsableAccount?: boolean }
193
195
  function verdictKey(p:string,a:string,c:OAuthCredentials){return `${p}\0${a}\0${credentialGeneration(c)}`;}
194
196
  function cached(p:string,a:string,c:OAuthCredentials,now:()=>number){const k=verdictKey(p,a,c),u=permanentRefreshFailures.get(k);if(u===undefined)return false;if(u<=now()){permanentRefreshFailures.delete(k);return false;}return true;}
195
197
  export function sweepExpiredXaiPermanentFailureVerdicts(now=Date.now()):number{let removed=0;for(const[key,until]of permanentRefreshFailures){if(until>now)continue;permanentRefreshFailures.delete(key);removed+=1;}return removed;}
@@ -448,71 +450,16 @@ export function getOAuthCredentialApiBaseUrl(provider: string): string | undefin
448
450
  export function listOAuthProviders(): string[] {
449
451
  return Object.keys(OAUTH_PROVIDERS).filter(isPublicOAuthProvider);
450
452
  }
451
-
452
- export class UnsupportedOAuthProviderError extends Error {
453
- constructor(provider: string) {
454
- super(`Unsupported OAuth provider in config: ${provider}`);
455
- this.name = "UnsupportedOAuthProviderError";
456
- }
457
- }
458
-
459
- export class OAuthLoginRequiredError extends Error {
460
- readonly provider: string;
461
-
462
- constructor(provider: string) {
463
- super(`Not logged in to ${provider}. Run: ocx login ${provider}`);
464
- this.name = "OAuthLoginRequiredError";
465
- this.provider = provider;
466
- }
467
- }
468
-
469
- /** An operator-paused account is temporarily unavailable, not an invalid login. */
470
- export class OAuthAccountPausedError extends Error {
471
- constructor() {
472
- super("OAuth account is paused. Resume it in account settings and retry.");
473
- this.name = "OAuthAccountPausedError";
474
- }
475
- }
476
-
477
- export class OAuthProviderPublicationError extends Error {
478
- constructor(provider?: string, credentialWritten = true) {
479
- super(provider !== "anthropic2" ? "OAuth credential was saved, but the provider entry was not written. Resolve the account namespace collision, then retry login."
480
- : credentialWritten ? "Anthropic Pool 2 credential was saved as an orphan auth row, but the provider entry was not written. Repair the persisted config or resolve the provider/account namespace collision, then retry login."
481
- : "Anthropic Pool 2 login did not start because the config file is missing or could not be written; no credential was saved. Repair the persisted config, then retry login.");
482
- this.name = "OAuthProviderPublicationError";
483
- }
484
- }
485
-
486
- /** A local configuration conflict found before any credential is written; its text is fixed. */
487
- export class OAuthProviderNamespaceCollisionError extends Error {
488
- constructor(message: string) {
489
- super(message);
490
- this.name = "OAuthProviderNamespaceCollisionError";
491
- }
492
- }
493
-
494
- export class OAuthReauthIdentityMismatchError extends Error {
495
- constructor() {
496
- super("Signed-in account does not match the selected account. Sign in with the same account.");
497
- this.name = "OAuthReauthIdentityMismatchError";
498
- }
499
- }
500
-
501
- export class OAuthReauthIdentityUnverifiedError extends Error {
502
- constructor() {
503
- super("Could not verify signed-in account identity for reauth.");
504
- this.name = "OAuthReauthIdentityUnverifiedError";
505
- }
506
- }
507
-
508
- class OAuthLoginSupersededError extends Error {
509
- constructor() {
510
- super("OAuth login was superseded before credential persistence");
511
- this.name = "OAuthLoginSupersededError";
512
- }
453
+ import { OAuthAccountUnusableError, OAuthLoginSupersededError, OAuthAccountPausedError, OAuthLoginRequiredError, OAuthProviderNamespaceCollisionError, OAuthProviderPublicationError, OAuthReauthIdentityMismatchError, OAuthReauthIdentityUnverifiedError, UnsupportedOAuthProviderError } from "./oauth-errors";
454
+ export { OAuthAccountPausedError, OAuthLoginRequiredError, OAuthProviderNamespaceCollisionError, OAuthProviderPublicationError, OAuthReauthIdentityMismatchError, OAuthReauthIdentityUnverifiedError, UnsupportedOAuthProviderError } from "./oauth-errors";
455
+ /** Project arbitrary OAuth failures onto the small, stable public error vocabulary. */
456
+ export function publicOAuthErrorPresentation(error: unknown): import("../lib/client-error-body").ProxyErrorPresentation | undefined {
457
+ if (error instanceof OAuthLoginRequiredError) return "oauth_login";
458
+ if (error instanceof AntigravityProjectDiscoveryError) return "discovery";
459
+ if (error instanceof MuseLoginError && error.kind === "validation-http" && error.status !== undefined) return "muse_http";
460
+ return undefined;
513
461
  }
514
462
 
515
- /** Project arbitrary OAuth failures onto the small, stable public error vocabulary. */
516
463
  export function publicOAuthAuthenticationErrorMessage(error: unknown): string {
517
464
  if (error instanceof AntigravityProjectDiscoveryError) return error.publicMessage;
518
465
  if (error instanceof MuseLoginError) return museLoginErrorMessage(error.kind, error.status);
@@ -632,6 +579,8 @@ async function resolveAccessSnapshotForAccount(
632
579
  rejectedGeneration?: string,
633
580
  requireUsableAccount = false,
634
581
  oauthProvider = provider,
582
+ authorityCurrent?: () => boolean,
583
+ retryCancelledDiscovery = true,
635
584
  ): Promise<OAuthAccessSnapshot> {
636
585
  const def = OAUTH_PROVIDERS[oauthProvider];
637
586
  if (!def) throw new UnsupportedOAuthProviderError(oauthProvider);
@@ -661,6 +610,7 @@ async function resolveAccessSnapshotForAccount(
661
610
  // no replacement starts until the old consumers have actually released enough capacity.
662
611
  const waiter = tokenRefreshWaiters.tryAcquire();
663
612
  if (!waiter) throw new OAuthTokenRefreshBusyError();
613
+ let unrestrictedRetry = false;
664
614
  try {
665
615
  if (existing && replacedStaleFlight) {
666
616
  // A replacement would wait for this owner's lock anyway. Keep its registry slot
@@ -675,7 +625,10 @@ async function resolveAccessSnapshotForAccount(
675
625
  }
676
626
  if (existing) {
677
627
  logOAuthEvent("OAuth refresh joined existing operation", { provider, accountId });
678
- return await existing.promise;
628
+ const joined = await existing.promise;
629
+ // The owner may not have required usability; a mark that landed meanwhile still rejects us.
630
+ if (requireUsableAccount && getAccountCredentialWithStatus(provider, accountId)?.needsReauth) throw new OAuthAccountUnusableError(provider);
631
+ return joined;
679
632
  }
680
633
  if (tokenRefreshes.size >= MAX_OAUTH_TOKEN_REFRESH_FLIGHTS) {
681
634
  for (const [staleKey, stale] of tokenRefreshes) {
@@ -691,12 +644,14 @@ async function resolveAccessSnapshotForAccount(
691
644
  abort,
692
645
  flightId: randomUUID(),
693
646
  dispatched: false,
647
+ requireUsable: requireUsableAccount,
694
648
  };
695
649
  const refresh = (async (): Promise<OAuthAccessSnapshot> => {
696
- const accessToken = await refreshAndPersistAccessToken(provider, accountId, def, cred, abort.signal, flight, replacedStaleFlight);
650
+ const accessToken = await refreshAndPersistAccessToken(provider, accountId, def, cred, abort.signal, flight, replacedStaleFlight, authorityCurrent, requireUsableAccount);
697
651
  const persistedRow = getAccountCredentialWithStatus(provider, accountId);
698
652
  if (!persistedRow) throw new OAuthLoginRequiredError(provider);
699
653
  if (persistedRow.paused === true) throw new OAuthAccountPausedError();
654
+ if (requireUsableAccount && persistedRow.needsReauth) throw new OAuthAccountUnusableError(provider);
700
655
  const persisted = persistedRow.credential;
701
656
  if (persisted.access !== accessToken) {
702
657
  throw new Error(`OAuth refresh persisted an unexpected access token for ${provider}`);
@@ -715,7 +670,13 @@ async function resolveAccessSnapshotForAccount(
715
670
  flight.promise = refresh;
716
671
  tokenRefreshes.set(key, flight);
717
672
  return await refresh;
673
+ } catch (error) {
674
+ // An unrestricted caller that joined a usable-only owner is not bound by that owner's rejection.
675
+ if (!requireUsableAccount && error instanceof OAuthAccountUnusableError) unrestrictedRetry = true;
676
+ else if (authorityCurrent || !retryCancelledDiscovery || !(error instanceof OAuthDiscoveryRefreshCancelledError)) throw error;
718
677
  } finally { waiter.release(); }
678
+ if (unrestrictedRetry) return resolveAccessSnapshotForAccount(provider, accountId, rejectedGeneration, false, oauthProvider, authorityCurrent, retryCancelledDiscovery);
679
+ return resolveAccessSnapshotForAccount(provider, accountId, rejectedGeneration, requireUsableAccount, oauthProvider, undefined, false);
719
680
  }
720
681
 
721
682
  export async function getValidAccessTokenSnapshot(
@@ -773,9 +734,9 @@ export async function getValidAccessTokenForAccount(provider: string, accountId:
773
734
  export async function getValidAccessSnapshotForAccount(
774
735
  provider: string,
775
736
  accountId: string,
776
- opts: { requireUsableAccount?: boolean } = {},
737
+ opts: { requireUsableAccount?: boolean; authorityCurrent?: () => boolean } = {},
777
738
  ): Promise<OAuthAccessSnapshot> {
778
- return resolveAccessSnapshotForAccount(provider, accountId, undefined, opts.requireUsableAccount === true);
739
+ return resolveAccessSnapshotForAccount(provider, accountId, undefined, opts.requireUsableAccount === true, provider, opts.authorityCurrent);
779
740
  }
780
741
 
781
742
  /** Terminal refresh failures (revoked/rotated-away grants) — retrying cannot succeed. */
@@ -839,7 +800,7 @@ function merged(fresh: OAuthCredentials, previous: OAuthCredentials): OAuthCrede
839
800
  ...(fresh.kiro === undefined && previous.kiro ? { kiro: previous.kiro } : {}),
840
801
  };
841
802
  }
842
- export async function refreshXaiAccountWithLock(provider:string,accountId:string,def:OAuthProviderDef,callerCredential:OAuthCredentials,deps:XaiRefreshDeps={}):Promise<string>{const writerGeneration=captureConfigGeneration();const now=deps.now??Date.now;const guard=await(deps.intentLock??createOAuthRefreshIntentLock(provider,accountId)).acquire();try{const row=getAccountCredentialWithStatus(provider,accountId);if(!row)throw new OAuthLoginRequiredError(provider);if(row.paused)throw new OAuthAccountPausedError();const stored=row.credential;const active=getAccountSet(provider)?.activeAccountId===accountId,candidate=authoritative(stored,active,now);if(credentialGeneration(candidate)!==credentialGeneration(callerCredential)&&candidate.expires>now()+REFRESH_SKEW_MS){if(credentialGeneration(candidate)!==credentialGeneration(stored)){const o=await mergeAccountCredential(provider,accountId,candidate,{expectedGeneration:credentialGeneration(stored),afterPrePersistRead:deps.afterPrePersistRead});if(o.superseded){if(o.stored.expires>now()+REFRESH_SKEW_MS)return o.stored.access;throw new OAuthLoginRequiredError(provider);}}return candidate.access;}if(cached(provider,accountId,candidate,now))throw new OAuthLoginRequiredError(provider);const generation=credentialGeneration(candidate);try{const fresh=merged(await def.refresh(candidate.refresh,deps.signal),candidate);const o=await mergeAccountCredential(provider,accountId,fresh,{expectedGeneration:generation,afterPrePersistRead:deps.afterPrePersistRead});if(o.superseded){if(o.stored.expires>now()+REFRESH_SKEW_MS)return o.stored.access;throw new OAuthLoginRequiredError(provider);}permanentRefreshFailures.delete(verdictKey(provider,accountId,candidate));if(candidate.source==="local-cli")console.warn(XAI_LOCAL_CLI_DETACH_WARNING);return fresh.access;}catch(error){if(error instanceof OAuthMutationBusyError){permanentRefreshFailures.delete(verdictKey(provider,accountId,candidate));throw error;}if(!terminal(error))throw error;const failedAt=now();permanentRefreshFailures.set(verdictKey(provider,accountId,candidate),failedAt+XAI_PERMANENT_FAILURE_TTL_MS);sweepExpiredOnWrite(failedAt);await markAccountNeedsReauthIfGeneration(provider,accountId,generation,writerGeneration);throw new OAuthLoginRequiredError(provider);}}finally{guard.release();}}
803
+ export async function refreshXaiAccountWithLock(provider:string,accountId:string,def:OAuthProviderDef,callerCredential:OAuthCredentials,deps:XaiRefreshDeps={}):Promise<string>{const writerGeneration=captureConfigGeneration();const now=deps.now??Date.now;const guard=await(deps.intentLock??createOAuthRefreshIntentLock(provider,accountId)).acquire();try{const row=getAccountCredentialWithStatus(provider,accountId);if(!row)throw new OAuthLoginRequiredError(provider);if(row.paused)throw new OAuthAccountPausedError();if(deps.requireUsableAccount&&row.needsReauth)throw new OAuthAccountUnusableError(provider);const stored=row.credential;const active=getAccountSet(provider)?.activeAccountId===accountId,candidate=authoritative(stored,active,now);if(credentialGeneration(candidate)!==credentialGeneration(callerCredential)&&candidate.expires>now()+REFRESH_SKEW_MS){if(credentialGeneration(candidate)!==credentialGeneration(stored)){const o=await mergeAccountCredential(provider,accountId,candidate,{expectedGeneration:credentialGeneration(stored),afterPrePersistRead:deps.afterPrePersistRead});if(o.superseded){if(o.stored.expires>now()+REFRESH_SKEW_MS)return o.stored.access;throw new OAuthLoginRequiredError(provider);}}return candidate.access;}if(cached(provider,accountId,candidate,now))throw new OAuthLoginRequiredError(provider);const generation=credentialGeneration(candidate);try{const fresh=merged(await def.refresh(candidate.refresh,deps.signal),candidate);const o=await mergeAccountCredential(provider,accountId,fresh,{expectedGeneration:generation,afterPrePersistRead:deps.afterPrePersistRead,keepReauthMarkedAfterDispatch:!row.needsReauth});if(o.superseded){if(o.stored.expires>now()+REFRESH_SKEW_MS)return o.stored.access;throw new OAuthLoginRequiredError(provider);}permanentRefreshFailures.delete(verdictKey(provider,accountId,candidate));if(candidate.source==="local-cli")console.warn(XAI_LOCAL_CLI_DETACH_WARNING);return fresh.access;}catch(error){if(error instanceof OAuthMutationBusyError){permanentRefreshFailures.delete(verdictKey(provider,accountId,candidate));throw error;}if(!terminal(error))throw error;const failedAt=now();permanentRefreshFailures.set(verdictKey(provider,accountId,candidate),failedAt+XAI_PERMANENT_FAILURE_TTL_MS);sweepExpiredOnWrite(failedAt);await markAccountNeedsReauthIfGeneration(provider,accountId,generation,writerGeneration);throw new OAuthLoginRequiredError(provider);}}finally{guard.release();}}
843
804
 
844
805
 
845
806
  /**
@@ -1030,6 +991,9 @@ export async function refreshGenericAccountWithLock(
1030
991
  const row = getAccountCredentialWithStatus(provider, accountId);
1031
992
  if (!row) throw new OAuthLoginRequiredError(provider);
1032
993
  if (row.paused) throw new OAuthAccountPausedError();
994
+ // A usable-account caller rechecks needsReauth here: a mark committed while it waited must
995
+ // stop the refresh before the stored refresh token is sent.
996
+ if (deps.requireUsableAccount && row.needsReauth) throw new OAuthAccountUnusableError(provider);
1033
997
  const stored = row.credential;
1034
998
  if (
1035
999
  credentialGeneration(stored) !== credentialGeneration(callerCredential)
@@ -1040,11 +1004,14 @@ export async function refreshGenericAccountWithLock(
1040
1004
  }
1041
1005
  const generation = credentialGeneration(stored);
1042
1006
  try {
1007
+ if (deps.authorityCurrent && !deps.authorityCurrent()) throw new OAuthDiscoveryRefreshCancelledError();
1043
1008
  const refreshed = await def.refresh(stored.refresh, deps.signal, stored, accountId);
1044
1009
  const fresh = merged(refreshed, stored);
1045
1010
  const outcome = await mergeAccountCredential(provider, accountId, fresh, {
1046
1011
  expectedGeneration: generation,
1047
1012
  afterPrePersistRead: deps.afterPrePersistRead,
1013
+ // A mark that landed after this flight read the row is newer than the refresh: keep it.
1014
+ keepReauthMarkedAfterDispatch: !row.needsReauth,
1048
1015
  ...(provider === "devin" ? { assertOwnership: (store: AuthStore) => {
1049
1016
  if (store[provider]?.accounts.find(row => row.id === accountId)?.paused) throw new OAuthAccountPausedError();
1050
1017
  assertDevinCliAdoptionOwnership(store, provider, accountId, refreshed);
@@ -1138,10 +1105,12 @@ async function refreshAndPersistAccessToken(
1138
1105
  signal?: AbortSignal,
1139
1106
  flight?: OAuthRefreshFlightEvidence,
1140
1107
  replacedStaleFlight?: OAuthRefreshFlightEvidence,
1108
+ authorityCurrent?: () => boolean,
1109
+ requireUsableAccount = false,
1141
1110
  ): Promise<string> {
1142
- if (provider === "xai") return refreshXaiAccountWithLock(provider, accountId, def, cred, { signal });
1111
+ if (provider === "xai") return refreshXaiAccountWithLock(provider, accountId, def, cred, { signal, requireUsableAccount });
1143
1112
  if (isAnthropicOAuthInstance(provider)) return refreshAnthropicAccountWithLock(provider, accountId, def, cred, { signal, flight, replacedStaleFlight });
1144
- return refreshGenericAccountWithLock(provider, accountId, def, cred, { signal });
1113
+ return refreshGenericAccountWithLock(provider, accountId, def, cred, { signal, authorityCurrent, requireUsableAccount });
1145
1114
  }
1146
1115
 
1147
1116
  /** Resolve discovery credentials only for the caller-owned configured OAuth row. */
@@ -0,0 +1,67 @@
1
+ import { errorDestinationText, providerErrorDestinationLabel } from "../lib/error-destination";
2
+
3
+ export class UnsupportedOAuthProviderError extends Error {
4
+ constructor(provider: string) {
5
+ super(`Unsupported OAuth provider in config: ${errorDestinationText(providerErrorDestinationLabel(provider))}`);
6
+ this.name = "UnsupportedOAuthProviderError";
7
+ }
8
+ }
9
+
10
+ export class OAuthLoginRequiredError extends Error {
11
+ readonly provider: string;
12
+
13
+ constructor(provider: string) {
14
+ super(`Not logged in to ${errorDestinationText(providerErrorDestinationLabel(provider))}. Run: ocx login ${errorDestinationText(providerErrorDestinationLabel(provider))}`);
15
+ this.name = "OAuthLoginRequiredError";
16
+ this.provider = provider;
17
+ }
18
+ }
19
+
20
+ /** A usable-account caller found needsReauth under the refresh lock; unrestricted joiners retry alone. */
21
+ export class OAuthAccountUnusableError extends OAuthLoginRequiredError {}
22
+
23
+ /** An operator-paused account is temporarily unavailable, not an invalid login. */
24
+ export class OAuthAccountPausedError extends Error {
25
+ constructor() {
26
+ super("OAuth account is paused. Resume it in account settings and retry.");
27
+ this.name = "OAuthAccountPausedError";
28
+ }
29
+ }
30
+
31
+ export class OAuthProviderPublicationError extends Error {
32
+ constructor(provider?: string, credentialWritten = true) {
33
+ super(provider !== "anthropic2" ? "OAuth credential was saved, but the provider entry was not written. Resolve the account namespace collision, then retry login."
34
+ : credentialWritten ? "Anthropic Pool 2 credential was saved as an orphan auth row, but the provider entry was not written. Repair the persisted config or resolve the provider/account namespace collision, then retry login."
35
+ : "Anthropic Pool 2 login did not start because the config file is missing or could not be written; no credential was saved. Repair the persisted config, then retry login.");
36
+ this.name = "OAuthProviderPublicationError";
37
+ }
38
+ }
39
+
40
+ /** A local configuration conflict found before any credential is written; its text is fixed. */
41
+ export class OAuthProviderNamespaceCollisionError extends Error {
42
+ constructor(message: string) {
43
+ super(message);
44
+ this.name = "OAuthProviderNamespaceCollisionError";
45
+ }
46
+ }
47
+
48
+ export class OAuthReauthIdentityMismatchError extends Error {
49
+ constructor() {
50
+ super("Signed-in account does not match the selected account. Sign in with the same account.");
51
+ this.name = "OAuthReauthIdentityMismatchError";
52
+ }
53
+ }
54
+
55
+ export class OAuthReauthIdentityUnverifiedError extends Error {
56
+ constructor() {
57
+ super("Could not verify signed-in account identity for reauth.");
58
+ this.name = "OAuthReauthIdentityUnverifiedError";
59
+ }
60
+ }
61
+
62
+ export class OAuthLoginSupersededError extends Error {
63
+ constructor() {
64
+ super("OAuth login was superseded before credential persistence");
65
+ this.name = "OAuthLoginSupersededError";
66
+ }
67
+ }
@@ -34,7 +34,7 @@ import { join } from "node:path";
34
34
  import { getConfigDir, atomicWriteFile, backupInvalidConfig, hardenConfigDir, hardenExistingSecret, withConfigMutationLockSync, loadConfig } from "../config";
35
35
  import { atomicWriteFileNoFollowUnclaimed } from "../config/atomic-write";
36
36
  import { assertNotRealHomeUnderTest } from "../lib/test-home-guard";
37
- import { recordOwnedConfigPath } from "../lib/config-ownership";
37
+ import { recordOwnedConfigPath, registerOwnedConfigPath, type OwnedPathRegistration } from "../lib/config-ownership";
38
38
  import { statTimeMs } from "../lib/file-identity";
39
39
  import { MAX_PENDING_OAUTH_MUTATIONS } from "../lib/translator-budget";
40
40
  import { publishAccountSelection, publishOAuthAccountPauseChange, publishOAuthAccountRoutingPolicyChange } from "../lib/account-selection-events";
@@ -467,18 +467,28 @@ function backupLegacyOnce(): void {
467
467
  // Any existing entry, including a dangling symlink existsSync would call absent, is left
468
468
  // alone, and the copy is exclusive, so credentials are never written through a link.
469
469
  if (!existsSync(path) || directoryEntryExists(backup)) return;
470
+ // Register before creating, so no credential copy ever exists without its manifest entry. The
471
+ // entry is checked absent above and the copy below is exclusive, so nothing existing is adopted.
472
+ let registration: OwnedPathRegistration;
473
+ try {
474
+ registration = registerOwnedConfigPath(getConfigDir(), backup);
475
+ } catch {
476
+ // Uninstall in progress, or a busy ownership lock: defer the migration. The legacy store stays
477
+ // as it is and the next mutation backs it up again.
478
+ throw new Error("OAuth store migration deferred: its recovery backup could not be registered for uninstall; retry shortly.");
479
+ }
480
+ if (registration === "full") {
481
+ // An owned home whose manifest is full: a copy made now would survive uninstall with the legacy
482
+ // credentials in it. Migrate without the downgrade copy instead of blocking credential writes.
483
+ console.warn("[oauth] Recovery backup skipped: the uninstall ownership manifest is full.");
484
+ return;
485
+ }
470
486
  try {
471
487
  publishCredentialSync(() => copyFileSync(path, backup, fsConstants.COPYFILE_EXCL));
472
488
  try { chmodSync(backup, 0o600); } catch { /* best-effort */ }
473
- try {
474
- // Register only the copy we just created. An unowned home still needs downgrade recovery.
475
- if (!recordOwnedConfigPath(getConfigDir(), backup)) {
476
- console.warn("[oauth] Recovery backup created, but uninstall ownership registration failed.");
477
- }
478
- } catch {
479
- console.warn("[oauth] Recovery backup created, but uninstall ownership registration failed.");
480
- }
481
- } catch { /* best-effort */ }
489
+ } catch { return; /* best-effort */ }
490
+ // An unowned home still needs downgrade recovery; it has no manifest to record the copy in.
491
+ if (registration === "unowned") console.warn("[oauth] Recovery backup created, but uninstall ownership registration failed.");
482
492
  }
483
493
 
484
494
  /**
@@ -1610,7 +1620,7 @@ export async function markAccountNeedsReauth(
1610
1620
  }, [provider, accountId]);
1611
1621
  }
1612
1622
 
1613
- export async function mergeAccountCredential(provider:string,accountId:string,credential:OAuthCredentials,opts:{expectedGeneration?:string;afterPrePersistRead?:()=>void|Promise<void>;assertOwnership?: (store: AuthStore) => void}={}):Promise<{superseded:false}|{superseded:true;stored:OAuthCredentials}>{const safe=normalizeCredential(credential);if(!safe)throw new Error("Refusing to persist invalid OAuth credential");if(isAnthropicInstanceId(provider))assertAnthropicCredentialSource(provider,safe);return await mutateStore(async store=>{await opts.afterPrePersistRead?.();const account=store[provider]?.accounts.find(x=>x.id===accountId);if(!account)throw new Error(`OAuth account disappeared before persist: ${provider}`);if(opts.expectedGeneration!==undefined&&credentialGeneration(account.credential)!==opts.expectedGeneration)return{superseded:true,stored:account.credential};opts.assertOwnership?.(store);account.credential=safe;delete account.refreshAttentionGeneration;if(account.needsReauthReason!=="verify_account"){delete account.needsReauth;delete account.needsReauthReason;}return{superseded:false};},[provider,accountId,safe,opts.expectedGeneration]);}
1623
+ export async function mergeAccountCredential(provider:string,accountId:string,credential:OAuthCredentials,opts:{expectedGeneration?:string;afterPrePersistRead?:()=>void|Promise<void>;assertOwnership?: (store: AuthStore) => void;keepReauthMarkedAfterDispatch?:boolean}={}):Promise<{superseded:false}|{superseded:true;stored:OAuthCredentials}>{const safe=normalizeCredential(credential);if(!safe)throw new Error("Refusing to persist invalid OAuth credential");if(isAnthropicInstanceId(provider))assertAnthropicCredentialSource(provider,safe);return await mutateStore(async store=>{await opts.afterPrePersistRead?.();const account=store[provider]?.accounts.find(x=>x.id===accountId);if(!account)throw new Error(`OAuth account disappeared before persist: ${provider}`);if(opts.expectedGeneration!==undefined&&credentialGeneration(account.credential)!==opts.expectedGeneration)return{superseded:true,stored:account.credential};opts.assertOwnership?.(store);account.credential=safe;delete account.refreshAttentionGeneration;if(account.needsReauthReason!=="verify_account"&&!(opts.keepReauthMarkedAfterDispatch&&account.needsReauth)){delete account.needsReauth;delete account.needsReauthReason;}return{superseded:false};},[provider,accountId,safe,opts.expectedGeneration]);}
1614
1624
  // A late refresh failure must not change an operator-paused account's health. Check under
1615
1625
  // the mutation lock, not before awaiting it, so a concurrent pause cannot be overwritten.
1616
1626
  export async function markAccountNeedsReauthIfGeneration(provider:string,accountId:string,generation:string,writerGeneration=captureConfigGeneration(),reason?:"verify_account",isCurrent?:(store:AuthStore)=>boolean):Promise<boolean>{const key=oauthAccountKey(provider,accountId);if(writerGeneration<lastReconciledGeneration&&!liveOAuthAccountKeys.has(key))return false;return await mutateStore(store=>{const account=store[provider]?.accounts.find(x=>x.id===accountId);if(!account?.credential||account.paused||credentialGeneration(account.credential)!==generation)return false;if(writerGeneration<lastReconciledGeneration&&!liveOAuthAccountKeys.has(key))return false;if(isCurrent&&!isCurrent(store))return false;account.needsReauth=true;if(reason==="verify_account")account.needsReauthReason=reason;return true;},[provider,accountId,generation]);}
@@ -1,3 +1,5 @@
1
+ import { messagesRolePresentation } from "../../lib/messages-error-body";
2
+ import { CLAUDE_CONTEXT_OVERFLOW_MESSAGE, markProxyError } from "../../lib/client-error-body";
1
3
  /**
2
4
  * Anthropic Messages -> IR, directly (the Antigravity direct lane).
3
5
  *
@@ -169,10 +171,10 @@ export function messagesConversationToIr(
169
171
  budget: TranslatorBudget,
170
172
  modelId: string,
171
173
  ): MessagesIrConversation {
172
- if (!isRec(raw)) throw new AnthropicRequestError("request body must be a JSON object");
173
- if (typeof raw.model !== "string" || raw.model.length === 0) throw new AnthropicRequestError("model is required");
174
+ if (!isRec(raw)) throw markProxyError(new AnthropicRequestError("request body must be a JSON object"));
175
+ if (typeof raw.model !== "string" || raw.model.length === 0) throw markProxyError(new AnthropicRequestError("model is required"));
174
176
  if (!Array.isArray(raw.messages) || raw.messages.length === 0) {
175
- throw new AnthropicRequestError("messages must be a non-empty array");
177
+ throw markProxyError(new AnthropicRequestError("messages must be a non-empty array"));
176
178
  }
177
179
  const requestedModel = raw.model;
178
180
  const now = Date.now();
@@ -332,7 +334,7 @@ export function messagesConversationToIr(
332
334
  case "tool_result": {
333
335
  flush();
334
336
  if (typeof block.tool_use_id !== "string" || block.tool_use_id.length === 0) {
335
- throw new AnthropicRequestError("tool_result requires tool_use_id");
337
+ throw markProxyError(new AnthropicRequestError("tool_result requires tool_use_id"));
336
338
  }
337
339
  pushToolResult(
338
340
  block.tool_use_id,
@@ -376,7 +378,7 @@ export function messagesConversationToIr(
376
378
  case "tool_use":
377
379
  flush();
378
380
  if (typeof block.id !== "string" || block.id.length === 0 || typeof block.name !== "string" || block.name.length === 0) {
379
- throw new AnthropicRequestError("tool_use requires id and name");
381
+ throw markProxyError(new AnthropicRequestError("tool_use requires id and name"));
380
382
  }
381
383
  pushToolCall(block.id, block.name, block.input);
382
384
  break;
@@ -386,9 +388,9 @@ export function messagesConversationToIr(
386
388
  const signature = typeof block.signature === "string" ? block.signature : "";
387
389
  if (signature.startsWith(OCX_REASONING_PREFIX)) {
388
390
  const owned = decodeReasoningEnvelope(signature, budget);
389
- if (!owned) throw new AnthropicRequestError(MALFORMED_REASONING_SIGNATURE);
391
+ if (!owned) throw markProxyError(new AnthropicRequestError(MALFORMED_REASONING_SIGNATURE));
390
392
  if (Object.hasOwn(owned, "sig")) {
391
- throw new AnthropicRequestError("OpenCodex reasoning continuity cannot be replayed as an Anthropic signature");
393
+ throw markProxyError(new AnthropicRequestError("OpenCodex reasoning continuity cannot be replayed as an Anthropic signature"));
392
394
  }
393
395
  if (owned.nat) {
394
396
  // The provider's own blob goes back only to the model that minted it.
@@ -429,13 +431,17 @@ export function messagesConversationToIr(
429
431
  };
430
432
 
431
433
  for (const message of raw.messages) {
432
- if (!isRec(message)) throw new AnthropicRequestError("each message must be an object");
434
+ if (!isRec(message)) throw markProxyError(new AnthropicRequestError("each message must be an object"));
433
435
  if (message.role === "user") userContent(message.content);
434
436
  else if (message.role === "assistant") assistantContent(message.content);
435
437
  else if (message.role === "system") {
436
438
  const text = systemMessageText(message.content);
437
439
  if (text.length > 0) pushDeveloper(text);
438
- } else throw new AnthropicRequestError(`unsupported message role: ${String(message.role)}`);
440
+ } else {
441
+ const role = messagesRolePresentation(message.role);
442
+ if (role.coercionFailed) throw markProxyError(new TypeError("unsupported message role: unsupported"));
443
+ throw markProxyError(new AnthropicRequestError(role.overflow ? CLAUDE_CONTEXT_OVERFLOW_MESSAGE : "unsupported message role: unsupported"));
444
+ }
439
445
  }
440
446
 
441
447
  const system = anthropicSystemLayout(raw.system, cc);
@@ -0,0 +1,197 @@
1
+ /** Pure Ollama native request and Chat response projections. */
2
+ type Obj = Record<string, unknown>;
3
+ export type OllamaKind = "chat" | "generate";
4
+ export class OllamaCodecError extends Error {
5
+ readonly status = 400;
6
+ readonly code = "invalid_ollama_request";
7
+ constructor(message: string) { super(message); this.name = "OllamaCodecError"; }
8
+ }
9
+ function fail(message: string): never { throw new OllamaCodecError(message); }
10
+ function object(value: unknown, label: string): Obj {
11
+ if (!value || typeof value !== "object" || Array.isArray(value)) fail(`Invalid ${label}`);
12
+ return value as Obj;
13
+ }
14
+ function keys(value: Obj, allowed: readonly string[], label: string): void {
15
+ if (Object.keys(value).some(k => !allowed.includes(k))) fail(`Unsupported ${label} field`);
16
+ }
17
+ function string(value: unknown, label: string, nonempty = false): string {
18
+ if (typeof value !== "string" || (nonempty && !value.trim())) fail(`Invalid ${label}`);
19
+ return value;
20
+ }
21
+ function image(value: unknown): Obj {
22
+ const data = string(value, "image", true);
23
+ if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(data)) fail("Invalid image encoding");
24
+ let bytes: Uint8Array;
25
+ // The pattern above already validated the whole string; decode only the signature window.
26
+ try { bytes = Uint8Array.from(atob(data.slice(0, 16)), c => c.charCodeAt(0)); } catch { return fail("Invalid image encoding"); }
27
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
28
+ if ((data.endsWith("==") && (alphabet.indexOf(data[data.length - 3]!) & 15) !== 0) ||
29
+ (data.endsWith("=") && !data.endsWith("==") && (alphabet.indexOf(data[data.length - 2]!) & 3) !== 0)) fail("Invalid image encoding");
30
+ const starts = (...prefix: number[]) => prefix.every((b, i) => bytes[i] === b);
31
+ const mime = starts(137,80,78,71,13,10,26,10) ? "image/png" : starts(255,216,255) ? "image/jpeg" : starts(71,73,70,56,55,97) || starts(71,73,70,56,57,97) ? "image/gif" : starts(82,73,70,70) && bytes.length >= 12 && bytes[8] === 87 && bytes[9] === 69 && bytes[10] === 66 && bytes[11] === 80 ? "image/webp" : undefined;
32
+ if (!mime) fail("Unsupported image media");
33
+ return { type: "image_url", image_url: { url: `data:${mime};base64,${data}` } };
34
+ }
35
+ function content(text: unknown, images: unknown): unknown {
36
+ const value = string(text, "content");
37
+ if (images === undefined) return value;
38
+ if (!Array.isArray(images)) fail("Invalid images");
39
+ if (!images.length) return value;
40
+ return [{ type: "text", text: value }, ...images.map(image)];
41
+ }
42
+ function requestTools(value: unknown): Obj[] {
43
+ if (!Array.isArray(value)) fail("Invalid tools");
44
+ return value.map(item => {
45
+ const tool = object(item, "tool"); keys(tool, ["type", "function"], "tool");
46
+ if (tool.type !== "function") fail("Unsupported tool type");
47
+ const fn = object(tool.function, "tool function"); keys(fn, ["name", "description", "parameters"], "tool function");
48
+ string(fn.name, "tool name", true);
49
+ if (fn.description !== undefined) string(fn.description, "tool description");
50
+ object(fn.parameters, "tool parameters");
51
+ return { type: "function", function: { ...fn } };
52
+ });
53
+ }
54
+ export function ollamaToChat(kind: OllamaKind, input: unknown): Obj {
55
+ const body = object(input, "request");
56
+ keys(body, kind === "chat" ? ["model", "messages", "stream", "options", "format", "tools"] : ["model", "prompt", "system", "images", "stream", "options", "format"], "request");
57
+ const model = string(body.model, "model", true);
58
+ if (body.stream !== undefined && typeof body.stream !== "boolean") fail("Invalid stream");
59
+ const result: Obj = { model, stream: body.stream ?? true, messages: [] };
60
+ const messages: Obj[] = [];
61
+ if (kind === "generate") {
62
+ if (body.system !== undefined) messages.push({ role: "system", content: string(body.system, "system") });
63
+ messages.push({ role: "user", content: content(body.prompt, body.images) });
64
+ } else {
65
+ if (!Array.isArray(body.messages)) fail("Invalid messages");
66
+ const pending: { id: string; name: string; message: number; matched: boolean }[] = [];
67
+ body.messages.forEach((raw, mi) => {
68
+ const msg = object(raw, "message");
69
+ const role = string(msg.role, "role");
70
+ if (!["system", "user", "assistant", "tool"].includes(role)) fail("Unsupported role");
71
+ keys(msg, role === "user" ? ["role", "content", "images"] : role === "assistant" ? ["role", "content", "tool_calls"] : role === "tool" ? ["role", "content", "tool_name", "tool_call_id"] : ["role", "content"], "message");
72
+ const projected: Obj = { role, content: content(msg.content, role === "user" ? msg.images : undefined) };
73
+ if (role === "assistant" && msg.tool_calls !== undefined) {
74
+ if (!Array.isArray(msg.tool_calls)) fail("Invalid tool calls");
75
+ projected.tool_calls = msg.tool_calls.map((rawCall, ci) => {
76
+ // A replayed response call keeps the id this proxy returned for it; older clients send none.
77
+ const call = object(rawCall, "tool call"); keys(call, ["id", "function"], "tool call");
78
+ const fn = object(call.function, "tool call function"); keys(fn, ["name", "arguments"], "tool call function");
79
+ const name = string(fn.name, "tool name", true); const args = object(fn.arguments, "tool arguments");
80
+ const id = call.id === undefined ? `call_ollama_${mi}_${ci}` : string(call.id, "tool call id", true);
81
+ if (pending.some(p => p.id === id)) fail("Duplicate tool call id");
82
+ pending.push({ id, name, message: mi, matched: false });
83
+ return { id, type: "function", function: { name, arguments: JSON.stringify(args) } };
84
+ });
85
+ }
86
+ if (role === "tool") {
87
+ const id = msg.tool_call_id === undefined ? undefined : string(msg.tool_call_id, "tool call id", true);
88
+ const name = msg.tool_name === undefined ? undefined : string(msg.tool_name, "tool name", true);
89
+ const candidates = pending.filter(p => !p.matched && (id ? p.id === id && (!name || p.name === name) : name && p.name === name));
90
+ if (!id && name && candidates.length) {
91
+ const latestMessage = candidates[candidates.length - 1]!.message;
92
+ const latest = candidates.filter(p => p.message === latestMessage);
93
+ if (latest.length !== 1) fail("Ambiguous tool result");
94
+ latest[0]!.matched = true; projected.tool_call_id = latest[0]!.id;
95
+ } else {
96
+ if (candidates.length !== 1) fail("Unmatched tool result");
97
+ candidates[0]!.matched = true; projected.tool_call_id = candidates[0]!.id;
98
+ }
99
+ }
100
+ messages.push(projected);
101
+ });
102
+ if (body.tools !== undefined) result.tools = requestTools(body.tools);
103
+ }
104
+ result.messages = messages;
105
+ if (body.options !== undefined) {
106
+ const opts = object(body.options, "options"); keys(opts, ["temperature", "top_p", "num_predict", "stop"], "option");
107
+ for (const key of ["temperature", "top_p", "num_predict"] as const) if (opts[key] !== undefined) {
108
+ const v = opts[key]; if (typeof v !== "number" || !Number.isFinite(v) || (key === "num_predict" && (!Number.isSafeInteger(v) || v < 1))) fail("Invalid option");
109
+ result[key === "num_predict" ? "max_tokens" : key] = v;
110
+ }
111
+ if (opts.stop !== undefined) {
112
+ if (!Array.isArray(opts.stop) || !opts.stop.every(v => typeof v === "string")) fail("Invalid stop option");
113
+ result.stop = opts.stop;
114
+ }
115
+ }
116
+ if (body.format !== undefined) { if (body.format !== "json") fail("Unsupported format"); result.response_format = { type: "json_object" }; }
117
+ return result;
118
+ }
119
+
120
+ function usage(value: unknown): Obj {
121
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
122
+ const u = value as Obj; const out: Obj = {};
123
+ if (typeof u.prompt_tokens === "number" && Number.isSafeInteger(u.prompt_tokens) && u.prompt_tokens >= 0) out.prompt_eval_count = u.prompt_tokens;
124
+ if (typeof u.completion_tokens === "number" && Number.isSafeInteger(u.completion_tokens) && u.completion_tokens >= 0) out.eval_count = u.completion_tokens;
125
+ return out;
126
+ }
127
+ function finish(value: unknown): string | undefined { return value === "stop" || value === "tool_calls" || value === "length" ? value : undefined; }
128
+ function nativeError(): Obj { return { error: "Chat completion did not finish successfully" }; }
129
+ function nativeCalls(calls: unknown): Obj[] {
130
+ if (!Array.isArray(calls)) throw new Error("Invalid Chat tool calls");
131
+ return calls.map((raw, i) => {
132
+ const call = object(raw, "response tool call"); const fn = object(call.function, "response tool function");
133
+ const name = string(fn.name, "response tool name", true);
134
+ let args: unknown; try { args = typeof fn.arguments === "string" ? JSON.parse(fn.arguments) : fn.arguments; } catch { throw new Error("Invalid Chat tool arguments"); }
135
+ object(args, "response tool arguments");
136
+ return { id: typeof call.id === "string" && call.id ? call.id : `call_ollama_response_${i}`, function: { name, arguments: args } };
137
+ });
138
+ }
139
+ function payload(kind: OllamaKind, text: string, calls?: Obj[]): Obj {
140
+ return kind === "chat" ? { message: { role: "assistant", content: text, ...(calls?.length ? { tool_calls: calls } : {}) } } : { response: text };
141
+ }
142
+ export function ollamaBufferedResponse(kind: OllamaKind, model: string, input: unknown, createdAt: string): Obj {
143
+ try {
144
+ const body = object(input, "Chat response"); if (!Array.isArray(body.choices) || body.choices.length !== 1) return nativeError();
145
+ const choice = object(body.choices[0], "Chat choice"); const reason = finish(choice.finish_reason); if (!reason) return nativeError();
146
+ const msg = object(choice.message, "Chat message");
147
+ if (msg.content != null && typeof msg.content !== "string") return nativeError();
148
+ const calls = msg.tool_calls === undefined ? undefined : nativeCalls(msg.tool_calls);
149
+ if (kind === "generate" && calls?.length) return nativeError();
150
+ return { model, created_at: createdAt, ...payload(kind, (msg.content as string | null | undefined) ?? "", calls), done: true, done_reason: reason, ...usage(body.usage) };
151
+ } catch { return nativeError(); }
152
+ }
153
+ type StreamTool = { id?: string; name: string; arguments: string };
154
+ export interface OllamaStreamState { kind: OllamaKind; model: string; createdAt: string; finishReason?: unknown; usage: Obj; tools: Map<number, StreamTool>; toolsEmitted: boolean; }
155
+ export function createOllamaStreamState(kind: OllamaKind, model: string, createdAt: string): OllamaStreamState {
156
+ return { kind, model, createdAt, usage: {}, tools: new Map(), toolsEmitted: false };
157
+ }
158
+ /** Consume one parsed Chat chunk. The caller owns settlement and may discard these records on failure. */
159
+ export function consumeOllamaChatChunk(state: OllamaStreamState, input: unknown): Obj[] {
160
+ const body = object(input, "Chat chunk");
161
+ if (body.error !== undefined) throw new Error("Chat stream error");
162
+ if (body.usage != null) state.usage = usage(body.usage);
163
+ if (!Array.isArray(body.choices) || body.choices.length > 1) throw new Error("Invalid Chat chunk choices");
164
+ if (!body.choices.length) return [];
165
+ const choice = object(body.choices[0], "Chat choice"); const delta = object(choice.delta, "Chat delta");
166
+ if (state.finishReason !== undefined) throw new Error("Chat chunk after finish");
167
+ const records: Obj[] = [];
168
+ if (delta.content != null) {
169
+ const text = string(delta.content, "Chat content");
170
+ if (text) records.push({ model: state.model, created_at: state.createdAt, ...payload(state.kind, text), done: false });
171
+ }
172
+ if (delta.tool_calls !== undefined) {
173
+ if (state.kind !== "chat" || !Array.isArray(delta.tool_calls) || state.toolsEmitted) throw new Error("Invalid Chat tool delta");
174
+ for (const raw of delta.tool_calls) {
175
+ const call = object(raw, "tool delta"); if (!Number.isSafeInteger(call.index) || (call.index as number) < 0) throw new Error("Invalid tool index");
176
+ const index = call.index as number; const current = state.tools.get(index) ?? { name: "", arguments: "" };
177
+ if (call.id !== undefined) { const id = string(call.id, "tool id", true); if (current.id && current.id !== id) throw new Error("Conflicting tool id"); current.id = id; }
178
+ if (call.function !== undefined) { const fn = object(call.function, "tool function"); if (fn.name !== undefined) current.name += string(fn.name, "tool name"); if (fn.arguments !== undefined) current.arguments += string(fn.arguments, "tool arguments"); }
179
+ state.tools.set(index, current);
180
+ }
181
+ }
182
+ if (choice.finish_reason != null) {
183
+ if (state.finishReason !== undefined) throw new Error("Duplicate Chat finish");
184
+ state.finishReason = choice.finish_reason;
185
+ if (choice.finish_reason === "tool_calls" && state.tools.size) {
186
+ const calls = [...state.tools.entries()].sort((a, b) => a[0] - b[0]).map(([index, tool]) => ({ id: tool.id ?? `call_ollama_response_${index}`, function: { name: tool.name, arguments: tool.arguments } }));
187
+ records.push({ model: state.model, created_at: state.createdAt, ...payload(state.kind, "", nativeCalls(calls)), done: false }); state.toolsEmitted = true;
188
+ }
189
+ }
190
+ return records;
191
+ }
192
+ /** Call only after the outer handler confirms successful upstream settlement. */
193
+ export function ollamaStreamTerminal(state: OllamaStreamState): Obj {
194
+ const reason = finish(state.finishReason);
195
+ if (!reason || (state.tools.size > 0 && !state.toolsEmitted)) return nativeError();
196
+ return { model: state.model, created_at: state.createdAt, ...payload(state.kind, ""), done: true, done_reason: reason, ...state.usage };
197
+ }