swayrouter 1.0.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 (643) hide show
  1. package/.env.example +43 -0
  2. package/CHANGELOG.md +132 -0
  3. package/LICENSE +30 -0
  4. package/README.id.md +633 -0
  5. package/README.md +628 -0
  6. package/cli/cli.js +388 -0
  7. package/cli/package.json +4 -0
  8. package/cli/src/cli/commands/xaiVideo.js +280 -0
  9. package/cli/src/cli/tray/SwayAvatar.svg +20 -0
  10. package/cli/src/cli/tray/autostart.js +351 -0
  11. package/cli/src/cli/tray/icon.ico +0 -0
  12. package/cli/src/cli/tray/icon.png +0 -0
  13. package/cli/src/cli/tray/tray.js +258 -0
  14. package/cli/src/cli/tray/tray.ps1 +129 -0
  15. package/cli/src/cli/tray/trayHost.js +157 -0
  16. package/cli/src/cli/tray/trayWin.js +83 -0
  17. package/cli/src/cli/utils/display.js +123 -0
  18. package/cli/src/cli/utils/input.js +138 -0
  19. package/cli/src/runtime/discover.js +153 -0
  20. package/cli/src/runtime/lifecycle.js +333 -0
  21. package/cli/src/runtime/runMenu.js +250 -0
  22. package/cli/src/runtime/uiAdapters.js +12 -0
  23. package/cli/src/runtime/update.js +130 -0
  24. package/dashboard/dist/assets/CliTools-Ch3gKuNw.js +24 -0
  25. package/dashboard/dist/assets/Combo-BBCldjWi.js +1 -0
  26. package/dashboard/dist/assets/ConsoleLog-wywAYcPT.js +6 -0
  27. package/dashboard/dist/assets/Dashboard-DxzyF41b.js +1 -0
  28. package/dashboard/dist/assets/Header-C_9Su9BF.js +1 -0
  29. package/dashboard/dist/assets/Keys-D0ufgcsc.js +1 -0
  30. package/dashboard/dist/assets/Login-BeKpipS_.js +1 -0
  31. package/dashboard/dist/assets/ManageApiKey-CVXsmW2B.js +1 -0
  32. package/dashboard/dist/assets/OAuthCallback-D_UZYcF6.js +1 -0
  33. package/dashboard/dist/assets/Provider-BU7JfTqm.js +4 -0
  34. package/dashboard/dist/assets/ProviderModelAccordion-BAifkfVR.js +1 -0
  35. package/dashboard/dist/assets/Proxy-CU15VJ--.js +1 -0
  36. package/dashboard/dist/assets/QuotaMonitor-HzGK7bcc.js +1 -0
  37. package/dashboard/dist/assets/Settings-Dt4y2dC0.js +1 -0
  38. package/dashboard/dist/assets/Setup-DSDUwU7N.js +1 -0
  39. package/dashboard/dist/assets/StatusBadge-1nAOyHU2.js +1 -0
  40. package/dashboard/dist/assets/SwayChat-Bup7up6D.js +10 -0
  41. package/dashboard/dist/assets/Usage-eWnrPQ_v.js +4 -0
  42. package/dashboard/dist/assets/accordion-DOOPDDgt.js +1 -0
  43. package/dashboard/dist/assets/admin-extras-api-CCdu5TFM.js +1 -0
  44. package/dashboard/dist/assets/api-keys-api-ifAC2Ok3.js +1 -0
  45. package/dashboard/dist/assets/card-CC0Omjcv.js +1 -0
  46. package/dashboard/dist/assets/chatStudio-C0zPz_Z_.js +2 -0
  47. package/dashboard/dist/assets/checkbox-7SZBrmbN.js +1 -0
  48. package/dashboard/dist/assets/connections-api-_N54UD3S.js +1 -0
  49. package/dashboard/dist/assets/copy-button-qBvM6H9z.js +1 -0
  50. package/dashboard/dist/assets/currency-api-SV9CBf5e.js +1 -0
  51. package/dashboard/dist/assets/flip-button-BGgkjtl0.js +1 -0
  52. package/dashboard/dist/assets/frame-cUiti6Lq.js +1 -0
  53. package/dashboard/dist/assets/icons-vendor-CUx7SB5V.js +541 -0
  54. package/dashboard/dist/assets/index-B6j-9zHy.js +10 -0
  55. package/dashboard/dist/assets/index-C-_l0yYz.css +1 -0
  56. package/dashboard/dist/assets/live-mode-CHShLY4E.js +1 -0
  57. package/dashboard/dist/assets/markdown-vendor-BY8e1gQ8.js +29 -0
  58. package/dashboard/dist/assets/motion-vendor-g5fpGzmJ.js +9 -0
  59. package/dashboard/dist/assets/oauth-callback-CqYQzyd7.js +1 -0
  60. package/dashboard/dist/assets/query-vendor-DVevaSVS.js +1 -0
  61. package/dashboard/dist/assets/react-vendor-xnYrwzsL.js +61 -0
  62. package/dashboard/dist/assets/ripple-button-l8aMiVVG.js +1 -0
  63. package/dashboard/dist/assets/segmented-CqmEnQjZ.js +1 -0
  64. package/dashboard/dist/assets/select-D8pUtMXp.js +1 -0
  65. package/dashboard/dist/assets/skeleton-7uJDiIXe.js +1 -0
  66. package/dashboard/dist/assets/table-D0M60Tu1.js +1 -0
  67. package/dashboard/dist/assets/tabs-C6YkuulG.js +1 -0
  68. package/dashboard/dist/assets/tunnel-api-DDPsBaDV.js +1 -0
  69. package/dashboard/dist/assets/ui-vendor-BuM9f2NY.js +17 -0
  70. package/dashboard/dist/image2/SwayAvatar.svg +20 -0
  71. package/dashboard/dist/index.html +32 -0
  72. package/dashboard/dist/logo/avatar.svg +1 -0
  73. package/dashboard/dist/logo/sway.svg +20 -0
  74. package/dashboard/dist/logo/swaychat.svg +20 -0
  75. package/dashboard/dist/providers/SwayCustom.svg +19 -0
  76. package/dashboard/dist/providers/alicode.svg +12 -0
  77. package/dashboard/dist/providers/anthropic.svg +11 -0
  78. package/dashboard/dist/providers/antigravity.svg +3 -0
  79. package/dashboard/dist/providers/azure.svg +5 -0
  80. package/dashboard/dist/providers/baidu.svg +3 -0
  81. package/dashboard/dist/providers/blackbox.svg +5 -0
  82. package/dashboard/dist/providers/byteplus.svg +3 -0
  83. package/dashboard/dist/providers/cerebras.svg +4 -0
  84. package/dashboard/dist/providers/chutes.svg +4 -0
  85. package/dashboard/dist/providers/claude.svg +3 -0
  86. package/dashboard/dist/providers/cline.svg +11 -0
  87. package/dashboard/dist/providers/cloudflare-ai.svg +4 -0
  88. package/dashboard/dist/providers/codebuddy.svg +11 -0
  89. package/dashboard/dist/providers/codex.svg +10 -0
  90. package/dashboard/dist/providers/commandcode.svg +3 -0
  91. package/dashboard/dist/providers/cursor.svg +3 -0
  92. package/dashboard/dist/providers/deepseek.svg +10 -0
  93. package/dashboard/dist/providers/featherless.svg +3 -0
  94. package/dashboard/dist/providers/fireworks.svg +3 -0
  95. package/dashboard/dist/providers/gemini.svg +3 -0
  96. package/dashboard/dist/providers/geminicli.svg +11 -0
  97. package/dashboard/dist/providers/github.svg +3 -0
  98. package/dashboard/dist/providers/grok.svg +3 -0
  99. package/dashboard/dist/providers/groq.svg +3 -0
  100. package/dashboard/dist/providers/hermesagent.svg +1 -0
  101. package/dashboard/dist/providers/kilocode.svg +15 -0
  102. package/dashboard/dist/providers/kimchi.svg +3 -0
  103. package/dashboard/dist/providers/kimi.svg +4 -0
  104. package/dashboard/dist/providers/kiro.svg +10 -0
  105. package/dashboard/dist/providers/meta.svg +3 -0
  106. package/dashboard/dist/providers/mimo.svg +10 -0
  107. package/dashboard/dist/providers/minimax.svg +3 -0
  108. package/dashboard/dist/providers/mistral.svg +3 -0
  109. package/dashboard/dist/providers/morph.svg +3 -0
  110. package/dashboard/dist/providers/nebius.svg +4 -0
  111. package/dashboard/dist/providers/nvidia.svg +3 -0
  112. package/dashboard/dist/providers/ollama.svg +3 -0
  113. package/dashboard/dist/providers/omp.svg +5 -0
  114. package/dashboard/dist/providers/openai.svg +3 -0
  115. package/dashboard/dist/providers/opencode.svg +3 -0
  116. package/dashboard/dist/providers/openrouter.svg +3 -0
  117. package/dashboard/dist/providers/perplexity.svg +3 -0
  118. package/dashboard/dist/providers/poolside.svg +36 -0
  119. package/dashboard/dist/providers/qoder.svg +11 -0
  120. package/dashboard/dist/providers/sumopod.svg +3 -0
  121. package/dashboard/dist/providers/tencent.svg +5 -0
  122. package/dashboard/dist/providers/together.svg +12 -0
  123. package/dashboard/dist/providers/trae.svg +3 -0
  124. package/dashboard/dist/providers/venice.svg +4 -0
  125. package/dashboard/dist/providers/vercel.svg +3 -0
  126. package/dashboard/dist/providers/vertex.svg +17 -0
  127. package/dashboard/dist/providers/windsurf.svg +10 -0
  128. package/dashboard/dist/providers/zai.svg +3 -0
  129. package/dashboard/tsconfig.json +13 -0
  130. package/package.json +87 -0
  131. package/src/config/appConstants.js +153 -0
  132. package/src/config/defaultThinkingSignature.js +7 -0
  133. package/src/config/errorConfig.js +117 -0
  134. package/src/config/grokCli.js +9 -0
  135. package/src/config/kiroConstants.js +235 -0
  136. package/src/config/mediaConfig.js +20 -0
  137. package/src/config/ollamaModels.js +18 -0
  138. package/src/config/providerModels.js +109 -0
  139. package/src/config/providers.js +17 -0
  140. package/src/config/runtimeConfig.js +84 -0
  141. package/src/dashboardGuard.js +254 -0
  142. package/src/executors/antigravity.js +389 -0
  143. package/src/executors/azure.js +49 -0
  144. package/src/executors/base.js +225 -0
  145. package/src/executors/codebuddy-cn.js +23 -0
  146. package/src/executors/codebuddy-intl.js +60 -0
  147. package/src/executors/codex.js +436 -0
  148. package/src/executors/commandcode.js +83 -0
  149. package/src/executors/cursor.js +1075 -0
  150. package/src/executors/default.js +294 -0
  151. package/src/executors/gemini-cli.js +88 -0
  152. package/src/executors/github.js +393 -0
  153. package/src/executors/grok-cli.js +510 -0
  154. package/src/executors/grok-web.js +342 -0
  155. package/src/executors/index.js +86 -0
  156. package/src/executors/kimchi.js +116 -0
  157. package/src/executors/kiro.js +1155 -0
  158. package/src/executors/ollama-local.js +14 -0
  159. package/src/executors/opencode-go.js +47 -0
  160. package/src/executors/opencode.js +31 -0
  161. package/src/executors/qoder.js +433 -0
  162. package/src/executors/trae.js +318 -0
  163. package/src/executors/vertex.js +151 -0
  164. package/src/executors/windsurf.js +555 -0
  165. package/src/executors/xiaomi-tokenplan.js +16 -0
  166. package/src/handlers/chatCore/nonStreamingHandler.js +370 -0
  167. package/src/handlers/chatCore/requestDetail.js +130 -0
  168. package/src/handlers/chatCore/sseToJsonHandler.js +318 -0
  169. package/src/handlers/chatCore/streamingHandler.js +250 -0
  170. package/src/handlers/chatCore.js +652 -0
  171. package/src/lib/auth/dashboardSession.js +83 -0
  172. package/src/lib/auth/loginLimiter.js +99 -0
  173. package/src/lib/cache/ttlCache.js +153 -0
  174. package/src/lib/consoleLogBuffer.js +127 -0
  175. package/src/lib/dataDir.js +45 -0
  176. package/src/lib/db/adapters/betterSqliteAdapter.js +36 -0
  177. package/src/lib/db/adapters/bunSqliteAdapter.js +47 -0
  178. package/src/lib/db/adapters/nodeSqliteAdapter.js +65 -0
  179. package/src/lib/db/adapters/runtimeHelpers.js +23 -0
  180. package/src/lib/db/adapters/sqljsAdapter.js +103 -0
  181. package/src/lib/db/backup.js +75 -0
  182. package/src/lib/db/driver.js +110 -0
  183. package/src/lib/db/helpers/jsonCol.js +18 -0
  184. package/src/lib/db/helpers/kvStore.js +48 -0
  185. package/src/lib/db/helpers/metaStore.js +32 -0
  186. package/src/lib/db/index.js +473 -0
  187. package/src/lib/db/migrate.js +267 -0
  188. package/src/lib/db/migrations/001-initial.js +12 -0
  189. package/src/lib/db/migrations/002-prune-headroom-pxpipe-settings.js +32 -0
  190. package/src/lib/db/migrations/004-request-details-trace-id.js +12 -0
  191. package/src/lib/db/migrations/005-request-details-payload-capture.js +11 -0
  192. package/src/lib/db/migrations/007-headroom-readd-settings.js +35 -0
  193. package/src/lib/db/migrations/008-account-model-locks.js +22 -0
  194. package/src/lib/db/migrations/009-warp-pool-lifecycle.js +5 -0
  195. package/src/lib/db/migrations/010-api-key-file-permissions.js +7 -0
  196. package/src/lib/db/migrations/011-remove-upstream-user-agent-profile.js +41 -0
  197. package/src/lib/db/migrations/012-remove-headroom-settings.js +33 -0
  198. package/src/lib/db/migrations/013-default-fill-first-routing.js +20 -0
  199. package/src/lib/db/migrations/014-normalize-fill-first-routing.js +37 -0
  200. package/src/lib/db/migrations/015-remove-ip-ban-tables.js +8 -0
  201. package/src/lib/db/migrations/016-prune-legacy-codebuddy-intl-models.js +25 -0
  202. package/src/lib/db/migrations/index.js +20 -0
  203. package/src/lib/db/nineRouterMigration.js +785 -0
  204. package/src/lib/db/paths.js +23 -0
  205. package/src/lib/db/repos/accountModelLocksRepo.js +74 -0
  206. package/src/lib/db/repos/aliasRepo.js +108 -0
  207. package/src/lib/db/repos/apiKeysRepo.js +204 -0
  208. package/src/lib/db/repos/combosRepo.js +85 -0
  209. package/src/lib/db/repos/connectionsRepo.js +522 -0
  210. package/src/lib/db/repos/disabledModelsRepo.js +63 -0
  211. package/src/lib/db/repos/nodesRepo.js +127 -0
  212. package/src/lib/db/repos/pricingRepo.js +108 -0
  213. package/src/lib/db/repos/proxyPoolsRepo.js +104 -0
  214. package/src/lib/db/repos/requestDetailsRepo.js +345 -0
  215. package/src/lib/db/repos/settingsRepo.js +135 -0
  216. package/src/lib/db/repos/usageRepo.js +1335 -0
  217. package/src/lib/db/schema.js +179 -0
  218. package/src/lib/db/version.js +32 -0
  219. package/src/lib/db/writeBehind.js +174 -0
  220. package/src/lib/disabledModelsDb.js +3 -0
  221. package/src/lib/env.ts +175 -0
  222. package/src/lib/errors/publicError.js +18 -0
  223. package/src/lib/grokBuildConfig.js +243 -0
  224. package/src/lib/guardRequest.js +51 -0
  225. package/src/lib/localDb.js +21 -0
  226. package/src/lib/mcp/stdioSseBridge.js +174 -0
  227. package/src/lib/network/connectionProxy.js +200 -0
  228. package/src/lib/network/proxyTest.js +158 -0
  229. package/src/lib/network/proxyUrl.js +76 -0
  230. package/src/lib/network/relay.js +71 -0
  231. package/src/lib/oauth/constants/oauth.js +152 -0
  232. package/src/lib/oauth/constants/xai.js +43 -0
  233. package/src/lib/oauth/kiroExternalIdp.js +167 -0
  234. package/src/lib/oauth/providerHelpers.js +90 -0
  235. package/src/lib/oauth/providers/_shared.js +12 -0
  236. package/src/lib/oauth/providers/antigravity.js +126 -0
  237. package/src/lib/oauth/providers/claude.js +60 -0
  238. package/src/lib/oauth/providers/cline.js +62 -0
  239. package/src/lib/oauth/providers/clinepass.js +62 -0
  240. package/src/lib/oauth/providers/codebuddy-cn.js +75 -0
  241. package/src/lib/oauth/providers/codebuddy-intl.js +73 -0
  242. package/src/lib/oauth/providers/codex.js +72 -0
  243. package/src/lib/oauth/providers/cursor.js +18 -0
  244. package/src/lib/oauth/providers/gemini-cli.js +84 -0
  245. package/src/lib/oauth/providers/github.js +96 -0
  246. package/src/lib/oauth/providers/grok-cli.js +123 -0
  247. package/src/lib/oauth/providers/index.js +233 -0
  248. package/src/lib/oauth/providers/kilocode.js +60 -0
  249. package/src/lib/oauth/providers/kimchi.js +79 -0
  250. package/src/lib/oauth/providers/kimi.js +79 -0
  251. package/src/lib/oauth/providers/kiro.js +147 -0
  252. package/src/lib/oauth/providers/qoder.js +90 -0
  253. package/src/lib/oauth/providers/trae.js +244 -0
  254. package/src/lib/oauth/providers/windsurf.js +123 -0
  255. package/src/lib/oauth/providers/xai.js +95 -0
  256. package/src/lib/oauth/providers.js +16 -0
  257. package/src/lib/oauth/services/cursor.js +132 -0
  258. package/src/lib/oauth/services/kiro.js +351 -0
  259. package/src/lib/oauth/services/oauth.js +135 -0
  260. package/src/lib/oauth/services/qoder.js +151 -0
  261. package/src/lib/oauth/services/xai.js +204 -0
  262. package/src/lib/oauth/utils/ideDetect.js +55 -0
  263. package/src/lib/oauth/utils/pkce.js +25 -0
  264. package/src/lib/oauth/utils/server.js +732 -0
  265. package/src/lib/oauth/utils/ui.js +43 -0
  266. package/src/lib/providerNormalization.js +40 -0
  267. package/src/lib/qoder/constants.js +1 -0
  268. package/src/lib/requestDetailsDb.js +3 -0
  269. package/src/lib/resourceProfile.ts +124 -0
  270. package/src/lib/runtimeSecrets.ts +130 -0
  271. package/src/lib/security/payloadCapture.js +87 -0
  272. package/src/lib/tunnel/cloudflare/cloudflared.js +436 -0
  273. package/src/lib/tunnel/cloudflare/config.js +8 -0
  274. package/src/lib/tunnel/cloudflare/healthCheck.js +37 -0
  275. package/src/lib/tunnel/cloudflare/manager.js +149 -0
  276. package/src/lib/tunnel/cloudflare/pid.js +31 -0
  277. package/src/lib/tunnel/cloudflare/publicUrl.js +41 -0
  278. package/src/lib/tunnel/cloudflare/requirements.js +12 -0
  279. package/src/lib/tunnel/index.js +26 -0
  280. package/src/lib/tunnel/shared/dnsResolver.js +16 -0
  281. package/src/lib/tunnel/shared/internetCheck.js +30 -0
  282. package/src/lib/tunnel/shared/state.js +45 -0
  283. package/src/lib/tunnel/shared/watchdogConfig.js +6 -0
  284. package/src/lib/update/installer.js +52 -0
  285. package/src/lib/update/version.js +116 -0
  286. package/src/lib/usageDb.js +6 -0
  287. package/src/lib/usageRefresh.js +88 -0
  288. package/src/lifecycle/appLifecycle.ts +99 -0
  289. package/src/models.js +36 -0
  290. package/src/next/headers.js +12 -0
  291. package/src/next/server.js +74 -0
  292. package/src/observability/metrics.js +439 -0
  293. package/src/observability/tracing.js +107 -0
  294. package/src/open-sse-index.js +70 -0
  295. package/src/providers/capabilities.js +299 -0
  296. package/src/providers/display.ts +142 -0
  297. package/src/providers/index.js +27 -0
  298. package/src/providers/models/helpers.js +19 -0
  299. package/src/providers/models/namePatterns.js +27 -0
  300. package/src/providers/models/schema.js +32 -0
  301. package/src/providers/pricing.js +248 -0
  302. package/src/providers/registry/agentrouter.js +52 -0
  303. package/src/providers/registry/alicode-intl.js +32 -0
  304. package/src/providers/registry/alicode.js +33 -0
  305. package/src/providers/registry/alims-intl.js +30 -0
  306. package/src/providers/registry/anthropic.js +29 -0
  307. package/src/providers/registry/antigravity.js +139 -0
  308. package/src/providers/registry/azure.js +23 -0
  309. package/src/providers/registry/baidu.js +35 -0
  310. package/src/providers/registry/blackbox.js +41 -0
  311. package/src/providers/registry/byteplus.js +36 -0
  312. package/src/providers/registry/cerebras.js +33 -0
  313. package/src/providers/registry/chutes.js +26 -0
  314. package/src/providers/registry/claude.js +80 -0
  315. package/src/providers/registry/cline.js +53 -0
  316. package/src/providers/registry/clinepass.js +62 -0
  317. package/src/providers/registry/cloudflare-ai.js +84 -0
  318. package/src/providers/registry/codebuddy-cn.js +95 -0
  319. package/src/providers/registry/codebuddy-intl.js +91 -0
  320. package/src/providers/registry/codex.js +145 -0
  321. package/src/providers/registry/commandcode.js +45 -0
  322. package/src/providers/registry/cursor.js +61 -0
  323. package/src/providers/registry/deepseek.js +55 -0
  324. package/src/providers/registry/featherless.js +36 -0
  325. package/src/providers/registry/fireworks.js +34 -0
  326. package/src/providers/registry/gemini-cli.js +59 -0
  327. package/src/providers/registry/gemini.js +76 -0
  328. package/src/providers/registry/github.js +131 -0
  329. package/src/providers/registry/glm-cn.js +35 -0
  330. package/src/providers/registry/glm.js +58 -0
  331. package/src/providers/registry/grok-cli.js +87 -0
  332. package/src/providers/registry/grok-web.js +41 -0
  333. package/src/providers/registry/groq.js +38 -0
  334. package/src/providers/registry/index.js +77 -0
  335. package/src/providers/registry/kilo-gateway.js +34 -0
  336. package/src/providers/registry/kilocode.js +48 -0
  337. package/src/providers/registry/kimchi.js +49 -0
  338. package/src/providers/registry/kimi.js +82 -0
  339. package/src/providers/registry/kiro.js +132 -0
  340. package/src/providers/registry/meta.js +34 -0
  341. package/src/providers/registry/minimax-cn.js +90 -0
  342. package/src/providers/registry/minimax.js +90 -0
  343. package/src/providers/registry/mistral.js +36 -0
  344. package/src/providers/registry/morph.js +31 -0
  345. package/src/providers/registry/nebius.js +26 -0
  346. package/src/providers/registry/nvidia.js +55 -0
  347. package/src/providers/registry/ollama-local.js +18 -0
  348. package/src/providers/registry/ollama.js +38 -0
  349. package/src/providers/registry/openai.js +114 -0
  350. package/src/providers/registry/opencode-go.js +41 -0
  351. package/src/providers/registry/opencode.js +26 -0
  352. package/src/providers/registry/openrouter.js +36 -0
  353. package/src/providers/registry/perplexity.js +56 -0
  354. package/src/providers/registry/poolside.js +30 -0
  355. package/src/providers/registry/qoder.js +58 -0
  356. package/src/providers/registry/sumopod.js +84 -0
  357. package/src/providers/registry/tencent.js +29 -0
  358. package/src/providers/registry/together.js +38 -0
  359. package/src/providers/registry/trae.js +71 -0
  360. package/src/providers/registry/venice.js +69 -0
  361. package/src/providers/registry/vercel-ai-gateway.js +37 -0
  362. package/src/providers/registry/vertex-partner.js +31 -0
  363. package/src/providers/registry/vertex.js +33 -0
  364. package/src/providers/registry/windsurf.js +129 -0
  365. package/src/providers/registry/xai.js +46 -0
  366. package/src/providers/registry/xiaomi-mimo.js +66 -0
  367. package/src/providers/registry/xiaomi-tokenplan.js +58 -0
  368. package/src/providers/registryEntry.js +3 -0
  369. package/src/providers/schema.js +33 -0
  370. package/src/providers/shared.js +114 -0
  371. package/src/providers/thinkingLevels.js +49 -0
  372. package/src/routes/api/auth/login/route.js +82 -0
  373. package/src/routes/api/auth/logout/route.js +9 -0
  374. package/src/routes/api/auth/reset-password/route.js +12 -0
  375. package/src/routes/api/auth/status/route.js +33 -0
  376. package/src/routes/api/auth/verify-password/route.js +39 -0
  377. package/src/routes/api/chat/tools/curl/route.js +100 -0
  378. package/src/routes/api/chat/tools/router/route.js +215 -0
  379. package/src/routes/api/chat/tools/search/route.js +362 -0
  380. package/src/routes/api/chat/tools/shell/route.js +228 -0
  381. package/src/routes/api/cli-tools/all-statuses/route.js +37 -0
  382. package/src/routes/api/cli-tools/claude-settings/route.js +261 -0
  383. package/src/routes/api/cli-tools/codex-settings/route.js +220 -0
  384. package/src/routes/api/cli-tools/cowork-mcp-registry/route.js +80 -0
  385. package/src/routes/api/cli-tools/cowork-mcp-tools/route.js +96 -0
  386. package/src/routes/api/cli-tools/cowork-settings/route.js +380 -0
  387. package/src/routes/api/cli-tools/grok-build-settings/route.js +152 -0
  388. package/src/routes/api/cli-tools/hermes-settings/route.js +169 -0
  389. package/src/routes/api/cli-tools/kilo-settings/route.js +131 -0
  390. package/src/routes/api/cli-tools/model-mappings/route.js +43 -0
  391. package/src/routes/api/cli-tools/omp-settings/route.js +266 -0
  392. package/src/routes/api/cli-tools/opencode-settings/route.js +243 -0
  393. package/src/routes/api/combos/[id]/route.js +73 -0
  394. package/src/routes/api/combos/route.js +43 -0
  395. package/src/routes/api/health/live/route.js +7 -0
  396. package/src/routes/api/health/ready/route.js +19 -0
  397. package/src/routes/api/health/route.js +17 -0
  398. package/src/routes/api/inflight/stream/route.js +24 -0
  399. package/src/routes/api/init/route.js +3 -0
  400. package/src/routes/api/keys/[id]/route.js +71 -0
  401. package/src/routes/api/keys/route.js +41 -0
  402. package/src/routes/api/logs/route.js +19 -0
  403. package/src/routes/api/mcp/[plugin]/message/route.js +23 -0
  404. package/src/routes/api/mcp/[plugin]/sse/route.js +35 -0
  405. package/src/routes/api/models/availability/route.js +104 -0
  406. package/src/routes/api/models/custom/route.js +58 -0
  407. package/src/routes/api/models/disabled/route.js +47 -0
  408. package/src/routes/api/models/route.js +64 -0
  409. package/src/routes/api/models/test/ping.js +236 -0
  410. package/src/routes/api/models/test/route.js +14 -0
  411. package/src/routes/api/oauth/[provider]/[action]/route.js +491 -0
  412. package/src/routes/api/oauth/codex/bulk-import/route.js +105 -0
  413. package/src/routes/api/oauth/codex/import-token/route.js +82 -0
  414. package/src/routes/api/oauth/cursor/auto-import/route.js +250 -0
  415. package/src/routes/api/oauth/cursor/import/route.js +86 -0
  416. package/src/routes/api/oauth/kiro/api-key/route.js +60 -0
  417. package/src/routes/api/oauth/kiro/auto-import/route.js +120 -0
  418. package/src/routes/api/oauth/kiro/import/route.js +72 -0
  419. package/src/routes/api/oauth/kiro/import-cli-proxy/route.js +42 -0
  420. package/src/routes/api/oauth/kiro/social-authorize/route.js +40 -0
  421. package/src/routes/api/oauth/kiro/social-exchange/route.js +62 -0
  422. package/src/routes/api/pricing/route.js +96 -0
  423. package/src/routes/api/provider-nodes/[id]/route.js +106 -0
  424. package/src/routes/api/provider-nodes/route.js +110 -0
  425. package/src/routes/api/provider-nodes/validate/route.js +197 -0
  426. package/src/routes/api/providers/[id]/models/route.js +716 -0
  427. package/src/routes/api/providers/[id]/route.js +195 -0
  428. package/src/routes/api/providers/[id]/test/route.js +27 -0
  429. package/src/routes/api/providers/[id]/test/testUtils.js +912 -0
  430. package/src/routes/api/providers/[id]/test-models/route.js +211 -0
  431. package/src/routes/api/providers/catalog/route.js +58 -0
  432. package/src/routes/api/providers/client/route.js +133 -0
  433. package/src/routes/api/providers/counts/route.js +43 -0
  434. package/src/routes/api/providers/kilo/free-models/route.js +58 -0
  435. package/src/routes/api/providers/route.js +361 -0
  436. package/src/routes/api/providers/suggested-models/filters.js +24 -0
  437. package/src/routes/api/providers/suggested-models/route.js +34 -0
  438. package/src/routes/api/providers/test-batch/route.js +145 -0
  439. package/src/routes/api/providers/validate/route.js +633 -0
  440. package/src/routes/api/proxy-pools/[id]/route.js +129 -0
  441. package/src/routes/api/proxy-pools/[id]/test/route.js +64 -0
  442. package/src/routes/api/proxy-pools/cloudflare-deploy/route.js +183 -0
  443. package/src/routes/api/proxy-pools/route.js +85 -0
  444. package/src/routes/api/proxy-pools/vercel-deploy/route.js +181 -0
  445. package/src/routes/api/settings/currency/route.js +29 -0
  446. package/src/routes/api/settings/database/path/route.js +8 -0
  447. package/src/routes/api/settings/database/route.js +89 -0
  448. package/src/routes/api/settings/migrate-9router/route.js +81 -0
  449. package/src/routes/api/settings/require-login/route.js +14 -0
  450. package/src/routes/api/settings/route.js +186 -0
  451. package/src/routes/api/shutdown/route.js +25 -0
  452. package/src/routes/api/tags/route.js +17 -0
  453. package/src/routes/api/translator/console-logs/route.js +28 -0
  454. package/src/routes/api/translator/console-logs/stream/route.js +95 -0
  455. package/src/routes/api/tunnel/disable/route.js +18 -0
  456. package/src/routes/api/tunnel/enable/route.js +32 -0
  457. package/src/routes/api/tunnel/status/route.js +23 -0
  458. package/src/routes/api/update/route.js +42 -0
  459. package/src/routes/api/usage/[connectionId]/codex-reset-credits/route.js +169 -0
  460. package/src/routes/api/usage/[connectionId]/route.js +222 -0
  461. package/src/routes/api/usage/chart/route.js +27 -0
  462. package/src/routes/api/usage/history/route.js +94 -0
  463. package/src/routes/api/usage/logs/route.js +14 -0
  464. package/src/routes/api/usage/providers/route.js +36 -0
  465. package/src/routes/api/usage/request-details/route.js +61 -0
  466. package/src/routes/api/usage/request-logs/route.js +15 -0
  467. package/src/routes/api/usage/stats/route.js +23 -0
  468. package/src/routes/api/usage/stream/route.js +78 -0
  469. package/src/routes/api/v1/api/chat/route.js +36 -0
  470. package/src/routes/api/v1/chat/completions/route.js +28 -0
  471. package/src/routes/api/v1/images/edits/route.js +70 -0
  472. package/src/routes/api/v1/images/generations/route.js +50 -0
  473. package/src/routes/api/v1/images/imageValidation.js +45 -0
  474. package/src/routes/api/v1/messages/count_tokens/route.js +87 -0
  475. package/src/routes/api/v1/messages/route.js +26 -0
  476. package/src/routes/api/v1/models/route.js +440 -0
  477. package/src/routes/api/v1/responses/compact/route.js +34 -0
  478. package/src/routes/api/v1/responses/route.js +26 -0
  479. package/src/routes/api/v1/route.js +1 -0
  480. package/src/routes/api/version/route.js +11 -0
  481. package/src/routes/table.js +1141 -0
  482. package/src/rtk/applyFilter.js +13 -0
  483. package/src/rtk/autodetect.js +104 -0
  484. package/src/rtk/caveman.js +6 -0
  485. package/src/rtk/cavemanPrompts.js +107 -0
  486. package/src/rtk/constants.js +51 -0
  487. package/src/rtk/filters/buildOutput.js +120 -0
  488. package/src/rtk/filters/dedupLog.js +43 -0
  489. package/src/rtk/filters/find.js +47 -0
  490. package/src/rtk/filters/gitDiff.js +90 -0
  491. package/src/rtk/filters/gitLog.js +88 -0
  492. package/src/rtk/filters/gitStatus.js +101 -0
  493. package/src/rtk/filters/grep.js +45 -0
  494. package/src/rtk/filters/ls.js +73 -0
  495. package/src/rtk/filters/readNumbered.js +22 -0
  496. package/src/rtk/filters/searchList.js +49 -0
  497. package/src/rtk/filters/smartTruncate.js +13 -0
  498. package/src/rtk/filters/tree.js +28 -0
  499. package/src/rtk/index.js +143 -0
  500. package/src/rtk/ponytail.js +6 -0
  501. package/src/rtk/ponytailPrompt.js +49 -0
  502. package/src/rtk/systemInject.js +89 -0
  503. package/src/server.ts +474 -0
  504. package/src/services/accountFallback.js +241 -0
  505. package/src/services/accountPool.js +389 -0
  506. package/src/services/capacityAdapter.js +140 -0
  507. package/src/services/cliModelMapping.js +84 -0
  508. package/src/services/clinepassModels.js +60 -0
  509. package/src/services/codebuddyModels.js +250 -0
  510. package/src/services/combo.js +482 -0
  511. package/src/services/copilotModels.js +126 -0
  512. package/src/services/currencyRate.js +56 -0
  513. package/src/services/cursorModels.js +197 -0
  514. package/src/services/grokCliModels.js +130 -0
  515. package/src/services/kimchiModels.js +175 -0
  516. package/src/services/kiroModels.js +246 -0
  517. package/src/services/model.js +83 -0
  518. package/src/services/oauthCredentialManager.js +153 -0
  519. package/src/services/projectId.js +240 -0
  520. package/src/services/provider.js +145 -0
  521. package/src/services/qoderModels.js +274 -0
  522. package/src/services/tokenRefresh/dedup.js +70 -0
  523. package/src/services/tokenRefresh/providers.js +626 -0
  524. package/src/services/tokenRefresh.js +274 -0
  525. package/src/services/usage/claude.js +134 -0
  526. package/src/services/usage/codebuddy-cn.js +212 -0
  527. package/src/services/usage/codex.js +193 -0
  528. package/src/services/usage/deepseek.js +103 -0
  529. package/src/services/usage/github.js +94 -0
  530. package/src/services/usage/google.js +218 -0
  531. package/src/services/usage/grok-cli.js +368 -0
  532. package/src/services/usage/grokCliQuotaFrame.js +170 -0
  533. package/src/services/usage/kimi.js +185 -0
  534. package/src/services/usage/kiro.js +172 -0
  535. package/src/services/usage/minimax.js +215 -0
  536. package/src/services/usage/misc.js +264 -0
  537. package/src/services/usage/shared.js +59 -0
  538. package/src/services/usage.js +56 -0
  539. package/src/shared/clineAuth.js +37 -0
  540. package/src/shared/constants/config.js +80 -0
  541. package/src/shared/constants/coworkPlugins.js +69 -0
  542. package/src/shared/constants/models.js +41 -0
  543. package/src/shared/constants/providers.js +128 -0
  544. package/src/shared/constants/providersDisplay.js +1 -0
  545. package/src/shared/qoder/constants.js +50 -0
  546. package/src/shared/qoder/cosy.js +134 -0
  547. package/src/shared/qoder/encoding.js +36 -0
  548. package/src/shared/services/initializeApp.js +226 -0
  549. package/src/shared/services/quotaAutoPing.js +310 -0
  550. package/src/shared/utils/apiKey.js +65 -0
  551. package/src/shared/utils/clineAuth.js +1 -0
  552. package/src/shared/utils/index.js +3 -0
  553. package/src/shared/utils/machineId.js +60 -0
  554. package/src/shared/utils/ssrfGuard.js +280 -0
  555. package/src/sse/handlers/chat.js +426 -0
  556. package/src/sse/oauthLease.js +32 -0
  557. package/src/sse/recovery.js +235 -0
  558. package/src/sse/services/auth.js +489 -0
  559. package/src/sse/services/backgroundTokenRefresh.js +173 -0
  560. package/src/sse/services/model.js +129 -0
  561. package/src/sse/services/requestCancellation.js +4 -0
  562. package/src/sse/services/tokenRefresh.js +264 -0
  563. package/src/sse/utils/logger.js +142 -0
  564. package/src/staticServe.ts +95 -0
  565. package/src/transformer/streamToJsonConverter.js +87 -0
  566. package/src/translator/canonical.js +81 -0
  567. package/src/translator/concerns/chunk.js +9 -0
  568. package/src/translator/concerns/compatFallback.js +147 -0
  569. package/src/translator/concerns/finishReason.js +59 -0
  570. package/src/translator/concerns/image.js +105 -0
  571. package/src/translator/concerns/json.js +4 -0
  572. package/src/translator/concerns/kiroConversation.js +428 -0
  573. package/src/translator/concerns/message.js +5 -0
  574. package/src/translator/concerns/modality.js +134 -0
  575. package/src/translator/concerns/paramSupport.js +97 -0
  576. package/src/translator/concerns/prefetch.js +86 -0
  577. package/src/translator/concerns/reasoning.js +18 -0
  578. package/src/translator/concerns/thinking.js +40 -0
  579. package/src/translator/concerns/thinkingUnified.js +319 -0
  580. package/src/translator/concerns/toolCall.js +134 -0
  581. package/src/translator/concerns/usage.js +61 -0
  582. package/src/translator/detection.js +42 -0
  583. package/src/translator/formats/claude.js +323 -0
  584. package/src/translator/formats/gemini.js +366 -0
  585. package/src/translator/formats/maxTokens.js +19 -0
  586. package/src/translator/formats/openai.js +116 -0
  587. package/src/translator/formats/responsesApi.js +117 -0
  588. package/src/translator/formats.js +28 -0
  589. package/src/translator/index.js +237 -0
  590. package/src/translator/request/antigravity-to-openai.js +217 -0
  591. package/src/translator/request/claude-to-kiro.js +288 -0
  592. package/src/translator/request/claude-to-openai.js +199 -0
  593. package/src/translator/request/gemini-to-openai.js +142 -0
  594. package/src/translator/request/openai-responses.js +373 -0
  595. package/src/translator/request/openai-to-claude.js +260 -0
  596. package/src/translator/request/openai-to-commandcode.js +161 -0
  597. package/src/translator/request/openai-to-cursor.js +175 -0
  598. package/src/translator/request/openai-to-gemini.js +422 -0
  599. package/src/translator/request/openai-to-kiro.js +360 -0
  600. package/src/translator/request/openai-to-ollama.js +152 -0
  601. package/src/translator/request/openai-to-vertex.js +36 -0
  602. package/src/translator/response/claude-to-openai.js +185 -0
  603. package/src/translator/response/commandcode-to-openai.js +164 -0
  604. package/src/translator/response/cursor-to-openai.js +18 -0
  605. package/src/translator/response/gemini-to-openai.js +127 -0
  606. package/src/translator/response/kiro-to-claude.js +230 -0
  607. package/src/translator/response/kiro-to-openai.js +136 -0
  608. package/src/translator/response/ollama-to-openai.js +106 -0
  609. package/src/translator/response/openai-responses.js +534 -0
  610. package/src/translator/response/openai-to-antigravity.js +107 -0
  611. package/src/translator/response/openai-to-claude.js +231 -0
  612. package/src/translator/schema/blocks.js +40 -0
  613. package/src/translator/schema/defaults.js +3 -0
  614. package/src/translator/schema/finishReasons.js +22 -0
  615. package/src/translator/schema/index.js +7 -0
  616. package/src/translator/schema/roles.js +12 -0
  617. package/src/transport/requestBoundary.ts +223 -0
  618. package/src/transport/routerAdmission.ts +380 -0
  619. package/src/types/provider.ts +59 -0
  620. package/src/utils/bypassHandler.js +272 -0
  621. package/src/utils/claudeCloaking.js +10 -0
  622. package/src/utils/claudeSignature.js +35 -0
  623. package/src/utils/clientDetector.js +183 -0
  624. package/src/utils/cursorChecksum.js +104 -0
  625. package/src/utils/cursorProtobuf.js +801 -0
  626. package/src/utils/debugLog.js +12 -0
  627. package/src/utils/error.js +120 -0
  628. package/src/utils/inflight.js +127 -0
  629. package/src/utils/kiroSessionReplay.js +139 -0
  630. package/src/utils/ollamaTransform.js +83 -0
  631. package/src/utils/proxyFetch.js +308 -0
  632. package/src/utils/reasoningContentInjector.js +71 -0
  633. package/src/utils/requestLogger.js +272 -0
  634. package/src/utils/responsesStreamHelpers.js +46 -0
  635. package/src/utils/sessionManager.js +205 -0
  636. package/src/utils/sse.js +13 -0
  637. package/src/utils/sseConstants.js +21 -0
  638. package/src/utils/stream.js +511 -0
  639. package/src/utils/streamHandler.js +256 -0
  640. package/src/utils/streamHelpers.js +113 -0
  641. package/src/utils/toolDeduper.js +44 -0
  642. package/src/utils/usageTracking.js +329 -0
  643. package/tsconfig.json +45 -0
@@ -0,0 +1,1075 @@
1
+ import { BaseExecutor } from "./base.js";
2
+ import { PROVIDERS, PROVIDER_OAUTH } from "../config/providers.js";
3
+ import { HTTP_STATUS } from "../config/runtimeConfig.js";
4
+ import {
5
+ generateCursorBody,
6
+ encodeField,
7
+ wrapConnectRPCFrame,
8
+ decodeMessage,
9
+ parseConnectRPCFrame,
10
+ extractTextFromResponse
11
+ } from "../utils/cursorProtobuf.js";
12
+ import { buildCursorHeaders } from "../utils/cursorChecksum.js";
13
+ import { estimateUsage } from "../utils/usageTracking.js";
14
+ import { SSE_DONE, SSE_HEADERS } from "../utils/sseConstants.js";
15
+ import { chatChunkSse, sseChunk } from "../utils/sse.js";
16
+ import { FORMATS } from "../translator/formats.js";
17
+ import { proxyAwareFetch } from "../utils/proxyFetch.js";
18
+ import zlib from "zlib";
19
+ import crypto from "crypto";
20
+
21
+ const isCloudEnv = () => {
22
+ if (typeof caches !== "undefined" && typeof caches === "object") return true;
23
+ if (typeof EdgeRuntime !== "undefined") return true;
24
+ return false;
25
+ };
26
+
27
+ let http2 = null;
28
+ let http2Promise = null;
29
+ async function getHttp2() {
30
+ if (http2 || isCloudEnv()) return http2;
31
+ if (!http2Promise) {
32
+ http2Promise = import("http2").then((module) => {
33
+ http2 = module;
34
+ return module;
35
+ }).catch(() => null);
36
+ }
37
+ return http2Promise;
38
+ }
39
+
40
+ const COMPRESS_FLAG = {
41
+ NONE: 0x00,
42
+ GZIP: 0x01,
43
+ TRAILER: 0x02,
44
+ GZIP_TRAILER: 0x03
45
+ };
46
+
47
+ const AGENT_RUN_PATH = "/agent.v1.AgentService/Run";
48
+ const PROTOBUF_LEN = 2;
49
+ const PROTOBUF_VARINT = 0;
50
+
51
+ function concatBuffers(...parts) {
52
+ const length = parts.reduce((total, part) => total + part.length, 0);
53
+ const result = new Uint8Array(length);
54
+ let offset = 0;
55
+ for (const part of parts) {
56
+ result.set(part, offset);
57
+ offset += part.length;
58
+ }
59
+ return result;
60
+ }
61
+
62
+ const agentString = (field, value) => encodeField(field, PROTOBUF_LEN, value);
63
+ const agentMessage = (field, value) => encodeField(field, PROTOBUF_LEN, value);
64
+ const agentBool = (field, value) => encodeField(field, PROTOBUF_VARINT, value ? 1 : 0);
65
+
66
+ function textFromContent(content) {
67
+ if (typeof content === "string") return content;
68
+ if (!Array.isArray(content)) return "";
69
+ return content
70
+ .filter((part) => part?.type === "text" && typeof part.text === "string")
71
+ .map((part) => part.text)
72
+ .join("\n");
73
+ }
74
+
75
+ function isAgentTextRequest(body) {
76
+
77
+ return Array.isArray(body?.messages) && body.messages.every((message) => {
78
+ if (message?.tool_calls?.length || message?.role === "tool") return false;
79
+ return typeof message?.content === "string"
80
+ || Array.isArray(message?.content) && message.content.every((part) => part?.type === "text");
81
+ });
82
+ }
83
+
84
+ function encodeHistoryMessage(message) {
85
+ const content = textFromContent(message?.content);
86
+ if (!content) return null;
87
+
88
+ const text = agentString(1, content);
89
+ if (message.role === "assistant") {
90
+ return agentMessage(2, agentMessage(1, agentMessage(1, text)));
91
+ }
92
+ return agentMessage(1, agentMessage(1, agentMessage(1, text)));
93
+ }
94
+
95
+ function buildAgentRunFrame(messages, model) {
96
+ const system = messages
97
+ .filter((message) => message?.role === "system" || message?.role === "developer")
98
+ .map((message) => textFromContent(message.content))
99
+ .filter(Boolean)
100
+ .join("\n\n");
101
+ const chatMessages = messages.filter((message) => message?.role !== "system" && message?.role !== "developer");
102
+ const currentIndex = [...chatMessages].map((message) => message?.role).lastIndexOf("user");
103
+ const current = currentIndex >= 0 ? chatMessages[currentIndex] : chatMessages.at(-1);
104
+ const history = chatMessages
105
+ .slice(0, currentIndex >= 0 ? currentIndex : -1)
106
+ .map(encodeHistoryMessage)
107
+ .filter(Boolean);
108
+ const userText = textFromContent(current?.content);
109
+
110
+ const userMessage = concatBuffers(
111
+ agentString(1, userText),
112
+ agentString(2, crypto.randomUUID()),
113
+ );
114
+ const conversationHistory = history.length
115
+ ? concatBuffers(...history.map((entry) => agentMessage(1, entry)))
116
+ : null;
117
+ const userAction = concatBuffers(
118
+ agentMessage(1, userMessage),
119
+ ...(conversationHistory ? [agentMessage(7, conversationHistory)] : []),
120
+ );
121
+ const conversationAction = agentMessage(1, userAction);
122
+ const requestedModel = concatBuffers(agentString(1, model), agentBool(7, true));
123
+ const runRequest = concatBuffers(
124
+
125
+ agentMessage(1, new Uint8Array()),
126
+ agentMessage(2, conversationAction),
127
+ ...(system ? [agentString(8, system)] : []),
128
+ agentMessage(9, requestedModel),
129
+ );
130
+
131
+ return wrapConnectRPCFrame(agentMessage(1, runRequest));
132
+ }
133
+
134
+ function extractAgentString(message, field) {
135
+ const value = message?.get(field)?.[0]?.value;
136
+ return value ? Buffer.from(value).toString("utf8") : "";
137
+ }
138
+
139
+ function decodeAgentFrames(buffer, onFrame) {
140
+ let pending = Buffer.from(buffer || []);
141
+ while (pending.length >= 5) {
142
+ const flags = pending[0];
143
+ const length = pending.readUInt32BE(1);
144
+ if (pending.length < 5 + length) break;
145
+ let payload = pending.subarray(5, 5 + length);
146
+ pending = pending.subarray(5 + length);
147
+ if (flags & COMPRESS_FLAG.GZIP) {
148
+ payload = zlib.gunzipSync(payload);
149
+ }
150
+ if (!(flags & COMPRESS_FLAG.TRAILER)) onFrame(payload);
151
+ }
152
+ return pending;
153
+ }
154
+
155
+ function createRequestContextResponse() {
156
+ const requestContextSuccess = agentMessage(1, new Uint8Array());
157
+ const requestContextResult = agentMessage(1, requestContextSuccess);
158
+ const execClientMessage = agentMessage(10, requestContextResult);
159
+ return wrapConnectRPCFrame(agentMessage(2, execClientMessage));
160
+ }
161
+
162
+ const CURSOR_STREAM_DEBUG = process.env.CURSOR_STREAM_DEBUG === "1";
163
+ const debugLog = (...args) => {
164
+ if (CURSOR_STREAM_DEBUG) console.log(...args);
165
+ };
166
+
167
+ function isComposerModel(model) {
168
+ const modelId = String(model || "").split("/").pop();
169
+ return /^composer(?:-|$)/i.test(modelId);
170
+ }
171
+
172
+ function visibleComposerContentFromThinking(thinking) {
173
+ if (!thinking) return "";
174
+ const endTag = "</think>";
175
+ const endIdx = thinking.lastIndexOf(endTag);
176
+ if (endIdx < 0) return "";
177
+ return thinking.slice(endIdx + endTag.length).trimStart();
178
+ }
179
+
180
+ function decompressPayload(payload, flags) {
181
+
182
+ if (payload.length > 10 && payload[0] === 0x7b && payload[1] === 0x22) {
183
+ try {
184
+ const text = payload.toString("utf-8");
185
+ if (text.startsWith('{"error"')) {
186
+ debugLog(`[DECOMPRESS] Detected JSON error, skipping decompression`);
187
+ return payload;
188
+ }
189
+ } catch {}
190
+ }
191
+
192
+ if (
193
+ flags === COMPRESS_FLAG.GZIP ||
194
+ flags === COMPRESS_FLAG.TRAILER ||
195
+ flags === COMPRESS_FLAG.GZIP_TRAILER
196
+ ) {
197
+
198
+ try {
199
+ return zlib.gunzipSync(payload);
200
+ } catch (gzipErr) {
201
+
202
+ try {
203
+ return zlib.inflateSync(payload);
204
+ } catch (deflateErr) {
205
+
206
+ try {
207
+ return zlib.inflateRawSync(payload);
208
+ } catch (rawErr) {
209
+ debugLog(
210
+ `[DECOMPRESS ERROR] flags=${flags}, payloadSize=${payload.length}, gzip=${gzipErr.message}, deflate=${deflateErr.message}, raw=${rawErr.message}`
211
+ );
212
+ debugLog(
213
+ `[DECOMPRESS ERROR] First 50 bytes (hex):`,
214
+ payload.slice(0, 50).toString("hex")
215
+ );
216
+ return payload;
217
+ }
218
+ }
219
+ }
220
+ }
221
+ return payload;
222
+ }
223
+
224
+ function readCursorFrame(buffer, offset, frameNum, tag) {
225
+ if (offset + 5 > buffer.length) {
226
+ debugLog(`[CURSOR BUFFER${tag}] Reached end, offset=${offset}, remaining=${buffer.length - offset}`);
227
+ return { status: "done" };
228
+ }
229
+
230
+ const flags = buffer[offset];
231
+ const length = buffer.readUInt32BE(offset + 1);
232
+ debugLog(`[CURSOR BUFFER${tag}] Frame ${frameNum + 1}: flags=0x${flags.toString(16).padStart(2, "0")}, length=${length}`);
233
+
234
+ if (offset + 5 + length > buffer.length) {
235
+ debugLog(`[CURSOR BUFFER${tag}] Incomplete frame, offset=${offset}, length=${length}, buffer.length=${buffer.length}`);
236
+ return { status: "done" };
237
+ }
238
+
239
+ let payload = buffer.slice(offset + 5, offset + 5 + length);
240
+ const newOffset = offset + 5 + length;
241
+ payload = decompressPayload(payload, flags);
242
+ if (!payload) {
243
+ debugLog(`[CURSOR BUFFER${tag}] Frame ${frameNum + 1}: decompression failed, skipping`);
244
+ return { status: "skip", offset: newOffset };
245
+ }
246
+ return { status: "ok", payload, offset: newOffset };
247
+ }
248
+
249
+ function createErrorResponse(jsonError) {
250
+ const errorMsg = jsonError?.error?.details?.[0]?.debug?.details?.title
251
+ || jsonError?.error?.details?.[0]?.debug?.details?.detail
252
+ || jsonError?.error?.message
253
+ || "API Error";
254
+
255
+ const isRateLimit = jsonError?.error?.code === "resource_exhausted";
256
+
257
+ return new Response(JSON.stringify({
258
+ error: {
259
+ message: errorMsg,
260
+ type: isRateLimit ? "rate_limit_error" : "api_error",
261
+ code: jsonError?.error?.details?.[0]?.debug?.error || "unknown"
262
+ }
263
+ }), {
264
+ status: isRateLimit ? HTTP_STATUS.RATE_LIMITED : HTTP_STATUS.BAD_REQUEST,
265
+ headers: { "Content-Type": "application/json" }
266
+ });
267
+ }
268
+
269
+ export class CursorExecutor extends BaseExecutor {
270
+ constructor() {
271
+ super("cursor", PROVIDERS.cursor);
272
+ }
273
+
274
+ buildUrl() {
275
+ return `${this.config.baseUrl}${this.config.chatPath}`;
276
+ }
277
+
278
+ buildHeaders(credentials) {
279
+ const accessToken = credentials.accessToken;
280
+ const machineId = credentials.providerSpecificData?.machineId;
281
+ const ghostMode = credentials.providerSpecificData?.ghostMode !== false;
282
+
283
+ if (!machineId) {
284
+ throw new Error("Machine ID is required for Cursor API");
285
+ }
286
+
287
+ return buildCursorHeaders(accessToken, machineId, ghostMode);
288
+ }
289
+
290
+ transformRequest(model, body, stream, credentials) {
291
+
292
+ const messages = body.messages || [];
293
+ const tools = body.tools || [];
294
+ const reasoningEffort = body.reasoning_effort || null;
295
+
296
+ const ua = credentials?.rawHeaders?.["user-agent"] || "";
297
+ const forceAgentMode = ua.includes("claude-cli") || ua.includes("claude-code") || ua.includes("Claude Code");
298
+ return generateCursorBody(messages, model, tools, reasoningEffort, forceAgentMode);
299
+ }
300
+
301
+ async makeFetchRequest(url, headers, body, signal, proxyOptions = null) {
302
+ const response = await proxyAwareFetch(url, {
303
+ method: "POST",
304
+ headers,
305
+ body,
306
+ signal
307
+ }, proxyOptions);
308
+
309
+ return {
310
+ status: response.status,
311
+ headers: Object.fromEntries(response.headers.entries()),
312
+ body: Buffer.from(await response.arrayBuffer())
313
+ };
314
+ }
315
+
316
+ async makeHttp2Request(url, headers, body, signal) {
317
+ await getHttp2();
318
+ if (!http2) {
319
+ throw new Error("http2 module not available");
320
+ }
321
+
322
+ const HTTP2_TIMEOUT_MS = 60000;
323
+
324
+ return new Promise((resolve, reject) => {
325
+ const urlObj = new URL(url);
326
+ const client = http2.connect(`https://${urlObj.host}`);
327
+ const chunks = [];
328
+ let responseHeaders = {};
329
+ let settled = false;
330
+
331
+ const finish = (fn) => (...args) => {
332
+ if (settled) return;
333
+ settled = true;
334
+ clearTimeout(hangTimeout);
335
+ client.close();
336
+ fn(...args);
337
+ };
338
+
339
+ const hangTimeout = setTimeout(finish(() => {
340
+ reject(new Error("HTTP/2 request timed out"));
341
+ }), HTTP2_TIMEOUT_MS);
342
+
343
+ client.on("error", finish(reject));
344
+
345
+ const req = client.request({
346
+ ":method": "POST",
347
+ ":path": urlObj.pathname,
348
+ ":authority": urlObj.host,
349
+ ":scheme": "https",
350
+ ...headers
351
+ });
352
+
353
+ req.on("response", (hdrs) => { responseHeaders = hdrs; });
354
+ req.on("data", (chunk) => { chunks.push(chunk); });
355
+ req.on("end", finish(() => {
356
+ resolve({
357
+ status: responseHeaders[":status"],
358
+ headers: responseHeaders,
359
+ body: Buffer.concat(chunks)
360
+ });
361
+ }));
362
+ req.on("error", finish(reject));
363
+
364
+ if (signal) {
365
+ const onAbort = finish(() => reject(new Error("Request aborted")));
366
+ signal.addEventListener("abort", onAbort, { once: true });
367
+ }
368
+
369
+ req.write(body);
370
+ req.end();
371
+ });
372
+ }
373
+
374
+ async openAgentHttp2Stream(url, headers, signal) {
375
+ await getHttp2();
376
+ if (!http2) {
377
+ throw new Error("HTTP/2 is required for Cursor AgentService (endpoint is h2-only)");
378
+ }
379
+
380
+ const urlObj = new URL(url);
381
+ const client = http2.connect(`https://${urlObj.host}`);
382
+ const chunkQueue = [];
383
+ let waiting = null;
384
+ let ended = false;
385
+ let streamError = null;
386
+ let req = null;
387
+
388
+ const wake = (result) => {
389
+ if (!waiting) return;
390
+ const resolve = waiting;
391
+ waiting = null;
392
+ resolve(result);
393
+ };
394
+
395
+ const fail = (error) => {
396
+ if (streamError) return;
397
+ streamError = error;
398
+ ended = true;
399
+ wake(null);
400
+ };
401
+
402
+ const close = () => {
403
+ try { req?.destroy(); } catch {}
404
+ try { client.close(); } catch {}
405
+ };
406
+
407
+ client.on("error", fail);
408
+
409
+ req = client.request({
410
+ ":method": "POST",
411
+ ":path": urlObj.pathname,
412
+ ":authority": urlObj.host,
413
+ ":scheme": "https",
414
+ ...headers,
415
+ });
416
+
417
+ req.on("error", fail);
418
+ req.on("data", (chunk) => {
419
+ if (waiting) wake({ value: chunk, done: false });
420
+ else chunkQueue.push(chunk);
421
+ });
422
+ req.on("end", () => {
423
+ ended = true;
424
+ wake({ value: undefined, done: true });
425
+ });
426
+
427
+ if (signal) {
428
+ const onAbort = () => {
429
+ fail(new Error("Request aborted"));
430
+ close();
431
+ };
432
+ if (signal.aborted) onAbort();
433
+ else signal.addEventListener("abort", onAbort, { once: true });
434
+ }
435
+
436
+ const responseHeaders = new Promise((resolve, reject) => {
437
+ const onEarlyError = (error) => reject(error);
438
+ client.once("error", onEarlyError);
439
+ req.once("error", onEarlyError);
440
+ req.once("response", (hdrs) => {
441
+ client.off("error", onEarlyError);
442
+ req.off("error", onEarlyError);
443
+ resolve(hdrs);
444
+ });
445
+ });
446
+
447
+ return {
448
+ responseHeaders,
449
+ write(frame) {
450
+ if (req && !req.destroyed) req.write(Buffer.from(frame));
451
+ },
452
+ end() {
453
+ try { if (req && !req.destroyed) req.end(); } catch {}
454
+ },
455
+ close,
456
+ async read() {
457
+ if (chunkQueue.length) return { value: chunkQueue.shift(), done: false };
458
+ if (ended) {
459
+ if (streamError) throw streamError;
460
+ return { value: undefined, done: true };
461
+ }
462
+ const result = await new Promise((resolve) => { waiting = resolve; });
463
+ if (streamError) throw streamError;
464
+ return result || { value: undefined, done: true };
465
+ },
466
+ };
467
+ }
468
+
469
+ async executeAgent({ model, body, stream, credentials, signal }) {
470
+ const agentEndpoint = PROVIDER_OAUTH.cursor?.agentEndpoint;
471
+ if (!agentEndpoint) throw new Error("Cursor AgentService endpoint is not configured");
472
+
473
+ const url = `${agentEndpoint}${AGENT_RUN_PATH}`;
474
+ const headers = this.buildHeaders(credentials);
475
+ const requestController = new AbortController();
476
+ if (signal?.addEventListener) {
477
+ signal.addEventListener("abort", () => requestController.abort(signal.reason), { once: true });
478
+ }
479
+
480
+ let session;
481
+ try {
482
+ session = await this.openAgentHttp2Stream(url, headers, requestController.signal);
483
+ session.write(buildAgentRunFrame(body.messages || [], model));
484
+ } catch (error) {
485
+ throw new Error(`Cursor AgentService request failed: ${error.message}`);
486
+ }
487
+
488
+ let responseHeaders;
489
+ try {
490
+ responseHeaders = await session.responseHeaders;
491
+ } catch (error) {
492
+ session.close();
493
+ throw new Error(`Cursor AgentService request failed: ${error.message}`);
494
+ }
495
+
496
+ const status = Number(responseHeaders[":status"] || 0);
497
+ if (status !== 200) {
498
+ let errorText = "";
499
+ try {
500
+ while (true) {
501
+ const { done, value } = await session.read();
502
+ if (done) break;
503
+ errorText += Buffer.from(value).toString("utf8");
504
+ }
505
+ } catch {}
506
+ session.close();
507
+ return {
508
+ response: new Response(JSON.stringify({
509
+ error: { message: `Cursor AgentService ${status}: ${errorText || "request failed"}`, type: "api_error" },
510
+ }), { status: status || HTTP_STATUS.SERVER_ERROR, headers: { "Content-Type": "application/json" } }),
511
+ url,
512
+ headers,
513
+ transformedBody: body,
514
+ responseFormat: FORMATS.OPENAI,
515
+ };
516
+ }
517
+
518
+ const responseId = `chatcmpl-msg_${Date.now()}`;
519
+ const created = Math.floor(Date.now() / 1000);
520
+ let pending = Buffer.alloc(0);
521
+ let finished = false;
522
+
523
+ const consume = async (onEvent) => {
524
+ try {
525
+ while (!finished) {
526
+ const { done, value } = await session.read();
527
+ if (done) break;
528
+ pending = Buffer.concat([pending, Buffer.from(value)]);
529
+ pending = decodeAgentFrames(pending, (payload) => {
530
+
531
+ if (finished) return;
532
+ const serverMessage = decodeMessage(payload);
533
+
534
+ if (serverMessage.has(1)) {
535
+ const update = decodeMessage(serverMessage.get(1)[0].value);
536
+ if (update.has(1)) {
537
+ const textDelta = extractAgentString(decodeMessage(update.get(1)[0].value), 1);
538
+ if (textDelta) onEvent({ type: "text", value: textDelta });
539
+ }
540
+
541
+ if (update.has(14)) {
542
+ finished = true;
543
+ onEvent({ type: "done" });
544
+ }
545
+ }
546
+
547
+ if (serverMessage.has(2)) {
548
+ const execRequest = decodeMessage(serverMessage.get(2)[0].value);
549
+ if (execRequest.has(10)) {
550
+ session.write(createRequestContextResponse());
551
+ } else {
552
+ debugLog(`[CURSOR AGENT] Unsupported exec request fields: ${[...execRequest.keys()].join(",")}`);
553
+ finished = true;
554
+ onEvent({ type: "error", value: "Cursor AgentService requested an unsupported IDE tool" });
555
+ }
556
+ }
557
+ });
558
+ }
559
+ } finally {
560
+ try { session.end(); } catch {}
561
+ try { session.close(); } catch {}
562
+ if (!finished) onEvent({ type: "done" });
563
+ }
564
+ };
565
+
566
+ if (stream === false) {
567
+ let content = "";
568
+ let reasoning = "";
569
+ let agentError = null;
570
+ await consume((event) => {
571
+ if (event.type === "text") content += event.value;
572
+ else if (event.type === "thinking") reasoning += event.value;
573
+ else if (event.type === "error") agentError = event.value;
574
+ });
575
+ if (agentError) {
576
+ return {
577
+ response: new Response(JSON.stringify({ error: { message: agentError, type: "api_error" } }), {
578
+ status: HTTP_STATUS.BAD_REQUEST,
579
+ headers: { "Content-Type": "application/json" },
580
+ }),
581
+ url,
582
+ headers,
583
+ transformedBody: body,
584
+ responseFormat: FORMATS.OPENAI,
585
+ };
586
+ }
587
+ return {
588
+ response: new Response(JSON.stringify({
589
+ id: responseId,
590
+ object: "chat.completion",
591
+ created,
592
+ model,
593
+ choices: [{ index: 0, message: { role: "assistant", content: content || null, ...(reasoning ? { reasoning_content: reasoning } : {}) }, finish_reason: "stop" }],
594
+ usage: estimateUsage(body, content.length, FORMATS.OPENAI),
595
+ }), { headers: { "Content-Type": "application/json" } }),
596
+ url,
597
+ headers,
598
+ transformedBody: body,
599
+ responseFormat: FORMATS.OPENAI,
600
+ };
601
+ }
602
+
603
+ const encoder = new TextEncoder();
604
+ const responseStream = new ReadableStream({
605
+ start(controller) {
606
+ consume((event) => {
607
+ if (event.type === "text") {
608
+ controller.enqueue(encoder.encode(chatChunkSse({ id: responseId, created, model, delta: { content: event.value } })));
609
+ } else if (event.type === "thinking") {
610
+ controller.enqueue(encoder.encode(chatChunkSse({ id: responseId, created, model, delta: { reasoning_content: event.value } })));
611
+ } else if (event.type === "error") {
612
+
613
+ controller.enqueue(encoder.encode(sseChunk({ error: { message: event.value, type: "api_error" } })));
614
+ controller.enqueue(encoder.encode(SSE_DONE));
615
+ controller.close();
616
+ } else if (event.type === "done") {
617
+ controller.enqueue(encoder.encode(chatChunkSse({ id: responseId, created, model, delta: {}, finishReason: "stop" })));
618
+ controller.enqueue(encoder.encode(SSE_DONE));
619
+ controller.close();
620
+ }
621
+ }).catch((error) => controller.error(error));
622
+ },
623
+ cancel() {
624
+ requestController.abort();
625
+ },
626
+ });
627
+
628
+ return {
629
+ response: new Response(responseStream, { headers: SSE_HEADERS }),
630
+ url,
631
+ headers,
632
+ transformedBody: body,
633
+ responseFormat: FORMATS.OPENAI,
634
+ };
635
+ }
636
+
637
+ async execute({ model, body, stream, credentials, signal, log, proxyOptions = null }) {
638
+ if (isAgentTextRequest(body)) {
639
+ try {
640
+ return await this.executeAgent({ model, body, stream, credentials, signal });
641
+ } catch (error) {
642
+ return {
643
+ response: new Response(JSON.stringify({
644
+ error: { message: error.message, type: "connection_error", code: "" },
645
+ }), { status: HTTP_STATUS.SERVER_ERROR, headers: { "Content-Type": "application/json" } }),
646
+ url: `${PROVIDER_OAUTH.cursor?.agentEndpoint || ""}${AGENT_RUN_PATH}`,
647
+ headers: {},
648
+ transformedBody: body,
649
+ };
650
+ }
651
+ }
652
+
653
+ const url = this.buildUrl();
654
+ const headers = this.buildHeaders(credentials);
655
+ const transformedBody = this.transformRequest(model, body, stream, credentials);
656
+
657
+ try {
658
+ const shouldForceFetch = proxyOptions?.enabled === true || proxyOptions?.connectionProxyEnabled === true || !!proxyOptions?.relayUrl || !!proxyOptions?.vercelRelayUrl;
659
+ const response = (http2 && !shouldForceFetch)
660
+ ? await this.makeHttp2Request(url, headers, transformedBody, signal)
661
+ : await this.makeFetchRequest(url, headers, transformedBody, signal, proxyOptions);
662
+
663
+ if (response.status !== 200) {
664
+ const errorText = response.body?.toString() || "Unknown error";
665
+ const errorResponse = new Response(JSON.stringify({
666
+ error: {
667
+ message: `[${response.status}]: ${errorText}`,
668
+ type: "invalid_request_error",
669
+ code: ""
670
+ }
671
+ }), {
672
+ status: response.status,
673
+ headers: { "Content-Type": "application/json" }
674
+ });
675
+ return { response: errorResponse, url, headers, transformedBody: body };
676
+ }
677
+
678
+ const transformedResponse = stream !== false
679
+ ? this.transformProtobufToSSE(response.body, model, body)
680
+ : this.transformProtobufToJSON(response.body, model, body);
681
+
682
+ return { response: transformedResponse, url, headers, transformedBody: body };
683
+ } catch (error) {
684
+ const errorResponse = new Response(JSON.stringify({
685
+ error: {
686
+ message: error.message,
687
+ type: "connection_error",
688
+ code: ""
689
+ }
690
+ }), {
691
+ status: HTTP_STATUS.SERVER_ERROR,
692
+ headers: { "Content-Type": "application/json" }
693
+ });
694
+ return { response: errorResponse, url, headers, transformedBody: body };
695
+ }
696
+ }
697
+
698
+ transformProtobufToJSON(buffer, model, body) {
699
+ const responseId = `chatcmpl-cursor-${Date.now()}`;
700
+ const created = Math.floor(Date.now() / 1000);
701
+
702
+ let offset = 0;
703
+ let totalContent = "";
704
+ let totalThinking = "";
705
+ const toolCalls = [];
706
+ const toolCallsMap = new Map();
707
+ const finalizedIds = new Set();
708
+ let frameCount = 0;
709
+
710
+ debugLog(`[CURSOR BUFFER] Total length: ${buffer.length} bytes`);
711
+
712
+ while (offset < buffer.length) {
713
+ const frame = readCursorFrame(buffer, offset, frameCount, "");
714
+ if (frame.status === "done") break;
715
+ offset = frame.offset;
716
+ frameCount++;
717
+ if (frame.status === "skip") continue;
718
+ const payload = frame.payload;
719
+
720
+ if (payload.length > 0 && payload[0] === 0x7b) {
721
+ try {
722
+ const text = payload.toString("utf-8");
723
+ if (text.includes('"error"')) {
724
+ const hasContent = totalContent || toolCallsMap.size > 0;
725
+ debugLog(
726
+ `[CURSOR BUFFER] Error frame (hasContent=${hasContent}): ${text.slice(0, 500)}`
727
+ );
728
+ if (hasContent) {
729
+ break;
730
+ }
731
+ return createErrorResponse(JSON.parse(text));
732
+ }
733
+ } catch {}
734
+ }
735
+
736
+ const result = extractTextFromResponse(new Uint8Array(payload));
737
+ debugLog(`[CURSOR DECODED] Frame ${frameCount}:`, result);
738
+
739
+ if (result.error) {
740
+ const hasContent = totalContent || toolCallsMap.size > 0;
741
+ debugLog(`[CURSOR BUFFER] Decoded error (hasContent=${hasContent}): ${result.error}`);
742
+ if (hasContent) {
743
+ break;
744
+ }
745
+ return new Response(
746
+ JSON.stringify({
747
+ error: {
748
+ message: result.error,
749
+ type: "rate_limit_error",
750
+ code: "rate_limited"
751
+ }
752
+ }),
753
+ {
754
+ status: HTTP_STATUS.RATE_LIMITED,
755
+ headers: { "Content-Type": "application/json" }
756
+ }
757
+ );
758
+ }
759
+
760
+ if (result.toolCall) {
761
+ const tc = result.toolCall;
762
+
763
+ if (toolCallsMap.has(tc.id)) {
764
+
765
+ const existing = toolCallsMap.get(tc.id);
766
+ existing.function.arguments += tc.function.arguments;
767
+ existing.isLast = tc.isLast;
768
+ } else {
769
+
770
+ toolCallsMap.set(tc.id, { ...tc });
771
+ }
772
+
773
+ if (tc.isLast) {
774
+ const finalToolCall = toolCallsMap.get(tc.id);
775
+ finalizedIds.add(tc.id);
776
+ toolCalls.push({
777
+ id: finalToolCall.id,
778
+ type: finalToolCall.type,
779
+ function: {
780
+ name: finalToolCall.function.name,
781
+ arguments: finalToolCall.function.arguments
782
+ }
783
+ });
784
+ }
785
+ }
786
+
787
+ if (result.text) totalContent += result.text;
788
+ if (result.thinking) totalThinking += result.thinking;
789
+ }
790
+
791
+ const visibleComposerContent = isComposerModel(model)
792
+ ? visibleComposerContentFromThinking(totalThinking)
793
+ : "";
794
+ const finalContent = totalContent || visibleComposerContent;
795
+
796
+ debugLog(
797
+ `[CURSOR BUFFER] Parsed ${frameCount} frames, toolCallsMap size: ${toolCallsMap.size}, finalized toolCalls: ${toolCalls.length}`
798
+ );
799
+
800
+ for (const [id, tc] of toolCallsMap.entries()) {
801
+
802
+ if (!finalizedIds.has(id)) {
803
+ debugLog(`[CURSOR BUFFER] Finalizing incomplete tool call: ${id}, isLast=${tc.isLast}`);
804
+ toolCalls.push({
805
+ id: tc.id,
806
+ type: tc.type,
807
+ function: {
808
+ name: tc.function.name,
809
+ arguments: tc.function.arguments
810
+ }
811
+ });
812
+ }
813
+ }
814
+
815
+ debugLog(`[CURSOR BUFFER] Final toolCalls count: ${toolCalls.length}`);
816
+
817
+ const message = {
818
+ role: "assistant",
819
+ content: finalContent || null
820
+ };
821
+
822
+ if (toolCalls.length > 0) {
823
+ message.tool_calls = toolCalls;
824
+ }
825
+
826
+ const usage = estimateUsage(body, finalContent.length, FORMATS.OPENAI);
827
+
828
+ const completion = {
829
+ id: responseId,
830
+ object: "chat.completion",
831
+ created,
832
+ model,
833
+ choices: [{
834
+ index: 0,
835
+ message,
836
+ finish_reason: toolCalls.length > 0 ? "tool_calls" : "stop"
837
+ }],
838
+ usage
839
+ };
840
+
841
+ return new Response(JSON.stringify(completion), {
842
+ status: 200,
843
+ headers: { "Content-Type": "application/json" }
844
+ });
845
+ }
846
+
847
+ transformProtobufToSSE(buffer, model, body) {
848
+ const responseId = `chatcmpl-cursor-${Date.now()}`;
849
+ const created = Math.floor(Date.now() / 1000);
850
+
851
+ const chunks = [];
852
+ let offset = 0;
853
+ let totalContent = "";
854
+ let totalThinking = "";
855
+ let emittedComposerThinkingContentLength = 0;
856
+ const toolCalls = [];
857
+ const toolCallsMap = new Map();
858
+ const finalizedIds = new Set();
859
+ const emittedToolCallIds = new Set();
860
+ let frameCount = 0;
861
+
862
+ debugLog(`[CURSOR BUFFER SSE] Total length: ${buffer.length} bytes`);
863
+
864
+ while (offset < buffer.length) {
865
+ const frame = readCursorFrame(buffer, offset, frameCount, " SSE");
866
+ if (frame.status === "done") break;
867
+ offset = frame.offset;
868
+ frameCount++;
869
+ if (frame.status === "skip") continue;
870
+ const payload = frame.payload;
871
+
872
+ if (payload[0] === 0x7b) {
873
+ try {
874
+ const text = payload.toString("utf-8");
875
+ if (text.includes('"error"')) {
876
+ const hasContent = chunks.length > 0 || totalContent || toolCallsMap.size > 0;
877
+ debugLog(
878
+ `[CURSOR BUFFER SSE] Error frame (hasContent=${hasContent}): ${text.slice(0, 500)}`
879
+ );
880
+ if (hasContent) {
881
+ break;
882
+ }
883
+ return createErrorResponse(JSON.parse(text));
884
+ }
885
+ } catch {}
886
+ }
887
+
888
+ const result = extractTextFromResponse(new Uint8Array(payload));
889
+ debugLog(`[CURSOR DECODED SSE] Frame ${frameCount}:`, result);
890
+
891
+ if (result.error) {
892
+ const hasContent = chunks.length > 0 || totalContent || toolCallsMap.size > 0;
893
+ debugLog(`[CURSOR BUFFER SSE] Decoded error (hasContent=${hasContent}): ${result.error}`);
894
+ if (hasContent) {
895
+ break;
896
+ }
897
+ return new Response(
898
+ JSON.stringify({
899
+ error: {
900
+ message: result.error,
901
+ type: "rate_limit_error",
902
+ code: "rate_limited"
903
+ }
904
+ }),
905
+ {
906
+ status: HTTP_STATUS.RATE_LIMITED,
907
+ headers: { "Content-Type": "application/json" }
908
+ }
909
+ );
910
+ }
911
+
912
+ if (result.toolCall) {
913
+ const tc = result.toolCall;
914
+
915
+ if (chunks.length === 0) {
916
+ chunks.push(chatChunkSse({ id: responseId, created, model, delta: { role: "assistant", content: "" } }));
917
+ }
918
+
919
+ if (toolCallsMap.has(tc.id)) {
920
+
921
+ const existing = toolCallsMap.get(tc.id);
922
+ const oldArgsLen = existing.function.arguments.length;
923
+ existing.function.arguments += tc.function.arguments;
924
+ existing.isLast = tc.isLast;
925
+
926
+ if (tc.function.arguments) {
927
+ emittedToolCallIds.add(tc.id);
928
+ chunks.push(chatChunkSse({
929
+ id: responseId, created, model,
930
+ delta: {
931
+ tool_calls: [
932
+ {
933
+ index: existing.index,
934
+ id: tc.id,
935
+ type: "function",
936
+ function: {
937
+ name: tc.function.name,
938
+ arguments: tc.function.arguments
939
+ }
940
+ }
941
+ ]
942
+ }
943
+ }));
944
+ }
945
+ } else {
946
+
947
+ const toolCallIndex = toolCalls.length;
948
+ finalizedIds.add(tc.id);
949
+ toolCalls.push({ ...tc, index: toolCallIndex });
950
+ toolCallsMap.set(tc.id, { ...tc, index: toolCallIndex });
951
+
952
+ emittedToolCallIds.add(tc.id);
953
+ chunks.push(chatChunkSse({
954
+ id: responseId, created, model,
955
+ delta: {
956
+ tool_calls: [
957
+ {
958
+ index: toolCallIndex,
959
+ id: tc.id,
960
+ type: "function",
961
+ function: {
962
+ name: tc.function.name,
963
+ arguments: tc.function.arguments
964
+ }
965
+ }
966
+ ]
967
+ }
968
+ }));
969
+ }
970
+ }
971
+
972
+ if (result.text) {
973
+ totalContent += result.text;
974
+ chunks.push(chatChunkSse({
975
+ id: responseId, created, model,
976
+ delta:
977
+ chunks.length === 0 && toolCalls.length === 0
978
+ ? { role: "assistant", content: result.text }
979
+ : { content: result.text }
980
+ }));
981
+ }
982
+
983
+ if (isComposerModel(model) && result.thinking) {
984
+ totalThinking += result.thinking;
985
+ const visibleContent = visibleComposerContentFromThinking(totalThinking);
986
+ if (visibleContent.length > emittedComposerThinkingContentLength) {
987
+ const deltaContent = visibleContent.slice(emittedComposerThinkingContentLength);
988
+ emittedComposerThinkingContentLength = visibleContent.length;
989
+ totalContent += deltaContent;
990
+ chunks.push(chatChunkSse({
991
+ id: responseId, created, model,
992
+ delta:
993
+ chunks.length === 0 && toolCalls.length === 0
994
+ ? { role: "assistant", content: deltaContent }
995
+ : { content: deltaContent }
996
+ }));
997
+ }
998
+ }
999
+ }
1000
+
1001
+ debugLog(
1002
+ `[CURSOR BUFFER SSE] Parsed ${frameCount} frames, toolCallsMap size: ${toolCallsMap.size}, toolCalls array: ${toolCalls.length}`
1003
+ );
1004
+
1005
+ for (const [id, tc] of toolCallsMap.entries()) {
1006
+ if (!finalizedIds.has(id)) {
1007
+ debugLog(`[CURSOR BUFFER SSE] Finalizing incomplete tool call: ${id}, isLast=${tc.isLast}`);
1008
+ const toolCallIndex = toolCalls.length;
1009
+ toolCalls.push({
1010
+ id: tc.id,
1011
+ type: tc.type,
1012
+ index: toolCallIndex,
1013
+ function: {
1014
+ name: tc.function.name,
1015
+ arguments: tc.function.arguments
1016
+ }
1017
+ });
1018
+
1019
+ if (!emittedToolCallIds.has(tc.id)) {
1020
+ chunks.push(chatChunkSse({
1021
+ id: responseId, created, model,
1022
+ delta: {
1023
+ tool_calls: [
1024
+ {
1025
+ index: toolCallIndex,
1026
+ id: tc.id,
1027
+ type: "function",
1028
+ function: {
1029
+ name: tc.function.name,
1030
+ arguments: tc.function.arguments
1031
+ }
1032
+ }
1033
+ ]
1034
+ }
1035
+ }));
1036
+ }
1037
+ }
1038
+ }
1039
+
1040
+ if (chunks.length === 0 && toolCalls.length === 0) {
1041
+ chunks.push(chatChunkSse({ id: responseId, created, model, delta: { role: "assistant", content: "" } }));
1042
+ }
1043
+
1044
+ const usage = estimateUsage(body, totalContent.length, FORMATS.OPENAI);
1045
+
1046
+ chunks.push(
1047
+ `data: ${JSON.stringify({
1048
+ id: responseId,
1049
+ object: "chat.completion.chunk",
1050
+ created,
1051
+ model,
1052
+ choices: [
1053
+ {
1054
+ index: 0,
1055
+ delta: {},
1056
+ finish_reason: toolCalls.length > 0 ? "tool_calls" : "stop"
1057
+ }
1058
+ ],
1059
+ usage
1060
+ })}\n\n`
1061
+ );
1062
+ chunks.push(SSE_DONE);
1063
+
1064
+ return new Response(chunks.join(""), {
1065
+ status: 200,
1066
+ headers: { ...SSE_HEADERS }
1067
+ });
1068
+ }
1069
+
1070
+ async refreshCredentials() {
1071
+ return null;
1072
+ }
1073
+ }
1074
+
1075
+ export default CursorExecutor;