cartethyia 2.4.6 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (302) hide show
  1. package/README.md +45 -13
  2. package/dist/dashboard/assets/BannedPage-9igfctfZ.js +1 -0
  3. package/dist/dashboard/assets/BannedPage-9igfctfZ.js.gz +0 -0
  4. package/dist/dashboard/assets/{CliToolDetailPage-Bcy150Jo.js → CliToolDetailPage-ZRr2K2sF.js} +1 -1
  5. package/dist/dashboard/assets/CliToolDetailPage-ZRr2K2sF.js.gz +0 -0
  6. package/dist/dashboard/assets/{CliToolsPage-DyNXefph.js → CliToolsPage-D3xqZbN-.js} +1 -1
  7. package/dist/dashboard/assets/CliToolsPage-D3xqZbN-.js.gz +0 -0
  8. package/dist/dashboard/assets/CombosPage-CVnQPBBz.js +1 -0
  9. package/dist/dashboard/assets/CombosPage-CVnQPBBz.js.gz +0 -0
  10. package/dist/dashboard/assets/{ConsoleLogPage-CATpAEOz.js → ConsoleLogPage-u6W1UXSc.js} +1 -1
  11. package/dist/dashboard/assets/ConsoleLogPage-u6W1UXSc.js.gz +0 -0
  12. package/dist/dashboard/assets/{CustomizationPage-D6jEU7nL.js → CustomizationPage-CTTpCb25.js} +1 -1
  13. package/dist/dashboard/assets/CustomizationPage-CTTpCb25.js.gz +0 -0
  14. package/dist/dashboard/assets/{HealthEventsModal-CZkpn0a7.js → HealthEventsModal-C5XpWlvy.js} +1 -1
  15. package/dist/dashboard/assets/HealthEventsModal-C5XpWlvy.js.gz +0 -0
  16. package/dist/dashboard/assets/{LoginPage-BJlMVN4U.js → LoginPage-DHoB3Agn.js} +1 -1
  17. package/dist/dashboard/assets/LoginPage-DHoB3Agn.js.gz +0 -0
  18. package/dist/dashboard/assets/{ModelPicker-Br3CXEau.js → ModelPicker-oQ-SDXp8.js} +1 -1
  19. package/dist/dashboard/assets/ModelPicker-oQ-SDXp8.js.gz +0 -0
  20. package/dist/dashboard/assets/OverviewPage-BrY4SgIt.js +1 -0
  21. package/dist/dashboard/assets/OverviewPage-BrY4SgIt.js.gz +0 -0
  22. package/dist/dashboard/assets/ProviderDetailPage-D9VSt7T_.js +3 -0
  23. package/dist/dashboard/assets/ProviderDetailPage-D9VSt7T_.js.gz +0 -0
  24. package/dist/dashboard/assets/ProviderIcon-CmfzxpVM.js +1 -0
  25. package/dist/dashboard/assets/ProviderIcon-CmfzxpVM.js.gz +0 -0
  26. package/dist/dashboard/assets/ProvidersPage-Df77V5I5.js +1 -0
  27. package/dist/dashboard/assets/ProvidersPage-Df77V5I5.js.gz +0 -0
  28. package/dist/dashboard/assets/ProxyPage-CDfxP7AC.js +7 -0
  29. package/dist/dashboard/assets/ProxyPage-CDfxP7AC.js.gz +0 -0
  30. package/dist/dashboard/assets/QuotaPage-CY4o2t4p.js +1 -0
  31. package/dist/dashboard/assets/QuotaPage-CY4o2t4p.js.gz +0 -0
  32. package/dist/dashboard/assets/{SettingsPage-BHW4Zt06.js → SettingsPage-CvjZxHE4.js} +1 -1
  33. package/dist/dashboard/assets/SettingsPage-CvjZxHE4.js.gz +0 -0
  34. package/dist/dashboard/assets/{SetupPage-VOYC_lIa.js → SetupPage-D3nza7LH.js} +1 -1
  35. package/dist/dashboard/assets/SetupPage-D3nza7LH.js.gz +0 -0
  36. package/dist/dashboard/assets/SortableList-Dtt12WT1.js +1 -0
  37. package/dist/dashboard/assets/SortableList-Dtt12WT1.js.gz +0 -0
  38. package/dist/dashboard/assets/{StudioPage-BNIDLiU6.js → StudioPage-CbK3hXvU.js} +4 -4
  39. package/dist/dashboard/assets/StudioPage-CbK3hXvU.js.gz +0 -0
  40. package/dist/dashboard/assets/UsagePage-BQlWbWg2.js +56 -0
  41. package/dist/dashboard/assets/UsagePage-BQlWbWg2.js.gz +0 -0
  42. package/dist/dashboard/assets/{api-keys-BETfaMYZ.js → api-keys-BmDbsior.js} +1 -1
  43. package/dist/dashboard/assets/api-keys-BmDbsior.js.gz +0 -0
  44. package/dist/dashboard/assets/app-BbpSarVV.css +2 -0
  45. package/dist/dashboard/assets/app-BbpSarVV.css.gz +0 -0
  46. package/dist/dashboard/assets/assert-BHfaei-X.js +1 -0
  47. package/dist/dashboard/assets/assert-BHfaei-X.js.gz +0 -0
  48. package/dist/dashboard/assets/{badge-BTyGk_DL.js → badge-DpXT4Ixt.js} +1 -1
  49. package/dist/dashboard/assets/badge-DpXT4Ixt.js.gz +0 -0
  50. package/dist/dashboard/assets/{banner-bujTWYM4.js → banner-CSAAWLJv.js} +1 -1
  51. package/dist/dashboard/assets/banner-CSAAWLJv.js.gz +0 -0
  52. package/dist/dashboard/assets/{card-B0Bnx5CA.js → card-DEhRXXw4.js} +1 -1
  53. package/dist/dashboard/assets/card-DEhRXXw4.js.gz +0 -0
  54. package/dist/dashboard/assets/{cli-tools-DE2ug812.js → cli-tools-B0wBq-RL.js} +1 -1
  55. package/dist/dashboard/assets/cli-tools-B0wBq-RL.js.gz +0 -0
  56. package/dist/dashboard/assets/{clipboard-button-R_rArH8S.js → clipboard-button-DOo6EU8O.js} +1 -1
  57. package/dist/dashboard/assets/clipboard-button-DOo6EU8O.js.gz +0 -0
  58. package/dist/dashboard/assets/{dialog-BWIP_EvW.js → dialog-BvQeBMfP.js} +1 -1
  59. package/dist/dashboard/assets/dialog-BvQeBMfP.js.gz +0 -0
  60. package/dist/dashboard/assets/{drawer-BKcgVugF.js → drawer-CMwPXwQB.js} +1 -1
  61. package/dist/dashboard/assets/drawer-CMwPXwQB.js.gz +0 -0
  62. package/dist/dashboard/assets/{entry-CcWkGR4a.js → entry-D4O2229X.js} +1 -1
  63. package/dist/dashboard/assets/{entry-CcWkGR4a.js.gz → entry-D4O2229X.js.gz} +0 -0
  64. package/dist/dashboard/assets/{entry-kTiTFrvh.js → entry-DKvr5Q9K.js} +1 -1
  65. package/dist/dashboard/assets/entry-DKvr5Q9K.js.gz +0 -0
  66. package/dist/dashboard/assets/entry-FQCejoDY.js +4 -0
  67. package/dist/dashboard/assets/entry-FQCejoDY.js.gz +0 -0
  68. package/dist/dashboard/assets/{github-badge-Booc5mNe.js → github-badge-zliLvBwr.js} +1 -1
  69. package/dist/dashboard/assets/github-badge-zliLvBwr.js.gz +0 -0
  70. package/dist/dashboard/assets/{index-D70pChfn.js → index-CXm3FIyt.js} +2 -2
  71. package/dist/dashboard/assets/index-CXm3FIyt.js.gz +0 -0
  72. package/dist/dashboard/assets/{inline-D1TCqM2D.js → inline-D1IlZZ8H.js} +1 -1
  73. package/dist/dashboard/assets/inline-D1IlZZ8H.js.gz +0 -0
  74. package/dist/dashboard/assets/{input-B9oyU93y.js → input-BpVZdrbc.js} +1 -1
  75. package/dist/dashboard/assets/input-BpVZdrbc.js.gz +0 -0
  76. package/dist/dashboard/assets/{layout-BArzXirQ.js → layout-BioLW7gN.js} +1 -1
  77. package/dist/dashboard/assets/layout-BioLW7gN.js.gz +0 -0
  78. package/dist/dashboard/assets/{list-row-BVZzaoHF.js → list-row-CwVcGAIc.js} +1 -1
  79. package/dist/dashboard/assets/list-row-CwVcGAIc.js.gz +0 -0
  80. package/dist/dashboard/assets/{live-EmuIayqp.js → live-yfEJFF9T.js} +1 -1
  81. package/dist/dashboard/assets/live-yfEJFF9T.js.gz +0 -0
  82. package/dist/dashboard/assets/{model-bans-CSPQ9xB0.js → model-bans-CT-TxSNX.js} +1 -1
  83. package/dist/dashboard/assets/model-bans-CT-TxSNX.js.gz +0 -0
  84. package/dist/dashboard/assets/providers/cursor.webp +0 -0
  85. package/dist/dashboard/assets/providers/trae.webp +0 -0
  86. package/dist/dashboard/assets/{routing-BExgxxBU.js → routing-Cs6jl49L.js} +1 -1
  87. package/dist/dashboard/assets/routing-Cs6jl49L.js.gz +0 -0
  88. package/dist/dashboard/assets/select-C0Rer3gF.js +41 -0
  89. package/dist/dashboard/assets/select-C0Rer3gF.js.gz +0 -0
  90. package/dist/dashboard/assets/settings-CfcTcOyU.js +1 -0
  91. package/dist/dashboard/assets/settings-CfcTcOyU.js.gz +0 -0
  92. package/dist/dashboard/assets/{stack-Ca5HxI5i.js → stack-C9_uUjaA.js} +1 -1
  93. package/dist/dashboard/assets/stack-C9_uUjaA.js.gz +0 -0
  94. package/dist/dashboard/assets/{state-CzUPfLXo.js → state-DA0B95UQ.js} +1 -1
  95. package/dist/dashboard/assets/state-DA0B95UQ.js.gz +0 -0
  96. package/dist/dashboard/assets/{switch-DOUIky_i.js → switch-Cittxy-x.js} +1 -1
  97. package/dist/dashboard/assets/switch-Cittxy-x.js.gz +0 -0
  98. package/dist/dashboard/assets/{toast-C76WrMhc.js → toast-CNt_jzO4.js} +1 -1
  99. package/dist/dashboard/assets/toast-CNt_jzO4.js.gz +0 -0
  100. package/dist/dashboard/assets/{useMutation-D87FZwH0.js → useMutation-BQKMcJ1H.js} +1 -1
  101. package/dist/dashboard/assets/useMutation-BQKMcJ1H.js.gz +0 -0
  102. package/dist/dashboard/index.html +1 -1
  103. package/dist/dashboard/index.html.gz +0 -0
  104. package/dist/dashboard/precompressed-assets.json +51 -52
  105. package/migrations/full-postgres/0015_add_payload_stages.sql +18 -0
  106. package/migrations/full-postgres/0016_add_share_link_slug.sql +20 -0
  107. package/migrations/full-postgres/0017_add_models_pro_only.sql +18 -0
  108. package/migrations/full-postgres/0018_add_accounts_quota_plan.sql +18 -0
  109. package/migrations/full-postgres/0019_add_models_free_tier.sql +15 -0
  110. package/migrations/lite-sqlite3/0015_add_payload_stages.sql +18 -0
  111. package/migrations/lite-sqlite3/0016_add_share_link_slug.sql +20 -0
  112. package/migrations/lite-sqlite3/0017_add_models_pro_only.sql +18 -0
  113. package/migrations/lite-sqlite3/0018_add_accounts_quota_plan.sql +18 -0
  114. package/migrations/lite-sqlite3/0019_add_models_free_tier.sql +15 -0
  115. package/package.json +3 -2
  116. package/scripts/cli/command/console-menu.ts +30 -11
  117. package/scripts/cli/command/start.ts +77 -13
  118. package/scripts/cli/command/update.ts +1 -1
  119. package/scripts/cli/gateway/instance-lock.ts +105 -0
  120. package/scripts/cli/gateway/spawn.ts +173 -101
  121. package/scripts/cli/ui/background.ts +110 -49
  122. package/src/boot/app.ts +20 -6
  123. package/src/boot/dependencies.ts +19 -0
  124. package/src/boot/elysia-typebox-bridge.ts +37 -0
  125. package/src/boot/lifecycle.ts +2 -0
  126. package/src/config/cooldowns.ts +138 -138
  127. package/src/config/providers.ts +5 -5
  128. package/src/config/runtime.ts +19 -3
  129. package/src/config/spec.ts +9 -0
  130. package/src/console/api-keys/contracts.ts +414 -391
  131. package/src/console/api-keys/routes.ts +880 -870
  132. package/src/console/auth/account-reset-store.ts +14 -0
  133. package/src/console/auth/account-reset.ts +3 -2
  134. package/src/console/auth/setup-service.ts +6 -3
  135. package/src/console/domain-registration.ts +9 -2
  136. package/src/console/observability/contracts.ts +475 -455
  137. package/src/console/observability/store.ts +1015 -952
  138. package/src/console/providers/catalog/contracts.ts +31 -0
  139. package/src/console/providers/catalog/provider-operations.ts +8 -0
  140. package/src/console/providers/catalog/store.ts +1532 -1525
  141. package/src/console/providers/oauth/callback-listener.ts +18 -3
  142. package/src/console/providers/oauth/routes.ts +38 -15
  143. package/src/console/quota/refresh.ts +19 -0
  144. package/src/console/updates/routes.ts +162 -4
  145. package/src/main.ts +3 -0
  146. package/src/network/http2-bidi.ts +85 -0
  147. package/src/network/outbound-fetch.ts +1 -26
  148. package/src/network/pool/agent.ts +478 -460
  149. package/src/network/pool/resolver.ts +1104 -544
  150. package/src/network/pool-health-machine.ts +12 -5
  151. package/src/observability/payload-capture.ts +344 -324
  152. package/src/persistence/db-pg.ts +9 -3
  153. package/src/persistence/db-sqlite.ts +497 -495
  154. package/src/persistence/health-event-flush.ts +137 -0
  155. package/src/persistence/migrate.ts +181 -129
  156. package/src/persistence/schema.ts +1360 -1295
  157. package/src/persistence/settings-revision.ts +25 -0
  158. package/src/persistence/shared-cache.ts +217 -0
  159. package/src/persistence/stores/share-store.ts +556 -528
  160. package/src/persistence/usage-flush.ts +61 -1
  161. package/src/protocol/canonical-model.ts +23 -1
  162. package/src/protocol/response/chat.ts +143 -10
  163. package/src/protocol/response/omp-tool-call-markup.ts +221 -0
  164. package/src/providers/default-registry.ts +173 -1
  165. package/src/providers/discovery/openai-model-discovery.ts +39 -3
  166. package/src/providers/discovery/openrouter-free-roster.ts +98 -0
  167. package/src/providers/discovery/probing-service.ts +1022 -1001
  168. package/src/providers/integrations/buddy/buddy-catalog-shared.ts +39 -0
  169. package/src/providers/integrations/buddy/buddy-chat-shared.ts +913 -914
  170. package/src/providers/integrations/buddy/buddy-conversation-headers.ts +18 -5
  171. package/src/providers/integrations/buddy/codebuddy/cn-provider.ts +4 -0
  172. package/src/providers/integrations/buddy/codebuddy/provider.ts +180 -175
  173. package/src/providers/integrations/buddy/codebuddy/shared.ts +15 -6
  174. package/src/providers/integrations/buddy/workbuddy/provider.ts +206 -204
  175. package/src/providers/integrations/buddy/workbuddy/shared.ts +3 -3
  176. package/src/providers/integrations/claude/claude.ts +606 -582
  177. package/src/providers/integrations/cline/cline-quota.ts +18 -16
  178. package/src/providers/integrations/cline/cline.ts +539 -468
  179. package/src/providers/integrations/commandcode/commandcode.ts +675 -541
  180. package/src/providers/integrations/commandcode/discovery.ts +116 -0
  181. package/src/providers/integrations/commandcode/quota.ts +160 -0
  182. package/src/providers/integrations/cursor/cursor-auth.ts +418 -0
  183. package/src/providers/integrations/cursor/cursor-catalog.ts +368 -0
  184. package/src/providers/integrations/cursor/cursor-http2.ts +300 -0
  185. package/src/providers/integrations/cursor/cursor-identity.ts +92 -0
  186. package/src/providers/integrations/cursor/cursor-request.ts +471 -0
  187. package/src/providers/integrations/cursor/cursor-session-manager.ts +281 -0
  188. package/src/providers/integrations/cursor/cursor-shared.ts +108 -0
  189. package/src/providers/integrations/cursor/cursor.ts +960 -0
  190. package/src/providers/integrations/cursor/protocol/framing.ts +129 -0
  191. package/src/providers/integrations/cursor/protocol/messages.ts +2355 -0
  192. package/src/providers/integrations/cursor/protocol/struct.ts +305 -0
  193. package/src/providers/integrations/github/github.ts +4 -4
  194. package/src/providers/integrations/hermes.ts +79 -8
  195. package/src/providers/integrations/kilo/kilo-discovery.ts +10 -1
  196. package/src/providers/integrations/kilo/kilo.ts +153 -146
  197. package/src/providers/integrations/opencode/provider.ts +532 -538
  198. package/src/providers/integrations/openrouter/provider.ts +139 -281
  199. package/src/providers/integrations/qoder/qoder-catalog.ts +450 -0
  200. package/src/providers/integrations/qoder/qoder-oauth.ts +310 -257
  201. package/src/providers/integrations/qoder/qoder-realm.ts +106 -0
  202. package/src/providers/integrations/qoder/qoder-virtual.ts +77 -0
  203. package/src/providers/integrations/qoder/qoder.ts +865 -730
  204. package/src/providers/integrations/trae/trae-catalog.ts +190 -0
  205. package/src/providers/integrations/trae/trae-headers.ts +149 -0
  206. package/src/providers/integrations/trae/trae-oauth.ts +773 -0
  207. package/src/providers/integrations/trae/trae-protocol.ts +400 -0
  208. package/src/providers/integrations/trae/trae-realm.ts +220 -0
  209. package/src/providers/integrations/trae/trae.ts +458 -0
  210. package/src/providers/operations/account-health-service.ts +107 -10
  211. package/src/providers/operations/client-versions.ts +133 -6
  212. package/src/providers/operations/provider-catalog-seeder.ts +95 -86
  213. package/src/providers/operations/provider-credential-service.ts +46 -7
  214. package/src/providers/provider-contracts.ts +76 -0
  215. package/src/providers/provider-metadata.ts +78 -6
  216. package/src/providers/provider-model-definition.ts +373 -349
  217. package/src/security/api-key-auth.ts +126 -8
  218. package/src/transport/contracts.ts +3 -0
  219. package/src/transport/dispatch/attempt-finalize.ts +32 -1
  220. package/src/transport/dispatch/attempt-loop.ts +530 -515
  221. package/src/transport/dispatch/generation.ts +88 -21
  222. package/src/transport/dispatch/leases.ts +99 -2
  223. package/src/transport/dispatch/proxy-request.ts +60 -3
  224. package/src/transport/dispatch/streaming/finalize.ts +16 -1
  225. package/src/transport/dispatch/streaming/stream.ts +22 -2
  226. package/src/transport/dispatch/upstream.ts +19 -1
  227. package/src/transport/guards/auth-guard.ts +26 -1
  228. package/src/transport/guards/body-policy.ts +5 -4
  229. package/src/transport/request/preparer.ts +103 -0
  230. package/src/transport/request/state.ts +14 -0
  231. package/src/transport/routing/plan-gate.ts +45 -0
  232. package/src/transport/routing/route-catalog.ts +799 -777
  233. package/src/transport/routing/route-model.ts +52 -1
  234. package/src/transport/routing/router.ts +51 -0
  235. package/dist/dashboard/assets/BannedPage-QhvbJB9o.js +0 -1
  236. package/dist/dashboard/assets/BannedPage-QhvbJB9o.js.gz +0 -0
  237. package/dist/dashboard/assets/CliToolDetailPage-Bcy150Jo.js.gz +0 -0
  238. package/dist/dashboard/assets/CliToolsPage-DyNXefph.js.gz +0 -0
  239. package/dist/dashboard/assets/CombosPage-Cak0ljnO.js +0 -1
  240. package/dist/dashboard/assets/CombosPage-Cak0ljnO.js.gz +0 -0
  241. package/dist/dashboard/assets/ConsoleLogPage-CATpAEOz.js.gz +0 -0
  242. package/dist/dashboard/assets/CustomizationPage-D6jEU7nL.js.gz +0 -0
  243. package/dist/dashboard/assets/HealthEventsModal-CZkpn0a7.js.gz +0 -0
  244. package/dist/dashboard/assets/LoginPage-BJlMVN4U.js.gz +0 -0
  245. package/dist/dashboard/assets/ModelPicker-Br3CXEau.js.gz +0 -0
  246. package/dist/dashboard/assets/OverviewPage-CQxXbo2g.js +0 -1
  247. package/dist/dashboard/assets/OverviewPage-CQxXbo2g.js.gz +0 -0
  248. package/dist/dashboard/assets/ProviderDetailPage--0RBNh99.js +0 -3
  249. package/dist/dashboard/assets/ProviderDetailPage--0RBNh99.js.gz +0 -0
  250. package/dist/dashboard/assets/ProviderIcon-paOCq8I0.js +0 -1
  251. package/dist/dashboard/assets/ProviderIcon-paOCq8I0.js.gz +0 -0
  252. package/dist/dashboard/assets/ProvidersPage-1M-C3mbu.js +0 -1
  253. package/dist/dashboard/assets/ProvidersPage-1M-C3mbu.js.gz +0 -0
  254. package/dist/dashboard/assets/ProxyPage-CXiumA53.js +0 -7
  255. package/dist/dashboard/assets/ProxyPage-CXiumA53.js.gz +0 -0
  256. package/dist/dashboard/assets/QuotaPage-BGDIfIYP.js +0 -1
  257. package/dist/dashboard/assets/QuotaPage-BGDIfIYP.js.gz +0 -0
  258. package/dist/dashboard/assets/SettingsPage-BHW4Zt06.js.gz +0 -0
  259. package/dist/dashboard/assets/SetupPage-VOYC_lIa.js.gz +0 -0
  260. package/dist/dashboard/assets/SortableList-DpOTnGuH.js +0 -1
  261. package/dist/dashboard/assets/SortableList-DpOTnGuH.js.gz +0 -0
  262. package/dist/dashboard/assets/StudioPage-BNIDLiU6.js.gz +0 -0
  263. package/dist/dashboard/assets/UsagePage-BAFaSDQV.js +0 -56
  264. package/dist/dashboard/assets/UsagePage-BAFaSDQV.js.gz +0 -0
  265. package/dist/dashboard/assets/api-keys-BETfaMYZ.js.gz +0 -0
  266. package/dist/dashboard/assets/app-BLCvGdzb.css +0 -2
  267. package/dist/dashboard/assets/app-BLCvGdzb.css.gz +0 -0
  268. package/dist/dashboard/assets/assert-7J6_LVD3.js +0 -1
  269. package/dist/dashboard/assets/assert-7J6_LVD3.js.gz +0 -0
  270. package/dist/dashboard/assets/badge-BTyGk_DL.js.gz +0 -0
  271. package/dist/dashboard/assets/banner-bujTWYM4.js.gz +0 -0
  272. package/dist/dashboard/assets/card-B0Bnx5CA.js.gz +0 -0
  273. package/dist/dashboard/assets/cli-tools-DE2ug812.js.gz +0 -0
  274. package/dist/dashboard/assets/clipboard-button-R_rArH8S.js.gz +0 -0
  275. package/dist/dashboard/assets/dialog-BWIP_EvW.js.gz +0 -0
  276. package/dist/dashboard/assets/drawer-BKcgVugF.js.gz +0 -0
  277. package/dist/dashboard/assets/entry-7dpgvpJ3.js +0 -4
  278. package/dist/dashboard/assets/entry-7dpgvpJ3.js.gz +0 -0
  279. package/dist/dashboard/assets/entry-kTiTFrvh.js.gz +0 -0
  280. package/dist/dashboard/assets/github-badge-Booc5mNe.js.gz +0 -0
  281. package/dist/dashboard/assets/index-D70pChfn.js.gz +0 -0
  282. package/dist/dashboard/assets/inline-D1TCqM2D.js.gz +0 -0
  283. package/dist/dashboard/assets/input-B9oyU93y.js.gz +0 -0
  284. package/dist/dashboard/assets/layout-BArzXirQ.js.gz +0 -0
  285. package/dist/dashboard/assets/list-row-BVZzaoHF.js.gz +0 -0
  286. package/dist/dashboard/assets/live-EmuIayqp.js.gz +0 -0
  287. package/dist/dashboard/assets/model-bans-CSPQ9xB0.js.gz +0 -0
  288. package/dist/dashboard/assets/routing-BExgxxBU.js.gz +0 -0
  289. package/dist/dashboard/assets/select-C9mMoEpJ.js +0 -41
  290. package/dist/dashboard/assets/select-C9mMoEpJ.js.gz +0 -0
  291. package/dist/dashboard/assets/settings-C4_Gn_wq.js +0 -1
  292. package/dist/dashboard/assets/settings-C4_Gn_wq.js.gz +0 -0
  293. package/dist/dashboard/assets/sliders-horizontal-ClG7dBeJ.js +0 -1
  294. package/dist/dashboard/assets/sliders-horizontal-ClG7dBeJ.js.gz +0 -0
  295. package/dist/dashboard/assets/stack-Ca5HxI5i.js.gz +0 -0
  296. package/dist/dashboard/assets/state-CzUPfLXo.js.gz +0 -0
  297. package/dist/dashboard/assets/switch-DOUIky_i.js.gz +0 -0
  298. package/dist/dashboard/assets/toast-C76WrMhc.js.gz +0 -0
  299. package/dist/dashboard/assets/useMutation-D87FZwH0.js.gz +0 -0
  300. package/src/network/tls/bun-client-hello.ts +0 -112
  301. /package/dist/dashboard/assets/{app-Cjq7nrwu.js → app-C-Y4oZT0.js} +0 -0
  302. /package/dist/dashboard/assets/{app-Cjq7nrwu.js.gz → app-C-Y4oZT0.js.gz} +0 -0
@@ -1,730 +1,865 @@
1
- // Factory-blocked (Phase C4): PAT-to-jobToken session handshake, COSY
2
- // AES/RSA request signing, alphabet-scrambled binary body, enveloped SSE
3
- // frames — session/crypto protocol outside factory reach; stays bespoke.
4
- import { constants, createCipheriv, createHash, publicEncrypt, randomUUID } from "node:crypto";
5
- import { classifyUpstreamError, extractUpstreamMessage, mapUpstreamHttpError, upstreamErrorIdentifier } from "../../../transport/failure-policy";
6
- import { GatewayError } from "../../../protocol/gateway-error";
7
- import type { CanonicalEvent, CanonicalRequest, CanonicalStopReason, ContentPart } from "../../../protocol/canonical-model";
8
- import { toolResultParts } from "../../../protocol/canonical-model";
9
- import { decodeSseEvents } from "../../../protocol/sse-decoder";
10
- import { usageFromProvider, readReasoningText } from "../../provider-usage";
11
- import { readCredentialSecret, type ProviderDispatchTarget, type ProviderAdapter, type ProviderDispatchContext } from "../../provider-contracts";
12
- import type { ModelDefinition } from "../../provider-model-definition";
13
- import { parseQoderOAuthState } from "./qoder-oauth";
14
- import { defineModel } from "../../provider-model-definition";
15
- import { getQoderVersion } from "../../operations/client-versions";
16
- import { abortGatewayError, createUpstreamDeadlineLifecycle } from "../../operations/upstream-deadline";
17
- import { qoderMachineOs } from "../../operations/cli-platform";
18
-
19
- interface QoderModeProfile {
20
- readonly chatUrl: string;
21
- readonly businessProduct: string;
22
- readonly businessType: string;
23
- readonly businessVersion: string;
24
- readonly cosyScene: string;
25
- readonly mirrorTopLevelSystem: boolean;
26
- readonly sendBusinessHeaders: boolean;
27
- readonly sendModelSourceHeaders: boolean;
28
- readonly emptyAliyunUserType: boolean;
29
- }
30
-
31
- export const MODERN_PROFILE: QoderModeProfile = {
32
- chatUrl: "https://api2.qoder.sh/algo/api/v2/service/pro/sse/agent_chat_generation?FetchKeys=llm_model_result&AgentId=agent_common&Encode=1",
33
- businessProduct: "cli",
34
- businessType: "agent",
35
- businessVersion: "1.0.22",
36
- cosyScene: "assistant",
37
- mirrorTopLevelSystem: true,
38
- sendBusinessHeaders: true,
39
- sendModelSourceHeaders: true,
40
- emptyAliyunUserType: true,
41
- };
42
-
43
- const QODER_PROVIDER_ID = "qoder" as const;
44
-
45
- export const QODER_MODEL_CONFIGS: Record<
46
- string,
47
- { id: string; display_name: string; max_input_tokens: number; max_output_tokens?: number; is_vl: boolean; is_reasoning: boolean; source?: string }
48
- > = {
49
- auto: { id: "auto", display_name: "Auto", max_input_tokens: 180000, is_vl: true, is_reasoning: false },
50
- ultimate: { id: "ultimate", display_name: "Ultimate", max_input_tokens: 180000, is_vl: true, is_reasoning: true },
51
- performance: { id: "performance", display_name: "Performance", max_input_tokens: 272000, is_vl: true, is_reasoning: false },
52
- efficient: { id: "efficient", display_name: "Efficient", max_input_tokens: 180000, is_vl: true, is_reasoning: false },
53
- lite: { id: "lite", display_name: "Lite", max_input_tokens: 180000, is_vl: false, is_reasoning: true },
54
- qmodel: { id: "qmodel", display_name: "Qwen 3.6 Plus", max_input_tokens: 180000, is_vl: true, is_reasoning: false },
55
- qmodel_latest: { id: "qmodel_latest", display_name: "Qwen 3.7 Max", max_input_tokens: 1000000, is_vl: true, is_reasoning: false },
56
- qmodel_preview: { id: "qmodel_preview", display_name: "Qwen 3.8 Max", max_input_tokens: 1000000, is_vl: true, is_reasoning: false },
57
- dmodel: { id: "dmodel", display_name: "DeepSeek V4 Pro", max_input_tokens: 180000, is_vl: true, is_reasoning: true },
58
- dfmodel: { id: "dfmodel", display_name: "DeepSeek V4 Flash", max_input_tokens: 180000, is_vl: true, is_reasoning: true },
59
- gm51model: { id: "gm51model", display_name: "GLM 5.1", max_input_tokens: 180000, is_vl: true, is_reasoning: true },
60
- kmodel: { id: "kmodel", display_name: "Kimi K2.6", max_input_tokens: 256000, is_vl: true, is_reasoning: false },
61
- mmodel: { id: "mmodel", display_name: "MiniMax M2.7", max_input_tokens: 180000, is_vl: true, is_reasoning: false },
62
- kmodel_latest: { id: "kmodel_latest", display_name: "Kimi K2.7 Latest", max_input_tokens: 256000, is_vl: true, is_reasoning: false },
63
- };
64
-
65
- const QODER_APPCODE = "cosy";
66
- const QODER_SIG_SECRET = "d2FyLCB3YXIgbmV2ZXIgY2hhbmdlcw==";
67
- const QODER_JOB_TOKEN_URL = "https://center.qoder.sh/algo/api/v3/user/jobToken?Encode=1";
68
- const QODER_STANDARD_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
69
- const QODER_ALPHABET = "_doRTgHZBKcGVjlvpC,@aFSx#DPuNJme&i*MzLOEn)sUrthbf%Y^w.(kIQyXqWA!";
70
- const QODER_RSA_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
71
- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDA8iMH5c02LilrsERw9t6Pv5Nc
72
- 4k6Pz1EaDicBMpdpxKduSZu5OANqUq8er4GM95omAGIOPOh+Nx0spthYA2BqGz+l
73
- 6HRkPJ7S236FZz73In/KVuLnwI8JJ2CbuJap8kvheCCZpmAWpb/cPx/3Vr/J6I17
74
- XcW+ML9FoCI6AOvOzwIDAQAB
75
- -----END PUBLIC KEY-----`;
76
-
77
- export interface QoderAuth {
78
- userId: string;
79
- userName: string;
80
- userType: string;
81
- securityOauthToken: string;
82
- refreshToken: string;
83
- machineId: string;
84
- }
85
- interface QoderModelConfig {
86
- id: string;
87
- display_name: string;
88
- max_input_tokens: number;
89
- max_output_tokens?: number;
90
- is_vl: boolean;
91
- is_reasoning: boolean;
92
- source?: string;
93
- }
94
-
95
-
96
- function qoderMd5(value: string | Uint8Array): string {
97
- return createHash("md5").update(value).digest("hex");
98
- }
99
- function qoderPathSignature(url: string): string {
100
- const path = new URL(url).pathname;
101
- return path.startsWith("/algo") ? path.slice(5) : path;
102
- }
103
-
104
- const QODER_MACHINE_ID_TTL_MS = 60 * 60 * 1000;
105
- const QODER_MAX_MACHINE_IDS = 1_024;
106
- const qoderMachineIds = new Map<string, { id: string; expiresAt: number }>();
107
- /**
108
- * A PAT (`pt-...`) must be exchanged for a short-lived job token before it
109
- * can sign COSY requests. Device tokens (`dt-...`) from OAuth login and job
110
- * tokens (`jt-...`) are used directly.
111
- */
112
- export function isQoderPat(secret: string): boolean {
113
- return secret.startsWith("pt-");
114
- }
115
-
116
- /**
117
- * Stable per-account machine id for OAuth dispatches. Derived from the
118
- * account id (not minted per request) so pooled accounts keep one device
119
- * fingerprint across restarts instead of looking like a new device every
120
- * time, while staying distinct per account.
121
- */
122
- export function qoderMachineIdForAccount(accountId: string): string {
123
- const hex = createHash("sha256").update(`qoder-machine-v1:${accountId}`).digest("hex");
124
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
125
- }
126
-
127
- /**
128
- * Builds dispatch auth from an OAuth device token. The token is used
129
- * directly as the COSY identity's oauth token; the user id and machine id
130
- * come from the `auth_state` the login persisted. Fails closed with a
131
- * reconnect prompt when the identity is absent (e.g. an account created
132
- * before `auth_state` existed) instead of signing with a guessed id.
133
- */
134
- export function qoderOAuthAuth(
135
- secret: string,
136
- authState: unknown,
137
- accountId: string | undefined,
138
- ): QoderAuth {
139
- const state = parseQoderOAuthState(authState);
140
- if (state === undefined || !state.userId) {
141
- throw new GatewayError(
142
- "authentication_failed",
143
- 401,
144
- "Qoder OAuth account is missing its user identity; sign in again",
145
- );
146
- }
147
- return {
148
- userId: state.userId,
149
- userName: "",
150
- userType: "personal_standard",
151
- securityOauthToken: secret,
152
- refreshToken: "",
153
- machineId: state.machineId || (accountId ? qoderMachineIdForAccount(accountId) : randomUUID()),
154
- };
155
- }
156
-
157
- function qoderMachineIdFromPat(pat: string): string {
158
- const key = createHash("sha256").update(pat).digest("hex");
159
- const now = Date.now();
160
- const existing = qoderMachineIds.get(key);
161
- if (existing && existing.expiresAt > now) return existing.id;
162
- const id = randomUUID();
163
- qoderMachineIds.delete(key);
164
- qoderMachineIds.set(key, { id, expiresAt: now + QODER_MACHINE_ID_TTL_MS });
165
- for (const [candidate, value] of qoderMachineIds) {
166
- if (value.expiresAt <= now) qoderMachineIds.delete(candidate);
167
- }
168
- while (qoderMachineIds.size > QODER_MAX_MACHINE_IDS) {
169
- const oldest = qoderMachineIds.keys().next();
170
- if (oldest.done) break;
171
- qoderMachineIds.delete(oldest.value);
172
- }
173
- return id;
174
- }
175
-
176
- function qoderStaticHeaders(machineId: string, version = getQoderVersion()): Record<string, string> {
177
- const date = new Date().toUTCString();
178
- return {
179
- "cosy-machinetoken": machineId,
180
- "cosy-machinetype": "5",
181
- "cosy-machineid": machineId,
182
- "cosy-clienttype": "5",
183
- "cosy-version": version,
184
- "login-version": "v2",
185
- appcode: QODER_APPCODE,
186
- accept: "application/json",
187
- "accept-encoding": "identity",
188
- date,
189
- signature: qoderMd5(`${QODER_APPCODE}&${QODER_SIG_SECRET}&${date}`),
190
- "content-type": "application/json",
191
- "user-agent": "Go-http-client/2.0",
192
- };
193
- }
194
-
195
- function transformQoderBody(plaintext: string): Uint8Array {
196
- const base64 = Buffer.from(plaintext).toString("base64");
197
- const third = Math.floor(base64.length / 3);
198
- const reordered = base64.slice(base64.length - third) + base64.slice(third, base64.length - third) + base64.slice(0, third);
199
- let encoded = "";
200
- for (const char of reordered) {
201
- if (char === "=") encoded += "$";
202
- else encoded += QODER_ALPHABET[QODER_STANDARD_ALPHABET.indexOf(char)] ?? char;
203
- }
204
- return Buffer.from(encoded, "latin1");
205
- }
206
-
207
- function qoderBuildCosyHeaders(
208
- body: Uint8Array,
209
- url: string,
210
- auth: QoderAuth,
211
- version = getQoderVersion(),
212
- ): Record<string, string> {
213
- const key = randomUUID().replaceAll("-", "").slice(0, 16);
214
- const identity = JSON.stringify({
215
- name: auth.userName,
216
- aid: auth.userId,
217
- uid: auth.userId,
218
- yx_uid: "",
219
- organization_id: "",
220
- organization_name: "",
221
- user_type: auth.userType,
222
- security_oauth_token: auth.securityOauthToken,
223
- refresh_token: auth.refreshToken,
224
- });
225
- const cipher = createCipheriv("aes-128-cbc", Buffer.from(key), Buffer.from(key));
226
- const info = Buffer.concat([cipher.update(identity), cipher.final()]).toString("base64");
227
- const cosyKey = publicEncrypt({ key: QODER_RSA_PUBLIC_KEY, padding: constants.RSA_PKCS1_PADDING }, Buffer.from(key)).toString("base64");
228
- const payload = Buffer.from(
229
- JSON.stringify({ version: "v1", requestId: randomUUID(), info, cosyVersion: version, ideVersion: "" }),
230
- ).toString("base64");
231
- const date = String(Math.floor(Date.now() / 1000));
232
- const signature = qoderMd5(`${payload}\n${cosyKey}\n${date}\n${Buffer.from(body).toString("latin1")}\n${qoderPathSignature(url)}`);
233
- return {
234
- authorization: `Bearer COSY.${payload}.${signature}`,
235
- "cosy-data-policy": "agree",
236
- "cosy-machinetype": "5",
237
- "cosy-machineos": qoderMachineOs(),
238
- "cosy-clienttype": "5",
239
- "cosy-date": date,
240
- "cosy-user": auth.userId,
241
- "cosy-key": cosyKey,
242
- "cosy-bodyhash": qoderMd5(body),
243
- "cosy-bodylength": String(body.byteLength),
244
- "cosy-sigpath": qoderPathSignature(url),
245
- "cosy-organization-id": "",
246
- "cosy-organization-tags": "",
247
- "x-request-id": randomUUID(),
248
- ...(MODERN_PROFILE.sendBusinessHeaders
249
- ? {
250
- "cosy-business-product": MODERN_PROFILE.businessProduct,
251
- "cosy-business-type": MODERN_PROFILE.businessType,
252
- "cosy-business-version": version,
253
- "cosy-scene": MODERN_PROFILE.cosyScene,
254
- }
255
- : {}),
256
- "cosy-version": version,
257
- "login-version": "v2",
258
- appcode: QODER_APPCODE,
259
- accept: "application/json",
260
- "accept-encoding": "identity",
261
- date: new Date().toUTCString(),
262
- signature: qoderMd5(`${QODER_APPCODE}&${QODER_SIG_SECRET}&${new Date().toUTCString()}`),
263
- "content-type": "application/json",
264
- "user-agent": "Go-http-client/2.0",
265
- };
266
- }
267
-
268
- type QoderFetcher = (url: string, init: RequestInit) => Promise<Response>;
269
-
270
- async function exchangeQoderPat(
271
- pat: string,
272
- signal: AbortSignal,
273
- fetcher: QoderFetcher,
274
- version = getQoderVersion(),
275
- ): Promise<QoderAuth> {
276
- const machineId = qoderMachineIdFromPat(pat);
277
- const encodedBody = transformQoderBody(JSON.stringify({ payload: JSON.stringify({ personalToken: pat, securityOauthToken: "", refreshToken: "", needRefresh: false, authInfo: {} }), encodeVersion: "1" }));
278
- const response = await fetcher(QODER_JOB_TOKEN_URL, { method: "POST", headers: qoderStaticHeaders(machineId, version), body: encodedBody as unknown as BodyInit, signal });
279
- if (!response.ok) throw await mapUpstreamHttpError(response, "qoder");
280
- let responseBody: unknown;
281
- try {
282
- responseBody = await response.json();
283
- } catch {
284
- throw new GatewayError("platform_unavailable", 502, "Qoder PAT exchange returned invalid JSON", {}, "upstream");
285
- }
286
- if (typeof responseBody !== "object" || responseBody === null || Array.isArray(responseBody)) {
287
- throw new GatewayError("platform_unavailable", 502, "Qoder PAT exchange returned unexpected response", {}, "upstream");
288
- }
289
- const rec = responseBody as Record<string, unknown>;
290
- if (typeof rec["id"] !== "string" || typeof rec["securityOauthToken"] !== "string") {
291
- throw new GatewayError("platform_unavailable", 502, "Qoder PAT exchange returned incomplete credentials", {}, "upstream");
292
- }
293
- return {
294
- userId: rec["id"] as string,
295
- userName: typeof rec["name"] === "string" ? (rec["name"] as string) : "",
296
- userType: typeof rec["userType"] === "string" ? (rec["userType"] as string) : "personal_standard",
297
- securityOauthToken: rec["securityOauthToken"] as string,
298
- refreshToken: typeof rec["refreshToken"] === "string" ? (rec["refreshToken"] as string) : "",
299
- machineId,
300
- };
301
- }
302
-
303
- async function callQoder(
304
- url: string,
305
- body: Record<string, unknown>,
306
- modelId: string,
307
- auth: QoderAuth,
308
- signal: AbortSignal,
309
- fetcher: QoderFetcher,
310
- version = getQoderVersion(),
311
- ): Promise<Response> {
312
- const encoded = transformQoderBody(JSON.stringify(body));
313
- const modelConfig = (body["model_config"] as Record<string, unknown> | null) ?? null;
314
- return fetcher(url, {
315
- method: "POST",
316
- headers: {
317
- ...qoderBuildCosyHeaders(encoded, url, auth, version),
318
- ...(MODERN_PROFILE.sendModelSourceHeaders
319
- ? { "x-model-key": modelId, "x-model-source": typeof modelConfig?.["source"] === "string" ? (modelConfig["source"] as string) : "system" }
320
- : {}),
321
- Accept: "text/event-stream",
322
- "Cache-Control": "no-cache",
323
- "Accept-Encoding": "identity",
324
- },
325
- body: encoded as unknown as BodyInit,
326
- signal,
327
- });
328
- }
329
-
330
- /**
331
- * The human-readable text out of a Qoder error envelope.
332
- *
333
- * The envelope is Qoder's own wrapper around the stream, and it does not use
334
- * one field for the message: the text has been seen as a nested `error`
335
- * object, a bare string `body`, and a top-level `message`/`msg`. The canonical
336
- * extractor covers the structured shapes; a string body and the top-level
337
- * fields cover the rest. Whatever survives is bounded the same way an upstream
338
- * message is, so a verbose envelope cannot blow up the public error line.
339
- */
340
- function qoderEnvelopeMessage(rec: Record<string, unknown>): string {
341
- const structured = extractUpstreamMessage(rec["body"]);
342
- if (structured.length > 0) return structured;
343
- if (typeof rec["body"] === "string" && rec["body"].trim().length > 0 && rec["body"] !== "[DONE]")
344
- return rec["body"].replace(/[\r\n]+/g, " ").trim().slice(0, 500);
345
- return extractUpstreamMessage(rec);
346
- }
347
-
348
- function qoderEnvelopeToFrames(data: string): Array<{ event: string | null; data: string }> {
349
- if (data === "[DONE]") return [{ event: null, data: "[DONE]" }];
350
- let envelope: unknown;
351
- try {
352
- envelope = JSON.parse(data);
353
- } catch {
354
- }
355
- if (typeof envelope !== "object" || envelope === null || Array.isArray(envelope)) return [];
356
- const rec = envelope as Record<string, unknown>;
357
- if (rec["statusCodeValue"] !== undefined && rec["statusCodeValue"] !== 200) {
358
- const status = typeof rec["statusCodeValue"] === "number" ? (rec["statusCodeValue"] as number) : 502;
359
- // Qoder reports failures inside the stream envelope instead of as HTTP
360
- // responses, so classify its structured provider code and status through
361
- // the same gateway error policy as the other dispatch paths.
362
- const detail = qoderEnvelopeMessage(rec);
363
- const identifier = upstreamErrorIdentifier(rec["body"]) ?? upstreamErrorIdentifier(rec);
364
- const classification = classifyUpstreamError(status, identifier);
365
- throw new GatewayError(
366
- classification.code,
367
- classification.status,
368
- detail.length > 0 ? detail : `Qoder stream envelope returned HTTP ${status}`,
369
- {
370
- providerId: QODER_PROVIDER_ID,
371
- providerStatus: status,
372
- ...(identifier ? { providerCode: identifier } : {}),
373
- ...(classification.credentialEvidence ? { credentialEvidence: true } : {}),
374
- ...(classification.rateLimitScope
375
- ? { rateLimitScope: classification.rateLimitScope }
376
- : {}),
377
- },
378
- classification.origin,
379
- );
380
- }
381
- const body = rec["body"];
382
- if (body === "[DONE]") return [{ event: null, data: "[DONE]" }];
383
- if (typeof body !== "string") return [];
384
- return [{ event: null, data: body.replace(/\r?\n/g, "") }];
385
- }
386
-
387
- function qoderStableHash(prefix: string, ...parts: string[]): string {
388
- const h = createHash("sha256");
389
- h.update(prefix);
390
- for (const p of parts) {
391
- h.update("\0");
392
- h.update(p);
393
- }
394
- return h.digest("hex").slice(0, 16);
395
- }
396
-
397
- function flattenCanonicalContent(content: readonly ContentPart[]): string {
398
- return content
399
- .filter((b) => b.kind === "text" || b.kind === "toolResult")
400
- .map((b) => {
401
- if (b.kind === "text") return b.text;
402
- if (b.kind === "toolResult") return typeof b.content === "string" ? b.content : JSON.stringify(b.content);
403
- return "";
404
- })
405
- .join("\n");
406
- }
407
-
408
- function qoderStableRecordId(modelId: string, messages: CanonicalRequest["messages"], maxTokens: number): string {
409
- const h = createHash("sha256");
410
- h.update("qoder-record\0");
411
- h.update(modelId);
412
- for (const m of messages) {
413
- h.update("\0");
414
- h.update(m.role);
415
- const text = flattenCanonicalContent(m.content);
416
- if (text) {
417
- h.update("\0");
418
- h.update(text);
419
- }
420
- }
421
- h.update(`\0mt=${maxTokens}`);
422
- return h.digest("hex").slice(0, 16);
423
- }
424
-
425
- function qoderRequestedMaxTokens(request: CanonicalRequest, modelConfig: QoderModelConfig): number {
426
- const configured = typeof modelConfig.max_output_tokens === "number" ? modelConfig.max_output_tokens : 32768;
427
- const controls = request.generation_controls as Record<string, unknown>;
428
- const requested =
429
- typeof controls["max_tokens"] === "number"
430
- ? (controls["max_tokens"] as number)
431
- : typeof controls["max_output_tokens"] === "number"
432
- ? (controls["max_output_tokens"] as number)
433
- : null;
434
- return typeof requested === "number" && requested > 0 ? Math.min(requested, configured) : configured;
435
- }
436
-
437
- export function buildQoderRequest(
438
- modelId: string,
439
- request: CanonicalRequest,
440
- modelConfig: QoderModelConfig,
441
- auth: QoderAuth,
442
- ): Record<string, unknown> {
443
- const allMessages = request.messages;
444
- const systemParts: string[] = [];
445
- if (request.system) {
446
- for (const p of request.system) if (p.kind === "text") systemParts.push(p.text);
447
- }
448
- if (request.instructions) {
449
- for (const p of request.instructions) if (p.kind === "text") systemParts.push(p.text);
450
- }
451
- for (const m of allMessages) {
452
- if (m.role === "system" || m.role === "developer") {
453
- const t = flattenCanonicalContent(m.content);
454
- if (t) systemParts.push(t);
455
- }
456
- }
457
- const systemPrompt = systemParts.join("\n\n").trim();
458
- const qoderMessages: Array<Record<string, unknown>> = [];
459
- if (MODERN_PROFILE.mirrorTopLevelSystem && systemPrompt.length > 0) {
460
- qoderMessages.push({
461
- role: "system",
462
- content: systemPrompt,
463
- contents: [{ type: "text", text: systemPrompt }],
464
- });
465
- }
466
- for (const m of allMessages) {
467
- if (m.role === "system" || m.role === "developer") continue;
468
- // Answers may live in a `user` turn (the Messages ledger re-homes them),
469
- // so the result scan is role-agnostic. Each result becomes its own `tool`
470
- // turn carrying its `tool_call_id`; any non-result content on the same turn
471
- // is emitted after, so nothing is duplicated or lost.
472
- const results = toolResultParts(m);
473
- if (results.length > 0) {
474
- for (const block of results) {
475
- const text = flattenCanonicalContent(
476
- typeof block.content === "string"
477
- ? [{ kind: "text", text: block.content }]
478
- : block.content,
479
- );
480
- qoderMessages.push({
481
- role: "tool",
482
- content: text,
483
- contents: [{ type: "text", text }],
484
- tool_call_id: block.call_id,
485
- });
486
- }
487
- const remaining = m.content.filter((part) => part.kind !== "toolResult");
488
- if (remaining.length === 0) continue;
489
- const flat = flattenCanonicalContent(remaining);
490
- qoderMessages.push({
491
- role: "user",
492
- content: flat,
493
- contents: [{ type: "text", text: flat }],
494
- });
495
- continue;
496
- }
497
- const flat = flattenCanonicalContent(m.content);
498
- qoderMessages.push({
499
- role: m.role === "assistant" ? "assistant" : "user",
500
- content: flat,
501
- contents: [{ type: "text", text: flat }],
502
- });
503
- }
504
- const latestUserMessage = [...qoderMessages].reverse().find((m) => m["role"] === "user");
505
- const latestUserText = typeof latestUserMessage?.["content"] === "string" ? (latestUserMessage["content"] as string) : "";
506
- const maxTokens = qoderRequestedMaxTokens(request, modelConfig);
507
- const reasoning = modelConfig.is_reasoning === true;
508
- const sessionId = qoderStableHash("qoder-session", auth.userId, modelId);
509
- const recordId = qoderStableRecordId(modelId, allMessages, maxTokens);
510
- return {
511
- request_id: randomUUID(),
512
- request_set_id: recordId,
513
- chat_record_id: recordId,
514
- session_id: sessionId,
515
- stream: true,
516
- ...(MODERN_PROFILE.emptyAliyunUserType ? { aliyun_user_type: "" } : {}),
517
- chat_task: "FREE_INPUT",
518
- is_reply: true,
519
- is_retry: false,
520
- source: 1,
521
- version: "3",
522
- session_type: "qodercli",
523
- agent_id: "agent_common",
524
- task_id: "common",
525
- code_language: "",
526
- chat_prompt: MODERN_PROFILE.mirrorTopLevelSystem ? systemPrompt : "",
527
- image_urls: null,
528
- chat_context: {
529
- chatPrompt: MODERN_PROFILE.mirrorTopLevelSystem ? systemPrompt : "",
530
- imageUrls: null,
531
- extra: { context: [], modelConfig: { key: modelId, is_reasoning: reasoning }, originalContent: latestUserText },
532
- features: [],
533
- text: latestUserText,
534
- },
535
- model_config: {
536
- key: modelId,
537
- display_name: modelConfig.display_name,
538
- is_vl: modelConfig.is_vl,
539
- is_reasoning: modelConfig.is_reasoning,
540
- max_input_tokens: modelConfig.max_input_tokens,
541
- max_output_tokens: modelConfig.max_output_tokens ?? 32768,
542
- source: modelConfig.source ?? "system",
543
- },
544
- messages: qoderMessages,
545
- max_tokens: maxTokens,
546
- };
547
- }
548
-
549
- // Stream transformation — decode SSE, unwrap COSY envelope, map OpenAI chat chunks to CanonicalEvent
550
-
551
- function mapQoderFinishReason(raw: unknown): CanonicalStopReason | undefined {
552
- if (raw === "stop") return "stop";
553
- if (raw === "length") return "length";
554
- if (raw === "tool_calls") return "tool_use";
555
- if (raw === "content_filter") return "content_filter";
556
- return undefined;
557
- }
558
-
559
- async function* qoderBodyToCanonicalEvents(
560
- body: ReadableStream<Uint8Array>,
561
- signal: AbortSignal,
562
- model: string,
563
- ): AsyncIterable<CanonicalEvent> {
564
- let seq = 1;
565
- yield { type: "response_start", sequence_number: seq++, model } as CanonicalEvent;
566
- let finishReason: unknown = undefined;
567
- let rawUsage: Record<string, unknown> | undefined = undefined;
568
- let hasTerminal = false;
569
-
570
- for await (const sse of decodeSseEvents(body, { signal })) {
571
- const sseData = sse.data;
572
- let frames: Array<{ event: string | null; data: string }>;
573
- try {
574
- frames = qoderEnvelopeToFrames(sseData);
575
- } catch (e) {
576
- throw e;
577
- }
578
- for (const frame of frames) {
579
- const data = frame.data.trim();
580
- if (!data) continue;
581
- if (data === "[DONE]") {
582
- hasTerminal = true;
583
- continue;
584
- }
585
- let json: Record<string, unknown>;
586
- try {
587
- json = JSON.parse(data) as Record<string, unknown>;
588
- } catch {
589
- continue;
590
- }
591
- if (json["usage"] && typeof json["usage"] === "object") rawUsage = json["usage"] as Record<string, unknown>;
592
- const choices = (json["choices"] as Array<Record<string, unknown>>) ?? [];
593
- for (const choice of choices) {
594
- const delta = choice["delta"] as Record<string, unknown> | undefined;
595
- if (delta) {
596
- if (typeof delta["content"] === "string" && (delta["content"] as string).length > 0) {
597
- yield {
598
- type: "content_delta",
599
- sequence_number: seq++,
600
- content: { kind: "text", text: delta["content"] as string },
601
- } as CanonicalEvent;
602
- }
603
- const reasoningText = readReasoningText(delta);
604
- if (typeof reasoningText === "string" && reasoningText.length > 0) {
605
- yield {
606
- type: "content_delta",
607
- sequence_number: seq++,
608
- content: { kind: "reasoning", payload: null, summary: reasoningText },
609
- } as CanonicalEvent;
610
- }
611
- const toolCalls = delta["tool_calls"] as Array<Record<string, unknown>> | undefined;
612
- if (toolCalls) {
613
- for (const tc of toolCalls) {
614
- const fn = tc["function"] as Record<string, unknown> | undefined;
615
- yield {
616
- type: "tool_call_delta",
617
- sequence_number: seq++,
618
- call_id: (tc["id"] as string) ?? `call_${String(tc["index"] ?? 0)}`,
619
- name: fn?.["name"] as string | undefined,
620
- arguments_delta: (fn?.["arguments"] as string) ?? "",
621
- } as CanonicalEvent;
622
- }
623
- }
624
- }
625
- const fr = choice["finish_reason"];
626
- if (fr !== null && fr !== undefined) finishReason = fr;
627
- // Some providers send usage in choices[0].usage or top-level
628
- if (choice["usage"] && typeof choice["usage"] === "object") rawUsage = choice["usage"] as Record<string, unknown>;
629
- }
630
- // Some Qoder chunks carry finish_reason at top level
631
- if (json["finish_reason"] !== undefined) finishReason = json["finish_reason"];
632
- }
633
- }
634
- // If no terminal arrived, synthesize one (prevents truncation error)
635
- const stopReason = mapQoderFinishReason(finishReason);
636
- const _providerStop = typeof finishReason === "string" ? finishReason : undefined;
637
- void hasTerminal;
638
- yield {
639
- type: "terminal",
640
- sequence_number: seq++,
641
- state: "complete",
642
- ...(stopReason === undefined ? {} : { stop_reason: stopReason }),
643
- ...(_providerStop === undefined ? {} : { provider_stop_reason: _providerStop }),
644
- usage: usageFromProvider(rawUsage),
645
- } as CanonicalEvent;
646
- }
647
-
648
- // Model catalog — maps QODER_MODEL_CONFIGS (provider) to Cartethyia ModelDefinition
649
-
650
- export const QODER_MODELS: readonly ModelDefinition[] = Object.entries(QODER_MODEL_CONFIGS).map(([id, cfg]) =>
651
- defineModel({ id, endpoint: "/algo/api/v2/service/pro/sse/agent_chat_generation?FetchKeys=llm_model_result&AgentId=agent_common&Encode=1", ctx: cfg.max_input_tokens, out: cfg.max_output_tokens ?? 32768, vision: cfg.is_vl, reasoning: cfg.is_reasoning }),
652
- );
653
-
654
- // ProviderAdapter — manual dispatch preserving COSY encryption + envelope logic
655
-
656
- interface QoderAdapterOptions {
657
- readonly fetch?: typeof fetch;
658
- }
659
-
660
- class QoderAdapter implements ProviderAdapter {
661
- readonly provider_id = QODER_PROVIDER_ID;
662
- private readonly fetchFn: typeof fetch;
663
-
664
- constructor(options: QoderAdapterOptions = {}) {
665
- this.fetchFn = options.fetch ?? globalThis.fetch;
666
- }
667
-
668
- async *dispatch(
669
- request: CanonicalRequest,
670
- candidate: ProviderDispatchTarget,
671
- context: ProviderDispatchContext,
672
- ): AsyncIterable<CanonicalEvent> {
673
- if (candidate.wire_family !== "chat") {
674
- throw new GatewayError("capability_unsupported", 400, `qoder supports chat only, got ${candidate.wire_family}`);
675
- }
676
- const secret = readCredentialSecret(context.credential, "Qoder credential is required");
677
-
678
- const modelId = candidate.model_id || request.model;
679
- const modelConfig = (QODER_MODEL_CONFIGS as Record<string, QoderModelConfig>)[modelId] ?? {
680
- id: modelId,
681
- display_name: modelId,
682
- max_input_tokens: 180_000,
683
- is_vl: true,
684
- is_reasoning: false,
685
- };
686
-
687
- const lifecycle = createUpstreamDeadlineLifecycle(context);
688
-
689
- // Outbound fetch respects SSRF binding when provided
690
- const outboundFetch: typeof fetch = (context.outbound_fetch as unknown as typeof fetch) ?? this.fetchFn;
691
-
692
- const fetcher: QoderFetcher = (url, init) =>
693
- outboundFetch(url, { ...init, signal: lifecycle.signal } as RequestInit) as Promise<Response>;
694
-
695
- try {
696
- const version = getQoderVersion();
697
- // Dual mode like Cline: a pasted PAT is exchanged for a job token per
698
- // request, while an OAuth device token is used directly with the
699
- // identity the login persisted.
700
- const auth = isQoderPat(secret)
701
- ? await exchangeQoderPat(secret, lifecycle.signal, fetcher, version)
702
- : qoderOAuthAuth(secret, context.credential.auth_state, context.credential.account_id);
703
- const qoderBody = buildQoderRequest(modelId, request, modelConfig, auth);
704
- const url =
705
- candidate.endpoint_path && candidate.endpoint_path.startsWith("http")
706
- ? candidate.endpoint_path
707
- : MODERN_PROFILE.chatUrl;
708
-
709
- const response = await callQoder(url, qoderBody, modelId, auth, lifecycle.signal, fetcher, version);
710
- if (!response.ok) throw await mapUpstreamHttpError(response, "qoder");
711
- if (!response.body) throw new GatewayError("platform_unavailable", 502, "Qoder returned empty body", {}, "upstream");
712
- // Headers arrived: the pre-stream deadline has served its purpose.
713
- // From here the gateway stall/first-chunk watchdog (propagated via
714
- // context.abort_signal) governs the body. Keeping this timer armed
715
- // would kill healthy long streams at the stale pre-stream deadline.
716
- lifecycle.release();
717
- yield* qoderBodyToCanonicalEvents(response.body as ReadableStream<Uint8Array>, lifecycle.signal, request.model);
718
- } catch (err: unknown) {
719
- const abortError = abortGatewayError(lifecycle, err, context.abort_signal);
720
- if (abortError) throw abortError;
721
- throw err;
722
- } finally {
723
- lifecycle.release();
724
- }
725
- }
726
- }
727
-
728
- export function createQoderAdapter(options: QoderAdapterOptions = {}): ProviderAdapter {
729
- return new QoderAdapter(options);
730
- }
1
+ // Factory-blocked (Phase C4): PAT-to-jobToken session handshake, COSY
2
+ // AES/RSA request signing, alphabet-scrambled binary body, enveloped SSE
3
+ // frames — session/crypto protocol outside factory reach; stays bespoke.
4
+ import { constants, createCipheriv, createHash, publicEncrypt, randomUUID } from "node:crypto";
5
+ import { classifyUpstreamError, extractUpstreamMessage, mapUpstreamHttpError, upstreamErrorIdentifier } from "../../../transport/failure-policy";
6
+ import { GatewayError } from "../../../protocol/gateway-error";
7
+ import type { CanonicalEvent, CanonicalRequest, CanonicalStopReason, ContentPart } from "../../../protocol/canonical-model";
8
+ import { toolResultParts } from "../../../protocol/canonical-model";
9
+ import { decodeSseEvents } from "../../../protocol/sse-decoder";
10
+ import { usageFromProvider, readReasoningText } from "../../provider-usage";
11
+ import { readCredentialSecret, type ProviderDispatchTarget, type ProviderAdapter, type ProviderDispatchContext, type ProviderId } from "../../provider-contracts";
12
+ import type { ModelDefinition } from "../../provider-model-definition";
13
+ import { parseQoderOAuthState } from "./qoder-oauth";
14
+ import { getQoderVersion } from "../../operations/client-versions";
15
+ import { abortGatewayError, createUpstreamDeadlineLifecycle } from "../../operations/upstream-deadline";
16
+ import { qoderMachineOs } from "../../operations/cli-platform";
17
+ import { qoderGatewayCandidates, QODER_CHAT_PATH, QODER_REALMS, type QoderRealm } from "./qoder-realm";
18
+ import { QODER_CN_MODEL_CONFIGS, QODER_INTL_MODEL_CONFIGS, QODER_INTL_MODELS } from "./qoder-catalog";
19
+ import { isQoderVirtualModel, qoderDispatchModelId } from "./qoder-virtual";
20
+
21
+ interface QoderModeProfile {
22
+ readonly chatUrl: string;
23
+ readonly businessProduct: string;
24
+ readonly businessType: string;
25
+ readonly businessVersion: string;
26
+ readonly cosyScene: string;
27
+ readonly mirrorTopLevelSystem: boolean;
28
+ readonly sendBusinessHeaders: boolean;
29
+ readonly sendModelSourceHeaders: boolean;
30
+ readonly emptyAliyunUserType: boolean;
31
+ }
32
+
33
+ export const MODERN_PROFILE: QoderModeProfile = {
34
+ chatUrl: "https://api2.qoder.sh/algo/api/v2/service/pro/sse/agent_chat_generation?FetchKeys=llm_model_result&AgentId=agent_common&Encode=1",
35
+ businessProduct: "cli",
36
+ businessType: "agent",
37
+ businessVersion: "1.0.22",
38
+ cosyScene: "assistant",
39
+ mirrorTopLevelSystem: true,
40
+ sendBusinessHeaders: true,
41
+ sendModelSourceHeaders: true,
42
+ emptyAliyunUserType: true,
43
+ };
44
+
45
+ const QODER_PROVIDER_ID = "qoder" as const;
46
+
47
+ export const QODER_MODEL_CONFIGS: Record<
48
+ string,
49
+ { id: string; display_name: string; max_input_tokens: number; max_output_tokens?: number; is_vl: boolean; is_reasoning: boolean; source?: string }
50
+ > = {
51
+ auto: { id: "auto", display_name: "Auto", max_input_tokens: 180000, is_vl: true, is_reasoning: false },
52
+ ultimate: { id: "ultimate", display_name: "Ultimate", max_input_tokens: 180000, is_vl: true, is_reasoning: true },
53
+ performance: { id: "performance", display_name: "Performance", max_input_tokens: 272000, is_vl: true, is_reasoning: false },
54
+ efficient: { id: "efficient", display_name: "Efficient", max_input_tokens: 180000, is_vl: true, is_reasoning: false },
55
+ lite: { id: "lite", display_name: "Lite", max_input_tokens: 180000, is_vl: false, is_reasoning: true },
56
+ qmodel: { id: "qmodel", display_name: "Qwen 3.6 Plus", max_input_tokens: 180000, is_vl: true, is_reasoning: false },
57
+ qmodel_latest: { id: "qmodel_latest", display_name: "Qwen 3.7 Max", max_input_tokens: 1000000, is_vl: true, is_reasoning: false },
58
+ qmodel_preview: { id: "qmodel_preview", display_name: "Qwen 3.8 Max", max_input_tokens: 1000000, is_vl: true, is_reasoning: false },
59
+ dmodel: { id: "dmodel", display_name: "DeepSeek V4 Pro", max_input_tokens: 180000, is_vl: true, is_reasoning: true },
60
+ dfmodel: { id: "dfmodel", display_name: "DeepSeek V4 Flash", max_input_tokens: 180000, is_vl: true, is_reasoning: true },
61
+ gm51model: { id: "gm51model", display_name: "GLM 5.1", max_input_tokens: 180000, is_vl: true, is_reasoning: true },
62
+ kmodel: { id: "kmodel", display_name: "Kimi K2.6", max_input_tokens: 256000, is_vl: true, is_reasoning: false },
63
+ mmodel: { id: "mmodel", display_name: "MiniMax M2.7", max_input_tokens: 180000, is_vl: true, is_reasoning: false },
64
+ kmodel_latest: { id: "kmodel_latest", display_name: "Kimi K2.7 Latest", max_input_tokens: 256000, is_vl: true, is_reasoning: false },
65
+ };
66
+
67
+ const QODER_APPCODE = "cosy";
68
+ const QODER_SIG_SECRET = "d2FyLCB3YXIgbmV2ZXIgY2hhbmdlcw==";
69
+ /**
70
+ * Where a PAT is exchanged for a short-lived job token, per realm.
71
+ *
72
+ * The job token is realm-bound: one minted on the global host answers "Login
73
+ * expired" on the China gateway. Exchanging against the wrong host therefore
74
+ * looks like a dead credential rather than a routing bug, which is why the
75
+ * URL is derived from the realm table instead of being one constant.
76
+ *
77
+ * `intl` keeps its historical `center.qoder.sh` v3 endpoint. `cn` uses the
78
+ * openapi host the donor's `PATH_JOB_EXCHANGE` describes; if that path is
79
+ * ever wrong for CN, the failure surfaces as a 401/403 on exchange, not as a
80
+ * silently misrouted request.
81
+ */
82
+ const QODER_JOB_TOKEN_URL = "https://center.qoder.sh/algo/api/v3/user/jobToken?Encode=1";
83
+ function qoderJobTokenUrl(realm: QoderRealm): string {
84
+ return realm === "cn"
85
+ ? `${QODER_REALMS.cn.openapi}/api/v1/jobToken/exchange`
86
+ : QODER_JOB_TOKEN_URL;
87
+ }
88
+ const QODER_STANDARD_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
89
+ const QODER_ALPHABET = "_doRTgHZBKcGVjlvpC,@aFSx#DPuNJme&i*MzLOEn)sUrthbf%Y^w.(kIQyXqWA!";
90
+ const QODER_RSA_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
91
+ MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDA8iMH5c02LilrsERw9t6Pv5Nc
92
+ 4k6Pz1EaDicBMpdpxKduSZu5OANqUq8er4GM95omAGIOPOh+Nx0spthYA2BqGz+l
93
+ 6HRkPJ7S236FZz73In/KVuLnwI8JJ2CbuJap8kvheCCZpmAWpb/cPx/3Vr/J6I17
94
+ XcW+ML9FoCI6AOvOzwIDAQAB
95
+ -----END PUBLIC KEY-----`;
96
+
97
+ export interface QoderAuth {
98
+ userId: string;
99
+ userName: string;
100
+ userType: string;
101
+ securityOauthToken: string;
102
+ refreshToken: string;
103
+ machineId: string;
104
+ }
105
+ interface QoderModelConfig {
106
+ id: string;
107
+ display_name: string;
108
+ max_input_tokens: number;
109
+ max_output_tokens?: number;
110
+ is_vl: boolean;
111
+ is_reasoning: boolean;
112
+ source?: string;
113
+ }
114
+
115
+
116
+ function qoderMd5(value: string | Uint8Array): string {
117
+ return createHash("md5").update(value).digest("hex");
118
+ }
119
+ function qoderPathSignature(url: string): string {
120
+ const path = new URL(url).pathname;
121
+ return path.startsWith("/algo") ? path.slice(5) : path;
122
+ }
123
+
124
+ const QODER_MACHINE_ID_TTL_MS = 60 * 60 * 1000;
125
+ const QODER_MAX_MACHINE_IDS = 1_024;
126
+ const qoderMachineIds = new Map<string, { id: string; expiresAt: number }>();
127
+ /**
128
+ * A PAT (`pt-...`) must be exchanged for a short-lived job token before it
129
+ * can sign COSY requests. Device tokens (`dt-...`) from OAuth login and job
130
+ * tokens (`jt-...`) are used directly.
131
+ */
132
+ export function isQoderPat(secret: string): boolean {
133
+ return secret.startsWith("pt-");
134
+ }
135
+
136
+ /**
137
+ * Stable per-account machine id for OAuth dispatches. Derived from the
138
+ * account id (not minted per request) so pooled accounts keep one device
139
+ * fingerprint across restarts instead of looking like a new device every
140
+ * time, while staying distinct per account.
141
+ */
142
+ export function qoderMachineIdForAccount(accountId: string): string {
143
+ const hex = createHash("sha256").update(`qoder-machine-v1:${accountId}`).digest("hex");
144
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
145
+ }
146
+
147
+ /**
148
+ * Builds dispatch auth from an OAuth device token. The token is used
149
+ * directly as the COSY identity's oauth token; the user id and machine id
150
+ * come from the `auth_state` the login persisted. Fails closed with a
151
+ * reconnect prompt when the identity is absent (e.g. an account created
152
+ * before `auth_state` existed) instead of signing with a guessed id.
153
+ */
154
+ export function qoderOAuthAuth(
155
+ secret: string,
156
+ authState: unknown,
157
+ accountId: string | undefined,
158
+ ): QoderAuth {
159
+ const state = parseQoderOAuthState(authState);
160
+ if (state === undefined || !state.userId) {
161
+ throw new GatewayError(
162
+ "authentication_failed",
163
+ 401,
164
+ "Qoder OAuth account is missing its user identity; sign in again",
165
+ );
166
+ }
167
+ return {
168
+ userId: state.userId,
169
+ userName: "",
170
+ userType: "personal_standard",
171
+ securityOauthToken: secret,
172
+ refreshToken: "",
173
+ machineId: state.machineId || (accountId ? qoderMachineIdForAccount(accountId) : randomUUID()),
174
+ };
175
+ }
176
+
177
+ function qoderMachineIdFromPat(pat: string): string {
178
+ const key = createHash("sha256").update(pat).digest("hex");
179
+ const now = Date.now();
180
+ const existing = qoderMachineIds.get(key);
181
+ if (existing && existing.expiresAt > now) return existing.id;
182
+ const id = randomUUID();
183
+ qoderMachineIds.delete(key);
184
+ qoderMachineIds.set(key, { id, expiresAt: now + QODER_MACHINE_ID_TTL_MS });
185
+ for (const [candidate, value] of qoderMachineIds) {
186
+ if (value.expiresAt <= now) qoderMachineIds.delete(candidate);
187
+ }
188
+ while (qoderMachineIds.size > QODER_MAX_MACHINE_IDS) {
189
+ const oldest = qoderMachineIds.keys().next();
190
+ if (oldest.done) break;
191
+ qoderMachineIds.delete(oldest.value);
192
+ }
193
+ return id;
194
+ }
195
+
196
+ function qoderStaticHeaders(machineId: string, version = getQoderVersion()): Record<string, string> {
197
+ const date = new Date().toUTCString();
198
+ return {
199
+ "cosy-machinetoken": machineId,
200
+ "cosy-machinetype": "5",
201
+ "cosy-machineid": machineId,
202
+ "cosy-clienttype": "5",
203
+ "cosy-version": version,
204
+ "login-version": "v2",
205
+ appcode: QODER_APPCODE,
206
+ accept: "application/json",
207
+ "accept-encoding": "identity",
208
+ date,
209
+ signature: qoderMd5(`${QODER_APPCODE}&${QODER_SIG_SECRET}&${date}`),
210
+ "content-type": "application/json",
211
+ "user-agent": "Go-http-client/2.0",
212
+ };
213
+ }
214
+
215
+ function transformQoderBody(plaintext: string): Uint8Array {
216
+ const base64 = Buffer.from(plaintext).toString("base64");
217
+ const third = Math.floor(base64.length / 3);
218
+ const reordered = base64.slice(base64.length - third) + base64.slice(third, base64.length - third) + base64.slice(0, third);
219
+ let encoded = "";
220
+ for (const char of reordered) {
221
+ if (char === "=") encoded += "$";
222
+ else encoded += QODER_ALPHABET[QODER_STANDARD_ALPHABET.indexOf(char)] ?? char;
223
+ }
224
+ return Buffer.from(encoded, "latin1");
225
+ }
226
+
227
+ function qoderBuildCosyHeaders(
228
+ body: Uint8Array,
229
+ url: string,
230
+ auth: QoderAuth,
231
+ version = getQoderVersion(),
232
+ ): Record<string, string> {
233
+ const key = randomUUID().replaceAll("-", "").slice(0, 16);
234
+ const identity = JSON.stringify({
235
+ name: auth.userName,
236
+ aid: auth.userId,
237
+ uid: auth.userId,
238
+ yx_uid: "",
239
+ organization_id: "",
240
+ organization_name: "",
241
+ user_type: auth.userType,
242
+ security_oauth_token: auth.securityOauthToken,
243
+ refresh_token: auth.refreshToken,
244
+ });
245
+ const cipher = createCipheriv("aes-128-cbc", Buffer.from(key), Buffer.from(key));
246
+ const info = Buffer.concat([cipher.update(identity), cipher.final()]).toString("base64");
247
+ const cosyKey = publicEncrypt({ key: QODER_RSA_PUBLIC_KEY, padding: constants.RSA_PKCS1_PADDING }, Buffer.from(key)).toString("base64");
248
+ const payload = Buffer.from(
249
+ JSON.stringify({ version: "v1", requestId: randomUUID(), info, cosyVersion: version, ideVersion: "" }),
250
+ ).toString("base64");
251
+ const date = String(Math.floor(Date.now() / 1000));
252
+ const signature = qoderMd5(`${payload}\n${cosyKey}\n${date}\n${Buffer.from(body).toString("latin1")}\n${qoderPathSignature(url)}`);
253
+ return {
254
+ authorization: `Bearer COSY.${payload}.${signature}`,
255
+ "cosy-data-policy": "agree",
256
+ "cosy-machinetype": "5",
257
+ "cosy-machineos": qoderMachineOs(),
258
+ "cosy-clienttype": "5",
259
+ "cosy-date": date,
260
+ "cosy-user": auth.userId,
261
+ "cosy-key": cosyKey,
262
+ "cosy-bodyhash": qoderMd5(body),
263
+ "cosy-bodylength": String(body.byteLength),
264
+ "cosy-sigpath": qoderPathSignature(url),
265
+ "cosy-organization-id": "",
266
+ "cosy-organization-tags": "",
267
+ "x-request-id": randomUUID(),
268
+ ...(MODERN_PROFILE.sendBusinessHeaders
269
+ ? {
270
+ "cosy-business-product": MODERN_PROFILE.businessProduct,
271
+ "cosy-business-type": MODERN_PROFILE.businessType,
272
+ "cosy-business-version": version,
273
+ "cosy-scene": MODERN_PROFILE.cosyScene,
274
+ }
275
+ : {}),
276
+ "cosy-version": version,
277
+ "login-version": "v2",
278
+ appcode: QODER_APPCODE,
279
+ accept: "application/json",
280
+ "accept-encoding": "identity",
281
+ date: new Date().toUTCString(),
282
+ signature: qoderMd5(`${QODER_APPCODE}&${QODER_SIG_SECRET}&${new Date().toUTCString()}`),
283
+ "content-type": "application/json",
284
+ "user-agent": "Go-http-client/2.0",
285
+ };
286
+ }
287
+
288
+ type QoderFetcher = (url: string, init: RequestInit) => Promise<Response>;
289
+
290
+ async function exchangeQoderPat(
291
+ pat: string,
292
+ signal: AbortSignal,
293
+ fetcher: QoderFetcher,
294
+ version = getQoderVersion(),
295
+ realm: QoderRealm = "intl",
296
+ ): Promise<QoderAuth> {
297
+ const machineId = qoderMachineIdFromPat(pat);
298
+ const encodedBody = transformQoderBody(JSON.stringify({ payload: JSON.stringify({ personalToken: pat, securityOauthToken: "", refreshToken: "", needRefresh: false, authInfo: {} }), encodeVersion: "1" }));
299
+ const response = await fetcher(qoderJobTokenUrl(realm), { method: "POST", headers: qoderStaticHeaders(machineId, version), body: encodedBody as unknown as BodyInit, signal });
300
+ if (!response.ok) throw await mapUpstreamHttpError(response, "qoder");
301
+ let responseBody: unknown;
302
+ try {
303
+ responseBody = await response.json();
304
+ } catch {
305
+ throw new GatewayError("platform_unavailable", 502, "Qoder PAT exchange returned invalid JSON", {}, "upstream");
306
+ }
307
+ if (typeof responseBody !== "object" || responseBody === null || Array.isArray(responseBody)) {
308
+ throw new GatewayError("platform_unavailable", 502, "Qoder PAT exchange returned unexpected response", {}, "upstream");
309
+ }
310
+ const rec = responseBody as Record<string, unknown>;
311
+ if (typeof rec["id"] !== "string" || typeof rec["securityOauthToken"] !== "string") {
312
+ throw new GatewayError("platform_unavailable", 502, "Qoder PAT exchange returned incomplete credentials", {}, "upstream");
313
+ }
314
+ return {
315
+ userId: rec["id"] as string,
316
+ userName: typeof rec["name"] === "string" ? (rec["name"] as string) : "",
317
+ userType: typeof rec["userType"] === "string" ? (rec["userType"] as string) : "personal_standard",
318
+ securityOauthToken: rec["securityOauthToken"] as string,
319
+ refreshToken: typeof rec["refreshToken"] === "string" ? (rec["refreshToken"] as string) : "",
320
+ machineId,
321
+ };
322
+ }
323
+
324
+ async function callQoder(
325
+ url: string,
326
+ body: Record<string, unknown>,
327
+ modelId: string,
328
+ auth: QoderAuth,
329
+ signal: AbortSignal,
330
+ fetcher: QoderFetcher,
331
+ version = getQoderVersion(),
332
+ ): Promise<Response> {
333
+ const encoded = transformQoderBody(JSON.stringify(body));
334
+ const modelConfig = (body["model_config"] as Record<string, unknown> | null) ?? null;
335
+ return fetcher(url, {
336
+ method: "POST",
337
+ headers: {
338
+ ...qoderBuildCosyHeaders(encoded, url, auth, version),
339
+ ...(MODERN_PROFILE.sendModelSourceHeaders
340
+ ? { "x-model-key": modelId, "x-model-source": typeof modelConfig?.["source"] === "string" ? (modelConfig["source"] as string) : "system" }
341
+ : {}),
342
+ Accept: "text/event-stream",
343
+ "Cache-Control": "no-cache",
344
+ "Accept-Encoding": "identity",
345
+ },
346
+ body: encoded as unknown as BodyInit,
347
+ signal,
348
+ });
349
+ }
350
+
351
+ /**
352
+ * The human-readable text out of a Qoder error envelope.
353
+ *
354
+ * The envelope is Qoder's own wrapper around the stream, and it does not use
355
+ * one field for the message: the text has been seen as a nested `error`
356
+ * object, a bare string `body`, and a top-level `message`/`msg`. The canonical
357
+ * extractor covers the structured shapes; a string body and the top-level
358
+ * fields cover the rest. Whatever survives is bounded the same way an upstream
359
+ * message is, so a verbose envelope cannot blow up the public error line.
360
+ */
361
+ function qoderEnvelopeMessage(rec: Record<string, unknown>): string {
362
+ const structured = extractUpstreamMessage(rec["body"]);
363
+ if (structured.length > 0) return structured;
364
+ if (typeof rec["body"] === "string" && rec["body"].trim().length > 0 && rec["body"] !== "[DONE]")
365
+ return rec["body"].replace(/[\r\n]+/g, " ").trim().slice(0, 500);
366
+ return extractUpstreamMessage(rec);
367
+ }
368
+
369
+ function qoderEnvelopeToFrames(data: string): Array<{ event: string | null; data: string }> {
370
+ if (data === "[DONE]") return [{ event: null, data: "[DONE]" }];
371
+ let envelope: unknown;
372
+ try {
373
+ envelope = JSON.parse(data);
374
+ } catch {
375
+ }
376
+ if (typeof envelope !== "object" || envelope === null || Array.isArray(envelope)) return [];
377
+ const rec = envelope as Record<string, unknown>;
378
+ if (rec["statusCodeValue"] !== undefined && rec["statusCodeValue"] !== 200) {
379
+ const status = typeof rec["statusCodeValue"] === "number" ? (rec["statusCodeValue"] as number) : 502;
380
+ // Qoder reports failures inside the stream envelope instead of as HTTP
381
+ // responses, so classify its structured provider code and status through
382
+ // the same gateway error policy as the other dispatch paths.
383
+ const detail = qoderEnvelopeMessage(rec);
384
+ const identifier = upstreamErrorIdentifier(rec["body"]) ?? upstreamErrorIdentifier(rec);
385
+ const classification = classifyUpstreamError(status, identifier);
386
+ throw new GatewayError(
387
+ classification.code,
388
+ classification.status,
389
+ detail.length > 0 ? detail : `Qoder stream envelope returned HTTP ${status}`,
390
+ {
391
+ providerId: QODER_PROVIDER_ID,
392
+ providerStatus: status,
393
+ ...(identifier ? { providerCode: identifier } : {}),
394
+ ...(classification.credentialEvidence ? { credentialEvidence: true } : {}),
395
+ ...(classification.rateLimitScope
396
+ ? { rateLimitScope: classification.rateLimitScope }
397
+ : {}),
398
+ },
399
+ classification.origin,
400
+ );
401
+ }
402
+ const body = rec["body"];
403
+ if (body === "[DONE]") return [{ event: null, data: "[DONE]" }];
404
+ if (typeof body !== "string") return [];
405
+ return [{ event: null, data: body.replace(/\r?\n/g, "") }];
406
+ }
407
+
408
+ function qoderStableHash(prefix: string, ...parts: string[]): string {
409
+ const h = createHash("sha256");
410
+ h.update(prefix);
411
+ for (const p of parts) {
412
+ h.update("\0");
413
+ h.update(p);
414
+ }
415
+ return h.digest("hex").slice(0, 16);
416
+ }
417
+
418
+ function flattenCanonicalContent(content: readonly ContentPart[]): string {
419
+ return content
420
+ .filter((b) => b.kind === "text" || b.kind === "toolResult")
421
+ .map((b) => {
422
+ if (b.kind === "text") return b.text;
423
+ if (b.kind === "toolResult") return typeof b.content === "string" ? b.content : JSON.stringify(b.content);
424
+ return "";
425
+ })
426
+ .join("\n");
427
+ }
428
+
429
+ function qoderStableRecordId(modelId: string, messages: CanonicalRequest["messages"], maxTokens: number): string {
430
+ const h = createHash("sha256");
431
+ h.update("qoder-record\0");
432
+ h.update(modelId);
433
+ for (const m of messages) {
434
+ h.update("\0");
435
+ h.update(m.role);
436
+ const text = flattenCanonicalContent(m.content);
437
+ if (text) {
438
+ h.update("\0");
439
+ h.update(text);
440
+ }
441
+ }
442
+ h.update(`\0mt=${maxTokens}`);
443
+ return h.digest("hex").slice(0, 16);
444
+ }
445
+
446
+ function qoderRequestedMaxTokens(request: CanonicalRequest, modelConfig: QoderModelConfig): number {
447
+ /**
448
+ * The ceiling is the roster's stated one. The 32k this used to fall back to
449
+ * clamped every model alike, so a request asking for more was silently
450
+ * lowered no matter which model it named.
451
+ */
452
+ const configured = typeof modelConfig.max_output_tokens === "number" ? modelConfig.max_output_tokens : 65_536;
453
+ const controls = request.generation_controls as Record<string, unknown>;
454
+ const requested =
455
+ typeof controls["max_tokens"] === "number"
456
+ ? (controls["max_tokens"] as number)
457
+ : typeof controls["max_output_tokens"] === "number"
458
+ ? (controls["max_output_tokens"] as number)
459
+ : null;
460
+ return typeof requested === "number" && requested > 0 ? Math.min(requested, configured) : configured;
461
+ }
462
+
463
+ export function buildQoderRequest(
464
+ modelId: string,
465
+ request: CanonicalRequest,
466
+ modelConfig: QoderModelConfig,
467
+ auth: QoderAuth,
468
+ ): Record<string, unknown> {
469
+ const allMessages = request.messages;
470
+ const systemParts: string[] = [];
471
+ if (request.system) {
472
+ for (const p of request.system) if (p.kind === "text") systemParts.push(p.text);
473
+ }
474
+ if (request.instructions) {
475
+ for (const p of request.instructions) if (p.kind === "text") systemParts.push(p.text);
476
+ }
477
+ for (const m of allMessages) {
478
+ if (m.role === "system" || m.role === "developer") {
479
+ const t = flattenCanonicalContent(m.content);
480
+ if (t) systemParts.push(t);
481
+ }
482
+ }
483
+ const systemPrompt = systemParts.join("\n\n").trim();
484
+ const qoderMessages: Array<Record<string, unknown>> = [];
485
+ if (MODERN_PROFILE.mirrorTopLevelSystem && systemPrompt.length > 0) {
486
+ qoderMessages.push({
487
+ role: "system",
488
+ content: systemPrompt,
489
+ contents: [{ type: "text", text: systemPrompt }],
490
+ });
491
+ }
492
+ for (const m of allMessages) {
493
+ if (m.role === "system" || m.role === "developer") continue;
494
+ // Answers may live in a `user` turn (the Messages ledger re-homes them),
495
+ // so the result scan is role-agnostic. Each result becomes its own `tool`
496
+ // turn carrying its `tool_call_id`; any non-result content on the same turn
497
+ // is emitted after, so nothing is duplicated or lost.
498
+ const results = toolResultParts(m);
499
+ if (results.length > 0) {
500
+ for (const block of results) {
501
+ const text = flattenCanonicalContent(
502
+ typeof block.content === "string"
503
+ ? [{ kind: "text", text: block.content }]
504
+ : block.content,
505
+ );
506
+ qoderMessages.push({
507
+ role: "tool",
508
+ content: text,
509
+ contents: [{ type: "text", text }],
510
+ tool_call_id: block.call_id,
511
+ });
512
+ }
513
+ const remaining = m.content.filter((part) => part.kind !== "toolResult");
514
+ if (remaining.length === 0) continue;
515
+ const flat = flattenCanonicalContent(remaining);
516
+ qoderMessages.push({
517
+ role: "user",
518
+ content: flat,
519
+ contents: [{ type: "text", text: flat }],
520
+ });
521
+ continue;
522
+ }
523
+ const flat = flattenCanonicalContent(m.content);
524
+ qoderMessages.push({
525
+ role: m.role === "assistant" ? "assistant" : "user",
526
+ content: flat,
527
+ contents: [{ type: "text", text: flat }],
528
+ });
529
+ }
530
+ const latestUserMessage = [...qoderMessages].reverse().find((m) => m["role"] === "user");
531
+ const latestUserText = typeof latestUserMessage?.["content"] === "string" ? (latestUserMessage["content"] as string) : "";
532
+ const maxTokens = qoderRequestedMaxTokens(request, modelConfig);
533
+ const reasoning = modelConfig.is_reasoning === true;
534
+ const sessionId = qoderStableHash("qoder-session", auth.userId, modelId);
535
+ const recordId = qoderStableRecordId(modelId, allMessages, maxTokens);
536
+ return {
537
+ request_id: randomUUID(),
538
+ request_set_id: recordId,
539
+ chat_record_id: recordId,
540
+ session_id: sessionId,
541
+ stream: true,
542
+ ...(MODERN_PROFILE.emptyAliyunUserType ? { aliyun_user_type: "" } : {}),
543
+ chat_task: "FREE_INPUT",
544
+ is_reply: true,
545
+ is_retry: false,
546
+ source: 1,
547
+ version: "3",
548
+ session_type: "qodercli",
549
+ agent_id: "agent_common",
550
+ task_id: "common",
551
+ code_language: "",
552
+ chat_prompt: MODERN_PROFILE.mirrorTopLevelSystem ? systemPrompt : "",
553
+ image_urls: null,
554
+ chat_context: {
555
+ chatPrompt: MODERN_PROFILE.mirrorTopLevelSystem ? systemPrompt : "",
556
+ imageUrls: null,
557
+ extra: { context: [], modelConfig: { key: modelId, is_reasoning: reasoning }, originalContent: latestUserText },
558
+ features: [],
559
+ text: latestUserText,
560
+ },
561
+ model_config: {
562
+ key: modelId,
563
+ display_name: modelConfig.display_name,
564
+ is_vl: modelConfig.is_vl,
565
+ is_reasoning: modelConfig.is_reasoning,
566
+ max_input_tokens: modelConfig.max_input_tokens,
567
+ // Mirrors the roster's stated ceiling. The 32k this used to fall back to
568
+ // was sent for every model alike, so the request declared a cap the
569
+ // catalog no longer publishes.
570
+ max_output_tokens: modelConfig.max_output_tokens ?? 65_536,
571
+ source: modelConfig.source ?? "system",
572
+ },
573
+ messages: qoderMessages,
574
+ max_tokens: maxTokens,
575
+ };
576
+ }
577
+
578
+ // Stream transformation — decode SSE, unwrap COSY envelope, map OpenAI chat chunks to CanonicalEvent
579
+
580
+ function mapQoderFinishReason(raw: unknown): CanonicalStopReason | undefined {
581
+ if (raw === "stop") return "stop";
582
+ if (raw === "length") return "length";
583
+ if (raw === "tool_calls") return "tool_use";
584
+ if (raw === "content_filter") return "content_filter";
585
+ return undefined;
586
+ }
587
+
588
+ async function* qoderBodyToCanonicalEvents(
589
+ body: ReadableStream<Uint8Array>,
590
+ signal: AbortSignal,
591
+ model: string,
592
+ ): AsyncIterable<CanonicalEvent> {
593
+ let seq = 1;
594
+ yield { type: "response_start", sequence_number: seq++, model } as CanonicalEvent;
595
+ let finishReason: unknown = undefined;
596
+ let rawUsage: Record<string, unknown> | undefined = undefined;
597
+ let hasTerminal = false;
598
+
599
+ for await (const sse of decodeSseEvents(body, { signal })) {
600
+ const sseData = sse.data;
601
+ let frames: Array<{ event: string | null; data: string }>;
602
+ try {
603
+ frames = qoderEnvelopeToFrames(sseData);
604
+ } catch (e) {
605
+ throw e;
606
+ }
607
+ for (const frame of frames) {
608
+ const data = frame.data.trim();
609
+ if (!data) continue;
610
+ if (data === "[DONE]") {
611
+ hasTerminal = true;
612
+ continue;
613
+ }
614
+ let json: Record<string, unknown>;
615
+ try {
616
+ json = JSON.parse(data) as Record<string, unknown>;
617
+ } catch {
618
+ continue;
619
+ }
620
+ if (json["usage"] && typeof json["usage"] === "object") rawUsage = json["usage"] as Record<string, unknown>;
621
+ const choices = (json["choices"] as Array<Record<string, unknown>>) ?? [];
622
+ for (const choice of choices) {
623
+ const delta = choice["delta"] as Record<string, unknown> | undefined;
624
+ if (delta) {
625
+ if (typeof delta["content"] === "string" && (delta["content"] as string).length > 0) {
626
+ yield {
627
+ type: "content_delta",
628
+ sequence_number: seq++,
629
+ content: { kind: "text", text: delta["content"] as string },
630
+ } as CanonicalEvent;
631
+ }
632
+ const reasoningText = readReasoningText(delta);
633
+ if (typeof reasoningText === "string" && reasoningText.length > 0) {
634
+ yield {
635
+ type: "content_delta",
636
+ sequence_number: seq++,
637
+ content: { kind: "reasoning", payload: null, summary: reasoningText },
638
+ } as CanonicalEvent;
639
+ }
640
+ const toolCalls = delta["tool_calls"] as Array<Record<string, unknown>> | undefined;
641
+ if (toolCalls) {
642
+ for (const tc of toolCalls) {
643
+ const fn = tc["function"] as Record<string, unknown> | undefined;
644
+ yield {
645
+ type: "tool_call_delta",
646
+ sequence_number: seq++,
647
+ call_id: (tc["id"] as string) ?? `call_${String(tc["index"] ?? 0)}`,
648
+ name: fn?.["name"] as string | undefined,
649
+ arguments_delta: (fn?.["arguments"] as string) ?? "",
650
+ } as CanonicalEvent;
651
+ }
652
+ }
653
+ }
654
+ const fr = choice["finish_reason"];
655
+ if (fr !== null && fr !== undefined) finishReason = fr;
656
+ // Some providers send usage in choices[0].usage or top-level
657
+ if (choice["usage"] && typeof choice["usage"] === "object") rawUsage = choice["usage"] as Record<string, unknown>;
658
+ }
659
+ // Some Qoder chunks carry finish_reason at top level
660
+ if (json["finish_reason"] !== undefined) finishReason = json["finish_reason"];
661
+ }
662
+ }
663
+ // If no terminal arrived, synthesize one (prevents truncation error)
664
+ const stopReason = mapQoderFinishReason(finishReason);
665
+ const _providerStop = typeof finishReason === "string" ? finishReason : undefined;
666
+ void hasTerminal;
667
+ yield {
668
+ type: "terminal",
669
+ sequence_number: seq++,
670
+ state: "complete",
671
+ ...(stopReason === undefined ? {} : { stop_reason: stopReason }),
672
+ ...(_providerStop === undefined ? {} : { provider_stop_reason: _providerStop }),
673
+ usage: usageFromProvider(rawUsage),
674
+ } as CanonicalEvent;
675
+ }
676
+
677
+ // Model catalog — maps QODER_MODEL_CONFIGS (provider) to Cartethyia ModelDefinition
678
+
679
+ /**
680
+ * The intl catalog this provider publishes.
681
+ *
682
+ * Previously built from the legacy `QODER_MODEL_CONFIGS`, which froze most
683
+ * rows at 180k while the upstream reports 1M for the same keys. That number is
684
+ * not cosmetic: it is sent upstream as `model_config.max_input_tokens`, so a
685
+ * stale low value told Qoder the conversation window was small and made it
686
+ * behave that way. Both the published catalog and the dispatched request now
687
+ * come from the realm's roster, which carries the upstream's own numbers.
688
+ */
689
+ export const QODER_MODELS: readonly ModelDefinition[] = QODER_INTL_MODELS;
690
+
691
+ // ProviderAdapter — manual dispatch preserving COSY encryption + envelope logic
692
+
693
+ interface QoderAdapterOptions {
694
+ readonly fetch?: typeof fetch;
695
+ /** Which deployment this adapter dispatches to. Defaults to intl. */
696
+ readonly realm?: QoderRealm;
697
+ /** Bundled provider id, so the adapter's own id matches the route's. */
698
+ readonly providerId?: string;
699
+ }
700
+
701
+ class QoderAdapter implements ProviderAdapter {
702
+ readonly provider_id: ProviderId;
703
+ private readonly realm: QoderRealm;
704
+ private readonly fetchFn: typeof fetch;
705
+
706
+ constructor(options: QoderAdapterOptions = {}) {
707
+ this.provider_id = (options.providerId ?? QODER_PROVIDER_ID) as ProviderId;
708
+ this.realm = options.realm ?? "intl";
709
+ this.fetchFn = options.fetch ?? globalThis.fetch;
710
+ }
711
+
712
+ /**
713
+ * The static roster for this adapter's realm.
714
+ *
715
+ * A single merged table advertised CN-only keys to global accounts and vice
716
+ * versa, so a request was routed to a deployment that refuses it.
717
+ */
718
+ #modelConfigs(): Record<string, QoderModelConfig> {
719
+ return (this.realm === "cn" ? QODER_CN_MODEL_CONFIGS : QODER_INTL_MODEL_CONFIGS) as Record<
720
+ string,
721
+ QoderModelConfig
722
+ >;
723
+ }
724
+
725
+ async *dispatch(
726
+ request: CanonicalRequest,
727
+ candidate: ProviderDispatchTarget,
728
+ context: ProviderDispatchContext,
729
+ ): AsyncIterable<CanonicalEvent> {
730
+ if (candidate.wire_family !== "chat") {
731
+ throw new GatewayError("capability_unsupported", 400, `qoder supports chat only, got ${candidate.wire_family}`);
732
+ }
733
+ const secret = readCredentialSecret(context.credential, "Qoder credential is required");
734
+
735
+ /**
736
+ * A caller-facing virtual name is translated to its roster key here.
737
+ *
738
+ * The translation has to happen before the config lookup and before the
739
+ * request body: the body carries the roster key, and looking up the
740
+ * virtual id in the config table would fall through to the synthetic
741
+ * default and silently dispatch under-declared capabilities.
742
+ */
743
+ const requestedModelId = candidate.model_id || request.model;
744
+ if (isQoderVirtualModel(requestedModelId) && !this.#modelConfigs()[qoderDispatchModelId(requestedModelId)]) {
745
+ throw new GatewayError(
746
+ "model_not_found",
747
+ 404,
748
+ `Qoder virtual model ${requestedModelId} resolves to a roster key this realm does not serve`,
749
+ { virtual_model: requestedModelId, target: qoderDispatchModelId(requestedModelId) },
750
+ "upstream",
751
+ );
752
+ }
753
+ const modelId = qoderDispatchModelId(requestedModelId);
754
+ const modelConfig = this.#modelConfigs()[modelId] ?? {
755
+ id: modelId,
756
+ display_name: modelId,
757
+ max_input_tokens: 180_000,
758
+ is_vl: true,
759
+ is_reasoning: false,
760
+ };
761
+
762
+ const lifecycle = createUpstreamDeadlineLifecycle(context);
763
+
764
+ // Outbound fetch respects SSRF binding when provided
765
+ const outboundFetch: typeof fetch = (context.outbound_fetch as unknown as typeof fetch) ?? this.fetchFn;
766
+
767
+ const fetcher: QoderFetcher = (url, init) =>
768
+ outboundFetch(url, { ...init, signal: lifecycle.signal } as RequestInit) as Promise<Response>;
769
+
770
+ try {
771
+ const version = getQoderVersion();
772
+ // Dual mode like Cline: a pasted PAT is exchanged for a job token per
773
+ // request, while an OAuth device token is used directly with the
774
+ // identity the login persisted.
775
+ const auth = isQoderPat(secret)
776
+ ? await exchangeQoderPat(secret, lifecycle.signal, fetcher, version, this.realm)
777
+ : qoderOAuthAuth(secret, context.credential.auth_state, context.credential.account_id);
778
+ const qoderBody = buildQoderRequest(modelId, request, modelConfig, auth);
779
+ // A full URL from the route wins, but the fallback is this realm's
780
+ // gateway — not the intl host hardcoded into `MODERN_PROFILE`. Dispatching
781
+ // a CN credential to `*.qoder.sh` is refused outright.
782
+ const url =
783
+ candidate.endpoint_path && candidate.endpoint_path.startsWith("http")
784
+ ? candidate.endpoint_path
785
+ : `${qoderGatewayCandidates(this.realm)[0] ?? ""}${QODER_CHAT_PATH}`;
786
+
787
+ const response = await callQoder(url, qoderBody, modelId, auth, lifecycle.signal, fetcher, version);
788
+ if (!response.ok) throw await mapUpstreamHttpError(response, "qoder");
789
+ if (!response.body) throw new GatewayError("platform_unavailable", 502, "Qoder returned empty body", {}, "upstream");
790
+ // Headers arrived: the pre-stream deadline has served its purpose.
791
+ // From here the gateway stall/first-chunk watchdog (propagated via
792
+ // context.abort_signal) governs the body. Keeping this timer armed
793
+ // would kill healthy long streams at the stale pre-stream deadline.
794
+ lifecycle.release();
795
+ yield* qoderBodyToCanonicalEvents(response.body as ReadableStream<Uint8Array>, lifecycle.signal, request.model);
796
+ } catch (err: unknown) {
797
+ const abortError = abortGatewayError(lifecycle, err, context.abort_signal);
798
+ if (abortError) throw abortError;
799
+ throw err;
800
+ } finally {
801
+ lifecycle.release();
802
+ }
803
+ }
804
+ }
805
+
806
+ export function createQoderAdapter(options: QoderAdapterOptions = {}): ProviderAdapter {
807
+ return new QoderAdapter(options);
808
+ }
809
+
810
+ /**
811
+ * Adapter for the China deployment.
812
+ *
813
+ * Same wire, different gateway host and roster — see `qoder-realm.ts`.
814
+ */
815
+ export function createQoderCnAdapter(options: QoderAdapterOptions = {}): ProviderAdapter {
816
+ return new QoderAdapter({ ...options, realm: "cn", providerId: "qodercn" });
817
+ }
818
+
819
+ /**
820
+ * A COSY signer for one already-resolved account identity.
821
+ *
822
+ * Discovery needs signed headers but lives in `qoder-catalog.ts`, which cannot
823
+ * import this module (the adapter imports its rosters — that would be a cycle).
824
+ * Exporting the signer keeps one signing implementation and lets discovery
825
+ * stay pure and injectable.
826
+ */
827
+ export function qoderSignerFor(
828
+ auth: QoderAuth,
829
+ version = getQoderVersion(),
830
+ ): (url: string, body: string) => Record<string, string> {
831
+ return (url: string, body: string): Record<string, string> =>
832
+ qoderBuildCosyHeaders(Buffer.from(body, "latin1"), url, auth, version);
833
+ }
834
+
835
+ /** Qoder's own base64 alphabet transform, for a request body. */
836
+ export function qoderEncodeBody(plaintext: Uint8Array | string): string {
837
+ const text = typeof plaintext === "string" ? plaintext : new TextDecoder().decode(plaintext);
838
+ return Buffer.from(transformQoderBody(text)).toString("latin1");
839
+ }
840
+
841
+ /**
842
+ * Resolves the dispatch identity for one Qoder credential.
843
+ *
844
+ * Shared by the adapter and by discovery: both need the same `QoderAuth` the
845
+ * COSY signature is built from, and duplicating the PAT-vs-OAuth branch would
846
+ * let the two drift.
847
+ */
848
+ export async function resolveQoderAuth(input: {
849
+ readonly secret: string;
850
+ readonly authState: unknown;
851
+ readonly signal: AbortSignal;
852
+ readonly fetcher: (url: string, init: RequestInit) => Promise<Response>;
853
+ /** Which deployment mints the job token; a PAT is realm-bound. */
854
+ readonly realm?: QoderRealm;
855
+ }): Promise<QoderAuth> {
856
+ const realm = input.realm ?? "intl";
857
+ if (isQoderPat(input.secret)) {
858
+ return await exchangeQoderPat(input.secret, input.signal, input.fetcher, getQoderVersion(), realm);
859
+ }
860
+ // Discovery is handed only the secret and the persisted state, so the
861
+ // account id is read from that state — the same place `qoderOAuthAuth` reads
862
+ // it — rather than being a separate field callers can pass wrongly.
863
+ const state = parseQoderOAuthState(input.authState);
864
+ return qoderOAuthAuth(input.secret, input.authState, state?.userId);
865
+ }