@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
@@ -1,3 +1,4 @@
1
+ import { markProxyError } from "../lib/client-error-body";
1
2
  import type { OcxConfig, OcxClaudeCodeConfig } from "../types";
2
3
  import { isAnthropicOutputSchema, satisfiesOpenAiStrictSchema } from "../adapters/anthropic-output-schema";
3
4
  import { resolveAlias } from "./alias";
@@ -60,7 +61,7 @@ export function resolveInboundModel(model: string, cc?: OcxClaudeCodeConfig): st
60
61
  // A missing date-shaped ID is ambiguous even after a successful but partial
61
62
  // discovery. Never infer that a genuine native model is invalid or reroute it.
62
63
  if (validDateAlias(base)) throw new DesktopModelMappingUnavailableError();
63
- throw new AnthropicRequestError("Unknown Claude Desktop alias; reapply the Desktop profile from the connected hub");
64
+ throw markProxyError(new AnthropicRequestError("Unknown Claude Desktop alias; reapply the Desktop profile from the connected hub"));
64
65
  }
65
66
  const stripped = model.replace(/-\d{8}$/, "");
66
67
  const dateless = map[stripped];
@@ -1,9 +1,11 @@
1
+ import { markProxyError } from "../lib/client-error-body";
1
2
  export class AnthropicRequestError extends Error {}
2
3
 
3
4
  /** A date-shaped Desktop ID can also name a genuine native model absent from discovery. */
4
5
  export class DesktopModelMappingUnavailableError extends AnthropicRequestError {
5
6
  constructor() {
6
7
  super("Claude Desktop model mapping is unavailable; refresh model discovery or reapply the connected hub profile");
8
+ markProxyError(this);
7
9
  }
8
10
  }
9
11
 
@@ -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
  * Claude Code inbound: Anthropic Messages API request -> internal /v1/responses body.
3
5
  *
@@ -34,9 +36,9 @@ export function anthropicImageBlockUrl(block: Rec): string | null {
34
36
  const source = block.source;
35
37
  if (!isRec(source)) return null;
36
38
  if (source.type === "file") {
37
- throw new AnthropicRequestError(
39
+ throw markProxyError(new AnthropicRequestError(
38
40
  "File-backed images require native Anthropic passthrough; use base64 or URL images on translated routes.",
39
- );
41
+ ));
40
42
  }
41
43
  if (source.type === "base64" && typeof source.data === "string") {
42
44
  const media = typeof source.media_type === "string" ? source.media_type : "image/png";
@@ -274,7 +276,7 @@ function userMessageToItems(content: unknown, input: Rec[], elide: SkillElisionC
274
276
  pushUserMessage(input, pending);
275
277
  pending = [];
276
278
  if (typeof raw.tool_use_id !== "string" || raw.tool_use_id.length === 0) {
277
- throw new AnthropicRequestError("tool_result requires tool_use_id");
279
+ throw markProxyError(new AnthropicRequestError("tool_result requires tool_use_id"));
278
280
  }
279
281
  input.push({
280
282
  type: "function_call_output",
@@ -319,7 +321,7 @@ function assistantMessageToItems(content: unknown, input: Rec[], budget: Transla
319
321
  case "tool_use": {
320
322
  flush();
321
323
  if (typeof raw.id !== "string" || raw.id.length === 0 || typeof raw.name !== "string" || raw.name.length === 0) {
322
- throw new AnthropicRequestError("tool_use requires id and name");
324
+ throw markProxyError(new AnthropicRequestError("tool_use requires id and name"));
323
325
  }
324
326
  input.push({ type: "function_call", call_id: raw.id, name: raw.name, arguments: JSON.stringify(raw.input ?? {}) });
325
327
  break;
@@ -330,8 +332,8 @@ function assistantMessageToItems(content: unknown, input: Rec[], budget: Transla
330
332
  const signature = typeof raw.signature === "string" ? raw.signature : "";
331
333
  if (signature.startsWith(OCX_REASONING_PREFIX)) {
332
334
  const owned = decodeReasoningEnvelope(signature, budget);
333
- if (!owned) throw new AnthropicRequestError("malformed ocxr1 reasoning signature");
334
- if (Object.hasOwn(owned, "sig")) throw new AnthropicRequestError("OpenCodex reasoning continuity cannot be replayed as an Anthropic signature");
335
+ if (!owned) throw markProxyError(new AnthropicRequestError("malformed ocxr1 reasoning signature"));
336
+ if (Object.hasOwn(owned, "sig")) throw markProxyError(new AnthropicRequestError("OpenCodex reasoning continuity cannot be replayed as an Anthropic signature"));
335
337
  if (owned.nat) {
336
338
  // The provider's own blob goes back only to the model that minted it; any other
337
339
  // model gets the visible text alone, as before this envelope field existed.
@@ -456,7 +458,7 @@ function translateAnthropicRequest(
456
458
  names: blockedNames,
457
459
  };
458
460
  for (const msg of raw.messages) {
459
- if (!isRec(msg)) throw new AnthropicRequestError("each message must be an object");
461
+ if (!isRec(msg)) throw markProxyError(new AnthropicRequestError("each message must be an object"));
460
462
  if (msg.role === "user") userMessageToItems(msg.content, input, elide);
461
463
  else if (msg.role === "assistant") assistantMessageToItems(msg.content, input, budget, raw.model, nativeReasoningReplay);
462
464
  else if (msg.role === "system") {
@@ -468,7 +470,11 @@ function translateAnthropicRequest(
468
470
  input.push({ type: "message", role: "developer", content: [{ type: "input_text", text }] });
469
471
  }
470
472
  }
471
- else throw new AnthropicRequestError(`unsupported message role: ${String(msg.role)}`);
473
+ else {
474
+ const role = messagesRolePresentation(msg.role);
475
+ if (role.coercionFailed) throw markProxyError(new TypeError("unsupported message role: unsupported"));
476
+ throw markProxyError(new AnthropicRequestError(role.overflow ? CLAUDE_CONTEXT_OVERFLOW_MESSAGE : "unsupported message role: unsupported"));
477
+ }
472
478
  }
473
479
 
474
480
  const body: Rec = {
@@ -495,12 +501,12 @@ function translateAnthropicRequest(
495
501
  }
496
502
 
497
503
  function assertAnthropicRequestShape(raw: unknown): asserts raw is Rec & { model: string; messages: unknown[] } {
498
- if (!isRec(raw)) throw new AnthropicRequestError("request body must be a JSON object");
504
+ if (!isRec(raw)) throw markProxyError(new AnthropicRequestError("request body must be a JSON object"));
499
505
  if (typeof raw.model !== "string" || raw.model.length === 0) {
500
- throw new AnthropicRequestError("model is required");
506
+ throw markProxyError(new AnthropicRequestError("model is required"));
501
507
  }
502
508
  if (!Array.isArray(raw.messages) || raw.messages.length === 0) {
503
- throw new AnthropicRequestError("messages must be a non-empty array");
509
+ throw markProxyError(new AnthropicRequestError("messages must be a non-empty array"));
504
510
  }
505
511
  }
506
512
 
@@ -1,3 +1,7 @@
1
+ import type { UpstreamConditionEvidence } from "../lib/upstream-condition";
2
+ import { ownedAnthropicErrorPayload, messagesOverflowPresentation } from "../lib/messages-error-body";
3
+ import { proxyMessagePresentation, markProxyError, hasProxyErrorMessage, hasProxyIncomplete } from "../lib/client-error-body";
4
+ import { admitMessagesFailure, collectMessagesFailure, type MessagesFailureVerdictSink } from "./failure-verdict";
1
5
  import { anthropicProgressEnvelope, isAnthropicProgressMirror } from "../responses/anthropic-progress";
2
6
  /**
3
7
  * Claude Code outbound: internal /v1/responses output -> Anthropic Messages API shapes.
@@ -132,6 +136,56 @@ export function isThroughputLimitText(message: string): boolean {
132
136
  return THROUGHPUT_LIMIT_TEXT_RE.test(message);
133
137
  }
134
138
 
139
+ /** Codes that say nothing about the cause, so the message decides (#8127). */
140
+ /** Generic 5xx responses use `upstream_server_error`; 503 uses `server_is_overloaded`. */
141
+ const GENERIC_FAILURE_CODES: ReadonlySet<string> = new Set(["server_error", "upstream_error", "upstream_server_error", "api_error", "internal_error"]);
142
+ const NON_OVERFLOW_ERROR_TYPES: ReadonlySet<string> = new Set(["rate_limit_error", "authentication_error", "permission_error"]);
143
+ const NON_OVERFLOW_STATUSES: ReadonlySet<number> = new Set([401, 403, 429]);
144
+ /**
145
+ * Wording that asserts the request itself is over a size limit. Narrower than
146
+ * CONTEXT_OVERFLOW_TEXT_RE on purpose: without a code, a message that only mentions the context
147
+ * window (for example a configuration failure or a validation error) must not make Claude Code
148
+ * compact. Quoted values are removed first, a stated maximum counts only when the stated request
149
+ * is larger, and a negated verdict ("does not exceed") never counts.
150
+ */
151
+ const TOO_LONG_TEXT_RE = /\b(?:prompt|input) is too long\b([^.\n]{0,60})/i;
152
+ const CONDITIONAL_LEAD_RE = /\b(?:if|whether|unless)\b[^.\n]{0,40}$/i;
153
+ const STATED_COUNTS_RE = /maximum context length is (\d+)[^]{0,200}?\b(?:resulted in|you requested|requested) (\d+) tokens/i;
154
+ const EXCEEDS_TEXT_RE = /\b(?:input|prompt|request|messages?|conversation)\b[^.\n]{0,60}\bexceed(?:s|ed|ing)?\b[^.\n]{0,40}\b(?:context (?:window|length)|maximum context|token limit)/i;
155
+ const NEGATION_RE = /\b(?:not|never|no|neither|nor)\b|n['\u2019]t\b/i;
156
+ /** A quoted value inside a message (a field, enum or tool name), ASCII or typographic; an apostrophe inside a word does not open one. */
157
+ const QUOTED_SPAN_RE = /(?<!\w)(['"`])[^'"`\n]{1,200}\1(?!\w)|\u2018[^\u2019\n]{1,200}\u2019|\u201c[^\u201d\n]{1,200}\u201d/g;
158
+
159
+ function assertsOverflow(message: string): boolean {
160
+ const text = message.replace(QUOTED_SPAN_RE, " ");
161
+ const tooLong = TOO_LONG_TEXT_RE.exec(text);
162
+ if (tooLong && !NEGATION_RE.test(tooLong[1] ?? "") && !CONDITIONAL_LEAD_RE.test(text.slice(0, tooLong.index))) return true;
163
+ const counts = STATED_COUNTS_RE.exec(text);
164
+ if (counts && Number(counts[2]) > Number(counts[1])) return true;
165
+ for (const exceeds of text.matchAll(new RegExp(EXCEEDS_TEXT_RE, "gi"))) {
166
+ if (!NEGATION_RE.test(exceeds[0]) && !CONDITIONAL_LEAD_RE.test(text.slice(0, exceeds.index))) return true;
167
+ }
168
+ return false;
169
+ }
170
+
171
+ /**
172
+ * Whether a translated refusal is an oversized-input refusal. A coded context_length_exceeded
173
+ * always is. Some Responses upstreams send the refusal uncoded or as a generic server_error
174
+ * ("Your input exceeds the context window of this model"); as a 502 Claude Code retries it
175
+ * instead of compacting (#8127). Those count only when the wording is an overflow, is not a
176
+ * throughput limit, and the type is not a rate-limit or credential refusal. Any other specific
177
+ * code keeps its own classification.
178
+ */
179
+ export function isContextOverflowError(error: { type?: unknown; code?: unknown }, message: string): boolean {
180
+ const code = error.code;
181
+ if (code === "context_length_exceeded") return true;
182
+ if (code != null && !(typeof code === "string" && GENERIC_FAILURE_CODES.has(code))) return false;
183
+ if (typeof error.type === "string" && NON_OVERFLOW_ERROR_TYPES.has(error.type)) return false;
184
+ const status = (error as { status?: unknown }).status;
185
+ if (typeof status === "number" && NON_OVERFLOW_STATUSES.has(status)) return false;
186
+ return assertsOverflow(message) && !isThroughputLimitText(message);
187
+ }
188
+
135
189
  export function anthropicErrorBody(status: number, message: string, type?: string, code?: string): Rec {
136
190
  const overflow = code === "context_length_exceeded" && !isThroughputLimitText(message);
137
191
  const text = overflow ? claudePromptTooLongMessage(message) : message;
@@ -333,7 +387,7 @@ export function anthropicIncompleteOutcome(
333
387
  */
334
388
  export function anthropicFailedStatus(error: Rec, message: string): number {
335
389
  const code = typeof error.code === "string" ? error.code : undefined;
336
- if (code === "context_length_exceeded") return 400;
390
+ if (isContextOverflowError(error, message)) return 400;
337
391
  return code === "translation_buffer_limit"
338
392
  ? 413
339
393
  : typeof error.status === "number"
@@ -380,6 +434,8 @@ export function responsesSseToAnthropicSse(
380
434
  model: string,
381
435
  opts: {
382
436
  pingIntervalMs?: number;
437
+ failureVerdictSink?: MessagesFailureVerdictSink;
438
+ proxyErrorContext?: object;
383
439
  translatorBudget: TranslatorBudget;
384
440
  /**
385
441
  * This proxy's count of the prompt it forwarded, published on `message_start` only when the
@@ -432,12 +488,13 @@ export function responsesSseToAnthropicSse(
432
488
 
433
489
  return new ReadableStream<Uint8Array>({
434
490
  start(controller) {
435
- const emit = (name: string, data: Rec) => {
491
+ const emit = (name: string, data: Rec, admissionData: Rec = data) => {
436
492
  const frame = encoder.encode(sseFrame(name, data));
437
- const reservation = translatorBudget.reserveTransient(frame.byteLength, { kind: "live_transient" });
493
+ const admittedBytes = admissionData === data ? frame.byteLength : Buffer.byteLength(sseFrame(name, admissionData));
494
+ const reservation = translatorBudget.reserveTransient(admittedBytes, { kind: "live_transient" });
438
495
  controller.enqueue(frame);
439
496
  reservation.commitRetained();
440
- queuedLiveFrameBytes.push(frame.byteLength);
497
+ queuedLiveFrameBytes.push(admittedBytes);
441
498
  };
442
499
  const ensureStarted = () => {
443
500
  if (started) return;
@@ -541,11 +598,20 @@ export function responsesSseToAnthropicSse(
541
598
  // (devlog/_plan/260716_claudecode_hardening/020). On win32 mid-stream socket
542
599
  // resets reach the reader catch (no failed-tail relay) and stay api_error —
543
600
  // same as today, deliberate residual.
544
- const fail = (status: number, message: string, upstreamDerived = false, code?: string) => {
601
+ const fail = (status: number, message: string, upstreamDerived = false, code?: string, local = false, contract?: "stream_incomplete" | "transport_failed", evidence?: UpstreamConditionEvidence) => {
545
602
  // finish/fail sets terminated before closeOpenBlock. A closure-time
546
603
  // allocation failure must still emit one error, without retrying closure.
547
604
  if (terminated && (code !== "translation_buffer_limit" || terminalDelivered)) return;
548
605
  terminated = true;
606
+ const type = code === "translation_buffer_limit" ? "request_too_large"
607
+ : upstreamDerived && isTransientUpstreamStatus(status) ? "overloaded_error" : anthropicErrorType(status);
608
+ const legacy = anthropicErrorBody(status, message, type, code);
609
+ const payload = ownedAnthropicErrorPayload({ status, type, code, evidence: evidence ?? { status, message },
610
+ overflow: messagesOverflowPresentation((legacy.error as Rec).message),
611
+ condition: code === "context_length_exceeded" && isThroughputLimitText(message) ? "rate_limited" : undefined, contract,
612
+ ...(local ? { localError: markProxyError({ message }, proxyMessagePresentation(opts.proxyErrorContext, message, { type: evidence?.type, code: evidence?.code ?? code })) } : {}),
613
+ });
614
+ const admitted = () => admitMessagesFailure(opts.failureVerdictSink, payload, legacy);
549
615
  if (code === "translation_buffer_limit") {
550
616
  releaseThinkingBuffer(open);
551
617
  if (open?.callId) translatorBudget.closeCall(open.callId);
@@ -553,25 +619,22 @@ export function responsesSseToAnthropicSse(
553
619
  terminalDelivered = true;
554
620
  // No normal close frames are valid after overflow. Emit exactly one bounded
555
621
  // typed terminal without consulting the exhausted budget.
556
- controller.enqueue(encoder.encode(sseFrame("error", anthropicErrorBody(
557
- 413,
558
- message,
559
- "request_too_large",
560
- "translation_buffer_limit",
561
- ))));
622
+ controller.enqueue(encoder.encode(sseFrame("error", payload)));
623
+ admitted();
562
624
  return;
563
625
  }
564
- const type = upstreamDerived && isTransientUpstreamStatus(status) ? "overloaded_error" : undefined;
565
626
  if (!started) {
566
627
  // An initial upstream failure is an Anthropic error stream, not a partial message.
567
628
  // Do not manufacture message_start before the terminal error. Earlier transport-only
568
629
  // pings remain valid and do not turn the failure into a partial message.
569
- emit("error", anthropicErrorBody(status, message, type, code));
630
+ emit("error", payload, legacy);
631
+ admitted();
570
632
  terminalDelivered = true;
571
633
  return;
572
634
  }
573
635
  closeOpenBlock();
574
- emit("error", anthropicErrorBody(status, message, type, code));
636
+ emit("error", payload, legacy);
637
+ admitted();
575
638
  terminalDelivered = true;
576
639
  };
577
640
 
@@ -819,7 +882,7 @@ export function responsesSseToAnthropicSse(
819
882
  case "response.completed": {
820
883
  const response = isRec(data.response) ? data.response : {};
821
884
  if (response.end_turn === false && !sawToolUse) {
822
- fail(529, "upstream turn ended without a final answer", true);
885
+ fail(529, "upstream turn ended without a final answer", true, undefined, true);
823
886
  break;
824
887
  }
825
888
  finish(sawToolUse ? "tool_use" : "end_turn", response.usage);
@@ -830,7 +893,7 @@ export function responsesSseToAnthropicSse(
830
893
  const details = isRec(response.incomplete_details) ? response.incomplete_details : {};
831
894
  const outcome = anthropicIncompleteOutcome(details.reason, details.message);
832
895
  if ("stopReason" in outcome) finish(outcome.stopReason, response.usage);
833
- else fail(529, outcome.failMessage, true);
896
+ else fail(529, outcome.failMessage, true, undefined, hasProxyIncomplete(opts.proxyErrorContext ?? upstream, details.reason, details.message), "stream_incomplete");
834
897
  break;
835
898
  }
836
899
  case "response.failed": {
@@ -852,7 +915,9 @@ export function responsesSseToAnthropicSse(
852
915
  status,
853
916
  message,
854
917
  !deterministic,
855
- deterministic || code === "context_length_exceeded" ? code : undefined,
918
+ deterministic ? code : isContextOverflowError(error, message) ? "context_length_exceeded" : undefined,
919
+ hasProxyErrorMessage(opts.proxyErrorContext, message, { type: typeof error.type === "string" ? error.type : undefined, code }),
920
+ undefined, { status, message, type: typeof error.type === "string" ? error.type : undefined, code },
856
921
  );
857
922
  break;
858
923
  }
@@ -863,9 +928,12 @@ export function responsesSseToAnthropicSse(
863
928
 
864
929
  reader = upstream.getReader();
865
930
  void (async () => {
931
+ let readingUpstream = false;
866
932
  try {
867
933
  for (;;) {
934
+ readingUpstream = true;
868
935
  const { done, value } = await reader.read();
936
+ readingUpstream = false;
869
937
  if (done) break;
870
938
  const decodedReservation = translatorBudget.reserveTransient(value.byteLength, { kind: "live_transient" });
871
939
  let decodedCommitted = false;
@@ -976,12 +1044,12 @@ export function responsesSseToAnthropicSse(
976
1044
  // gateways that close such streams politely hand Claude Code an empty/partial
977
1045
  // turn with no retryable error — CLIProxyAPI#2189 failure pattern). Fail closed
978
1046
  // with a mid-stream Anthropic error event so the client can retry.
979
- if (!cancelled) fail(502, "upstream stream ended before a terminal frame (truncated response)", true);
1047
+ if (!cancelled) fail(502, "upstream stream ended before a terminal frame (truncated response)", true, undefined, true);
980
1048
  } catch (err) {
981
1049
  if (isTranslatorBudgetExceededError(err)) {
982
1050
  try { await reader.cancel(err); } catch { /* already closed */ }
983
- fail(413, "upstream translation buffer exceeded the safe limit", false, "translation_buffer_limit");
984
- } else fail(500, err instanceof Error ? err.message : String(err));
1051
+ fail(413, "upstream translation buffer exceeded the safe limit", false, "translation_buffer_limit", true);
1052
+ } else fail(500, err instanceof Error ? err.message : String(err), false, undefined, false, readingUpstream ? "transport_failed" : undefined);
985
1053
  } finally {
986
1054
  releaseThinkingBuffer(open);
987
1055
  translatorBudget.releaseRetained(bufferBytes, { kind: "live_transient" });
@@ -1089,10 +1157,15 @@ export function responsesJsonToAnthropicMessage(json: unknown, model: string, tr
1089
1157
  const message = typeof details.message === "string" && details.message.trim()
1090
1158
  ? details.message
1091
1159
  : `upstream response was incomplete${typeof details.reason === "string" ? ` (${details.reason})` : ""}`;
1092
- return anthropicErrorBody(529, message, "overloaded_error");
1160
+ const legacy = anthropicErrorBody(529, message, "overloaded_error");
1161
+ return ownedAnthropicErrorPayload({ status: 529, type: "overloaded_error", evidence: { status: 529, message },
1162
+ overflow: messagesOverflowPresentation((legacy.error as Rec).message), contract: "stream_incomplete" });
1093
1163
  }
1094
1164
  if (body.status === "completed" && body.end_turn === false && !sawToolUse) {
1095
- return anthropicErrorBody(529, "upstream turn ended without a final answer", "overloaded_error");
1165
+ const message = "upstream turn ended without a final answer";
1166
+ const legacy = anthropicErrorBody(529, message, "overloaded_error");
1167
+ return ownedAnthropicErrorPayload({ status: 529, type: "overloaded_error", evidence: { status: 529 },
1168
+ localError: markProxyError({ message }), overflow: messagesOverflowPresentation((legacy.error as Rec).message) });
1096
1169
  }
1097
1170
  const stopReason = body.status === "incomplete" && details.reason === "max_output_tokens"
1098
1171
  ? "max_tokens"
@@ -1122,6 +1195,7 @@ export async function collectAnthropicMessage(
1122
1195
  stream: ReadableStream<Uint8Array>,
1123
1196
  model: string,
1124
1197
  translatorBudget: TranslatorBudget,
1198
+ failureVerdictSink?: MessagesFailureVerdictSink,
1125
1199
  ): Promise<Rec> {
1126
1200
  const decoder = new TextDecoder();
1127
1201
  const reader = stream.getReader();
@@ -1183,6 +1257,7 @@ export async function collectAnthropicMessage(
1183
1257
  break;
1184
1258
  }
1185
1259
  case "error":
1260
+ collectMessagesFailure(failureVerdictSink, data);
1186
1261
  error = data;
1187
1262
  break;
1188
1263
  default:
@@ -1206,6 +1281,7 @@ export async function collectAnthropicMessage(
1206
1281
  if (dataValue !== null) dataLines.push(dataValue);
1207
1282
  }
1208
1283
  const dataLine = dataLines.join("\n");
1284
+ if (eventName === "error" && failureVerdictSink) failureVerdictSink.collectedErrorEvent = true;
1209
1285
  if (!dataLine) continue;
1210
1286
  let data: unknown;
1211
1287
  try { data = JSON.parse(dataLine); } catch { continue; }
@@ -2,6 +2,19 @@ import type { Capability } from "./capability-types";
2
2
 
3
3
  /** Verified existing handlers only; local operations never claim management routes. */
4
4
  export const ACCESS_REMOTE_CAPABILITIES: readonly Capability[] = [
5
+ {
6
+ command: ["disconnect"], summary: "Disconnect a client or preserve orphaned token files for recovery.",
7
+ usage: "ocx disconnect [--keep-catalog] [--json] | ocx disconnect --orphaned-token --yes [--json]",
8
+ routes: [],
9
+ flags: [
10
+ { name: "--keep-catalog", value: "boolean", summary: "Keep the connected client's catalog during ordinary disconnect." },
11
+ { name: "--orphaned-token", value: "boolean", summary: "Preserve unowned service-token files in a private backup when disconnected." },
12
+ { name: "--yes", value: "boolean", summary: "Explicitly confirm orphan-token recovery; requires --orphaned-token." },
13
+ { name: "--json", value: "boolean", summary: "Emit the local result and backup location as JSON." },
14
+ ],
15
+ mutates: true, json: "payload",
16
+ details: ["Orphan recovery requires a disconnected durable state, no pending connect or disconnect, no Hub or admission-secret use, no installed or unverified service, and verified absence of a client runtime. It preserves rather than deletes token files and does not establish their ownership.", "If refused, inspect the bind, API keys, token environment and service status; manage a Hub secret through its service. Stop OpenCodex and move saved files back only when their original names are absent. Never print their contents."],
17
+ },
5
18
  {
6
19
  command: ["hub", "disable"], summary: "Return a hub to standalone in one validated config write.",
7
20
  usage: "ocx hub disable [--revoke-clients --client-key <id> ...] [--json]",
@@ -215,12 +215,30 @@ export const CAPABILITIES: readonly Capability[] = [
215
215
  "A rotation left pending by a crash is resumed here — startup and status stop rather than guess which key generation is live.",
216
216
  ],
217
217
  },
218
+ {
219
+ command: ["update"],
220
+ summary: "Plan or apply an OpenCodex update.",
221
+ routes: [],
222
+ flags: [
223
+ { name: "--plan", value: "boolean", summary: "Preview an orchestrated update with --json." },
224
+ { name: "--yes", value: "boolean", summary: "Apply an orchestrated update with --json." },
225
+ { name: "--json", value: "boolean", summary: "Emit a versioned plan or result." },
226
+ { name: "--tag", value: "string", summary: "Select latest or preview for the legacy update or plan." },
227
+ { name: "--version", value: "string", summary: "Select an exact version for a plan or apply." },
228
+ { name: "--expect-plan", value: "string", summary: "Require the apply plan to match this planToken." },
229
+ { name: "--not-after", value: "string", summary: "Refuse mutation after this Unix millisecond deadline." },
230
+ ],
231
+ mutates: true,
232
+ json: "envelope",
233
+ details: ["Orchestrated exit codes: 0 verified or up-to-date; 10 refused; 11 previous version verified; 12 uncertain; 64 usage."],
234
+ },
218
235
  {
219
236
  command: ["capabilities"],
220
237
  summary: "List the declared CLI capabilities and the management routes they drive.",
221
238
  routes: [],
222
239
  flags: [
223
240
  { name: "--json", value: "boolean", summary: "Emit the full capability table as JSON." },
241
+ { name: "--contracts", value: "boolean", summary: "List supported versioned contracts." },
224
242
  { name: "--mutating-only", value: "boolean", summary: "Restrict output to capabilities that mutate state." },
225
243
  { name: "--route", value: "string", summary: "Show which capabilities drive a management route." },
226
244
  ],
@@ -618,7 +636,7 @@ export const CAPABILITIES: readonly Capability[] = [
618
636
  routes: [],
619
637
  flags: [{ name: "--plan-id", value: "string", summary: "Required 32-hex id from the current plan." }, { name: "--yes", value: "boolean", summary: "Required confirmation." }, { name: "--request-id", value: "string", summary: "Optional stable retry key." }, { name: "--json", value: "boolean", summary: "Emit the public job status." }],
620
638
  mutates: true, json: "envelope",
621
- details: ["Local counterpart of POST /api/codex/cli-update/apply: invokes the same durable job owner with --yes confirmation; HTTP admission separately requires a trusted loopback GUI session.", "Admission is stored under the protected current-user config root before the installer can run.", "Exit 0 requires an applied job; refused, not_applied, ambiguous and pending duplicate jobs exit 1, including with --json.", "Only POSIX npm-global managed installs are currently supported; Windows, shims and other managers remain refused."],
639
+ details: ["Local counterpart of POST /api/codex/cli-update/apply: invokes the same durable job owner with --yes confirmation; HTTP admission separately requires a current paired dashboard session on trusted loopback ingress, matching origin, CSRF and confirmed: true.", "Standalone HTTP pairing requires the configured literal 127.0.0.1 or ::1 origin; localhost aliases, wildcard binds and connected-client roles use the local CLI --yes path instead.", "Admission is stored under the protected current-user config root before the installer can run.", "Exit 0 requires an applied job; refused, not_applied, ambiguous and pending duplicate jobs exit 1, including with --json.", "Only POSIX npm-global managed installs are currently supported; Windows, shims and other managers remain refused."],
622
640
  usage: "ocx system codex-cli-update apply --plan-id <32-hex> --yes [--request-id <key>] [--json]",
623
641
  },
624
642
  {
@@ -752,6 +770,8 @@ export const CAPABILITIES: readonly Capability[] = [
752
770
  summary: "Synchronize client catalogs, including Aside profiles through the running server's mutation owner.",
753
771
  routes: [{ method: "POST", path: "/api/client-integrations/aside/sync" }],
754
772
  flags: [
773
+ { name: "--local-only", value: "boolean", summary: "Do not fan out the Home sync to linked Children." },
774
+ { name: "--json", value: "boolean", summary: "Emit the sync fan-out result as JSON." },
755
775
  { name: "--restart-codex", value: "boolean", summary: "Restart the Codex app-servers and fully quit and relaunch the Codex desktop app after a catalog, cache, or changed configuration write, on macOS, Linux and Windows." },
756
776
  { name: "--restart-app-server-only", value: "boolean", summary: "Restart only the Codex app-servers and leave the desktop app running; wins over --restart-codex when both are given." },
757
777
  { name: "--restart-desktop-app", value: "boolean", summary: "Deprecated alias of --restart-codex." },
@@ -759,12 +779,15 @@ export const CAPABILITIES: readonly Capability[] = [
759
779
  { name: "--expect-hub-key", value: "string", summary: "Sync only when this machine is a hub client connected with this API key id; otherwise exit 5 with nothing changed." },
760
780
  ],
761
781
  mutates: true,
762
- json: "none",
782
+ json: "payload",
763
783
  details: [
764
784
  "The Aside refresh uses the live server; other catalog synchronization also performs local work.",
785
+ "An update in flight or an unavailable update/sync mutex refuses without changes: update-in-flight, exit 7. Another sync reports sync-in-progress, exit 1.",
786
+ "A current Home catalog fans out to linked Children. Fan-out never requests a Codex app or app-server restart on a Child; use GOAT or ocx sync --restart-codex there. Applying changed Home settings may restart the Child's own OpenCodex client runtime.",
787
+ "After a successful Home sync, a connected Child skipped during fan-out, a failed or timed-out Child, or an unreadable link store yields partial exit 6. Skipped connected Children include an actionable hint; update an outdated ocx through its owning installer, with the Desktop tray as an option for Desktop installs. Intentional skips, including client-initiated links and --local-only, keep their existing exit behavior.",
765
788
  "--expect-link/--expect-hub-key are checked under the lock that selects the sync path. A mismatch writes nothing, never falls back to local providers, exits 5, and ends stderr with {\"phase\":\"child_link_mismatch\"|\"hub_client_mismatch\",\"reason\":...}; reasons are disconnected, invalid_state, disconnect_pending, pending_operation, hub_client, link_client, other_link and other_key. Usage errors exit 2.",
766
789
  ],
767
- usage: "ocx sync [--expect-link <linkId> | --expect-hub-key <apiKeyId>] [--restart-codex] [--restart-app-server-only]",
790
+ usage: "ocx sync [--expect-link <linkId> | --expect-hub-key <apiKeyId>] [--local-only] [--json] [--restart-codex] [--restart-app-server-only]",
768
791
  },
769
792
  {
770
793
  command: ["agent","subagents","force"],
@@ -13,6 +13,7 @@ import {
13
13
  type Capability,
14
14
  } from "./capabilities";
15
15
  import { takeFlag } from "./runtime-api";
16
+ import { CAPABILITY_CONTRACTS } from "./capability-contracts";
16
17
 
17
18
  function takeValueFlag(args: string[], flag: string): string | undefined {
18
19
  // Order-independent by construction: scan for the flag anywhere in argv rather than
@@ -49,14 +50,21 @@ function renderHuman(caps: readonly Capability[], includeHead: boolean): void {
49
50
  export async function runCapabilities(argv: string[]): Promise<number> {
50
51
  const args = [...argv];
51
52
  const json = takeFlag(args, "--json");
53
+ const contracts = takeFlag(args, "--contracts");
52
54
  const mutatingOnly = takeFlag(args, "--mutating-only");
53
55
  const route = takeValueFlag(args, "--route");
54
56
 
55
- if (args.length > 0 || (route !== undefined && route.trim().length === 0)) {
56
- console.error("Usage: ocx capabilities [--json] [--mutating-only] [--route <path>]");
57
+ if (args.length > 0 || (route !== undefined && route.trim().length === 0) || (contracts && (mutatingOnly || route !== undefined))) {
58
+ console.error("Usage: ocx capabilities [--json] [--contracts] [--mutating-only] [--route <path>]");
57
59
  return 64;
58
60
  }
59
61
 
62
+ if (contracts) {
63
+ if (json) console.log(JSON.stringify({ schemaVersion: 1, contracts: CAPABILITY_CONTRACTS }));
64
+ else for (const contract of CAPABILITY_CONTRACTS) console.log(contract);
65
+ return 0;
66
+ }
67
+
60
68
  let selected: readonly Capability[] = route === undefined ? CAPABILITIES : capabilitiesForRoute(route);
61
69
  if (mutatingOnly) selected = selected.filter(cap => cap.mutates);
62
70
 
@@ -64,7 +72,7 @@ export async function runCapabilities(argv: string[]): Promise<number> {
64
72
  // An unmatched route is a real answer, not an error: the route may be exempt or may
65
73
  // not exist. Say which, rather than exiting 0 with silence.
66
74
  if (json) {
67
- console.log(JSON.stringify({ schemaVersion: 1, route, capabilities: [] }, null, 2));
75
+ console.log(JSON.stringify({ schemaVersion: 1, contracts: CAPABILITY_CONTRACTS, route, capabilities: [] }, null, 2));
68
76
  } else {
69
77
  console.error(`No CLI capability drives ${route}.`);
70
78
  }
@@ -74,6 +82,7 @@ export async function runCapabilities(argv: string[]): Promise<number> {
74
82
  if (json) {
75
83
  console.log(JSON.stringify({
76
84
  schemaVersion: 1,
85
+ contracts: CAPABILITY_CONTRACTS,
77
86
  ...(route === undefined ? {} : { route }),
78
87
  capabilities: selected.map(cap => ({
79
88
  command: cap.command,
@@ -87,10 +87,10 @@ export const PROVIDER_MODEL_CAPABILITIES: readonly Capability[] = [
87
87
  details: ["Projects values only from an explicit allowlist of non-secret metadata fields (provider IDs, app types, base URLs, wire dialects, and default models); source and embedded-config bytes are read transiently while secret fields, free-text names, and TOML comments are skipped at the byte level and never decoded into strings, written, or logged, and transient byte buffers are zeroed in finally.", "Only import from a trusted local CC-Switch source: apply prints every imported ID, model, and destination URL before writing, refuses SQLite hard links (nlink > 1) and non-empty -wal/-journal sidecars until CC-Switch is closed, and opens sources read-only with O_NOFOLLOW|O_NONBLOCK descriptor checks; restore inspects auth.json read-only at the byte level and retains any provider that was edited, selected as defaultProvider, or referenced by routing, combos, fallback policy, OAuth accounts, or API keys."],
88
88
  },
89
89
  {
90
- command: ["models", "list"], summary: "List static configured models locally.",
90
+ command: ["models", "list"], summary: "List local configured and router-known models.",
91
91
  usage: "ocx models list [--provider <name>] [--json]", routes: [], mutates: false, json: "envelope",
92
- flags: [{ name: "--provider", value: "string", summary: "Limit to a configured provider." }, { name: "--json", value: "boolean", summary: "Emit models and the static-catalog note." }],
93
- details: ["A bare models invocation is equivalent. Reads local config, never the live catalog; use models live for runtime discovery."],
92
+ flags: [{ name: "--provider", value: "string", summary: "Limit to a configured provider." }, { name: "--json", value: "boolean", summary: "Emit models and the local-catalog note." }],
93
+ details: ["A bare models invocation is equivalent. Includes saved IDs, registry seeds, custom models and this process's discovery cache; use models live for the running catalog."],
94
94
  },
95
95
  {
96
96
  command: ["models","add"],
@@ -0,0 +1,2 @@
1
+ /** Versioned machine contracts implemented by this CLI. */
2
+ export const CAPABILITY_CONTRACTS = ["sync.home-fanout/1", "update.orchestrated/1"] as const;
@@ -7,10 +7,34 @@ import { readBoundedCodexConfig } from "../codex/inject/bounded-config-reader";
7
7
  import { buildProviderTableBlockForTarget } from "../codex/inject/config-toml";
8
8
  import { standaloneCodexRoutingTarget, validateCodexRoutingTarget } from "../codex/inject/routing-target";
9
9
  import { readClientConnectionState } from "../client/state";
10
+ import { normalizeBindHostname } from "../server/bind-host";
11
+ import { probeHostname, proveLiveProxyOwnedByHome, type LiveProxy } from "../server/proxy-liveness";
10
12
  import { codexHasOtherTokenConsumers, codexTokenConfigShapeIsSafe } from "./codex-launch-policy";
11
13
  import { codexLaunchHomeIsOwned, codexLaunchProjectAliasIsOwned, codexLaunchSystemNamespaceIsSafe } from "./codex-launch-ownership";
12
14
  import type { CodexTokenRefusal, CodexTokenRefusalReporter } from "./codex-launch-diagnostics";
13
15
 
16
+ export type CodexRuntimeAttestation = Readonly<{ origin: string }>;
17
+
18
+ /** Retain the exact dial endpoint that answered the ownership challenge, not just its verdict. */
19
+ export async function attestCodexRuntime(
20
+ live: LiveProxy,
21
+ prove: typeof proveLiveProxyOwnedByHome = proveLiveProxyOwnedByHome,
22
+ ): Promise<CodexRuntimeAttestation | null> {
23
+ // Probe the address the listener actually binds: a configured localhost binds 127.0.0.1,
24
+ // which is also what the standalone Codex target dials.
25
+ const snapshot = Object.freeze({ ...live, probeHostname: normalizeBindHostname(live.probeHostname ?? live.hostname) });
26
+ try {
27
+ const origin = new URL(`http://${probeHostname(snapshot.probeHostname)}:${snapshot.port}`).origin;
28
+ return await prove(snapshot) === "proven" ? Object.freeze({ origin }) : null;
29
+ } catch { return null; }
30
+ }
31
+
32
+ /** IPv4 and IPv6 listeners are distinct recipients, even when their ports are equal. */
33
+ export function codexRuntimeAttestationMatchesTarget(baseUrl: string, proof: CodexRuntimeAttestation | null | undefined): boolean {
34
+ try { return proof !== null && proof !== undefined && new URL(baseUrl).origin === proof.origin; }
35
+ catch { return false; }
36
+ }
37
+
14
38
  /** Resolve once; the credential verifier and child must use this exact directory. */
15
39
  export function resolveCodexLaunchHome(env: Record<string, string | undefined>): string | null {
16
40
  try {
@@ -28,7 +52,7 @@ export function resolveCodexLaunchHome(env: Record<string, string | undefined>):
28
52
  }
29
53
 
30
54
  /** Config classification is a startup hint; credentials need an independently bound destination. */
31
- export function codexCredentialDestinationIsTrusted(home: string, systemNamespaceDirectory?: string, report?: CodexTokenRefusalReporter): boolean {
55
+ export function codexCredentialDestinationIsTrusted(home: string, systemNamespaceDirectory?: string, report?: CodexTokenRefusalReporter, runtimeAttestation?: CodexRuntimeAttestation | null): boolean {
32
56
  const refuse = (reason: CodexTokenRefusal): false => { report?.(reason); return false; };
33
57
  try {
34
58
  if (!codexLaunchHomeIsOwned(home)) return refuse("ownership");
@@ -43,15 +67,20 @@ export function codexCredentialDestinationIsTrusted(home: string, systemNamespac
43
67
  if (diagnostics.error || diagnostics.source === "fallback") return refuse("installationConfig");
44
68
  const cfg = diagnostics.config;
45
69
  let target = standaloneCodexRoutingTarget(cfg.port, cfg);
70
+ // A direct client's proof comes from its own machine listener, never from the hub it
71
+ // dials, so only a standalone destination can be compared with the proven origin.
72
+ let destinationIsProvenListener = true;
46
73
  if (cfg.runtimeRole === "client") {
47
74
  // Direct clients bind to persisted connection state; link clients use an authless relay.
48
75
  const connection = readClientConnectionState();
49
76
  if (connection.kind !== "connected" || connection.value.transport === "link") return refuse("connection");
50
77
  target = validateCodexRoutingTarget({ baseUrl: `${connection.value.serverUrl}/v1`, requiresAdmissionToken: true, tokenEnv: "OPENCODEX_API_AUTH_TOKEN" });
78
+ destinationIsProvenListener = false;
51
79
  }
52
80
  const url = new URL(target.baseUrl);
53
81
  if (!target.requiresAdmissionToken) return refuse("admission");
54
82
  if (url.protocol !== "http:" || !["127.0.0.1", "[::1]"].includes(url.hostname)) return refuse("loopback");
83
+ if (destinationIsProvenListener && !codexRuntimeAttestationMatchesTarget(target.baseUrl, runtimeAttestation)) return refuse("destination");
55
84
  const content = readBoundedCodexConfig(join(home, "config.toml"));
56
85
  if (content === null) return refuse("configRead");
57
86
  const config = Bun.TOML.parse(content) as Record<string, unknown>;