@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,5 @@
1
+ import type { MessagesSseErrorFilter } from "./messages-sse-error-filter";
2
+ import type { MessagesSseFrameHooks } from "../lib/messages-sse-error-presentation";
1
3
  import type { TranslatorBudget } from "../lib/translator-budget";
2
4
  import { Buffer } from "node:buffer";
3
5
 
@@ -89,6 +91,7 @@ export function createSseBlockBuffer(
89
91
  next(): { block: string; delimiter: string } | null;
90
92
  tail(): string;
91
93
  isEmpty(): boolean;
94
+ endsWithLineFeed(): boolean;
92
95
  compact(): void;
93
96
  clear(): void;
94
97
  } {
@@ -169,6 +172,7 @@ export function createSseBlockBuffer(
169
172
  },
170
173
  tail: () => buffer.slice(offset),
171
174
  isEmpty: () => offset === buffer.length,
175
+ endsWithLineFeed: () => lastCodeUnit === 10,
172
176
  compact,
173
177
  clear() {
174
178
  budget.releaseRetained(bufferBytes, scope);
@@ -271,8 +275,10 @@ export function relaySseWithPayloadRewrite(
271
275
  body: ReadableStream<Uint8Array>,
272
276
  rewrite: SsePayloadRewrite,
273
277
  translatorBudget: TranslatorBudget,
278
+ frameHooks?: MessagesSseFrameHooks,
279
+ clientFilter?: MessagesSseErrorFilter,
274
280
  ): ReadableStream<Uint8Array> {
275
- return relaySseWithBlockRewrite(body, payloadRewriteAsBlockRewrite(rewrite), translatorBudget);
281
+ return relaySseWithBlockRewrite(body, payloadRewriteAsBlockRewrite(rewrite), translatorBudget, frameHooks, clientFilter);
276
282
  }
277
283
 
278
284
  /**
@@ -285,6 +291,8 @@ export function relaySseWithBlockRewrite(
285
291
  body: ReadableStream<Uint8Array>,
286
292
  rewrite: SseBlockRewrite,
287
293
  translatorBudget: TranslatorBudget,
294
+ frameHooks?: MessagesSseFrameHooks,
295
+ clientFilter?: MessagesSseErrorFilter,
288
296
  ): ReadableStream<Uint8Array> {
289
297
  const reader = body.getReader();
290
298
  const decoder = new TextDecoder();
@@ -298,20 +306,27 @@ export function relaySseWithBlockRewrite(
298
306
  const disposeRewrite = (): void => {
299
307
  if (disposed) return;
300
308
  disposed = true;
309
+ frameHooks?.dispose();
310
+ clientFilter?.dispose();
301
311
  try { rewrite.dispose?.(); } catch { /* teardown must not throw */ }
302
312
  };
303
313
 
304
314
  const enqueueText = (
305
315
  controller: ReadableStreamDefaultController<Uint8Array>,
306
316
  text: string,
307
- ): void => {
317
+ original?: string,
318
+ ): number => {
308
319
  const bytes = Buffer.byteLength(text, "utf8");
309
320
  const reservation = translatorBudget.reserveTransient(bytes, { kind: "live_transient" });
310
321
  try {
311
322
  const encoded = encoder.encode(text);
312
- controller.enqueue(encoded);
323
+ if (original !== undefined) frameHooks?.output(original, encoded);
324
+ let emitted = 0;
325
+ if (clientFilter) clientFilter.push(encoded, value => { controller.enqueue(value); emitted++; });
326
+ else { controller.enqueue(encoded); emitted++; }
313
327
  reservation.commitRetained();
314
328
  translatorBudget.releaseRetained(bytes, { kind: "live_transient" });
329
+ return emitted;
315
330
  } catch (error) {
316
331
  reservation.release();
317
332
  throw error;
@@ -336,8 +351,7 @@ export function relaySseWithBlockRewrite(
336
351
  // Synthetic earlier blocks need a settled delimiter; only the final one can
337
352
  // inherit an upstream LF in a later chunk. Completing CR as CRLF is equivalent.
338
353
  const settled = index < outBlocks.length - 1 && delimiter.endsWith("\r") ? delimiter + "\n" : delimiter;
339
- enqueueText(controller, outBlocks[index]! + settled);
340
- emitted += 1;
354
+ emitted += enqueueText(controller, outBlocks[index]! + settled, block + delimiter);
341
355
  }
342
356
  }
343
357
  buffer.compact();
@@ -349,8 +363,7 @@ export function relaySseWithBlockRewrite(
349
363
  // blocks must still be framed as separate events (#893 review).
350
364
  const tailDelimiter = tail.includes("\r\n") ? "\r\n\r\n" : "\n\n";
351
365
  for (let i = 0; i < tailBlocks.length; i++) {
352
- enqueueText(controller, tailBlocks[i]! + (i < tailBlocks.length - 1 ? tailDelimiter : ""));
353
- emitted += 1;
366
+ emitted += enqueueText(controller, tailBlocks[i]! + (i < tailBlocks.length - 1 ? tailDelimiter : ""), tail);
354
367
  }
355
368
  buffer.clear();
356
369
  }
@@ -367,10 +380,7 @@ export function relaySseWithBlockRewrite(
367
380
  // Consume a late LF before scanning, so it cannot pair with a new LF to create
368
381
  // a phantom empty callback. Any following line ending stays in the input buffer.
369
382
  buffer.append(fragment);
370
- if (continuation && pendingLineFeedVisible) {
371
- enqueueText(controller, "\n");
372
- return 1;
373
- }
383
+ if (continuation && pendingLineFeedVisible) return enqueueText(controller, "\n");
374
384
  return 0;
375
385
  };
376
386
 
@@ -392,10 +402,12 @@ export function relaySseWithBlockRewrite(
392
402
  emitProcessedBlocks(controller, true);
393
403
  if (cancelled) return;
394
404
  buffer.clear();
405
+ clientFilter?.finish(value => controller.enqueue(value));
395
406
  disposeRewrite();
396
407
  controller.close();
397
408
  return;
398
409
  }
410
+ frameHooks?.input(value, buffer.isEmpty(), !buffer.isEmpty() && buffer.endsWithLineFeed(), pendingLineFeed);
399
411
  const continuation = appendFragment(controller, decoder.decode(value, { stream: true }));
400
412
  const emitted = continuation + emitProcessedBlocks(controller);
401
413
  if (cancelled || emitted > 0) return;
@@ -0,0 +1,164 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { createHash } from "node:crypto";
3
+
4
+ /**
5
+ * Proxy-owned handles for the Codex turn-state token.
6
+ *
7
+ * Codex reads `x-codex-turn-state` from a response (or the WebSocket upgrade) and sends it back on
8
+ * later requests of the same turn, so the upstream can keep the turn on one backend. The client
9
+ * receives a random handle this proxy generates instead of the upstream bytes. Each handle is bound
10
+ * at issuance to the admitted caller, the selected provider and the outbound account, and maps back
11
+ * to the upstream token here, in process memory, only at the physical send of a request with the
12
+ * same binding. A mismatched, unknown or expired handle is not forwarded. The map is bounded (oldest
13
+ * entries are evicted) and entries expire. Handles, tokens and bindings are never logged.
14
+ */
15
+
16
+ export const TURN_STATE_HEADER = "x-codex-turn-state";
17
+ /** Where the provider fetch attaches a send's binding on the RequestInit it hands the WebSocket upstream. */
18
+ export const TURN_STATE_BINDING_INIT: unique symbol = Symbol("opencodex.turn-state-binding");
19
+ const HANDLE_PREFIX = "ocx-ts-";
20
+ const HANDLE = /^ocx-ts-[0-9a-f]{32}$/;
21
+ const MAX_HANDLES = 4096;
22
+ const HANDLE_TTL_MS = 6 * 60 * 60 * 1000;
23
+
24
+ type Entry = { value: string; binding: string; expiresAt: number };
25
+ const byHandle = new Map<string, Entry>();
26
+ const byBoundValue = new Map<string, string>();
27
+
28
+ // The admitted caller of the request being served. Admission records it; the provider fetch reads it.
29
+ type CallerScope = { caller?: string };
30
+ const callerScope = new AsyncLocalStorage<CallerScope>();
31
+
32
+ /** Run one request (or one WebSocket frame) with its own caller slot. */
33
+ export function runTurnStateCallerScope<T>(run: () => T): T {
34
+ return callerScope.run({}, run);
35
+ }
36
+
37
+ /** Record the admitted caller for the current request: a configured key id, an environment principal, or loopback. */
38
+ export function noteTurnStateCaller(admission: { kind: string; keyId?: string; contextPrincipalId?: string }): void {
39
+ const scope = callerScope.getStore();
40
+ if (!scope) return;
41
+ scope.caller = admission.kind === "configured" ? `configured:${admission.keyId ?? ""}`
42
+ : admission.kind === "environment" ? `environment:${admission.contextPrincipalId ?? ""}` : admission.kind;
43
+ }
44
+
45
+ /**
46
+ * The binding of an outbound send: a digest of the admitted caller, the provider name and the account
47
+ * the send goes out as (the ChatGPT account id, or the outbound credential when there is none).
48
+ */
49
+ export function turnStateBinding(providerName: string, headers: Headers): string {
50
+ const account = headers.get("chatgpt-account-id")?.trim() ?? "";
51
+ const credential = account ? "" : headers.get("authorization") ?? "";
52
+ return createHash("sha256")
53
+ .update(JSON.stringify([callerScope.getStore()?.caller ?? "unadmitted", providerName, account, credential]))
54
+ .digest("hex");
55
+ }
56
+
57
+ function randomHandle(): string {
58
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
59
+ return HANDLE_PREFIX + Array.from(bytes, byte => byte.toString(16).padStart(2, "0")).join("");
60
+ }
61
+
62
+ function boundKey(entry: { binding: string; value: string }): string {
63
+ return entry.binding + "\0" + entry.value;
64
+ }
65
+
66
+ function live(handle: string, now: number): Entry | undefined {
67
+ const entry = byHandle.get(handle);
68
+ if (!entry) return undefined;
69
+ if (entry.expiresAt > now) return entry;
70
+ byHandle.delete(handle);
71
+ if (byBoundValue.get(boundKey(entry)) === handle) byBoundValue.delete(boundKey(entry));
72
+ return undefined;
73
+ }
74
+
75
+ /** True for a handle this proxy issued that has not expired. */
76
+ export function isLiveTurnStateHandle(value: string, now = Date.now()): boolean {
77
+ return HANDLE.test(value) && live(value, now) !== undefined;
78
+ }
79
+
80
+ /** The handle a client receives for an upstream turn-state token under `binding`; a live handle is returned as is. */
81
+ export function issueTurnStateHandle(value: string, binding: string, now = Date.now()): string {
82
+ if (isLiveTurnStateHandle(value, now)) return value;
83
+ const key = boundKey({ binding, value });
84
+ const existing = byBoundValue.get(key);
85
+ if (existing && live(existing, now)) return existing;
86
+ const handle = randomHandle();
87
+ byHandle.set(handle, { value, binding, expiresAt: now + HANDLE_TTL_MS });
88
+ byBoundValue.set(key, handle);
89
+ while (byHandle.size > MAX_HANDLES) {
90
+ const [oldest, entry] = byHandle.entries().next().value as [string, Entry];
91
+ byHandle.delete(oldest);
92
+ if (byBoundValue.get(boundKey(entry)) === oldest) byBoundValue.delete(boundKey(entry));
93
+ }
94
+ return handle;
95
+ }
96
+
97
+ export type TurnStateResolution = { value: string } | { dropped: "unknown" | "mismatch" };
98
+
99
+ /**
100
+ * What to forward for an inbound turn-state under `binding`: the upstream token for a live handle
101
+ * with the same binding, nothing for an unknown, expired or differently bound handle, and any other
102
+ * value unchanged (it did not come from a handle).
103
+ */
104
+ export function resolveTurnStateHandle(value: string, binding: string, now = Date.now()): TurnStateResolution {
105
+ if (!value.startsWith(HANDLE_PREFIX)) return { value };
106
+ const entry = live(value, now);
107
+ if (!entry) return { dropped: "unknown" };
108
+ return entry.binding === binding ? { value: entry.value } : { dropped: "mismatch" };
109
+ }
110
+
111
+ /** Fixed service-log flag for a handle presented under a different binding; it never names the handle. */
112
+ export const TURN_STATE_MISMATCH_NOTICE = "[opencodex] turn_state_binding_mismatch: a turn-state handle was not forwarded";
113
+ const MISMATCH_NOTICE_INTERVAL_MS = 60_000;
114
+ let lastMismatchNotice = 0;
115
+
116
+ function redeem(value: string, binding: string): string | undefined {
117
+ const resolution = resolveTurnStateHandle(value, binding);
118
+ if ("value" in resolution) return resolution.value;
119
+ if (resolution.dropped === "mismatch" && Date.now() - lastMismatchNotice >= MISMATCH_NOTICE_INTERVAL_MS) {
120
+ lastMismatchNotice = Date.now();
121
+ console.warn(TURN_STATE_MISMATCH_NOTICE);
122
+ }
123
+ return undefined;
124
+ }
125
+
126
+ function record(value: unknown): value is Record<string, unknown> {
127
+ return value !== null && typeof value === "object" && !Array.isArray(value);
128
+ }
129
+
130
+ /**
131
+ * Translate turn-state handles in an outbound send, after admission and routing: the request header
132
+ * and `client_metadata["x-codex-turn-state"]` in a JSON body. The init is returned unchanged when it
133
+ * carries no handle, so ordinary sends keep their exact headers and body bytes.
134
+ */
135
+ export function redeemOutboundTurnState(init: RequestInit | undefined, binding: string): RequestInit | undefined {
136
+ if (!init) return init;
137
+ let next: RequestInit = init;
138
+ const headers = new Headers(init.headers);
139
+ const header = headers.get(TURN_STATE_HEADER);
140
+ if (header !== null && header.startsWith(HANDLE_PREFIX)) {
141
+ const value = redeem(header, binding);
142
+ if (value === undefined) headers.delete(TURN_STATE_HEADER); else headers.set(TURN_STATE_HEADER, value);
143
+ next = { ...next, headers };
144
+ }
145
+ if (typeof init.body === "string" && init.body.includes(HANDLE_PREFIX)) {
146
+ let body: unknown;
147
+ try { body = JSON.parse(init.body); } catch { return next; }
148
+ const metadata = record(body) ? body.client_metadata : undefined;
149
+ const handle = record(metadata) ? metadata[TURN_STATE_HEADER] : undefined;
150
+ if (record(body) && record(metadata) && typeof handle === "string" && handle.startsWith(HANDLE_PREFIX)) {
151
+ const value = redeem(handle, binding);
152
+ const nextMetadata = { ...metadata };
153
+ if (value === undefined) delete nextMetadata[TURN_STATE_HEADER]; else nextMetadata[TURN_STATE_HEADER] = value;
154
+ next = { ...next, body: JSON.stringify({ ...body, client_metadata: nextMetadata }) };
155
+ }
156
+ }
157
+ return next;
158
+ }
159
+
160
+ export function resetTurnStateHandlesForTests(): void {
161
+ byHandle.clear();
162
+ byBoundValue.clear();
163
+ lastMismatchNotice = 0;
164
+ }
@@ -1,3 +1,4 @@
1
+ import { markProxyError } from "../lib/client-error-body";
1
2
  import { sharedPoolContinuityDenial } from "../lib/spend-reservation-ledger";
2
3
  /**
3
4
  * The one place that knows how this proxy refuses a turn on its own workflow budget.
@@ -98,7 +99,7 @@ export function workflowRefusalResponse(
98
99
  // Without this a browser dashboard cannot read the header at all: the data plane never sets
99
100
  // Access-Control-Expose-Headers, so a cross-origin reader sees only the CORS-safelisted ones.
100
101
  refusal.headers.set("Access-Control-Expose-Headers", WORKFLOW_LOCAL_REFUSAL_HEADER);
101
- return refusal;
102
+ return markProxyError(refusal, reason === "workflow-spend-exhausted" && spend && Object.hasOwn({ root: 1, identity: 1, pool: 1 }, spend.scope) ? (spend.includesUnboundPoolHistory ? "workflow_unbound" : "workflow") : undefined);
102
103
  }
103
104
 
104
105
  /** Render the approved conservative-overlay explanation after a dispatch reservation refuses. */
@@ -14,6 +14,7 @@ import { safeResponseHeaders } from "./safe-response-headers";
14
14
  import type { AudioSocketTarget } from "./audio-dictation";
15
15
  import type { CodexWebSocketActivity } from "../codex/websocket-activity";
16
16
  import { AGENT_ASSERTION_HEADER } from "../lib/authorization-scheme";
17
+ import type { UsageClient } from "../usage/client";
17
18
 
18
19
  export { safeResponseHeaders } from "./safe-response-headers";
19
20
 
@@ -22,6 +23,7 @@ type ResponsesTerminalReporter = (status: ResponsesTerminalStatus) => void;
22
23
  type ResponsesPayloadObserver = (payload: string) => void;
23
24
 
24
25
  export interface WsData {
26
+ client?: UsageClient;
25
27
  responsesActivity?: CodexWebSocketActivity;
26
28
  nativeControl?: NativeResponseControl;
27
29
  /** Content-free per-turn explanation; never a model capability assertion. */
@@ -104,12 +106,14 @@ export function buildResponsesWsData(
104
106
  admission: DataPlaneAdmission,
105
107
  admissionLease?: AdmissionReservation<ServerWebSocket<WsData>>,
106
108
  sessionLaneId?: string,
109
+ client?: UsageClient,
107
110
  ): WsData {
108
111
  // Auth is handshake-time only on this path: the per-frame contexts have no
109
112
  // request headers left to re-resolve from, so the decision rides along here.
110
113
  return {
111
114
  headers,
112
115
  admission,
116
+ ...(client ? { client } : {}),
113
117
  ...(admissionLease ? { admissionLease } : {}),
114
118
  ...(sessionLaneId ? { sessionLaneId } : {}),
115
119
  };
@@ -7,15 +7,40 @@
7
7
  * route back through them (see `installedServiceListenPort` in `health.ts`, which
8
8
  * intentionally stays behind because it asks every backend).
9
9
  */
10
+ import { basename, join } from "node:path";
10
11
  import { getConfigDir, loadConfig } from "../config";
11
12
  import { readClaudeInterceptProxyToken } from "../claude/intercept/proxy-auth";
12
13
  import { serviceApiTokenFilePath } from "../lib/service-secrets";
13
14
  import { PROXY_ENV_KEYS } from "../lib/proxy-env";
14
15
 
16
+ /**
17
+ * The service token file under one OpenCodex home, for a definition that pins that home.
18
+ * The file name comes from {@link serviceApiTokenFilePath}, which stays its only owner.
19
+ */
20
+ export function serviceApiTokenFileUnder(opencodexHome: string): string {
21
+ return join(opencodexHome, basename(serviceApiTokenFilePath()));
22
+ }
23
+
15
24
  export function shellQuote(value: string): string {
16
25
  return `'${value.replace(/'/g, "'\\''")}'`;
17
26
  }
18
27
 
28
+ /**
29
+ * Assign the resolved service homes AFTER the login shell initializes, with shell-safe quoting.
30
+ *
31
+ * launchd and systemd run the service command through `/bin/sh -lc`. A login profile can
32
+ * export CODEX_HOME/OPENCODEX_HOME after the manager supplied the definition environment, and
33
+ * the shell assignment that runs last wins. Pinning only `<key>/Environment` therefore cannot
34
+ * guarantee the proxy sees the home the service install recorded. The command assigns both
35
+ * homes immediately before `exec`, so a profile export cannot override the pinned values.
36
+ */
37
+ export function pinnedServiceHomeShellAssignments(
38
+ codexHome: string,
39
+ opencodexHome: string,
40
+ ): string {
41
+ return `CODEX_HOME=${shellQuote(codexHome)} OPENCODEX_HOME=${shellQuote(opencodexHome)} export CODEX_HOME OPENCODEX_HOME;`;
42
+ }
43
+
19
44
  /**
20
45
  * Listen port baked into service wrappers / WinSW XML.
21
46
  * Priority: explicit override → OCX_BAKE_PORT (update restart) → config.port → 10100.
@@ -36,8 +61,12 @@ export function resolveServiceListenPort(override?: number): number {
36
61
  return 10100;
37
62
  }
38
63
 
39
- export function buildServiceShellCommand(bun: string, cli: string | null, port = resolveServiceListenPort()): string {
40
- const tokenFile = serviceApiTokenFilePath();
64
+ export function buildServiceShellCommand(
65
+ bun: string,
66
+ cli: string | null,
67
+ port = resolveServiceListenPort(),
68
+ tokenFile = serviceApiTokenFilePath(),
69
+ ): string {
41
70
  const args = cli ? `${shellQuote(cli)} start` : "start";
42
71
  return `if [ -f ${shellQuote(tokenFile)} ]; then OPENCODEX_API_AUTH_TOKEN="$(cat ${shellQuote(tokenFile)})"; export OPENCODEX_API_AUTH_TOKEN; fi; exec ${shellQuote(bun)} ${args} --port ${port}`;
43
72
  }
@@ -48,8 +77,11 @@ export function buildServiceShellCommand(bun: string, cli: string | null, port =
48
77
  * in form: the service still reads the token from disk at start and never carries it in
49
78
  * the unit.
50
79
  */
51
- export function buildServiceLauncherShellCommand(launcher: string, port = resolveServiceListenPort()): string {
52
- const tokenFile = serviceApiTokenFilePath();
80
+ export function buildServiceLauncherShellCommand(
81
+ launcher: string,
82
+ port = resolveServiceListenPort(),
83
+ tokenFile = serviceApiTokenFilePath(),
84
+ ): string {
53
85
  return `if [ -f ${shellQuote(tokenFile)} ]; then OPENCODEX_API_AUTH_TOKEN="$(cat ${shellQuote(tokenFile)})"; export OPENCODEX_API_AUTH_TOKEN; fi; exec ${shellQuote(launcher)} start --port ${port}`;
54
86
  }
55
87
 
@@ -11,19 +11,14 @@ import { BUN_RUNTIME_PATH_ENV, BUN_RUNTIME_SOURCE_ENV, durableBunRuntime, type D
11
11
  import { serviceApiTokenFilePath } from "../lib/service-secrets";
12
12
  import { recordOwnedConfigPath } from "../lib/config-ownership";
13
13
  import { writeServiceApiTokenFile, assertLiveServiceManagerAllowed } from "./guards";
14
- import { resolveServiceListenPort, buildServiceShellCommand, buildServiceLauncherShellCommand, resolvedProxyEnv } from "./definition";
15
- import { SERVICE_MANAGED_ENV, LABEL, cliEntry, filterTransientServicePath, logPath, serviceStatePath, currentCodexSqliteHomeAbsolute, type ServiceInstallState, writeServiceInstallState, readServiceInstallState } from "./state";
14
+ import { resolveServiceListenPort, buildServiceShellCommand, buildServiceLauncherShellCommand, resolvedProxyEnv, pinnedServiceHomeShellAssignments, serviceApiTokenFileUnder } from "./definition";
15
+ import { SERVICE_MANAGED_ENV, LABEL, cliEntry, filterTransientServicePath, logPath, serviceStatePath, currentCodexSqliteHomeAbsolute, currentCodexHome, currentOpenCodexHome, type ServiceInstallState, writeServiceInstallState, readServiceInstallState } from "./state";
16
16
  import { writeServiceDefinitionFile } from "./windows-ops";
17
17
  import { readTextOrNull } from "./windows-taskxml";
18
+ import { encodePlistString, plistKeyedString } from "./plist-xml";
18
19
 
19
- function plistString(value: string): string {
20
- return value
21
- .replace(/&/g, "&amp;")
22
- .replace(/</g, "&lt;")
23
- .replace(/>/g, "&gt;")
24
- .replace(/"/g, "&quot;")
25
- .replace(/'/g, "&apos;");
26
- }
20
+ /** Encode a plist value; `field` names it if it holds a character XML cannot carry. */
21
+ const plistString = encodePlistString;
27
22
 
28
23
  /**
29
24
  * Render the launchd plist from the package-local Bun + CLI pair. Unlike systemd, launchd
@@ -34,15 +29,15 @@ function plistString(value: string): string {
34
29
  */
35
30
  export function buildPlist(
36
31
  proxyEnv: { name: string; value: string }[] = resolvedProxyEnv(),
37
- deps: { runtime?: DurableBunRuntime; launcher?: string | null } = {},
32
+ deps: { runtime?: DurableBunRuntime; launcher?: string | null; homes?: LaunchdPinnedHomes } = {},
38
33
  ): string {
39
34
  const runtime = deps.runtime ?? durableBunRuntime();
40
35
  const { bun, bunRuntimeSource, cli } = cliEntry(runtime);
41
36
  const log = logPath();
42
37
  const path = filterTransientServicePath(process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin", ":", "darwin");
43
- const codexHome = process.env.CODEX_HOME?.trim();
38
+ const homes = deps.homes ?? currentLaunchdPinnedHomes();
39
+ const { codexHome, opencodexHome } = homes;
44
40
  const codexSqliteHome = currentCodexSqliteHomeAbsolute();
45
- const opencodexHome = process.env.OPENCODEX_HOME?.trim();
46
41
  const envLines = [
47
42
  ` <key>OCX_SERVICE</key><string>1</string>`,
48
43
  // OCX_SERVICE alone cannot identify the managed job: `ocx claude` and `ocx opencode`
@@ -51,15 +46,15 @@ export function buildPlist(
51
46
  // the dashboard-stop refusal below can tell a real launchd job from an ordinary child.
52
47
  ` <key>${SERVICE_MANAGED_ENV}</key><string>1</string>`,
53
48
  ` <key>${BUN_RUNTIME_SOURCE_ENV}</key><string>${bunRuntimeSource}</string>`,
54
- ` <key>${BUN_RUNTIME_PATH_ENV}</key><string>${plistString(bun)}</string>`,
55
- ` <key>PATH</key><string>${plistString(path)}</string>`,
56
- codexHome ? ` <key>CODEX_HOME</key><string>${plistString(codexHome)}</string>` : null,
57
- codexSqliteHome ? ` <key>CODEX_SQLITE_HOME</key><string>${plistString(codexSqliteHome)}</string>` : null,
58
- opencodexHome ? ` <key>OPENCODEX_HOME</key><string>${plistString(opencodexHome)}</string>` : null,
49
+ ` <key>${BUN_RUNTIME_PATH_ENV}</key><string>${plistString(bun, BUN_RUNTIME_PATH_ENV)}</string>`,
50
+ ` <key>PATH</key><string>${plistString(path, "PATH")}</string>`,
51
+ codexHome ? ` <key>CODEX_HOME</key><string>${plistString(codexHome, "CODEX_HOME")}</string>` : null,
52
+ codexSqliteHome ? ` <key>CODEX_SQLITE_HOME</key><string>${plistString(codexSqliteHome, "CODEX_SQLITE_HOME")}</string>` : null,
53
+ opencodexHome ? ` <key>OPENCODEX_HOME</key><string>${plistString(opencodexHome, "OPENCODEX_HOME")}</string>` : null,
59
54
  ...proxyEnv.map(({ name, value }) =>
60
- ` <key>${name}</key><string>${plistString(value)}</string>`),
55
+ ` <key>${name}</key><string>${plistString(value, name)}</string>`),
61
56
  ].filter((line): line is string => Boolean(line)).join("\n");
62
- const command = launchdServiceCommand(runtime);
57
+ const command = launchdServiceCommand(runtime, resolveServiceListenPort(), homes);
63
58
  return `<?xml version="1.0" encoding="UTF-8"?>
64
59
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
65
60
  <plist version="1.0">
@@ -69,7 +64,7 @@ export function buildPlist(
69
64
  <array>
70
65
  <string>/bin/sh</string>
71
66
  <string>-lc</string>
72
- <string>${plistString(command)}</string>
67
+ <string>${plistString(command, "the service command")}</string>
73
68
  </array>
74
69
  <key>RunAtLoad</key><true/>
75
70
  <key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>
@@ -77,8 +72,8 @@ export function buildPlist(
77
72
  <dict>
78
73
  ${envLines}
79
74
  </dict>
80
- <key>StandardOutPath</key><string>${plistString(log)}</string>
81
- <key>StandardErrorPath</key><string>${plistString(log)}</string>
75
+ <key>StandardOutPath</key><string>${plistString(log, "the service log path")}</string>
76
+ <key>StandardErrorPath</key><string>${plistString(log, "the service log path")}</string>
82
77
  </dict>
83
78
  </plist>
84
79
  `;
@@ -132,19 +127,58 @@ export function reusePreviousPlistPathVariable(previous: string, rendered: strin
132
127
  return adopted === normalizedPrevious ? normalizedPrevious : null;
133
128
  }
134
129
 
130
+ /** The homes a launchd plist pins, resolved once per definition. */
131
+ export type LaunchdPinnedHomes = { codexHome: string; opencodexHome: string };
132
+
133
+ function currentLaunchdPinnedHomes(): LaunchdPinnedHomes {
134
+ return { codexHome: currentCodexHome(), opencodexHome: currentOpenCodexHome() };
135
+ }
136
+
135
137
  /**
136
- * The exec line {@link buildPlist} bakes, for the runtime a single install already
138
+ * The homes the installed plist pins, or null when it cannot be read or does not pin both.
139
+ * The plist path does not follow either home, so this answers the same from any shell.
140
+ */
141
+ function installedLaunchdPinnedHomes(readPlist: () => string): LaunchdPinnedHomes | null {
142
+ let plist: string;
143
+ try { plist = readPlist(); } catch { return null; }
144
+ const codexHome = plistKeyedString(plist, "CODEX_HOME");
145
+ const opencodexHome = plistKeyedString(plist, "OPENCODEX_HOME");
146
+ return codexHome && opencodexHome ? { codexHome, opencodexHome } : null;
147
+ }
148
+
149
+ /**
150
+ * The homes the installed job runs with: the plist on disk, then the recorded install state,
151
+ * and the current shell only when neither records them. Every comparison against a job that
152
+ * is already loaded starts here, so a shell exporting other homes cannot make it read stale.
153
+ */
154
+ function installedLaunchdHomes(state: ServiceInstallState | null, readPlist: () => string): LaunchdPinnedHomes {
155
+ return installedLaunchdPinnedHomes(readPlist)
156
+ ?? (state?.codexHome && state.opencodexHome ? { codexHome: state.codexHome, opencodexHome: state.opencodexHome } : null)
157
+ ?? currentLaunchdPinnedHomes();
158
+ }
159
+
160
+ /**
161
+ * The complete exec line {@link buildPlist} bakes, for the runtime a single install already
137
162
  * resolved. Shared so `installLaunchd` can verify the live job against the exact string it
138
163
  * just wrote instead of re-deriving it from install state that has not been written yet
139
164
  * (a fresh install has no state, so `expectedLaunchdCommand` falls back to the package
140
165
  * pair — identical here, but only by accident of the fresh state).
166
+ *
167
+ * The EnvironmentVariables dict is supplied first, but `/bin/sh -lc` runs a login shell
168
+ * after launchd injects it. A profile export could otherwise overwrite the pinned homes,
169
+ * so the command re-assigns both immediately before exec. The assignments are part of the
170
+ * line every live-job comparison uses: a job loaded from an older plist without them, or
171
+ * with other homes, must read as stale.
141
172
  */
142
173
  function launchdServiceCommand(
143
174
  runtime: DurableBunRuntime = durableBunRuntime(),
144
175
  port: number = resolveServiceListenPort(),
176
+ homes: LaunchdPinnedHomes = currentLaunchdPinnedHomes(),
145
177
  ): string {
146
178
  const { bun, cli } = cliEntry(runtime);
147
- return buildServiceShellCommand(bun, cli, port);
179
+ // The token file lives under the pinned OpenCodex home, so it follows the homes too.
180
+ const tokenFile = serviceApiTokenFileUnder(homes.opencodexHome);
181
+ return `${pinnedServiceHomeShellAssignments(homes.codexHome, homes.opencodexHome)} ${buildServiceShellCommand(bun, cli, port, tokenFile)}`;
148
182
  }
149
183
 
150
184
  /**
@@ -153,15 +187,29 @@ function launchdServiceCommand(
153
187
  * stateless install runs the Bun + CLI pair. `start` and `status` compare the live job
154
188
  * against this, so both must follow the launcher or a healthy launcher-backed job reads as
155
189
  * "an OLDER plist" (#3464). PATH is deliberately NOT re-walked here.
190
+ *
191
+ * The pinned homes follow the same rule. A status run from a shell that exports another
192
+ * CODEX_HOME must still recognise a job loaded from the plist on disk, so the homes come from
193
+ * that plist, then from the recorded install state, and from the current environment only
194
+ * when neither records them. A fresh install bakes its own line through
195
+ * {@link launchdServiceCommand} and does not come through here.
156
196
  */
157
197
  export function expectedLaunchdCommand(
158
198
  port: number,
159
- deps: { state?: ServiceInstallState | null; entry?: { bun: string; cli: string | null } } = {},
199
+ deps: {
200
+ state?: ServiceInstallState | null;
201
+ entry?: { bun: string; cli: string | null };
202
+ homes?: LaunchdPinnedHomes;
203
+ readPlist?: () => string;
204
+ } = {},
160
205
  ): string {
161
206
  const state = deps.state === undefined ? readServiceInstallState() : deps.state;
162
- if (state?.launcherPath) return buildServiceLauncherShellCommand(state.launcherPath, port);
207
+ const homes = deps.homes ?? installedLaunchdHomes(state, deps.readPlist ?? (() => readFileSync(plistPath(), "utf8")));
208
+ const pinned = pinnedServiceHomeShellAssignments(homes.codexHome, homes.opencodexHome);
209
+ const tokenFile = serviceApiTokenFileUnder(homes.opencodexHome);
210
+ if (state?.launcherPath) return `${pinned} ${buildServiceLauncherShellCommand(state.launcherPath, port, tokenFile)}`;
163
211
  const entry = deps.entry ?? cliEntry();
164
- return buildServiceShellCommand(entry.bun, entry.cli, port);
212
+ return `${pinned} ${buildServiceShellCommand(entry.bun, entry.cli, port, tokenFile)}`;
165
213
  }
166
214
 
167
215
  /**
@@ -510,7 +558,9 @@ export function installLaunchd(deps: {
510
558
  // install there is no state yet, and after a lost state file `expectedLaunchdCommand`
511
559
  // falls back to the Bun + CLI pair, which happens to be the same answer only by accident
512
560
  // of the empty state.
513
- const expectedCommand = launchdServiceCommand();
561
+ // The homes are resolved once so the probe and the plist pin the same directories.
562
+ const homes = currentLaunchdPinnedHomes();
563
+ const expectedCommand = launchdServiceCommand(undefined, undefined, homes);
514
564
  const uid = process.getuid?.() ?? 0;
515
565
  const guiDomain = launchdGuiDomain();
516
566
  const guiTarget = `${guiDomain}/${LABEL}`;
@@ -531,7 +581,7 @@ export function installLaunchd(deps: {
531
581
  );
532
582
  }
533
583
 
534
- let rendered = buildPlist(resolvedProxyEnv());
584
+ let rendered = buildPlist(resolvedProxyEnv(), { homes });
535
585
  if (previousPlist !== null && previousPlist !== rendered && verdict.state === "loaded-current") {
536
586
  // The live job runs exactly the exec line this install baked, so the definition on disk
537
587
  // IS the one launchd is running: keep the PATH it already carries instead of replacing
@@ -732,13 +782,20 @@ export function installLaunchd(deps: {
732
782
  export function restartLaunchdJob(deps: {
733
783
  launchctl?: typeof runLaunchctl;
734
784
  probe?: typeof probeLaunchdLoadState;
735
- /** The exec line the live job must carry; defaults to the one an install would bake. */
785
+ /**
786
+ * The exec line the live job must carry; defaults to the one an install would bake for the
787
+ * homes the installed plist pins, so a restart from a shell with other homes still matches.
788
+ */
736
789
  expectedCommand?: () => string;
790
+ readPlist?: () => string;
737
791
  } = {}): void {
738
792
  const run = deps.launchctl ?? runLaunchctl;
739
793
  const target = `${launchdGuiDomain()}/${LABEL}`;
740
794
  const expectedCommand = deps.expectedCommand
741
- ?? (() => launchdServiceCommand());
795
+ ?? (() => launchdServiceCommand(undefined, undefined, installedLaunchdHomes(
796
+ readServiceInstallState(),
797
+ deps.readPlist ?? (() => readFileSync(plistPath(), "utf8")),
798
+ )));
742
799
  const kicked = run(["kickstart", "-k", target]);
743
800
  const verdict = (deps.probe ?? probeLaunchdLoadState)({ expectedCommand });
744
801
  if (!kicked.ok || verdict.state === "not-loaded" || verdict.state === "loaded-stale") {