@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
@@ -0,0 +1,93 @@
1
+ import { markProxyError, UNDECLARED_TOOL_CALL_MESSAGE } from "./client-error-body";
2
+ import { messagesOverflowPresentation, messagesSseErrorOverflowPresentation, ownedAnthropicErrorPayload } from "./messages-error-body";
3
+ import { sseFieldValue } from "./sse-decoder";
4
+
5
+ export const MESSAGES_SSE_ERROR_HOLD_BYTES = 1024 * 1024;
6
+ export type MessagesSseLocalOrigin = "guard" | "eof" | "stop-error" | "stall" | "cap" | "read";
7
+ type Rec = Record<string, unknown>;
8
+ const record = (value: unknown): Rec => value !== null && typeof value === "object" && !Array.isArray(value) ? value as Rec : {};
9
+ const encoder = new TextEncoder();
10
+ const overLimit = markProxyError({ message: "The provider stream reported an error." });
11
+ export function messagesSseErrorPayload(data: string): string {
12
+ let parsed: unknown;
13
+ try { parsed = JSON.parse(data); } catch { parsed = undefined; }
14
+ const body = record(parsed), nested = body.error;
15
+ // A null, scalar or array error member carries no fields; read the top-level ones, as the buffered paths do.
16
+ const error = nested !== null && typeof nested === "object" && !Array.isArray(nested) ? nested as Rec : body;
17
+ return JSON.stringify(ownedAnthropicErrorPayload({ status: 502,
18
+ type: typeof error.type === "string" ? error.type : "api_error",
19
+ code: typeof error.code === "string" ? error.code : undefined,
20
+ evidence: { status: 502, type: typeof error.type === "string" ? error.type : undefined,
21
+ code: typeof error.code === "string" ? error.code : undefined,
22
+ message: typeof error.message === "string" ? error.message : undefined },
23
+ overflow: messagesSseErrorOverflowPresentation(data, parsed),
24
+ }));
25
+ }
26
+ export function messagesSseOversizePayload(): string {
27
+ return JSON.stringify(ownedAnthropicErrorPayload({ status: 502, type: "api_error", evidence: { status: 502 }, localError: overLimit }));
28
+ }
29
+ const localMessages: Readonly<Record<MessagesSseLocalOrigin, string>> = {
30
+ guard: UNDECLARED_TOOL_CALL_MESSAGE,
31
+ eof: "anthropic passthrough upstream stream ended before message_stop",
32
+ "stop-error": 'upstream ended the turn with stop_reason "error"',
33
+ stall: "anthropic passthrough body stalled: no upstream bytes arrived before the configured timeout",
34
+ cap: "anthropic passthrough body exceeded the safe limit",
35
+ read: "anthropic passthrough upstream stream failed",
36
+ };
37
+ export function messagesSseLocalFrame(origin: MessagesSseLocalOrigin, originalMessage: string): Uint8Array {
38
+ const local = markProxyError({ message: localMessages[origin] }, origin === "stall" ? "body_stall" : origin === "cap" ? "body_overflow" : undefined);
39
+ const payload = ownedAnthropicErrorPayload({ status: 502, type: origin === "stall" ? "timeout_error" : "api_error",
40
+ code: origin === "guard" ? "undeclared_tool_call" : undefined, evidence: { status: 502 },
41
+ overflow: messagesOverflowPresentation(originalMessage), localError: local });
42
+ return encoder.encode(`${origin === "guard" ? "" : "\n\n"}event: error\ndata: ${JSON.stringify(payload)}\n\n`);
43
+ }
44
+
45
+ /** The echo flag comes from the original field order, never the parsed payload. */
46
+ export function messagesSseEchoRenamedError(frame: string): boolean {
47
+ const lines = frame.split(/\r\n|\r|\n/).filter(line => line !== "" && !line.startsWith(":"));
48
+ return sseFieldValue(lines[0] ?? "", "event") === "error"
49
+ && lines.map(line => sseFieldValue(line, "event")).filter(value => value !== null).at(-1) === "error";
50
+ }
51
+ export type MessagesSseFrameOrigin = { echoRenamedError: true } | { client: Uint8Array };
52
+ /** One request's complete-frame handoffs. Input bytes alone can never create an origin. */
53
+ export class MessagesSseFrameContext {
54
+ private readonly frames = new WeakMap<Uint8Array, MessagesSseFrameOrigin>();
55
+ register(bytes: Uint8Array, origin: MessagesSseFrameOrigin): Uint8Array { this.frames.set(bytes, origin); return bytes; }
56
+ take(bytes: Uint8Array): MessagesSseFrameOrigin | undefined {
57
+ const origin = this.frames.get(bytes); this.frames.delete(bytes); return origin;
58
+ }
59
+ }
60
+ export interface MessagesSseFrameHooks {
61
+ input(bytes: Uint8Array, empty: boolean, tailLineFeed?: boolean, continuation?: boolean): void;
62
+ output(original: string, bytes: Uint8Array): void;
63
+ dispose(): void;
64
+ }
65
+ /** Only a dedicated, complete producer frame may traverse a buffering stage. */
66
+ export function messagesSseFrameHooks(context: MessagesSseFrameContext): MessagesSseFrameHooks {
67
+ let pending: { digest: string; origin: MessagesSseFrameOrigin; repair?: boolean } | undefined;
68
+ const digest = (value: string | Uint8Array, prefix = "") => new Bun.CryptoHasher("sha256").update(prefix).update(value).digest("hex");
69
+ const broken = () => new Error("The proxy could not reach or read the provider.");
70
+ return {
71
+ input(bytes, empty, tailLineFeed = false, continuation = false) {
72
+ const origin = context.take(bytes);
73
+ if (!origin) return;
74
+ if (pending) throw broken();
75
+ if ("client" in origin && bytes[0] === 10 && bytes[1] === 10) {
76
+ const prefix = tailLineFeed || empty && continuation ? "\n" : "";
77
+ pending = { digest: digest(bytes.subarray(2), prefix),
78
+ origin: { client: encoder.encode(prefix + new TextDecoder().decode(origin.client.subarray(2))) },
79
+ repair: !(empty && continuation) };
80
+ } else {
81
+ if (!empty) throw broken();
82
+ pending = { digest: digest(bytes), origin };
83
+ }
84
+ },
85
+ output(original, bytes) {
86
+ if (!pending) return;
87
+ if (pending.repair) { pending.repair = false; return; }
88
+ if (digest(original) !== pending.digest) { pending = undefined; throw broken(); }
89
+ context.register(bytes, pending.origin); pending = undefined;
90
+ },
91
+ dispose() { pending = undefined; },
92
+ };
93
+ }
@@ -0,0 +1,44 @@
1
+ import { redactSecretString } from "./redact";
2
+ import { pinnedNativeModelRows } from "../codex/catalog/pinned-models";
3
+ import { getModelMetadata, resolveMetadataProvider } from "../generated/model-metadata";
4
+
5
+ /** Longest model identity a row or relayed header may carry. */
6
+ export const MAX_MODEL_IDENTITY_LENGTH = 128;
7
+
8
+ /**
9
+ * A model identity (served, resolved, or a relayed model header) is an identifier, never free-form
10
+ * text to truncate into one: `[A-Za-z0-9._:/@-]`, at most 128 characters. A value the secret redactor
11
+ * would change is dropped, because credential-shaped text can fit the identifier alphabet.
12
+ */
13
+ export function boundedModelIdentity(value: unknown): string | undefined {
14
+ return typeof value === "string"
15
+ && value.length <= MAX_MODEL_IDENTITY_LENGTH
16
+ && /^[A-Za-z0-9._:/@-]+$/.test(value)
17
+ && redactSecretString(value) === value
18
+ ? value
19
+ : undefined;
20
+ }
21
+
22
+ /** Model ids this build pins for the Codex catalog; a known id a route can be served without config. */
23
+ const PINNED_MODEL_IDS: ReadonlyMap<string, string> = new Map(
24
+ pinnedNativeModelRows().flatMap(row => typeof row.slug === "string" ? [[row.slug, row.slug] as [string, string]] : []),
25
+ );
26
+
27
+ /**
28
+ * An upstream-reported model string is kept only when it exactly equals a model id this proxy
29
+ * already knows: one of `known` (the requested model, the routed target, the wire model, a
30
+ * configured target), a model the bundled Codex catalog pins, or a model in the bundled metadata
31
+ * catalog for `provider` (the selected provider). The identity grammar still applies first. What is
32
+ * returned is the proxy's own copy of the matched id; anything else is undefined, because no grammar
33
+ * can tell a prefixless credential from a model name.
34
+ */
35
+ export function knownModelIdentity(value: unknown, known: Iterable<unknown> = [], provider?: string): string | undefined {
36
+ const bounded = boundedModelIdentity(value);
37
+ if (bounded === undefined) return undefined;
38
+ for (const candidate of known) {
39
+ if (typeof candidate === "string" && candidate === bounded) return candidate;
40
+ }
41
+ const pinned = PINNED_MODEL_IDS.get(bounded);
42
+ if (pinned !== undefined || !provider) return pinned;
43
+ return getModelMetadata(resolveMetadataProvider(provider) ?? provider, bounded)?.id;
44
+ }
@@ -23,13 +23,18 @@
23
23
  */
24
24
  import { AsyncLocalStorage } from "node:async_hooks";
25
25
 
26
- const passive = new AsyncLocalStorage<true>();
26
+ const passive = new AsyncLocalStorage<{ onDiagnostic?: (message: string) => void }>();
27
27
 
28
28
  /** Run a management read passively, including everything it awaits or schedules. */
29
- export function runPassiveRead<T>(run: () => Promise<T>): Promise<T> {
30
- return passive.run(true, run);
29
+ export function runPassiveRead<T>(run: () => Promise<T>, options: { onDiagnostic?: (message: string) => void } = {}): Promise<T> {
30
+ return passive.run(options, run);
31
31
  }
32
32
 
33
33
  export function isPassiveRead(): boolean {
34
- return passive.getStore() === true;
34
+ return passive.getStore() !== undefined;
35
+ }
36
+
37
+ /** Deliver an optional read-only diagnostic without affecting other passive callers. */
38
+ export function passiveReadDiagnostic(message: string): void {
39
+ passive.getStore()?.onDiagnostic?.(message);
35
40
  }
@@ -0,0 +1,124 @@
1
+ import { closeSync, lstatSync, openSync } from "node:fs";
2
+
3
+ /** The files SQLite opens next to a database: the rollback journal, and the WAL and its index. */
4
+ export const SQLITE_SIDECAR_SUFFIXES = ["-journal", "-wal", "-shm"] as const;
5
+
6
+ /** A database or sidecar name holds something other than a private regular file. Carries no path. */
7
+ export class UnsafeSqlitePathError extends Error {
8
+ constructor() {
9
+ super("SQLite storage path is not a private regular file");
10
+ this.name = "UnsafeSqlitePathError";
11
+ }
12
+ }
13
+
14
+ const FILE_ATTRIBUTE_REPARSE_POINT = 0x400;
15
+ const INVALID_FILE_ATTRIBUTES = 0xffffffff;
16
+ type ReparseProbe = (path: string) => boolean;
17
+ let nativeAttributes: ((path: string) => number) | undefined;
18
+ let probeForTests: ReparseProbe | null = null;
19
+ /**
20
+ * Whether the native attribute query runs: on Windows, except ARM64, whose Bun build cannot execute
21
+ * `bun:ffi` (the limitation src/lib/windows-user-principal.ts works around). There `lstat` still
22
+ * reports symbolic links, junctions and app execution aliases as links; other reparse tags are not
23
+ * visible without native code.
24
+ */
25
+ export function nativeReparseProbeApplies(platform: string, arch: string): boolean {
26
+ return platform === "win32" && arch !== "arm64";
27
+ }
28
+ // Read once at load: tests replace `process.platform` to drive Windows-only branches on POSIX, and
29
+ // the native query must follow the system the process actually runs on.
30
+ const NATIVE_ATTRIBUTES = nativeReparseProbeApplies(process.platform, process.arch);
31
+
32
+ function errorCode(error: unknown): unknown {
33
+ return error !== null && typeof error === "object" && "code" in error ? error.code : undefined;
34
+ }
35
+
36
+ /**
37
+ * Whether the entry at `path` itself is a Windows reparse point: a symbolic link, a junction, or any
38
+ * other tag. `GetFileAttributesW` reports the named entry rather than what it points to, so this
39
+ * sees what `lstat` cannot classify. Throws when the attribute cannot be read.
40
+ */
41
+ export function isWindowsReparsePoint(path: string): boolean {
42
+ if (!nativeAttributes) {
43
+ // Loaded on first use, only on Windows; the repository's other Windows file checks use the same call.
44
+ const ffi = require("bun:ffi") as typeof import("bun:ffi");
45
+ const kernel = ffi.dlopen("kernel32.dll", {
46
+ GetFileAttributesW: { args: [ffi.FFIType.ptr], returns: ffi.FFIType.u32 },
47
+ });
48
+ nativeAttributes = (name: string) => {
49
+ const wide = Buffer.from(`${name}\0`, "utf16le");
50
+ return kernel.symbols.GetFileAttributesW(ffi.ptr(wide)) >>> 0;
51
+ };
52
+ }
53
+ const attributes = nativeAttributes(path);
54
+ if (attributes === INVALID_FILE_ATTRIBUTES) throw new Error("file attributes unavailable");
55
+ return (attributes & FILE_ATTRIBUTE_REPARSE_POINT) !== 0;
56
+ }
57
+
58
+ /** Test seam: replace the reparse-point probe on every platform; null restores the default. */
59
+ export function setSqlitePathReparseProbeForTests(probe: ReparseProbe | null): void {
60
+ probeForTests = probe;
61
+ }
62
+
63
+ function isReparsePoint(path: string): boolean {
64
+ if (probeForTests) return probeForTests(path);
65
+ return NATIVE_ATTRIBUTES && isWindowsReparsePoint(path);
66
+ }
67
+
68
+ /**
69
+ * Refuse unless nothing is at `path` or it is a private regular file: not a link or other reparse
70
+ * point, not a directory, a single directory entry, and on POSIX owned by this user. Returns
71
+ * whether an entry exists. A probe that cannot answer refuses.
72
+ */
73
+ export function assertPrivateSqliteEntryOrMissing(path: string): boolean {
74
+ let stat;
75
+ try {
76
+ stat = lstatSync(path);
77
+ } catch (error) {
78
+ if (errorCode(error) === "ENOENT") return false;
79
+ throw error;
80
+ }
81
+ let reparse: boolean;
82
+ try {
83
+ reparse = isReparsePoint(path);
84
+ } catch {
85
+ throw new UnsafeSqlitePathError();
86
+ }
87
+ if (
88
+ reparse
89
+ || !stat.isFile()
90
+ || stat.isSymbolicLink()
91
+ || stat.nlink !== 1
92
+ || (process.platform !== "win32" && stat.uid !== process.getuid!())
93
+ ) throw new UnsafeSqlitePathError();
94
+ return true;
95
+ }
96
+
97
+ /**
98
+ * Refuse unless every sidecar of `databasePath` is absent or a private regular file. SQLite's POSIX
99
+ * VFS opens them with O_NOFOLLOW; its Windows VFS opens them by name with CreateFileW, which follows
100
+ * a link planted there. Check before opening the database and before every write transaction: the
101
+ * rollback journal is created and deleted per transaction. Something planted after the check, while
102
+ * SQLite opens the file, is outside what this can see.
103
+ */
104
+ export function assertPrivateSqliteSidecars(databasePath: string): void {
105
+ for (const suffix of SQLITE_SIDECAR_SUFFIXES) assertPrivateSqliteEntryOrMissing(databasePath + suffix);
106
+ }
107
+
108
+ /**
109
+ * Make sure `databasePath` is a private regular file without creating anything through a link at
110
+ * its name or at a sidecar's. POSIX O_CREAT|O_EXCL refuses a link at the final component, but
111
+ * Windows CREATE_NEW follows a dangling file symlink and creates its target, so every entry is
112
+ * checked before the create. An entry planted between the check and the create is not covered;
113
+ * callers check the file again after hardening it.
114
+ */
115
+ export function preparePrivateSqliteDatabase(databasePath: string): void {
116
+ assertPrivateSqliteSidecars(databasePath);
117
+ if (assertPrivateSqliteEntryOrMissing(databasePath)) return;
118
+ try {
119
+ closeSync(openSync(databasePath, "wx", 0o600));
120
+ } catch (error) {
121
+ if (errorCode(error) !== "EEXIST") throw error;
122
+ }
123
+ if (!assertPrivateSqliteEntryOrMissing(databasePath)) throw new UnsafeSqlitePathError();
124
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Response service tiers a request-log row may record. A provider can return any string in
3
+ * `service_tier` (or an Anthropic `speed`), so only these closed members are kept; anything else
4
+ * is omitted. Pricing and Fast confirmation read the raw observation separately.
5
+ */
6
+ export const RESPONSE_SERVICE_TIERS = ["auto", "default", "flex", "scale", "priority", "fast", "standard", "ultrafast"] as const;
7
+
8
+ export type ResponseServiceTier = typeof RESPONSE_SERVICE_TIERS[number];
9
+
10
+ const TIERS: ReadonlySet<string> = new Set(RESPONSE_SERVICE_TIERS);
11
+
12
+ /** The closed member a tier names (case-insensitive), or undefined. */
13
+ export function boundedServiceTier(value: unknown): ResponseServiceTier | undefined {
14
+ if (typeof value !== "string") return undefined;
15
+ const folded = value.trim().toLowerCase();
16
+ return TIERS.has(folded) ? folded as ResponseServiceTier : undefined;
17
+ }
@@ -1,5 +1,8 @@
1
1
  import { parseRetryAfterMs } from "../combos";
2
2
  import { classifyError, parseRetryAfterFromMessage } from "./errors";
3
+ import { formatClientRetryAfter } from "./client-retry-after";
4
+
5
+ export { formatClientRetryAfter, MAX_CLIENT_RETRY_AFTER_SECONDS } from "./client-retry-after";
3
6
 
4
7
  /** Small default when a retryable 429 has no upstream Retry-After (#507). */
5
8
  export const DEFAULT_RETRYABLE_429_RETRY_AFTER_SEC = "2";
@@ -256,9 +256,13 @@ class SocketReader {
256
256
  if (preserveBuffered && !this.ended && !this.socket.destroyed && this.buffer.byteLength > 0) {
257
257
  this.socket.unshift(this.buffer);
258
258
  }
259
+ // A read continuation may resume after cleanup; it must not enqueue a new waiter
260
+ // after the socket listeners that could settle it have been removed.
261
+ this.ended = true;
262
+ this.failure ??= new Socks5FetchError("SOCKS5 reader disposed");
259
263
  this.buffer = Buffer.alloc(0);
260
- this.rejectExact(new Socks5FetchError("SOCKS5 reader disposed"));
261
- this.rejectAny(new Socks5FetchError("SOCKS5 reader disposed"));
264
+ this.rejectExact(this.failure);
265
+ this.rejectAny(this.failure);
262
266
  }
263
267
  }
264
268
 
@@ -267,19 +271,21 @@ async function socks5Connect(proxy: string, target: URL, signal?: AbortSignal):
267
271
  const credentials = socks5Credentials(parsedProxy);
268
272
  const proxyHost = parsedProxy.hostname.replace(/^\[|\]$/g, "");
269
273
  const socket = await connectSocket(proxyHost, Number(parsedProxy.port) || DEFAULT_SOCKS5_PORT, signal);
270
- socket.setTimeout(SOCKS5_CONNECT_TIMEOUT_MS, () => {
274
+ const onHandshakeTimeout = () => {
271
275
  socket.destroy(new Socks5FetchError("SOCKS5 handshake timed out"));
272
- });
276
+ };
277
+ socket.setTimeout(SOCKS5_CONNECT_TIMEOUT_MS, onHandshakeTimeout);
273
278
  const reader = new SocketReader(socket);
274
279
  try {
275
280
  await socks5Handshake(reader, { host: target.hostname, port: targetPort(target) }, credentials, signal);
276
- socket.setTimeout(0);
277
281
  return socket;
278
282
  } catch (error) {
279
283
  socket.destroy();
280
284
  if (error instanceof Socks5HandshakeError) throw new Socks5FetchError(error.message);
281
285
  throw error;
282
286
  } finally {
287
+ socket.setTimeout(0);
288
+ socket.removeListener("timeout", onHandshakeTimeout);
283
289
  reader.dispose(true);
284
290
  }
285
291
  }
@@ -420,10 +426,12 @@ function responseBody(
420
426
  headers: Headers,
421
427
  status: number,
422
428
  method: string,
429
+ onResponseTimeout: () => void,
423
430
  ): ReadableStream<Uint8Array> | null {
424
431
  if (bodylessResponse(method, status)) {
425
432
  reader.dispose();
426
433
  socket.setTimeout(0);
434
+ socket.removeListener("timeout", onResponseTimeout);
427
435
  socket.destroy();
428
436
  return null;
429
437
  }
@@ -443,6 +451,7 @@ function responseBody(
443
451
  signal.removeEventListener("abort", onAbort);
444
452
  reader.dispose();
445
453
  socket.setTimeout(0);
454
+ socket.removeListener("timeout", onResponseTimeout);
446
455
  socket.destroy();
447
456
  };
448
457
  const onAbort = () => socket.destroy();
@@ -677,12 +686,13 @@ export async function socks5Fetch(
677
686
  // Pending reads carry the abort reason; destruction must not enqueue an
678
687
  // unhandled socket error after their listeners have been removed.
679
688
  const onAbort = () => socket.destroy();
689
+ const onResponseTimeout = () => {
690
+ socket.destroy(new Socks5FetchError("SOCKS5 upstream request timed out"));
691
+ };
680
692
  request.signal.addEventListener("abort", onAbort, { once: true });
681
693
  try {
682
694
  if (target.protocol === "https:") socket = await secureSocket(tunnel, target, request.signal);
683
- socket.setTimeout(SOCKS5_RESPONSE_TIMEOUT_MS, () => {
684
- socket.destroy(new Socks5FetchError("SOCKS5 upstream request timed out"));
685
- });
695
+ socket.setTimeout(SOCKS5_RESPONSE_TIMEOUT_MS, onResponseTimeout);
686
696
  // Observe socket errors and early responses while uploading, not only after it.
687
697
  reader = new SocketReader(socket);
688
698
  const headers = requestHeaders(request, target);
@@ -706,7 +716,7 @@ export async function socks5Fetch(
706
716
  const codingFormat = bodylessResponse(request.method, responseHead.status)
707
717
  ? undefined
708
718
  : contentCodingFormat(responseHead.headers);
709
- const body = responseBody(reader, socket, request.signal, responseHead.headers, responseHead.status, request.method);
719
+ const body = responseBody(reader, socket, request.signal, responseHead.headers, responseHead.status, request.method, onResponseTimeout);
710
720
  const responseHeaders = new Headers(responseHead.headers);
711
721
  if (codingFormat !== undefined) {
712
722
  responseHeaders.delete("content-encoding");
@@ -729,6 +739,8 @@ export async function socks5Fetch(
729
739
  } catch (error) {
730
740
  request.signal.removeEventListener("abort", onAbort);
731
741
  reader?.dispose();
742
+ socket.setTimeout(0);
743
+ socket.removeListener("timeout", onResponseTimeout);
732
744
  socket.destroy();
733
745
  // An aborted caller gets its own reason back. Several waiters inside this transport can win
734
746
  // the race that settles an abort, and they do not agree on what to do with a reason they
@@ -1,9 +1,10 @@
1
1
  /** Process-lifetime single-writer ownership for the shared spend journal. */
2
2
  import { Database } from "bun:sqlite";
3
- import { chmodSync, closeSync, lstatSync, mkdirSync, openSync, realpathSync } from "node:fs";
3
+ import { chmodSync, lstatSync, mkdirSync, realpathSync } from "node:fs";
4
4
  import { join, resolve } from "node:path";
5
5
  import { getConfigDir } from "../config/paths";
6
6
  import { recordOwnedConfigPath } from "./config-ownership";
7
+ import { assertPrivateSqliteSidecars, preparePrivateSqliteDatabase } from "./private-sqlite-path";
7
8
  import { assertNotRealHomeUnderTest } from "./test-home-guard";
8
9
  import { hardenSecretDir, hardenSecretPath } from "./windows-secret-acl";
9
10
 
@@ -47,6 +48,26 @@ let boundLedgerHome: string | null = null;
47
48
  */
48
49
  let ownerGeneration = 0;
49
50
  const releaseHooks: Array<() => void> = [];
51
+ const acquiredHooks: Array<(home: string) => void> = [];
52
+
53
+ /** Run once after each new ownership generation is acquired. */
54
+ export function onSpendLedgerOwnerAcquired(hook: (home: string) => void): void {
55
+ acquiredHooks.push(hook);
56
+ }
57
+ const releasingHooks: Array<() => void> = [];
58
+ let releasing = false;
59
+
60
+ /** Run before the final lease is released, while existing storage tokens remain valid. */
61
+ export function onSpendLedgerOwnerReleasing(hook: () => void): void {
62
+ releasingHooks.push(hook);
63
+ }
64
+
65
+ function assertNotReleasing(): void {
66
+ if (releasing) throw new SpendLedgerOwnerError(
67
+ "SPEND_LEDGER_OWNER_NOT_HELD",
68
+ "Spend-ledger ownership is required before the shared ledger can be used.",
69
+ );
70
+ }
50
71
 
51
72
  /**
52
73
  * Run when the last lease on a state directory goes away.
@@ -95,8 +116,9 @@ function prepareOwnerPath(configDir: string): { home: string; path: string } {
95
116
  // its sidecars were left behind by a later uninstall because nothing recorded them.
96
117
  recordOwnedConfigPath(home, path);
97
118
  for (const suffix of OWNER_SIDECARS) recordOwnedConfigPath(home, `${path}${suffix}`);
98
- try { closeSync(openSync(path, "wx", 0o600)); }
99
- catch (error) { if (errorCode(error) !== "EEXIST") throw error; }
119
+ // Refuses a link or reparse point at the database or a sidecar before anything is created:
120
+ // Windows creates a new file through a link at its name.
121
+ preparePrivateSqliteDatabase(path);
100
122
  assertPrivateFile(path);
101
123
  if (process.platform !== "win32") chmodSync(path, 0o600);
102
124
  hardenSecretPath(path, { required: true });
@@ -142,6 +164,7 @@ export function spendLedgerRestartEnvironment(
142
164
  * can evict a live owner or mistake a reused process identity for this lease.
143
165
  */
144
166
  export function acquireSpendLedgerOwner(configDir = getConfigDir()): SpendLedgerOwnerLease {
167
+ assertNotReleasing();
145
168
  const requestedHome = stateDirectoryIdentity(configDir);
146
169
  const busyTimeout = restartHandoffWaitMs();
147
170
  if (boundLedgerHome !== null && boundLedgerHome !== requestedHome) {
@@ -175,6 +198,7 @@ export function acquireSpendLedgerOwner(configDir = getConfigDir()): SpendLedger
175
198
 
176
199
  let database: Database | undefined;
177
200
  try {
201
+ assertPrivateSqliteSidecars(prepared.path);
178
202
  database = new Database(prepared.path, { create: true });
179
203
  database.exec(`PRAGMA locking_mode = NORMAL; PRAGMA busy_timeout = ${busyTimeout}; BEGIN IMMEDIATE`);
180
204
  } catch (cause) {
@@ -194,7 +218,11 @@ export function acquireSpendLedgerOwner(configDir = getConfigDir()): SpendLedger
194
218
 
195
219
  activeOwner = { home: prepared.home, database, references: 1 };
196
220
  ownerGeneration += 1;
197
- return leaseFor(activeOwner);
221
+ const owner = activeOwner;
222
+ for (const hook of acquiredHooks) {
223
+ try { hook(owner.home); } catch { /* one hook must not prevent acquisition */ }
224
+ }
225
+ return leaseFor(owner);
198
226
  }
199
227
 
200
228
  function leaseFor(owner: ActiveOwner): SpendLedgerOwnerLease {
@@ -204,6 +232,16 @@ function leaseFor(owner: ActiveOwner): SpendLedgerOwnerLease {
204
232
  if (released) return;
205
233
  released = true;
206
234
  if (activeOwner !== owner || owner.references < 1) return;
235
+ if (owner.references === 1) {
236
+ releasing = true;
237
+ try {
238
+ for (const hook of releasingHooks) {
239
+ try { hook(); } catch { /* a flush hook must not prevent release */ }
240
+ }
241
+ } finally {
242
+ releasing = false;
243
+ }
244
+ }
207
245
  owner.references -= 1;
208
246
  if (owner.references > 0) return;
209
247
  activeOwner = null;
@@ -265,6 +303,7 @@ function trustedStorage(storage: SpendLedgerStorage): { readonly path: string; r
265
303
  * choose the destination, which is the thing ownership is supposed to decide.
266
304
  */
267
305
  export function mintSpendLedgerStorage(fileName: string): SpendLedgerStorage {
306
+ assertNotReleasing();
268
307
  if (fileName.includes("/") || fileName.includes("\\") || fileName === "." || fileName === "..") {
269
308
  throw new SpendLedgerOwnerError(
270
309
  "SPEND_LEDGER_OWNER_UNAVAILABLE",
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Presentation-only classification of an upstream failure into a small closed set of conditions.
3
+ *
4
+ * The output is what request logs and client-facing error text may name. It never carries input
5
+ * bytes: callers pass bounded structured tokens (status, type, code, reason) and optionally the
6
+ * upstream message, which is read here only through fixed lowercase keyword sets and never stored
7
+ * or returned. Routing, retry and recovery keep using their own classifiers (src/lib/errors.ts);
8
+ * this module must not feed them.
9
+ */
10
+
11
+ import { isDefiniteContextOverflow } from "./context-overflow-verdict";
12
+
13
+ export const UPSTREAM_CONDITIONS = [
14
+ "auth_failed",
15
+ "access_denied",
16
+ "context_overflow",
17
+ "location_unsupported",
18
+ "account_verification_required",
19
+ "billing_exhausted",
20
+ "model_unavailable",
21
+ "rate_limited",
22
+ "upstream_unavailable",
23
+ "upstream_failed",
24
+ "request_rejected",
25
+ ] as const;
26
+
27
+ export type UpstreamCondition = typeof UPSTREAM_CONDITIONS[number];
28
+
29
+ const CONDITION_SET: ReadonlySet<string> = new Set(UPSTREAM_CONDITIONS);
30
+
31
+ export function isUpstreamCondition(value: unknown): value is UpstreamCondition {
32
+ return typeof value === "string" && CONDITION_SET.has(value);
33
+ }
34
+
35
+ export interface UpstreamConditionEvidence {
36
+ status: number;
37
+ type?: string;
38
+ code?: string;
39
+ reason?: string;
40
+ message?: string;
41
+ }
42
+
43
+ // Structured tokens are compared after lowercasing; anything longer than this is not a token.
44
+ const MAX_TOKEN_LENGTH = 128;
45
+ // Keyword matching reads at most this much of the message.
46
+ const MAX_MESSAGE_SCAN = 4096;
47
+
48
+ const STRUCTURED: ReadonlyArray<readonly [UpstreamCondition, ReadonlySet<string>]> = [
49
+ ["context_overflow", new Set(["context_length_exceeded", "string_above_max_length", "context_window_exceeded", "prompt_too_long"])],
50
+ ["location_unsupported", new Set(["location_not_supported", "unsupported_country_region_territory", "unsupported_country", "user_location_is_not_supported"])],
51
+ ["account_verification_required", new Set(["validation_required", "verification_required", "organization_verification_required"])],
52
+ ["billing_exhausted", new Set(["insufficient_quota", "billing_hard_limit_reached", "usage_limit_reached", "usage_limit_exceeded", "1308", "monthly_request_count", "overage_request_limit_exceeded", "payment_required", "insufficient_balance", "credit_balance_too_low"])],
53
+ ["model_unavailable", new Set(["model_not_found", "unsupported_model", "model_not_available", "model_not_supported", "deployment_not_found"])],
54
+ ["rate_limited", new Set(["rate_limit_exceeded", "rate_limit_error", "too_many_requests", "throttling", "throttled", "rate_limited"])],
55
+ ["upstream_unavailable", new Set(["server_is_overloaded", "overloaded_error", "service_unavailable", "unavailable"])],
56
+ ];
57
+
58
+ // Context overflow from message text uses the same verdict the combo router trusts, so a validation
59
+ // error that merely quotes "prompt is too long" (an invalid tool name, for example) is not an overflow.
60
+ const KEYWORDS: Readonly<Record<"location_unsupported" | "account_verification_required" | "billing_exhausted" | "model_unavailable" | "rate_limited", readonly string[]>> = {
61
+ location_unsupported: ["location is not supported", "unsupported location", "not supported in your region", "region is not supported", "country, region, or territory", "not available in your country", "not available in your region"],
62
+ account_verification_required: ["verify your organization", "organization must be verified", "verification required", "verify your account", "account verification"],
63
+ billing_exhausted: ["insufficient quota", "quota exceeded", "quota exhausted", "exceeded your current quota", "run out of credits", "out of credits", "insufficient credits", "credit balance", "insufficient balance", "billing", "payment required"],
64
+ model_unavailable: ["model not found", "model does not exist", "unsupported model", "not allowed to use this model", "does not have access to model", "model is not available", "no such model"],
65
+ rate_limited: ["rate limit", "too many requests", "throttl"],
66
+ };
67
+
68
+ function token(value: string | undefined): string | undefined {
69
+ if (typeof value !== "string") return undefined;
70
+ const trimmed = value.trim();
71
+ return trimmed && trimmed.length <= MAX_TOKEN_LENGTH ? trimmed.toLowerCase() : undefined;
72
+ }
73
+
74
+ function structuredCondition(tokens: readonly string[]): UpstreamCondition | undefined {
75
+ for (const [condition, set] of STRUCTURED) {
76
+ if (tokens.some(value => set.has(value))) return condition;
77
+ }
78
+ return undefined;
79
+ }
80
+
81
+ function mentions(message: string, condition: keyof typeof KEYWORDS): boolean {
82
+ return KEYWORDS[condition].some(keyword => message.includes(keyword));
83
+ }
84
+
85
+ function statusFallback(status: number): UpstreamCondition | undefined {
86
+ if (status === 401) return "auth_failed";
87
+ if (status === 403) return "access_denied";
88
+ if (status === 402) return "billing_exhausted";
89
+ if (status === 404) return "model_unavailable";
90
+ if (status === 429) return "rate_limited";
91
+ if (status === 503 || status === 529) return "upstream_unavailable";
92
+ if (status >= 500) return "upstream_failed";
93
+ if (status >= 400) return "request_rejected";
94
+ return undefined;
95
+ }
96
+
97
+ /**
98
+ * Precedence: 401 is authoritative; structured tokens next; keyword evidence only for 4xx
99
+ * statuses (a 5xx stays a server failure whatever its text says); a bare status last.
100
+ */
101
+ export function classifyUpstreamCondition(evidence: UpstreamConditionEvidence): UpstreamCondition | undefined {
102
+ const { status } = evidence;
103
+ if (!Number.isInteger(status)) return undefined;
104
+ if (status === 401) return "auth_failed";
105
+ const tokens = [token(evidence.code), token(evidence.type), token(evidence.reason)].filter((value): value is string => value !== undefined);
106
+ const structured = structuredCondition(tokens);
107
+ if (structured) return structured;
108
+ const message = typeof evidence.message === "string" ? evidence.message.slice(0, MAX_MESSAGE_SCAN).toLowerCase() : "";
109
+ if (message && status >= 400 && status < 500) {
110
+ if (isDefiniteContextOverflow(status, evidence.message!.slice(0, MAX_MESSAGE_SCAN))) return "context_overflow";
111
+ if (mentions(message, "location_unsupported")) return "location_unsupported";
112
+ if (mentions(message, "account_verification_required")) return "account_verification_required";
113
+ // A 429 that names a rate limit is a rate limit even when it also mentions quota.
114
+ if (status === 429 && mentions(message, "rate_limited")) return "rate_limited";
115
+ if (mentions(message, "billing_exhausted")) return "billing_exhausted";
116
+ if (mentions(message, "model_unavailable")) return "model_unavailable";
117
+ if (mentions(message, "rate_limited")) return "rate_limited";
118
+ }
119
+ return statusFallback(status);
120
+ }
121
+
122
+ const MESSAGES: Readonly<Record<UpstreamCondition, string>> = {
123
+ auth_failed: "The provider rejected the configured credentials.",
124
+ access_denied: "The provider denied access to this request.",
125
+ context_overflow: "The request exceeds the model's context window.",
126
+ location_unsupported: "The provider does not serve this request from the current location.",
127
+ account_verification_required: "The provider requires account verification before serving this model.",
128
+ billing_exhausted: "The provider account has no remaining quota or credits.",
129
+ model_unavailable: "The requested model is not available from the provider.",
130
+ rate_limited: "The provider rate limit was reached; retry later.",
131
+ upstream_unavailable: "The provider is temporarily unavailable; retry later.",
132
+ upstream_failed: "The provider failed to complete the request.",
133
+ request_rejected: "The provider rejected the request.",
134
+ };
135
+
136
+ const PROVIDER_ID = /^[A-Za-z0-9._-]{1,64}$/;
137
+
138
+ /** Proxy-written text for a condition; the provider id comes from configuration, never from an error. */
139
+ export function upstreamConditionMessage(condition: UpstreamCondition, providerId?: string): string {
140
+ const base = MESSAGES[condition];
141
+ return providerId !== undefined && PROVIDER_ID.test(providerId) ? `${base} (provider: ${providerId})` : base;
142
+ }