cartethyia 2.5.4 → 2.5.7

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 (395) hide show
  1. package/.env.example +13 -4
  2. package/README.md +2 -2
  3. package/dist/dashboard/assets/{BannedPage-C2orBsI2.js → BannedPage-DE2607Tb.js} +1 -1
  4. package/dist/dashboard/assets/BannedPage-DE2607Tb.js.gz +0 -0
  5. package/dist/dashboard/assets/CliToolDetailPage-Duv6mfrl.js +1 -0
  6. package/dist/dashboard/assets/CliToolDetailPage-Duv6mfrl.js.gz +0 -0
  7. package/dist/dashboard/assets/{CliToolsPage-BV6pxVQo.js → CliToolsPage-C2PNYWzk.js} +1 -1
  8. package/dist/dashboard/assets/CliToolsPage-C2PNYWzk.js.gz +0 -0
  9. package/dist/dashboard/assets/CombosPage-TXP9OfAM.js +1 -0
  10. package/dist/dashboard/assets/CombosPage-TXP9OfAM.js.gz +0 -0
  11. package/dist/dashboard/assets/{ConsoleLogPage-CW-wPmJ6.js → ConsoleLogPage-B-9xnAQN.js} +1 -1
  12. package/dist/dashboard/assets/ConsoleLogPage-B-9xnAQN.js.gz +0 -0
  13. package/dist/dashboard/assets/{CustomizationPage-0p8uX7vB.js → CustomizationPage-xeax9nJt.js} +1 -1
  14. package/dist/dashboard/assets/CustomizationPage-xeax9nJt.js.gz +0 -0
  15. package/dist/dashboard/assets/{HealthEventsModal-BjqSMfko.js → HealthEventsModal-Df4jjaHJ.js} +1 -1
  16. package/dist/dashboard/assets/HealthEventsModal-Df4jjaHJ.js.gz +0 -0
  17. package/dist/dashboard/assets/{LoginPage-BvzCx8Kr.js → LoginPage-Dyojsm84.js} +1 -1
  18. package/dist/dashboard/assets/LoginPage-Dyojsm84.js.gz +0 -0
  19. package/dist/dashboard/assets/ModelPicker-C7pDb41R.js +1 -0
  20. package/dist/dashboard/assets/ModelPicker-C7pDb41R.js.gz +0 -0
  21. package/dist/dashboard/assets/OverviewPage-BJfg4ow6.js +1 -0
  22. package/dist/dashboard/assets/OverviewPage-BJfg4ow6.js.gz +0 -0
  23. package/dist/dashboard/assets/ProviderDetailPage-ChCX1gmT.js +3 -0
  24. package/dist/dashboard/assets/ProviderDetailPage-ChCX1gmT.js.gz +0 -0
  25. package/dist/dashboard/assets/{ProvidersPage-Js9jUPSb.js → ProvidersPage-DeWSOEUO.js} +1 -1
  26. package/dist/dashboard/assets/ProvidersPage-DeWSOEUO.js.gz +0 -0
  27. package/dist/dashboard/assets/ProxyPage-CkpWln2S.js +7 -0
  28. package/dist/dashboard/assets/ProxyPage-CkpWln2S.js.gz +0 -0
  29. package/dist/dashboard/assets/QuotaPage-B3VOgQmt.js +1 -0
  30. package/dist/dashboard/assets/QuotaPage-B3VOgQmt.js.gz +0 -0
  31. package/dist/dashboard/assets/SettingsPage-C_klIZom.js +1 -0
  32. package/dist/dashboard/assets/SettingsPage-C_klIZom.js.gz +0 -0
  33. package/dist/dashboard/assets/{SetupPage-DDbMQsoo.js → SetupPage-BYph-InK.js} +1 -1
  34. package/dist/dashboard/assets/SetupPage-BYph-InK.js.gz +0 -0
  35. package/dist/dashboard/assets/{SortableList-CB3Z7VTf.js → SortableList-CvyQCYWJ.js} +1 -1
  36. package/dist/dashboard/assets/SortableList-CvyQCYWJ.js.gz +0 -0
  37. package/dist/dashboard/assets/{StudioPage-D95UCPHI.js → StudioPage-Cm1JYilI.js} +3 -3
  38. package/dist/dashboard/assets/StudioPage-Cm1JYilI.js.gz +0 -0
  39. package/dist/dashboard/assets/UsagePage-DlFnc3_S.js +56 -0
  40. package/dist/dashboard/assets/UsagePage-DlFnc3_S.js.gz +0 -0
  41. package/dist/dashboard/assets/api-keys-DQYLQxpW.js +1 -0
  42. package/dist/dashboard/assets/api-keys-DQYLQxpW.js.gz +0 -0
  43. package/dist/dashboard/assets/app-CX_Z8cMs.css +2 -0
  44. package/dist/dashboard/assets/app-CX_Z8cMs.css.gz +0 -0
  45. package/dist/dashboard/assets/{assert-Chi7pCnt.js → assert-C9FD_JwJ.js} +1 -1
  46. package/dist/dashboard/assets/assert-C9FD_JwJ.js.gz +0 -0
  47. package/dist/dashboard/assets/{badge-D4pQapKj.js → badge-CR72dasT.js} +1 -1
  48. package/dist/dashboard/assets/badge-CR72dasT.js.gz +0 -0
  49. package/dist/dashboard/assets/{banner-DH6cg-_B.js → banner-CI9_eSfO.js} +1 -1
  50. package/dist/dashboard/assets/banner-CI9_eSfO.js.gz +0 -0
  51. package/dist/dashboard/assets/{card-BKqlUOe4.js → card-DS7CQEsO.js} +1 -1
  52. package/dist/dashboard/assets/card-DS7CQEsO.js.gz +0 -0
  53. package/dist/dashboard/assets/{cli-tools-fTgljTGA.js → cli-tools-CNqzrfdb.js} +1 -1
  54. package/dist/dashboard/assets/cli-tools-CNqzrfdb.js.gz +0 -0
  55. package/dist/dashboard/assets/{clipboard-button-D5Ys_sM0.js → clipboard-button-611pSsaX.js} +1 -1
  56. package/dist/dashboard/assets/clipboard-button-611pSsaX.js.gz +0 -0
  57. package/dist/dashboard/assets/{fingerprint-pattern-BWuHtbW4.js → concurrency-BDF0ok7y.js} +1 -1
  58. package/dist/dashboard/assets/concurrency-BDF0ok7y.js.gz +0 -0
  59. package/dist/dashboard/assets/dialog-k37exjNt.js +1 -0
  60. package/dist/dashboard/assets/dialog-k37exjNt.js.gz +0 -0
  61. package/dist/dashboard/assets/drawer-CX7N8ucR.js +1 -0
  62. package/dist/dashboard/assets/drawer-CX7N8ucR.js.gz +0 -0
  63. package/dist/dashboard/assets/{entry-CQBr6U9c.js → entry-B9Xvtnfj.js} +1 -1
  64. package/dist/dashboard/assets/entry-B9Xvtnfj.js.gz +0 -0
  65. package/dist/dashboard/assets/entry-Bog0p925.js +4 -0
  66. package/dist/dashboard/assets/entry-Bog0p925.js.gz +0 -0
  67. package/dist/dashboard/assets/entry-CTP8AyiS.js +1 -0
  68. package/dist/dashboard/assets/entry-CTP8AyiS.js.gz +0 -0
  69. package/dist/dashboard/assets/{github-badge-BlptL8Uf.js → github-badge-sltk1qUi.js} +1 -1
  70. package/dist/dashboard/assets/github-badge-sltk1qUi.js.gz +0 -0
  71. package/dist/dashboard/assets/{index-js6TJvdr.js → index-CZQIrdoX.js} +2 -2
  72. package/dist/dashboard/assets/index-CZQIrdoX.js.gz +0 -0
  73. package/dist/dashboard/assets/{inline-DUWDSmDV.js → inline-BhY2sSnO.js} +1 -1
  74. package/dist/dashboard/assets/inline-BhY2sSnO.js.gz +0 -0
  75. package/dist/dashboard/assets/{input-LVjgZq4f.js → input-V1umFiBk.js} +1 -1
  76. package/dist/dashboard/assets/input-V1umFiBk.js.gz +0 -0
  77. package/dist/dashboard/assets/layout-BBOYycyS.js +1 -0
  78. package/dist/dashboard/assets/layout-BBOYycyS.js.gz +0 -0
  79. package/dist/dashboard/assets/{list-row-DupvLfDx.js → list-row-1zzZYM0B.js} +1 -1
  80. package/dist/dashboard/assets/list-row-1zzZYM0B.js.gz +0 -0
  81. package/dist/dashboard/assets/{live-C4pEJUqI.js → live-BivGfuUs.js} +1 -1
  82. package/dist/dashboard/assets/live-BivGfuUs.js.gz +0 -0
  83. package/dist/dashboard/assets/{model-bans-BRiuufkB.js → model-bans-CmffjLuG.js} +1 -1
  84. package/dist/dashboard/assets/model-bans-CmffjLuG.js.gz +0 -0
  85. package/dist/dashboard/assets/{mutation-B4ROwk8L.js → mutation-46P0oWMe.js} +1 -1
  86. package/dist/dashboard/assets/mutation-46P0oWMe.js.gz +0 -0
  87. package/dist/dashboard/assets/numbers-DkfMR5Qs.js +2 -0
  88. package/dist/dashboard/assets/numbers-DkfMR5Qs.js.gz +0 -0
  89. package/dist/dashboard/assets/{query-keys-gmjzC3RS.js → query-keys-BFhGpwR1.js} +1 -1
  90. package/dist/dashboard/assets/query-keys-BFhGpwR1.js.gz +0 -0
  91. package/dist/dashboard/assets/{routing-C7tBT5o-.js → routing-CAb4F37R.js} +1 -1
  92. package/dist/dashboard/assets/routing-CAb4F37R.js.gz +0 -0
  93. package/dist/dashboard/assets/{select-WUCXorXw.js → select-BPpSsBgL.js} +1 -1
  94. package/dist/dashboard/assets/select-BPpSsBgL.js.gz +0 -0
  95. package/dist/dashboard/assets/{settings-C_zKl1GS.js → settings-DNX9sydi.js} +1 -1
  96. package/dist/dashboard/assets/settings-DNX9sydi.js.gz +0 -0
  97. package/dist/dashboard/assets/{stack-_3O0F8Xn.js → stack-BHTfXdz_.js} +1 -1
  98. package/dist/dashboard/assets/stack-BHTfXdz_.js.gz +0 -0
  99. package/dist/dashboard/assets/{state-BgTxHcJS.js → state-mPDRlQkl.js} +1 -1
  100. package/dist/dashboard/assets/state-mPDRlQkl.js.gz +0 -0
  101. package/dist/dashboard/assets/{switch-DEjTtOWf.js → switch-DOmJxg7H.js} +1 -1
  102. package/dist/dashboard/assets/switch-DOmJxg7H.js.gz +0 -0
  103. package/dist/dashboard/assets/tokens-COzario9.js +1 -0
  104. package/dist/dashboard/assets/tokens-COzario9.js.gz +0 -0
  105. package/dist/dashboard/assets/use-modal-focus-By7oJoGd.js +1 -0
  106. package/dist/dashboard/assets/use-modal-focus-By7oJoGd.js.gz +0 -0
  107. package/dist/dashboard/assets/{useMutation-BWSC0UAS.js → useMutation-Dem0lXQj.js} +1 -1
  108. package/dist/dashboard/assets/useMutation-Dem0lXQj.js.gz +0 -0
  109. package/dist/dashboard/index.html +1 -1
  110. package/dist/dashboard/index.html.gz +0 -0
  111. package/dist/dashboard/precompressed-assets.json +54 -54
  112. package/migrations/README.md +52 -52
  113. package/migrations/lite-sqlite3/0000_baseline.sql +2 -2
  114. package/package.json +95 -95
  115. package/scripts/cli/admin.ts +125 -0
  116. package/scripts/cli/{ui/background.ts → background.ts} +1 -1
  117. package/scripts/cli/{command/console-menu.ts → console-menu.ts} +275 -244
  118. package/scripts/cli/doctor.ts +37 -0
  119. package/scripts/cli/{support/env.ts → env.ts} +99 -99
  120. package/scripts/cli/{gateway/spawn.ts → gateway.ts} +112 -24
  121. package/scripts/cli/instance.ts +224 -0
  122. package/scripts/cli/main.ts +61 -18
  123. package/scripts/cli/{support/platform.ts → platform.ts} +64 -64
  124. package/scripts/cli/port.ts +100 -0
  125. package/scripts/cli/{support/services.ts → services.ts} +88 -88
  126. package/scripts/cli/{command/setup.ts → setup.ts} +35 -34
  127. package/scripts/cli/{command/start.ts → start.ts} +10 -5
  128. package/scripts/cli/{support/startup-signal.ts → startup-signal.ts} +23 -23
  129. package/scripts/cli/tray/index.ts +62 -12
  130. package/scripts/cli/{command/tray.ts → tray.ts} +208 -208
  131. package/scripts/cli/{command/update.ts → update.ts} +39 -39
  132. package/scripts/cli/version.ts +67 -0
  133. package/scripts/cli/{ui/wordmark.ts → wordmark.ts} +58 -58
  134. package/src/boot/app.ts +697 -693
  135. package/src/boot/dependencies.ts +647 -646
  136. package/src/boot/timeout.ts +2 -13
  137. package/src/config/cooldowns.ts +186 -138
  138. package/src/config/network.ts +8 -14
  139. package/src/config/providers.ts +7 -10
  140. package/src/config/runtime.ts +76 -76
  141. package/src/config/security.ts +15 -0
  142. package/src/config/spec.ts +20 -30
  143. package/src/config/telemetry.ts +0 -20
  144. package/src/config/timeouts.ts +0 -6
  145. package/src/console/admin/model-abuse/contracts.ts +28 -6
  146. package/src/console/admin/model-abuse/routes.ts +56 -3
  147. package/src/console/api-keys/contracts.ts +410 -414
  148. package/src/console/api-keys/routes.ts +881 -880
  149. package/src/console/auth/credentials.ts +3 -3
  150. package/src/console/auth/setup-service.ts +2 -2
  151. package/src/console/backup/export-endpoint.ts +6 -2
  152. package/src/console/backup/nine-router.ts +2 -5
  153. package/src/console/backup/service.ts +4 -0
  154. package/src/console/backup/store.ts +192 -29
  155. package/src/console/backup/validate.ts +3 -45
  156. package/src/console/cli-tools/fs-ops.ts +487 -487
  157. package/src/console/console-router-guards.ts +1 -1
  158. package/src/console/data-management/contracts.ts +13 -6
  159. package/src/console/data-management/operations.ts +23 -18
  160. package/src/console/data-management/routes.ts +0 -1
  161. package/src/console/domain-registration.ts +10 -5
  162. package/src/console/observability/live.ts +22 -0
  163. package/src/console/observability/store.ts +39 -16
  164. package/src/console/observability/usage-dimensions.ts +4 -4
  165. package/src/console/providers/catalog/catalog-projections.ts +6 -7
  166. package/src/console/providers/catalog/model-operations.ts +5 -2
  167. package/src/console/providers/catalog/provider-operations.ts +4 -4
  168. package/src/console/providers/catalog/public-model-store.ts +8 -11
  169. package/src/console/providers/catalog/store.ts +1553 -1553
  170. package/src/console/providers/oauth/routes.ts +8 -12
  171. package/src/console/quota/account-quota-tenant.ts +6 -6
  172. package/src/console/quota/quota-view.ts +1 -1
  173. package/src/console/remote-support/contracts.ts +61 -0
  174. package/src/console/remote-support/routes.ts +65 -0
  175. package/src/console/remote-support/service.ts +207 -0
  176. package/src/console/response-compression.ts +0 -3
  177. package/src/console/routing/pools/probe-result.ts +3 -2
  178. package/src/console/routing/pools/probe-verdict.ts +132 -132
  179. package/src/console/routing/pools/store.ts +8 -8
  180. package/src/console/settings/contracts.ts +58 -2
  181. package/src/console/settings/store.ts +30 -3
  182. package/src/console/shared/cursor.ts +8 -8
  183. package/src/console/shared/errors.ts +1 -3
  184. package/src/network/http2-bidi.ts +2 -4
  185. package/src/network/pool/agent.ts +478 -478
  186. package/src/network/pool/selector.ts +5 -4
  187. package/src/network/retry.ts +1 -2
  188. package/src/network/ssrf.ts +5 -4
  189. package/src/observability/event-compaction.ts +80 -78
  190. package/src/observability/event-day-index.ts +13 -15
  191. package/src/observability/event-log.ts +4 -4
  192. package/src/observability/logger.ts +6 -6
  193. package/src/observability/payload-capture.ts +151 -33
  194. package/src/observability/payload-store.ts +397 -440
  195. package/src/observability/redaction.ts +5 -6
  196. package/src/observability/request-notify.ts +43 -0
  197. package/src/observability/telemetry-status.ts +8 -9
  198. package/src/observability/token-speed.ts +5 -4
  199. package/src/persistence/db-mode.ts +7 -7
  200. package/src/persistence/readiness.ts +1 -1
  201. package/src/persistence/schema.ts +1406 -1402
  202. package/src/persistence/shared-cache.ts +1 -2
  203. package/src/persistence/stores/api-key-store.ts +18 -6
  204. package/src/persistence/stores/share-store.ts +4 -3
  205. package/src/persistence/stores/telemetry-store.ts +236 -237
  206. package/src/protocol/canonical-model.ts +11 -3
  207. package/src/protocol/codecs.ts +138 -4
  208. package/src/protocol/gateway-error.ts +6 -4
  209. package/src/protocol/request/chat.ts +21 -1
  210. package/src/protocol/request/codex.ts +10 -1
  211. package/src/protocol/request/messages.ts +4 -5
  212. package/src/protocol/request/responses.ts +9 -1
  213. package/src/protocol/response/chat.ts +34 -4
  214. package/src/protocol/response/codex.ts +7 -4
  215. package/src/protocol/response/dsml.ts +140 -28
  216. package/src/protocol/response/responses.ts +11 -5
  217. package/src/protocol/stream-error-frames.ts +4 -5
  218. package/src/providers/authentication/jwt-validator.ts +9 -10
  219. package/src/providers/authentication/oauth-refresh-service.ts +9 -11
  220. package/src/providers/configured-openai-providers.ts +134 -136
  221. package/src/providers/discovery/catalog/catalog-blob.ts +18 -18
  222. package/src/providers/discovery/catalog/catalog-format.ts +3 -6
  223. package/src/providers/discovery/models-dev-catalog.ts +354 -354
  224. package/src/providers/discovery/probe-phases.ts +4 -4
  225. package/src/providers/discovery/probe-wire.ts +6 -13
  226. package/src/providers/discovery/probing-service.ts +1117 -1045
  227. package/src/providers/integrations/alibabacp/alibabacp.ts +1 -1
  228. package/src/providers/integrations/antigravity/antigravity-quota.ts +5 -7
  229. package/src/providers/integrations/buddy/buddy-chat-shared.ts +23 -2
  230. package/src/providers/integrations/buddy/buddy-checkin.ts +1 -4
  231. package/src/providers/integrations/buddy/buddy-cli-headers.ts +23 -6
  232. package/src/providers/integrations/buddy/buddy-conversation-headers.ts +0 -1
  233. package/src/providers/integrations/buddy/buddy-identity.ts +52 -0
  234. package/src/providers/integrations/buddy/buddy-media.ts +2 -2
  235. package/src/providers/integrations/buddy/buddy-usage-store.ts +3 -4
  236. package/src/providers/integrations/buddy/codebuddy/quota.ts +2 -13
  237. package/src/providers/integrations/buddy/codebuddy/shared.ts +118 -115
  238. package/src/providers/integrations/buddy/workbuddy/quota.ts +0 -11
  239. package/src/providers/integrations/buddy/workbuddy/shared.ts +5 -2
  240. package/src/providers/integrations/claude/claude.ts +608 -608
  241. package/src/providers/integrations/cline/cline-quota.ts +132 -132
  242. package/src/providers/integrations/cline/cline.ts +537 -539
  243. package/src/providers/integrations/codex/codex-oauth.ts +1 -1
  244. package/src/providers/integrations/commandcode/commandcode.ts +674 -675
  245. package/src/providers/integrations/commandcode/discovery.ts +117 -116
  246. package/src/providers/integrations/cursor/cursor-auth.ts +418 -418
  247. package/src/providers/integrations/cursor/cursor-quota.ts +309 -310
  248. package/src/providers/integrations/cursor/cursor.ts +11 -163
  249. package/src/providers/integrations/factory/factory-models.ts +3 -5
  250. package/src/providers/integrations/grok/grok-install-id.ts +2 -3
  251. package/src/providers/integrations/grok/grok.ts +6 -7
  252. package/src/providers/integrations/hermes.ts +14 -18
  253. package/src/providers/integrations/kiro/kiro-discovery.ts +1 -1
  254. package/src/providers/integrations/kiro/kiro.ts +1 -1
  255. package/src/providers/integrations/mistral.ts +6 -6
  256. package/src/providers/integrations/opencode/fingerprint.ts +3 -3
  257. package/src/providers/integrations/opencode/provider.ts +8 -8
  258. package/src/providers/integrations/qoder/qoder-catalog.ts +450 -450
  259. package/src/providers/integrations/qoder/qoder-oauth.ts +388 -310
  260. package/src/providers/integrations/qoder/qoder.ts +884 -865
  261. package/src/providers/integrations/shared/connect.ts +6 -6
  262. package/src/providers/integrations/trae/trae-catalog.ts +1 -2
  263. package/src/providers/integrations/trae/trae.ts +2 -2
  264. package/src/providers/integrations/zcode/oauth.ts +6 -1
  265. package/src/providers/operations/account-health-service.ts +1528 -1523
  266. package/src/providers/operations/account-reset-service.ts +1 -1
  267. package/src/providers/operations/client-versions.ts +6 -6
  268. package/src/providers/operations/custom-cli-headers.ts +3 -4
  269. package/src/providers/operations/provider-catalog-seeder.ts +95 -95
  270. package/src/providers/operations/provider-catalog-service.ts +3 -4
  271. package/src/providers/provider-metadata.ts +4 -8
  272. package/src/providers/provider-registry.ts +6 -7
  273. package/src/providers/provider-usage.ts +1 -1
  274. package/src/security/abuse.ts +15 -10
  275. package/src/security/access-control.ts +144 -146
  276. package/src/security/admission/contracts.ts +11 -0
  277. package/src/security/admission/in-memory-store.ts +4 -3
  278. package/src/security/admission/lease-sweep.ts +6 -6
  279. package/src/security/admission/reasons.ts +5 -1
  280. package/src/security/admission/redis-store.ts +211 -210
  281. package/src/security/admission/service.ts +4 -0
  282. package/src/security/api-key-auth.ts +504 -504
  283. package/src/security/ip-boundary.ts +155 -15
  284. package/src/security/model-abuse.ts +366 -94
  285. package/src/security/outbound-headers.ts +3 -4
  286. package/src/shared/sleep.ts +4 -0
  287. package/src/transport/dispatch/attempt-finalize.ts +47 -5
  288. package/src/transport/dispatch/attempt-loop.ts +531 -530
  289. package/src/transport/dispatch/stream-bridge.ts +1 -3
  290. package/src/transport/dispatch/streaming/finalize.ts +1 -1
  291. package/src/transport/dispatch/streaming/stream.ts +5 -6
  292. package/src/transport/failure-policy.ts +162 -8
  293. package/src/transport/guards/auth-guard.ts +7 -4
  294. package/src/transport/guards/concurrency-guard.ts +0 -5
  295. package/src/transport/guards/error-lifecycle.ts +13 -6
  296. package/src/transport/guards/pipeline.ts +15 -3
  297. package/src/transport/guards/request-context.ts +8 -2
  298. package/src/transport/request/inflight.ts +5 -6
  299. package/src/transport/request/preparer.ts +2 -2
  300. package/src/transport/request/state.ts +12 -8
  301. package/src/transport/routing/admission.ts +4 -0
  302. package/src/transport/routing/route-catalog.ts +8 -1
  303. package/src/transport/routing/route-model.ts +46 -14
  304. package/src/transport/routing/router.ts +21 -14
  305. package/src/transport/surface/completion.ts +2 -3
  306. package/src/transport/surface/dialects.ts +5 -6
  307. package/src/transport/surface/responses/encode.ts +38 -0
  308. package/src/transport/surface/responses/parse.ts +4 -0
  309. package/src/transport/translation/capabilities.ts +2 -3
  310. package/src/transport/translation/quirks.ts +3 -3
  311. package/src/workers/buddy-growth-tasks.ts +5 -10
  312. package/src/workers/daily-checkin.ts +17 -23
  313. package/src/workers/quota-refresh-sweep.ts +26 -26
  314. package/dist/dashboard/assets/BannedPage-C2orBsI2.js.gz +0 -0
  315. package/dist/dashboard/assets/CliToolDetailPage-DUcZ6pMB.js +0 -1
  316. package/dist/dashboard/assets/CliToolDetailPage-DUcZ6pMB.js.gz +0 -0
  317. package/dist/dashboard/assets/CliToolsPage-BV6pxVQo.js.gz +0 -0
  318. package/dist/dashboard/assets/CombosPage-Bsan4679.js +0 -1
  319. package/dist/dashboard/assets/CombosPage-Bsan4679.js.gz +0 -0
  320. package/dist/dashboard/assets/ConsoleLogPage-CW-wPmJ6.js.gz +0 -0
  321. package/dist/dashboard/assets/CustomizationPage-0p8uX7vB.js.gz +0 -0
  322. package/dist/dashboard/assets/HealthEventsModal-BjqSMfko.js.gz +0 -0
  323. package/dist/dashboard/assets/LoginPage-BvzCx8Kr.js.gz +0 -0
  324. package/dist/dashboard/assets/ModelPicker-BY1aKEkP.js +0 -1
  325. package/dist/dashboard/assets/ModelPicker-BY1aKEkP.js.gz +0 -0
  326. package/dist/dashboard/assets/OverviewPage-DOQpy1y0.js +0 -1
  327. package/dist/dashboard/assets/OverviewPage-DOQpy1y0.js.gz +0 -0
  328. package/dist/dashboard/assets/ProviderDetailPage-ecxyUMzt.js +0 -3
  329. package/dist/dashboard/assets/ProviderDetailPage-ecxyUMzt.js.gz +0 -0
  330. package/dist/dashboard/assets/ProvidersPage-Js9jUPSb.js.gz +0 -0
  331. package/dist/dashboard/assets/ProxyPage-J3TBi3Kx.js +0 -7
  332. package/dist/dashboard/assets/ProxyPage-J3TBi3Kx.js.gz +0 -0
  333. package/dist/dashboard/assets/QuotaPage-C1gZS6xr.js +0 -1
  334. package/dist/dashboard/assets/QuotaPage-C1gZS6xr.js.gz +0 -0
  335. package/dist/dashboard/assets/SettingsPage-CS86ho5X.js +0 -1
  336. package/dist/dashboard/assets/SettingsPage-CS86ho5X.js.gz +0 -0
  337. package/dist/dashboard/assets/SetupPage-DDbMQsoo.js.gz +0 -0
  338. package/dist/dashboard/assets/SortableList-CB3Z7VTf.js.gz +0 -0
  339. package/dist/dashboard/assets/StudioPage-D95UCPHI.js.gz +0 -0
  340. package/dist/dashboard/assets/UsagePage-Cnae9SWA.js +0 -56
  341. package/dist/dashboard/assets/UsagePage-Cnae9SWA.js.gz +0 -0
  342. package/dist/dashboard/assets/api-keys-VY68Mhd1.js +0 -1
  343. package/dist/dashboard/assets/api-keys-VY68Mhd1.js.gz +0 -0
  344. package/dist/dashboard/assets/app-COlK95oi.css +0 -2
  345. package/dist/dashboard/assets/app-COlK95oi.css.gz +0 -0
  346. package/dist/dashboard/assets/assert-Chi7pCnt.js.gz +0 -0
  347. package/dist/dashboard/assets/badge-D4pQapKj.js.gz +0 -0
  348. package/dist/dashboard/assets/banner-DH6cg-_B.js.gz +0 -0
  349. package/dist/dashboard/assets/card-BKqlUOe4.js.gz +0 -0
  350. package/dist/dashboard/assets/cli-tools-fTgljTGA.js.gz +0 -0
  351. package/dist/dashboard/assets/clipboard-button-D5Ys_sM0.js.gz +0 -0
  352. package/dist/dashboard/assets/dialog-BYj-8WuK.js +0 -1
  353. package/dist/dashboard/assets/dialog-BYj-8WuK.js.gz +0 -0
  354. package/dist/dashboard/assets/drawer-CmXIZ6H1.js +0 -1
  355. package/dist/dashboard/assets/drawer-CmXIZ6H1.js.gz +0 -0
  356. package/dist/dashboard/assets/entry-CBg5zeu8.js +0 -1
  357. package/dist/dashboard/assets/entry-CBg5zeu8.js.gz +0 -0
  358. package/dist/dashboard/assets/entry-CQBr6U9c.js.gz +0 -0
  359. package/dist/dashboard/assets/entry-CgdSAzEV.js +0 -4
  360. package/dist/dashboard/assets/entry-CgdSAzEV.js.gz +0 -0
  361. package/dist/dashboard/assets/fingerprint-pattern-BWuHtbW4.js.gz +0 -0
  362. package/dist/dashboard/assets/github-badge-BlptL8Uf.js.gz +0 -0
  363. package/dist/dashboard/assets/index-js6TJvdr.js.gz +0 -0
  364. package/dist/dashboard/assets/inline-DUWDSmDV.js.gz +0 -0
  365. package/dist/dashboard/assets/input-LVjgZq4f.js.gz +0 -0
  366. package/dist/dashboard/assets/layout-CPfxpsfy.js +0 -1
  367. package/dist/dashboard/assets/layout-CPfxpsfy.js.gz +0 -0
  368. package/dist/dashboard/assets/list-row-DupvLfDx.js.gz +0 -0
  369. package/dist/dashboard/assets/live-C4pEJUqI.js.gz +0 -0
  370. package/dist/dashboard/assets/model-bans-BRiuufkB.js.gz +0 -0
  371. package/dist/dashboard/assets/mutation-B4ROwk8L.js.gz +0 -0
  372. package/dist/dashboard/assets/numbers-YNcHvRY7.js +0 -2
  373. package/dist/dashboard/assets/numbers-YNcHvRY7.js.gz +0 -0
  374. package/dist/dashboard/assets/query-keys-gmjzC3RS.js.gz +0 -0
  375. package/dist/dashboard/assets/routing-C7tBT5o-.js.gz +0 -0
  376. package/dist/dashboard/assets/select-WUCXorXw.js.gz +0 -0
  377. package/dist/dashboard/assets/settings-C_zKl1GS.js.gz +0 -0
  378. package/dist/dashboard/assets/stack-_3O0F8Xn.js.gz +0 -0
  379. package/dist/dashboard/assets/state-BgTxHcJS.js.gz +0 -0
  380. package/dist/dashboard/assets/switch-DEjTtOWf.js.gz +0 -0
  381. package/dist/dashboard/assets/tokens-DDxMbSRL.js +0 -1
  382. package/dist/dashboard/assets/tokens-DDxMbSRL.js.gz +0 -0
  383. package/dist/dashboard/assets/use-presence-BSZEBx7U.js +0 -1
  384. package/dist/dashboard/assets/use-presence-BSZEBx7U.js.gz +0 -0
  385. package/dist/dashboard/assets/useMutation-BWSC0UAS.js.gz +0 -0
  386. package/scripts/cli/command/admin.ts +0 -65
  387. package/scripts/cli/command/doctor.ts +0 -257
  388. package/scripts/cli/gateway/drain-token.ts +0 -78
  389. package/scripts/cli/gateway/instance-lock.ts +0 -105
  390. package/scripts/cli/gateway/stop.ts +0 -51
  391. package/scripts/cli/support/bun.ts +0 -27
  392. package/scripts/cli/support/version.ts +0 -37
  393. /package/dist/dashboard/assets/{app-DCQZRmHY.js → app-BIt446yE.js} +0 -0
  394. /package/dist/dashboard/assets/{app-DCQZRmHY.js.gz → app-BIt446yE.js.gz} +0 -0
  395. /package/scripts/cli/{ui/prompt.ts → prompt.ts} +0 -0
@@ -1,675 +1,674 @@
1
- // Factory-blocked (Phase C4): proprietary `{threadId, config, params}`
2
- // envelope with NDJSON stream transform — non-OpenAI wire; stays bespoke.
3
- import { GatewayError } from "../../../protocol/gateway-error";
4
- import { canContainToolResult, joinTextParts, toolCallParts, toolResultParts } from "../../../protocol/canonical-model";
5
- import {
6
- classifyUpstreamError,
7
- extractUpstreamMessage,
8
- upstreamErrorIdentifier,
9
- } from "../../../transport/failure-policy";
10
- import { createApiKeyAdapter } from "../../configured-provider";
11
- import type { CanonicalEvent, CanonicalRequest, CanonicalStopReason, ContentPart } from "../../../protocol/canonical-model";
12
- import { isRecord, readNumber, readString, resolveImageSource, splitDataUrl } from "../../../protocol/codecs";
13
- import { usageFromProvider } from "../../provider-usage";
14
- import { readCredentialSecret, type ProviderDispatchTarget, type ProviderAdapter, type ProviderDispatchContext } from "../../provider-contracts";
15
- import { providerBaseUrl } from "../../provider-metadata";
16
- import { defineModel } from "../../provider-model-definition";
17
- import type { ModelDefinition } from "../../provider-model-definition";
18
- import {
19
- getCommandCodeVersion,
20
- } from "../../operations/client-versions";
21
- import { MimoThinkSplitter } from "../xiaomi-mimo/think-stream";
22
- export const COMMANDCODE_PROVIDER_ID = "commandcode" as const;
23
- export const COMMANDCODE_BASE_URL = providerBaseUrl("commandcode");
24
- /** The three routes the Provider API serves, one per wire family. */
25
- export const COMMANDCODE_CHAT_PATH = "/chat/completions" as const;
26
- export const COMMANDCODE_RESPONSES_PATH = "/responses" as const;
27
- export const COMMANDCODE_MESSAGES_PATH = "/messages" as const;
28
-
29
- /**
30
- * Command Code's roster, as the Provider API publishes it.
31
- *
32
- * Generated from the live `/provider/v1/models` listing (95 rows). Each row
33
- * carries the wire that serves it and the context window the API states, which
34
- * is the whole point: the previous list was 36 ids with no limits and one wire
35
- * for everything, so every `claude-*` id — served on `/messages` only — was
36
- * filed as chat and could never be dispatched.
37
- *
38
- * `vision: true` on every row is the catalog's own declaration for this
39
- * provider; a model that rejects an image answers for itself.
40
- *
41
- * This is the offline seed. It is superseded by `discoverCommandCodeModels`
42
- * whenever a fetch succeeds, and `seedBundledModels` prunes any row this list
43
- * stops declaring — so an id Command Code retires disappears on the next boot
44
- * rather than lingering as a card that can only ever fail.
45
- */
46
- export const COMMANDCODE_MODELS: readonly ModelDefinition[] = [
47
- defineModel({ id: "MiniMaxAI/MiniMax-M2.5", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 200000, reasoning: true, toolCall: true, vision: true }),
48
- defineModel({ id: "MiniMaxAI/MiniMax-M2.7", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 200000, reasoning: true, toolCall: true, vision: true }),
49
- defineModel({ id: "MiniMaxAI/MiniMax-M3", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
50
- defineModel({ id: "Qwen/Qwen3.6-Max-Preview", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 200000, reasoning: true, toolCall: true, vision: true }),
51
- defineModel({ id: "Qwen/Qwen3.6-Plus", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 200000, reasoning: true, toolCall: true, vision: true }),
52
- defineModel({ id: "Qwen/Qwen3.7-Flash", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
53
- defineModel({ id: "Qwen/Qwen3.7-Max", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
54
- defineModel({ id: "Qwen/Qwen3.7-Plus", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
55
- defineModel({ id: "Qwen/Qwen3.8-27B", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 262144, reasoning: true, toolCall: true, vision: true }),
56
- defineModel({ id: "Qwen/Qwen3.8-Flash", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "chat", endpoint: "/chat/completions", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
57
- defineModel({ id: "Qwen/Qwen3.8-Max", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
58
- defineModel({ id: "Qwen/Qwen3.8-Max-0902", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "chat", endpoint: "/chat/completions", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
59
- defineModel({ id: "Qwen/Qwen3.8-Max-Prime", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
60
- defineModel({ id: "Qwen/Qwen3.8-Omni-Flash", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
61
- defineModel({ id: "claude-fable-5", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "messages", endpoint: "/messages", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
62
- defineModel({ id: "claude-fable-5-1", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "messages", endpoint: "/messages", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
63
- defineModel({ id: "claude-haiku-4-5-20251001", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "messages", endpoint: "/messages", ctx: 200000, reasoning: true, toolCall: true, vision: true }),
64
- defineModel({ id: "claude-haiku-5-5", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "messages", endpoint: "/messages", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
65
- defineModel({ id: "claude-opus-4-7", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "messages", endpoint: "/messages", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
66
- defineModel({ id: "claude-opus-4-8", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "messages", endpoint: "/messages", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
67
- defineModel({ id: "claude-opus-5", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "messages", endpoint: "/messages", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
68
- defineModel({ id: "claude-opus-5-5", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "messages", endpoint: "/messages", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
69
- defineModel({ id: "claude-sonnet-4-6", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "messages", endpoint: "/messages", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
70
- defineModel({ id: "claude-sonnet-5", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "messages", endpoint: "/messages", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
71
- defineModel({ id: "claude-sonnet-5-5", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "messages", endpoint: "/messages", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
72
- defineModel({ id: "deepseek/deepseek-v4-flash", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
73
- defineModel({ id: "deepseek/deepseek-v4-flash-fast", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "chat", endpoint: "/chat/completions", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
74
- defineModel({ id: "deepseek/deepseek-v4-flash-vision-exp", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
75
- defineModel({ id: "deepseek/deepseek-v4-pro", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
76
- defineModel({ id: "deepseek/deepseek-v4.1-flash", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
77
- defineModel({ id: "deepseek/deepseek-v4.1-flash-fast", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
78
- defineModel({ id: "google/gemini-3.1-flash-lite", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
79
- defineModel({ id: "google/gemini-3.5-flash", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
80
- defineModel({ id: "google/gemini-3.5-flash-lite", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
81
- defineModel({ id: "google/gemini-3.6-flash", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
82
- defineModel({ id: "google/gemini-3.7-flash", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "chat", endpoint: "/chat/completions", ctx: 1048576, reasoning: true, toolCall: true, vision: true }),
83
- defineModel({ id: "google/gemini-3.8-flash", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
84
- defineModel({ id: "google/gemini-4-argon", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
85
- defineModel({ id: "gpt-5.3-codex", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 400000, reasoning: true, toolCall: true, vision: true }),
86
- defineModel({ id: "gpt-5.4", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 400000, reasoning: true, toolCall: true, vision: true }),
87
- defineModel({ id: "gpt-5.4-mini", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 400000, reasoning: true, toolCall: true, vision: true }),
88
- defineModel({ id: "gpt-5.5", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 400000, reasoning: true, toolCall: true, vision: true }),
89
- defineModel({ id: "gpt-5.6-luna", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1050000, reasoning: true, toolCall: true, vision: true }),
90
- defineModel({ id: "gpt-5.6-sol", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1050000, reasoning: true, toolCall: true, vision: true }),
91
- defineModel({ id: "gpt-5.6-terra", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1050000, reasoning: true, toolCall: true, vision: true }),
92
- defineModel({ id: "gpt-6-astra", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1050000, reasoning: true, toolCall: true, vision: true }),
93
- defineModel({ id: "gpt-6-luna", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1050000, reasoning: true, toolCall: true, vision: true }),
94
- defineModel({ id: "gpt-6-sol", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1050000, reasoning: true, toolCall: true, vision: true }),
95
- defineModel({ id: "gpt-6.1-sol", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1050000, reasoning: true, toolCall: true, vision: true }),
96
- defineModel({ id: "inclusionai/ling-3.1-flash", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "chat", endpoint: "/chat/completions", ctx: 262144, reasoning: true, toolCall: true, vision: true }),
97
- defineModel({ id: "meituan/LongCat-2.0", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "chat", endpoint: "/chat/completions", ctx: 1048576, reasoning: true, toolCall: true, vision: true }),
98
- defineModel({ id: "meta/muse-spark-1.1", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1048576, reasoning: true, toolCall: true, vision: true }),
99
- defineModel({ id: "meta/muse-spark-1.2", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1048576, reasoning: true, toolCall: true, vision: true }),
100
- defineModel({ id: "meta/muse-spark-1.2-contributor", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1048576, reasoning: true, toolCall: true, vision: true }),
101
- defineModel({ id: "meta/muse-spark-1.3", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1048576, reasoning: true, toolCall: true, vision: true }),
102
- defineModel({ id: "meta/muse-spark-1.3-contributor", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1048576, reasoning: true, toolCall: true, vision: true }),
103
- defineModel({ id: "meta/muse-spark-open", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1048576, reasoning: true, toolCall: true, vision: true }),
104
- defineModel({ id: "meta/muse-wonder-1.0", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1048576, reasoning: true, toolCall: true, vision: true }),
105
- defineModel({ id: "minimax/minimax-m3.1-flash-preview", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
106
- defineModel({ id: "minimax/minimax-m3.1-flash-preview:free", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
107
- defineModel({ id: "mistral/mistral-large-4", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 524288, reasoning: true, toolCall: true, vision: true }),
108
- defineModel({ id: "moonshotai/Kimi-K2.5", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 256000, reasoning: true, toolCall: true, vision: true }),
109
- defineModel({ id: "moonshotai/Kimi-K2.6", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 256000, reasoning: true, toolCall: true, vision: true }),
110
- defineModel({ id: "moonshotai/Kimi-K2.7-Code", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 256000, reasoning: true, toolCall: true, vision: true }),
111
- defineModel({ id: "moonshotai/Kimi-K2.7-Code-Highspeed", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 262000, reasoning: true, toolCall: true, vision: true }),
112
- defineModel({ id: "moonshotai/Kimi-K3", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
113
- defineModel({ id: "nvidia/nemotron-3-ultra-550b-a55b", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
114
- defineModel({ id: "nvidia/nemotron-3.5-super-vl", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 262144, reasoning: true, toolCall: true, vision: true }),
115
- defineModel({ id: "poolside/laguna-s-2.1-free", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 256000, reasoning: true, toolCall: true, vision: true }),
116
- defineModel({ id: "reflection/beam:free", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1048576, reasoning: true, toolCall: true, vision: true }),
117
- defineModel({ id: "sakana/fugu-ultra", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
118
- defineModel({ id: "stealth/cat-jam:free", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1048576, reasoning: true, toolCall: true, vision: true }),
119
- defineModel({ id: "stealth/glyph-cluster:free", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 256000, reasoning: true, toolCall: true, vision: true }),
120
- defineModel({ id: "stepfun/Step-3.5-Flash", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 262144, reasoning: true, toolCall: true, vision: true }),
121
- defineModel({ id: "stepfun/Step-3.7-Flash", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 256000, reasoning: true, toolCall: true, vision: true }),
122
- defineModel({ id: "stepfun/Step-5-Preview", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
123
- defineModel({ id: "tencent/hy3-paid", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 262144, reasoning: true, toolCall: true, vision: true }),
124
- defineModel({ id: "tencent/hy4-preview", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "chat", endpoint: "/chat/completions", ctx: 1048576, reasoning: true, toolCall: true, vision: true }),
125
- defineModel({ id: "thinkingmachines/inkling", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 256000, reasoning: true, toolCall: true, vision: true }),
126
- defineModel({ id: "thinkingmachines/inkling-small", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
127
- defineModel({ id: "xai/grok-4.5", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 500000, reasoning: true, toolCall: true, vision: true }),
128
- defineModel({ id: "xai/grok-4.6", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 500000, reasoning: true, toolCall: true, vision: true }),
129
- defineModel({ id: "xai/grok-4.7", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 500000, reasoning: true, toolCall: true, vision: true }),
130
- defineModel({ id: "xiaomi/mimo-v2.5", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
131
- defineModel({ id: "xiaomi/mimo-v2.5-pro", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
132
- defineModel({ id: "xiaomi/mimo-v2.6-flash", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1048576, reasoning: true, toolCall: true, vision: true }),
133
- defineModel({ id: "xiaomi/mimo-v2.6-pro", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1048576, reasoning: true, toolCall: true, vision: true }),
134
- defineModel({ id: "xiaomi/mimo-v2.6-pro-ultraspeed", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1048576, reasoning: true, toolCall: true, vision: true }),
135
- defineModel({ id: "z-ai/glm-5.3-flash", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "chat", endpoint: "/chat/completions", ctx: 1048576, reasoning: true, toolCall: true, vision: true }),
136
- defineModel({ id: "z-ai/glm-5.3-flashx", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
137
- defineModel({ id: "zai-org/GLM-5", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 200000, reasoning: true, toolCall: true, vision: true }),
138
- defineModel({ id: "zai-org/GLM-5.1", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 200000, reasoning: true, toolCall: true, vision: true }),
139
- defineModel({ id: "zai-org/GLM-5.2", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
140
- defineModel({ id: "zai-org/GLM-5.2-Fast", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
141
- defineModel({ id: "zai-org/GLM-5.3", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
142
- ];
143
-
144
-
145
- // CommandCode provider constants.
146
-
147
- const COMMANDCODE_DEFAULT_MAX_TOKENS = 4096;
148
-
149
- /**
150
- * The `/alpha/generate` wire, as the CLI client sends it:
151
- * - `params.system` is a top-level string; system turns never enter `messages`
152
- * - every `content` is an array of blocks, never a string
153
- * - an assistant tool call is `{type:"tool-call", toolCallId, toolName, input}`
154
- * and is preceded by a reasoning block, which the upstream requires
155
- * - a tool result is its own `role:"tool"` turn, not text glued into the user turn
156
- * - an image is `{type:"image", image, mimeType}`
157
- */
158
- function toolResultValue(content: readonly ContentPart[] | string): string {
159
- if (typeof content === "string") return content;
160
- return content
161
- .filter((part) => part.kind === "text")
162
- .map((part) => part.text)
163
- .filter((text) => text.length > 0)
164
- .join("\n");
165
- }
166
-
167
- function imageBlock(payload: unknown): Record<string, unknown> | undefined {
168
- const source = resolveImageSource(payload);
169
- if (source?.url === undefined) return undefined;
170
- const inline = splitDataUrl(source.url);
171
- return { type: "image", image: source.url, ...(inline ? { mimeType: inline.mediaType } : {}) };
172
- }
173
-
174
- function contentBlocks(parts: readonly ContentPart[]): Array<Record<string, unknown>> {
175
- const blocks: Array<Record<string, unknown>> = [];
176
- for (const part of parts) {
177
- if (part.kind === "text") {
178
- if (part.text.length > 0) blocks.push({ type: "text", text: part.text });
179
- continue;
180
- }
181
- if (part.kind === "image") {
182
- const block = imageBlock(part.payload);
183
- if (block) blocks.push(block);
184
- }
185
- }
186
- return blocks.length > 0 ? blocks : [{ type: "text", text: "" }];
187
- }
188
-
189
- function parsedInput(value: unknown): unknown {
190
- if (typeof value !== "string") return value ?? {};
191
- try {
192
- return JSON.parse(value);
193
- } catch {
194
- return {};
195
- }
196
- }
197
-
198
- export function convertMessages(messages: CanonicalRequest["messages"]): {
199
- messages: Array<Record<string, unknown>>;
200
- system?: string;
201
- } {
202
- const out: Array<Record<string, unknown>> = [];
203
- const systemTexts: string[] = [];
204
- for (const message of messages) {
205
- if (message.role === "system" || message.role === "developer") {
206
- const text = joinTextParts(message.content);
207
- if (text.length > 0) systemTexts.push(text);
208
- continue;
209
- }
210
- // Answers live in `tool` turns or in `user` turns (the Messages ledger
211
- // re-homes them). Each result is its own `role:"tool"` turn: flattening
212
- // them into the user turn as prose left the tool call unanswered.
213
- if (canContainToolResult(message) && toolResultParts(message).length > 0) {
214
- for (const result of toolResultParts(message)) {
215
- out.push({
216
- role: "tool",
217
- content: [
218
- {
219
- type: "tool-result",
220
- toolCallId: result.call_id,
221
- toolName: "",
222
- output: { type: "text", value: toolResultValue(result.content) },
223
- },
224
- ],
225
- });
226
- }
227
- const remainder = contentBlocks(message.content.filter((part) => part.kind !== "toolResult"));
228
- if (remainder.some((block) => block["text"] !== "")) out.push({ role: "user", content: remainder });
229
- continue;
230
- }
231
- if (message.role === "assistant") {
232
- const blocks: Array<Record<string, unknown>> = [];
233
- const calls = toolCallParts(message);
234
- const reasoning = message.content
235
- .filter((part) => part.kind === "reasoning")
236
- .map((part) => part.summary ?? "")
237
- .filter((text) => text.length > 0)
238
- .join("");
239
- if (reasoning.length > 0 || calls.length > 0) {
240
- blocks.push({ type: "reasoning", text: reasoning.length > 0 ? reasoning : " " });
241
- }
242
- const text = joinTextParts(message.content);
243
- if (text.length > 0) blocks.push({ type: "text", text });
244
- for (const call of calls) {
245
- blocks.push({
246
- type: "tool-call",
247
- toolCallId: call.call_id,
248
- toolName: call.name,
249
- input: parsedInput(call.arguments),
250
- });
251
- }
252
- out.push({ role: "assistant", content: blocks.length > 0 ? blocks : [{ type: "text", text: "" }] });
253
- continue;
254
- }
255
- out.push({ role: "user", content: contentBlocks(message.content) });
256
- }
257
- const system = systemTexts.join("\n\n");
258
- return system.length > 0 ? { messages: out, system } : { messages: out };
259
- }
260
-
261
- /**
262
- * Whether a tool schema needs Gemini's normalized form.
263
- *
264
- * The client rewrites a schema for `google/gemini-*` because the gateway can
265
- * turn nullable type arrays into `any_of` with sibling fields, which Vertex
266
- * rejects. This provider routes Gemini over the same Provider API, so the same
267
- * rewrite applies.
268
- */
269
- export function isGeminiModelId(modelId: string): boolean {
270
- return modelId.startsWith("google/gemini-");
271
- }
272
-
273
- const SCHEMA_MAP_FIELDS = new Set([
274
- "$defs",
275
- "definitions",
276
- "dependentSchemas",
277
- "patternProperties",
278
- "properties",
279
- ]);
280
- const SCHEMA_ARRAY_FIELDS = new Set(["allOf", "anyOf", "oneOf", "prefixItems"]);
281
- const SCHEMA_VALUE_FIELDS = new Set([
282
- "additionalItems",
283
- "additionalProperties",
284
- "contains",
285
- "contentSchema",
286
- "else",
287
- "if",
288
- "items",
289
- "not",
290
- "propertyNames",
291
- "then",
292
- "unevaluatedItems",
293
- "unevaluatedProperties",
294
- ]);
295
-
296
- /**
297
- * A schema Gemini's transport accepts: a single type plus `nullable`, with null
298
- * defaults dropped. Genuine multi-type unions and `required` are left alone —
299
- * only the nullable-array spelling is what Vertex rejects.
300
- */
301
- export function geminiSafeSchema(value: unknown): unknown {
302
- if (Array.isArray(value)) return value.map(geminiSafeSchema);
303
- if (!isRecord(value)) return value;
304
- const out: Record<string, unknown> = {};
305
- for (const [key, raw] of Object.entries(value)) {
306
- if (key === "default" && raw === null) continue;
307
- if (SCHEMA_MAP_FIELDS.has(key) && isRecord(raw)) {
308
- out[key] = Object.fromEntries(
309
- Object.entries(raw).map(([name, child]) => [name, geminiSafeSchema(child)]),
310
- );
311
- continue;
312
- }
313
- out[key] = SCHEMA_ARRAY_FIELDS.has(key) || SCHEMA_VALUE_FIELDS.has(key)
314
- ? geminiSafeSchema(raw)
315
- : raw;
316
- }
317
- // A nullable type array becomes one type plus `nullable`.
318
- if (Array.isArray(out["type"])) {
319
- const types = out["type"].filter((entry): entry is string => typeof entry === "string");
320
- const withoutNull = types.filter((entry) => entry !== "null");
321
- if (types.length !== withoutNull.length && withoutNull.length > 0) {
322
- out["type"] = withoutNull.length === 1 ? withoutNull[0] : withoutNull;
323
- out["nullable"] = true;
324
- }
325
- }
326
- return out;
327
- }
328
-
329
- export function buildRequest(
330
- modelId: string,
331
- request: { messages: CanonicalRequest["messages"]; tools: { readonly name: string; readonly description: string | undefined; readonly jsonSchema: unknown }[]; maxOutputTokens: number | null; temperature: number | null; topP: number | null; reasoningEffort: string | null },
332
- threadId: string,
333
- systemExtra?: string,
334
- ): Record<string, unknown> {
335
- const { messages, system: systemFromMessages } = convertMessages(request.messages);
336
- const systemCombined = systemExtra ? (systemFromMessages ? `${systemExtra}\n${systemFromMessages}` : systemExtra) : systemFromMessages;
337
- const params: Record<string, unknown> = {
338
- model: modelId,
339
- messages,
340
- stream: true,
341
- max_tokens: request.maxOutputTokens ?? COMMANDCODE_DEFAULT_MAX_TOKENS,
342
- temperature: request.temperature ?? 0.3,
343
- };
344
- if (request.topP !== null) params["top_p"] = request.topP;
345
- if (request.reasoningEffort !== null && request.reasoningEffort !== "none") {
346
- params["reasoning_effort"] = request.reasoningEffort;
347
- }
348
- if (systemCombined) params["system"] = systemCombined;
349
- if (request.tools.length > 0) {
350
- params["tools"] = request.tools.map((tool) => ({
351
- // `type: "function"` is part of the envelope. The reference client sends
352
- // it on every tool, and a tool without it is not recognised as callable.
353
- type: "function",
354
- name: tool.name,
355
- description: tool.description ?? undefined,
356
- input_schema: isGeminiModelId(modelId) ? geminiSafeSchema(tool.jsonSchema) : tool.jsonSchema,
357
- }));
358
- }
359
- return {
360
- threadId,
361
- // The client sends these three as `null`, not `""` / absent. `memory` was
362
- // an empty string and `taste`/`skills` were missing entirely; the envelope
363
- // is validated, so an absent field is not the same as a null one.
364
- memory: null,
365
- taste: null,
366
- skills: null,
367
- config: {
368
- workingDir: "",
369
- date: new Date().toISOString().slice(0, 10),
370
- // The client reports the real runtime: `linux-x64, Node.js v24.0.0`.
371
- // An empty string is a blank attribution field the upstream never sees
372
- // filled, which is indistinguishable from a client that did not report.
373
- environment: `${process.platform}-${process.arch}, Node.js ${process.version}`,
374
- structure: [],
375
- isGitRepo: false,
376
- currentBranch: "",
377
- mainBranch: "",
378
- gitStatus: "",
379
- recentCommits: [],
380
- },
381
- params,
382
- };
383
- }
384
-
385
- /**
386
- * The identity headers Command Code's own client sends.
387
- *
388
- * `x-cli-environment` is `production`, not `cli` — that is the value the client
389
- * sends, and the pair is what identifies the surface to the gateway.
390
- *
391
- * `x-project-slug` and `x-taste-learning` were simply absent. Both are
392
- * attribution fields the client always sends; the slug is derived from the
393
- * working directory the same way the client derives it.
394
- *
395
- * `x-session-id` is sent only when a session exists. The client omits it rather
396
- * than inventing one, and a value minted per request would attribute every
397
- * call to a different session.
398
- */
399
- export async function headers(sessionId: string, token: string): Promise<Record<string, string>> {
400
- return {
401
- "content-type": "application/json",
402
- accept: "text/event-stream",
403
- authorization: `Bearer ${token}`,
404
- "x-command-code-version": getCommandCodeVersion(),
405
- "x-cli-environment": "production",
406
- "x-taste-learning": "true",
407
- "x-project-slug": "cartethyia",
408
- "user-agent": "cli",
409
- ...(sessionId.length > 0 ? { "x-session-id": sessionId } : {}),
410
- };
411
- }
412
-
413
-
414
- type StreamState = { toolIndexById: Map<string, number>; nextToolIndex: number; finishReason: string | undefined; usage: Record<string, unknown> | undefined; think: MimoThinkSplitter };
415
-
416
- export function ccMapFinishReason(reason: string): CanonicalStopReason {
417
- return reason === "length" ? "length" : reason === "tool_calls" ? "tool_use" : reason === "content_filter" ? "content_filter" : "stop";
418
- }
419
-
420
- export function transformLine(line: string, state: StreamState, seqBase: number): CanonicalEvent[] {
421
- let event: Record<string, unknown>;
422
- try {
423
- event = JSON.parse(line) as Record<string, unknown>;
424
- } catch {
425
- return [];
426
- }
427
- const type = readString(event, "type");
428
- if (!type) return [];
429
- if (type === "reasoning-delta") {
430
- const text = readString(event, "text") || readString(event, "delta");
431
- return text ? [{ type: "content_delta", sequence_number: seqBase, content: { kind: "reasoning", payload: null, summary: text } } as CanonicalEvent] : [];
432
- }
433
- if (type === "text-delta") {
434
- const text = readString(event, "text") || readString(event, "delta");
435
- if (!text) return [];
436
- const split = state.think.push(text);
437
- const events: CanonicalEvent[] = [];
438
- if (split.reasoning) events.push({ type: "content_delta", sequence_number: seqBase, content: { kind: "reasoning", payload: null, summary: split.reasoning } } as CanonicalEvent);
439
- if (split.text) events.push({ type: "content_delta", sequence_number: seqBase, content: { kind: "text", text: split.text } } as CanonicalEvent);
440
- return events;
441
- }
442
- if (type === "tool-input-start") {
443
- const id = readString(event, "id") || readString(event, "toolCallId");
444
- if (!id || state.toolIndexById.has(id)) return [];
445
- state.toolIndexById.set(id, state.nextToolIndex++);
446
- return [{ type: "tool_call_delta", sequence_number: seqBase, call_id: id, name: readString(event, "toolName") ?? "", arguments_delta: "" } as CanonicalEvent];
447
- }
448
- if (type === "tool-input-delta") {
449
- const id = readString(event, "id") || readString(event, "toolCallId");
450
- const delta = readString(event, "delta") || readString(event, "inputTextDelta");
451
- if (!id || !delta || !state.toolIndexById.has(id)) return [];
452
- return [{ type: "tool_call_delta", sequence_number: seqBase, call_id: id, arguments_delta: delta } as CanonicalEvent];
453
- }
454
- if (type === "tool-call") {
455
- const id = readString(event, "toolCallId");
456
- if (!id || state.toolIndexById.has(id)) return [];
457
- state.toolIndexById.set(id, state.nextToolIndex++);
458
- const input = typeof event["input"] === "string" ? (event["input"] as string) : JSON.stringify(event["input"] ?? {});
459
- return [
460
- { type: "tool_call_delta", sequence_number: seqBase, call_id: id, name: readString(event, "toolName") ?? "", arguments_delta: "" } as CanonicalEvent,
461
- { type: "tool_call_delta", sequence_number: seqBase + 1, call_id: id, arguments_delta: input } as CanonicalEvent,
462
- ];
463
- }
464
- if (type === "finish-step") {
465
- const reason = readString(event, "finishReason");
466
- if (reason) state.finishReason = reason;
467
- if (typeof event["usage"] === "object" && event["usage"] !== null && !Array.isArray(event["usage"])) state.usage = event["usage"] as Record<string, unknown>;
468
- return [];
469
- }
470
- if (type === "finish") {
471
- const reason = state.finishReason ?? readString(event, "finishReason") ?? "stop";
472
- const canonicalReason = ccMapFinishReason(reason);
473
- const events: CanonicalEvent[] = [
474
- { type: "terminal", sequence_number: seqBase, state: "complete", stop_reason: canonicalReason, provider_stop_reason: reason } as CanonicalEvent,
475
- ];
476
- if (state.usage) {
477
- const prompt = readNumber(state.usage, "promptTokens") ?? readNumber(state.usage, "inputTokens") ?? 0;
478
- const completion = readNumber(state.usage, "completionTokens") ?? readNumber(state.usage, "outputTokens") ?? 0;
479
- const total = readNumber(state.usage, "totalTokens") ?? prompt + completion;
480
- const cached = readNumber(state.usage, "cachedTokens") ?? readNumber(state.usage, "cacheReadTokens") ?? 0;
481
- const usageRecord = usageFromProvider({
482
- input_tokens: prompt,
483
- output_tokens: completion,
484
- total_tokens: total,
485
- cached_tokens: cached,
486
- cache_creation_input_tokens: readNumber(state.usage, "cacheWriteTokens") ?? undefined,
487
- } as unknown as Record<string, unknown>);
488
- // Append usage to terminal
489
- (events[0] as unknown as Record<string, unknown>)["usage"] = usageRecord;
490
- }
491
- return events;
492
- }
493
- if (type === "error") {
494
- const raw = event["error"] ?? event["message"] ?? event;
495
- const errorObject = isRecord(raw) ? raw : event;
496
- const identifier = upstreamErrorIdentifier(raw) ?? upstreamErrorIdentifier(event);
497
- const providerStatus = [
498
- errorObject["status"],
499
- errorObject["statusCode"],
500
- errorObject["code"],
501
- event["status"],
502
- event["statusCode"],
503
- event["code"],
504
- ].find(
505
- (value): value is number =>
506
- typeof value === "number" &&
507
- Number.isFinite(value) &&
508
- value >= 400 &&
509
- value < 600,
510
- );
511
- const classification = classifyUpstreamError(providerStatus, identifier);
512
- const message =
513
- extractUpstreamMessage(raw) ||
514
- extractUpstreamMessage(event) ||
515
- "Command Code stream error";
516
- throw new GatewayError(
517
- classification.code,
518
- classification.status,
519
- message.slice(0, 500),
520
- {
521
- ...(providerStatus === undefined ? {} : { providerStatus }),
522
- ...(identifier ? { providerCode: identifier } : {}),
523
- ...(classification.credentialEvidence ? { credentialEvidence: true } : {}),
524
- ...(classification.rateLimitScope
525
- ? { rateLimitScope: classification.rateLimitScope }
526
- : {}),
527
- },
528
- classification.origin,
529
- );
530
- }
531
- return [];
532
- }
533
-
534
- /** NDJSON transform — beta-style simple loop + signal-aware read for abort/timeout propagation. */
535
- export async function* transformNdjson(body: ReadableStream<Uint8Array>, signal: AbortSignal): AsyncIterable<CanonicalEvent> {
536
- const reader = body.getReader();
537
- const decoder = new TextDecoder();
538
- const state: StreamState = { toolIndexById: new Map(), nextToolIndex: 0, finishReason: undefined, usage: undefined, think: new MimoThinkSplitter() };
539
- let buffer = "";
540
- let hasTerminal = false;
541
- let seq = 1;
542
- // initial response_start
543
- yield { type: "response_start", sequence_number: seq++, model: "commandcode" } as CanonicalEvent;
544
-
545
- const readWithAbort = (): Promise<{ done: boolean; value?: Uint8Array }> => {
546
- if (signal.aborted) throw new GatewayError("transport_closed", 499, "Command Code stream aborted");
547
- const { promise, resolve, reject } = Promise.withResolvers<{ done: boolean; value?: Uint8Array }>() as unknown as { promise: Promise<{ done: boolean; value?: Uint8Array }>; resolve: (v: unknown) => void; reject: (e: unknown) => void };
548
- const onAbort = (): void => {
549
- if (signal.aborted) reject(new GatewayError("transport_closed", 499, "Command Code stream aborted"));
550
- else reject(new GatewayError("platform_unavailable", 502, "Command Code stream error", {}, "upstream"));
551
- };
552
- signal.addEventListener("abort", onAbort, { once: true });
553
- void reader.read().then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
554
- return promise;
555
- };
556
-
557
- try {
558
- while (true) {
559
- const { done, value } = await readWithAbort();
560
- if (done) break;
561
- buffer += decoder.decode(value, { stream: true });
562
- let nl = buffer.indexOf("\n");
563
- while (nl !== -1) {
564
- const line = buffer.slice(0, nl).trim();
565
- buffer = buffer.slice(nl + 1);
566
- if (line) {
567
- let evs: CanonicalEvent[] = [];
568
- try {
569
- evs = transformLine(line, state, seq);
570
- } catch (e) {
571
- throw e;
572
- }
573
- for (const ev of evs) {
574
- // Strictly increasing per line, in emission order: the Responses
575
- // surface throws on any non-monotonic sequence mid-stream, after
576
- // partial bytes are already flushed. No special-casing for
577
- // dual-event lines — order is order.
578
- (ev as unknown as Record<string, unknown>)["sequence_number"] = seq++;
579
- if (ev.type === "terminal") hasTerminal = true;
580
- yield ev;
581
- }
582
- }
583
- nl = buffer.indexOf("\n");
584
- }
585
- }
586
- buffer += decoder.decode();
587
- const tail = buffer.trim();
588
- if (tail) {
589
- for (const ev of transformLine(tail, state, seq)) {
590
- if (ev.type === "terminal") hasTerminal = true;
591
- (ev as unknown as Record<string, unknown>)["sequence_number"] = seq++;
592
- yield ev;
593
- }
594
- }
595
- const rest = state.think.flush();
596
- if (rest.reasoning) yield { type: "content_delta", sequence_number: seq++, content: { kind: "reasoning", payload: null, summary: rest.reasoning } } as CanonicalEvent;
597
- if (rest.text) yield { type: "content_delta", sequence_number: seq++, content: { kind: "text", text: rest.text } } as CanonicalEvent;
598
- if (!hasTerminal) {
599
- // NDJSON ended with no terminal envelope: truncated, never complete.
600
- yield { type: "terminal", sequence_number: seq++, state: "failed", stop_reason: ccMapFinishReason(state.finishReason ?? "stop"), provider_stop_reason: state.finishReason ?? "stop" } as CanonicalEvent;
601
- }
602
- } finally {
603
- try {
604
- reader.releaseLock?.();
605
- } catch {
606
- // Best-effort reader unlock during stream cleanup.
607
- }
608
- void reader.cancel().catch(() => {});
609
- }
610
- }
611
-
612
- // CommandCode model catalog.
613
-
614
-
615
-
616
- // ProviderAdapter — the Provider API serves three wires, so dispatch is the
617
- // shared OpenAI-compatible adapter rather than one bespoke NDJSON reader.
618
- //
619
- // `/provider/v1` answers `/chat/completions`, `/responses` and `/messages`, and
620
- // the model row states which one serves it. The bespoke `/alpha/generate`
621
- // envelope is the CLI's own surface and stays reachable through
622
- // `buildRequest` for callers that still speak it, but routing no longer forces
623
- // every model onto it — which is what left all nine `claude-*` ids unroutable.
624
-
625
- interface CommandCodeAdapterOptions {
626
- readonly fetch?: typeof fetch;
627
- }
628
-
629
- function commandCodeIdentityHeaders(_token: string): Record<string, string> {
630
- return {
631
- "x-command-code-version": getCommandCodeVersion(),
632
- "x-cli-environment": "production",
633
- "x-taste-learning": "true",
634
- "x-project-slug": "cartethyia",
635
- "user-agent": "cli",
636
- };
637
- }
638
-
639
- function providerApiAdapter(options: CommandCodeAdapterOptions): ProviderAdapter {
640
- return createApiKeyAdapter(
641
- {
642
- provider_id: COMMANDCODE_PROVIDER_ID,
643
- base_url: COMMANDCODE_BASE_URL,
644
- endpoint_paths_by_wire_family: {
645
- chat: COMMANDCODE_CHAT_PATH,
646
- responses: COMMANDCODE_RESPONSES_PATH,
647
- messages: COMMANDCODE_MESSAGES_PATH,
648
- },
649
- buildExtraHeaders: async (context: ProviderDispatchContext) =>
650
- commandCodeIdentityHeaders(await readCredentialSecret(context.credential, "Command Code bearer token is required")),
651
- },
652
- options.fetch,
653
- );
654
- }
655
-
656
- class CommandCodeAdapter implements ProviderAdapter {
657
- readonly provider_id = COMMANDCODE_PROVIDER_ID;
658
- private readonly inner: ProviderAdapter;
659
-
660
- constructor(options: CommandCodeAdapterOptions = {}) {
661
- this.inner = providerApiAdapter(options);
662
- }
663
-
664
- dispatch(
665
- request: CanonicalRequest,
666
- candidate: ProviderDispatchTarget,
667
- context: ProviderDispatchContext,
668
- ): AsyncIterable<CanonicalEvent> {
669
- return this.inner.dispatch(request, candidate, context);
670
- }
671
- }
672
-
673
- export function createCommandCodeAdapter(options: CommandCodeAdapterOptions = {}): ProviderAdapter {
674
- return new CommandCodeAdapter(options);
675
- }
1
+ // Factory-blocked (Phase C4): proprietary `{threadId, config, params}`
2
+ // envelope with NDJSON stream transform — non-OpenAI wire; stays bespoke.
3
+ import { GatewayError } from "../../../protocol/gateway-error";
4
+ import { canContainToolResult, joinTextParts, toolCallParts, toolResultParts } from "../../../protocol/canonical-model";
5
+ import {
6
+ classifyUpstreamError,
7
+ extractUpstreamMessage,
8
+ upstreamErrorIdentifier,
9
+ } from "../../../transport/failure-policy";
10
+ import { createApiKeyAdapter } from "../../configured-provider";
11
+ import type { CanonicalEvent, CanonicalRequest, CanonicalStopReason, ContentPart } from "../../../protocol/canonical-model";
12
+ import { isRecord, readNumber, readString, resolveImageSource, splitDataUrl } from "../../../protocol/codecs";
13
+ import { usageFromProvider } from "../../provider-usage";
14
+ import { readCredentialSecret, type ProviderDispatchTarget, type ProviderAdapter, type ProviderDispatchContext } from "../../provider-contracts";
15
+ import { providerBaseUrl } from "../../provider-metadata";
16
+ import { defineModel } from "../../provider-model-definition";
17
+ import type { ModelDefinition } from "../../provider-model-definition";
18
+ import {
19
+ getCommandCodeVersion,
20
+ } from "../../operations/client-versions";
21
+ import { MimoThinkSplitter } from "../xiaomi-mimo/think-stream";
22
+ export const COMMANDCODE_PROVIDER_ID = "commandcode" as const;
23
+ export const COMMANDCODE_BASE_URL = providerBaseUrl("commandcode");
24
+ /** The three routes the Provider API serves, one per wire family. */
25
+ export const COMMANDCODE_CHAT_PATH = "/chat/completions" as const;
26
+ export const COMMANDCODE_RESPONSES_PATH = "/responses" as const;
27
+ export const COMMANDCODE_MESSAGES_PATH = "/messages" as const;
28
+
29
+ /**
30
+ * Command Code's roster, as the Provider API publishes it.
31
+ *
32
+ * Generated from the live `/provider/v1/models` listing (95 rows). Each row
33
+ * carries the wire that serves it and the context window the API states, which
34
+ * is the whole point: dispatch is per-row, and every `claude-*` id is served on
35
+ * `/messages` only — filed as chat, it could never be dispatched.
36
+ *
37
+ * `vision: true` on every row is the catalog's own declaration for this
38
+ * provider; a model that rejects an image answers for itself.
39
+ *
40
+ * This is the offline seed. It is superseded by `discoverCommandCodeModels`
41
+ * whenever a fetch succeeds, and `seedBundledModels` prunes any row this list
42
+ * stops declaring — so an id Command Code retires disappears on the next boot
43
+ * rather than lingering as a card that can only ever fail.
44
+ */
45
+ export const COMMANDCODE_MODELS: readonly ModelDefinition[] = [
46
+ defineModel({ id: "MiniMaxAI/MiniMax-M2.5", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 200000, reasoning: true, toolCall: true, vision: true }),
47
+ defineModel({ id: "MiniMaxAI/MiniMax-M2.7", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 200000, reasoning: true, toolCall: true, vision: true }),
48
+ defineModel({ id: "MiniMaxAI/MiniMax-M3", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
49
+ defineModel({ id: "Qwen/Qwen3.6-Max-Preview", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 200000, reasoning: true, toolCall: true, vision: true }),
50
+ defineModel({ id: "Qwen/Qwen3.6-Plus", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 200000, reasoning: true, toolCall: true, vision: true }),
51
+ defineModel({ id: "Qwen/Qwen3.7-Flash", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
52
+ defineModel({ id: "Qwen/Qwen3.7-Max", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
53
+ defineModel({ id: "Qwen/Qwen3.7-Plus", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
54
+ defineModel({ id: "Qwen/Qwen3.8-27B", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 262144, reasoning: true, toolCall: true, vision: true }),
55
+ defineModel({ id: "Qwen/Qwen3.8-Flash", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "chat", endpoint: "/chat/completions", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
56
+ defineModel({ id: "Qwen/Qwen3.8-Max", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
57
+ defineModel({ id: "Qwen/Qwen3.8-Max-0902", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "chat", endpoint: "/chat/completions", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
58
+ defineModel({ id: "Qwen/Qwen3.8-Max-Prime", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
59
+ defineModel({ id: "Qwen/Qwen3.8-Omni-Flash", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
60
+ defineModel({ id: "claude-fable-5", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "messages", endpoint: "/messages", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
61
+ defineModel({ id: "claude-fable-5-1", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "messages", endpoint: "/messages", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
62
+ defineModel({ id: "claude-haiku-4-5-20251001", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "messages", endpoint: "/messages", ctx: 200000, reasoning: true, toolCall: true, vision: true }),
63
+ defineModel({ id: "claude-haiku-5-5", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "messages", endpoint: "/messages", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
64
+ defineModel({ id: "claude-opus-4-7", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "messages", endpoint: "/messages", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
65
+ defineModel({ id: "claude-opus-4-8", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "messages", endpoint: "/messages", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
66
+ defineModel({ id: "claude-opus-5", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "messages", endpoint: "/messages", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
67
+ defineModel({ id: "claude-opus-5-5", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "messages", endpoint: "/messages", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
68
+ defineModel({ id: "claude-sonnet-4-6", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "messages", endpoint: "/messages", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
69
+ defineModel({ id: "claude-sonnet-5", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "messages", endpoint: "/messages", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
70
+ defineModel({ id: "claude-sonnet-5-5", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "messages", endpoint: "/messages", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
71
+ defineModel({ id: "deepseek/deepseek-v4-flash", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
72
+ defineModel({ id: "deepseek/deepseek-v4-flash-fast", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "chat", endpoint: "/chat/completions", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
73
+ defineModel({ id: "deepseek/deepseek-v4-flash-vision-exp", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
74
+ defineModel({ id: "deepseek/deepseek-v4-pro", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
75
+ defineModel({ id: "deepseek/deepseek-v4.1-flash", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
76
+ defineModel({ id: "deepseek/deepseek-v4.1-flash-fast", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
77
+ defineModel({ id: "google/gemini-3.1-flash-lite", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
78
+ defineModel({ id: "google/gemini-3.5-flash", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
79
+ defineModel({ id: "google/gemini-3.5-flash-lite", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
80
+ defineModel({ id: "google/gemini-3.6-flash", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
81
+ defineModel({ id: "google/gemini-3.7-flash", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "chat", endpoint: "/chat/completions", ctx: 1048576, reasoning: true, toolCall: true, vision: true }),
82
+ defineModel({ id: "google/gemini-3.8-flash", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
83
+ defineModel({ id: "google/gemini-4-argon", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
84
+ defineModel({ id: "gpt-5.3-codex", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 400000, reasoning: true, toolCall: true, vision: true }),
85
+ defineModel({ id: "gpt-5.4", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 400000, reasoning: true, toolCall: true, vision: true }),
86
+ defineModel({ id: "gpt-5.4-mini", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 400000, reasoning: true, toolCall: true, vision: true }),
87
+ defineModel({ id: "gpt-5.5", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 400000, reasoning: true, toolCall: true, vision: true }),
88
+ defineModel({ id: "gpt-5.6-luna", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1050000, reasoning: true, toolCall: true, vision: true }),
89
+ defineModel({ id: "gpt-5.6-sol", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1050000, reasoning: true, toolCall: true, vision: true }),
90
+ defineModel({ id: "gpt-5.6-terra", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1050000, reasoning: true, toolCall: true, vision: true }),
91
+ defineModel({ id: "gpt-6-astra", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1050000, reasoning: true, toolCall: true, vision: true }),
92
+ defineModel({ id: "gpt-6-luna", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1050000, reasoning: true, toolCall: true, vision: true }),
93
+ defineModel({ id: "gpt-6-sol", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1050000, reasoning: true, toolCall: true, vision: true }),
94
+ defineModel({ id: "gpt-6.1-sol", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1050000, reasoning: true, toolCall: true, vision: true }),
95
+ defineModel({ id: "inclusionai/ling-3.1-flash", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "chat", endpoint: "/chat/completions", ctx: 262144, reasoning: true, toolCall: true, vision: true }),
96
+ defineModel({ id: "meituan/LongCat-2.0", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "chat", endpoint: "/chat/completions", ctx: 1048576, reasoning: true, toolCall: true, vision: true }),
97
+ defineModel({ id: "meta/muse-spark-1.1", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1048576, reasoning: true, toolCall: true, vision: true }),
98
+ defineModel({ id: "meta/muse-spark-1.2", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1048576, reasoning: true, toolCall: true, vision: true }),
99
+ defineModel({ id: "meta/muse-spark-1.2-contributor", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1048576, reasoning: true, toolCall: true, vision: true }),
100
+ defineModel({ id: "meta/muse-spark-1.3", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1048576, reasoning: true, toolCall: true, vision: true }),
101
+ defineModel({ id: "meta/muse-spark-1.3-contributor", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1048576, reasoning: true, toolCall: true, vision: true }),
102
+ defineModel({ id: "meta/muse-spark-open", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1048576, reasoning: true, toolCall: true, vision: true }),
103
+ defineModel({ id: "meta/muse-wonder-1.0", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1048576, reasoning: true, toolCall: true, vision: true }),
104
+ defineModel({ id: "minimax/minimax-m3.1-flash-preview", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
105
+ defineModel({ id: "minimax/minimax-m3.1-flash-preview:free", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
106
+ defineModel({ id: "mistral/mistral-large-4", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 524288, reasoning: true, toolCall: true, vision: true }),
107
+ defineModel({ id: "moonshotai/Kimi-K2.5", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 256000, reasoning: true, toolCall: true, vision: true }),
108
+ defineModel({ id: "moonshotai/Kimi-K2.6", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 256000, reasoning: true, toolCall: true, vision: true }),
109
+ defineModel({ id: "moonshotai/Kimi-K2.7-Code", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 256000, reasoning: true, toolCall: true, vision: true }),
110
+ defineModel({ id: "moonshotai/Kimi-K2.7-Code-Highspeed", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 262000, reasoning: true, toolCall: true, vision: true }),
111
+ defineModel({ id: "moonshotai/Kimi-K3", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
112
+ defineModel({ id: "nvidia/nemotron-3-ultra-550b-a55b", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
113
+ defineModel({ id: "nvidia/nemotron-3.5-super-vl", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 262144, reasoning: true, toolCall: true, vision: true }),
114
+ defineModel({ id: "poolside/laguna-s-2.1-free", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 256000, reasoning: true, toolCall: true, vision: true }),
115
+ defineModel({ id: "reflection/beam:free", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1048576, reasoning: true, toolCall: true, vision: true }),
116
+ defineModel({ id: "sakana/fugu-ultra", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
117
+ defineModel({ id: "stealth/cat-jam:free", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1048576, reasoning: true, toolCall: true, vision: true }),
118
+ defineModel({ id: "stealth/glyph-cluster:free", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 256000, reasoning: true, toolCall: true, vision: true }),
119
+ defineModel({ id: "stepfun/Step-3.5-Flash", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 262144, reasoning: true, toolCall: true, vision: true }),
120
+ defineModel({ id: "stepfun/Step-3.7-Flash", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 256000, reasoning: true, toolCall: true, vision: true }),
121
+ defineModel({ id: "stepfun/Step-5-Preview", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
122
+ defineModel({ id: "tencent/hy3-paid", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 262144, reasoning: true, toolCall: true, vision: true }),
123
+ defineModel({ id: "tencent/hy4-preview", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "chat", endpoint: "/chat/completions", ctx: 1048576, reasoning: true, toolCall: true, vision: true }),
124
+ defineModel({ id: "thinkingmachines/inkling", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 256000, reasoning: true, toolCall: true, vision: true }),
125
+ defineModel({ id: "thinkingmachines/inkling-small", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
126
+ defineModel({ id: "xai/grok-4.5", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 500000, reasoning: true, toolCall: true, vision: true }),
127
+ defineModel({ id: "xai/grok-4.6", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 500000, reasoning: true, toolCall: true, vision: true }),
128
+ defineModel({ id: "xai/grok-4.7", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 500000, reasoning: true, toolCall: true, vision: true }),
129
+ defineModel({ id: "xiaomi/mimo-v2.5", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
130
+ defineModel({ id: "xiaomi/mimo-v2.5-pro", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
131
+ defineModel({ id: "xiaomi/mimo-v2.6-flash", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1048576, reasoning: true, toolCall: true, vision: true }),
132
+ defineModel({ id: "xiaomi/mimo-v2.6-pro", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1048576, reasoning: true, toolCall: true, vision: true }),
133
+ defineModel({ id: "xiaomi/mimo-v2.6-pro-ultraspeed", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1048576, reasoning: true, toolCall: true, vision: true }),
134
+ defineModel({ id: "z-ai/glm-5.3-flash", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "chat", endpoint: "/chat/completions", ctx: 1048576, reasoning: true, toolCall: true, vision: true }),
135
+ defineModel({ id: "z-ai/glm-5.3-flashx", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
136
+ defineModel({ id: "zai-org/GLM-5", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 200000, reasoning: true, toolCall: true, vision: true }),
137
+ defineModel({ id: "zai-org/GLM-5.1", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 200000, reasoning: true, toolCall: true, vision: true }),
138
+ defineModel({ id: "zai-org/GLM-5.2", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
139
+ defineModel({ id: "zai-org/GLM-5.2-Fast", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
140
+ defineModel({ id: "zai-org/GLM-5.3", providerId: COMMANDCODE_PROVIDER_ID, wireFamily: "responses", endpoint: "/responses", ctx: 1000000, reasoning: true, toolCall: true, vision: true }),
141
+ ];
142
+
143
+
144
+ // CommandCode provider constants.
145
+
146
+ const COMMANDCODE_DEFAULT_MAX_TOKENS = 4096;
147
+
148
+ /**
149
+ * The `/alpha/generate` wire, as the CLI client sends it:
150
+ * - `params.system` is a top-level string; system turns never enter `messages`
151
+ * - every `content` is an array of blocks, never a string
152
+ * - an assistant tool call is `{type:"tool-call", toolCallId, toolName, input}`
153
+ * and is preceded by a reasoning block, which the upstream requires
154
+ * - a tool result is its own `role:"tool"` turn, not text glued into the user turn
155
+ * - an image is `{type:"image", image, mimeType}`
156
+ */
157
+ function toolResultValue(content: readonly ContentPart[] | string): string {
158
+ if (typeof content === "string") return content;
159
+ return content
160
+ .filter((part) => part.kind === "text")
161
+ .map((part) => part.text)
162
+ .filter((text) => text.length > 0)
163
+ .join("\n");
164
+ }
165
+
166
+ function imageBlock(payload: unknown): Record<string, unknown> | undefined {
167
+ const source = resolveImageSource(payload);
168
+ if (source?.url === undefined) return undefined;
169
+ const inline = splitDataUrl(source.url);
170
+ return { type: "image", image: source.url, ...(inline ? { mimeType: inline.mediaType } : {}) };
171
+ }
172
+
173
+ function contentBlocks(parts: readonly ContentPart[]): Array<Record<string, unknown>> {
174
+ const blocks: Array<Record<string, unknown>> = [];
175
+ for (const part of parts) {
176
+ if (part.kind === "text") {
177
+ if (part.text.length > 0) blocks.push({ type: "text", text: part.text });
178
+ continue;
179
+ }
180
+ if (part.kind === "image") {
181
+ const block = imageBlock(part.payload);
182
+ if (block) blocks.push(block);
183
+ }
184
+ }
185
+ return blocks.length > 0 ? blocks : [{ type: "text", text: "" }];
186
+ }
187
+
188
+ function parsedInput(value: unknown): unknown {
189
+ if (typeof value !== "string") return value ?? {};
190
+ try {
191
+ return JSON.parse(value);
192
+ } catch {
193
+ return {};
194
+ }
195
+ }
196
+
197
+ export function convertMessages(messages: CanonicalRequest["messages"]): {
198
+ messages: Array<Record<string, unknown>>;
199
+ system?: string;
200
+ } {
201
+ const out: Array<Record<string, unknown>> = [];
202
+ const systemTexts: string[] = [];
203
+ for (const message of messages) {
204
+ if (message.role === "system" || message.role === "developer") {
205
+ const text = joinTextParts(message.content);
206
+ if (text.length > 0) systemTexts.push(text);
207
+ continue;
208
+ }
209
+ // Answers live in `tool` turns or in `user` turns (the Messages ledger
210
+ // re-homes them). Each result is its own `role:"tool"` turn: flattening
211
+ // them into the user turn as prose left the tool call unanswered.
212
+ if (canContainToolResult(message) && toolResultParts(message).length > 0) {
213
+ for (const result of toolResultParts(message)) {
214
+ out.push({
215
+ role: "tool",
216
+ content: [
217
+ {
218
+ type: "tool-result",
219
+ toolCallId: result.call_id,
220
+ toolName: "",
221
+ output: { type: "text", value: toolResultValue(result.content) },
222
+ },
223
+ ],
224
+ });
225
+ }
226
+ const remainder = contentBlocks(message.content.filter((part) => part.kind !== "toolResult"));
227
+ if (remainder.some((block) => block["text"] !== "")) out.push({ role: "user", content: remainder });
228
+ continue;
229
+ }
230
+ if (message.role === "assistant") {
231
+ const blocks: Array<Record<string, unknown>> = [];
232
+ const calls = toolCallParts(message);
233
+ const reasoning = message.content
234
+ .filter((part) => part.kind === "reasoning")
235
+ .map((part) => part.summary ?? "")
236
+ .filter((text) => text.length > 0)
237
+ .join("");
238
+ if (reasoning.length > 0 || calls.length > 0) {
239
+ blocks.push({ type: "reasoning", text: reasoning.length > 0 ? reasoning : " " });
240
+ }
241
+ const text = joinTextParts(message.content);
242
+ if (text.length > 0) blocks.push({ type: "text", text });
243
+ for (const call of calls) {
244
+ blocks.push({
245
+ type: "tool-call",
246
+ toolCallId: call.call_id,
247
+ toolName: call.name,
248
+ input: parsedInput(call.arguments),
249
+ });
250
+ }
251
+ out.push({ role: "assistant", content: blocks.length > 0 ? blocks : [{ type: "text", text: "" }] });
252
+ continue;
253
+ }
254
+ out.push({ role: "user", content: contentBlocks(message.content) });
255
+ }
256
+ const system = systemTexts.join("\n\n");
257
+ return system.length > 0 ? { messages: out, system } : { messages: out };
258
+ }
259
+
260
+ /**
261
+ * Whether a tool schema needs Gemini's normalized form.
262
+ *
263
+ * The client rewrites a schema for `google/gemini-*` because the gateway can
264
+ * turn nullable type arrays into `any_of` with sibling fields, which Vertex
265
+ * rejects. This provider routes Gemini over the same Provider API, so the same
266
+ * rewrite applies.
267
+ */
268
+ export function isGeminiModelId(modelId: string): boolean {
269
+ return modelId.startsWith("google/gemini-");
270
+ }
271
+
272
+ const SCHEMA_MAP_FIELDS = new Set([
273
+ "$defs",
274
+ "definitions",
275
+ "dependentSchemas",
276
+ "patternProperties",
277
+ "properties",
278
+ ]);
279
+ const SCHEMA_ARRAY_FIELDS = new Set(["allOf", "anyOf", "oneOf", "prefixItems"]);
280
+ const SCHEMA_VALUE_FIELDS = new Set([
281
+ "additionalItems",
282
+ "additionalProperties",
283
+ "contains",
284
+ "contentSchema",
285
+ "else",
286
+ "if",
287
+ "items",
288
+ "not",
289
+ "propertyNames",
290
+ "then",
291
+ "unevaluatedItems",
292
+ "unevaluatedProperties",
293
+ ]);
294
+
295
+ /**
296
+ * A schema Gemini's transport accepts: a single type plus `nullable`, with null
297
+ * defaults dropped. Genuine multi-type unions and `required` are left alone —
298
+ * only the nullable-array spelling is what Vertex rejects.
299
+ */
300
+ export function geminiSafeSchema(value: unknown): unknown {
301
+ if (Array.isArray(value)) return value.map(geminiSafeSchema);
302
+ if (!isRecord(value)) return value;
303
+ const out: Record<string, unknown> = {};
304
+ for (const [key, raw] of Object.entries(value)) {
305
+ if (key === "default" && raw === null) continue;
306
+ if (SCHEMA_MAP_FIELDS.has(key) && isRecord(raw)) {
307
+ out[key] = Object.fromEntries(
308
+ Object.entries(raw).map(([name, child]) => [name, geminiSafeSchema(child)]),
309
+ );
310
+ continue;
311
+ }
312
+ out[key] = SCHEMA_ARRAY_FIELDS.has(key) || SCHEMA_VALUE_FIELDS.has(key)
313
+ ? geminiSafeSchema(raw)
314
+ : raw;
315
+ }
316
+ // A nullable type array becomes one type plus `nullable`.
317
+ if (Array.isArray(out["type"])) {
318
+ const types = out["type"].filter((entry): entry is string => typeof entry === "string");
319
+ const withoutNull = types.filter((entry) => entry !== "null");
320
+ if (types.length !== withoutNull.length && withoutNull.length > 0) {
321
+ out["type"] = withoutNull.length === 1 ? withoutNull[0] : withoutNull;
322
+ out["nullable"] = true;
323
+ }
324
+ }
325
+ return out;
326
+ }
327
+
328
+ export function buildRequest(
329
+ modelId: string,
330
+ request: { messages: CanonicalRequest["messages"]; tools: { readonly name: string; readonly description: string | undefined; readonly jsonSchema: unknown }[]; maxOutputTokens: number | null; temperature: number | null; topP: number | null; reasoningEffort: string | null },
331
+ threadId: string,
332
+ systemExtra?: string,
333
+ ): Record<string, unknown> {
334
+ const { messages, system: systemFromMessages } = convertMessages(request.messages);
335
+ const systemCombined = systemExtra ? (systemFromMessages ? `${systemExtra}\n${systemFromMessages}` : systemExtra) : systemFromMessages;
336
+ const params: Record<string, unknown> = {
337
+ model: modelId,
338
+ messages,
339
+ stream: true,
340
+ max_tokens: request.maxOutputTokens ?? COMMANDCODE_DEFAULT_MAX_TOKENS,
341
+ temperature: request.temperature ?? 0.3,
342
+ };
343
+ if (request.topP !== null) params["top_p"] = request.topP;
344
+ if (request.reasoningEffort !== null && request.reasoningEffort !== "none") {
345
+ params["reasoning_effort"] = request.reasoningEffort;
346
+ }
347
+ if (systemCombined) params["system"] = systemCombined;
348
+ if (request.tools.length > 0) {
349
+ params["tools"] = request.tools.map((tool) => ({
350
+ // `type: "function"` is part of the envelope. The reference client sends
351
+ // it on every tool, and a tool without it is not recognised as callable.
352
+ type: "function",
353
+ name: tool.name,
354
+ description: tool.description ?? undefined,
355
+ input_schema: isGeminiModelId(modelId) ? geminiSafeSchema(tool.jsonSchema) : tool.jsonSchema,
356
+ }));
357
+ }
358
+ return {
359
+ threadId,
360
+ // The client sends these three as `null`, not `""` / absent. `memory` was
361
+ // an empty string and `taste`/`skills` were missing entirely; the envelope
362
+ // is validated, so an absent field is not the same as a null one.
363
+ memory: null,
364
+ taste: null,
365
+ skills: null,
366
+ config: {
367
+ workingDir: "",
368
+ date: new Date().toISOString().slice(0, 10),
369
+ // The client reports the real runtime: `linux-x64, Node.js v24.0.0`.
370
+ // An empty string is a blank attribution field the upstream never sees
371
+ // filled, which is indistinguishable from a client that did not report.
372
+ environment: `${process.platform}-${process.arch}, Node.js ${process.version}`,
373
+ structure: [],
374
+ isGitRepo: false,
375
+ currentBranch: "",
376
+ mainBranch: "",
377
+ gitStatus: "",
378
+ recentCommits: [],
379
+ },
380
+ params,
381
+ };
382
+ }
383
+
384
+ /**
385
+ * The identity headers Command Code's own client sends.
386
+ *
387
+ * `x-cli-environment` is `production`, not `cli` — that is the value the client
388
+ * sends, and the pair is what identifies the surface to the gateway.
389
+ *
390
+ * `x-project-slug` and `x-taste-learning` were simply absent. Both are
391
+ * attribution fields the client always sends; the slug is derived from the
392
+ * working directory the same way the client derives it.
393
+ *
394
+ * `x-session-id` is sent only when a session exists. The client omits it rather
395
+ * than inventing one, and a value minted per request would attribute every
396
+ * call to a different session.
397
+ */
398
+ export async function headers(sessionId: string, token: string): Promise<Record<string, string>> {
399
+ return {
400
+ "content-type": "application/json",
401
+ accept: "text/event-stream",
402
+ authorization: `Bearer ${token}`,
403
+ "x-command-code-version": getCommandCodeVersion(),
404
+ "x-cli-environment": "production",
405
+ "x-taste-learning": "true",
406
+ "x-project-slug": "cartethyia",
407
+ "user-agent": "cli",
408
+ ...(sessionId.length > 0 ? { "x-session-id": sessionId } : {}),
409
+ };
410
+ }
411
+
412
+
413
+ type StreamState = { toolIndexById: Map<string, number>; nextToolIndex: number; finishReason: string | undefined; usage: Record<string, unknown> | undefined; think: MimoThinkSplitter };
414
+
415
+ export function ccMapFinishReason(reason: string): CanonicalStopReason {
416
+ return reason === "length" ? "length" : reason === "tool_calls" ? "tool_use" : reason === "content_filter" ? "content_filter" : "stop";
417
+ }
418
+
419
+ export function transformLine(line: string, state: StreamState, seqBase: number): CanonicalEvent[] {
420
+ let event: Record<string, unknown>;
421
+ try {
422
+ event = JSON.parse(line) as Record<string, unknown>;
423
+ } catch {
424
+ return [];
425
+ }
426
+ const type = readString(event, "type");
427
+ if (!type) return [];
428
+ if (type === "reasoning-delta") {
429
+ const text = readString(event, "text") || readString(event, "delta");
430
+ return text ? [{ type: "content_delta", sequence_number: seqBase, content: { kind: "reasoning", payload: null, summary: text } } as CanonicalEvent] : [];
431
+ }
432
+ if (type === "text-delta") {
433
+ const text = readString(event, "text") || readString(event, "delta");
434
+ if (!text) return [];
435
+ const split = state.think.push(text);
436
+ const events: CanonicalEvent[] = [];
437
+ if (split.reasoning) events.push({ type: "content_delta", sequence_number: seqBase, content: { kind: "reasoning", payload: null, summary: split.reasoning } } as CanonicalEvent);
438
+ if (split.text) events.push({ type: "content_delta", sequence_number: seqBase, content: { kind: "text", text: split.text } } as CanonicalEvent);
439
+ return events;
440
+ }
441
+ if (type === "tool-input-start") {
442
+ const id = readString(event, "id") || readString(event, "toolCallId");
443
+ if (!id || state.toolIndexById.has(id)) return [];
444
+ state.toolIndexById.set(id, state.nextToolIndex++);
445
+ return [{ type: "tool_call_delta", sequence_number: seqBase, call_id: id, name: readString(event, "toolName") ?? "", arguments_delta: "" } as CanonicalEvent];
446
+ }
447
+ if (type === "tool-input-delta") {
448
+ const id = readString(event, "id") || readString(event, "toolCallId");
449
+ const delta = readString(event, "delta") || readString(event, "inputTextDelta");
450
+ if (!id || !delta || !state.toolIndexById.has(id)) return [];
451
+ return [{ type: "tool_call_delta", sequence_number: seqBase, call_id: id, arguments_delta: delta } as CanonicalEvent];
452
+ }
453
+ if (type === "tool-call") {
454
+ const id = readString(event, "toolCallId");
455
+ if (!id || state.toolIndexById.has(id)) return [];
456
+ state.toolIndexById.set(id, state.nextToolIndex++);
457
+ const input = typeof event["input"] === "string" ? (event["input"] as string) : JSON.stringify(event["input"] ?? {});
458
+ return [
459
+ { type: "tool_call_delta", sequence_number: seqBase, call_id: id, name: readString(event, "toolName") ?? "", arguments_delta: "" } as CanonicalEvent,
460
+ { type: "tool_call_delta", sequence_number: seqBase + 1, call_id: id, arguments_delta: input } as CanonicalEvent,
461
+ ];
462
+ }
463
+ if (type === "finish-step") {
464
+ const reason = readString(event, "finishReason");
465
+ if (reason) state.finishReason = reason;
466
+ if (typeof event["usage"] === "object" && event["usage"] !== null && !Array.isArray(event["usage"])) state.usage = event["usage"] as Record<string, unknown>;
467
+ return [];
468
+ }
469
+ if (type === "finish") {
470
+ const reason = state.finishReason ?? readString(event, "finishReason") ?? "stop";
471
+ const canonicalReason = ccMapFinishReason(reason);
472
+ const events: CanonicalEvent[] = [
473
+ { type: "terminal", sequence_number: seqBase, state: "complete", stop_reason: canonicalReason, provider_stop_reason: reason } as CanonicalEvent,
474
+ ];
475
+ if (state.usage) {
476
+ const prompt = readNumber(state.usage, "promptTokens") ?? readNumber(state.usage, "inputTokens") ?? 0;
477
+ const completion = readNumber(state.usage, "completionTokens") ?? readNumber(state.usage, "outputTokens") ?? 0;
478
+ const total = readNumber(state.usage, "totalTokens") ?? prompt + completion;
479
+ const cached = readNumber(state.usage, "cachedTokens") ?? readNumber(state.usage, "cacheReadTokens") ?? 0;
480
+ const usageRecord = usageFromProvider({
481
+ input_tokens: prompt,
482
+ output_tokens: completion,
483
+ total_tokens: total,
484
+ cached_tokens: cached,
485
+ cache_creation_input_tokens: readNumber(state.usage, "cacheWriteTokens") ?? undefined,
486
+ } as unknown as Record<string, unknown>);
487
+ // Append usage to terminal
488
+ (events[0] as unknown as Record<string, unknown>)["usage"] = usageRecord;
489
+ }
490
+ return events;
491
+ }
492
+ if (type === "error") {
493
+ const raw = event["error"] ?? event["message"] ?? event;
494
+ const errorObject = isRecord(raw) ? raw : event;
495
+ const identifier = upstreamErrorIdentifier(raw) ?? upstreamErrorIdentifier(event);
496
+ const providerStatus = [
497
+ errorObject["status"],
498
+ errorObject["statusCode"],
499
+ errorObject["code"],
500
+ event["status"],
501
+ event["statusCode"],
502
+ event["code"],
503
+ ].find(
504
+ (value): value is number =>
505
+ typeof value === "number" &&
506
+ Number.isFinite(value) &&
507
+ value >= 400 &&
508
+ value < 600,
509
+ );
510
+ const classification = classifyUpstreamError(providerStatus, identifier);
511
+ const message =
512
+ extractUpstreamMessage(raw) ||
513
+ extractUpstreamMessage(event) ||
514
+ "Command Code stream error";
515
+ throw new GatewayError(
516
+ classification.code,
517
+ classification.status,
518
+ message.slice(0, 500),
519
+ {
520
+ ...(providerStatus === undefined ? {} : { providerStatus }),
521
+ ...(identifier ? { providerCode: identifier } : {}),
522
+ ...(classification.credentialEvidence ? { credentialEvidence: true } : {}),
523
+ ...(classification.rateLimitScope
524
+ ? { rateLimitScope: classification.rateLimitScope }
525
+ : {}),
526
+ },
527
+ classification.origin,
528
+ );
529
+ }
530
+ return [];
531
+ }
532
+
533
+ /** NDJSON transform — beta-style simple loop + signal-aware read for abort/timeout propagation. */
534
+ export async function* transformNdjson(body: ReadableStream<Uint8Array>, signal: AbortSignal): AsyncIterable<CanonicalEvent> {
535
+ const reader = body.getReader();
536
+ const decoder = new TextDecoder();
537
+ const state: StreamState = { toolIndexById: new Map(), nextToolIndex: 0, finishReason: undefined, usage: undefined, think: new MimoThinkSplitter() };
538
+ let buffer = "";
539
+ let hasTerminal = false;
540
+ let seq = 1;
541
+ // initial response_start
542
+ yield { type: "response_start", sequence_number: seq++, model: "commandcode" } as CanonicalEvent;
543
+
544
+ const readWithAbort = (): Promise<{ done: boolean; value?: Uint8Array }> => {
545
+ if (signal.aborted) throw new GatewayError("transport_closed", 499, "Command Code stream aborted");
546
+ const { promise, resolve, reject } = Promise.withResolvers<{ done: boolean; value?: Uint8Array }>() as unknown as { promise: Promise<{ done: boolean; value?: Uint8Array }>; resolve: (v: unknown) => void; reject: (e: unknown) => void };
547
+ const onAbort = (): void => {
548
+ if (signal.aborted) reject(new GatewayError("transport_closed", 499, "Command Code stream aborted"));
549
+ else reject(new GatewayError("platform_unavailable", 502, "Command Code stream error", {}, "upstream"));
550
+ };
551
+ signal.addEventListener("abort", onAbort, { once: true });
552
+ void reader.read().then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
553
+ return promise;
554
+ };
555
+
556
+ try {
557
+ while (true) {
558
+ const { done, value } = await readWithAbort();
559
+ if (done) break;
560
+ buffer += decoder.decode(value, { stream: true });
561
+ let nl = buffer.indexOf("\n");
562
+ while (nl !== -1) {
563
+ const line = buffer.slice(0, nl).trim();
564
+ buffer = buffer.slice(nl + 1);
565
+ if (line) {
566
+ let evs: CanonicalEvent[] = [];
567
+ try {
568
+ evs = transformLine(line, state, seq);
569
+ } catch (e) {
570
+ throw e;
571
+ }
572
+ for (const ev of evs) {
573
+ // Strictly increasing per line, in emission order: the Responses
574
+ // surface throws on any non-monotonic sequence mid-stream, after
575
+ // partial bytes are already flushed. No special-casing for
576
+ // dual-event lines — order is order.
577
+ (ev as unknown as Record<string, unknown>)["sequence_number"] = seq++;
578
+ if (ev.type === "terminal") hasTerminal = true;
579
+ yield ev;
580
+ }
581
+ }
582
+ nl = buffer.indexOf("\n");
583
+ }
584
+ }
585
+ buffer += decoder.decode();
586
+ const tail = buffer.trim();
587
+ if (tail) {
588
+ for (const ev of transformLine(tail, state, seq)) {
589
+ if (ev.type === "terminal") hasTerminal = true;
590
+ (ev as unknown as Record<string, unknown>)["sequence_number"] = seq++;
591
+ yield ev;
592
+ }
593
+ }
594
+ const rest = state.think.flush();
595
+ if (rest.reasoning) yield { type: "content_delta", sequence_number: seq++, content: { kind: "reasoning", payload: null, summary: rest.reasoning } } as CanonicalEvent;
596
+ if (rest.text) yield { type: "content_delta", sequence_number: seq++, content: { kind: "text", text: rest.text } } as CanonicalEvent;
597
+ if (!hasTerminal) {
598
+ // NDJSON ended with no terminal envelope: truncated, never complete.
599
+ yield { type: "terminal", sequence_number: seq++, state: "failed", stop_reason: ccMapFinishReason(state.finishReason ?? "stop"), provider_stop_reason: state.finishReason ?? "stop" } as CanonicalEvent;
600
+ }
601
+ } finally {
602
+ try {
603
+ reader.releaseLock?.();
604
+ } catch {
605
+ // Best-effort reader unlock during stream cleanup.
606
+ }
607
+ void reader.cancel().catch(() => {});
608
+ }
609
+ }
610
+
611
+ // CommandCode model catalog.
612
+
613
+
614
+
615
+ // ProviderAdapter — the Provider API serves three wires, so dispatch is the
616
+ // shared OpenAI-compatible adapter rather than one bespoke NDJSON reader.
617
+ //
618
+ // `/provider/v1` answers `/chat/completions`, `/responses` and `/messages`, and
619
+ // the model row states which one serves it. The bespoke `/alpha/generate`
620
+ // envelope is the CLI's own surface and stays reachable through
621
+ // `buildRequest` for callers that still speak it, while routing follows the
622
+ // wire each model row declares rather than forcing every model onto it.
623
+
624
+ interface CommandCodeAdapterOptions {
625
+ readonly fetch?: typeof fetch;
626
+ }
627
+
628
+ function commandCodeIdentityHeaders(_token: string): Record<string, string> {
629
+ return {
630
+ "x-command-code-version": getCommandCodeVersion(),
631
+ "x-cli-environment": "production",
632
+ "x-taste-learning": "true",
633
+ "x-project-slug": "cartethyia",
634
+ "user-agent": "cli",
635
+ };
636
+ }
637
+
638
+ function providerApiAdapter(options: CommandCodeAdapterOptions): ProviderAdapter {
639
+ return createApiKeyAdapter(
640
+ {
641
+ provider_id: COMMANDCODE_PROVIDER_ID,
642
+ base_url: COMMANDCODE_BASE_URL,
643
+ endpoint_paths_by_wire_family: {
644
+ chat: COMMANDCODE_CHAT_PATH,
645
+ responses: COMMANDCODE_RESPONSES_PATH,
646
+ messages: COMMANDCODE_MESSAGES_PATH,
647
+ },
648
+ buildExtraHeaders: async (context: ProviderDispatchContext) =>
649
+ commandCodeIdentityHeaders(await readCredentialSecret(context.credential, "Command Code bearer token is required")),
650
+ },
651
+ options.fetch,
652
+ );
653
+ }
654
+
655
+ class CommandCodeAdapter implements ProviderAdapter {
656
+ readonly provider_id = COMMANDCODE_PROVIDER_ID;
657
+ private readonly inner: ProviderAdapter;
658
+
659
+ constructor(options: CommandCodeAdapterOptions = {}) {
660
+ this.inner = providerApiAdapter(options);
661
+ }
662
+
663
+ dispatch(
664
+ request: CanonicalRequest,
665
+ candidate: ProviderDispatchTarget,
666
+ context: ProviderDispatchContext,
667
+ ): AsyncIterable<CanonicalEvent> {
668
+ return this.inner.dispatch(request, candidate, context);
669
+ }
670
+ }
671
+
672
+ export function createCommandCodeAdapter(options: CommandCodeAdapterOptions = {}): ProviderAdapter {
673
+ return new CommandCodeAdapter(options);
674
+ }