@bitkyc08/opencodex 2.97.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 (290) hide show
  1. package/bin/ocx.mjs +1 -1
  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-CEw0y0jR.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/google.ts +7 -7
  123. package/src/adapters/kiro/adapter.ts +18 -3
  124. package/src/adapters/kiro/conversation.ts +8 -8
  125. package/src/adapters/kiro/payload.ts +45 -12
  126. package/src/adapters/kiro/stream.ts +169 -12
  127. package/src/adapters/kiro/structured-output-json.ts +191 -0
  128. package/src/adapters/kiro/structured-output-schema.ts +542 -0
  129. package/src/adapters/kiro/structured-output.ts +367 -0
  130. package/src/adapters/kiro-constants.ts +9 -0
  131. package/src/adapters/kiro-tools.ts +14 -9
  132. package/src/adapters/kiro-wire.ts +9 -5
  133. package/src/adapters/openai-chat/messages.ts +58 -5
  134. package/src/adapters/openai-chat/mistral-image-limit.ts +50 -0
  135. package/src/adapters/openai-chat/passthrough.ts +5 -3
  136. package/src/adapters/openai-chat/tool-schema.ts +83 -13
  137. package/src/adapters/openai-responses/opengateway-input.ts +18 -6
  138. package/src/adapters/openai-responses/tool-output-recovery.ts +79 -0
  139. package/src/adapters/qoder/live-models.ts +115 -1
  140. package/src/claude/failure-verdict.ts +21 -0
  141. package/src/claude/inbound-content-options.ts +15 -2
  142. package/src/claude/inbound-model-options.ts +2 -1
  143. package/src/claude/inbound-records.ts +2 -0
  144. package/src/claude/inbound.ts +17 -11
  145. package/src/claude/outbound.ts +52 -23
  146. package/src/cli/capabilities-access-remote.ts +13 -0
  147. package/src/cli/capabilities-base.ts +1 -0
  148. package/src/cli/capabilities-provider-models.ts +3 -3
  149. package/src/cli/codex-shim-autorestore.ts +7 -0
  150. package/src/cli/config-command.ts +11 -2
  151. package/src/cli/connect.ts +17 -2
  152. package/src/cli/dispatch.ts +3 -1
  153. package/src/cli/doctor.ts +95 -7
  154. package/src/cli/index.ts +12 -7
  155. package/src/cli/link-apply-restart.ts +9 -2
  156. package/src/cli/models.ts +124 -38
  157. package/src/cli/registry.ts +1 -1
  158. package/src/cli/restart-failure.ts +17 -0
  159. package/src/cli/stop-approval.ts +2 -2
  160. package/src/cli/sync-command.ts +1 -1
  161. package/src/cli/sync-fanout.ts +15 -4
  162. package/src/cli/system-restart-client.ts +5 -0
  163. package/src/cli/uninstall-client-state.ts +12 -1
  164. package/src/cli/update-restart-child.ts +13 -3
  165. package/src/cli/update-restart-home.ts +6 -3
  166. package/src/cli/update-restart.ts +36 -19
  167. package/src/client/connect.ts +4 -1
  168. package/src/client/hub-client.ts +5 -0
  169. package/src/client/link-management-relay.ts +39 -2
  170. package/src/client/link-readiness.ts +3 -1
  171. package/src/client/machine-api.ts +2 -1
  172. package/src/client/machine-listener.ts +7 -0
  173. package/src/client/orphan-token-recovery.ts +322 -0
  174. package/src/codex/catalog/provider-models.ts +12 -4
  175. package/src/codex/native-profile-api.ts +27 -1
  176. package/src/codex/shim-diagnostics.ts +7 -0
  177. package/src/codex/shim-legacy-record.ts +290 -0
  178. package/src/codex/shim-windows-refresh.ts +9 -2
  179. package/src/codex/shim-wrapper-write.ts +7 -0
  180. package/src/codex/shim.ts +80 -21
  181. package/src/config/diagnostics.ts +9 -9
  182. package/src/config/load-degrade.ts +27 -27
  183. package/src/config/provider-validation.ts +9 -2
  184. package/src/config/removed-opencode-free-backup.ts +6 -3
  185. package/src/config/tracked-runtime-inspection.ts +3 -3
  186. package/src/generated/compatibility-version.json +219 -147
  187. package/src/images/loop.ts +2 -2
  188. package/src/lib/client-error-body.ts +37 -6
  189. package/src/lib/config-ownership-removal.ts +422 -0
  190. package/src/lib/config-ownership.ts +646 -81
  191. package/src/lib/context-overflow-verdict.ts +3 -3
  192. package/src/lib/crash-guard.ts +4 -2
  193. package/src/lib/desktop-cli-handoff.d.mts +3 -4
  194. package/src/lib/desktop-cli-handoff.mjs +7 -16
  195. package/src/lib/errors.ts +1 -0
  196. package/src/lib/local-management-capability.ts +3 -1
  197. package/src/lib/messages-error-body.ts +162 -0
  198. package/src/lib/messages-sse-error-presentation.ts +93 -0
  199. package/src/lib/passive-read.ts +9 -4
  200. package/src/lib/socks5-fetch.ts +21 -9
  201. package/src/lib/upstream-retry.ts +81 -1
  202. package/src/lib/windows-owner-acl.ts +9 -3
  203. package/src/lib/winsw.ts +5 -5
  204. package/src/lib/workflow-budget.ts +3 -1
  205. package/src/oauth/index.ts +7 -0
  206. package/src/oauth/store.ts +20 -10
  207. package/src/protocols/codecs/messages-ir.ts +15 -9
  208. package/src/protocols/encoders/adapter-events.ts +26 -7
  209. package/src/protocols/encoders/messages.ts +72 -28
  210. package/src/providers/antigravity-models.ts +45 -12
  211. package/src/providers/free-directory.ts +2 -2
  212. package/src/providers/reasoning-metadata.ts +2 -1
  213. package/src/providers/registry/entries-extended.ts +9 -0
  214. package/src/reasoning-effort.ts +7 -2
  215. package/src/remote/hub-usage.ts +3 -0
  216. package/src/server/admission-model-scope.ts +1 -1
  217. package/src/server/admitted-http-turn.ts +2 -1
  218. package/src/server/anthropic-rate-limit-headers.ts +75 -3
  219. package/src/server/claude-messages.ts +130 -67
  220. package/src/server/gui-static.ts +4 -1
  221. package/src/server/hub-usage.ts +7 -2
  222. package/src/server/index/link-management.ts +8 -0
  223. package/src/server/index/ollama-routes.ts +2 -0
  224. package/src/server/index/serve-options.ts +23 -20
  225. package/src/server/index/startup-warnings.ts +5 -12
  226. package/src/server/index/websocket-handler.ts +1 -0
  227. package/src/server/inference/client-encoder-delivery.ts +5 -1
  228. package/src/server/management/logs-usage-routes.ts +89 -4
  229. package/src/server/management/provider-routes.ts +2 -22
  230. package/src/server/management/qoder-provider-probe.ts +105 -0
  231. package/src/server/management/route-registry.ts +3 -0
  232. package/src/server/management/usage-aggregate-cache.ts +15 -5
  233. package/src/server/management/usage-source-facets.ts +38 -0
  234. package/src/server/messages-native-tool-guard.ts +11 -3
  235. package/src/server/messages-native.ts +111 -40
  236. package/src/server/messages-response-headers.ts +25 -11
  237. package/src/server/messages-shared.ts +94 -64
  238. package/src/server/messages-sse-error-filter.ts +199 -0
  239. package/src/server/request-log.ts +12 -0
  240. package/src/server/responses/adapter-continuation.ts +11 -5
  241. package/src/server/responses/adapter-delivery.ts +14 -8
  242. package/src/server/responses/adapter-dispatch.ts +8 -8
  243. package/src/server/responses/anthropic-thinking-recovery.ts +2 -2
  244. package/src/server/responses/codex-auth-error.ts +8 -4
  245. package/src/server/responses/codex-ws-wire.ts +19 -3
  246. package/src/server/responses/compact.ts +4 -1
  247. package/src/server/responses/core-auth.ts +1 -1
  248. package/src/server/responses/core-combo-failure.ts +2 -0
  249. package/src/server/responses/core-combo.ts +2 -0
  250. package/src/server/responses/core-errors.ts +5 -4
  251. package/src/server/responses/core-options.ts +2 -0
  252. package/src/server/responses/empty-completion-guard.ts +4 -1
  253. package/src/server/responses/pacing-overload.ts +1 -1
  254. package/src/server/responses/passthrough-dispatch.ts +5 -5
  255. package/src/server/responses/request-prepare.ts +3 -1
  256. package/src/server/responses/request-transport.ts +9 -8
  257. package/src/server/responses/response-effects.ts +3 -2
  258. package/src/server/responses/terminal-guard.ts +30 -0
  259. package/src/server/restart-replacement.ts +3 -1
  260. package/src/server/sse-payload-rewrite.ts +23 -11
  261. package/src/server/workflow-refusal.ts +1 -1
  262. package/src/server/ws-bridge.ts +4 -0
  263. package/src/service/definition.ts +36 -4
  264. package/src/service/launchd.ts +89 -32
  265. package/src/service/logging.ts +34 -7
  266. package/src/service/plist-xml.ts +59 -0
  267. package/src/service/state.ts +8 -0
  268. package/src/service/systemd-env.ts +2 -0
  269. package/src/service/systemd.ts +31 -7
  270. package/src/service/windows-taskxml.ts +16 -7
  271. package/src/service-manager-probe.ts +4 -10
  272. package/src/types/provider.ts +2 -0
  273. package/src/types/request.ts +13 -1
  274. package/src/update/config-preflight.ts +48 -0
  275. package/src/update/index.ts +15 -1
  276. package/src/usage/client.ts +43 -0
  277. package/src/usage/error-detail.ts +1 -1
  278. package/src/usage/log.ts +4 -0
  279. package/src/usage/source-facets.ts +51 -0
  280. package/src/usage/source-filter.ts +65 -0
  281. package/src/usage/summary.ts +50 -8
  282. package/src/web-search/anthropic-executor.ts +105 -24
  283. package/src/web-search/executor.ts +5 -3
  284. package/src/web-search/loop.ts +2 -1
  285. package/src/web-search/progress-stream.ts +64 -5
  286. package/gui/dist/assets/App-DuNhggE1.js +0 -58
  287. package/gui/dist/assets/index-CynE_Rue.js +0 -94
  288. package/gui/dist/assets/quota-summary-VHFSlUuM.js +0 -1
  289. /package/gui/dist/{assets → classic/assets}/App-B4j-Txmb.css +0 -0
  290. /package/gui/dist/{assets → classic/assets}/index-CHWwDo9L.css +0 -0
@@ -8,9 +8,9 @@ import { BUN_RUNTIME_PATH_ENV, BUN_RUNTIME_SOURCE_ENV, durableBunRuntime, type D
8
8
  import { recordOwnedConfigPath } from "../lib/config-ownership";
9
9
  import { systemdProperty } from "../service-manager-probe";
10
10
  import { writeServiceApiTokenFile, sh } from "./guards";
11
- import { shellQuote, buildServiceShellCommand, buildServiceLauncherShellCommand, resolvedProxyEnv } from "./definition";
11
+ import { shellQuote, buildServiceShellCommand, buildServiceLauncherShellCommand, resolvedProxyEnv, pinnedServiceHomeShellAssignments } from "./definition";
12
12
  import type { ServiceInstallCleanupOps } from "./orchestration";
13
- import { SERVICE_MANAGED_ENV, TASK, cliEntry, filterTransientServicePath, stableLauncherEntry, logPath, serviceStatePath, currentCodexSqliteHomeAbsolute, writeServiceInstallState } from "./state";
13
+ import { SERVICE_MANAGED_ENV, TASK, cliEntry, filterTransientServicePath, stableLauncherEntry, logPath, serviceStatePath, currentCodexSqliteHomeAbsolute, currentCodexHome, currentOpenCodexHome, writeServiceInstallState } from "./state";
14
14
  import { writeServiceDefinitionFile } from "./windows-ops";
15
15
 
16
16
  /** The `--port <n>` baked into the installed systemd user unit. Linux only. */
@@ -26,12 +26,29 @@ export function systemdListenPort(deps: { readUnit?: () => string } = {}): numbe
26
26
  }
27
27
  }
28
28
 
29
+ /**
30
+ * Quote one word for a systemd unit setting. systemd unquotes double-quoted words with C-style
31
+ * escapes (systemd.syntax), so backslash, double quote and line breaks are escaped, and it
32
+ * resolves `%` specifiers in every setting used here, so a literal `%` becomes `%%`.
33
+ */
29
34
  function systemdQuote(value: string): string {
30
35
  return `"${value
31
36
  .replace(/\\/g, "\\\\")
32
37
  .replace(/"/g, "\\\"")
33
38
  .replace(/%/g, "%%")
34
- .replace(/\n/g, "\\n")}"`;
39
+ .replace(/\n/g, "\\n")
40
+ .replace(/\r/g, "\\r")
41
+ .replace(/\t/g, "\\t")}"`;
42
+ }
43
+
44
+ /**
45
+ * Quote one ExecStart= word. On top of {@link systemdQuote}, ExecStart= expands `$NAME` and
46
+ * `${NAME}` from the unit environment before the program runs (systemd.service, "Command
47
+ * lines"), so a literal `$` must be written `$$`. Environment= does not expand variables,
48
+ * which is why this escape stays out of the shared quoting.
49
+ */
50
+ function systemdExecQuote(value: string): string {
51
+ return systemdQuote(value).replace(/\$/g, "$$$$");
35
52
  }
36
53
 
37
54
  function systemdEnvironmentAssignment(name: string, value: string | undefined): string | null {
@@ -60,9 +77,16 @@ export function buildUnit(
60
77
  const launcher = deps.launcher ?? null;
61
78
  const log = logPath();
62
79
  const path = filterTransientServicePath(process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin", ":", "linux");
63
- const codexHome = systemdEnvironmentAssignment("CODEX_HOME", process.env.CODEX_HOME?.trim());
80
+ // Resolve each home once: the default Codex home follows filesystem state (a retargeted
81
+ // ~/.codex link), so a second resolution could write two different homes into one unit.
82
+ const codexHomeValue = currentCodexHome();
83
+ const opencodexHomeValue = currentOpenCodexHome();
84
+ const codexHome = systemdEnvironmentAssignment("CODEX_HOME", codexHomeValue);
64
85
  const codexSqliteHome = systemdEnvironmentAssignment("CODEX_SQLITE_HOME", currentCodexSqliteHomeAbsolute());
65
- const opencodexHome = systemdEnvironmentAssignment("OPENCODEX_HOME", process.env.OPENCODEX_HOME?.trim());
86
+ const opencodexHome = systemdEnvironmentAssignment("OPENCODEX_HOME", opencodexHomeValue);
87
+ // The Environment= lines are a first pin only: ExecStart is /bin/sh -lc, so a login profile
88
+ // can re-export the homes after systemd supplies them. The command re-assigns both after
89
+ // profile initialization and before exec, with the same shell quoting the rest of the line uses.
66
90
  const envLines = [
67
91
  systemdEnvironmentAssignment("OCX_SERVICE", "1"),
68
92
  systemdEnvironmentAssignment(SERVICE_MANAGED_ENV, "1"),
@@ -82,7 +106,7 @@ export function buildUnit(
82
106
  opencodexHome,
83
107
  ...proxyEnv.map(({ name, value }) => systemdEnvironmentAssignment(name, value)),
84
108
  ].filter((line): line is string => Boolean(line)).join("\n");
85
- const command = `${launcher ? buildServiceLauncherShellCommand(launcher) : buildServiceShellCommand(bun, cli)} >> ${shellQuote(log)} 2>&1`;
109
+ const command = `${pinnedServiceHomeShellAssignments(codexHomeValue, opencodexHomeValue)} ${launcher ? buildServiceLauncherShellCommand(launcher) : buildServiceShellCommand(bun, cli)} >> ${shellQuote(log)} 2>&1`;
86
110
  return `[Unit]
87
111
  Description=OpenCodex Proxy Server
88
112
  After=network-online.target
@@ -90,7 +114,7 @@ Wants=network-online.target
90
114
 
91
115
  [Service]
92
116
  Type=simple
93
- ExecStart=${systemdQuote("/bin/sh")} -lc ${systemdQuote(command)}
117
+ ExecStart=${systemdExecQuote("/bin/sh")} -lc ${systemdExecQuote(command)}
94
118
  Restart=on-failure
95
119
  RestartSec=5
96
120
  ${envLines}
@@ -9,12 +9,19 @@ import { serviceApiTokenFilePath } from "../lib/service-secrets";
9
9
  import { windowsEnvIndirectBatchPathList, windowsEnvIndirectBatchValue } from "../lib/win-paths";
10
10
  import { cachedCurrentWindowsIdentity, resolveCurrentWindowsPrincipal, WINDOWS_PRINCIPAL_LOOKUP_TIMEOUT_MS } from "../lib/windows-user-principal";
11
11
  import { resolveServiceListenPort, resolvedProxyEnv } from "./definition";
12
- import { cliEntry, filterTransientServicePath, serviceLogPath, currentCodexSqliteHomeAbsolute } from "./state";
12
+ import { cliEntry, filterTransientServicePath, serviceLogPath, currentCodexSqliteHomeAbsolute, currentWindowsServiceCodexHome, currentOpenCodexHome } from "./state";
13
13
 
14
+ /**
15
+ * Escape a value for the quoted `set "NAME=value"` form every wrapper assignment uses.
16
+ * Inside the quotes cmd treats `^`, `&`, `|`, `<`, `>` and parentheses as literal, so a
17
+ * caret must stay single: doubling it would point the variable at a different path. Percent
18
+ * expansion still runs in a batch file, so `%` becomes `%%`. `!` is literal because the
19
+ * wrapper runs under DisableDelayedExpansion. A quote or line break cannot be represented
20
+ * and is dropped.
21
+ */
14
22
  function windowsBatchValue(value: string): string {
15
23
  return value
16
24
  .replace(/%/g, "%%")
17
- .replace(/\^/g, "^^")
18
25
  .replace(/"/g, "")
19
26
  .replace(/[\r\n]/g, "");
20
27
  }
@@ -80,12 +87,14 @@ export function buildWindowsServiceScript(
80
87
  windowsBatchSet(BUN_RUNTIME_SOURCE_ENV, bunRuntimeSource),
81
88
  windowsBatchSet(BUN_RUNTIME_PATH_ENV, bun, "path"),
82
89
  windowsBatchSet("PATH", path, "pathList"),
83
- windowsBatchSet("CODEX_HOME", process.env.CODEX_HOME?.trim(), "path"),
84
- windowsBatchSet("CODEX_SQLITE_HOME", currentCodexSqliteHomeAbsolute("windows"), "path"),
85
- windowsBatchSet("OPENCODEX_HOME", process.env.OPENCODEX_HOME?.trim(), "path"),
90
+ windowsBatchSet("CODEX_HOME", currentWindowsServiceCodexHome()),
91
+ windowsBatchSet("CODEX_SQLITE_HOME", currentCodexSqliteHomeAbsolute("windows")),
92
+ windowsBatchSet("OPENCODEX_HOME", currentOpenCodexHome()),
86
93
  ...proxyEnv.map(({ name, value }) => windowsBatchSet(name, value)),
87
- windowsBatchSet("OCX_API_TOKEN_FILE", serviceApiTokenFilePath(), "path"),
88
- windowsBatchSet("OCX_SERVICE_LOG", serviceLogPath(), "path"),
94
+ // Absolute like the homes above: a profile-variable form could read the token, or write
95
+ // the log, under another profile than the home the proxy is pinned to.
96
+ windowsBatchSet("OCX_API_TOKEN_FILE", serviceApiTokenFilePath()),
97
+ windowsBatchSet("OCX_SERVICE_LOG", serviceLogPath()),
89
98
  windowsBatchSet("OCX_BUN", bun, "path"),
90
99
  windowsBatchSet("OCX_CLI", cli ?? undefined, "path"),
91
100
  // Standalone executables have no npm package tree; recovery is "replace the executable", so no OCX_PKG_DIR/restore_backup wiring.
@@ -28,6 +28,7 @@ import {
28
28
  } from "./lib/windows-elevation";
29
29
  import { decodeWindowsTextBytes } from "./lib/windows-text";
30
30
  import { WINSW_SERVICE_ID } from "./lib/winsw";
31
+ import { decodePlistString } from "./service/plist-xml";
31
32
  import { BUN_RUNTIME_PATH_ENV, BUN_RUNTIME_SOURCE_ENV } from "./lib/bun-runtime";
32
33
  import { REAL_BUN_MIN_BYTES } from "./lib/bun-binary-validator.mjs";
33
34
  import { WINDOWS_WRAPPER_PROTOCOL_ENV, WINDOWS_WRAPPER_STAY_OUT_EXIT_CODE } from "./service/windows-wrapper-exit";
@@ -247,16 +248,9 @@ function unknown(reason: string): ServiceManagerInstallation {
247
248
  return { kind: "unknown", reason };
248
249
  }
249
250
 
250
- /** Decode the entities buildPlist's plistString applies. `&amp;` goes last so a
251
- * literal `&amp;lt;` written by a double-escaped value stays `&lt;`. */
252
- function plistStringValue(raw: string): string {
253
- return raw
254
- .replace(/&lt;/g, "<")
255
- .replace(/&gt;/g, ">")
256
- .replace(/&quot;/g, "\"")
257
- .replace(/&apos;/g, "'")
258
- .replace(/&amp;/g, "&");
259
- }
251
+ /** Decode the entities and character references buildPlist's encoder applies, in one pass,
252
+ * so a literal `&amp;lt;` written by a double-escaped value stays `&lt;`. */
253
+ const plistStringValue = decodePlistString;
260
254
 
261
255
  /** Pull `<key>NAME</key><string>VALUE</string>` out of a plist body. */
262
256
  function plistEnvValue(body: string, key: string): string | null {
@@ -294,6 +294,8 @@ export interface ModelCapabilities extends ReasoningCapabilities {
294
294
  video?: { processing?: "static" | "agentic" };
295
295
  /** Opt in exact first-party DeepSeek models to one-hour image file persistence. */
296
296
  deepseekImageFiles?: boolean;
297
+ /** Images a first-party Mistral Chat request may carry for this model; older ones are pruned. */
298
+ mistralMaxImages?: number;
297
299
  }
298
300
 
299
301
  /**
@@ -86,6 +86,11 @@ export interface OcxParsedRequest {
86
86
  * followed them (`call:<tool_use id>` / `text:<text>`). Same audience as `_anthropicServerTools`.
87
87
  */
88
88
  _anthropicServerReplay?: ReadonlyMap<string, readonly Record<string, unknown>[]>;
89
+ /**
90
+ * The caller's `instructions` prefix through its last cache-marked system block. The anthropic
91
+ * adapter ends a system block there so the breakpoint stays off the per-turn tail.
92
+ */
93
+ _anthropicSystemCachePrefix?: string;
89
94
  /**
90
95
  * Boundary between replayed history and this turn's newly appended input. Usually the
91
96
  * items the proxy restored from local previous_response_id state; also set when the
@@ -180,6 +185,13 @@ export interface OcxParsedRequest {
180
185
  * answer/"Sources:" text can't bleed into and corrupt the model's schema-constrained output.
181
186
  */
182
187
  _structuredOutput?: boolean;
188
+ /**
189
+ * True for a Claude Messages `output_config.format` json_schema. Anthropic promises an answer
190
+ * that conforms to that schema, whatever `strict` the Responses translation states for
191
+ * OpenAI-compatible destinations, so an emulating adapter (Kiro) holds it to full conformance.
192
+ * Process-local; never forwarded.
193
+ */
194
+ _structuredOutputConformance?: boolean;
183
195
  /**
184
196
  * True when the input carried `{type:"compaction_trigger"}` — Codex remote compaction v2 asking
185
197
  * this turn to produce a `{type:"compaction"}` output item. Routed adapters can't natively;
@@ -414,7 +426,7 @@ export interface OcxRequestOptions {
414
426
  * upstream wire has an equivalent. The openai-chat adapter re-nests it as chat
415
427
  * `response_format`, the exact inverse of responseFormatToText in src/chat/inbound.ts.
416
428
  * The native passthrough ignores it (it forwards `_rawBody.text` verbatim) and Kiro
417
- * keeps rejecting structured output via `_structuredOutput`.
429
+ * emulates it through a private structured-output tool (src/adapters/kiro/structured-output.ts).
418
430
  */
419
431
  textFormat?: {
420
432
  type: "json_schema" | "json_object";
@@ -0,0 +1,48 @@
1
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync } from "node:fs";
2
+ import { configDiagnosticsFromRaw } from "../config/diagnostics";
3
+
4
+ export interface ConfigPreflightResult {
5
+ ok: boolean;
6
+ reason?: "fallback" | "read_error";
7
+ error?: string;
8
+ }
9
+
10
+ /** Observe the same opened file for type and passive runtime loadability. */
11
+ export function runConfigPreflight(configPath: string, open: typeof openSync = openSync, close: typeof closeSync = closeSync): ConfigPreflightResult {
12
+ let fd: number;
13
+ try {
14
+ // Nonblocking open avoids hanging on a FIFO before its type can be checked.
15
+ fd = open(configPath, constants.O_RDONLY | constants.O_NONBLOCK);
16
+ } catch (error: unknown) {
17
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") {
18
+ try {
19
+ // A dangling link occupies the path even though opening its target failed.
20
+ lstatSync(configPath);
21
+ } catch (entryError: unknown) {
22
+ if ((entryError as NodeJS.ErrnoException).code === "ENOENT") return { ok: true };
23
+ }
24
+ }
25
+ return { ok: false, reason: "read_error", error: "Configuration cannot be read as a regular file." };
26
+ }
27
+
28
+ let result: ConfigPreflightResult;
29
+ try {
30
+ if (!fstatSync(fd).isFile()) {
31
+ result = { ok: false, reason: "read_error", error: "Configuration is not a regular file." };
32
+ } else {
33
+ const raw = readFileSync(fd, "utf8");
34
+ result = runtimeAcceptsConfig(raw) ? { ok: true } : { ok: false, reason: "fallback", error: "Configuration failed to load." };
35
+ }
36
+ } catch {
37
+ result = { ok: false, reason: "read_error", error: "Configuration cannot be read as a regular file." };
38
+ } finally {
39
+ try { close(fd); } catch { result = { ok: false, reason: "read_error", error: "Configuration cannot be read as a regular file." }; }
40
+ }
41
+ return result;
42
+ }
43
+
44
+ function runtimeAcceptsConfig(raw: string): boolean {
45
+ // Imported text takes the same passive path as disk diagnostics, without a backup.
46
+ // Discard configuration-derived warnings, including provider and model names.
47
+ return configDiagnosticsFromRaw(raw, { warn: () => {} }).source === "file";
48
+ }
@@ -10,7 +10,8 @@ import { decidePostStopUpdate } from "./stop-decision.mjs";
10
10
  import { existsSync, readFileSync, readdirSync, realpathSync } from "node:fs";
11
11
  import { fileURLToPath } from "node:url";
12
12
  import { dirname, join, resolve } from "node:path";
13
- import { getConfigDir, loadConfig } from "../config";
13
+ import { getConfigDir, getConfigPath, loadConfig } from "../config";
14
+ import { runConfigPreflight } from "./config-preflight";
14
15
  import { readPid, readRuntimePort, getRuntimePortPath } from "../config/process-state";
15
16
  import { pendingTeardownOutstanding } from "../config/pending-teardown";
16
17
  import type { ServiceOwnership } from "../service/state";
@@ -561,6 +562,19 @@ async function runUpdateWithSession(child: Extract<OrchestratedChildArgs, { ok:
561
562
  const { inspectUpdateServiceHome } = await import("./service-home-authority");
562
563
  const homePolicy = createUpdateServiceHomePolicy(inspectUpdateServiceHome, message => console.warn(message), process.argv.includes("--update-package-only"), parseUpdateWorkerHome(process.argv));
563
564
  if (!homePolicy.authorizeMutation("package")) return 1;
565
+ const configPath = getConfigPath(), configPreflight = runConfigPreflight(configPath);
566
+ if (!configPreflight.ok) {
567
+ console.error(`⚠️ Configuration preflight failed for ${configPath}; aborting update before stopping services.`);
568
+ if (configPreflight.error) console.error(` ${configPreflight.error}`);
569
+ if (configPreflight.reason === "read_error") {
570
+ console.error(" Inspect the config path, permissions, and any symlink target; correct them or restore a readable regular config from a trusted backup, then retry.");
571
+ console.error(" 'ocx config validate' may report defaults if a symlink target is missing; it does not change the file.");
572
+ } else {
573
+ console.error(" Run 'ocx config validate' to diagnose the configuration; it does not change the file. Back up and correct the file, then retry.");
574
+ }
575
+ return 1;
576
+ }
577
+
564
578
  // Remember whether a background service manages the proxy BEFORE stopping — `ocx stop`
565
579
  // unloads it, so a successful update must repair/restart it afterwards.
566
580
  let serviceWasInstalled = false;
@@ -0,0 +1,43 @@
1
+ /** A bounded, observational client label. Header values themselves are never returned. */
2
+ export const USAGE_CLIENTS = [
3
+ "codex_cli", "codex_desktop", "codex_ide", "claude_code", "claude_desktop",
4
+ "grok", "opencode", "aside", "other", "unknown",
5
+ ] as const;
6
+
7
+ export type UsageClient = (typeof USAGE_CLIENTS)[number];
8
+
9
+ const KNOWN_CLIENTS: ReadonlySet<string> = new Set(USAGE_CLIENTS);
10
+ const MAX_HEADER_LENGTH = 1024;
11
+
12
+ /** Preserve absence on legacy rows; a present invalid value is explicitly unknown. */
13
+ export function normalizeRecordedClient(value: unknown): UsageClient | undefined {
14
+ if (value === undefined) return undefined;
15
+ return typeof value === "string" && KNOWN_CLIENTS.has(value) ? value as UsageClient : "unknown";
16
+ }
17
+
18
+ /**
19
+ * Classify only signatures established by existing client fixtures or upstream sources.
20
+ * These headers can be supplied by callers and must never authorize an action.
21
+ */
22
+ export function classifyUsageClient(headers: Headers): UsageClient {
23
+ const originator = headers.get("originator") ?? "";
24
+ const userAgent = headers.get("user-agent") ?? "";
25
+ if (originator.length > MAX_HEADER_LENGTH || userAgent.length > MAX_HEADER_LENGTH) return "unknown";
26
+
27
+ let originClient: UsageClient | undefined;
28
+ if (originator === "codex_cli_rs" || originator === "codex-tui") originClient = "codex_cli";
29
+ else if (originator === "Codex Desktop" || originator === "codex_desktop") originClient = "codex_desktop";
30
+ else if (originator === "codex_vscode") originClient = "codex_ide";
31
+ else if (originator === "opencode") originClient = "opencode";
32
+
33
+ const claudeEntrypoint = /^claude-cli\/[A-Za-z0-9][A-Za-z0-9._+-]* \(external, ([A-Za-z0-9._-]+)(?:, [^,()]+)*\)$/i.exec(userAgent)?.[1]?.toLowerCase();
34
+ let agentClient: UsageClient | undefined;
35
+ if (claudeEntrypoint === "cli" || claudeEntrypoint === "sdk-cli") agentClient = "claude_code";
36
+ else if (claudeEntrypoint === "claude-desktop" || claudeEntrypoint === "claude-desktop-3p" || claudeEntrypoint === "local-agent") agentClient = "claude_desktop";
37
+ else if (/^claude-code\/[A-Za-z0-9][A-Za-z0-9._+-]*(?:\s|$)/i.test(userAgent)) agentClient = "claude_code";
38
+ else if (/^opencode\/[A-Za-z0-9][A-Za-z0-9._+-]*(?:\s|$)/i.test(userAgent)) agentClient = "opencode";
39
+ else if (/^codex_cli_rs\/[A-Za-z0-9][A-Za-z0-9._+-]*(?:\s|$)/i.test(userAgent)) agentClient = "codex_cli";
40
+ if (originClient && agentClient && originClient !== agentClient
41
+ && !(originClient.startsWith("codex_") && agentClient.startsWith("codex_"))) return "unknown";
42
+ return originClient ?? agentClient ?? "unknown";
43
+ }
@@ -150,7 +150,7 @@ export function errorDetailFor(entry: ErrorDetailSource): ErrorDetail {
150
150
  });
151
151
  }
152
152
  const rateLimitResetAt = boundedRateLimitResetAt(entry.rateLimitResetAt, entry.timestamp)
153
- ?? deriveRateLimitResetAt({ ...entry, errorCode });
153
+ ?? deriveRateLimitResetAt({ provider: entry.provider, status: entry.status, timestamp: entry.timestamp, upstreamError: entry.upstreamError, errorCode });
154
154
  // A closed code with bounded parameters; free text (a legacy or edited row) is dropped.
155
155
  const failureDetail = boundedFailureDetail(entry.failureDetail) ?? proxySentenceDetail(str(entry.upstreamError));
156
156
  return {
package/src/usage/log.ts CHANGED
@@ -10,6 +10,7 @@ import { enforceAppOwnedMemoryBudget } from "../lib/app-owned-memory";
10
10
  import { recordOwnedConfigPath } from "../lib/config-ownership";
11
11
  import { sanitizeLogMetadataString } from "../lib/redact";
12
12
  import { usageDisplayTotalTokens } from "./totals";
13
+ import { normalizeRecordedClient, type UsageClient } from "./client";
13
14
  import {
14
15
  normalizePersistedJevDecision,
15
16
  type PersistedJevDecisionV1,
@@ -304,6 +305,8 @@ export function normalizeRequestSpend(value: unknown): PersistedRequestSpend | u
304
305
  export interface PersistedUsageEntry {
305
306
  requestedAlias?: string;
306
307
  requestId: string;
308
+ /** Best-effort classified client; absent only for records predating attribution. */
309
+ client?: UsageClient;
307
310
  /**
308
311
  * Identity of the ONE logical request this row belongs to (#4546), minted by
309
312
  * `createRequestExecutionBudget` at ingress. `requestId` identifies a log row; a retry layer,
@@ -1035,6 +1038,7 @@ function normalizeUsageEntry(entry: PersistedUsageEntry): PersistedUsageEntry {
1035
1038
  const protocolTrace = parseProtocolTraceV1(entry.protocolTrace);
1036
1039
  const normalized: PersistedUsageEntry = {
1037
1040
  requestId: entry.requestId,
1041
+ ...(Object.hasOwn(entry, "client") ? { client: normalizeRecordedClient(entry.client) ?? "unknown" } : {}),
1038
1042
  ...(isLogicalRequestId(entry.logicalRequestId) ? { logicalRequestId: entry.logicalRequestId } : {}),
1039
1043
  timestamp: entry.timestamp,
1040
1044
  provider: entry.provider,
@@ -0,0 +1,51 @@
1
+ import type { PersistedUsageEntry } from "./log";
2
+ import { isLegacyCodexUsage, matchesUsageSource, snapshotConfiguredKeyIds, USAGE_SOURCE_CLIENTS,
3
+ type UsageDeviceFilter, type UsageSourceClient, type UsageSourceFilter } from "./source-filter";
4
+ import type { UsageTimeWindow } from "./time-range";
5
+
6
+ /** Fold request rows once. Only currently configured IDs get individual counters. */
7
+ export function createSourceFacetAccumulator(filter: UsageSourceFilter, ids: readonly string[], window: UsageTimeWindow) {
8
+ const configured = new Set(snapshotConfiguredKeyIds(ids));
9
+ const apps = Object.fromEntries(USAGE_SOURCE_CLIENTS.map(client => [client, 0])) as Record<UsageSourceClient, number>;
10
+ // Preserve every exact ID in `configured` for filtering, but do not advertise an
11
+ // ID the wire contract cannot select (a padded ID cannot be safely trimmed).
12
+ const selectable = [...configured].filter(id => id === id.trim()).sort();
13
+ const unavailableConfiguredKeys = configured.size - selectable.length;
14
+ const keys = new Map(selectable.map(id => [id, 0]));
15
+ let all = 0;
16
+ let noKey = 0;
17
+ let unconfigured = 0;
18
+ let legacyUnclassifiedRequests = 0;
19
+ const selectedDevice = { ...filter.device };
20
+ const matches = (entry: PersistedUsageEntry, client: UsageSourceClient, device: UsageDeviceFilter) =>
21
+ matchesUsageSource(entry, { client, device }, configured);
22
+ return {
23
+ add(entry: PersistedUsageEntry) {
24
+ if (!Number.isFinite(entry.timestamp) || entry.timestamp < window.since || entry.timestamp > window.until) return;
25
+ for (const client of USAGE_SOURCE_CLIENTS) {
26
+ if (matches(entry, client, selectedDevice)) apps[client] += 1;
27
+ }
28
+ // This is the unclassified subset of the Codex option, independently of the
29
+ // currently selected app; the app facets all share the selected device scope.
30
+ if (matches(entry, "codex", selectedDevice) && isLegacyCodexUsage(entry)) legacyUnclassifiedRequests += 1;
31
+ if (!matches(entry, filter.client, { kind: "all" })) return;
32
+ all += 1;
33
+ if (entry.apiKeyId === undefined) noKey += 1;
34
+ else if (keys.has(entry.apiKeyId)) keys.set(entry.apiKeyId, keys.get(entry.apiKeyId)! + 1);
35
+ if (matches(entry, filter.client, { kind: "unconfigured" })) unconfigured += 1;
36
+ },
37
+ snapshot() {
38
+ return {
39
+ apps: { ...apps },
40
+ devices: [
41
+ { device: { kind: "all" as const }, requests: all },
42
+ { device: { kind: "no-key" as const }, requests: noKey },
43
+ ...[...keys].map(([id, requests]) => ({ device: { kind: "key" as const, id }, requests })),
44
+ { device: { kind: "unconfigured" as const }, requests: unconfigured },
45
+ ],
46
+ legacyUnclassifiedRequests,
47
+ unavailableConfiguredKeys,
48
+ };
49
+ },
50
+ };
51
+ }
@@ -0,0 +1,65 @@
1
+ import type { PersistedUsageEntry } from "./log";
2
+
3
+ export const USAGE_SOURCE_CLIENTS = [
4
+ "all", "codex", "claude_code", "claude_desktop", "grok", "opencode", "aside", "other", "unknown",
5
+ ] as const;
6
+ export type UsageSourceClient = (typeof USAGE_SOURCE_CLIENTS)[number];
7
+ export type UsageDeviceFilter = { kind: "all" | "no-key" | "unconfigured" } | { kind: "key"; id: string };
8
+ export interface UsageSourceFilter { client: UsageSourceClient; device: UsageDeviceFilter }
9
+
10
+ /** Reject excessive snapshots instead of truncating identity or retaining unbounded keys. */
11
+ export const MAX_USAGE_CONFIGURED_KEYS = 1024;
12
+ export function snapshotConfiguredKeyIds(ids: readonly string[]): string[] {
13
+ if (ids.length > MAX_USAGE_CONFIGURED_KEYS) throw new Error("configured key snapshot exceeds limit");
14
+ let size = 0;
15
+ for (const id of ids) {
16
+ if (typeof id !== "string" || !id || id.length > 256 || (size += id.length) > 65536) {
17
+ throw new Error("configured key snapshot exceeds limit");
18
+ }
19
+ }
20
+ return [...new Set(ids)].sort();
21
+ }
22
+
23
+ /** Old rows in the historic Codex surface are disclosed as unclassified, never as a subtype. */
24
+ export function isLegacyCodexUsage(entry: PersistedUsageEntry): boolean {
25
+ return entry.client === undefined && entry.surface === undefined;
26
+ }
27
+
28
+ export function matchesUsageSource(entry: PersistedUsageEntry, filter: UsageSourceFilter, configuredIds?: ReadonlySet<string>): boolean {
29
+ const device = filter.device;
30
+ if (device.kind === "no-key" && entry.apiKeyId !== undefined) return false;
31
+ if (device.kind === "key" && entry.apiKeyId !== device.id) return false;
32
+ if (device.kind === "unconfigured" && (!configuredIds || entry.admissionKind !== "configured"
33
+ || !entry.apiKeyId || configuredIds.has(entry.apiKeyId))) return false;
34
+ if (filter.client === "all") return true;
35
+ if (filter.client === "codex") {
36
+ return isLegacyCodexUsage(entry) || entry.client === "codex_cli"
37
+ || entry.client === "codex_desktop" || entry.client === "codex_ide";
38
+ }
39
+ if (filter.client === "unknown") return entry.client === "unknown" || (entry.client === undefined && !isLegacyCodexUsage(entry));
40
+ return entry.client === filter.client;
41
+ }
42
+
43
+ export type ParsedUsageSource =
44
+ | { kind: "legacy" }
45
+ | { kind: "invalid" }
46
+ | { kind: "filtered"; filter: UsageSourceFilter };
47
+
48
+ /** Parse a management query without letting absent or malformed fields broaden its scope. */
49
+ export function parseUsageSource(params: URLSearchParams): ParsedUsageSource {
50
+ if (!params.has("client") && !params.has("device")) return { kind: "legacy" };
51
+ if (params.getAll("client").length !== 1 || params.getAll("device").length !== 1
52
+ || params.getAll("surface").length > 1 || params.getAll("apiKeyId").length > 1
53
+ || (params.has("surface") && params.get("surface") !== "all")
54
+ || params.has("jev") || params.has("failures")) return { kind: "invalid" };
55
+ const client = params.get("client");
56
+ const device = params.get("device");
57
+ if (!client || !(USAGE_SOURCE_CLIENTS as readonly string[]).includes(client)) return { kind: "invalid" };
58
+ if (device === "key") {
59
+ const id = params.get("apiKeyId");
60
+ if (!id || id !== id.trim()) return { kind: "invalid" };
61
+ return { kind: "filtered", filter: { client: client as UsageSourceClient, device: { kind: "key", id } } };
62
+ }
63
+ if ((device !== "all" && device !== "no-key" && device !== "unconfigured") || params.has("apiKeyId")) return { kind: "invalid" };
64
+ return { kind: "filtered", filter: { client: client as UsageSourceClient, device: { kind: device } } };
65
+ }