@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
@@ -16,6 +16,9 @@
16
16
  * the shared abort helpers from here).
17
17
  */
18
18
  import { clearableDeadline } from "./abort";
19
+ import { isDefiniteContextOverflow } from "./context-overflow-verdict";
20
+ import { errorDestinationLabel, errorDestinationText, type ErrorDestinationLabel } from "./error-destination";
21
+ export { errorDestinationLabel, providerErrorDestinationLabel, errorDestinationText } from "./error-destination";
19
22
  import { redactSecretString } from "./redact";
20
23
 
21
24
  /**
@@ -198,9 +201,9 @@ export function createTransientSendBudget(): TransientSendBudget {
198
201
  */
199
202
  export class SendBudgetExhaustedError extends Error {
200
203
  readonly code = "request_send_budget_exhausted";
201
- constructor(label?: string) {
202
- super(label
203
- ? `request send budget exhausted before dispatch (${label})`
204
+ constructor(label?: ErrorDestinationLabel) {
205
+ super(label !== undefined
206
+ ? `request send budget exhausted before dispatch (${errorDestinationText(label)})`
204
207
  : "request send budget exhausted before dispatch");
205
208
  this.name = "SendBudgetExhaustedError";
206
209
  }
@@ -215,7 +218,7 @@ export class SendBudgetExhaustedError extends Error {
215
218
  */
216
219
  export class InvalidSendBudgetError extends Error {
217
220
  constructor(value: unknown) {
218
- super(`invalid upstream send budget: ${String(value)}`);
221
+ super(`invalid upstream send budget: ${typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : "invalid"}`);
219
222
  this.name = "InvalidSendBudgetError";
220
223
  }
221
224
  }
@@ -516,6 +519,8 @@ export interface ResetRetryOptions {
516
519
  abortSignal?: AbortSignal;
517
520
  /** Short host/path label for the retry warn log (no secrets/query strings). */
518
521
  label?: string;
522
+ /** Client error labels are separate from the operational retry-log label. */
523
+ destination?: ErrorDestinationLabel;
519
524
  /** Total upstream sends allowed, including the first one. Not a per-layer retry count. */
520
525
  attempts?: number;
521
526
  /**
@@ -585,14 +590,13 @@ export class UpstreamRetryEvidenceError extends Error {
585
590
  /** True when a connection-reset retry already reached the origin. */
586
591
  public readonly resetSeen = false,
587
592
  ) {
588
- const detail = cause instanceof Error ? cause.message : String(cause);
589
593
  const kinds: string[] = [];
590
594
  if (transientStatuses.length > 0) kinds.push("transient 5xx response(s)");
591
595
  if (resetSeen) kinds.push("a credential-visible connection reset");
592
596
  super(
593
597
  kinds.length > 0
594
- ? `upstream fetch failed after ${kinds.join(" and ")}: ${detail}`
595
- : `upstream fetch failed: ${detail}`,
598
+ ? `upstream fetch failed after ${kinds.join(" and ")}`
599
+ : "upstream fetch failed",
596
600
  { cause },
597
601
  );
598
602
  this.name = "UpstreamRetryEvidenceError";
@@ -652,7 +656,7 @@ export async function fetchWithResetRetry(
652
656
  // Zero is zero. The old Math.max(1, ...) floor meant an exhausted budget still bought one
653
657
  // more send on every recovery leg, which is most of what made a bounded per-layer retry
654
658
  // compose into an unbounded per-request count.
655
- if (attempts === 0) throw new SendBudgetExhaustedError(opts.label);
659
+ if (attempts === 0) throw new SendBudgetExhaustedError(opts.destination ?? (opts.label ? errorDestinationLabel(opts.label) : undefined));
656
660
  try {
657
661
  let lastError: unknown;
658
662
  let sawReset = false;
@@ -665,7 +669,7 @@ export async function fetchWithResetRetry(
665
669
  // Reported before the await, one physical send at a time: a send that rejects has still
666
670
  // been made, and this helper leaves through four exits (return, reset give-up, non-reset
667
671
  // rethrow, abort), so a per-send report is the only shape that is correct on all of them.
668
- if (opts.onSendsConsumed?.beforeSend && !opts.onSendsConsumed.beforeSend()) throw new SendBudgetExhaustedError(opts.label);
672
+ if (opts.onSendsConsumed?.beforeSend && !opts.onSendsConsumed.beforeSend()) throw new SendBudgetExhaustedError(opts.destination ?? (opts.label ? errorDestinationLabel(opts.label) : undefined));
669
673
  if (!opts.onSendsConsumed?.beforeSend) opts.onSendsConsumed?.(1);
670
674
  try {
671
675
  let response: Response;
@@ -718,6 +722,82 @@ export async function fetchWithResetRetry(
718
722
  } finally { opts.onSendsConsumed?.close?.(); }
719
723
  }
720
724
 
725
+ /** Bytes of a 5xx body read to look for a context-overflow verdict; the verdict caps its input too. */
726
+ const CONTEXT_OVERFLOW_PEEK_BYTES = 16_384;
727
+ /** A body that has not arrived by then is not evidence; the peek must never stall the retry. */
728
+ const CONTEXT_OVERFLOW_PEEK_MS = 250;
729
+ // A hypothetical, negated, or configuration-failure mention does not justify suppressing a retry.
730
+ // Inspect the unwrapped provider message, not its JSON spelling or unrelated envelope fields.
731
+ const NON_VERDICT_CONTEXT = /(?:\b(?:not|never|no|neither|nor|if|unless|whether)\b|n['\u2019]t\b)[^.!?\n]{0,100}\b(?:context(?:\s+(?:window|length))?|tokens?|(?:input|prompt)\s+is\s+too\s+long)\b|\b(?:context\s+(?:window|length)|token\s+limit|(?:input|prompt)\s+is\s+too\s+long)\b[^.!?\n]{0,40}\?/i;
732
+ const CONTEXT_CONFIG_FAILURE = /\b(?:fail(?:ed|ure)?|unable|cannot|error)\b[^.!?\n]{0,100}\b(?:configuration|settings|documentation)\b|\b(?:configuration|settings|documentation)\b[^.!?\n]{0,100}\b(?:fail(?:ed|ure)?|unavailable|missing|error)\b/i;
733
+ const CONTEXT_THROUGHPUT = /\bper (?:second|minute|hour|day)\b|\brate limit|\bquota\b|\btpm\b/i;
734
+
735
+ function retryContextOverflowMessage(message: string): boolean {
736
+ if (CONTEXT_THROUGHPUT.test(message)) return false;
737
+ return message.split(/(?<=[.!?])\s+|[\r\n]+/).some(sentence => {
738
+ if (NON_VERDICT_CONTEXT.test(sentence) || CONTEXT_CONFIG_FAILURE.test(sentence)) return false;
739
+ const withoutGenericThrottle = sentence.replace(/too many tokens/gi, "");
740
+ return isDefiniteContextOverflow(503, withoutGenericThrottle)
741
+ || /\bprompt is too long\b/i.test(sentence);
742
+ });
743
+ }
744
+
745
+ /** Up to `maxBytes` of a clone of the body, or what arrived before the deadline. */
746
+ async function peekBodyText(res: Response, maxBytes: number, deadlineMs: number, signal?: AbortSignal): Promise<string> {
747
+ const reader = res.clone().body?.getReader();
748
+ if (!reader) return "";
749
+ const decoder = new TextDecoder();
750
+ let text = "";
751
+ let bytes = 0;
752
+ let emptyChunks = 0;
753
+ const deadlineAt = performance.now() + deadlineMs;
754
+ let timer: ReturnType<typeof setTimeout> | undefined;
755
+ let stop = () => {};
756
+ const timedOut = new Promise<null>(resolve => {
757
+ stop = () => resolve(null);
758
+ timer = setTimeout(stop, deadlineMs);
759
+ signal?.addEventListener("abort", stop, { once: true });
760
+ if (signal?.aborted) stop();
761
+ });
762
+ try {
763
+ while (bytes < maxBytes) {
764
+ if (signal?.aborted || performance.now() >= deadlineAt) break;
765
+ const chunk = await Promise.race([reader.read(), timedOut]);
766
+ if (!chunk || chunk.done) break;
767
+ if (chunk.value.byteLength === 0) {
768
+ if (++emptyChunks % 64 === 0) await new Promise<void>(resolve => setTimeout(resolve, 0));
769
+ continue;
770
+ }
771
+ emptyChunks = 0;
772
+ const bounded = chunk.value.subarray(0, maxBytes - bytes);
773
+ bytes += bounded.byteLength;
774
+ text += decoder.decode(bounded, { stream: true });
775
+ }
776
+ return text;
777
+ } finally {
778
+ clearTimeout(timer);
779
+ signal?.removeEventListener("abort", stop);
780
+ reader.cancel().catch(() => {});
781
+ }
782
+ }
783
+
784
+ /**
785
+ * True when a transient-status response's body is a definite context-overflow verdict. Peeks a
786
+ * clone within a byte and time bound, so the caller still receives the untouched body. A slow
787
+ * or endless body keeps the normal retry unless its observed prefix already proves overflow.
788
+ * "Too many tokens" alone is not enough here: a 5xx
789
+ * "Too many tokens, please wait" is a throttle that the retry exists for.
790
+ */
791
+ async function isContextOverflowResponse(res: Response, signal?: AbortSignal): Promise<boolean> {
792
+ if ((res.headers.get("content-type") ?? "").includes("text/event-stream")) return false;
793
+ try {
794
+ const text = await peekBodyText(res, CONTEXT_OVERFLOW_PEEK_BYTES, CONTEXT_OVERFLOW_PEEK_MS, signal);
795
+ return text.length > 0 && isDefiniteContextOverflow(res.status, text, retryContextOverflowMessage);
796
+ } catch {
797
+ return false;
798
+ }
799
+ }
800
+
721
801
  /**
722
802
  * fetchWithResetRetry plus the caller-selected transient-5xx policy, PRE-STREAM only.
723
803
  * A received HTTP error follows that policy; an ambiguous reset's non-replayable
@@ -747,7 +827,7 @@ export async function fetchWithTransientRetry(
747
827
  const countedFetch: ReplayableFetch = (recovery) => {
748
828
  // Incremented BEFORE the await so a rejected send still consumes budget; counting only
749
829
  // successes would let a reset storm loop without bound.
750
- if (opts.onSendsConsumed?.beforeSend && !opts.onSendsConsumed.beforeSend()) throw new SendBudgetExhaustedError(opts.label);
830
+ if (opts.onSendsConsumed?.beforeSend && !opts.onSendsConsumed.beforeSend()) throw new SendBudgetExhaustedError(opts.destination ?? (opts.label ? errorDestinationLabel(opts.label) : undefined));
751
831
  sent += 1;
752
832
  const run = () => doFetch(recovery);
753
833
  return opts.onSendsConsumed?.execute ? opts.onSendsConsumed.execute(run) : run();
@@ -769,7 +849,7 @@ export async function fetchWithTransientRetry(
769
849
  // and throws from one, and a caller sharing the budget across request legs must be told the
770
850
  // real count on every one of them.
771
851
  try {
772
- if (budget === 0) throw new SendBudgetExhaustedError(opts.label);
852
+ if (budget === 0) throw new SendBudgetExhaustedError(opts.destination ?? (opts.label ? errorDestinationLabel(opts.label) : undefined));
773
853
  let attemptStart = Date.now();
774
854
  let res = await fetchWithResetRetry(countedFetch, innerResetOptions());
775
855
  for (let attempt = 0; sent < budget; attempt++) {
@@ -779,10 +859,13 @@ export async function fetchWithTransientRetry(
779
859
  // thing about its own failure, so the ladder stops and hands the response back untouched.
780
860
  if (res.ok || !isTransientUpstreamStatus(res.status) || isNonReplayableResponse(res)
781
861
  || res.headers.get(REPLAY_REFUSAL_NO_RETRY_HEADER) === REPLAY_REFUSAL_NO_RETRY_VALUE) return res;
862
+ if (opts.abortSignal?.aborted || Date.now() - attemptStart > slowAttemptMs) return res;
863
+ // A 5xx that says the input does not fit is deterministic: resending the same body is
864
+ // refused the same way, so it goes back for the caller to classify (#8127).
865
+ if (await isContextOverflowResponse(res, opts.abortSignal)) return res;
782
866
  // Checked before cancelResponseBodyBestEffort so an already-aborted caller never receives
783
867
  // a response whose body we just cancelled.
784
868
  if (opts.abortSignal?.aborted) return res;
785
- if (Date.now() - attemptStart > slowAttemptMs) return res;
786
869
  const instructedDelay = retryAfterDelayMs(res.headers);
787
870
  // The deadline is the CALLER'S, not this module's default. Reading the constant directly
788
871
  // broke it in both directions: a caller with a 30s budget slept the full 45s an upstream
@@ -17,7 +17,8 @@ export interface WindowsPrivateEntry {
17
17
  * - "write-private": the POSIX mode&022==0 analog for objects we did NOT create — the
18
18
  * serving token or a kernel-equivalent owner (SYSTEM, Administrators, TrustedInstaller)
19
19
  * must own the object, and no grantee outside the trusted write set may hold write,
20
- * create, delete or DACL/owner control. Read grants to anyone are fine.
20
+ * create, delete or DACL/owner control, including inherit-only templates for
21
+ * children this process may create. Read grants to anyone are fine.
21
22
  * - "trusted-ancestry": the POSIX uid∈{euid,0} + non-shared-writable ancestor analog.
22
23
  * The owner must be the serving token or a kernel-equivalent owner (SYSTEM,
23
24
  * Administrators, TrustedInstaller — each can already take ownership of any object,
@@ -26,6 +27,9 @@ export interface WindowsPrivateEntry {
26
27
  * (FILE_ADD_FILE / FILE_ADD_SUBDIRECTORY without delete or write-existing): that is
27
28
  * the closest NTFS analog of a root-owned sticky directory such as C:\, whose stock
28
29
  * ACL grants Authenticated Users add-subdirectory while refusing every other write.
30
+ * This policy checks existing ancestors only and ignores inherit-only templates;
31
+ * callers must use write-private or the stricter private policy for every direct
32
+ * parent of a new child.
29
33
  */
30
34
  export type WindowsAclPolicy = "private" | "private-runtime-directory" | "write-private" | "trusted-ancestry";
31
35
  export interface WindowsAclEntry extends WindowsPrivateEntry {
@@ -117,14 +121,20 @@ try {
117
121
  `;
118
122
  const ENCODED_ACL_SCRIPT = Buffer.from(ACL_SCRIPT, "utf16le").toString("base64");
119
123
 
124
+ /** Above this many paths the script reads them from stdin, keeping one process for a whole tree. */
125
+ const ACL_ENV_PATH_LIMIT = 16;
126
+
120
127
  function defaultWindowsOwnerAclRunner(entries: readonly WindowsPrivateEntry[], timeoutMs: number): WindowsOwnerAclResult {
121
- const env: Record<string, string | undefined> = { ...process.env, OCX_ACL_COUNT: String(entries.length), OCX_ACL_STDIN: "0" };
122
- for (let i = 0; i < entries.length; i++) env[`OCX_ACL_PATH_${i}`] = entries[i]!.path;
128
+ const viaStdin = entries.length > ACL_ENV_PATH_LIMIT;
129
+ const env: Record<string, string | undefined> = { ...process.env, OCX_ACL_COUNT: String(entries.length), OCX_ACL_STDIN: viaStdin ? "1" : "0" };
130
+ if (!viaStdin) for (let i = 0; i < entries.length; i++) env[`OCX_ACL_PATH_${i}`] = entries[i]!.path;
131
+ // Base64 lines are data, as in the async runner; no path text becomes PowerShell source.
132
+ const input = viaStdin ? Buffer.from(entries.map(entry => Buffer.from(entry.path, "utf8").toString("base64")).join("\n") + "\n") : undefined;
123
133
  const result = Bun.spawnSync([
124
134
  resolveTrustedWindowsPowerShellExe(), "-NoLogo", "-NoProfile", "-NonInteractive",
125
135
  "-ExecutionPolicy", "Bypass", "-EncodedCommand", ENCODED_ACL_SCRIPT,
126
136
  ], {
127
- env, stdin: "ignore", stdout: "pipe", stderr: "ignore",
137
+ env, stdin: input ?? "ignore", stdout: "pipe", stderr: "ignore",
128
138
  timeout: timeoutMs, windowsHide: true,
129
139
  });
130
140
  return { success: result.success, timedOut: result.exitedDueToTimeout ?? false, stdout: result.stdout ?? new Uint8Array() };
@@ -243,9 +253,9 @@ function privateEntryOk(entry: ParsedEntry | null, directory: boolean, run: Pars
243
253
  * Confined-write and trusted-ancestry policies for objects this process did not create.
244
254
  *
245
255
  * Deny ACEs are permitted because they can only remove access; allow ACEs must be
246
- * ordinary non-callback CommonAce entries. Inherit-only ACEs are skipped: they are
247
- * templates for children, and every object this module protects carries its own
248
- * hardened protected DACL, so an ancestor's template cannot grant anything inside it.
256
+ * ordinary non-callback CommonAce entries. Write-private also checks inherit-only
257
+ * templates: newly created children receive those grants before hardening. Existing
258
+ * trusted ancestors are not creation parents; each descendant is checked separately.
249
259
  */
250
260
  function confinedEntryOk(entry: ParsedEntry | null, run: ParsedAclRun, policy: WindowsAclPolicy): boolean {
251
261
  if (!entry || entry.aces === null || (entry.controlFlags & 0x4 /* SE_DACL_PRESENT */) === 0) return false;
@@ -262,9 +272,12 @@ function confinedEntryOk(entry: ParsedEntry | null, run: ParsedAclRun, policy: W
262
272
  if (ace.type === 1) continue; // ACCESS_DENIED: removes access, never grants it.
263
273
  if (ace.type !== 0) return false; // only ACCESS_ALLOWED records can be evaluated.
264
274
  if (ace.flags === null || ace.mask === null || ace.sid === null) return false;
265
- if ((ace.flags & INHERIT_ONLY_ACE) !== 0) continue;
275
+ if (policy === "trusted-ancestry" && (ace.flags & INHERIT_ONLY_ACE) !== 0) continue;
266
276
  if (ace.sid === run.user || TRUSTED_WRITE_SIDS.has(ace.sid)) continue;
267
- const createOk = policy === "trusted-ancestry" && STICKY_OWNERS.has(owner) ? CREATE_MASK : 0;
277
+ // Create rights on a sticky trusted ancestor are safe for that ancestor itself,
278
+ // but an inherit-only template would grant them inside a newly created child.
279
+ const createOk = policy === "trusted-ancestry" && STICKY_OWNERS.has(owner)
280
+ && (ace.flags & INHERIT_ONLY_ACE) === 0 ? CREATE_MASK : 0;
268
281
  const allowed = (READ_MASK | createOk) >>> 0;
269
282
  if (((ace.mask >>> 0) & ~allowed) !== 0) return false;
270
283
  }
package/src/lib/winsw.ts CHANGED
@@ -16,9 +16,9 @@
16
16
  import { createHash } from "node:crypto";
17
17
  import { execFileSync } from "node:child_process";
18
18
  import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
19
- import { homedir } from "node:os";
20
19
  import { join, resolve, win32 } from "node:path";
21
20
  import { expandUserPath, getConfigDir, loadConfig } from "../config";
21
+ import { resolveCodexHomeDir } from "../codex/home";
22
22
  import { recordOwnedConfigPath } from "./config-ownership";
23
23
  import { BUN_RUNTIME_PATH_ENV, BUN_RUNTIME_SOURCE_ENV, durableBunRuntime, type DurableBunRuntime } from "./bun-runtime";
24
24
  import type { BunRuntimeSource } from "./bun-runtime";
@@ -59,9 +59,9 @@ function xmlEscape(value: string): string {
59
59
  .replace(/'/g, "&apos;");
60
60
  }
61
61
 
62
- function currentCodexHomeAbsolute(): string {
63
- const raw = process.env.CODEX_HOME?.trim();
64
- return raw ? resolve(expandUserPath(raw)) : join(homedir(), ".codex");
62
+ function currentCodexHomeAbsolute(env: NodeJS.ProcessEnv = process.env): string {
63
+ const raw = env.CODEX_HOME?.trim();
64
+ return raw ? windowsServicePathAbsolute(raw) : resolveCodexHomeDir({ env });
65
65
  }
66
66
 
67
67
  function windowsServicePathAbsolute(raw: string): string {
@@ -109,7 +109,7 @@ export function buildWinswXml(entry: WinswEntry, env: NodeJS.ProcessEnv = proces
109
109
  ` <env name="${BUN_RUNTIME_PATH_ENV}" value="${xmlEscape(entry.bun)}"/>`,
110
110
  ` <env name="OCX_API_TOKEN_FILE" value="${xmlEscape(serviceApiTokenFilePath())}"/>`,
111
111
  ` <env name="PATH" value="${xmlEscape(filterTransientServicePath(env.PATH ?? "", ";", "win32"))}"/>`,
112
- env.CODEX_HOME?.trim() ? ` <env name="CODEX_HOME" value="${xmlEscape(currentCodexHomeAbsolute())}"/>` : null,
112
+ ` <env name="CODEX_HOME" value="${xmlEscape(currentCodexHomeAbsolute(env))}"/>`,
113
113
  env.CODEX_SQLITE_HOME?.trim() ? ` <env name="CODEX_SQLITE_HOME" value="${xmlEscape(windowsServicePathAbsolute(env.CODEX_SQLITE_HOME.trim()))}"/>` : null,
114
114
  ` <env name="OPENCODEX_HOME" value="${xmlEscape(getConfigDir())}"/>`,
115
115
  aclTimeout ? ` <env name="OPENCODEX_ACL_TIMEOUT_MS" value="${xmlEscape(aclTimeout)}"/>` : null,
@@ -245,7 +245,9 @@ export function workflowDenialSummary(
245
245
  // because the alternative is an operator who can see that something refused and has
246
246
  // no way to find out what. Without one -- a caller that knows only the reason -- the
247
247
  // original sentence is kept unchanged.
248
- message: spend
248
+ message: spend && Object.hasOwn(SPEND_SCOPE_LABEL, spend.scope)
249
+ && Number.isSafeInteger(spend.limit) && spend.limit >= 0
250
+ && (spend.projected === undefined || (Number.isSafeInteger(spend.projected) && spend.projected >= 0))
249
251
  ? "This proxy refused the request locally: the configured " + SPEND_SCOPE_LABEL[spend.scope]
250
252
  + " token ceiling of " + formatTokenCount(spend.limit) + " is spent"
251
253
  + (spend.projected !== undefined
@@ -14,6 +14,7 @@ const SSH_TRANSPORT_FAILURE = 255;
14
14
 
15
15
  /** Remote argv that prints the kernel name; under cmd or PowerShell, `sh` itself is refused. */
16
16
  export const REMOTE_UNAME_ARGV: readonly string[] = ["sh", "-c", "uname -s 2>/dev/null", "ocx-platform"];
17
+ const REMOTE_FRAMED_UNAME_ARGV: readonly string[] = ["sh", "-c", "printf 'ocx-platform:%s\\n' \"$(uname -s 2>/dev/null)\"", "ocx-platform"];
17
18
 
18
19
  /** Does this output come from cmd.exe or PowerShell refusing a POSIX command? */
19
20
  export function isWindowsShellRefusal(output: string): boolean {
@@ -64,3 +65,16 @@ export async function requireRemotePlatform(runner: Pick<SshRunner, "run">, alia
64
65
  if (platform === "unknown") throw new Error("Remote platform could not be determined");
65
66
  return platform;
66
67
  }
68
+
69
+ /** Fan-out ignores login-shell output and trusts only one framed uname line. */
70
+ export async function requireRemotePlatformFramed(runner: Pick<SshRunner, "run">, alias: string, knownHostsFile: string): Promise<"posix" | "windows"> {
71
+ const windows = await runner.run(buildWindowsProbeArgv({ alias, knownHostsFile }), { timeoutMs: 10_000 });
72
+ if (windows.code === SSH_TRANSPORT_FAILURE) throw new Error("SSH platform discovery failed");
73
+ if (windows.code === 0 && windows.stdout.split(/\r?\n/).some(line => line.trim() === "Windows_NT")) return "windows";
74
+ const result = await runner.run(buildExecArgv({ alias, knownHostsFile, argv: REMOTE_FRAMED_UNAME_ARGV }), { timeoutMs: 10_000 });
75
+ if (result.code === SSH_TRANSPORT_FAILURE) throw new Error("SSH platform discovery failed");
76
+ const frames = result.stdout.split(/\r?\n/).filter(line => line.startsWith("ocx-platform:"));
77
+ const name = frames.length === 1 ? frames[0]!.slice("ocx-platform:".length) : "";
78
+ if (result.code !== 0 || !POSIX_UNAME.test(name)) throw new Error("Remote platform could not be determined");
79
+ return WINDOWS_UNAME.test(name) ? "windows" : "posix";
80
+ }
@@ -10,13 +10,30 @@ export const POWERSHELL_ENCODED_MAX = 8_000;
10
10
  export function powershellArgv(script: string): string[] {
11
11
  // Module preparation otherwise writes a CLIXML progress record to stderr, which Home would see.
12
12
  const encoded = Buffer.from("$ProgressPreference='SilentlyContinue'\n" + script, "utf16le").toString("base64");
13
- if (encoded.length > POWERSHELL_ENCODED_MAX) throw new Error("Remote PowerShell command exceeds the cmd.exe-compatible command-line budget");
13
+ if (encoded.length > POWERSHELL_ENCODED_MAX) throw new Error(`Remote PowerShell command exceeds the cmd.exe-compatible command-line budget (${encoded.length})`);
14
14
  return ["powershell.exe", "-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", encoded];
15
15
  }
16
16
 
17
17
  /** Exit status when the remote ocx cannot be contained; nothing ran. */
18
18
  export const WINDOWS_CONTAINMENT_EXIT = 126;
19
19
 
20
+ const SCRIPT_PACKED_PREFIX = "$ocxPacked='";
21
+ /**
22
+ * The whole script travels deflated and is inflated on the Child before anything in it exists,
23
+ * including Fail. A session that cannot inflate it (Constrained Language Mode blocks the stream
24
+ * types) must still exit 126, so only the inflate is guarded: Invoke-Expression stays outside the
25
+ * try, and the inflated script's own errors and exit status are never relabelled as containment.
26
+ */
27
+ export function packedPowerShellArgv(script: string): string[] {
28
+ const bytes = deflateRawSync(Buffer.from(script, "utf8"), { level: 9 });
29
+ const packed = Array.from(bytes, byte => String.fromCharCode(byte + 256)).join("");
30
+ return powershellArgv(`${SCRIPT_PACKED_PREFIX}${packed}'\n` + String.raw`$ErrorActionPreference='Stop';try{$b=[byte[]]@($ocxPacked.ToCharArray()|%{[int]$_-256});$r=[IO.StreamReader]::new([IO.Compression.DeflateStream]::new([IO.MemoryStream]::new($b),[IO.Compression.CompressionMode]::Decompress));$s=$r.ReadToEnd()}catch{try{[Console]::Error.WriteLine('Refusing to run ocx.exe outside a kill-on-close job.')}catch{$null=$_};exit ${WINDOWS_CONTAINMENT_EXIT}};Invoke-Expression $s`);
31
+ }
32
+ function unpackPowerShell(script: string): string {
33
+ const match = /\$ocxPacked='([^']+)'/.exec(script);
34
+ return match ? inflateRawSync(Buffer.from(Array.from(match[1]!, ch => ch.charCodeAt(0) - 256))).toString("utf8") : script;
35
+ }
36
+
20
37
  /**
21
38
  * OcxJob, compiled on the Child with Add-Type, contains the remote ocx. Run creates the process
22
39
  * with PROC_THREAD_ATTRIBUTE_JOB_LIST (STARTUPINFOEX, EXTENDED_STARTUPINFO_PRESENT), so it is a
@@ -50,6 +67,12 @@ export const OCX_JOB_SOURCE = [
50
67
  "var q=Process.Start(new ProcessStartInfo(x,\"--version\"){UseShellExecute=false,RedirectStandardInput=true,RedirectStandardOutput=true,RedirectStandardError=true});",
51
68
  "q.StandardInput.Close();q.StandardOutput.ReadToEndAsync();q.StandardError.ReadToEndAsync();",
52
69
  "if(q.WaitForExit(10000))return q.ExitCode==0;q.Kill();}catch{return false;}return false;}",
70
+ "public static string V(string x){Process q=null;try{",
71
+ "q=Process.Start(new ProcessStartInfo(x,\"--version\"){UseShellExecute=false,RedirectStandardInput=true,RedirectStandardOutput=true,RedirectStandardError=true});q.StandardInput.Close();",
72
+ "var p=q;var read=System.Threading.Tasks.Task.Run(()=>{var b=new char[257];int n=0,k;while(n<257&&(k=p.StandardOutput.Read(b,n,257-n))>0)n+=k;return n>256?null:new string(b,0,n);});",
73
+ "System.Threading.Tasks.Task.Run(()=>{var b=new char[1024];while(p.StandardError.Read(b,0,b.Length)>0){} });",
74
+ "var clock=Stopwatch.StartNew();var done=System.Threading.Tasks.Task.Run(()=>p.WaitForExit());if(!read.Wait(10000)||read.Result==null||!done.Wait(Math.Max(0,10000-(int)clock.ElapsedMilliseconds))){q.Kill();q.WaitForExit();return null;}return q.ExitCode==0?read.Result:null;",
75
+ "}catch{try{if(q!=null&&!q.HasExited){q.Kill();q.WaitForExit();}}catch{return null;}return null;}finally{if(q!=null)q.Dispose();}}",
53
76
  "public static int Run(string x,string c){",
54
77
  "IntPtr z=IntPtr.Zero,j=z,l=z,v=z,h=z,t=z;bool listed=false,done=false;",
55
78
  "try{",
@@ -69,20 +92,21 @@ export const OCX_JOB_SOURCE = [
69
92
  ].join("\n");
70
93
 
71
94
  /**
72
- * The helper travels deflated so the whole command fits cmd.exe's line; PowerShell inflates it and
73
- * hands the text to Add-Type. It is never evaluated as PowerShell.
95
+ * The helper reaches Add-Type as a quoted literal inside the packed script; it is never evaluated
96
+ * as PowerShell.
74
97
  */
75
- const OCX_JOB_PACKED = deflateRawSync(Buffer.from(OCX_JOB_SOURCE, "utf8"), { level: 9 }).toString("base64");
76
-
77
98
  const NATIVE_PROCESS = String.raw`$ErrorActionPreference='Stop'
78
99
  function Fail{try{[Console]::Error.WriteLine('Refusing to run ocx.exe outside a kill-on-close job.')}catch{$null=$_};exit 126}
79
- try{Add-Type ([IO.StreamReader]::new([IO.Compression.DeflateStream]::new([IO.MemoryStream]::new([Convert]::FromBase64String('` + OCX_JOB_PACKED + String.raw`')),[IO.Compression.CompressionMode]::Decompress)).ReadToEnd())}catch{Fail}
100
+ try{Add-Type '` + OCX_JOB_SOURCE.replaceAll("'", "''") + String.raw`'}catch{Fail}
80
101
  function Quote-Native([string]$v){'"'+[regex]::Replace([regex]::Replace($v,'(\\*)"','$1$1\"'),'(\\+)$','$1$1')+'"'}
81
102
  function Invoke-Native([string]$e,[string[]]$a){try{$c=[OcxJob]::Run($e,((@($e)+$a|%{Quote-Native $_}) -join ' '))}catch{Fail};exit $c}
82
103
  `;
83
104
 
84
105
  /** The packed helper a script carries, inflated; for tests that check the transport. */
85
106
  export function windowsScriptHelperSource(script: string): string | undefined {
107
+ script = unpackPowerShell(script);
108
+ const source = /try\{Add-Type '([\s\S]*?)'\}catch\{Fail\}/.exec(script);
109
+ if (source) return source[1]!.replaceAll("''", "'");
86
110
  const match = /FromBase64String\('([A-Za-z0-9+/=]+)'\)\),\[IO\.Compression\.CompressionMode\]::Decompress\)\)\.ReadToEnd\(\)/.exec(script);
87
111
  if (!match) return undefined;
88
112
  return inflateRawSync(Buffer.from(match[1]!, "base64")).toString("utf8");
@@ -103,6 +127,7 @@ function dataLine(value: { executable?: string; args: readonly string[] }): stri
103
127
  * undefined for any other script. Test fixtures decode with this, never with their own pattern.
104
128
  */
105
129
  export function windowsScriptData(script: string): { executable?: string; args: string[] } | undefined {
130
+ script = unpackPowerShell(script);
106
131
  const start = script.indexOf(DATA_OPEN);
107
132
  const end = start < 0 ? -1 : script.indexOf(DATA_CLOSE, start + DATA_OPEN.length);
108
133
  if (end < 0) return undefined;
@@ -112,23 +137,40 @@ export function windowsScriptData(script: string): { executable?: string; args:
112
137
  }
113
138
 
114
139
  export function windowsNativeArgv(executable: string, args: readonly string[]): string[] {
115
- return powershellArgv(NATIVE_PROCESS + dataLine({ executable, args }) + "Invoke-Native $d.executable @($d.args)\n");
140
+ return packedPowerShellArgv(NATIVE_PROCESS + dataLine({ executable, args }) + "Invoke-Native $d.executable @($d.args)\n");
116
141
  }
117
142
 
118
143
  /**
119
144
  * Desktop first, then the GOAT-managed current junction, then legacy and PATH candidates. Each
120
145
  * must answer --version within ten seconds; only the selected one runs the real command.
121
146
  */
122
- export function windowsOcxArgv(args: readonly string[]): string[] {
123
- return powershellArgv(NATIVE_PROCESS + dataLine({ args }) + String.raw`$u=$env:USERPROFILE;$c=@("$u\.opencodex-desktop\bin\ocx.exe","$u\.local\share\goat\opencodex\current\ocx.exe","$u\.local\bin\ocx.exe")
147
+ const OCX_CANDIDATES = String.raw`$u=$env:USERPROFILE;$c=@("$u\.opencodex-desktop\bin\ocx.exe","$u\.local\share\goat\opencodex\current\ocx.exe","$u\.local\bin\ocx.exe")
124
148
  if($env:LOCALAPPDATA){$c+="$env:LOCALAPPDATA\Programs\OpenCodex\ocx.exe"}
125
149
  if($env:ProgramFiles){$c+="$env:ProgramFiles\OpenCodex\ocx.exe"}
126
150
  $c+=@((Get-Command ocx.exe -Type Application -EA 0).Source)
151
+ `;
152
+ export function windowsOcxArgv(args: readonly string[]): string[] {
153
+ return packedPowerShellArgv(NATIVE_PROCESS + dataLine({ args }) + OCX_CANDIDATES + String.raw`
127
154
  foreach($x in ($c|select -Unique)){if([IO.File]::Exists($x)-and[OcxJob]::Ok($x)){Invoke-Native $x @($d.args)}}
128
155
  [Console]::Error.WriteLine('No runnable ocx.exe found; install the Windows standalone archive.');exit 127
129
156
  `);
130
157
  }
131
158
 
159
+ export function windowsPinnedSyncArgv(linkId: string): string[] {
160
+ return packedPowerShellArgv(NATIVE_PROCESS + dataLine({ args: ["sync", "--expect-link", linkId, "--json"] }) + OCX_CANDIDATES + String.raw`
161
+ foreach($x in ($c|select -Unique)){
162
+ if(![IO.File]::Exists($x)){continue};$v=[OcxJob]::V($x);if($null -eq $v){continue};$v=$v.Trim();if($v.StartsWith('opencodex ')){$v=$v.Substring(10)}
163
+ $m=[regex]::Match($v,'^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-([0-9A-Za-z.-]+))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$')
164
+ $bad=(!$m.Success -or $v.Length -gt 128);if(!$bad -and $m.Groups[4].Success){foreach($p in $m.Groups[4].Value.Split('.')){if(!$p -or ($p -match '^\d+$' -and $p.Length -gt 1 -and $p[0] -eq '0')){$bad=$true}}}
165
+ if($bad){[Console]::Error.WriteLine('ocx-fanout:child-ocx-version-unknown');exit 121}
166
+ $a=@($m.Groups[1].Value,$m.Groups[2].Value,$m.Groups[3].Value);$b=@('2','93','0');$cmp=0
167
+ for($i=0;$i -lt 3;$i++){if($a[$i].Length -ne $b[$i].Length){$cmp=$a[$i].Length-$b[$i].Length;break};$cmp=[string]::CompareOrdinal($a[$i],$b[$i]);if($cmp -ne 0){break}}
168
+ if($cmp -lt 0 -or ($cmp -eq 0 -and $m.Groups[4].Success)){[Console]::Error.WriteLine('ocx-fanout:child-ocx-lacks-expect-link');exit 121}
169
+ [Console]::Error.WriteLine('ocx-fanout:selected:'+$v);[Console]::Out.WriteLine('ocx-fanout:stdout-begin');Invoke-Native $x @($d.args)
170
+ };exit 127
171
+ `);
172
+ }
173
+
132
174
  /** Credential-free loopback probe of the Child; no proxy, no redirect, bounded body and deadline. */
133
175
  export function windowsChildHttpArgv(port: number, path: "healthz" | "v1/catalog", timeoutMs: number): string[] {
134
176
  if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("invalid Child port");
@@ -19,7 +19,7 @@
19
19
  */
20
20
 
21
21
  import { isAbsolute } from "node:path";
22
- import { POWERSHELL_ENCODED_MAX, windowsOcxArgv } from "./remote-windows";
22
+ import { POWERSHELL_ENCODED_MAX, windowsOcxArgv, windowsPinnedSyncArgv } from "./remote-windows";
23
23
 
24
24
  export type TunnelDirection = "R" | "L";
25
25
 
@@ -146,6 +146,16 @@ export const REMOTE_PLATFORM_UNSUPPORTED = 125;
146
146
  * ocx as `"$@"` without another round of parsing. Desktop binaries precede PATH candidates;
147
147
  * each candidate must run --version successfully. A missing runnable ocx exits 127.
148
148
  */
149
+ const REMOTE_OCX_CANDIDATES = `for candidate in "$HOME/.opencodex-desktop/bin/ocx" "/Applications/OpenCodex.app/Contents/MacOS/ocx" "/usr/bin/ocx"; do
150
+ try_ocx "$candidate" "$@"
151
+ done
152
+ remaining=$PATH
153
+ while :; do
154
+ directory=\${remaining%%:*}
155
+ try_ocx "\${directory:-.}/ocx" "$@"
156
+ case "$remaining" in *:*) remaining=\${remaining#*:};; *) break;; esac
157
+ done`;
158
+
149
159
  export const REMOTE_OCX_SCRIPT = `export PATH="$PATH:$HOME/.bun/bin:$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin"
150
160
  case "$(uname -s 2>/dev/null)" in Windows*|MSYS*|MINGW*|CYGWIN*) exit ${REMOTE_PLATFORM_UNSUPPORTED};; esac
151
161
  try_ocx() {
@@ -155,15 +165,7 @@ try_ocx() {
155
165
  exec "$executable" "$@"
156
166
  fi
157
167
  }
158
- for candidate in "$HOME/.opencodex-desktop/bin/ocx" "/Applications/OpenCodex.app/Contents/MacOS/ocx" "/usr/bin/ocx"; do
159
- try_ocx "$candidate" "$@"
160
- done
161
- remaining=$PATH
162
- while :; do
163
- directory=\${remaining%%:*}
164
- try_ocx "\${directory:-.}/ocx" "$@"
165
- case "$remaining" in *:*) remaining=\${remaining#*:};; *) break;; esac
166
- done
168
+ ${REMOTE_OCX_CANDIDATES}
167
169
  exit ${REMOTE_COMMAND_NOT_FOUND}`;
168
170
 
169
171
  export function remoteOcxArgv(args: readonly string[], platform: "posix" | "windows" = "posix"): string[] {
@@ -238,3 +240,54 @@ export function quoteRemote(argv: readonly string[]): string {
238
240
  return `'${arg.replaceAll("'", `'"'"'`)}'`;
239
241
  }).join(" ");
240
242
  }
243
+
244
+ const REMOTE_PINNED_SYNC_SCRIPT = `export PATH="$PATH:$HOME/.bun/bin:$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin"
245
+ case "$(uname -s 2>/dev/null)" in Windows*|MSYS*|MINGW*|CYGWIN*) exit ${REMOTE_PLATFORM_UNSUPPORTED};; esac
246
+ umask 077
247
+ dir=$(mktemp -d "\${TMPDIR:-/tmp}/ocx-fanout.XXXXXXXX") || exit 127
248
+ tmp=$dir/version; ready=$dir/ready
249
+ trap 'rm -rf "$dir"' EXIT HUP INT TERM
250
+ try_ocx() {
251
+ c=$1; shift
252
+ [ -x "$c" ] || return
253
+ ( ulimit -c 0; ulimit -f 1; exec "$c" --version ) >"$tmp" 2>/dev/null & vp=$!
254
+ ( sleep 10 & timer=$!; trap 'kill "$timer" 2>/dev/null; wait "$timer" 2>/dev/null; exit' TERM HUP INT; : > "$ready"; wait "$timer" 2>/dev/null; kill -9 "$vp" 2>/dev/null ) >/dev/null 2>&1 & watchdog=$!
255
+ while [ ! -f "$ready" ]; do kill -0 "$watchdog" 2>/dev/null || break; sleep 0.01 >/dev/null 2>&1; done
256
+ { wait "$vp"; status=$?; } 2>/dev/null
257
+ kill "$watchdog" 2>/dev/null; wait "$watchdog" 2>/dev/null; rm -f "$ready"
258
+ [ "$status" -eq 0 ] || return
259
+ bytes=$(wc -c < "$tmp" 2>/dev/null) || return
260
+ [ "$bytes" -le 256 ] 2>/dev/null || return
261
+ version=$(cat "$tmp"); version=\${version#opencodex }
262
+ printf '%s\\n' "$version" | awk '
263
+ function idlist(s,pre, n,a,i) {
264
+ n=split(s,a,/\\./); if (!n) return 0;
265
+ for(i=1;i<=n;i++) if(a[i]=="" || a[i] !~ /^[0-9A-Za-z-]+$/ || (pre && a[i] ~ /^[0-9]+$/ && length(a[i])>1 && substr(a[i],1,1)=="0")) return 0;
266
+ return 1
267
+ }
268
+ function cmp(a,b) { if(length(a)!=length(b)) return length(a)>length(b)?1:-1; return ("x" a)==("x" b)?0:(("x" a)>("x" b)?1:-1) }
269
+ NR==1 {
270
+ v=$0; if(length(v)>128) { result=2; next }
271
+ plus=index(v,"+"); if(plus) { build=substr(v,plus+1); v=substr(v,1,plus-1); if(!idlist(build,0)) {result=2; next} }
272
+ dash=index(v,"-"); if(dash) { pre=substr(v,dash+1); v=substr(v,1,dash-1); if(!idlist(pre,1)) {result=2; next} }
273
+ if(split(v,a,/\\./)!=3) { result=2; next }
274
+ for(i=1;i<=3;i++) if(a[i] !~ /^(0|[1-9][0-9]*)$/) { result=2; next }
275
+ c=cmp(a[1],"2"); if(!c)c=cmp(a[2],"93"); if(!c)c=cmp(a[3],"0"); if(c<0 || (!c && dash))result=1
276
+ }
277
+ NR>1 {result=2}
278
+ END {exit result}
279
+ ' 2>/dev/null
280
+ status=$?
281
+ if [ "$status" -eq 1 ]; then printf '%s\\n' 'ocx-fanout:child-ocx-lacks-expect-link' >&2; exit 121; fi
282
+ if [ "$status" -ne 0 ]; then printf '%s\\n' 'ocx-fanout:child-ocx-version-unknown' >&2; exit 121; fi
283
+ rm -rf "$dir"; trap - EXIT HUP INT TERM
284
+ printf 'ocx-fanout:selected:%s\\n' "$version" >&2
285
+ printf '%s\\n' 'ocx-fanout:stdout-begin'
286
+ exec "$c" sync --expect-link "$1" --json
287
+ }
288
+ ${REMOTE_OCX_CANDIDATES}
289
+ exit ${REMOTE_COMMAND_NOT_FOUND}`;
290
+
291
+ export function remotePinnedSyncArgv(linkId: string, platform: "posix" | "windows" = "posix"): string[] {
292
+ return platform === "windows" ? windowsPinnedSyncArgv(linkId) : ["sh", "-c", REMOTE_PINNED_SYNC_SCRIPT, "ocx", linkId];
293
+ }
@@ -1,3 +1,4 @@
1
+ import { clientFacingModelText, type ClientFacingModelLabel } from "../lib/error-destination";
1
2
  import { isBuiltinAnthropicInstanceRow } from "../providers/anthropic-instance";
2
3
  /**
3
4
  * Generic OAuth multi-account 429 failover (#2568).
@@ -293,14 +294,14 @@ export type AntigravityModelRoute =
293
294
  const KEEP_ANTIGRAVITY_ROUTE: AntigravityModelRoute = { kind: "keep" };
294
295
 
295
296
  /** Client-facing refusal when no usable account's discovery lists the model. Mirrored in docs-site. */
296
- export function antigravityModelUnlistedMessage(model: string): string {
297
- return `No usable Google Antigravity account lists the model "${model}" in its model discovery. `
297
+ export function antigravityModelUnlistedMessage(model?: ClientFacingModelLabel): string {
298
+ return `No usable Google Antigravity account lists the model "${clientFacingModelText(model)}" in its model discovery. `
298
299
  + "Choose a model your accounts list, or add an account that has access to it.";
299
300
  }
300
301
 
301
302
  /** Client-facing refusal when the chosen account omits the model but a sibling may serve it. */
302
- export function antigravitySelectedAccountUnlistedMessage(model: string): string {
303
- return `The selected Google Antigravity account does not list the model "${model}" in its model discovery. `
303
+ export function antigravitySelectedAccountUnlistedMessage(model?: ClientFacingModelLabel): string {
304
+ return `The selected Google Antigravity account does not list the model "${clientFacingModelText(model)}" in its model discovery. `
304
305
  + "Select an account that lists it, or enable oauthAccountFailover so OpenCodex can choose one.";
305
306
  }
306
307
 
@@ -325,6 +326,7 @@ export function routeAntigravityModel(
325
326
  plannedAccountId: string | null | undefined,
326
327
  model: string | null | undefined,
327
328
  now = Date.now(),
329
+ clientModel?: ClientFacingModelLabel,
328
330
  ): AntigravityModelRoute {
329
331
  if (providerName !== "google-antigravity" || !model || !plannedAccountId
330
332
  || accountListsModel(providerName, plannedAccountId, model) !== false) return KEEP_ANTIGRAVITY_ROUTE;
@@ -332,9 +334,9 @@ export function routeAntigravityModel(
332
334
  .filter(account => account.id !== plannedAccountId && account.paused !== true && account.needsReauth !== true)
333
335
  .map(account => account.id)
334
336
  .filter(id => accountListsModel(providerName, id, model) !== false);
335
- if (serving.length === 0) return { kind: "refuse", message: antigravityModelUnlistedMessage(model) };
337
+ if (serving.length === 0) return { kind: "refuse", message: antigravityModelUnlistedMessage(clientModel) };
336
338
  if (!isProactivePreferenceEnabled(config, providerName, now)) {
337
- return { kind: "refuse", message: antigravitySelectedAccountUnlistedMessage(model) };
339
+ return { kind: "refuse", message: antigravitySelectedAccountUnlistedMessage(clientModel) };
338
340
  }
339
341
  const ready = new Set(eligibleFailoverAccounts(providerName, now, classifyModelFamilyForQuota(providerName, model)));
340
342
  const rank = (id: string) => (ready.has(id) ? 0 : 2) + (accountListsModel(providerName, id, model) === true ? 0 : 1);
@@ -372,19 +374,19 @@ export function rotateAntigravityAccountOnModelNotFound(
372
374
  * Client-facing refusal when failover is on and a sibling may serve the model, but the request
373
375
  * still resolved to an omitting account (the sibling could not be resolved or admitted).
374
376
  */
375
- export function antigravityReplacementUnavailableMessage(model: string): string {
376
- return `The selected Google Antigravity account does not list the model "${model}" in its model discovery, `
377
+ export function antigravityReplacementUnavailableMessage(model?: ClientFacingModelLabel): string {
378
+ return `The selected Google Antigravity account does not list the model "${clientFacingModelText(model)}" in its model discovery, `
377
379
  + "and no account that may serve it could be used for this request. Retry the request.";
378
380
  }
379
381
 
380
382
  /** The refusal for an account that already resolved, or null when it may serve the model. */
381
383
  export function antigravityModelRefusal(
382
- config: OcxConfig, providerName: string, accountId: string, model: string | null | undefined, now = Date.now(),
384
+ config: OcxConfig, providerName: string, accountId: string, model: string | null | undefined, now = Date.now(), clientModel?: ClientFacingModelLabel,
383
385
  ): string | null {
384
- const verdict = routeAntigravityModel(config, providerName, accountId, model, now);
386
+ const verdict = routeAntigravityModel(config, providerName, accountId, model, now, clientModel);
385
387
  if (verdict.kind === "keep") return null;
386
388
  // A reroute verdict exists only with failover on, so advising to enable it would be wrong.
387
- return verdict.kind === "refuse" ? verdict.message : antigravityReplacementUnavailableMessage(model!);
389
+ return verdict.kind === "refuse" ? verdict.message : antigravityReplacementUnavailableMessage(clientModel);
388
390
  }
389
391
 
390
392
  function kiroModelListingHasRoom(config: OcxConfig, accountId: string, model: string): boolean {