@bitkyc08/opencodex 2.97.0 → 2.98.0

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-FQ0OtiMJ.js +59 -0
  4. package/gui/dist/assets/Tray-D2d5wqLq.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-A03mw_9y.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-BjTIN4to.js +94 -0
  111. package/gui/dist/assets/segment-thumb-features-Bf6vpwf8.js +1 -0
  112. package/gui/dist/classic/assets/App-C9Eg3nUo.js +58 -0
  113. package/gui/dist/{assets/Tray-CEw0y0jR.js → classic/assets/Tray-B8P8cokE.js} +1 -1
  114. package/gui/dist/classic/assets/index-DFAFnven.js +94 -0
  115. package/gui/dist/classic/assets/quota-summary-C-4HP4_5.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
@@ -2,6 +2,7 @@ import type { OcxConfig } from "../types";
2
2
  import { MAX_HUB_USAGE_BYTES, parseHubUsage } from "../remote/hub-usage";
3
3
  import { parseRange, parseUsageSurface, USAGE_RANGES, USAGE_SURFACES } from "../usage/summary";
4
4
  import { parseUsageTimeWindow } from "../usage/time-range";
5
+ import { USAGE_SOURCE_CLIENTS, type UsageSourceClient } from "../usage/source-filter";
5
6
  import { getFilteredUsageAggregate } from "./management/usage-aggregate-cache";
6
7
  import { isAllowedRequestOrigin, resolveDataPlaneAdmissionSecret, withCors, type DataPlaneAdmissionOptions, type RequestPolicyView } from "./auth-cors";
7
8
 
@@ -22,14 +23,16 @@ export async function handleHubUsage(req: Request, config: OcxConfig, policy: Re
22
23
  // this authenticated identity into another configured key (or no filter).
23
24
  if (!keyId || keyId.trim() !== keyId) return error("hub_usage_key_id_invalid", "Client key identity needs repair on the hub", 403);
24
25
  const query = new URL(req.url).searchParams;
25
- const allowed = new Set(["range", "surface", "provider", "model", "since", "until"]);
26
+ const allowed = new Set(["range", "surface", "provider", "model", "since", "until", "client"]);
26
27
  for (const key of query.keys()) {
27
28
  if (!allowed.has(key) || query.getAll(key).length !== 1) return error("hub_usage_query_invalid", "Unknown or repeated usage option", 400);
28
29
  }
29
30
  const rangeInput = query.get("range") ?? "30d";
30
31
  const surfaceInput = query.get("surface") ?? "all";
32
+ const client = query.get("client");
31
33
  if (!(rangeInput === "1d" || (USAGE_RANGES as readonly string[]).includes(rangeInput))
32
- || !(USAGE_SURFACES as readonly string[]).includes(surfaceInput)) {
34
+ || !(USAGE_SURFACES as readonly string[]).includes(surfaceInput)
35
+ || (client !== null && (!(USAGE_SOURCE_CLIENTS as readonly string[]).includes(client) || surfaceInput !== "all"))) {
33
36
  return error("hub_usage_query_invalid", "Invalid usage range or surface", 400);
34
37
  }
35
38
  let window;
@@ -38,6 +41,7 @@ export async function handleHubUsage(req: Request, config: OcxConfig, policy: Re
38
41
  try {
39
42
  const aggregate = await getFilteredUsageAggregate({
40
43
  apiKeyId: keyId, provider: query.get("provider"), model: query.get("model"),
44
+ ...(client !== null ? { sourceFilter: { client: client as UsageSourceClient, device: { kind: "key", id: keyId } } } : {}),
41
45
  }, window);
42
46
  const current = resolveDataPlaneAdmissionSecret(token, config, "dedicated", options);
43
47
  if (current?.kind !== "configured" || current.keyId !== keyId) {
@@ -45,6 +49,7 @@ export async function handleHubUsage(req: Request, config: OcxConfig, policy: Re
45
49
  }
46
50
  const summary = aggregate.accumulator.summarize(parseRange(rangeInput), Date.now(), parseUsageSurface(surfaceInput));
47
51
  const body = parseHubUsage({ ...summary, schemaVersion: 1, source: "hub", scope: "client",
52
+ ...(client !== null ? { sourceFilter: { client, scope: "authenticated-key" } } : {}),
48
53
  ...(aggregate.usageIncomplete ? { usageIncomplete: true, usageIncompleteReason: "oversized_rows" } : {}),
49
54
  });
50
55
  if (!body) return error("hub_usage_unavailable", "Usage could not be represented; narrow the requested range", 503);
@@ -19,6 +19,7 @@ import { linkStorePath } from "../../link/paths";
19
19
  import { readLinkStore } from "../../link/store";
20
20
  import { readBoundedResponseBytes } from "../../lib/bounded-body";
21
21
  import { packageVersion } from "../../lib/package-version";
22
+ import { parseUsageSource } from "../../usage/source-filter";
22
23
 
23
24
  const VERSION = packageVersion("0.0.0");
24
25
  const KEPT_RESPONSE_HEADERS = ["content-type", "content-language", "etag", "last-modified"];
@@ -83,6 +84,13 @@ export async function handleLinkManagementRequest(
83
84
  }
84
85
  const target = linkManagementTarget(url);
85
86
  if (!target) return notFound();
87
+ if (target.pathname === "/api/usage") {
88
+ const source = parseUsageSource(target.searchParams);
89
+ if (source.kind !== "legacy" && (source.kind !== "filtered" || !admittedKeyId
90
+ || source.filter.device.kind !== "key" || source.filter.device.id !== admittedKeyId)) {
91
+ return refused(403, "link_usage_scope_refused");
92
+ }
93
+ }
86
94
  const local = new URL(`${target.pathname}${target.search}`, "http://127.0.0.1");
87
95
  // The handlers branch on GET; an admitted HEAD runs as GET and its body is dropped below.
88
96
  const inner = new Request(local.href, {
@@ -9,6 +9,7 @@
9
9
  import type { Server } from "bun";
10
10
  import type { OcxConfig } from "../../types";
11
11
  import type { WsData } from "../ws-bridge";
12
+ import { classifyUsageClient } from "../../usage/client";
12
13
  import { admissionFields, isAllowedRequestOrigin, resolveApiAuth, resolveResponsesApiAuth, withCors, type RequestPolicyView } from "../auth-cors";
13
14
  import { withCallerSessionIdentity } from "../caller-session-identity";
14
15
  import { captureAdmissionPolicy } from "../capture-admission-policy";
@@ -68,6 +69,7 @@ export async function dispatchOllamaRoute(req: Request, url: URL, deps: OllamaRo
68
69
  model: "unknown",
69
70
  provider: "unknown",
70
71
  ...deps.requestMetricsLogContext,
72
+ client: classifyUsageClient(req.headers),
71
73
  ...admissionFields(admission),
72
74
  };
73
75
  const sessionReq = withCallerSessionIdentity(req, admission);
@@ -1,3 +1,4 @@
1
+ import { messagesUnknownEndpointMessage } from "../../lib/messages-error-body";
1
2
  import type { Server, ServerWebSocket } from "bun";
2
3
  import { modelAliasIdPromoter } from "./model-alias-id";
3
4
  import type { StartServerDeps } from "./startup-warnings";
@@ -200,6 +201,7 @@ import {
200
201
  expandFastRow,
201
202
  } from "../fast-row";
202
203
  import type { OcxConfig } from "../../types";
204
+ import { classifyUsageClient } from "../../usage/client";
203
205
  import type { PackageTreeIntegrityGuard } from "../../lib/package-tree-integrity";
204
206
  import type { ReadinessGate } from "../readiness";
205
207
  import type { WorkflowRefusalLog } from "../workflow-refusal";
@@ -338,14 +340,14 @@ export function createServeOptions(ctx: ServeOptionsContext) {
338
340
  // silently when a route is added below.
339
341
  if (ingress === "unauthenticated-loopback" && !loopbackRouteAllowed(codexCompatibleUrl(req.url), req)) {
340
342
  return withCors(
341
- formatErrorResponse(404, "not_found", `Unknown endpoint: ${req.method} ${new URL(req.url).pathname}`),
343
+ formatErrorResponse(404, "not_found", messagesUnknownEndpointMessage(req)),
342
344
  req,
343
345
  loopbackPolicy(),
344
346
  );
345
347
  }
346
348
  if (ingress === "hub-link" && !linkRouteAllowed(requestUrl, req)) {
347
349
  return withCors(
348
- formatErrorResponse(404, "not_found", `Unknown endpoint: ${req.method} ${new URL(req.url).pathname}`),
350
+ formatErrorResponse(404, "not_found", messagesUnknownEndpointMessage(req)),
349
351
  req,
350
352
  linkPolicyView!,
351
353
  );
@@ -354,14 +356,14 @@ export function createServeOptions(ctx: ServeOptionsContext) {
354
356
  // dispatch so no data, readiness, health, WebSocket, or unknown-static handler can run.
355
357
  if (ingress === "hub-management" && !managementIngressRouteAllowed(codexCompatibleUrl(req.url), req)) {
356
358
  return withCors(
357
- formatErrorResponse(404, "not_found", `Unknown endpoint: ${req.method} ${new URL(req.url).pathname}`),
359
+ formatErrorResponse(404, "not_found", messagesUnknownEndpointMessage(req)),
358
360
  req,
359
361
  config,
360
362
  );
361
363
  }
362
364
  if (ingress === "claude-intercept" && !claudeInterceptRouteAllowed(codexCompatibleUrl(req.url), req)) {
363
365
  return withCors(
364
- formatErrorResponse(404, "not_found", `Unknown endpoint: ${req.method} ${new URL(req.url).pathname}`),
366
+ formatErrorResponse(404, "not_found", messagesUnknownEndpointMessage(req)),
365
367
  req,
366
368
  loopbackPolicy(),
367
369
  );
@@ -460,7 +462,7 @@ export function createServeOptions(ctx: ServeOptionsContext) {
460
462
  // path) must answer the deterministic JSON 404, never the generic 204
461
463
  // preflight response that the SPA fallback would otherwise allow.
462
464
  if (readyzPath !== undefined) {
463
- return withCors(formatErrorResponse(404, "not_found", `Unknown endpoint: ${req.method} ${url.pathname}`), req, policy);
465
+ return withCors(formatErrorResponse(404, "not_found", messagesUnknownEndpointMessage(req)), req, policy);
464
466
  }
465
467
  // The exact Ollama-compatible paths are data-plane routes and take data-plane CORS.
466
468
  const managementPreflight = url.pathname.startsWith("/api/") && !isOllamaNativePath(url.pathname);
@@ -636,6 +638,7 @@ export function createServeOptions(ctx: ServeOptionsContext) {
636
638
  admission,
637
639
  websocketLease,
638
640
  sessionLaneIdFromRequest(req.headers),
641
+ classifyUsageClient(req.headers),
639
642
  ),
640
643
  })) return undefined as unknown as Response;
641
644
  websocketLease.release();
@@ -677,7 +680,7 @@ export function createServeOptions(ctx: ServeOptionsContext) {
677
680
  // fallback (which would serve index.html with HTTP 200 once gui/dist exists).
678
681
  if (readyzPath !== undefined) {
679
682
  if (readyzPath !== "/readyz" || req.method !== "GET") {
680
- return withCors(formatErrorResponse(404, "not_found", `Unknown endpoint: ${req.method} ${url.pathname}`), req, policy);
683
+ return withCors(formatErrorResponse(404, "not_found", messagesUnknownEndpointMessage(req)), req, policy);
681
684
  }
682
685
  // A draining proxy must never advertise ready: every data-plane branch
683
686
  // answers drainingResponse while isDraining() is set, but the one-shot
@@ -759,7 +762,7 @@ export function createServeOptions(ctx: ServeOptionsContext) {
759
762
  return withManagementCors(signed, req, config);
760
763
  }
761
764
  if (mgmtResponse) return withManagementCors(mgmtResponse, req, config);
762
- return withManagementCors(formatErrorResponse(404, "not_found", `Unknown endpoint: ${req.method} ${url.pathname}`), req, config);
765
+ return withManagementCors(formatErrorResponse(404, "not_found", messagesUnknownEndpointMessage(req)), req, config);
763
766
  }
764
767
 
765
768
  if (url.pathname === "/v1/catalog" && (req.method === "GET" || req.method === "HEAD")) {
@@ -1336,7 +1339,7 @@ export function createServeOptions(ctx: ServeOptionsContext) {
1336
1339
  const logCtx: RequestLogContext = {
1337
1340
  model: "unknown",
1338
1341
  provider: "unknown",
1339
- ...requestMetricsLogContext,
1342
+ ...requestMetricsLogContext, client: classifyUsageClient(req.headers),
1340
1343
  ...admissionFields(admission),
1341
1344
  inboundProtocol: "responses",
1342
1345
  };
@@ -1376,7 +1379,7 @@ export function createServeOptions(ctx: ServeOptionsContext) {
1376
1379
  const logCtx: RequestLogContext = {
1377
1380
  model: "image_gen",
1378
1381
  provider: "unknown",
1379
- ...requestMetricsLogContext,
1382
+ ...requestMetricsLogContext, client: classifyUsageClient(req.headers),
1380
1383
  ...admissionFields(admission),
1381
1384
  };
1382
1385
  const endpoint = url.pathname.endsWith("/edits") ? "edits" as const : "generations" as const;
@@ -1434,7 +1437,7 @@ export function createServeOptions(ctx: ServeOptionsContext) {
1434
1437
  const logCtx: RequestLogContext = {
1435
1438
  model: "context_history",
1436
1439
  provider: "unknown",
1437
- ...requestMetricsLogContext,
1440
+ ...requestMetricsLogContext, client: classifyUsageClient(req.headers),
1438
1441
  ...admissionFields(admission),
1439
1442
  };
1440
1443
  return runAdmittedHttpTurn(req, policy, async turnAdmissionLease => {
@@ -1461,7 +1464,7 @@ export function createServeOptions(ctx: ServeOptionsContext) {
1461
1464
  const logCtx: RequestLogContext = {
1462
1465
  model: "web_search",
1463
1466
  provider: "unknown",
1464
- ...requestMetricsLogContext,
1467
+ ...requestMetricsLogContext, client: classifyUsageClient(req.headers),
1465
1468
  ...admissionFields(admission),
1466
1469
  };
1467
1470
  return runAdmittedHttpTurn(req, policy, async turnAdmissionLease => {
@@ -1486,7 +1489,7 @@ export function createServeOptions(ctx: ServeOptionsContext) {
1486
1489
  const logCtx: RequestLogContext = {
1487
1490
  model: "unknown",
1488
1491
  provider: "unknown",
1489
- ...requestMetricsLogContext,
1492
+ ...requestMetricsLogContext, client: classifyUsageClient(req.headers),
1490
1493
  ...admissionFields(admission),
1491
1494
  inboundProtocol: "responses",
1492
1495
  };
@@ -1581,7 +1584,7 @@ export function createServeOptions(ctx: ServeOptionsContext) {
1581
1584
  const logCtx: RequestLogContext = {
1582
1585
  model: "unknown",
1583
1586
  provider: "unknown",
1584
- ...requestMetricsLogContext,
1587
+ ...requestMetricsLogContext, client: classifyUsageClient(req.headers),
1585
1588
  ...admissionFields(admission),
1586
1589
  inboundProtocol: "messages",
1587
1590
  };
@@ -1619,7 +1622,7 @@ export function createServeOptions(ctx: ServeOptionsContext) {
1619
1622
  const logCtx: RequestLogContext = {
1620
1623
  model: "unknown",
1621
1624
  provider: "unknown",
1622
- ...requestMetricsLogContext,
1625
+ ...requestMetricsLogContext, client: classifyUsageClient(req.headers),
1623
1626
  ...admissionFields(admission),
1624
1627
  inboundProtocol: "chat",
1625
1628
  };
@@ -1657,7 +1660,7 @@ export function createServeOptions(ctx: ServeOptionsContext) {
1657
1660
  const logCtx: RequestLogContext = {
1658
1661
  model: TRANSCRIPTION_MODEL,
1659
1662
  provider: "unknown",
1660
- ...requestMetricsLogContext,
1663
+ ...requestMetricsLogContext, client: classifyUsageClient(req.headers),
1661
1664
  ...admissionFields(admission),
1662
1665
  };
1663
1666
  return runAdmittedHttpTurn(req, policy, async lease => {
@@ -1690,7 +1693,7 @@ export function createServeOptions(ctx: ServeOptionsContext) {
1690
1693
  const logCtx: RequestLogContext = {
1691
1694
  model: "gpt-live",
1692
1695
  provider: "unknown",
1693
- ...requestMetricsLogContext,
1696
+ ...requestMetricsLogContext, client: classifyUsageClient(req.headers),
1694
1697
  ...admissionFields(admission),
1695
1698
  };
1696
1699
  return runAdmittedHttpTurn(req, policy, async turnAdmissionLease => {
@@ -1738,7 +1741,7 @@ export function createServeOptions(ctx: ServeOptionsContext) {
1738
1741
  const logCtx: RequestLogContext = {
1739
1742
  model: "gpt-live",
1740
1743
  provider: "unknown",
1741
- ...requestMetricsLogContext,
1744
+ ...requestMetricsLogContext, client: classifyUsageClient(req.headers),
1742
1745
  ...admissionFields(admission),
1743
1746
  };
1744
1747
  let liveRequestFinalized = false;
@@ -1901,7 +1904,7 @@ export function createServeOptions(ctx: ServeOptionsContext) {
1901
1904
  // endpoint clients — memories/*, realtime/* — would surface confusing
1902
1905
  // serde decode errors instead of a clean not-found).
1903
1906
  if (url.pathname.startsWith("/v1/")) {
1904
- return withCors(formatErrorResponse(404, "not_found", `Unknown endpoint: ${req.method} ${url.pathname}`), req, policy);
1907
+ return withCors(formatErrorResponse(404, "not_found", messagesUnknownEndpointMessage(req)), req, policy);
1905
1908
  }
1906
1909
 
1907
1910
  if (url.pathname === "/opencodex-session") {
@@ -1962,7 +1965,7 @@ export function createServeOptions(ctx: ServeOptionsContext) {
1962
1965
  ? withManagementCors(serveSessionBootstrap(pairing), req, config)
1963
1966
  : withManagementCors(new Response(null, { status: 401, headers: { "Cache-Control": "no-store" } }), req, config);
1964
1967
  }
1965
- return withCors(formatErrorResponse(404, "not_found", `Unknown endpoint: ${req.method} ${url.pathname}`), req, policy);
1968
+ return withCors(formatErrorResponse(404, "not_found", messagesUnknownEndpointMessage(req)), req, policy);
1966
1969
  }
1967
1970
  const guiSessionCandidate = req.method === "GET" && (url.pathname === "/" || !url.pathname.includes("."))
1968
1971
  ? issueGuiSession(req, config, managementAuth, {
@@ -1981,7 +1984,7 @@ export function createServeOptions(ctx: ServeOptionsContext) {
1981
1984
  return jsonResponse(rootFallbackPayload());
1982
1985
  }
1983
1986
 
1984
- return withCors(formatErrorResponse(404, "not_found", `Unknown endpoint: ${req.method} ${url.pathname}`), req, config);
1987
+ return withCors(formatErrorResponse(404, "not_found", messagesUnknownEndpointMessage(req)), req, config);
1985
1988
  },
1986
1989
  websocket: createWebsocketHandler(ctx, requestMetrics),
1987
1990
  } as const;
@@ -100,22 +100,15 @@ import {
100
100
 
101
101
  const REQUEST_LOG_ID_RESPONSE_HEADER = "x-opencodex-request-id";
102
102
 
103
- /** Messages clients persist request-id; the upstream diagnostic id has a separate namespace. */
103
+ /** Messages clients correlate requests with the proxy ledger ID. */
104
104
  export function withMessagesRequestLogId(response: Response, requestId: string): Response {
105
- const upstreamId = response.headers.get("request-id");
106
105
  const correlated = withRequestLogId(response, requestId);
107
106
  correlated.headers.delete("x-opencodex-upstream-request-id");
108
- if (upstreamId && /^req_[A-Za-z0-9_-]{1,128}$/.test(upstreamId)) {
109
- correlated.headers.set("x-opencodex-upstream-request-id", upstreamId);
110
- }
111
107
  correlated.headers.set("request-id", requestId);
112
- const exposed = correlated.headers.get("Access-Control-Expose-Headers") ?? "";
113
- const names = exposed.split(",").map(name => name.trim().toLowerCase());
114
- const additions = ["request-id", ...(correlated.headers.has("x-opencodex-upstream-request-id")
115
- ? ["x-opencodex-upstream-request-id"] : [])].filter(name => !names.includes(name));
116
- if (additions.length) {
117
- correlated.headers.set("Access-Control-Expose-Headers", [exposed, ...additions].filter(Boolean).join(", "));
118
- }
108
+ const names = (correlated.headers.get("Access-Control-Expose-Headers") ?? "").split(",")
109
+ .map(name => name.trim().toLowerCase()).filter(name => name && name !== "x-opencodex-upstream-request-id");
110
+ names.push("request-id");
111
+ correlated.headers.set("Access-Control-Expose-Headers", [...new Set(names)].join(", "));
119
112
  return correlated;
120
113
  }
121
114
 
@@ -325,6 +325,7 @@ export function createWebsocketHandler(
325
325
  provider: "unknown",
326
326
  ...(requestMetricsRecorder ? { requestMetricsRecorder } : {}),
327
327
  ...(wsAdmission ? admissionFields(wsAdmission) : {}),
328
+ client: ws.data.client ?? "unknown",
328
329
  inboundProtocol: "responses",
329
330
  };
330
331
  let logged = false;
@@ -1,3 +1,4 @@
1
+ import type { MessagesFailureVerdictSink } from "../../claude/failure-verdict";
1
2
  import type { FailureVerdictSink } from "../../chat/failure-verdict";
2
3
  /**
3
4
  * Adapter delivery straight into a Chat or Messages client's wire (PF-09).
@@ -217,6 +218,7 @@ export async function deliverClientEncodedResponse(input: ClientEncodedDelivery)
217
218
  },
218
219
  };
219
220
  const failureVerdictSink: FailureVerdictSink = {};
221
+ const messagesFailureVerdictSink: MessagesFailureVerdictSink = {};
220
222
  const encodeOptions = {
221
223
  model: encoder.model,
222
224
  translatorBudget,
@@ -229,6 +231,8 @@ export async function deliverClientEncodedResponse(input: ClientEncodedDelivery)
229
231
  ? encodeChatCompletionSse(events, { ...encodeOptions, failureVerdictSink, proxyErrorContext: logCtx, get localUpstream() { return input.localUpstream; } })
230
232
  : encodeAnthropicMessageSse(events, {
231
233
  ...encodeOptions,
234
+ failureVerdictSink: encoder.stream ? undefined : messagesFailureVerdictSink,
235
+ proxyErrorContext: logCtx,
232
236
  get localUpstream() { return input.localUpstream; },
233
237
  ...(encoder.inputTokenFloor !== undefined ? { inputTokenFloor: encoder.inputTokenFloor } : {}),
234
238
  });
@@ -241,7 +245,7 @@ export async function deliverClientEncodedResponse(input: ClientEncodedDelivery)
241
245
  // The routed turn always streams internally; a non-streaming client gets the fold.
242
246
  response = encoder.protocol === "chat"
243
247
  ? await collectChatCompletionResponse(tracked, encoder.model, translatorBudget, failureVerdictSink)
244
- : await collectAnthropicMessageResponse(tracked, encoder.model, translatorBudget);
248
+ : await collectAnthropicMessageResponse(tracked, encoder.model, translatorBudget, messagesFailureVerdictSink);
245
249
  }
246
250
  return attachClientWireLog(markClientWire(response, encoder.protocol), log);
247
251
  }
@@ -23,6 +23,7 @@ import {
23
23
  } from "../../oauth";
24
24
  import { removeCredential } from "../../oauth/store";
25
25
  import { getFailureProjection } from "../../usage/failure-projection-cache";
26
+ import { MAX_USAGE_CONFIGURED_KEYS, parseUsageSource, snapshotConfiguredKeyIds } from "../../usage/source-filter";
26
27
  import { providerDestinationResolvedError } from "../../lib/destination-policy";
27
28
  import { enrichProviderFromCatalog, listKeyLoginProviders } from "../../oauth/key-providers";
28
29
  import { deriveProviderPresets } from "../../providers/derive";
@@ -110,6 +111,17 @@ function refreshedUsageSummary<T extends UsageSummary & { historyTruncated: bool
110
111
  return { ...summary, since, generatedAt: now };
111
112
  }
112
113
 
114
+ function configuredUsageKeyIds(config: OcxConfig): string[] {
115
+ const keys = config.apiKeys ?? [];
116
+ if (keys.length > MAX_USAGE_CONFIGURED_KEYS) throw new Error("configured key snapshot exceeds limit");
117
+ return snapshotConfiguredKeyIds(keys.map(key => key.id));
118
+ }
119
+
120
+ /** Only used after a previously authorized session expires during an async read. */
121
+ function expiredUsageSession(): Response {
122
+ return Response.json({ error: "session_expired" }, { status: 401, headers: { "cache-control": "no-store" } });
123
+ }
124
+
113
125
  export async function handleLogsUsageRoutes(ctx: ManagementContext): Promise<Response | null> {
114
126
  const { req, url, config, deps, syncClaudeAgentDefsBestEffort } = ctx;
115
127
 
@@ -185,7 +197,67 @@ export async function handleLogsUsageRoutes(ctx: ManagementContext): Promise<Res
185
197
  return jsonResponse(setDebugSettings(partial));
186
198
  }
187
199
 
200
+ if (url.pathname === "/api/usage/source-facets" && req.method === "GET") {
201
+ const { auth, readStoreFor } = await import("./link-route-state");
202
+ const denied = auth(ctx, "dashboard");
203
+ if (denied) return denied;
204
+ if (config.runtimeRole === "client") return jsonResponse({ error: "source facets unavailable on a child" }, 403);
205
+ const parsed = parseUsageSource(url.searchParams);
206
+ if (parsed.kind !== "filtered" || [...url.searchParams.keys()].some(key => !["client", "device", "apiKeyId"].includes(key))) {
207
+ return Response.json({ error: "invalid usage source filter" }, { status: 400, headers: { "cache-control": "no-store" } });
208
+ }
209
+ try {
210
+ const ids = configuredUsageKeyIds(config);
211
+ if (parsed.filter.device.kind === "key" && !ids.includes(parsed.filter.device.id)) {
212
+ return Response.json({ error: "unknown key" }, { status: 400, headers: { "cache-control": "no-store" } });
213
+ }
214
+ const links = JSON.stringify(readStoreFor(ctx).links.map(({ apiKeyId, alias }) => [apiKeyId, alias]).sort());
215
+ const { getUsageSourceFacets } = await import("./usage-source-facets");
216
+ const facets = await getUsageSourceFacets(parsed.filter, ids);
217
+ const revoked = auth(ctx, "dashboard");
218
+ if (revoked) return expiredUsageSession();
219
+ const currentIds = configuredUsageKeyIds(config);
220
+ const currentLinks = JSON.stringify(readStoreFor(ctx).links.map(({ apiKeyId, alias }) => [apiKeyId, alias]).sort());
221
+ if (JSON.stringify(ids) !== JSON.stringify(currentIds) || links !== currentLinks) throw new Error("inventory changed");
222
+ return Response.json(facets, { headers: { "cache-control": "no-store" } });
223
+ } catch {
224
+ if (auth(ctx, "dashboard")) return expiredUsageSession();
225
+ return Response.json({ error: "usage_facets_unavailable" }, { status: 503, headers: { "cache-control": "no-store", "retry-after": "1" } });
226
+ }
227
+ }
228
+
229
+ if (url.pathname === "/api/usage/devices" && req.method === "GET") {
230
+ const { auth, readStoreFor } = await import("./link-route-state");
231
+ const denied = auth(ctx, "dashboard");
232
+ if (denied) return denied;
233
+ if (ctx.config.runtimeRole === "client") return jsonResponse({ error: "device inventory unavailable on a child" }, 403);
234
+ try {
235
+ const aliases = new Map<string, string | null>();
236
+ for (const link of readStoreFor(ctx).links) {
237
+ aliases.set(link.apiKeyId, aliases.has(link.apiKeyId) ? null : link.alias);
238
+ }
239
+ const devices = [...aliases].sort(([left], [right]) => left.localeCompare(right))
240
+ .map(([apiKeyId, alias]) => ({ apiKeyId, alias }));
241
+ return Response.json({ devices }, { headers: { "cache-control": "no-store" } });
242
+ } catch {
243
+ return jsonResponse({ error: "link_store_unavailable" }, 503);
244
+ }
245
+ }
246
+
188
247
  if (url.pathname === "/api/usage" && req.method === "GET") {
248
+ const source = parseUsageSource(url.searchParams);
249
+ if (source.kind === "invalid") return jsonResponse({ error: "invalid usage source filter" }, 400);
250
+ const unconfigured = source.kind === "filtered" && source.filter.device.kind === "unconfigured";
251
+ const sessionGuard = unconfigured ? (await import("./link-route-state")).auth : null;
252
+ if (sessionGuard) {
253
+ const denied = sessionGuard(ctx, "dashboard");
254
+ if (denied) return denied;
255
+ }
256
+ let configuredIds: string[] | undefined;
257
+ if (unconfigured) {
258
+ try { configuredIds = configuredUsageKeyIds(config); }
259
+ catch { return Response.json({ error: "usage_inventory_unavailable" }, { status: 503, headers: { "cache-control": "no-store" } }); }
260
+ }
189
261
  if (url.searchParams.get("jev") === "1") {
190
262
  const range = parseRange(url.searchParams.get("range"));
191
263
  const rawComboId = url.searchParams.get("comboId");
@@ -244,8 +316,10 @@ export async function handleLogsUsageRoutes(ctx: ManagementContext): Promise<Res
244
316
  provider: url.searchParams.get("provider"),
245
317
  model: url.searchParams.get("model"),
246
318
  apiKeyId: url.searchParams.get("apiKeyId"),
319
+ ...(source.kind === "filtered" ? { sourceFilter: source.filter } : {}),
320
+ ...(configuredIds ? { configuredApiKeyIds: configuredIds } : {}),
247
321
  };
248
- const filterRequested = window !== undefined || [filter.provider, filter.model, filter.apiKeyId]
322
+ const filterRequested = source.kind === "filtered" || window !== undefined || [filter.provider, filter.model, filter.apiKeyId]
249
323
  .some(value => typeof value === "string" && value.trim() !== "");
250
324
  const now = Date.now();
251
325
  try {
@@ -272,17 +346,27 @@ export async function handleLogsUsageRoutes(ctx: ManagementContext): Promise<Res
272
346
  if (cached && !filterRequested) discardUsageSummaryCacheEntry(cacheKey);
273
347
  if (filterRequested) {
274
348
  const filteredAggregate = await getFilteredUsageAggregate(filter, window);
349
+ if (sessionGuard) {
350
+ const denied = sessionGuard(ctx, "dashboard");
351
+ if (denied) return expiredUsageSession();
352
+ const currentIds = configuredUsageKeyIds(config);
353
+ if (JSON.stringify(currentIds) !== JSON.stringify(configuredIds)) {
354
+ return Response.json({ error: "usage_inventory_changed" }, { status: 503, headers: { "cache-control": "no-store" } });
355
+ }
356
+ }
275
357
  const accumulator = filteredAggregate.accumulator;
276
- return jsonResponse({
358
+ const body = {
277
359
  ...accumulator.summarize(range, now, surface),
278
- ...(filteredAggregate.usageIncomplete ? { usageIncomplete: true as const, usageIncompleteReason: "oversized_rows" as const } : {}),
360
+ ...(filteredAggregate.usageIncomplete ? { usageIncomplete: true as const, usageIncompleteReason: "oversized_rows" as const }
361
+ : unconfigured && filteredAggregate.usageInvalidRows ? { usageIncomplete: true as const } : {}),
279
362
  historyTruncated: false,
280
363
  truncatedPrefixBytes: 0,
281
364
  entriesTruncated: false,
282
365
  entriesDropped: 0,
283
366
  snapshotWindowStart: accumulator.snapshotWindow.start,
284
367
  snapshotWindowEnd: accumulator.snapshotWindow.end,
285
- });
368
+ };
369
+ return unconfigured ? Response.json(body, { headers: { "cache-control": "no-store" } }) : jsonResponse(body);
286
370
  }
287
371
 
288
372
  const configuredApiKeyIds = (config.apiKeys ?? []).map(key => key.id);
@@ -348,6 +432,7 @@ export async function handleLogsUsageRoutes(ctx: ManagementContext): Promise<Res
348
432
  }
349
433
  return jsonResponse(requestedSummary);
350
434
  } catch {
435
+ if (sessionGuard && sessionGuard(ctx, "dashboard")) return expiredUsageSession();
351
436
  // A missing ledger is handled as an empty installation by the reader. Reaching this catch
352
437
  // therefore means the report is unavailable, not that usage was measured as zero. Keep the
353
438
  // transport status aligned with the JEV projection above so every dashboard consumer can
@@ -49,8 +49,6 @@ import { ProviderOutboundPolicyError, providerOutboundGet, providerOutboundPost,
49
49
  import { fetchCursorUsableModels } from "../../adapters/cursor/live-models";
50
50
  import { fetchDevinUsableModels } from "../../adapters/devin/live-models";
51
51
  import { resolveDevinApiBaseUrl } from "../../oauth/devin/api-base";
52
- import { fetchQoderModels } from "../../adapters/qoder/live-models";
53
- import { resolveQoderProfile } from "../../adapters/qoder/profiles";
54
52
  import { parseAntigravityAvailableModels } from "../../providers/antigravity-models";
55
53
  import { enrichProviderFromCatalog, listKeyLoginProviders } from "../../oauth/key-providers";
56
54
  import {
@@ -1702,26 +1700,8 @@ export async function handleProviderRoutes(ctx: ManagementContext): Promise<Resp
1702
1700
  });
1703
1701
  }
1704
1702
  if (prov.adapter === "qoder") {
1705
- const started = Date.now();
1706
- const profile = resolveQoderProfile(prov.baseUrl);
1707
- if (!profile) {
1708
- return jsonResponse({ ok: false, latencyMs: 0, error: "qoder discovery refused a non-canonical destination" });
1709
- }
1710
- const live = await fetchQoderModels(profile, apiKey ?? "");
1711
- const latencyMs = Date.now() - started;
1712
- if (!live.ok) {
1713
- return jsonResponse({
1714
- ok: false,
1715
- latencyMs,
1716
- error: `qoder discovery ${live.error}${live.detail ? `: ${live.detail}` : ""}`,
1717
- });
1718
- }
1719
- return jsonResponse({
1720
- ok: true,
1721
- latencyMs,
1722
- models: live.models.length,
1723
- message: `Connected. ${live.models.length} models.`,
1724
- });
1703
+ // A late success re-syncs the catalog through the same convergence every mutation uses.
1704
+ return (await import("./qoder-provider-probe")).probeQoderProvider(name, prov, apiKey, convergeCodexCatalog);
1725
1705
  }
1726
1706
  const project = prov.project ?? snapshot?.projectId;
1727
1707
  if (antigravity && !project) {
@@ -0,0 +1,105 @@
1
+ import { discoverQoderModels, QODER_INTERACTIVE_DEADLINE_MS } from "../../adapters/qoder/live-models";
2
+ import { resolveQoderProfile } from "../../adapters/qoder/profiles";
3
+ import { captureModelCacheGeneration, isModelCacheGenerationCurrent } from "../../codex/model-cache";
4
+ import { clearGatherRoutedModelsInflight } from "../../codex/catalog/routed-gather";
5
+ import type { OcxProviderConfig } from "../../types";
6
+ import { jsonResponse } from "../auth-cors";
7
+
8
+ export interface QoderProbeDeps {
9
+ deadlineMs?: number;
10
+ /** Waits between re-sync attempts; the first attempt runs at once. */
11
+ resyncDelaysMs?: readonly number[];
12
+ sleep?: (ms: number) => Promise<void>;
13
+ clearGatherInflight?: () => void;
14
+ }
15
+
16
+ /** Re-sync attempts after a late success: at once, then while a busy or stale convergence clears. */
17
+ export const QODER_LATE_RESYNC_DELAYS_MS = [0, 2_000, 5_000, 10_000] as const;
18
+
19
+ function retryable(disposition: unknown): boolean {
20
+ const outcome = disposition as { status?: unknown; retryable?: unknown } | null | undefined;
21
+ return (outcome?.status === "skipped" || outcome?.status === "failed") && outcome.retryable === true;
22
+ }
23
+
24
+ /**
25
+ * Publish a late roster. The finished run is not stored yet, so the convergence gather prefers it
26
+ * over the cached roster, which stays as the fallback if publication never happens. Each attempt
27
+ * first drops in-flight aggregate gathers, as a provider reload does: one that started before the
28
+ * run finished may already hold the old roster and would hand it to the convergence that joins it.
29
+ * A busy or stale convergence is retried; an invalidated cache generation ends the attempts.
30
+ */
31
+ async function resyncAfterLateSuccess(
32
+ name: string,
33
+ generation: string,
34
+ converge: () => Promise<unknown>,
35
+ deps: QoderProbeDeps,
36
+ ): Promise<void> {
37
+ const sleep = deps.sleep ?? (ms => new Promise<void>(resolve => { setTimeout(resolve, ms).unref?.(); }));
38
+ for (const delay of deps.resyncDelaysMs ?? QODER_LATE_RESYNC_DELAYS_MS) {
39
+ if (delay > 0) await sleep(delay);
40
+ if (!isModelCacheGenerationCurrent(name, generation)) return;
41
+ (deps.clearGatherInflight ?? clearGatherRoutedModelsInflight)();
42
+ let disposition: unknown;
43
+ try { disposition = await converge(); } catch { continue; }
44
+ if (!retryable(disposition)) return;
45
+ }
46
+ }
47
+
48
+ /**
49
+ * Connection test for Qoder (#8115). Lives outside `provider-routes.ts`, which sits at the
50
+ * file-size threshold.
51
+ *
52
+ * `qoder --list-models` can take longer than this interactive test should wait, so the test joins
53
+ * the shared background discovery (the same run the catalog gather uses, with its longer bound)
54
+ * and waits only its own short deadline. Past it, the provider is reported as still discovering
55
+ * rather than failed. A later success runs `converge`, the management catalog convergence, whose
56
+ * gather reads that run ahead of the cached roster and publishes the models without a proxy
57
+ * restart; running Codex sessions keep their copy until restarted (see
58
+ * {@link resyncAfterLateSuccess}). Nothing happens when the cache was invalidated meanwhile: the run
59
+ * belongs to the previous generation.
60
+ */
61
+ export async function probeQoderProvider(
62
+ name: string,
63
+ prov: OcxProviderConfig,
64
+ apiKey: string | undefined,
65
+ converge: () => Promise<unknown>,
66
+ deps: QoderProbeDeps = {},
67
+ ): Promise<Response> {
68
+ const started = Date.now();
69
+ const profile = resolveQoderProfile(prov.baseUrl);
70
+ if (!profile) {
71
+ return jsonResponse({ ok: false, latencyMs: 0, error: "qoder discovery refused a non-canonical destination" });
72
+ }
73
+ const generation = captureModelCacheGeneration(name);
74
+ const run = discoverQoderModels(profile, apiKey ?? "", `${name}\0${generation}`);
75
+ let timer: ReturnType<typeof setTimeout> | undefined;
76
+ const deadline = new Promise<null>(resolve => {
77
+ timer = setTimeout(() => resolve(null), deps.deadlineMs ?? QODER_INTERACTIVE_DEADLINE_MS);
78
+ });
79
+ const live = await Promise.race([run, deadline]).finally(() => clearTimeout(timer));
80
+ const latencyMs = Date.now() - started;
81
+ if (live === null) {
82
+ void run.then(result => {
83
+ if (result.ok) return resyncAfterLateSuccess(name, generation, converge, deps);
84
+ }).catch(() => undefined);
85
+ return jsonResponse({
86
+ ok: true,
87
+ discovering: true,
88
+ latencyMs,
89
+ message: "Qoder is still listing models; they appear in the catalog when discovery finishes.",
90
+ });
91
+ }
92
+ if (!live.ok) {
93
+ return jsonResponse({
94
+ ok: false,
95
+ latencyMs,
96
+ error: `qoder discovery ${live.error}${live.detail ? `: ${live.detail}` : ""}`,
97
+ });
98
+ }
99
+ return jsonResponse({
100
+ ok: true,
101
+ latencyMs,
102
+ models: live.models.length,
103
+ message: `Connected. ${live.models.length} models.`,
104
+ });
105
+ }