@cortex-agent/server 2026.10.28 → 2026.12.5

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 (401) hide show
  1. package/LICENSE +255 -21
  2. package/README.md +36 -7
  3. package/THIRD_PARTY_NOTICES.txt +1990 -593
  4. package/defaults/hooks/cortex-hook-api.mjs +2 -1
  5. package/defaults/hooks/quota-stop.mjs +37 -0
  6. package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +23 -15
  7. package/defaults/prompts/clean-workspace.md +5 -0
  8. package/dist/agent-adapter/claude/remote-mcp-proxy.js +1 -1
  9. package/dist/chunks/agent-runner-LVZVKBZX.js +4 -0
  10. package/dist/chunks/anthropic-messages-TT6454AA.js +8 -0
  11. package/dist/chunks/azure-openai-responses-52LR2XZD.js +4 -0
  12. package/dist/chunks/bedrock-converse-stream-EOZGYUNY.js +60 -0
  13. package/dist/chunks/bowser-MLGGLXTZ.js +20 -0
  14. package/dist/chunks/child-runner-SMG2VOU5.js +4 -0
  15. package/dist/chunks/chunk-24DH4IR5.js +4 -0
  16. package/dist/chunks/chunk-25XKBRDT.js +70 -0
  17. package/dist/chunks/chunk-2ABET62E.js +23 -0
  18. package/dist/chunks/chunk-2BVUA256.js +4 -0
  19. package/dist/chunks/{chunk-LEUENXI2.js → chunk-2WFL62UO.js} +1 -1
  20. package/dist/chunks/{chunk-OZGBWAT2.js → chunk-2YTYYG4K.js} +1 -1
  21. package/dist/chunks/chunk-335SSANX.js +4 -0
  22. package/dist/chunks/chunk-377OPTXX.js +17 -0
  23. package/dist/chunks/chunk-3EZNVLBF.js +129 -0
  24. package/dist/chunks/chunk-3O6ZG5HA.js +7 -0
  25. package/dist/chunks/{chunk-6AKUD3CF.js → chunk-3XLHL5YT.js} +1 -1
  26. package/dist/chunks/chunk-4HRI75GU.js +4 -0
  27. package/dist/chunks/chunk-4JBYLRPM.js +57 -0
  28. package/dist/chunks/chunk-4KKV7VKE.js +4 -0
  29. package/dist/chunks/chunk-4KQHDDC5.js +4 -0
  30. package/dist/chunks/chunk-4SWD4JMP.js +33 -0
  31. package/dist/chunks/chunk-52VCLZS5.js +4 -0
  32. package/dist/chunks/chunk-54P7TSY3.js +10 -0
  33. package/dist/chunks/chunk-5DVSAXOI.js +7 -0
  34. package/dist/chunks/chunk-5F3A62YS.js +4 -0
  35. package/dist/chunks/{chunk-XNSSUVT6.js → chunk-5FHETFZM.js} +1 -1
  36. package/dist/chunks/{chunk-A34TDMIC.js → chunk-5LBLRAHS.js} +1 -1
  37. package/dist/chunks/chunk-5UYVNA3W.js +4 -0
  38. package/dist/chunks/chunk-6G3OYMCV.js +21 -0
  39. package/dist/chunks/chunk-7GGPYU5E.js +30 -0
  40. package/dist/chunks/chunk-7TYSMLUV.js +4 -0
  41. package/dist/chunks/chunk-7W7VYUTK.js +5 -0
  42. package/dist/chunks/chunk-AXYAZTTN.js +6 -0
  43. package/dist/chunks/{chunk-BGVHA2D4.js → chunk-B3NB243Z.js} +1 -1
  44. package/dist/chunks/chunk-BKYP6AGM.js +8 -0
  45. package/dist/chunks/chunk-BVEDNESB.js +4 -0
  46. package/dist/chunks/chunk-BWDJS6A4.js +12 -0
  47. package/dist/chunks/chunk-C6YVF7EI.js +4 -0
  48. package/dist/chunks/chunk-CEJIYYVE.js +15 -0
  49. package/dist/chunks/chunk-CI2RHH74.js +50 -0
  50. package/dist/chunks/chunk-CMSOOLJB.js +4 -0
  51. package/dist/chunks/chunk-CSVTYYLP.js +4 -0
  52. package/dist/chunks/chunk-DE5EGVKG.js +6 -0
  53. package/dist/chunks/{chunk-E6BYRULL.js → chunk-DK3RPZOQ.js} +1 -1
  54. package/dist/chunks/{chunk-YPK2CAIZ.js → chunk-DK4UCK7L.js} +1 -1
  55. package/dist/chunks/chunk-DYLBVUAU.js +4 -0
  56. package/dist/chunks/chunk-FDC2GRBK.js +27 -0
  57. package/dist/chunks/chunk-FE7HH5JS.js +18 -0
  58. package/dist/chunks/chunk-FYD57YRO.js +436 -0
  59. package/dist/chunks/chunk-G264APQN.js +5 -0
  60. package/dist/chunks/chunk-G4JYZFEO.js +11 -0
  61. package/dist/chunks/chunk-GFFM56U2.js +4 -0
  62. package/dist/chunks/chunk-GOS3P7KS.js +132 -0
  63. package/dist/chunks/chunk-HVN37UXD.js +4 -0
  64. package/dist/chunks/chunk-IA6IODY3.js +4 -0
  65. package/dist/chunks/{chunk-HU6UIDEJ.js → chunk-IGZWZP7Z.js} +1 -1
  66. package/dist/chunks/{chunk-NR6U3WIZ.js → chunk-IJ7XFQMI.js} +1 -1
  67. package/dist/chunks/chunk-IMMGYDAB.js +6 -0
  68. package/dist/chunks/chunk-IOWBF7UK.js +10 -0
  69. package/dist/chunks/{chunk-HALUQ7ZF.js → chunk-ITGCWQFK.js} +1 -1
  70. package/dist/chunks/chunk-IVZ7QUEG.js +4 -0
  71. package/dist/chunks/{chunk-YAEVYJAR.js → chunk-IWY2HIFK.js} +1 -1
  72. package/dist/chunks/{chunk-KGJZAYQD.js → chunk-J7OBATRN.js} +1 -1
  73. package/dist/chunks/{chunk-QWAQHHRS.js → chunk-JGUEIW2W.js} +1 -1
  74. package/dist/chunks/chunk-JKL3AK5D.js +106 -0
  75. package/dist/chunks/chunk-JZ7U7RUK.js +351 -0
  76. package/dist/chunks/chunk-KJUQCCB5.js +4 -0
  77. package/dist/chunks/chunk-KST6OY76.js +10 -0
  78. package/dist/chunks/chunk-KZSAFVSY.js +129 -0
  79. package/dist/chunks/chunk-LD2ZSH3M.js +903 -0
  80. package/dist/chunks/chunk-LE6QPXN6.js +7 -0
  81. package/dist/chunks/chunk-LEAV3FFG.js +4 -0
  82. package/dist/chunks/chunk-LIIZI3HY.js +5 -0
  83. package/dist/chunks/chunk-LP72AF56.js +45 -0
  84. package/dist/chunks/{chunk-FXDIR3SQ.js → chunk-MJQ2D2OP.js} +1 -1
  85. package/dist/chunks/{chunk-6LZK4DDH.js → chunk-NHHR4DCF.js} +1 -1
  86. package/dist/chunks/chunk-NW4GW47L.js +4 -0
  87. package/dist/chunks/chunk-OALEJ6FG.js +60 -0
  88. package/dist/chunks/chunk-OIV4DIMB.js +4 -0
  89. package/dist/chunks/chunk-OJ37ZWBG.js +4 -0
  90. package/dist/chunks/chunk-OZXMPBUX.js +4 -0
  91. package/dist/chunks/{chunk-3THJYAEF.js → chunk-PG7452XE.js} +1 -1
  92. package/dist/chunks/chunk-PJCUB7YJ.js +4 -0
  93. package/dist/chunks/chunk-PTS3J4DQ.js +6 -0
  94. package/dist/chunks/{chunk-PXS5SHOV.js → chunk-PVVEEBUU.js} +1 -1
  95. package/dist/chunks/chunk-Q7BZLPBU.js +8 -0
  96. package/dist/chunks/{chunk-FOJQXLL2.js → chunk-QC66ZXPP.js} +1 -1
  97. package/dist/chunks/chunk-QXFWIL4C.js +4 -0
  98. package/dist/chunks/{chunk-PFMEUFJ7.js → chunk-R2CCD4OF.js} +1 -1
  99. package/dist/chunks/chunk-R6CGBSTC.js +22 -0
  100. package/dist/chunks/chunk-RG5GP4RB.js +5 -0
  101. package/dist/chunks/{chunk-D3NXKK2L.js → chunk-RW2F2QNP.js} +1 -1
  102. package/dist/chunks/{models-L5VF4I5O-XXNJYQMQ.js → chunk-RWPO3NZ3.js} +1 -1
  103. package/dist/chunks/chunk-SAJD4EKE.js +10 -0
  104. package/dist/chunks/chunk-SDUS2H3E.js +4 -0
  105. package/dist/chunks/chunk-SIHGKM4E.js +4 -0
  106. package/dist/chunks/chunk-SKHFU5DI.js +4 -0
  107. package/dist/chunks/{chunk-STUHNKQS.js → chunk-SM45TH22.js} +1 -1
  108. package/dist/chunks/chunk-T54CZKNJ.js +6 -0
  109. package/dist/chunks/chunk-TKFFQNAP.js +19 -0
  110. package/dist/chunks/chunk-TMV2ZDOI.js +18 -0
  111. package/dist/chunks/chunk-TRXLIL7V.js +4 -0
  112. package/dist/chunks/{chunk-SUFW24P4.js → chunk-UEEW2R4E.js} +1 -1
  113. package/dist/chunks/chunk-UHXPRU6G.js +10 -0
  114. package/dist/chunks/chunk-UPQVWHZ3.js +4 -0
  115. package/dist/chunks/{chunk-JERCOLY3.js → chunk-V35MFAUQ.js} +4 -6
  116. package/dist/chunks/chunk-V7K3KNDM.js +4 -0
  117. package/dist/chunks/chunk-VHX2GHBF.js +4 -0
  118. package/dist/chunks/chunk-VOAKRJ4R.js +4 -0
  119. package/dist/chunks/{chunk-X2GYYRVM.js → chunk-VW7TLY3P.js} +1 -1
  120. package/dist/chunks/chunk-W34AK4SK.js +65 -0
  121. package/dist/chunks/{chunk-REBNWCKI.js → chunk-WU7RNAZD.js} +1 -1
  122. package/dist/chunks/chunk-WZC4TDDM.js +6 -0
  123. package/dist/chunks/chunk-WZYS2HAK.js +4 -0
  124. package/dist/chunks/chunk-X2TKJ7KR.js +11 -0
  125. package/dist/chunks/{chunk-H2FP6DG4.js → chunk-X5ND4H4P.js} +1 -1
  126. package/dist/chunks/{chunk-4U7XXM4W.js → chunk-Y3AOGNDT.js} +1 -1
  127. package/dist/chunks/chunk-Y6DGVTKM.js +6 -0
  128. package/dist/chunks/{chunk-KENCMLRE.js → chunk-YAEHSSR4.js} +1 -1
  129. package/dist/chunks/chunk-YWPBE5LP.js +4 -0
  130. package/dist/chunks/chunk-ZAVX7G2M.js +15 -0
  131. package/dist/chunks/chunk-ZD2M73XA.js +19 -0
  132. package/dist/chunks/chunk-ZD4O6NPV.js +4 -0
  133. package/dist/chunks/chunk-ZNAMETPQ.js +4 -0
  134. package/dist/chunks/chunk-ZY6N5LVQ.js +4 -0
  135. package/dist/chunks/chunk-ZYQ4TDTT.js +81 -0
  136. package/dist/chunks/cli-VB2N7HEK.js +55 -0
  137. package/dist/chunks/cloudflare-workers-ai-system-one-YKU742EC.js +4 -0
  138. package/dist/chunks/context-CI2FKEQE.js +4 -0
  139. package/dist/chunks/cost-CZRRSIUF.js +5 -0
  140. package/dist/chunks/dist-QCNQN6DY.js +4 -0
  141. package/dist/chunks/easter-egg-3d-XR5S2O3T.js +4 -0
  142. package/dist/chunks/{event-streams-3JSFPOTZ.js → event-streams-AVE4MSS6.js} +1 -1
  143. package/dist/chunks/{execution-repo-ZLJTBWFC.js → execution-repo-5TLV2NM4.js} +1 -1
  144. package/dist/chunks/{executions-6ARGR3IO.js → executions-I3UUIGSL.js} +1 -1
  145. package/dist/chunks/file-Y5G56IUT.js +4 -0
  146. package/dist/chunks/github-copilot-BRU2SRRZ.js +4 -0
  147. package/dist/chunks/google-generative-ai-ZF5QEUZV.js +4 -0
  148. package/dist/chunks/google-vertex-4PJZZI3Y.js +4 -0
  149. package/dist/chunks/init-A6GY656J.js +4 -0
  150. package/dist/chunks/{install-cli-4IZCSDFZ.js → install-cli-FALWKQYO.js} +1 -1
  151. package/dist/chunks/{interaction-ask-G5T3H3CG.js → interaction-ask-O5HGF6CH.js} +1 -1
  152. package/dist/chunks/{interaction-plan-E5V42MUP.js → interaction-plan-JTVDN3BC.js} +1 -1
  153. package/dist/chunks/kimi-coding-ZCIBMDZ6.js +4 -0
  154. package/dist/chunks/{llama-cpp-classify-OTXZWCMW.js → llama-cpp-classify-NRUXAIGQ.js} +3 -3
  155. package/dist/chunks/local-client-stop-RS4AHNF4.js +4 -0
  156. package/dist/chunks/{memory-cli-PYOILNN5.js → memory-cli-DIT4DQF3.js} +1 -1
  157. package/dist/chunks/meta-JQH66YU7.js +4 -0
  158. package/dist/chunks/mistral-conversations-CXHOECUV.js +7 -0
  159. package/dist/chunks/model-resolver-GIBPYRKP.js +4 -0
  160. package/dist/chunks/monitor-Z2HKNY5E.js +4 -0
  161. package/dist/chunks/{node-PTK2HCDV.js → node-DAO3SX7O.js} +1 -1
  162. package/dist/chunks/{openai-codex-2REL6UQU.js → openai-codex-JULCKICT.js} +1 -1
  163. package/dist/chunks/openai-codex-responses-U6DGMGDK.js +12 -0
  164. package/dist/chunks/openai-completions-PP4XLLOM.js +9 -0
  165. package/dist/chunks/{openai-decisions-2N6ZRPZC.js → openai-decisions-JU6QQKEM.js} +1 -1
  166. package/dist/chunks/openai-responses-2SG757TL.js +6 -0
  167. package/dist/chunks/openrouter-images-32M7YZWC.js +4 -0
  168. package/dist/chunks/pi-messages-VSINMXN4.js +10 -0
  169. package/dist/chunks/radius-THYKWV4E.js +4 -0
  170. package/dist/chunks/remote-ops-2WBEFQ3E.js +14 -0
  171. package/dist/chunks/runner-5MKMRTIN.js +4 -0
  172. package/dist/chunks/runtime-DST3H5JP.js +4 -0
  173. package/dist/chunks/schedule-cli-V7Y2BBVY.js +4 -0
  174. package/dist/chunks/slack-R7SEJYMY.js +4 -0
  175. package/dist/chunks/start-ui-http-7K5JOLPU.js +43 -0
  176. package/dist/chunks/subagent-Z5IQ4L54.js +4 -0
  177. package/dist/chunks/{time-KEHDQT6K.js → time-P6PE52WL.js} +1 -1
  178. package/dist/chunks/tool-shims-YCXZWTST.js +4 -0
  179. package/dist/chunks/typesafe-system-one-M2DABJSZ.js +4 -0
  180. package/dist/chunks/ui-board-HQIE4RZG.js +5 -0
  181. package/dist/chunks/ui-decision-YBZDS4YW.js +4 -0
  182. package/dist/chunks/{ui-file-GVH53O3X.js → ui-file-SRD4ILBS.js} +1 -1
  183. package/dist/chunks/ui-view-Z25MTZT7.js +4 -0
  184. package/dist/chunks/virtual-modules-H4DXPJZB.js +4 -0
  185. package/dist/chunks/waitpoint-M6JZBSLT.js +5 -0
  186. package/dist/chunks/workers-SQ2R32TK.js +4 -0
  187. package/dist/client-bundle/client.mjs +273 -93
  188. package/dist/client-bundle/manifest.json +2 -2
  189. package/dist/core/pi-sdk.js +1 -1
  190. package/dist/domain/auth/cc-auth-cli.js +1 -1
  191. package/dist/domain/mcp/bundled-server.js +1 -1
  192. package/dist/domain/mcp/feishu/client.js +4 -0
  193. package/dist/entry/app.js +151 -559
  194. package/dist/entry/browser-cli.js +10 -10
  195. package/dist/entry/cli.js +1 -1
  196. package/dist/entry/cortex-cli.js +1 -1
  197. package/dist/entry/daemon.js +4 -4
  198. package/dist/entry/hook-cli.js +2 -2
  199. package/dist/entry/production-app-bootstrap.js +1 -1
  200. package/dist/entry/production-evidence-export-cli.js +1 -1
  201. package/dist/entry/signal-cli.js +2 -2
  202. package/dist/tui/index.js +41 -41
  203. package/package.json +3 -3
  204. package/vendor/pi/CHANGELOG.md +330 -0
  205. package/vendor/pi/dist/codemode-worker.js +2 -0
  206. package/vendor/pi/dist/core/export-html/ansi-to-html.js +57 -20
  207. package/vendor/pi/dist/core/export-html/template.css +9 -0
  208. package/vendor/pi/dist/core/export-html/template.js +166 -46
  209. package/vendor/pi/dist/core/export-html/tool-renderer.js +5 -3
  210. package/vendor/pi/dist/core/extensions/loader.js +1 -1
  211. package/vendor/pi/dist/extensions/codemode/execute.js +15 -13
  212. package/vendor/pi/dist/modes/interactive/theme/theme.js +36 -23
  213. package/vendor/pi/dist/utils/image-resize-worker.js +1 -1
  214. package/vendor/pi/dist/utils/image-resize.js +1 -1
  215. package/vendor/pi/docs/cli.md +35 -12
  216. package/vendor/pi/docs/custom-provider.md +2 -0
  217. package/vendor/pi/docs/environment-variables.md +2 -0
  218. package/vendor/pi/docs/extensions.md +3192 -225
  219. package/vendor/pi/docs/keybindings.md +2 -2
  220. package/vendor/pi/docs/llama-cpp.md +27 -19
  221. package/vendor/pi/docs/mcp.md +6 -4
  222. package/vendor/pi/docs/message-types.md +1 -1
  223. package/vendor/pi/docs/models-configuration.md +9 -3
  224. package/vendor/pi/docs/models.md +2 -1
  225. package/vendor/pi/docs/nvidia-rtx-llama-cpp.md +5 -5
  226. package/vendor/pi/docs/packages.md +24 -0
  227. package/vendor/pi/docs/prompt-templates.md +1 -1
  228. package/vendor/pi/docs/providers.md +4 -2
  229. package/vendor/pi/docs/quickstart.md +7 -3
  230. package/vendor/pi/docs/rpc-commands.md +1 -1
  231. package/vendor/pi/docs/rpc.md +4 -2
  232. package/vendor/pi/docs/sessions.md +17 -3
  233. package/vendor/pi/docs/settings.md +6 -5
  234. package/vendor/pi/docs/slash-commands.md +3 -2
  235. package/vendor/pi/docs/terminal-setup.md +3 -1
  236. package/vendor/pi/docs/tmux.md +6 -0
  237. package/vendor/pi/docs/tui.md +4 -0
  238. package/vendor/pi/docs/windows.md +27 -0
  239. package/vendor/pi/examples/extensions/README.md +2 -1
  240. package/vendor/pi/examples/extensions/custom-provider-anthropic/index.ts +27 -31
  241. package/vendor/pi/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  242. package/vendor/pi/examples/extensions/custom-provider-anthropic/package.json +1 -1
  243. package/vendor/pi/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  244. package/vendor/pi/examples/extensions/debug-provider.ts +2 -2
  245. package/vendor/pi/examples/extensions/gondolin/index.ts +4 -7
  246. package/vendor/pi/examples/extensions/gondolin/package-lock.json +19 -29
  247. package/vendor/pi/examples/extensions/gondolin/package.json +2 -2
  248. package/vendor/pi/examples/extensions/plan-mode/index.ts +23 -13
  249. package/vendor/pi/examples/extensions/plan-mode/utils.ts +42 -16
  250. package/vendor/pi/examples/extensions/preset.ts +2 -0
  251. package/vendor/pi/examples/extensions/reload-runtime.ts +17 -5
  252. package/vendor/pi/examples/extensions/subagent/README.md +14 -11
  253. package/vendor/pi/examples/extensions/subagent/index.ts +392 -171
  254. package/vendor/pi/examples/extensions/todo.ts +7 -0
  255. package/vendor/pi/examples/extensions/tools.ts +2 -0
  256. package/vendor/pi/examples/extensions/with-deps/package-lock.json +2 -2
  257. package/vendor/pi/examples/extensions/with-deps/package.json +1 -1
  258. package/vendor/pi/examples/tsconfig.json +208 -0
  259. package/vendor/pi/package.json +15 -16
  260. package/vendor/pi/schemas/models.schema.json +66 -37
  261. package/vendor/pi/schemas/settings.schema.json +18 -1
  262. package/vendor/pi-ai/bedrock.js +1 -1
  263. package/vendor/pi-ai/oauth-load.js +1 -1
  264. package/web/dist/assets/{board-math-css-BPXakv_3.js → board-math-css-DKX6FcUS.js} +1 -1
  265. package/web/dist/assets/index-D11wi0uG.js +540 -0
  266. package/web/dist/assets/index-JedYumhY.css +1 -0
  267. package/web/dist/assets/{index-WCm6wwmM.js → index-jl30Gy8P.js} +1 -1
  268. package/web/dist/assets/pdf-worker-DdZgk2mV.js +57 -0
  269. package/web/dist/assets/pdf.worker.min-Bz_KHX45.js +55 -0
  270. package/web/dist/index.html +2 -2
  271. package/web/dist/theme.css +22 -0
  272. package/dist/chunks/anthropic-messages-M3SMXACA.js +0 -8
  273. package/dist/chunks/api-GM53PHIL-GFHEXXE6.js +0 -4
  274. package/dist/chunks/azure-openai-responses-76YWXHSB.js +0 -4
  275. package/dist/chunks/bedrock-converse-stream-5UPX4NTQ.js +0 -58
  276. package/dist/chunks/child-runner-3GHOWGZP.js +0 -4
  277. package/dist/chunks/chunk-2ZNLUY2U.js +0 -128
  278. package/dist/chunks/chunk-3F6WW7HR.js +0 -13
  279. package/dist/chunks/chunk-3OKHUVEM.js +0 -7
  280. package/dist/chunks/chunk-3YHOCPQU.js +0 -10
  281. package/dist/chunks/chunk-4EX2JJWB.js +0 -4
  282. package/dist/chunks/chunk-4LLH5OWM.js +0 -10
  283. package/dist/chunks/chunk-52T37Y47.js +0 -8
  284. package/dist/chunks/chunk-7MU2AKNM.js +0 -4
  285. package/dist/chunks/chunk-AAA3UBIS.js +0 -4
  286. package/dist/chunks/chunk-ASYQHJVQ.js +0 -9
  287. package/dist/chunks/chunk-BKHDWCRT.js +0 -79
  288. package/dist/chunks/chunk-CQLH4UVX.js +0 -4
  289. package/dist/chunks/chunk-CVC66CFV.js +0 -33
  290. package/dist/chunks/chunk-D6UA4BZC.js +0 -19
  291. package/dist/chunks/chunk-DGMNI4AO.js +0 -4
  292. package/dist/chunks/chunk-DHSA5ACV.js +0 -125
  293. package/dist/chunks/chunk-DPQPXBTP.js +0 -68
  294. package/dist/chunks/chunk-DXBSQXJL.js +0 -18
  295. package/dist/chunks/chunk-E7ZMYIY6.js +0 -30
  296. package/dist/chunks/chunk-EQITBTJC.js +0 -10
  297. package/dist/chunks/chunk-EXJA5RIX.js +0 -357
  298. package/dist/chunks/chunk-FF7UELTU.js +0 -4
  299. package/dist/chunks/chunk-FH74NME3.js +0 -115
  300. package/dist/chunks/chunk-FOQ7VLIL.js +0 -17
  301. package/dist/chunks/chunk-FX6MOGLR.js +0 -11
  302. package/dist/chunks/chunk-G2V65UBA.js +0 -4
  303. package/dist/chunks/chunk-HGPBHTVD.js +0 -6
  304. package/dist/chunks/chunk-J5DVLUKY.js +0 -6
  305. package/dist/chunks/chunk-JW2HFMTF.js +0 -4
  306. package/dist/chunks/chunk-KDYEGGMW.js +0 -4
  307. package/dist/chunks/chunk-KIGMAATV.js +0 -23
  308. package/dist/chunks/chunk-KIU5FAPY.js +0 -5
  309. package/dist/chunks/chunk-KIWMQPH7.js +0 -739
  310. package/dist/chunks/chunk-L6VCIGWS.js +0 -11
  311. package/dist/chunks/chunk-LACGULCN.js +0 -10
  312. package/dist/chunks/chunk-LMSQZ6TQ.js +0 -4
  313. package/dist/chunks/chunk-MEPASGPP.js +0 -6
  314. package/dist/chunks/chunk-MFAEUHMV.js +0 -28
  315. package/dist/chunks/chunk-NAA7GF6Q.js +0 -5
  316. package/dist/chunks/chunk-NKDMKRSB.js +0 -68
  317. package/dist/chunks/chunk-NKXV32S6.js +0 -4
  318. package/dist/chunks/chunk-NVX5IPRN.js +0 -4
  319. package/dist/chunks/chunk-O3JW2F7D.js +0 -8
  320. package/dist/chunks/chunk-OE4KH3NJ.js +0 -4
  321. package/dist/chunks/chunk-OISO5JXB.js +0 -4
  322. package/dist/chunks/chunk-OPYXNSMY.js +0 -4
  323. package/dist/chunks/chunk-OSEIQ7SS.js +0 -4
  324. package/dist/chunks/chunk-P52RMIYX.js +0 -6
  325. package/dist/chunks/chunk-PBJ5MPPX.js +0 -60
  326. package/dist/chunks/chunk-PZMGBKUR.js +0 -13
  327. package/dist/chunks/chunk-PZMXHA6X.js +0 -9
  328. package/dist/chunks/chunk-Q7CE3UIE.js +0 -133
  329. package/dist/chunks/chunk-QBKCAIJG.js +0 -4
  330. package/dist/chunks/chunk-QEOFEETJ.js +0 -4
  331. package/dist/chunks/chunk-QUUEQRIT.js +0 -4
  332. package/dist/chunks/chunk-RA6HKFBV.js +0 -4
  333. package/dist/chunks/chunk-REPYBMQS.js +0 -4
  334. package/dist/chunks/chunk-SKHLZ6XY.js +0 -9
  335. package/dist/chunks/chunk-TAWLERZA.js +0 -4
  336. package/dist/chunks/chunk-TWAEABGG.js +0 -52
  337. package/dist/chunks/chunk-TZFLHVOQ.js +0 -7
  338. package/dist/chunks/chunk-UD3NMUHR.js +0 -12
  339. package/dist/chunks/chunk-UNVEZI57.js +0 -4
  340. package/dist/chunks/chunk-VQUPKMDR.js +0 -4
  341. package/dist/chunks/chunk-W25TB3PU.js +0 -4
  342. package/dist/chunks/chunk-W5LGYSPZ.js +0 -4
  343. package/dist/chunks/chunk-WEZWKMYU.js +0 -4
  344. package/dist/chunks/chunk-XAJLZR7C.js +0 -28
  345. package/dist/chunks/chunk-XH6FMP3N.js +0 -71
  346. package/dist/chunks/chunk-XSRZHN63.js +0 -4
  347. package/dist/chunks/chunk-Y3GFB5XM.js +0 -8
  348. package/dist/chunks/chunk-YG7OEPR2.js +0 -6
  349. package/dist/chunks/chunk-YHIWOGVL.js +0 -4
  350. package/dist/chunks/chunk-YKKEI5GI.js +0 -4
  351. package/dist/chunks/chunk-YZSHTWNM.js +0 -92
  352. package/dist/chunks/chunk-Z4H3VDHI.js +0 -4
  353. package/dist/chunks/cli-5DBTRMHU.js +0 -53
  354. package/dist/chunks/client-XOGYH5UR.js +0 -4
  355. package/dist/chunks/cloudflare-workers-ai-system-one-32JCFHI3.js +0 -4
  356. package/dist/chunks/config-DJSQI77S-335IXHSM.js +0 -4
  357. package/dist/chunks/context-VCQH5OB6.js +0 -4
  358. package/dist/chunks/cost-PGGFI7QJ.js +0 -5
  359. package/dist/chunks/dist-PUKMZ7GW.js +0 -4
  360. package/dist/chunks/easter-egg-3d-MO4MOEVF.js +0 -4
  361. package/dist/chunks/es5-VNTQPCKX.js +0 -4
  362. package/dist/chunks/file-7BN7RCAY.js +0 -4
  363. package/dist/chunks/gateway-UCRPMR75.js +0 -36
  364. package/dist/chunks/github-copilot-HAI2DA62.js +0 -4
  365. package/dist/chunks/google-generative-ai-2VXWLHWI.js +0 -4
  366. package/dist/chunks/google-vertex-UA36QP2U.js +0 -4
  367. package/dist/chunks/init-HA7FAQ73.js +0 -4
  368. package/dist/chunks/kimi-coding-HMJRKCPA.js +0 -4
  369. package/dist/chunks/local-client-stop-SQRU7ZZM.js +0 -4
  370. package/dist/chunks/meta-KY3LNFV2.js +0 -4
  371. package/dist/chunks/mistral-conversations-34F66L3O.js +0 -7
  372. package/dist/chunks/model-resolver-N3DTAQ2S.js +0 -4
  373. package/dist/chunks/openai-codex-responses-ZBVHREB3.js +0 -12
  374. package/dist/chunks/openai-completions-VVIB26SH.js +0 -9
  375. package/dist/chunks/openai-responses-735XA2ZX.js +0 -6
  376. package/dist/chunks/openrouter-images-3IKETHAC.js +0 -4
  377. package/dist/chunks/pi-messages-I3E4ZFHA.js +0 -10
  378. package/dist/chunks/radius-HXRZVBDB.js +0 -4
  379. package/dist/chunks/remote-ops-BALZYKH6.js +0 -14
  380. package/dist/chunks/runner-PLVZDGHB.js +0 -4
  381. package/dist/chunks/runtime-6YLTA2ZD.js +0 -4
  382. package/dist/chunks/schedule-cli-OLASBBYJ.js +0 -4
  383. package/dist/chunks/slack-WAGSPZUX.js +0 -4
  384. package/dist/chunks/start-ui-http-QALT7C3P.js +0 -43
  385. package/dist/chunks/subagent-E3UC7ZHC.js +0 -4
  386. package/dist/chunks/tool-shims-Q6P6UXVC.js +0 -4
  387. package/dist/chunks/typesafe-system-one-6ULACYD4.js +0 -4
  388. package/dist/chunks/ui-board-4GYW6KKW.js +0 -5
  389. package/dist/chunks/ui-decision-U2FXSEC2.js +0 -4
  390. package/dist/chunks/ui-view-O7PLANT7.js +0 -4
  391. package/dist/chunks/virtual-modules-IDC5YKZJ.js +0 -4
  392. package/dist/chunks/waitpoint-2FGQBIAC.js +0 -5
  393. package/dist/chunks/workers-XN4PSTH6.js +0 -4
  394. package/vendor/aistatus/gateway-cli.js +0 -21
  395. package/vendor/pi/examples/extensions/sandbox/index.ts +0 -321
  396. package/vendor/pi/examples/extensions/sandbox/package-lock.json +0 -92
  397. package/vendor/pi/examples/extensions/sandbox/package.json +0 -19
  398. package/web/dist/assets/index-BHZpFXhc.js +0 -525
  399. package/web/dist/assets/index-DqWMdMkh.css +0 -1
  400. package/web/dist/assets/pdf-worker-Hp15W1QJ.js +0 -57
  401. package/web/dist/assets/pdf.worker.min-DnhTvCwe.js +0 -55
@@ -1,36 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{b as pt}from"./chunk-XSRZHN63.js";import{a as mt,b as de,c as pe,d as D,e as me,f as gt,g as B,h as ge}from"./chunk-YZSHTWNM.js";import{a as he}from"./chunk-JERCOLY3.js";import{e as fe}from"./chunk-WHC7AYZD.js";var Dt=fe(he(),1);import*as d from"fs";import*as b from"path";import*as Mt from"os";import*as Ut from"crypto";import*as g from"fs";import*as q from"path";import*as E from"fs";import*as W from"path";import*as Ct from"os";import*as x from"fs";import*as Pt from"os";import*as z from"path";import{randomUUID as fn}from"crypto";var _e={500:15,502:10,503:10,529:30},ye=10;function Et(t){return t>=500}var L=60,ke=5;function _t(){return{cooldownUntil:0,errors:[],totalRequests:0,totalErrors:0}}function I(){return Date.now()/1e3}var we=500,Tt=class{_state=new Map;_modelState=new Map;_getState(t,e){if(e!=null){let s=`${t}\0${e}`,r=this._modelState.get(s);return r||(r=_t(),this._modelState.set(s,r),this._modelState.size>we&&this._evictModelState()),r}let n=this._state.get(t);return n||(n=_t(),this._state.set(t,n)),n}_evictModelState(){let t=I()-L*2;for(let[e,n]of this._modelState)(n.errors.length>0?n.errors[n.errors.length-1]:0)<t&&n.cooldownUntil<I()&&this._modelState.delete(e)}isHealthy(t,e){let n=this._getState(t,e),s=I();if(s<n.cooldownUntil)return!1;let r=s-L,o=0;for(let i of n.errors)i>r&&o++;return o<ke}recordError(t,e,n){let s=this._getState(t,n),r=I();if(s.totalRequests++,!Et(e))return;s.errors.push(r),s.errors.length>50&&s.errors.splice(0,s.errors.length-50),s.totalErrors++;let o=_e[e]??ye;s.cooldownUntil=Math.max(s.cooldownUntil,r+o)}soonestCooldown(t){let e=null,n=I();for(let s of t){let r=this._state.get(s),o=r?Math.max(0,r.cooldownUntil-n):0;(!e||o<e.remaining)&&(e={id:s,remaining:o})}return e}recordSuccess(t,e){let n=this._getState(t,e);n.totalRequests++,n.cooldownUntil=0}errorCount(t,e){return this._getState(t,e).totalErrors}summary(){let t=I(),e={};for(let[n,s]of this._state){let r=t-L,o=0;for(let i of s.errors)i>r&&o++;e[n]={healthy:this.isHealthy(n),recent_errors:o,total_errors:s.totalErrors,total_requests:s.totalRequests,cooldown_remaining:Math.max(0,Math.round((s.cooldownUntil-t)*10)/10)}}if(this._modelState.size>0){let n={};for(let[s,r]of this._modelState){let[o,i]=s.split("\0"),a=t-L,c=0;for(let u of r.errors)u>a&&c++;let l=`${o}/${i}`;n[l]={healthy:this.isHealthy(o,i),recent_errors:c,total_errors:r.totalErrors,total_requests:r.totalRequests,cooldown_remaining:Math.max(0,Math.round((r.cooldownUntil-t)*10)/10)}}e.model_health=n}return e}},ot=["model","provider","billing_mode"];function Ot(t){return t===void 0?[]:Array.isArray(t)?[...t]:[t]}var be=256*1024,Se=64,ve=/^(\d{4}-\d{2})\.jsonl$/,Ee=class{constructor(t){this.projectDir=t}files=new Map;providerIds=new Map;providers=[];modelIds=new Map;models=[];billingModeIds=new Map;billingModes=[];interners={provider:t=>X(t,this.providerIds,this.providers),model:t=>X(t,this.modelIds,this.models),billingMode:t=>X(t,this.billingModeIds,this.billingModes)};prewarm(t="month"){this.syncFiles(t)}report(t="month",e){let n=Ot(e),s=nt(t),r=this.syncFiles(t),o=n.map(l=>this.groupNames(l)),i=o.map(l=>Math.max(l.length,1)),a=It(),c=new Map;for(let l of r){let u=this.files.get(l);u&&Re(u.columns,s,n,i,a,c)}return Be(t,n,i,a,c,o)}syncFiles(t){let e=Te(this.projectDir,nt(t));for(let n of e)this.syncFile(n);return e}syncFile(t){let e=g.statSync(t),n=this.files.get(t);if(!n||Oe(t,n,e)){this.files.set(t,this.loadFile(t));return}e.size>n.readOffset&&this.extendFile(t,n)}loadFile(t){let e=xe(),n=yt(t,0,s=>{kt(e,s,this.interners)});return{columns:e,readOffset:n.readOffset,guard:st(t,n.readOffset),dev:n.stat.dev,ino:n.stat.ino,mtimeMs:n.stat.mtimeMs,ctimeMs:n.stat.ctimeMs}}extendFile(t,e){let n=yt(t,e.readOffset,s=>{kt(e.columns,s,this.interners)});e.readOffset=n.readOffset,e.guard=st(t,n.readOffset),e.dev=n.stat.dev,e.ino=n.stat.ino,e.mtimeMs=n.stat.mtimeMs,e.ctimeMs=n.stat.ctimeMs}groupNames(t){return t==="model"?this.models:t==="billing_mode"?this.billingModes:this.providers}};function nt(t,e=new Date){if(t==="today")return new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime();if(t==="week")return e.getTime()-7*864e5;if(t==="month")return e.getTime()-30*864e5;if(t==="all")return null;throw new Error(`Unsupported period: ${t}`)}function Te(t,e){if(!g.existsSync(t))return[];let n=e===null?null:Ue(new Date(e));return g.readdirSync(t).filter(s=>s.endsWith(".jsonl")).map(s=>q.join(t,s)).filter(s=>Me(s,n,e)).sort()}function Me(t,e,n){if(e===null||n===null)return!0;let s=q.basename(t).match(ve);return s===null||s[1]>=e?!0:g.statSync(t).mtimeMs>=n}function Ue(t){let e=String(t.getUTCMonth()+1).padStart(2,"0");return`${t.getUTCFullYear()}-${e}`}function Oe(t,e,n){return n.dev!==e.dev||n.ino!==e.ino||n.size<e.readOffset||n.size===e.readOffset&&$e(e,n)?!0:!st(t,e.readOffset).equals(e.guard)}function $e(t,e){return e.mtimeMs!==t.mtimeMs||e.ctimeMs!==t.ctimeMs}function st(t,e){let n=Math.min(e,Se);if(n===0)return Buffer.alloc(0);let s=g.openSync(t,"r");try{let r=Buffer.allocUnsafe(n),o=g.readSync(s,r,0,n,e-n);return r.subarray(0,o)}finally{g.closeSync(s)}}function yt(t,e,n){let s=g.openSync(t,"r");try{return{readOffset:Ie(s,e,n),stat:g.fstatSync(s)}}finally{g.closeSync(s)}}function Ie(t,e,n){let s=Buffer.allocUnsafe(be),r=Buffer.alloc(0),o=e;for(;;){let i=g.readSync(t,s,0,s.length,o);if(i===0)break;o+=i,r=Ne(Buffer.concat([r,s.subarray(0,i)]),n)}return o-r.length}function Ne(t,e){let n=0;for(;;){let s=t.indexOf(10,n);if(s<0)return Buffer.from(t.subarray(n));Ae(t.subarray(n,s),e),n=s+1}}function Ae(t,e){if(t.length!==0)try{e(JSON.parse(t.toString("utf8")))}catch{}}function xe(){return{timestamps:[],providerIds:[],modelIds:[],billingModeIds:[],inputs:[],outputs:[],costs:[],fallbacks:[],latencies:[]}}function kt(t,e,n){t.timestamps.push(Ce(e.ts)),t.providerIds.push(n.provider(String(e.provider??"unknown"))),t.modelIds.push(n.model(String(e.model??"unknown"))),t.billingModeIds.push(n.billingMode(String(e.billing_mode??"unknown"))),t.inputs.push(Z(e.in)),t.outputs.push(Z(e.out)),t.costs.push(rt(e.cost)),t.fallbacks.push(e.fallback?1:0),t.latencies.push(Z(e.latency_ms))}function Ce(t){if(typeof t!="string")return Number.NEGATIVE_INFINITY;let e=Date.parse(t);return Number.isFinite(e)?e:Number.NEGATIVE_INFINITY}function Re(t,e,n,s,r,o){let i=n.map(a=>De(t,a));for(let a=0;a<t.timestamps.length;a++)e!==null&&t.timestamps[a]<e||($t(r,t,a,!1),i.length>0&&je(o,Fe(i,s,a),t,a))}function Fe(t,e,n){let s=0;for(let r=0;r<t.length;r++)s=s*e[r]+t[r][n];return s}function Pe(t,e){let n=new Array(e.length),s=t;for(let r=e.length-1;r>=0;r--)n[r]=s%e[r],s=Math.floor(s/e[r]);return n}function De(t,e){return e==="model"?t.modelIds:e==="billing_mode"?t.billingModeIds:t.providerIds}function je(t,e,n,s){let r=t.get(e)??It();$t(r,n,s,!0),t.set(e,r)}function $t(t,e,n,s){t.requests++,t.input_tokens+=e.inputs[n],t.output_tokens+=e.outputs[n];let r=t.cost_usd+e.costs[n];t.cost_usd=s?At(r):r,t.fallback_requests+=e.fallbacks[n],t.latency_sum+=e.latencies[n]}function Be(t,e,n,s,r,o){let i={summary:qe(s,t)};if(e.length===0)return i;let a=e.length===1?`${e[0]}s`:"rows";return i[a]=Le(e,n,r,o),i}function Le(t,e,n,s){let r=[...n].map(([o,i])=>{let a=Pe(o,e);return We(t.map((c,l)=>[c,s[l][a[l]]??"unknown"]),i)});return r.sort((o,i)=>rt(i.cost_usd)-rt(o.cost_usd)||He(t,o,i)),r}function He(t,e,n){for(let s of t){let r=String(e[s]??"").localeCompare(String(n[s]??""));if(r!==0)return r}return 0}function qe(t,e){return{period:e,requests:t.requests,input_tokens:t.input_tokens,output_tokens:t.output_tokens,cost_usd:At(t.cost_usd),avg_latency_ms:Nt(t),fallback_requests:t.fallback_requests}}function We(t,e){return{...Object.fromEntries(t),requests:e.requests,input_tokens:e.input_tokens,output_tokens:e.output_tokens,cost_usd:e.cost_usd,avg_latency_ms:Nt(e),fallback_requests:e.fallback_requests}}function It(){return{requests:0,input_tokens:0,output_tokens:0,cost_usd:0,fallback_requests:0,latency_sum:0}}function Nt(t){return t.requests===0?0:Math.round(t.latency_sum/t.requests*100)/100}function X(t,e,n){let s=e.get(t);if(s!==void 0)return s;let r=n.length;return e.set(t,r),n.push(t),r}function Z(t){let e=Number(t);return Number.isFinite(e)?Math.floor(e):0}function rt(t){let e=Number(t);return Number.isFinite(e)?e:0}function At(t){return Math.round(t*1e8)/1e8}var ze=class{_baseDir;_projectDir;_aggregateIndex;constructor(t,e){this._baseDir=t??b.join(Mt.homedir(),".aistatus","usage");let n=e??process.cwd(),s=Ut.createHash("sha256").update(n).digest("hex").slice(0,12);this._projectDir=b.join(this._baseDir,"projects",s),d.mkdirSync(this._projectDir,{recursive:!0}),this._ensureManifest(n),this._aggregateIndex=new Ee(this._projectDir)}append(t){let e=this._monthKey(t.ts),n=b.join(this._projectDir,`${e}.jsonl`);d.appendFileSync(n,JSON.stringify(t)+`
5
- `,"utf-8")}aggregate(t="month",e){return this._aggregateIndex.report(t,e)}prewarm(t="month"){this._aggregateIndex.prewarm(t)}read(t="month",e=!1){let n=e?this._allProjectDirs():[this._projectDir],s=Ge(t),r=[];for(let o of n){if(!d.existsSync(o))continue;let i=d.readdirSync(o).filter(a=>a.endsWith(".jsonl")).sort();for(let a of i){let c=b.join(o,a),l=d.readFileSync(c,"utf-8");for(let u of l.split(`
6
- `)){if(!u.trim())continue;let f;try{f=JSON.parse(u)}catch{continue}if(s){let h=wt(f.ts);if(!h||h<s)continue}f.project||(f.project=b.basename(o)),r.push(f)}}}return r}exportCsv(t,e){let n=["ts","project","provider","model","in","out","cost","fallback","latency_ms"],s=n.join(","),r=t.map(o=>n.map(i=>String(o[i]??"")).join(","));d.mkdirSync(b.dirname(e),{recursive:!0}),d.writeFileSync(e,[s,...r].join(`
7
- `)+`
8
- `,"utf-8")}exportJson(t,e){d.mkdirSync(b.dirname(e),{recursive:!0}),d.writeFileSync(e,JSON.stringify(t,null,2),"utf-8")}_ensureManifest(t){let e=b.join(this._projectDir,"manifest.json");if(d.existsSync(e))return;let n={path:t,created:new Date().toISOString()};d.writeFileSync(e,JSON.stringify(n,null,2),"utf-8")}_allProjectDirs(){let t=b.join(this._baseDir,"projects");return d.existsSync(t)?d.readdirSync(t).map(e=>b.join(t,e)).filter(e=>d.statSync(e).isDirectory()):[]}_monthKey(t){let e=wt(t)??new Date,n=e.getUTCFullYear(),s=String(e.getUTCMonth()+1).padStart(2,"0");return`${n}-${s}`}};function wt(t){if(!t||typeof t!="string")return null;let e=new Date(t);return isNaN(e.getTime())?null:e}function Ge(t){let e=nt(t);return e===null?null:new Date(e)}var xt=class{storage;uploader;constructor(t,e){this.storage=t??new ze,this.uploader=e??null}recordUsage(t){let e=new Set(["ts","provider","model","in","out","cost","fallback","latency_ms","billing_mode","cache_creation_in","cache_read_in"]),n={ts:new Date().toISOString(),provider:t.provider,model:t.model,in:t.input_tokens,out:t.output_tokens,cost:it(t.cost??0),fallback:t.fallback,latency_ms:t.latency_ms,billing_mode:t.billing_mode};if(t.cache_creation_input_tokens&&(n.cache_creation_in=t.cache_creation_input_tokens),t.cache_read_input_tokens&&(n.cache_read_in=t.cache_read_input_tokens),t.metadata)for(let[s,r]of Object.entries(t.metadata))e.has(s)||(n[s]=r);return this.storage.append(n),this.uploader?.upload(n),n}prewarm(t="month"){this.storage.prewarm?.(t)}report(t="month",e){if(typeof this.storage.aggregate=="function")return this.storage.aggregate(t,e);let n=this.storage.read(t),s=Ot(e),r={summary:Je(n,t)};return s.length===0||(r[s.length===1?`${s[0]}s`:"rows"]=Ke(n,s)),r}summary(t="month"){return this.report(t).summary}byModel(t="month"){return this.report(t,"model").models}byProvider(t="month"){return this.report(t,"provider").providers}};function Je(t,e){let n=t.length,s=t.reduce((a,c)=>a+A(c.in),0),r=t.reduce((a,c)=>a+A(c.out),0),o=it(t.reduce((a,c)=>a+H(c.cost),0)),i=t.reduce((a,c)=>a+A(c.latency_ms),0);return{period:e,requests:n,input_tokens:s,output_tokens:r,cost_usd:o,avg_latency_ms:n?Math.round(i/n*100)/100:0,fallback_requests:t.filter(a=>a.fallback).length}}function Ke(t,e){let n=new Map;for(let r of t){let o=e.map(c=>String(r[c]??"unknown")),i=JSON.stringify(o),a=n.get(i)??{names:o,bucket:Ve()};Qe(a.bucket,r),n.set(i,a)}let s=[...n.values()].map(({names:r,bucket:o})=>Xe(e,r,o));return s.sort((r,o)=>H(o.cost_usd)-H(r.cost_usd)||Ye(e,r,o)),s}function Ye(t,e,n){for(let s of t){let r=String(e[s]??"").localeCompare(String(n[s]??""));if(r!==0)return r}return 0}function Ve(){return{requests:0,input_tokens:0,output_tokens:0,cost_usd:0,fallback_requests:0,latency_sum:0}}function Qe(t,e){t.requests++,t.input_tokens+=A(e.in),t.output_tokens+=A(e.out),t.cost_usd=it(t.cost_usd+H(e.cost)),e.fallback&&t.fallback_requests++,t.latency_sum+=A(e.latency_ms)}function Xe(t,e,n){return{...Object.fromEntries(t.map((s,r)=>[s,e[r]])),requests:n.requests,input_tokens:n.input_tokens,output_tokens:n.output_tokens,cost_usd:n.cost_usd,avg_latency_ms:n.requests?Math.round(n.latency_sum/n.requests*100)/100:0,fallback_requests:n.fallback_requests}}function A(t){let e=Number(t);return Number.isFinite(e)?Math.floor(e):0}function H(t){let e=Number(t);return Number.isFinite(e)?e:0}function it(t){return Math.round(t*1e8)/1e8}var Ze="https://aistatus.cc",tn=3600,Rt=class{_baseUrl;_ttlSeconds;_memoryCache=new Map;_cachePath;_pendingRefreshes=new Map;constructor(t=Ze,e=tn){this._baseUrl=t.replace(/\/+$/,""),this._ttlSeconds=e,this._cachePath=W.join(Ct.homedir(),".aistatus","usage","pricing-cache.json")}calculateCost(t,e,n,s){return bt(this.getPricing(t,e),n,s)}async calculateCostAsync(t,e,n,s){return bt(await this._getPricingAfterRefresh(t,e),n,s)}calculateCostWithCache(t,e,n,s,r,o){return St(this.getPricing(t,e),n,s,r,o)}async calculateCostWithCacheAsync(t,e,n,s,r,o){let i=await this._getPricingAfterRefresh(t,e);return St(i,n,s,r,o)}getPricing(t,e){let n=this._normalizeKey(t,e),s=Date.now()/1e3,r=this._memoryCache.get(n);if(r&&this._isFresh(r,s))return r.pricing;let o=this._readFileCache(),i=o[n];return i&&this._isFresh(i,s)?(this._memoryCache.set(n,i),i.pricing):(this._refreshPricing(n,t,e,o),null)}async _getPricingAfterRefresh(t,e){let n=this._normalizeKey(t,e),s=this.getPricing(t,e);if(s)return s;await this._pendingRefreshes.get(n);let r=Date.now()/1e3,o=this._memoryCache.get(n);if(o&&this._isFresh(o,r))return o.pricing;let i=this._readFileCache()[n];return!i||!this._isFresh(i,r)?null:(this._memoryCache.set(n,i),i.pricing)}_refreshPricing(t,e,n,s){let r=this._pendingRefreshes.get(t);if(r)return r;let o=this._fetchAndCachePricing(t,e,n,s).catch(()=>{}).finally(()=>this._pendingRefreshes.delete(t));return this._pendingRefreshes.set(t,o),o}async _fetchAndCachePricing(t,e,n,s){let r=await this._fetchPricing(e,n);if(r==null)return;let o={ts:Date.now()/1e3,pricing:r};this._memoryCache.set(t,o),s[t]=o,this._writeFileCache(s)}async _fetchPricing(t,e){let[n,s]=this._splitModel(t,e),r=this._candidateQueries(s),o=[];for(let h of r)try{let m=`${this._baseUrl}/api/models?q=${encodeURIComponent(h)}`,p=await fetch(m,{signal:AbortSignal.timeout(3e3)});if(!p.ok)continue;if(o=(await p.json()).models??[],o.length>0)break}catch{continue}let i=this._pickModelMatch(n,s,o);if(!i)return null;let a=i.pricing??{},c=j(a.prompt),l=j(a.completion);if(c==null&&l==null)return null;let u=j(a.input_cache_read),f=j(a.input_cache_write);return{input_per_million:c==null?null:c*1e6,output_per_million:l==null?null:l*1e6,input_cache_read_per_million:u==null?null:u*1e6,input_cache_write_per_million:f==null?null:f*1e6}}_pickModelMatch(t,e,n){let s=N(`${t}/${e}`),r=N(e);for(let o of n)if(N(String(o.id??""))===s)return o;for(let o of n)if(N(String(o.id??"")).endsWith(`/${r}`))return o;for(let o of n)if(N(String(o.id??"")).includes(r))return o;return n[0]??null}_readFileCache(){try{if(!E.existsSync(this._cachePath))return{};let t=JSON.parse(E.readFileSync(this._cachePath,"utf-8"));if(typeof t=="object"&&t!==null)return t}catch{}return{}}_writeFileCache(t){let e=W.dirname(this._cachePath);E.mkdirSync(e,{recursive:!0});let n=`${this._cachePath}.tmp.${process.pid}`;E.writeFileSync(n,JSON.stringify(t,null,2),"utf-8"),E.renameSync(n,this._cachePath)}_normalizeKey(t,e){let[n,s]=this._splitModel(t,e);return`${n}/${s}`}_splitModel(t,e){if(e.includes("/")){let n=e.indexOf("/");return[e.slice(0,n),e.slice(n+1)]}return[t,e]}_isFresh(t,e){if(!t)return!1;let n=j(t.ts);return n!=null&&e-n<this._ttlSeconds}_candidateQueries(t){let e=[t],n=N(t);n!==t&&e.push(n);let s=en(t);e.push(...s),e.push(...s.map(i=>i.replace(/\./g,"-"))),e.push(n.replace(/\./g,"-")),e.push(n.replace(/-/g," "));let r=[],o=new Set;for(let i of e){let a=i.trim();!a||o.has(a)||(o.add(a),r.push(a))}return r}};function bt(t,e,n){if(!t)return 0;let{input_per_million:s,output_per_million:r}=t;if(s==null&&r==null)return 0;let o=s==null?0:Math.max(e,0)/1e6*s,i=r==null?0:Math.max(n,0)/1e6*r;return Ft(o+i)}function St(t,e,n,s,r){if(!t)return 0;let{input_per_million:o,output_per_million:i}=t;if(o==null&&i==null)return 0;let a=o==null?0:Math.max(e,0)/1e6*o,c=i==null?0:Math.max(n,0)/1e6*i,l=o==null?0:t.input_cache_write_per_million??o*1.25,u=o==null?0:t.input_cache_read_per_million??o*.1,f=Math.max(s,0)/1e6*l,h=Math.max(r,0)/1e6*u;return Ft(a+c+f+h)}function Ft(t){return Math.round(t*1e8)/1e8}function N(t){return t.toLowerCase().trim().replace(/(?<=\d)-(?=\d)/g,".")}function en(t){let e=t.toLowerCase().trim().match(/^(.+?)-(\d+)-(\d+)-(\d{8})$/);if(!e)return[];let[,n,s,r]=e;return[`${n}-${s}.${r}`]}function j(t){if(t==null)return null;let e=Number(t);return Number.isFinite(e)?e:null}var nn=z.join(Pt.homedir(),".aistatus"),at=z.join(nn,"config.yaml"),sn={name:null,org:null,email:null,uploadEnabled:!1},rn={};function ct(t={}){let e=t.env??process.env,n=t.skipFile?{}:on(t.filePath),s=an(e);return cn(rn,s,n,sn)}function on(t=at){if(!x.existsSync(t))return{};let e=x.readFileSync(t,"utf-8");if(!e.trim())return{};let n=Dt.default.parse(e);return un(n)?jt({name:T(n.name),org:T(n.org),email:T(n.email),uploadEnabled:lt(n.uploadEnabled??n.upload_enabled)}):{}}function an(t){return jt({name:T(t.AISTATUS_NAME),org:T(t.AISTATUS_ORG),email:T(t.AISTATUS_EMAIL),uploadEnabled:lt(t.AISTATUS_UPLOAD_ENABLED)})}function cn(...t){return{name:tt(...t.map(e=>e.name)),org:tt(...t.map(e=>e.org)),email:tt(...t.map(e=>e.email)),uploadEnabled:ln(...t.map(e=>e.uploadEnabled))}}function jt(t){return{name:T(t.name),org:T(t.org),email:T(t.email),uploadEnabled:lt(t.uploadEnabled)}}function T(t){if(t!==void 0){if(t===null)return null;if(typeof t=="string")return t}}function lt(t){if(typeof t=="boolean")return t;if(typeof t!="string")return;let e=t.trim().toLowerCase();if(["1","true","yes","on"].includes(e))return!0;if(["0","false","no","off"].includes(e))return!1}function tt(...t){for(let e of t)if(e!==void 0)return e;return null}function ln(...t){for(let e of t)if(e!==void 0)return e;return!1}function un(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Bt="0.0.11",hn="https://aistatus.cc",vt=100,dn=1e3,pn=6e4,mn=1e4,Lt=5e3,Ht=Symbol.for(`aistatus.usage-upload-queues@${Bt}`);function et(t,e){return t.length>e?t.slice(0,e):t}async function qt(t,e){let n,s=new Promise(r=>{n=setTimeout(r,Math.max(0,e))});try{await Promise.race([t,s])}finally{clearTimeout(n)}}var gn=class{constructor(t){this.url=t,setInterval(()=>{this.flush()},pn).unref?.()}enqueued=0;exitMark=0;records=[];head=null;inflight=null;push(t){this.records.push(t),this.enqueued+=1;let e=(this.head?.records.length??0)+this.records.length-dn;e>0&&this.records.splice(0,e),this.records.length>=vt&&!this.head&&this.flush()}hasWork(){return this.head!==null||this.records.length>0}flush(){return this.inflight??=this.drain().finally(()=>{this.inflight=null}),this.inflight}async flushAll(){this.inflight&&await this.inflight,this.hasWork()&&await this.flush()}async drain(){for(;;){if(!this.head){if(this.records.length===0)return;this.head={id:fn(),records:this.records.splice(0,vt)}}if(!await this.send(this.head))return;this.head=null}}async send(t){let e;try{let o={batch_id:t.id,sdk_version:Bt,records:t.records};e=JSON.stringify(o)}catch{return!0}let n=new AbortController,s,r=new Promise((o,i)=>{s=setTimeout(()=>{n.abort(),i(new Error("usage upload timed out"))},mn),s.unref?.()});try{let o=await Promise.race([fetch(this.url,{method:"POST",headers:{"Content-Type":"application/json"},body:e,signal:n.signal}),r]);return await Promise.race([o.text(),r]).catch(()=>{}),!(o.status===429||o.status>=500)}catch{return!1}finally{clearTimeout(s)}}};function ut(){return globalThis[Ht]}function _n(t){for(let e of t.values())e.enqueued!==e.exitMark&&e.hasWork()&&(e.exitMark=e.enqueued,e.flush())}function yn(t){let e=ut();if(!e){let s=new Map;globalThis[Ht]=s,typeof process<"u"&&typeof process.on=="function"&&process.on("beforeExit",()=>_n(s)),e=s}let n=e.get(t);return n||(n=new gn(t),e.set(t,n)),n}async function Wt(t=Lt){let e=ut();!e||e.size===0||await qt(Promise.all([...e.values()].map(n=>n.flushAll())).then(()=>{}),t)}var zt=class{config;url;constructor(t,e=hn){this.config=t,this.url=pt(e,"/api/usage/upload")}setConfig(t){this.config=t}get enabled(){return!!(this.config.uploadEnabled&&this.config.name&&this.config.email)}upload(t){if(this.enabled)try{yn(this.url).push(this.buildRecord(t))}catch{}}async flush(t=Lt){let e=ut()?.get(this.url);e&&await qt(e.flushAll(),t)}buildRecord(t){return{ts:t.ts,name:et(this.config.name,200),organization:this.config.org?et(this.config.org,200):null,email:et(this.config.email,254),provider:t.provider,model:t.model,input_tokens:t.in??0,output_tokens:t.out??0,cache_creation_input_tokens:t.cache_creation_in??0,cache_read_input_tokens:t.cache_read_in??0,cost_usd:t.cost??0,latency_ms:t.latency_ms??0}}};import*as J from"fs";import*as Zt from"os";import*as te from"path";import*as ee from"http";import*as C from"url";import*as O from"fs";import*as K from"path";import{timingSafeEqual as kn}from"crypto";import*as $ from"fs";import*as ne from"os";import*as Y from"path";import*as ae from"http";import*as V from"net";import*as ce from"stream";import*as le from"tls";function Gt(t,e,n){if(!t||!t.enabled||(t.public_paths??["/health"]).some(c=>e===c||e.startsWith(c+"/")))return!0;let r=(t.header??"authorization").toLowerCase(),o=n[r],i=Array.isArray(o)?o[0]??"":o??"",a;return r==="authorization"?a=i.toLowerCase().startsWith("bearer ")?i.slice(7).trim():i.trim():a=i.trim(),a?t.keys.some(c=>{let l=Buffer.from(c,"utf-8"),u=Buffer.from(a,"utf-8");return l.length!==u.length?!1:kn(l,u)}):!1}function wn(t){let e=JSON.parse(t.toString("utf-8")),n=[],s=e.system;if(s){if(typeof s=="string")n.push({role:"system",content:s});else if(Array.isArray(s)){let o=s.filter(i=>i.type==="text").map(i=>i.text??"").join(`
9
- `);o&&n.push({role:"system",content:o})}}for(let o of e.messages??[]){let i=o.role??"user",a=o.content;if(typeof a=="string")n.push({role:i,content:a});else if(Array.isArray(a)){let c=a.filter(l=>l.type==="text").map(l=>l.text??"");c.length>0?n.push({role:i,content:c.join(`
10
- `)}):n.push({role:i,content:JSON.stringify(a)})}}let r={model:e.model??"",messages:n};for(let o of["max_tokens","temperature","top_p","stream"])o in e&&(r[o]=e[o]);return"stop_sequences"in e&&(r.stop=e.stop_sequences),e.stream&&(r.stream_options={include_usage:!0}),Buffer.from(JSON.stringify(r),"utf-8")}function bn(t,e=""){let n=JSON.parse(t.toString("utf-8")),s="",r="end_turn",o=n.choices??[];if(o.length>0){let c=o[0];s=c.message?.content??"";let l=c.finish_reason??"stop";r={stop:"end_turn",length:"max_tokens"}[l]??"end_turn"}let i=n.usage??{},a={id:`msg_${n.id??"gw"}`,type:"message",role:"assistant",model:e||n.model||"",content:[{type:"text",text:s}],stop_reason:r,stop_sequence:null,usage:{input_tokens:i.prompt_tokens??0,output_tokens:i.completion_tokens??0}};return Buffer.from(JSON.stringify(a),"utf-8")}function M(t,e){return Buffer.from(`event: ${t}
11
- data: ${JSON.stringify(e)}
12
-
13
- `,"utf-8")}async function*Sn(t,e=""){let n=`msg_gw_${Math.floor(Date.now()/1e3)}`;yield M("message_start",{type:"message_start",message:{id:n,type:"message",role:"assistant",model:e,content:[],stop_reason:null,stop_sequence:null,usage:{input_tokens:0,output_tokens:0}}}),yield M("content_block_start",{type:"content_block_start",index:0,content_block:{type:"text",text:""}});let s=0,r="",o=!1;for await(let i of t)for(r+=i.toString("utf-8");r.includes(`
14
-
15
- `);){let a=r.indexOf(`
16
-
17
- `),c=r.slice(0,a).trim();if(r=r.slice(a+2),!!c)for(let l of c.split(`
18
- `)){if(!l.startsWith("data:"))continue;let u=l.slice(5).trim();if(u==="[DONE]"){if(o)return;o=!0,yield M("content_block_stop",{type:"content_block_stop",index:0}),yield M("message_delta",{type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{output_tokens:s}}),yield M("message_stop",{type:"message_stop"});return}let f;try{f=JSON.parse(u)}catch{continue}if(f.usage&&typeof f.usage=="object"){let S=f.usage;S.completion_tokens!=null&&(s=S.completion_tokens)}let h=f.choices??[];if(h.length===0)continue;let p=(h[0].delta??{}).content;if(typeof p=="string"&&p&&(yield M("content_block_delta",{type:"content_block_delta",index:0,delta:{type:"text_delta",text:p}})),h[0].finish_reason){if(o)return;o=!0,yield M("content_block_stop",{type:"content_block_stop",index:0}),yield M("message_delta",{type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{output_tokens:s}}),yield M("message_stop",{type:"message_stop"});return}}}}var vn=Y.join(ne.homedir(),".aistatus","quota.json"),En=[["five_hour","5h"],["seven_day","7d"]];function ht(t,e,n,s=1/0){let r=t.get(e);if(r===null||r.trim()==="")return null;let o=Number(r);return Number.isFinite(o)&&o>=n&&o<=s?o:null}function Tn(t,e,n){let s=`anthropic-ratelimit-unified-${n}`,r=ht(t,`${s}-utilization`,0,1),o=ht(t,`${s}-reset`,0);return r===null||o===null?null:{type:e,utilization:r,resets_at:o}}function Mn(t){return t==="5h"||t==="five_hour"?"five_hour":t==="7d"||t==="seven_day"?"seven_day":null}function Un(t){if(t.get("anthropic-ratelimit-unified-status")!=="rejected")return null;let e=Mn(t.get("anthropic-ratelimit-unified-representative-claim")),n=ht(t,"anthropic-ratelimit-unified-reset",0);return e&&n!==null?{type:e,utilization:1,resets_at:n}:null}function On(t){let e=En.flatMap(([s,r])=>{let o=Tn(t,s,r);return o?[o]:[]});if(e.length>0)return e;let n=Un(t);return n?[n]:[]}function $n(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return(e.type==="five_hour"||e.type==="seven_day")&&typeof e.utilization=="number"&&Number.isFinite(e.utilization)&&e.utilization>=0&&e.utilization<=1&&typeof e.resets_at=="number"&&Number.isFinite(e.resets_at)&&e.resets_at>=0}function In(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return typeof e.provider=="string"&&e.provider.length>0&&typeof e.mode=="string"&&e.mode.length>0&&typeof e.observed_at=="number"&&Number.isFinite(e.observed_at)&&Array.isArray(e.windows)&&e.windows.length>0&&e.windows.every($n)}function Nn(t){try{let e=JSON.parse($.readFileSync(t,"utf8"));return e.version===1&&Array.isArray(e.providers)?e.providers.filter(In):[]}catch{return[]}}var An=class{constructor(t=vn){this.filePath=t;for(let e of Nn(t))this.snapshots.set(e.provider,e)}snapshots=new Map;list(t){let e=[...this.snapshots.values()].filter(n=>!t||n.provider===t).sort((n,s)=>n.provider.localeCompare(s.provider));return structuredClone(e)}observe(t,e,n=Date.now()){if(e.status!==429&&(e.status<200||e.status>=300))return!1;let s=On(t);return s.length===0?!1:(this.snapshots.set(e.provider,{provider:e.provider,mode:e.mode,windows:s,observed_at:Math.floor(n/1e3)}),this.persistBestEffort(),!0)}persistBestEffort(){try{$.mkdirSync(Y.dirname(this.filePath),{recursive:!0});let t=`${this.filePath}.${process.pid}.tmp`,e={version:1,providers:this.list()};$.writeFileSync(t,`${JSON.stringify(e)}
19
- `,{encoding:"utf8",mode:384}),$.renameSync(t,this.filePath)}catch(t){console.warn(`[gateway] Failed to persist quota snapshot: ${t.message}`)}}},xn=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","content-length","content-encoding","content-type"]),Cn=1024*1024;function se(t,e){t.headers.forEach((n,s)=>{let r=s.toLowerCase();xn.has(r)||r.startsWith("x-gateway-")||(e[s]=n)})}function Rn(t){let e={};for(let n of t.split(",")){let s=n.indexOf("=");s<=0||(e[decodeURIComponent(n.slice(0,s))]=decodeURIComponent(n.slice(s+1)))}return e}function Jt(t,e){let n=t.match(/^\/m\/([^/]+)\/([^/]+)\/([^/]+)\/(.*)$/);if(n){let[,a,c,l,u]=n;if(!e[a])return{kind:"unknown-mode",mode:a};if(e[a][l])return{kind:"route",epName:l,pathStr:u,mode:a,metadata:Rn(c)}}let s=t.match(/^\/m\/([^/]+)\/([^/]+)\/(.*)$/);if(s){let[,a,c,l]=s;return e[a]?{kind:"route",epName:c,pathStr:l,mode:a}:{kind:"unknown-mode",mode:a}}let r=t.match(/^\/([^/]+)\/(.*)$/);if(!r)return{kind:"not-found"};let[,o,i]=r;return{kind:"route",epName:o,pathStr:i}}function y(t,e,n){t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify(n))}function Kt(t,e=mt){let n=e*Cn;return new Promise((s,r)=>{let o=[],i=0;t.on("data",a=>{if(i+=a.length,i>n){t.destroy(),r(new Error("Request body too large"));return}o.push(a)}),t.on("end",()=>s(Buffer.concat(o))),t.on("error",r)})}function Fn(t){if(t.length===0)return"";try{return JSON.parse(t.toString("utf-8")).model??""}catch{return""}}function G(t,e,n){return{id:t,base_url:e.base_url,api_key:n,auth_style:e.auth_style,model_prefix:"",model_map:{},translate:null}}function Yt(t,e){if(e==="anthropic")return t.headers["x-api-key"]??"";if(e==="google")return t.headers["x-goog-api-key"]??"";let n=t.headers.authorization??"";return n.toLowerCase().startsWith("bearer ")?n.slice(7):n}function Pn(t,e){let n={},s=new Set(["host","authorization","x-api-key","x-goog-api-key","content-length","transfer-encoding","connection"]);for(let[i,a]of Object.entries(t.headers))!s.has(i.toLowerCase())&&typeof a=="string"&&(n[i]=a);let[r,o]=D[e.auth_style]??D.bearer;return n[r]=o+e.api_key,n}function Dn(t,e){try{let n=JSON.parse(t.toString("utf-8"));return n.model?(n.model=e,Buffer.from(JSON.stringify(n),"utf-8")):t}catch{return t}}function jn(t,e){try{let n=JSON.parse(t.toString("utf-8")),s=n.model;return s?(s in e.model_map?n.model=e.model_map[s]:e.model_prefix&&(n.model=e.model_prefix+s),Buffer.from(JSON.stringify(n),"utf-8")):t}catch{return t}}function Bn(t,e){let n;try{n=JSON.parse(t.toString("utf-8"))}catch{return null}let s=e||n.model||"",r=n.usage??{},o=Ln(s,r);return s||o.inputTokens||o.outputTokens?o:null}function Ln(t,e){let n=re(t,e);return n||{model:t,inputTokens:_(e.input_tokens??e.prompt_tokens??0),outputTokens:_(e.output_tokens??e.completion_tokens??0),cacheCreationInputTokens:_(e.cache_creation_input_tokens??0),cacheReadInputTokens:_(e.cache_read_input_tokens??0)}}function re(t,e){let n=e.input_tokens_details;if(!n||typeof n!="object"||Array.isArray(n))return null;let s=n,r=_(s.cached_tokens??0),o=_(s.cache_write_tokens??0),i=_(e.input_tokens??0);return{model:t,inputTokens:Math.max(0,i-r-o),outputTokens:_(e.output_tokens??0),cacheCreationInputTokens:o,cacheReadInputTokens:r}}function Hn(t,e){return e.includes("/")?e.split("/",1)[0]:t.id.startsWith("anthropic")?"anthropic":t.id.startsWith("openai")?"openai":t.id.startsWith("google")?"google":t.id.startsWith("openrouter")?"openrouter":t.id.split(":",1)[0]||"unknown"}function qn(t){try{let e=JSON.parse(t.toString("utf-8")).thinking;return!e||typeof e!="object"?!1:e.type==="enabled"||e.type==="auto"}catch{return!1}}function Wn(t){try{let e=JSON.parse(t.toString("utf-8"));if(!Array.isArray(e.messages))return t;let n=!1;for(let s of e.messages)zn(s)&&(n=!0);return n?Buffer.from(JSON.stringify(e),"utf-8"):t}catch{return t}}function zn(t){if(t.role!=="assistant"||!Array.isArray(t.content))return!1;let e=t.content;if(e.some(s=>s.type==="thinking"))return!1;let n=e.findIndex(s=>s.type==="text");return n<0?!1:(e.splice(n,0,{type:"thinking",thinking:""}),!0)}function _(t){try{let e=Number(t??0);return Number.isFinite(e)?Math.floor(e):0}catch{return 0}}function Gn(t,e){y(e,200,{status:"ok",mode:t.mode,endpoints:Object.keys(t.endpoints)})}function Jn(t,e,n){let s=Object.fromEntries(Object.entries(t.endpoints).map(([i,a])=>[i,Kn(i,a,e)])),r=e.summary(),o=r.model_health;delete r.model_health,y(n,200,{mode:t.mode,available_modes:Object.keys(t.endpoint_modes),endpoints:s,health_detail:r,model_health:o??{}})}function Kn(t,e,n){let s=[];for(let o=0;o<e.keys.length;o++){let i=`${t}:key:${o}`;s.push({id:i,type:"primary",healthy:n.isHealthy(i)})}if(e.keys.length===0||e.passthrough){let o=`${t}:passthrough`;s.push({id:o,type:"passthrough",healthy:n.isHealthy(o)})}for(let o of e.fallbacks){let i=`${t}:fb:${o.name}`;s.push({id:i,type:"fallback",name:o.name,healthy:n.isHealthy(i)})}let r=e.keys.length===0?"passthrough":e.passthrough?"hybrid":"managed";return{backends:s,mode:r}}function Yn(t,e,n){if(e.format==="records"){Qn(t,e,n);return}Zn(t,e,n)}function Vn(t,e,n){let s=typeof e.provider=="string"?e.provider:void 0;y(n,200,{providers:t.list(s)})}function Qn(t,e,n){let s=Xn(t.storage.read("all"),e.since),r=Math.max(0,_(e.limit??1e3)),o=Math.max(0,_(e.offset??0)),i=r>0?s.slice(o,o+r):s.slice(o);y(n,200,{records:i})}function Xn(t,e){if(!e)return t;let n=new Date(e);return isNaN(n.getTime())?t:t.filter(s=>{let r=new Date(s.ts);return!isNaN(r.getTime())&&r>n})}function Zn(t,e,n){let s=e.period??"today",r=e.group_by??"",o=ts(r);es(s,o,r,n)&&y(n,200,t.report(s,o??[]))}function ts(t){if(t.trim()==="")return[];let e=t.split(",").map(r=>r.trim()),n=e.every(r=>ot.includes(r)),s=new Set(e).size===e.length;return n&&s?e:null}function es(t,e,n,s){let r=["today","week","month","all"];return r.includes(t)?e!==null?!0:(y(s,400,{error:{message:`Invalid group_by: ${n}. Must be distinct keys from ${ot.join(",")}`,type:"gateway_error"}}),!1):(y(s,400,{error:{message:`Invalid period: ${t}. Must be one of ${r.join(",")}`,type:"gateway_error"}}),!1)}async function Vt(t,e){if(!t.status_check)return;let n=ns(t);if(n.size===0)return;let s=await ss([...n].sort());if(s.size!==0)for(let r of Object.values(t.endpoints))rs(r,s,e)}function ns(t){let e=new Set;for(let n of Object.values(t.endpoints))for(let[s,r]of Object.entries(n.model_fallbacks)){e.add(s);for(let o of r)e.add(o)}return e}async function ss(t){let{StatusAPI:e}=await import("./api-GM53PHIL-GFHEXXE6.js"),{Status:n}=await import("./models-L5VF4I5O-XXNJYQMQ.js"),s=new e,r=await Promise.allSettled(t.map(i=>s.checkModel(i))),o=new Set;for(let i=0;i<t.length;i++){let a=r[i];a.status==="fulfilled"&&(a.value.status===n.DEGRADED||a.value.status===n.DOWN)&&o.add(t[i])}return o}function rs(t,e,n){let s=new Set(Object.keys(t.model_fallbacks));for(let o of Object.values(t.model_fallbacks))for(let i of o)s.add(i);let r=[...s].filter(o=>e.has(o));if(r.length!==0)for(let o of os(t))for(let i of r)n.recordError(o,529,i),console.log(`[gateway] Pre-marked ${o} model unhealthy from global status: ${i}`)}function os(t){let e=t.keys.map((n,s)=>`${t.name}:key:${s}`);(t.keys.length===0||t.passthrough)&&e.push(`${t.name}:passthrough`);for(let n of t.fallbacks)e.push(`${t.name}:fb:${n.name}`);return e}async function dt(t){let{backend:e,usage:n,elapsedMs:s,metadata:r,pricing:o,tracker:i}=t,a=Hn(e,n.model),c=n.model||`${a}/unknown`,l=await is(o,a,c,n);i.recordUsage({provider:a,model:c,cost:l,metadata:r,input_tokens:n.inputTokens,output_tokens:n.outputTokens,cache_creation_input_tokens:n.cacheCreationInputTokens,cache_read_input_tokens:n.cacheReadInputTokens,latency_ms:s,fallback:e.id.includes(":fb:"),billing_mode:t.billingMode||t.defaultBillingMode})}async function is(t,e,n,s){return s.cacheCreationInputTokens>0||s.cacheReadInputTokens>0?t.calculateCostWithCacheAsync(e,n,s.inputTokens,s.outputTokens,s.cacheCreationInputTokens,s.cacheReadInputTokens):t.calculateCostAsync(e,n,s.inputTokens,s.outputTokens)}var as=new Set(["response.completed","response.incomplete","response.done"]);function Qt(t){return{model:t,inputTokens:0,outputTokens:0,cacheCreationInputTokens:0,cacheReadInputTokens:0}}async function cs(t){if(!t.body)return{kind:"buffer",body:Buffer.alloc(0)};let e=t.body.getReader(),n=await e.read();if(n.done||!n.value)return{kind:"buffer",body:Buffer.alloc(0)};let s=Buffer.from(n.value);if(ls(s))return{kind:"event-stream",reader:us(s,e)};let r=[s];for(;;){let o=await e.read();if(o.done)break;o.value&&r.push(Buffer.from(o.value))}return{kind:"buffer",body:Buffer.concat(r)}}function ls(t){let e=t.subarray(0,64).toString("utf-8").replace(/^[\s]+/,"");return/^(event|data|id|retry):/.test(e)||e.startsWith(":")}function us(t,e){let n=t;return{async read(){if(n){let s=n;return n=null,{done:!1,value:s}}return e.read()}}}async function fs(t){let e=t.bodyReader??t.upstream.body?.getReader();if(hs(t),!e){t.res.end();return}let n=new ie(t.originalModel),s=[],r;try{r=await ds(t,e,n,s)}catch(i){throw Xt(t.res),i}if(!r){Xt(t.res);return}t.res.end();let o=s.length>0?Buffer.concat(s):void 0;t.dumpApiCall(t.requestBody,o,t.originalModel,t.backend.id,t.elapsedMs),n.hasUsage()&&await _s(t,n.usage)}function Xt(t){t.once("error",()=>{}),t.destroy(new Error("upstream stream interrupted"))}function hs(t){let e={};se(t.upstream,e),e["content-type"]="text/event-stream",e["cache-control"]="no-cache",e.connection="keep-alive",e["x-gateway-backend"]=t.backend.id,t.fallbackHeader&&(e["x-gateway-model-fallback"]=t.fallbackHeader),t.res.writeHead(200,e)}async function ds(t,e,n,s){try{return await ps(t,e,n,s),!0}catch(r){if(r instanceof oe)return n.hasTerminalEvent();throw r}}async function ps(t,e,n,s){let r=gs(e,n,s);if(t.backend.translate==="anthropic-to-openai"){for await(let o of Sn(r,t.originalModel))t.res.write(o);return}for await(let o of r)t.res.write(o)}var oe=class extends Error{};async function ms(t){try{return await t.read()}catch{throw new oe("upstream stream read failed")}}async function*gs(t,e,n){for(;;){let{done:s,value:r}=await ms(t);if(s||!r)return;let o=Buffer.from(r);e.push(o.toString("utf-8")),n.push(o),yield o}}async function _s(t,e){await dt({backend:t.backend,usage:e,elapsedMs:t.elapsedMs,billingMode:t.billingMode,defaultBillingMode:t.defaultBillingMode,metadata:t.metadata,pricing:t.pricing,tracker:t.tracker})}var ie=class{usage;initialModel;buffer="";terminalEvent=!1;constructor(t){this.initialModel=t,this.usage=Qt(t)}applyMessage(t){try{this.applyPayload(JSON.parse(t))}catch{}}reset(){this.usage=Qt(this.initialModel),this.terminalEvent=!1}push(t){for(this.buffer+=t;this.buffer.includes(`
20
-
21
- `);){let e=this.buffer.indexOf(`
22
-
23
- `),n=this.buffer.slice(0,e).trim();this.buffer=this.buffer.slice(e+2);for(let s of n.split(`
24
- `))this.parseLine(s)}}hasUsage(){return this.usage.inputTokens>0||this.usage.outputTokens>0}hasTerminalEvent(){return this.terminalEvent}parseLine(t){if(!t.startsWith("data:"))return;let e=t.slice(5).trim();if(e==="[DONE]"){this.terminalEvent=!0;return}try{this.applyPayload(JSON.parse(e))}catch{}}applyPayload(t){if(!this.applyResponsesPayload(t)){if(t.type==="message_stop"&&(this.terminalEvent=!0),t.type==="message_start"&&t.message?.usage){let e=t.message.usage;this.usage.inputTokens=_(e.input_tokens??0),this.usage.cacheCreationInputTokens=_(e.cache_creation_input_tokens??0),this.usage.cacheReadInputTokens=_(e.cache_read_input_tokens??0)}t.type==="message_delta"&&t.usage&&(this.usage.outputTokens=_(t.usage.output_tokens??0)),t.usage&&this.applyGenericUsage(t.usage)}}applyResponsesPayload(t){let e=typeof t?.type=="string"?t.type:"";if(!e.startsWith("response."))return!1;let n=t.response;if(!n||typeof n!="object"||(!this.usage.model&&typeof n.model=="string"&&(this.usage.model=n.model),!as.has(e)))return!0;this.terminalEvent=!0;let s=n.usage;if(!s||typeof s!="object")return!0;let r=re(this.usage.model,s);return r&&(this.usage.inputTokens=r.inputTokens,this.usage.outputTokens=r.outputTokens,this.usage.cacheCreationInputTokens=r.cacheCreationInputTokens,this.usage.cacheReadInputTokens=r.cacheReadInputTokens),!0}applyGenericUsage(t){this.usage.inputTokens=_(t.input_tokens??t.prompt_tokens??this.usage.inputTokens),this.usage.outputTokens=_(t.output_tokens??t.completion_tokens??this.usage.outputTokens),this.usage.cacheCreationInputTokens=_(t.cache_creation_input_tokens??this.usage.cacheCreationInputTokens),this.usage.cacheReadInputTokens=_(t.cache_read_input_tokens??this.usage.cacheReadInputTokens)}},ys=32*1024*1024,ks=0,ws=1,bs=2,Ss=8,vs=class{constructor(t,e=ys){this.onMessage=t,this.maxMessageBytes=e}buffer=Buffer.alloc(0);fragments=[];fragmentBytes=0;skippingMessage=!1;disabled=!1;get isDisabled(){return this.disabled}push(t){if(!this.disabled)try{for(this.buffer=this.buffer.length===0?t:Buffer.concat([this.buffer,t]);this.readFrame(););}catch{this.disable()}}disable(){this.disabled=!0,this.buffer=Buffer.alloc(0),this.fragments=[],this.fragmentBytes=0}readFrame(){if(this.buffer.length<2)return!1;let t=this.buffer[0],e=this.buffer[1],n=(t&128)!==0,s=t&15,r=(e&128)!==0,o=2,i=e&127;if(i===126){if(this.buffer.length<o+2)return!1;i=this.buffer.readUInt16BE(o),o+=2}else if(i===127){if(this.buffer.length<o+8)return!1;let l=this.buffer.readBigUInt64BE(o);if(l>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("frame length out of range");i=Number(l),o+=8}let a=null;if(r){if(this.buffer.length<o+4)return!1;a=this.buffer.subarray(o,o+4),o+=4}if(this.buffer.length<o+i)return!1;let c=this.buffer.subarray(o,o+i);return this.buffer=this.buffer.subarray(o+i),s>=Ss||this.collect(s,n,a?Es(c,a):c),!0}collect(t,e,n){if(t===ws||t===bs)this.fragments=[],this.fragmentBytes=0,this.skippingMessage=!1;else if(t!==ks)return;if(this.fragmentBytes+=n.length,this.fragmentBytes>this.maxMessageBytes&&(this.skippingMessage=!0,this.fragments=[]),this.skippingMessage||this.fragments.push(n),!e)return;let s=this.skippingMessage?null:Buffer.concat(this.fragments);this.fragments=[],this.fragmentBytes=0,this.skippingMessage=!1,s&&this.onMessage(s.toString("utf-8"))}};function Es(t,e){let n=Buffer.allocUnsafe(t.length);for(let s=0;s<t.length;s++)n[s]=t[s]^e[s&3];return n}var Ts=new Set(["host","authorization","x-api-key","x-goog-api-key","content-length","transfer-encoding","sec-websocket-extensions"]),Ms=64*1024,Us=3e4;async function Os(t){let{socket:e,backend:n}=t;e.on("error",()=>{});let s=new URL(n.base_url),o=`${s.pathname.replace(/\/+$/,"")}/${t.pathStr}${t.search}`,i;try{i=await $s(s)}catch(a){return t.health.recordError(n.id,502),U(e,502,`Upstream connection error: ${a}`)}i.on("error",()=>{});try{i.write(Is(t.req,n,s,o));let a=await Ns(i);if(a.status!==101){t.health.recordError(n.id,a.status),e.write(a.raw),i.pipe(e).on("end",()=>e.end());return}t.health.recordSuccess(n.id),e.write(a.raw),t.head.length>0&&i.write(t.head),As(t,i,a.rest)}catch(a){i.destroy(),t.health.recordError(n.id,502),U(e,502,`Upstream handshake failed: ${a}`)}}function $s(t){let e=t.protocol==="https:"||t.protocol==="wss:",n=t.port?Number(t.port):e?443:80;return new Promise((s,r)=>{let o=e?le.connect({host:t.hostname,port:n,servername:t.hostname,ALPNProtocols:["http/1.1"]}):V.connect({host:t.hostname,port:n}),i=()=>{o.setNoDelay(!0),o.removeListener("error",a),s(o)},a=c=>{o.destroy(),r(c)};o.once(e?"secureConnect":"connect",i),o.once("error",a)})}function Is(t,e,n,s){let r=[`GET ${s} HTTP/1.1`,`host: ${n.host}`];for(let[a,c]of Object.entries(t.headers))if(!Ts.has(a.toLowerCase())){if(typeof c=="string")r.push(`${a}: ${c}`);else if(Array.isArray(c))for(let l of c)r.push(`${a}: ${l}`)}let[o,i]=D[e.auth_style]??D.bearer;return r.push(`${o}: ${i}${e.api_key}`),`${r.join(`\r
25
- `)}\r
26
- \r
27
- `}function Ns(t){return new Promise((e,n)=>{let s=Buffer.alloc(0),r=setTimeout(()=>i(new Error("upstream handshake timed out")),Us),o=l=>{s=Buffer.concat([s,l]);let u=s.indexOf(`\r
28
- \r
29
- `);if(u<0){s.length>Ms&&i(new Error("upstream handshake head too large"));return}let f=u+4,h=s.subarray(0,s.indexOf(`\r
30
- `)).toString("latin1"),m=Number.parseInt(h.split(" ")[1]??"",10);if(!Number.isFinite(m))return i(new Error(`malformed upstream status line: ${h}`));i(null,{status:m,raw:s.subarray(0,f),rest:s.subarray(f)})},i=(l,u)=>{clearTimeout(r),t.removeListener("data",o),t.removeListener("error",a),t.removeListener("close",c),l?n(l):e(u)},a=l=>i(l),c=()=>i(new Error("upstream closed before completing the handshake"));t.on("data",o),t.once("error",a),t.once("close",c)})}function As(t,e,n){let{socket:s}=t;s instanceof V.Socket&&s.setNoDelay(!0);let r=new vs(xs(t)),o=new ce.Transform({transform(a,c,l){r.push(a),l(null,a)}}),i=()=>{s.destroy(),e.destroy()};s.on("error",i),s.on("close",i),e.on("error",i),e.on("close",i),n.length>0&&(r.push(n),s.write(n)),e.pipe(o).pipe(s),s.pipe(e)}function xs(t){let e=new ie(""),n=null;return s=>{if(n===null&&(n=Date.now()),e.applyMessage(s),!e.hasTerminalEvent())return;let r=Date.now()-n,o=e.usage,i=e.hasUsage();n=null,e.reset(),i&&(t.health.recordSuccess(t.backend.id),o.model&&t.health.recordSuccess(t.backend.id,o.model),dt({backend:t.backend,usage:o,elapsedMs:r,billingMode:t.billingMode,defaultBillingMode:t.defaultBillingMode,metadata:t.metadata,pricing:t.pricing,tracker:t.tracker}).catch(a=>console.warn("[gateway] websocket usage accounting failed:",a)))}}function U(t,e,n){let s=JSON.stringify({error:{message:n,type:"gateway_error"}});t.end(`HTTP/1.1 ${e} ${ae.STATUS_CODES[e]??"Error"}\r
31
- content-type: application/json\r
32
- content-length: ${Buffer.byteLength(s)}\r
33
- connection: close\r
34
- \r
35
- ${s}`)}var ft=class extends Error{status;body;constructor(t,e){super(`Upstream error: ${t}`),this.status=t,this.body=e}},Cs=class{config;health;usage;uploader;quota;pricing;_keyIdx={};_pidFile;_server=null;_dumpDir;constructor(t,e){t.endpoint_modes||(t.endpoint_modes={[t.mode??"default"]:t.endpoints}),t.mode||(t.mode=Object.keys(t.endpoint_modes)[0]??"default"),t.endpoints||(t.endpoints=t.endpoint_modes[t.mode]??{}),this.config=t,this.health=new Tt,this.uploader=new zt(ct()),this.usage=new xt(void 0,this.uploader),this.quota=new An,this.pricing=new Rt,this._pidFile=e??null,this._dumpDir=process.env.GATEWAY_DUMP_DIR||null,this._dumpDir&&O.mkdirSync(this._dumpDir,{recursive:!0})}reloadConfig(t){(t.host!==this.config.host||t.port!==this.config.port)&&console.warn(`[gateway] host/port change ignored on reload (already bound to ${this.config.host}:${this.config.port})`),t.host=this.config.host,t.port=this.config.port,(!t.endpoint_modes||Object.keys(t.endpoint_modes).length===0)&&(t.endpoint_modes={[t.mode??"default"]:t.endpoints??{}});let e=Object.keys(t.endpoint_modes),n=this.config.mode,s=t.endpoint_modes[n]?n:e[0]??"default";t.mode=s,t.endpoints=t.endpoint_modes[s]??{},this.config=t,this._keyIdx={},console.log("[gateway] Config reloaded"),Vt(this.config,this.health).catch(r=>{console.warn("[gateway] post-reload health precheck failed:",r)})}reloadUploadConfig(t){this.uploader.setConfig(t),console.log(`[gateway] Upload config reloaded (usage upload ${this.uploader.enabled?"enabled":"disabled"})`)}async run(){await Vt(this.config,this.health);let t=ee.createServer((s,r)=>{this._handleRequest(s,r).catch(o=>{console.error("[gateway] Unhandled error:",o),r.headersSent||(r.writeHead(500,{"content-type":"application/json"}),r.end(JSON.stringify({error:{message:"Internal server error",type:"gateway_error"}})))})});t.on("upgrade",(s,r,o)=>{this._handleUpgrade(s,r,o).catch(i=>{console.error("[gateway] Unhandled upgrade error:",i),r.destroy()})}),this._server=t,await new Promise((s,r)=>{t.listen(this.config.port,this.config.host,()=>s()),t.on("error",r)}),this._prewarmUsage(),this._writePidFile(),this._printBanner();let e=!1,n=()=>{if(e)return;e=!0,console.log("[gateway] Shutdown signal received, stopping gracefully..."),this._removePidFile(),setTimeout(()=>process.exit(0),5e3).unref();let s=new Promise(o=>t.close(()=>o())),r=new Promise(o=>setTimeout(o,1e3).unref());Promise.race([s,r]).then(()=>Wt(3e3)).finally(()=>{console.log("[gateway] Gateway stopped"),process.exit(0)})};process.on("SIGTERM",n),process.on("SIGINT",n)}_prewarmUsage(){try{this.usage.prewarm("month")}catch(t){console.warn("[gateway] Usage index prewarm failed:",t)}}async _handleRequest(t,e){let n=C.parse(t.url??"/",!0),s=n.pathname??"/";if(!Gt(this.config.auth,s,t.headers))return y(e,401,{error:{message:"Unauthorized: invalid or missing API key",type:"auth_error"}});if(s==="/health"&&t.method==="GET")return Gn(this.config,e);if(s==="/status"&&t.method==="GET")return Jn(this.config,this.health,e);if(s==="/usage"&&t.method==="GET")return Yn(this.usage,n.query,e);if(s==="/quota"&&t.method==="GET")return Vn(this.quota,n.query,e);if(s==="/mode"&&t.method==="POST")return this._handleModeSwitch(t,e);let r=Jt(s,this.config.endpoint_modes);if(r.kind==="unknown-mode")return y(e,400,{error:{message:`Unknown mode: ${r.mode}`,type:"gateway_error"}});if(r.kind==="not-found")return y(e,404,{error:{message:`Not found: ${s}`,type:"gateway_error"}});await this._handleProxy(t,e,r.epName,r.pathStr,n.query,r.mode,r.metadata)}async _handleUpgrade(t,e,n){let s=C.parse(t.url??"/",!0),r=s.pathname??"/";if(!this.config.websocket)return U(e,501,"WebSocket proxying is disabled");if(!Gt(this.config.auth,r,t.headers))return U(e,401,"Unauthorized: invalid or missing API key");let o=Jt(r,this.config.endpoint_modes);if(o.kind==="unknown-mode")return U(e,400,`Unknown mode: ${o.mode}`);if(o.kind==="not-found")return U(e,404,`Not found: ${r}`);let i=this._resolveEndpoint(o.epName,o.mode);if(!i)return U(e,404,`Unknown endpoint: ${o.epName}`);let c=this._buildBackendList(i.endpoint,t)[0]??this._pickSoonestCooldownBackend(i.endpoint,t);if(!c)return U(e,503,"All backends unavailable");let l=new C.URLSearchParams(s.query).toString();await Os({req:t,socket:e,head:n,backend:c,pathStr:o.pathStr,search:l?`?${l}`:"",billingMode:i.billingMode,defaultBillingMode:this.config.mode,metadata:o.metadata,health:this.health,pricing:this.pricing,tracker:this.usage})}_resolveEndpoint(t,e){let s=(e?this.config.endpoint_modes[e]??this.config.endpoints:this.config.endpoints)[t];if(s)return{endpoint:s,billingMode:e||this.config.mode};if(e)return null;for(let[r,o]of Object.entries(this.config.endpoint_modes)){if(r===this.config.mode)continue;let i=o[t];if(i)return{endpoint:i,billingMode:r}}return null}async _handleProxy(t,e,n,s,r,o,i){let a=this._resolveEndpoint(n,o);if(!a)return y(e,404,{error:{message:`Unknown endpoint: ${n}`,type:"gateway_error"}});let{endpoint:c,billingMode:l}=a,u=await Kt(t,this.config.max_body_size_mb),f=Fn(u),h=this._buildBackendList(c,t);if(h.length===0){let p=this._pickSoonestCooldownBackend(c,t);if(p)h=[p];else return y(e,503,{error:{message:"All backends unavailable",type:"gateway_error"}})}let m=null;for(let p of h){let[S,R,k]=this._applyModelFallback(c,p.id,u,f);try{return await this._forward(t,e,p,s,R,r,S,k,l,i)}catch(v){if(v instanceof ft)m=v,this.health.recordError(p.id,v.status),S&&this.health.recordError(p.id,v.status,S),console.warn(`[gateway] ${p.id} \u2192 ${v.status}, trying next backend`);else throw v}}m?(e.writeHead(m.status,{"content-type":"application/json"}),e.end(m.body)):y(e,503,{error:{message:"All backends failed",type:"gateway_error"}})}_buildBackendList(t,e){let n=[],s=t.name;if(t.keys.length>0){let r=this._keyIdx[s]??0,o=t.keys.length;for(let i=0;i<o;i++){let a=(r+i)%o,c=`${s}:key:${a}`;this.health.isHealthy(c)&&n.push(G(c,t,t.keys[a]))}this._keyIdx[s]=(r+1)%o}if(t.keys.length===0||t.passthrough){let r=`${s}:passthrough`;if(this.health.isHealthy(r)){let o=Yt(e,t.auth_style);o&&n.push(G(r,t,o))}}for(let r of t.fallbacks){let o=`${s}:fb:${r.name}`;!this.health.isHealthy(o)||!r.api_key||n.push({id:o,base_url:r.base_url,api_key:r.api_key,auth_style:r.auth_style,model_prefix:r.model_prefix,model_map:r.model_map,translate:r.translate})}return n}_pickSoonestCooldownBackend(t,e){let n=t.name,s=[];for(let o=0;o<t.keys.length;o++){let i=`${n}:key:${o}`;s.push({id:i,backend:G(i,t,t.keys[o])})}if(t.keys.length===0||t.passthrough){let o=`${n}:passthrough`,i=Yt(e,t.auth_style);i&&s.push({id:o,backend:G(o,t,i)})}for(let o of t.fallbacks){if(!o.api_key)continue;let i=`${n}:fb:${o.name}`;s.push({id:i,backend:{id:i,base_url:o.base_url,api_key:o.api_key,auth_style:o.auth_style,model_prefix:o.model_prefix,model_map:o.model_map,translate:o.translate}})}if(s.length===0)return null;let r=this.health.soonestCooldown(s.map(o=>o.id));return r?s.find(o=>o.id===r.id)?.backend??null:s[0].backend}async _forward(t,e,n,s,r,o,i,a,c,l){let u=n.translate==="anthropic-to-openai",f=i;if(!f&&u&&r.length>0)try{f=JSON.parse(r.toString("utf-8")).model??""}catch{}let h=s;u&&s.includes("v1/messages")&&(h="v1/chat/completions");let p=`${n.base_url.replace(/\/+$/,"")}/${h}`,S=new C.URLSearchParams(o).toString();S&&(p+=`?${S}`);let R=Pn(t,n),k=r;u&&r.length>0&&(k=wn(r)),r.length>0&&(Object.keys(n.model_map).length>0||n.model_prefix)&&(k=jn(k,n)),c?.includes("deepseek")&&k.length>0&&qn(k)&&(k=Wn(k));let v=Date.now(),w;try{let P=k.length>0?new Uint8Array(k.buffer,k.byteOffset,k.byteLength):void 0;w=await fetch(p,{method:t.method??"POST",headers:R,body:P})}catch(P){throw new ft(502,Buffer.from(JSON.stringify({error:{message:`Upstream connection error: ${P}`,type:"gateway_error"}})))}let F=Date.now()-v;if(this._observeQuota(w,n,c),[429,500,502,503,529].includes(w.status)){let P=await w.arrayBuffer();throw new ft(w.status,Buffer.from(P))}if(this.health.recordSuccess(n.id),i&&this.health.recordSuccess(n.id,i),(w.headers.get("content-type")??"").includes("text/event-stream")){await this._stream(e,w,n,f,a,F,c,r,l);return}let Q=await cs(w);if(Q.kind==="event-stream"){await this._stream(e,w,n,f,a,F,c,r,l,Q.reader);return}await this._respond(e,w,Q.body,n,f,F,a,c,r,l)}_observeQuota(t,e,n){!e.id.startsWith("anthropic:")||!e.id.endsWith(":passthrough")||e.auth_style==="bearer"&&this.quota.observe(t.headers,{provider:"anthropic",mode:n??this.config.mode,status:t.status})}async _respond(t,e,n,s,r,o,i,a,c,l){let u=n,f,h;if(s.translate==="anthropic-to-openai")u=bn(u,r),f="application/json";else{let p=e.headers.get("content-type")??"application/json",[S,...R]=p.split(";");f=S.trim()||"application/json";for(let k of R){let[v,w]=k.split("=").map(F=>F.trim());v?.toLowerCase()==="charset"&&w&&(h=w.replace(/"/g,""))}}await this._recordUsageIfPossible(s,u,r,o,a,l),this._dumpApiCall(c,u,r,s.id,o);let m={};se(e,m),m["content-type"]=h?`${f}; charset=${h}`:f,m["x-gateway-backend"]=s.id,m["x-gateway-ms"]=String(o),i&&(m["x-gateway-model-fallback"]=i),t.writeHead(e.status,m),t.end(u)}async _stream(t,e,n,s,r,o=0,i,a,c,l){await fs({res:t,upstream:e,backend:n,originalModel:s,fallbackHeader:r,elapsedMs:o,billingMode:i,defaultBillingMode:this.config.mode,requestBody:a,metadata:c,bodyReader:l,pricing:this.pricing,tracker:this.usage,dumpApiCall:this._dumpApiCall.bind(this)})}_applyModelFallback(t,e,n,s){if(n.length===0||!s)return[s,n,""];if(this.health.isHealthy(e,s))return[s,n,""];let r=t.model_fallbacks[s]??[];for(let o of r){if(!this.health.isHealthy(e,o))continue;let i=Dn(n,o);if(!i.equals(n))return[o,i,`${s}->${o}`]}return[s,n,""]}_dumpApiCall(t,e,n,s,r){if(!(!this._dumpDir||!t||t.length===0))try{let o=new Date().toISOString().replace(/[:.]/g,"-"),i=K.join(this._dumpDir,`${o}.json`),a;try{a=JSON.parse(t.toString("utf-8"))}catch{a=t.toString("utf-8")}let c;if(e&&e.length>0){let u=e.toString("utf-8");try{c=JSON.parse(u)}catch{c=u}}let l={ts:new Date().toISOString(),model:n||void 0,backend:s,latency_ms:r,request:a};c!==void 0&&(l.response=c),O.writeFileSync(i,JSON.stringify(l)+`
36
- `,"utf-8")}catch{}}async _recordUsageIfPossible(t,e,n,s,r,o){let i=Bn(e,n);i&&await dt({backend:t,usage:i,elapsedMs:s,billingMode:r,metadata:o,defaultBillingMode:this.config.mode,pricing:this.pricing,tracker:this.usage})}async _handleModeSwitch(t,e){let n=await Kt(t,this.config.max_body_size_mb),s;try{s=n.length>0?JSON.parse(n.toString("utf-8")):{}}catch{return y(e,400,{error:{message:"Invalid JSON body",type:"gateway_error"}})}let r=typeof s.mode=="string"?s.mode:"";if(!r||!this.config.endpoint_modes[r])return y(e,400,{error:{message:`Unknown mode: ${r}`,type:"gateway_error"}});let o=this.config.mode;return this.config.mode=r,this.config.endpoints=this.config.endpoint_modes[r],console.log(`[gateway] Switched mode ${o} -> ${r}`),y(e,200,{ok:!0,mode:r,previous:o})}_writePidFile(){this._pidFile&&(O.mkdirSync(K.dirname(this._pidFile),{recursive:!0}),O.writeFileSync(this._pidFile,String(process.pid),"utf-8"),console.log(`[gateway] PID ${process.pid} written to ${this._pidFile}`))}_removePidFile(){if(this._pidFile)try{O.unlinkSync(this._pidFile),console.log(`[gateway] PID file removed: ${this._pidFile}`)}catch{}}_printBanner(){let t=`http://${this.config.host}:${this.config.port}`;if(console.log(),console.log(` aistatus gateway running on ${t}`),this.config.auth?.enabled){let e=this.config.auth.keys.length,n=(this.config.auth.public_paths??["/health"]).join(", ");console.log(` Auth: ${e} key${e!==1?"s":""} configured (public: ${n})`)}console.log();for(let[e,n]of Object.entries(this.config.endpoints)){let s=n.keys.length,r=n.fallbacks.length,o;s>0&&n.passthrough?o=`${s} key${s!==1?"s":""} + passthrough`:s>0?o=`${s} key${s!==1?"s":""}`:o="passthrough";let i=n.fallbacks.map(c=>c.name).join(", "),a=i?` \u2192 fallback: ${i}`:"";console.log(` /${e}/* (${o}${a})`)}console.log(),console.log(" Configure your CLI tools:"),"anthropic"in this.config.endpoints&&console.log(` export ANTHROPIC_BASE_URL=${t}/anthropic`),"openai"in this.config.endpoints&&console.log(` export OPENAI_BASE_URL=${t}/openai/v1`),console.log(),console.log(` Status: ${t}/status`),console.log(` Health: ${t}/health`),console.log(` Usage: ${t}/usage?period=today&group_by=model`),console.log()}},Rs=te.join(Zt.homedir(),".aistatus","gateway.yaml");function ue(t,e,n,s){let r=s.intervalMs??1e3,o=null,i=(a,c)=>{a.mtimeMs===0&&!s.reloadOnDelete||a.mtimeMs===c.mtimeMs&&a.size===c.size||(o&&clearTimeout(o),o=setTimeout(()=>{o=null;try{n(e())}catch(l){console.warn(`[gateway] Config reload failed for ${t}:`,l)}},200))};return J.watchFile(t,{interval:r,persistent:!1},i),console.log(`[gateway] Watching config file for changes: ${t}`),()=>{o&&(clearTimeout(o),o=null),J.unwatchFile(t,i)}}function Fs(t,e,n={}){return ue(t,()=>B(t),e,n)}function Ps(t,e={}){let n=e.filePath??at;return ue(n,()=>ct({filePath:n,env:e.env}),t,{intervalMs:e.intervalMs,reloadOnDelete:!0})}async function Xs(t={}){let e=t.host??"127.0.0.1",n=t.port??9880,s,r=null;t.auto?s=gt(e,n):t.configPath?(s=B(t.configPath),r=t.configPath):(s=B(),r=Rs),s.host=e,s.port=n;let o=new Cs(s,t.pidFile);return t.watchConfig!==!1&&(r&&Fs(r,i=>o.reloadConfig(i)),Ps(i=>o.reloadUploadConfig(i))),await o.run(),o}export{D as AUTH_STYLES,pe as DEFAULT_BASE_URLS,mt as DEFAULT_MAX_BODY_SIZE_MB,Cs as GatewayServer,Tt as HealthTracker,An as QuotaSnapshotStore,de as RESERVED_KEYS,wn as anthropicRequestToOpenai,gt as autoDiscover,Gt as checkGatewayAuth,me as fromDict,ge as generateConfig,Et as isServerError,B as loadConfig,bn as openaiResponseToAnthropic,Sn as openaiSseToAnthropicSse,Xs as startGateway,Fs as watchConfigFile,Ps as watchUploadConfigFile};
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{d as w}from"./chunk-VQUPKMDR.js";import{a as g}from"./chunk-JXFG66UN.js";import{a as y}from"./chunk-ILEML5IP.js";import"./chunk-WHC7AYZD.js";var U=e=>atob(e),x=U("SXYxLmI1MDdhMDhjODdlY2ZlOTg="),f={"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},S="2026-06-01";function _(e){let t=e.trim();if(!t)return null;try{return(t.includes("://")?new URL(t):new URL(`https://${t}`)).hostname}catch{return null}}function h(e){return{deviceCodeUrl:`https://${e}/login/device/code`,accessTokenUrl:`https://${e}/login/oauth/access_token`,copilotTokenUrl:`https://api.${e}/copilot_internal/v2/token`}}function A(e){let t=e.match(/proxy-ep=([^;]+)/);return t?`https://${t[1].replace(/^proxy\./,"api.")}`:null}function b(e,t){if(e){let n=A(e);if(n)return n}return t?`https://copilot-api.${t}`:"https://api.individual.githubcopilot.com"}function p(e){return e&&typeof e=="object"?e:void 0}function M(e,t){let n=p(e)?.data;if(!Array.isArray(n))throw new Error("Invalid Copilot models response");let o=n.flatMap(i=>{let l=p(i),d=l?.id;if(!l||typeof d!="string")return[];let u=p(l.capabilities);return p(u?.supports)?.tool_calls===!1?[]:[{id:d,pickerEnabled:l.model_picker_enabled===!0,policyState:p(l.policy)?.state}]}),r=o.filter(i=>i.pickerEnabled&&i.policyState!=="disabled").map(i=>i.id),a=t&&r.length===0,s=r.length>0||!t?r:o.filter(i=>i.policyState==="enabled").map(i=>i.id),c=o.filter(i=>i.policyState==="unconfigured"&&Object.hasOwn(w,i.id)&&(i.pickerEnabled||a)).map(i=>i.id);return{availableModelIds:s,policyModelIds:c}}async function C(e,t,n,o){let r=o.maxRetries>0&&o.maxElapsedMs>0?AbortSignal.timeout(o.maxElapsedMs):void 0,a=r?AbortSignal.any([n,r]):n,s=r?Date.now()+o.maxElapsedMs:void 0;for(let c=0;;c++){let i=await fetch(e,{...t,signal:AbortSignal.any([a,AbortSignal.timeout(5e3)])});if(i.status!==429||c===o.maxRetries)return i;let l=i.headers.get("retry-after"),d=500*2**c;if(l){let u=Number.parseFloat(l);if(d=Number.isNaN(u)?Date.parse(l)-Date.now():u*1e3,!Number.isFinite(d))return i}if(d=Math.max(0,d),s!==void 0&&d>=s-Date.now())return i;await i.body?.cancel(),await g(d,a)}}async function E(e,t,n,o){let r=b(e,t),a=r==="https://api.individual.githubcopilot.com",s=await C(`${r}/models`,{headers:{Accept:"application/json",Authorization:`Bearer ${e}`,...f,"X-GitHub-Api-Version":S}},n,o);if(!s.ok)throw new Error(`${s.status} ${s.statusText}: ${await s.text()}`);return M(await s.json(),a)}async function m(e,t){let n=await fetch(e,t);if(!n.ok){let o=await n.text();throw new Error(`${n.status} ${n.statusText}: ${o}`)}return n.json()}async function k(e,t){let n=h(e),o=await m(n.deviceCodeUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"GitHubCopilotChat/0.35.0"},body:new URLSearchParams({client_id:x,scope:"read:user"}),signal:t});if(!o||typeof o!="object")throw new Error("Invalid device code response");let r=o.device_code,a=o.user_code,s=o.verification_uri,c=o.interval,i=o.expires_in;if(typeof r!="string"||typeof a!="string"||typeof s!="string"||c!==void 0&&typeof c!="number"||typeof i!="number")throw new Error("Invalid device code response fields");let l;try{l=new URL(s)}catch{throw new Error("Untrusted verification_uri in device code response")}if(l.protocol!=="https:"&&l.protocol!=="http:")throw new Error("Untrusted verification_uri in device code response");return{device_code:r,user_code:a,verification_uri:l.href,interval:c,expires_in:i}}async function $(e,t,n){let o=h(e);return y({intervalSeconds:t.interval,expiresInSeconds:t.expires_in,waitBeforeFirstPoll:!0,signal:n,poll:async()=>{let r=await m(o.accessTokenUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"GitHubCopilotChat/0.35.0"},body:new URLSearchParams({client_id:x,device_code:t.device_code,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal:n});if(r&&typeof r=="object"&&typeof r.access_token=="string")return{status:"complete",value:r.access_token};if(r&&typeof r=="object"&&typeof r.error=="string"){let{error:a,error_description:s,interval:c}=r;if(a==="authorization_pending")return{status:"pending"};if(a==="slow_down")return{status:"slow_down",intervalSeconds:typeof c=="number"?c:void 0};let i=s?`: ${s}`:"";return{status:"failed",message:`Device flow failed: ${a}${i}`}}return{status:"failed",message:"Invalid device token response"}}})}async function I(e,t,n){let r=h(t||"github.com"),a=await m(r.copilotTokenUrl,{headers:{Accept:"application/json",Authorization:`Bearer ${e}`,...f},signal:n});if(!a||typeof a!="object")throw new Error("Invalid Copilot token response");let s=a.token,c=a.expires_at;if(typeof s!="string"||typeof c!="number")throw new Error("Invalid Copilot token response fields");return{type:"oauth",refresh:e,access:s,expires:c*1e3-300*1e3,enterpriseUrl:t}}async function T(e,t,n){let o=await I(e,t,n),{availableModelIds:r}=await E(o.access,t,n,{maxRetries:0,maxElapsedMs:0});return{...o,availableModelIds:r}}async function H(e,t,n,o){let a=`${b(e,n)}/models/${t}/policy`,s;try{s=await C(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`,...f,"openai-intent":"chat-policy","x-interaction-type":"chat-policy"},body:JSON.stringify({state:"enabled"})},o,{maxRetries:2,maxElapsedMs:5e3})}catch(c){if(o.aborted)throw c;return!1}if(s.status===429)throw new Error(`${s.status} ${s.statusText}: ${await s.text()}`);return s.ok}async function O(e,t,n,o){let r=[];for(let a of t)try{await H(e,a,n,o)&&r.push(a)}catch(s){if(o.aborted)throw s;break}return r}async function G(e){let t=await e.prompt({type:"text",message:"GitHub Enterprise URL/domain (blank for github.com)",placeholder:"company.ghe.com"});if(e.signal.aborted)throw new Error("Login cancelled");let n=t.trim(),o=_(t);if(n&&!o)throw new Error("Invalid GitHub Enterprise URL/domain");let r=o||"github.com",a=await k(r,e.signal);e.notify({type:"device_code",userCode:a.user_code,verificationUri:a.verification_uri,intervalSeconds:a.interval,expiresInSeconds:a.expires_in});let s=await $(r,a,e.signal),c=await I(s,o??void 0,e.signal),i=await E(c.access,o??void 0,e.signal,{maxRetries:2,maxElapsedMs:5e3}),l=[];return i.policyModelIds.length>0&&(e.notify({type:"progress",message:"Enabling models..."}),l=await O(c.access,i.policyModelIds,o??void 0,e.signal)),{...c,availableModelIds:[...new Set([...i.availableModelIds,...l])]}}function v(e){let t=e.enterpriseUrl;if(!(typeof t!="string"||!t))return _(t)??void 0}var F={name:"GitHub Copilot",isSubscription:!0,login:G,refresh:(e,t)=>T(e.refresh,v(e),t),async toAuth(e){return{apiKey:e.access,baseUrl:b(e.access,v(e))}}};export{F as githubCopilotOAuth};
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{b as A,c as $,d as N,e as B,f as K,g as U,h as W,i as x,j as q,k as z,l as D,m as j,n as H,o as F}from"./chunk-XH6FMP3N.js";import"./chunk-23PRJECN.js";import{a as L,b as O}from"./chunk-FF7UELTU.js";import{i as P}from"./chunk-QBKCAIJG.js";import{J as M,L as _,o as S,s as I,u as v,x as R}from"./chunk-PZMGBKUR.js";import"./chunk-D6VMBA4C.js";import{a as E}from"./chunk-USBJFDJ6.js";import{b as G}from"./chunk-K4NTZEDJ.js";import{h as T}from"./chunk-6AKUD3CF.js";import"./chunk-OSEIQ7SS.js";import{b as w}from"./chunk-CXT5IR5T.js";import"./chunk-QN44UXQR.js";import"./chunk-I6OPDRVF.js";import"./chunk-WHC7AYZD.js";var J=0,y=(n,a,t)=>{let o=new w,s=R(a);return(async()=>{let e={role:"assistant",content:[],api:"google-generative-ai",provider:n.provider,model:n.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{if(t?.fetch&&t.fetch!==globalThis.fetch)throw new Error("Custom fetch is not supported by the Google Generative AI adapter");let l=t?.apiKey;if(!l)throw new Error(`No API key for provider: ${n.provider}`);let d=V(n,l,t?.headers,t?.identity),h=Q(n,s,t),k=await t?.onPayload?.(h,n);k!==void 0&&(h=k);let p=await F(()=>d.models.generateContentStream(h),t);o.push({type:"start",partial:e});let i=null,f=e.content,u=()=>f.length-1;for await(let g of p){await t?.onProviderStreamEvent?.(g,n),e.responseId||=g.responseId;let m=g.candidates?.[0];if(m?.content?.parts)for(let r of m.content.parts){if(r.text!==void 0){let c=W(r);(!i||c&&i.type!=="thinking"||!c&&i.type!=="text")&&(i&&(i.type==="text"?o.push({type:"text_end",contentIndex:f.length-1,content:i.text,partial:e}):o.push({type:"thinking_end",contentIndex:u(),content:i.thinking,partial:e})),c?(i={type:"thinking",thinking:"",thinkingSignature:void 0},e.content.push(i),o.push({type:"thinking_start",contentIndex:u(),partial:e})):(i={type:"text",text:""},e.content.push(i),o.push({type:"text_start",contentIndex:u(),partial:e}))),i.type==="thinking"?(i.thinking+=r.text,i.thinkingSignature=x(i.thinkingSignature,r.thoughtSignature),o.push({type:"thinking_delta",contentIndex:u(),delta:r.text,partial:e})):(i.text+=r.text,i.textSignature=x(i.textSignature,r.thoughtSignature),o.push({type:"text_delta",contentIndex:u(),delta:r.text,partial:e}))}if(r.functionCall){i&&(i.type==="text"?o.push({type:"text_end",contentIndex:u(),content:i.text,partial:e}):o.push({type:"thinking_end",contentIndex:u(),content:i.thinking,partial:e}),i=null);let c=r.functionCall.id,C={type:"toolCall",id:!c||e.content.some(b=>b.type==="toolCall"&&b.id===c)?`${r.functionCall.name}_${Date.now()}_${++J}`:c,name:r.functionCall.name||"",arguments:r.functionCall.args??{},...r.thoughtSignature&&{thoughtSignature:r.thoughtSignature}};e.content.push(C),o.push({type:"toolcall_start",contentIndex:u(),partial:e}),o.push({type:"toolcall_delta",contentIndex:u(),delta:JSON.stringify(C.arguments),partial:e}),o.push({type:"toolcall_end",contentIndex:u(),toolCall:C,partial:e})}}m?.finishReason&&(e.rawStopReason=m.finishReason,e.stopReason=H(m.finishReason),e.content.some(r=>r.type==="toolCall")&&e.stopReason==="stop"&&(e.stopReason="toolUse")),g.usageMetadata&&(e.usage={input:(g.usageMetadata.promptTokenCount||0)-(g.usageMetadata.cachedContentTokenCount||0),output:(g.usageMetadata.candidatesTokenCount||0)+(g.usageMetadata.thoughtsTokenCount||0),cacheRead:g.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,reasoning:g.usageMetadata.thoughtsTokenCount||0,totalTokens:g.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},M(n,e.usage))}if(i&&(i.type==="text"?o.push({type:"text_end",contentIndex:u(),content:i.text,partial:e}):o.push({type:"thinking_end",contentIndex:u(),content:i.thinking,partial:e})),t?.signal?.aborted)throw new Error("Request was aborted");if(e.stopReason==="pending")throw new Error("Google stream ended without a finish reason");if(e.stopReason==="aborted"||e.stopReason==="error"){let g=e.rawStopReason?`Provider stopped with: ${e.rawStopReason}`:"An unknown error occurred";throw new Error(g)}o.push({type:"done",reason:e.stopReason,message:e}),o.end()}catch(l){for(let d of e.content)"index"in d&&delete d.index;e.stopReason=t?.signal?.aborted?"aborted":"error",e.errorMessage=O(L(l)),o.push({type:"error",reason:e.stopReason,error:e}),o.end()}})(),o},de=(n,a,t)=>{let o=t?.apiKey;if(!o)throw new Error(`No API key for provider: ${n.provider}`);let s={...P(n,a,t,o),toolChoice:t?.toolChoice};if(!t?.reasoning)return y(n,a,{...s,thinking:{enabled:!1}});let e=_(n,t.reasoning);if(e==="off")return y(n,a,{...s,thinking:{enabled:!1}});let l=$(n,e);return N(n)?y(n,a,{...s,thinking:{enabled:!0,level:B(l)}}):y(n,a,{...s,thinking:{enabled:!0,budgetTokens:X(n,l,t.thinkingBudgets)}})};function V(n,a,t,o){let s={};n.baseUrl&&(s.baseUrl=n.baseUrl,s.apiVersion="");let e=G(T(n,o),n.headers,t);return e&&(s.headers=e),new A({apiKey:a,httpOptions:Object.keys(s).length>0?s:void 0})}function Q(n,a,t={}){let o=q(n,a),s=I(a.messages),e=v(a.messages),l={};t.temperature!==void 0&&(l.temperature=t.temperature),t.maxTokens!==void 0&&(l.maxOutputTokens=t.maxTokens);let d=D(n.id),h=e.length>0?j(e,t.toolChoice,d):void 0,k=s?S(s):"",p={...Object.keys(l).length>0&&l,...k&&{systemInstruction:E(k)},...e.length>0&&{tools:z(e,!1,d)},...h!==void 0&&{toolConfig:{functionCallingConfig:{mode:h}}}};if(t.thinking?.enabled&&n.reasoning){let f={includeThoughts:!0};t.thinking.level!==void 0?f.thinkingLevel=K(t.thinking.level):t.thinking.budgetTokens!==void 0&&(f.thinkingBudget=t.thinking.budgetTokens),p.thinkingConfig=f}else n.reasoning&&t.thinking&&!t.thinking.enabled&&(p.thinkingConfig=U(n));if(t.signal){if(t.signal.aborted)throw new Error("Request aborted");p.abortSignal=t.signal}return{model:n.id,contents:o,config:p}}function X(n,a,t){return t?.[a]!==void 0?t[a]:n.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[a]:n.id.includes("2.5-flash-lite")?{minimal:512,low:2048,medium:8192,high:24576}[a]:n.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[a]:-1}export{y as stream,de as streamSimple};
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as D,b as T,c as V,d as N,e as j,f as K,g as $,h as q,i as b,j as B,k as J,l as W,m as z,n as H,o as F}from"./chunk-XH6FMP3N.js";import"./chunk-23PRJECN.js";import{a as P,b as U}from"./chunk-FF7UELTU.js";import{i as A}from"./chunk-QBKCAIJG.js";import{J as E,L as G,o as R,s as S,u as w,x as _}from"./chunk-PZMGBKUR.js";import{a as C}from"./chunk-6R73ICDB.js";import"./chunk-D6VMBA4C.js";import{a as M}from"./chunk-USBJFDJ6.js";import{b as L}from"./chunk-K4NTZEDJ.js";import{h as O}from"./chunk-6AKUD3CF.js";import"./chunk-OSEIQ7SS.js";import{b as I}from"./chunk-CXT5IR5T.js";import"./chunk-QN44UXQR.js";import"./chunk-I6OPDRVF.js";import"./chunk-WHC7AYZD.js";var X="v1",Y="gcp-vertex-credentials",Z=0,y=(e,o,n)=>{let i=new I,s=_(o);return(async()=>{let t={role:"assistant",content:[],api:"google-vertex",provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{if(n?.fetch&&n.fetch!==globalThis.fetch)throw new Error("Custom fetch is not supported by the Google Vertex adapter");let l=re(n),g=l?te(e,l,n?.headers,n?.identity):ee(e,se(n),ue(n),n?.headers,n?.env,n?.identity),h=le(e,s,n),m=await n?.onPayload?.(h,e);m!==void 0&&(h=m);let p=await F(()=>g.models.generateContentStream(h),n);i.push({type:"start",partial:t});let r=null,f=t.content,c=()=>f.length-1;for await(let u of p){await n?.onProviderStreamEvent?.(u,e),t.responseId||=u.responseId;let k=u.candidates?.[0];if(k?.content?.parts)for(let a of k.content.parts){if(a.text!==void 0){let d=q(a);(!r||d&&r.type!=="thinking"||!d&&r.type!=="text")&&(r&&(r.type==="text"?i.push({type:"text_end",contentIndex:f.length-1,content:r.text,partial:t}):i.push({type:"thinking_end",contentIndex:c(),content:r.thinking,partial:t})),d?(r={type:"thinking",thinking:"",thinkingSignature:void 0},t.content.push(r),i.push({type:"thinking_start",contentIndex:c(),partial:t})):(r={type:"text",text:""},t.content.push(r),i.push({type:"text_start",contentIndex:c(),partial:t}))),r.type==="thinking"?(r.thinking+=a.text,r.thinkingSignature=b(r.thinkingSignature,a.thoughtSignature),i.push({type:"thinking_delta",contentIndex:c(),delta:a.text,partial:t})):(r.text+=a.text,r.textSignature=b(r.textSignature,a.thoughtSignature),i.push({type:"text_delta",contentIndex:c(),delta:a.text,partial:t}))}if(a.functionCall){r&&(r.type==="text"?i.push({type:"text_end",contentIndex:c(),content:r.text,partial:t}):i.push({type:"thinking_end",contentIndex:c(),content:r.thinking,partial:t}),r=null);let d=a.functionCall.id,x={type:"toolCall",id:!d||t.content.some(v=>v.type==="toolCall"&&v.id===d)?`${a.functionCall.name}_${Date.now()}_${++Z}`:d,name:a.functionCall.name||"",arguments:a.functionCall.args??{},...a.thoughtSignature&&{thoughtSignature:a.thoughtSignature}};t.content.push(x),i.push({type:"toolcall_start",contentIndex:c(),partial:t}),i.push({type:"toolcall_delta",contentIndex:c(),delta:JSON.stringify(x.arguments),partial:t}),i.push({type:"toolcall_end",contentIndex:c(),toolCall:x,partial:t})}}k?.finishReason&&(t.rawStopReason=k.finishReason,t.stopReason=H(k.finishReason),t.content.some(a=>a.type==="toolCall")&&t.stopReason==="stop"&&(t.stopReason="toolUse")),u.usageMetadata&&(t.usage={input:(u.usageMetadata.promptTokenCount||0)-(u.usageMetadata.cachedContentTokenCount||0),output:(u.usageMetadata.candidatesTokenCount||0)+(u.usageMetadata.thoughtsTokenCount||0),cacheRead:u.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,reasoning:u.usageMetadata.thoughtsTokenCount||0,totalTokens:u.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},E(e,t.usage))}if(r&&(r.type==="text"?i.push({type:"text_end",contentIndex:c(),content:r.text,partial:t}):i.push({type:"thinking_end",contentIndex:c(),content:r.thinking,partial:t})),n?.signal?.aborted)throw new Error("Request was aborted");if(t.stopReason==="pending")throw new Error("Google Vertex stream ended without a finish reason");if(t.stopReason==="aborted"||t.stopReason==="error"){let u=t.rawStopReason?`Provider stopped with: ${t.rawStopReason}`:"An unknown error occurred";throw new Error(u)}i.push({type:"done",reason:t.stopReason,message:t}),i.end()}catch(l){for(let g of t.content)"index"in g&&delete g.index;t.stopReason=n?.signal?.aborted?"aborted":"error",t.errorMessage=U(P(l)),i.push({type:"error",reason:t.stopReason,error:t}),i.end()}})(),i},Oe=(e,o,n)=>{let i={...A(e,o,n,void 0),toolChoice:n?.toolChoice};if(!n?.reasoning)return y(e,o,{...i,thinking:{enabled:!1}});let s=G(e,n.reasoning);if(s==="off")return y(e,o,{...i,thinking:{enabled:!1}});let t=V(e,s);return N(e)?y(e,o,{...i,thinking:{enabled:!0,level:j(t)}}):y(e,o,{...i,thinking:{enabled:!0,budgetTokens:ce(e,t,n.thinkingBudgets)}})};function ee(e,o,n,i,s,t){let l=ie(s);return new T({vertexai:!0,project:o,location:n,apiVersion:X,...l?{googleAuthOptions:l}:{},httpOptions:Q(e,i,t)})}function te(e,o,n,i){return new T({vertexai:!0,apiKey:o,apiVersion:X,httpOptions:Q(e,n,i)})}function Q(e,o,n){let i={},s=ne(e.baseUrl);s&&(i.baseUrl=s,i.baseUrlResourceScope=D.COLLECTION,oe(s)&&(i.apiVersion=""));let t=L(O(e,n),e.headers,o);return t&&(i.headers=t),Object.keys(i).length>0?i:void 0}function ne(e){let o=e.trim();if(!(!o||o.includes("{location}")))return o}function oe(e){try{return new URL(e).pathname.split("/").some(n=>/^v\d+(?:beta\d*)?$/.test(n))}catch{return/(?:^|\/)v\d+(?:beta\d*)?(?:\/|$)/.test(e)}}function ie(e){let o=C("GOOGLE_APPLICATION_CREDENTIALS",e);return o?{keyFilename:o}:void 0}function re(e){let o=e?.apiKey?.trim();if(!(!o||o===Y||ae(o)))return o}function ae(e){return/^<[^>]+>$/.test(e)}function se(e){let o=e?.project||C("GOOGLE_CLOUD_PROJECT",e?.env)||C("GCLOUD_PROJECT",e?.env);if(!o)throw new Error("Vertex AI requires a project ID. Set GOOGLE_CLOUD_PROJECT/GCLOUD_PROJECT or pass project in options.");return o}function ue(e){let o=e?.location||C("GOOGLE_CLOUD_LOCATION",e?.env);if(!o)throw new Error("Vertex AI requires a location. Set GOOGLE_CLOUD_LOCATION or pass location in options.");return o}function le(e,o,n={}){let i=B(e,o),s=S(o.messages),t=w(o.messages),l={};n.temperature!==void 0&&(l.temperature=n.temperature),n.maxTokens!==void 0&&(l.maxOutputTokens=n.maxTokens);let g=W(e.id),h=t.length>0?z(t,n.toolChoice,g):void 0,m=s?R(s):"",p={...Object.keys(l).length>0&&l,...m&&{systemInstruction:M(m)},...t.length>0&&{tools:J(t,!1,g)},...h!==void 0&&{toolConfig:{functionCallingConfig:{mode:h}}}};if(n.thinking?.enabled&&e.reasoning){let f={includeThoughts:!0};n.thinking.level!==void 0?f.thinkingLevel=K(n.thinking.level):n.thinking.budgetTokens!==void 0&&(f.thinkingBudget=n.thinking.budgetTokens),p.thinkingConfig=f}else e.reasoning&&n.thinking&&!n.thinking.enabled&&(p.thinkingConfig=$(e));if(n.signal){if(n.signal.aborted)throw new Error("Request aborted");p.abortSignal=n.signal}return{model:e.id,contents:i,config:p}}function ce(e,o,n){return n?.[o]!==void 0?n[o]:e.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[o]:e.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[o]:-1}export{y as stream,Oe as streamSimple};
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a,b,c,h as d,i as e,j as f,k as g,l as h,m as i,n as j,o as k,p as l,q as m,r as n,s as o,t as p,u as q,v as r,w as s,x as t}from"./chunk-2ZNLUY2U.js";import"./chunk-6LZK4DDH.js";import"./chunk-ASYQHJVQ.js";import"./chunk-O3JW2F7D.js";import"./chunk-HU6UIDEJ.js";import"./chunk-TZFLHVOQ.js";import"./chunk-7MU2AKNM.js";import"./chunk-JERCOLY3.js";import"./chunk-QEOFEETJ.js";import"./chunk-DGMNI4AO.js";import"./chunk-5T7IX5KN.js";import"./chunk-OKRK6JPY.js";import"./chunk-BGVHA2D4.js";import"./chunk-3OKHUVEM.js";import"./chunk-SUFW24P4.js";import"./chunk-OE4KH3NJ.js";import"./chunk-LCKVYFMD.js";import"./chunk-5M4PFLRW.js";import"./chunk-PMG4YGDU.js";import"./chunk-3YHOCPQU.js";import"./chunk-MEPASGPP.js";import"./chunk-STUHNKQS.js";import"./chunk-PFMEUFJ7.js";import"./chunk-KRXTI4JO.js";import"./chunk-DPQPXBTP.js";import"./chunk-Q4UGYGU5.js";import"./chunk-W5LGYSPZ.js";import"./chunk-E7ZMYIY6.js";import"./chunk-NAA7GF6Q.js";import"./chunk-QWAQHHRS.js";import"./chunk-J5DVLUKY.js";import"./chunk-WHC7AYZD.js";export{i as SLACK_APP_MANIFEST,c as ensureGitInstalled,h as formatConfigOutput,q as generateConfigs,g as generateDefaultModeJson,f as generateDotEnvContent,m as generateLaunchdPlist,l as generateSystemdUnit,b as getGitInstallHint,k as getInstallCommand,d as getResolvedPaths,j as isBackendInstalled,a as isGitInstalled,e as parseInitAnswersJson,o as parseInitAnswersLines,n as runFeishuUserLogin,s as runInit,p as safeCopy,r as writeDotEnv,t as writeInitConfigs};
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as _}from"./chunk-JXFG66UN.js";import{a as w}from"./chunk-ILEML5IP.js";import{a as d}from"./chunk-6R73ICDB.js";import"./chunk-WHC7AYZD.js";var f="17e5f671-d194-4dfb-9706-5516cb48c098",C="https://auth.kimi.com",E=900,k=5,T=30*1e3,y=3;function S(){return(d("KIMI_CODE_OAUTH_HOST")||d("KIMI_OAUTH_HOST")||C).replace(/\/+$/,"")}function p(e){return AbortSignal.any([AbortSignal.timeout(T),e])}function l(e){return new URLSearchParams(e).toString()}async function h(e){try{let o=await e.json();return o&&typeof o=="object"?o:null}catch{return null}}function g(e){if(typeof e!="string"||!e)return null;try{let o=new URL(e);return o.protocol!=="https:"&&o.protocol!=="http:"?null:o.href}catch{return null}}async function $(e,o){let r=await fetch(`${e}/api/oauth/device_authorization`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:l({client_id:f}),signal:p(o)});if(!r.ok){let m=await r.text().catch(()=>"");throw new Error(`Kimi Code device authorization failed with status ${r.status}${m?`: ${m}`:""}`)}let t=await h(r),n=t?.device_code,i=t?.user_code,a=t?.verification_uri,s=t?.verification_uri_complete;if(typeof n!="string"||typeof i!="string"||typeof a!="string"||typeof s!="string"||!g(s)||!g(a))throw new Error(`Invalid Kimi Code device authorization response: ${JSON.stringify(t)}`);let c=t?.interval,u=t?.expires_in;return{deviceCode:n,userCode:i,verificationUri:a,verificationUriComplete:s,intervalSeconds:typeof c=="number"&&Number.isFinite(c)&&c>0?c:k,expiresInSeconds:typeof u=="number"&&Number.isFinite(u)&&u>0?u:E}}function v(e,o){let r=e?.access_token,t=e?.refresh_token,n=e?.expires_in;if(typeof r!="string"||!r||typeof t!="string"||!t||typeof n!="number"||!Number.isFinite(n)||n<=0)throw new Error(`Kimi Code token ${o} response missing fields: ${JSON.stringify(e)}`);return{access:r,refresh:t,expires:Date.now()+n*1e3}}async function x(e,o,r){return w({intervalSeconds:o.intervalSeconds,expiresInSeconds:o.expiresInSeconds,waitBeforeFirstPoll:!0,signal:r,poll:async()=>{let t=await fetch(`${e}/api/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:l({client_id:f,device_code:o.deviceCode,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal:p(r)});if(t.status>=500){let s=await t.text().catch(()=>"");return{status:"failed",message:`Kimi Code device token request failed with status ${t.status}${s?`: ${s}`:""}`}}let n=await h(t);if(t.ok&&typeof n?.access_token=="string")try{return{status:"complete",value:v(n,"poll")}}catch(s){return{status:"failed",message:s instanceof Error?s.message:String(s)}}let i=n?.error,a=typeof n?.error_description=="string"?`: ${n.error_description}`:"";if(i==="authorization_pending")return{status:"pending"};if(i==="slow_down"){let s=n?.interval;return{status:"slow_down",intervalSeconds:typeof s=="number"&&s>0?s:void 0}}return i==="expired_token"?{status:"failed",message:"Kimi Code device authorization expired. Please restart login."}:i==="access_denied"?{status:"failed",message:"Kimi Code login was denied."}:{status:"failed",message:`Kimi Code device token request failed (status ${t.status})${typeof i=="string"?`: ${i}${a}`:""}`}}})}function O(e){return e.status===429||e.status>=500}async function b(e,o,r){let t;for(let n=0;n<=y;n++){if(n>0&&await _(1e3*2**(n-1),r),r.aborted)throw new Error("Kimi Code token refresh aborted");let i;try{i=await fetch(`${e}/api/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:l({client_id:f,grant_type:"refresh_token",refresh_token:o}),signal:p(r)})}catch(c){t=c instanceof Error?c:new Error(String(c));continue}let a=await h(i);if(i.ok)return v(a,"refresh");if(i.status===401||i.status===403||a?.error==="invalid_grant"){let c=typeof a?.error_description=="string"?`: ${a.error_description}`:"";throw new Error(`Kimi Code token refresh unauthorized (status ${i.status})${c}`)}if(O(i)&&n<y){t=new Error(`Kimi Code token refresh failed with status ${i.status}`);continue}let s=JSON.stringify(a);throw new Error(`Kimi Code token refresh failed with status ${i.status}${s?`: ${s}`:""}`)}throw t??new Error("Kimi Code token refresh failed")}async function I(e){let o=S(),r=await $(o,e.signal);e.notify({type:"device_code",userCode:r.userCode,verificationUri:r.verificationUriComplete,intervalSeconds:r.intervalSeconds,expiresInSeconds:r.expiresInSeconds});let t=await x(o,r,e.signal);return{type:"oauth",access:t.access,refresh:t.refresh,expires:t.expires}}var D={name:"Kimi Code (subscription)",isSubscription:!0,loginLabel:"Sign in with Kimi Code",login:I,refresh:async(e,o)=>{let r=await b(S(),e.refresh,o);return{type:"oauth",access:r.access,refresh:r.refresh,expires:r.expires}},async toAuth(e){return{headers:{Authorization:`Bearer ${e.access}`}}}};export{D as kimiCodingOAuth};
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as m,b as f,e as p,f as d}from"./chunk-JW2HFMTF.js";import{b as l,g as u}from"./chunk-HU6UIDEJ.js";import{a}from"./chunk-KENCMLRE.js";import"./chunk-W5LGYSPZ.js";import{f as s,l as c}from"./chunk-J5DVLUKY.js";import"./chunk-WHC7AYZD.js";import*as v from"fs";import*as y from"path";import{execFileSync as x}from"child_process";import{readFileSync as S}from"fs";import{execFileSync as L}from"node:child_process";function I(n){return S(`/proc/${n}/cmdline`,"utf8").split("\0").filter(Boolean).join(" ")}function _(n){let e=`[Console]::OutputEncoding = [Text.Encoding]::UTF8; $p = Get-CimInstance Win32_Process -Filter 'ProcessId=${n}'; if ($p) { [Console]::Out.Write($p.CommandLine) }`;return L("powershell.exe",["-NoProfile","-NonInteractive","-Command",e],{encoding:"utf8",timeout:1e4,windowsHide:!0,stdio:["ignore","pipe","ignore"]})}function P(n){return L("ps",["-o","command=","-p",String(n)],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]})}var E={linux:I,win32:_};function w(n){if(!Number.isInteger(n)||n<=0)return null;let e=E[process.platform]??P;try{return e(n).trim()||null}catch{return null}}var F=5e3,O=2e3,C=100;function g(n){x("taskkill",["/PID",String(n),"/T","/F"],{stdio:"ignore",windowsHide:!0})}function T(){try{return JSON.parse(v.readFileSync(y.join(c,"machines.json"),"utf8"))}catch{return{}}}var A={platform:process.platform,registry:T,alive:a,commandLine:w,terminate:n=>process.platform==="win32"?g(n):void process.kill(n,"SIGTERM"),kill:n=>process.platform==="win32"?g(n):void process.kill(n,"SIGKILL"),sleep:n=>new Promise(e=>setTimeout(e,n))};function D(n,e,t){let i=o=>t==="win32"?o.replace(/\//g,"\\").toLowerCase():o;return i(n).includes(i(e))}async function h(n,e,t){for(let i=0;i<e;i+=C){if(!t.alive(n))return!0;await t.sleep(C)}return!t.alive(n)}async function M(n,e){if(!e.alive(n))return"not-running";let t=e.commandLine(n);if(t===null)return e.alive(n)?"unverified":"not-running";if(!D(t,m(),e.platform))return"reused";try{e.terminate(n)}catch{}if(await h(n,F,e))return"stopped";try{e.kill(n)}catch{}return await h(n,O,e)?"stopped":"survived"}async function N(n){let e={DATA_DIR:s,CONFIG_DIR:c},t;try{t=l(e)?.device}catch{return}let i=n.find(o=>o.device===t);!t||!i||!["stopped","not-running","reused"].includes(i.outcome)||await u(e,t).catch(()=>{})}async function U(n=A){let e=n.registry(),t=[];for(let[i,o]of Object.entries(f())){if(!d(e[i])||!Number.isInteger(o)||o<=0)continue;let r=await M(o,n);r!=="unverified"&&r!=="survived"&&p(i),t.push({device:i,pid:o,outcome:r})}return await N(t),t}export{D as runsLocalClientEntry,U as stopLaunchedLocalClients};
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as l}from"./chunk-ILEML5IP.js";import"./chunk-WHC7AYZD.js";var p="1031625952748946",f="https://auth.meta.com",w=`${f}/oidc/device/authorization/`,y=`${f}/oidc/device/token/`,g="https://api.meta.ai/muse-code/key",_=1440*60*1e3,m=30*1e3;function u(e){return AbortSignal.any([AbortSignal.timeout(m),e])}async function d(e){try{let t=await e.json();return t&&typeof t=="object"?t:null}catch{return null}}function s(e){for(let t of["error_description","detail","message","error"]){let n=e?.[t];if(typeof n=="string"&&n.trim())return`: ${n.trim()}`}return""}function a(e){if(typeof e!="string"||!e)return null;try{let t=new URL(e);return t.protocol!=="https:"&&t.protocol!=="http:"?null:t.href}catch{return null}}function c(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}async function S(e){let t=await fetch(w,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({client_id:p}).toString(),signal:u(e)}),n=await d(t);if(!t.ok)throw new Error(`Meta device authorization failed with status ${t.status}${s(n)}`);let o=n?.device_code,i=n?.user_code,r=a(n?.verification_uri_complete)??a(n?.verification_uri);if(typeof o!="string"||!o||typeof i!="string"||!i||!r)throw new Error(`Invalid Meta device authorization response: ${JSON.stringify(n)}`);return{deviceCode:o,userCode:i,verificationUri:r,intervalSeconds:c(n?.interval),expiresInSeconds:c(n?.expires_in)}}async function v(e,t){return l({intervalSeconds:e.intervalSeconds,expiresInSeconds:e.expiresInSeconds,waitBeforeFirstPoll:!0,signal:t,poll:async()=>{let n=await fetch(y,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:e.deviceCode,client_id:p}).toString(),signal:u(t)}),o=await d(n);if(n.ok&&typeof o?.access_token=="string"&&o.access_token)return{status:"complete",value:o.access_token};switch(o?.error){case"authorization_pending":return{status:"pending"};case"slow_down":return{status:"slow_down",intervalSeconds:c(o?.interval)};case"access_denied":return{status:"failed",message:"Meta login was denied."};case"expired_token":return{status:"failed",message:"Meta device authorization expired. Please restart login."};default:return{status:"failed",message:`Meta device token request failed with status ${n.status}${s(o)}`}}}})}async function h(e,t){let n=await fetch(g,{method:"POST",headers:{Accept:"application/json",Authorization:`Bearer ${e}`,"Content-Type":"application/json","x-api-version":"1.0.0"},body:"{}",signal:u(t)}),o=await d(n);if(n.status===401||n.status===403)throw new Error(`Meta session expired (status ${n.status}). Run \`/login meta\` to sign in again.${s(o)}`);if(!n.ok)throw new Error(`Meta API key mint failed with status ${n.status}${s(o)}`);let i=o?.api_key;if(typeof i!="string"||!i){let r=a(o?.action_url);throw new Error(`Meta did not issue an API key.${r?` Complete setup at ${r}`:""}`)}return{type:"oauth",refresh:e,access:i,expires:Date.now()+_}}async function I(e){try{let t=await S(e.signal);e.notify({type:"device_code",userCode:t.userCode,verificationUri:t.verificationUri,intervalSeconds:t.intervalSeconds,expiresInSeconds:t.expiresInSeconds});let n=await v(t,e.signal);return e.notify({type:"progress",message:"Enabling Meta Model API access..."}),await h(n,e.signal)}catch(t){throw e.signal.aborted?new Error("Login cancelled"):t}}var A={name:"Meta (Muse subscription)",isSubscription:!0,loginLabel:"Sign in with Meta",login:I,refresh:(e,t)=>h(e.refresh,t),async toAuth(e){return{apiKey:e.access}}};export{A as metaOAuth};
@@ -1,7 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as H}from"./chunk-DQJ6LLAS.js";import{a as z}from"./chunk-V3AQJSWR.js";import{a as D,d as U,i as B,o as J}from"./chunk-QBKCAIJG.js";import{J as $,L as O,o as I,p as E,u as v,y as P}from"./chunk-PZMGBKUR.js";import{c as j,d as L}from"./chunk-SKHLZ6XY.js";import"./chunk-D6VMBA4C.js";import{a as y}from"./chunk-USBJFDJ6.js";import{a as N}from"./chunk-K4NTZEDJ.js";import{h as A}from"./chunk-6AKUD3CF.js";import"./chunk-OSEIQ7SS.js";import{b as S}from"./chunk-CXT5IR5T.js";import"./chunk-WHC7AYZD.js";var K=9,Q=4e3,V=(t,e,n)=>{let r=new S,o=P(e,t.compat?.supportsMidConvoSystemMessages);return(async()=>{let s=ee(t);try{let l=n?.apiKey;if(!l)throw new Error(`No API key for provider: ${t.provider}`);let f=te(),u=J(o.messages,t,d=>f(d)),a=de(t,o,u,n),i=await n?.onPayload?.(a,t);i!==void 0&&(a=i);let c=await se(t,a,l,n);if(r.push({type:"start",partial:s}),await pe(t,s,r,c,n?.onProviderStreamEvent),n?.signal?.aborted)throw new Error("Request was aborted");if(s.stopReason==="pending")throw new Error("Mistral stream ended without a finish reason");if(s.stopReason==="aborted"||s.stopReason==="error")throw new Error(s.errorMessage||"An unknown error occurred");r.push({type:"done",reason:s.stopReason,message:s}),r.end()}catch(l){for(let f of s.content)delete f.partialArgs;s.stopReason=n?.signal?.aborted?"aborted":"error",s.errorMessage=ne(l),r.push({type:"error",reason:s.stopReason,error:s}),r.end()}})(),r},Pe=(t,e,n)=>{let r=n?.apiKey;if(!r)throw new Error(`No API key for provider: ${t.provider}`);let o={...B(t,e,n,r),toolChoice:n?.toolChoice},s=n?.reasoning?O(t,n.reasoning):void 0,l=s==="off"?void 0:s,f=t.reasoning?t.thinkingLevelMap:void 0,u=f?l?f[l]??"high":f.off??void 0:void 0;return V(t,e,{...o,promptMode:t.reasoning&&!f&&l?"reasoning":void 0,reasoningEffort:u})};function ee(t){return{role:"assistant",content:[],api:t.api,provider:t.provider,model:t.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()}}function te(){let t=new Map,e=new Map;return n=>{let r=t.get(n);if(r)return r;let o=0;for(;;){let s=G(n,o),l=e.get(s);if(!l||l===n)return t.set(n,s),e.set(s,n),s;o++}}}function G(t,e){let n=t.replace(/[^a-zA-Z0-9]/g,"");if(e===0&&n.length===K)return n;let r=n||t,o=e===0?r:`${r}:${e}`;return z(o).replace(/[^a-zA-Z0-9]/g,"").slice(0,K)}function ne(t){if(t instanceof Error){let e=t,n=typeof e.statusCode=="number"?e.statusCode:void 0,r=typeof e.body=="string"?e.body.trim():void 0;return n!==void 0&&r?`Mistral API error (${n}): ${re(r,Q)}`:n!==void 0?`Mistral API error (${n}): ${t.message}`:t.message}return oe(t)}function re(t,e){return t.length<=e?t:`${t.slice(0,e)}... [truncated ${t.length-e} chars]`}function oe(t){try{let e=JSON.stringify(t);return e===void 0?String(t):e}catch{return String(t)}}async function se(t,e,n,r){let o=new URL(t.baseUrl);o.pathname=`${o.pathname.replace(/\/+$/u,"")}/`;let s=new URL("v1/chat/completions",o),l=ae(t,n,r),f=r?.timeoutMs??6e4,u=AbortSignal.timeout(f),a=H([r?.signal,u]),i;try{i=await(r?.fetch??globalThis.fetch)(s,{method:"POST",headers:l,body:JSON.stringify(ie(e)),signal:a.signal})}catch(c){throw u.aborted&&!r?.signal?.aborted?new Error(`Mistral response headers timed out after ${f}ms`):c}finally{a.cleanup()}if(await r?.onResponse?.({status:i.status,headers:N(i.headers)},t),!i.ok){let c=await i.text();throw new M(i.status,c,i.statusText)}if(!i.body)throw new Error("Mistral response has no body");return fe(i.body,r?.signal)}var M=class extends Error{statusCode;body;constructor(e,n,r){super(r||`Request failed with status ${e}`),this.name="MistralHttpError",this.statusCode=e,this.body=n}};function ae(t,e,n){let r=new Headers({...A(t,n?.identity),accept:"text/event-stream",authorization:`Bearer ${e}`,"content-type":"application/json"});W(r,t.headers),W(r,n?.headers);let o=q(t.headers,"x-affinity")||q(n?.headers,"x-affinity");return X(n)&&!o&&r.set("x-affinity",n.sessionId),r}function W(t,e){if(e)for(let[n,r]of Object.entries(e))r===null?t.delete(n):t.set(n,r)}function q(t,e){return!!t&&Object.keys(t).some(n=>n.toLowerCase()===e)}function ie(t){let e={...t};for(let[r,o]of[["topP","top_p"],["maxTokens","max_tokens"],["randomSeed","random_seed"],["responseFormat","response_format"],["toolChoice","tool_choice"],["presencePenalty","presence_penalty"],["frequencyPenalty","frequency_penalty"],["parallelToolCalls","parallel_tool_calls"],["reasoningEffort","reasoning_effort"],["promptMode","prompt_mode"],["promptCacheKey","prompt_cache_key"],["safePrompt","safe_prompt"]])k(e,r,o);e.messages=t.messages.map(r=>ce(r));let n=e.response_format;if(w(n)){let r={...n};k(r,"jsonSchema","json_schema");let o=r.json_schema;if(w(o)){let s={...o};k(s,"schemaDefinition","schema"),r.json_schema=s}e.response_format=r}return e}function ce(t){let e={...t};return k(e,"toolCalls","tool_calls"),k(e,"toolCallId","tool_call_id"),Array.isArray(t.content)&&(e.content=t.content.map(n=>le(n))),e}function le(t){let e={...t};for(let[n,r]of[["imageUrl","image_url"],["documentUrl","document_url"],["documentName","document_name"],["fileId","file_id"],["referenceIds","reference_ids"],["inputAudio","input_audio"]])k(e,n,r);return e}function k(t,e,n){e in t&&(t[n]=t[e],delete t[e])}function w(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var b=Symbol("mistral-stream-done");async function*fe(t,e){let n=t.getReader(),r=new TextDecoder,o="",s=()=>{n.cancel().catch(()=>{})};e?.addEventListener("abort",s,{once:!0});try{for(;;){if(e?.aborted)throw e.reason;let{done:l,value:f}=await n.read();if(e?.aborted)throw e.reason;o+=l?r.decode():r.decode(f,{stream:!0});let u=F(o);for(;u;){let a=Z(o.slice(0,u.index));if(o=o.slice(u.index+u.length),a===b)return;a&&(yield a),u=F(o)}if(l)break}if(o.trim()){let l=Z(o);l!==b&&l&&(yield l)}}finally{e?.removeEventListener("abort",s);try{await n.cancel()}catch{}try{n.releaseLock()}catch{}}}function F(t){let e=/\r\n\r\n|\r\n\r|\r\n\n|\r\r\n|\n\r\n|\r\r|\n\r|\n\n/u.exec(t);return e?.index===void 0?void 0:{index:e.index,length:e[0].length}}function Z(t){let e=t.split(/\r\n|\r|\n/u).filter(r=>r.startsWith("data:")).map(r=>r.slice(5).trimStart()).join(`
5
- `).trim();if(!e)return;if(e==="[DONE]")return b;let n=JSON.parse(e);if(!w(n)||!Array.isArray(n.choices))throw new Error("Invalid Mistral streaming event");return{data:n}}function de(t,e,n,r){let o={model:t.id,stream:!0,messages:he(n,t.input.includes("image"))},s=v(e.messages);return s.length>0&&(o.tools=me(s)),r?.temperature!==void 0&&(o.temperature=r.temperature),r?.maxTokens!==void 0&&(o.maxTokens=r.maxTokens),r?.toolChoice&&(o.toolChoice=ye(r.toolChoice)),r?.promptMode&&(o.promptMode=r.promptMode),r?.reasoningEffort&&(o.reasoningEffort=r.reasoningEffort),X(r)&&(o.promptCacheKey=r.sessionId),o}function X(t){return t?.cacheRetention!=="none"&&!!t?.sessionId}function ue(t,e){let n=t,r=n.promptTokensDetails?.cachedTokens??n.prompt_tokens_details?.cached_tokens??n.promptTokenDetails?.cachedTokens??n.prompt_token_details?.cached_tokens??n.numCachedTokens??n.num_cached_tokens??0,o=typeof r=="number"&&Number.isFinite(r)?r:0;return Math.min(e,Math.max(0,o))}async function pe(t,e,n,r,o){let s=null,l=e.content,f=()=>l.length-1,u=new Map,a=i=>{if(i){if(i.type==="text"){n.push({type:"text_end",contentIndex:f(),content:i.text,partial:e});return}i.type==="thinking"&&n.push({type:"thinking_end",contentIndex:f(),content:i.thinking,partial:e})}};for await(let i of r){let c=i.data;if(await o?.(c,t),e.responseId||=c.id,c.usage){let p=c.usage.prompt_tokens||0,h=ue(c.usage,p);e.usage.input=Math.max(0,p-h),e.usage.output=c.usage.completion_tokens||0,e.usage.cacheRead=h,e.usage.cacheWrite=0,e.usage.totalTokens=c.usage.total_tokens||e.usage.input+e.usage.output+e.usage.cacheRead+e.usage.cacheWrite,$(t,e.usage)}let d=c.choices[0];if(!d)continue;if(d.finish_reason){e.rawStopReason=d.finish_reason;let p=xe(d.finish_reason);e.stopReason=p.stopReason,p.errorMessage&&(e.errorMessage=p.errorMessage)}let x=d.delta;if(x.content!==null&&x.content!==void 0){let p=typeof x.content=="string"?[x.content]:x.content;for(let h of p){if(typeof h=="string"){let m=y(h);if(!m)continue;(!s||s.type!=="text")&&(a(s),s={type:"text",text:""},e.content.push(s),n.push({type:"text_start",contentIndex:f(),partial:e})),s.text+=m,n.push({type:"text_delta",contentIndex:f(),delta:m,partial:e});continue}if(h.type==="thinking"){let m=(h.thinking??[]).map(g=>g.text??"").filter(g=>g.length>0).join(""),_=y(m);if(!_)continue;(!s||s.type!=="thinking")&&(a(s),s={type:"thinking",thinking:""},e.content.push(s),n.push({type:"thinking_start",contentIndex:f(),partial:e})),s.thinking+=_,n.push({type:"thinking_delta",contentIndex:f(),delta:_,partial:e});continue}if(h.type==="text"){let m=y(h.text??"");if(!m)continue;(!s||s.type!=="text")&&(a(s),s={type:"text",text:""},e.content.push(s),n.push({type:"text_start",contentIndex:f(),partial:e})),s.text+=m,n.push({type:"text_delta",contentIndex:f(),delta:m,partial:e})}}}let Y=x.tool_calls||[];for(let p of Y){s&&(a(s),s=null);let h=p.id&&p.id!=="null"?p.id:G(`toolcall:${p.index??0}`,0),m=p.index??h,_=u.get(m),g;if(_!==void 0){let R=e.content[_];R?.type==="toolCall"&&(g=R)}g||(g={type:"toolCall",id:h,name:p.function.name,arguments:{},partialArgs:""},e.content.push(g),u.set(m,e.content.length-1),n.push({type:"toolcall_start",contentIndex:e.content.length-1,partial:e}));let C=typeof p.function.arguments=="string"?p.function.arguments:JSON.stringify(p.function.arguments||{});g.partialArgs=(g.partialArgs||"")+C,g.arguments=L(g.partialArgs),n.push({type:"toolcall_delta",contentIndex:u.get(m),delta:C,partial:e})}}a(s);for(let i of u.values()){let c=e.content[i];if(c.type!=="toolCall")continue;let d=c;Object.assign(d,j(d.partialArgs)),delete d.partialArgs,n.push({type:"toolcall_end",contentIndex:i,toolCall:d,partial:e})}}function me(t){return t.map(e=>{let n=U(e,!0);return{type:"function",function:{name:e.name,description:e.description,parameters:T(D(e,n)),strict:n??!1}}})}function T(t){if(Array.isArray(t))return t.map(e=>T(e));if(t&&typeof t=="object"){let e={};for(let[n,r]of Object.entries(t))e[n]=T(r);return e}return t}function he(t,e){let n=[];for(let[r,o]of t.entries()){if(o.role==="system"){let a=r===0?I(o):E(o);a.length>0&&n.push({role:"system",content:y(a)});continue}if(o.role==="user"){if(typeof o.content=="string"){n.push({role:"user",content:y(o.content)});continue}let a=o.content.some(c=>c.type==="image"),i=o.content.filter(c=>c.type==="text"||e).map(c=>c.type==="text"?{type:"text",text:y(c.text)}:{type:"image_url",imageUrl:`data:${c.mimeType};base64,${c.data}`});if(i.length>0){n.push({role:"user",content:i});continue}a&&!e&&n.push({role:"user",content:"(image omitted: model does not support images)"});continue}if(o.role==="assistant"){let a=[],i=[];for(let d of o.content){if(d.type==="text"){d.text.trim().length>0&&a.push({type:"text",text:y(d.text)});continue}if(d.type==="thinking"){d.thinking.trim().length>0&&a.push({type:"thinking",thinking:[{type:"text",text:y(d.thinking)}]});continue}i.push({id:d.id,type:"function",function:{name:d.name,arguments:JSON.stringify(d.arguments||{})},index:0})}let c={role:"assistant",prefix:!1};a.length>0&&(c.content=a),i.length>0&&(c.toolCalls=i),(a.length>0||i.length>0)&&n.push(c);continue}let s=[],l=o.content.filter(a=>a.type==="text").map(a=>a.type==="text"?y(a.text):"").join(`
6
- `),f=o.content.some(a=>a.type==="image"),u=ge(l,f,e,o.isError);s.push({type:"text",text:u});for(let a of o.content)e&&a.type==="image"&&s.push({type:"image_url",imageUrl:`data:${a.mimeType};base64,${a.data}`});n.push({role:"tool",toolCallId:o.toolCallId,name:o.toolName,content:s})}return n}function ge(t,e,n,r){let o=t.trim(),s=r?"[tool error] ":"";return o.length>0?`${s}${o}${e&&!n?`
7
- [tool image omitted: model does not support images]`:""}`:e?n?r?"[tool error] (see attached image)":"(see attached image)":r?"[tool error] (image omitted: model does not support images)":"(image omitted: model does not support images)":r?"[tool error] (no tool output)":"(no tool output)"}function ye(t){if(t)return t==="auto"||t==="none"||t==="any"||t==="required"?t:{type:"function",function:{name:t.function.name}}}function xe(t){if(t===null)return{stopReason:"stop"};switch(t){case"stop":return{stopReason:"stop"};case"length":case"model_length":return{stopReason:"length"};case"tool_calls":return{stopReason:"toolUse"};case"error":return{stopReason:"error",errorMessage:"Provider stopped with: error (server error)"};default:return{stopReason:"error",errorMessage:`Provider stopped with: ${t}`}}}export{V as stream,Pe as streamSimple};
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{H as a,I as b,J as c,K as d,L as e,M as f,N as g,O as h,P as i}from"./chunk-EXJA5RIX.js";import"./chunk-EQIMHXC4.js";import"./chunk-YKKEI5GI.js";import"./chunk-PZMGBKUR.js";import"./chunk-SKHLZ6XY.js";import"./chunk-D6VMBA4C.js";import"./chunk-6AKUD3CF.js";import"./chunk-OSEIQ7SS.js";import"./chunk-CXT5IR5T.js";import"./chunk-LACGULCN.js";import"./chunk-3TGQSGG4.js";import"./chunk-QUUEQRIT.js";import"./chunk-AWFUHWQK.js";import"./chunk-B3XBQEFM.js";import"./chunk-WHC7AYZD.js";export{a as defaultModelPerProvider,c as findExactModelReferenceMatch,h as findInitialModel,g as resolveCliModel,b as resolveModelReference,f as resolveModelScope,d as resolveModelScopeFromModels,e as resolveModelScopeWithDiagnostics,i as restoreModelFromSession};
@@ -1,12 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as ue,c as fe}from"./chunk-YKKEI5GI.js";import{a as we}from"./chunk-DQJ6LLAS.js";import{a as ye,b as G,c as be,d as j}from"./chunk-DXBSQXJL.js";import{a as me}from"./chunk-XIECJESP.js";import"./chunk-V3AQJSWR.js";import{a as he}from"./chunk-ZSV6TO7Q.js";import{a as de,b as pe}from"./chunk-FF7UELTU.js";import{f as K,i as le}from"./chunk-QBKCAIJG.js";import{C as J,F as ae,L as ce,o as ne,r as se,s as oe,y as ie}from"./chunk-PZMGBKUR.js";import"./chunk-6R73ICDB.js";import"./chunk-SKHLZ6XY.js";import{a as q,c as ee,d as te}from"./chunk-D6VMBA4C.js";import"./chunk-USBJFDJ6.js";import{a as H}from"./chunk-K4NTZEDJ.js";import{h as re}from"./chunk-6AKUD3CF.js";import"./chunk-OSEIQ7SS.js";import{b as Q}from"./chunk-CXT5IR5T.js";import"./chunk-WHC7AYZD.js";var Be="https://chatgpt.com/backend-api",Pe="https://api.openai.com/auth",Ie=0,ge=1e3,Fe=6e4,$e=15e3,Ue=3,Re=new Set(["openai","openai-codex","opencode"]),ze=1009,Je="websocket_connection_limit_reached",He="previous_response_not_found",Ke=new Set(["completed","incomplete","failed","cancelled","queued","in_progress"]);function Se(e){if(e.stopReason==="pending")throw new Error("Codex stream ended without a stop reason");if(e.stopReason==="error"||e.stopReason==="aborted")throw new Error(e.errorMessage||"An unknown error occurred")}function Ge(e){return/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(e)}function je(e,r){return e===429&&Ge(r)?!1:e===429||e===500||e===502||e===503||e===504?!0:/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(r)}function Ve(e){let r=e.get("retry-after-ms");if(r!==null){let s=Number(r);if(Number.isFinite(s))return Math.max(0,s)}let t=e.get("retry-after");if(!t)return;let n=Number(t);if(Number.isFinite(n))return Math.max(0,n*1e3);let i=Date.parse(t);if(!Number.isNaN(i))return Math.max(0,i-Date.now())}var F=class extends Error{};function Xe(e,r){let t=r?.maxRetryDelayMs??Fe;if(t>0&&e>t)throw new F(`Server requested ${Math.ceil(e/1e3)}s retry delay (max: ${Math.ceil(t/1e3)}s)`);return e}function Ee(e,r){return new Promise((t,n)=>{if(r?.aborted){n(new Error("Request was aborted"));return}let i=setTimeout(t,e);r?.addEventListener("abort",()=>{clearTimeout(i),n(new Error("Request was aborted"))})})}function _e(e){if(e!==void 0){if(!Number.isFinite(e)||e<0)throw new Error(`Invalid timeoutMs: ${String(e)}`);return Math.floor(e)}}function Ye(){return typeof process>"u"||!(process.versions?.node||process.versions?.bun)?null:process.getBuiltinModule?.("node:zlib")??null}function Ze(e){let r=Ye();if(!r||typeof r.zstdCompressSync!="function")return null;try{let t=r.zstdCompressSync(e,{params:{[r.constants.ZSTD_c_compressionLevel]:Ue}});return new Uint8Array(t)}catch{return null}}var Qe=(e,r,t)=>{let n=new Q,i=ie(r,e.compat?.supportsMidConvoSystemMessages);return(async()=>{let s={role:"assistant",content:[],api:"openai-codex-responses",provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{let o=t?.apiKey;if(!o)throw new Error(`No API key for provider: ${e.provider}`);let c=xt(o),a=K(J(i.messages),e.compat?.supportsOpenAIGrammarTools??!1),d=t?.cacheRetention==="none"?void 0:t?.sessionId,p=me(d),u=et(e,i,t,p,a),l=await t?.onPayload?.(u,e);l!==void 0&&(u=l);let f=p||fe(),m={originator:"pi",...re(e,t?.identity)},h=Ot(m,e.headers,t?.headers,c,o,p),S=At(m,e.headers,t?.headers,c,o,f),k=JSON.stringify(u),y=_e(t?.timeoutMs),C=_e(t?.websocketConnectTimeoutMs),T=t?.transport||"auto",b=!1,x=T!=="sse"&&Me(d);if(x&&ke(d),T!=="sse"&&!x){let g=!1,_=!1,A=!1;for(;;){g=!1;try{if(await Rt(rt(e.baseUrl),u,S,s,n,e,()=>{g=!0,b||(b=!0,n.push({type:"start",partial:s}))},y,C,d,c,a,t),t?.signal?.aborted)throw new Error("Request was aborted");Se(s),n.push({type:"done",reason:s.stopReason,message:s}),n.end();return}catch(v){let D=t?.signal?.aborted,N=!g&&ot(v),W=it(v);if(!D&&W&&!A){A=!0;continue}if(!D&&N&&!_){_=!0;continue}if(D||st(v)&&!N||(te(s,ee("provider_transport_failure",v,{configuredTransport:T,...g?{}:{fallbackTransport:"sse"},eventsEmitted:g,phase:g?"after_message_stream_start":"before_message_stream_start",requestBytes:new TextEncoder().encode(k).byteLength})),mt(d,v),g))throw v;ke(d);break}}}let O=Ze(k);O&&h.set("content-encoding","zstd");let Ne=O??k,E,L,z=t?.maxRetries??Ie;for(let g=0;g<=z;g++){if(t?.signal?.aborted)throw new Error("Request was aborted");try{let _=y!==void 0&&y>0?AbortSignal.timeout(y):void 0,A=we([t?.signal,_]);try{E=await(t?.fetch??globalThis.fetch)(Oe(e.baseUrl),{method:"POST",headers:h,body:Ne,signal:A.signal})}catch(W){throw _?.aborted&&!t?.signal?.aborted?new Error(`Codex SSE response headers timed out after ${y}ms`):W}finally{A.cleanup()}if(await t?.onResponse?.({status:E.status,headers:H(E.headers)},e),E.ok)break;let v=await E.text();if(g<z&&je(E.status,v)){let W=Ve(E.headers),qe=W===void 0?ge*2**g:Xe(W,t);await Ee(qe,t?.signal);continue}let D=new Response(v,{status:E.status,statusText:E.statusText}),N=await Ct(D);throw new Error(N.friendlyMessage||N.message)}catch(_){if(_ instanceof Error&&(_.name==="AbortError"||_.message==="Request was aborted"))throw new Error("Request was aborted");if(L=_ instanceof Error?_:new Error(String(_)),g<z&&!(L instanceof F)&&!L.message.includes("usage limit")){let A=ge*2**g;await Ee(A,t?.signal);continue}throw L}}if(!E?.ok)throw L??new Error("Failed after retries");if(!E.body)throw new Error("No response body");if(b||(b=!0,n.push({type:"start",partial:s})),await nt(E,s,n,e,a,t),t?.signal?.aborted)throw new Error("Request was aborted");Se(s),n.push({type:"done",reason:s.stopReason,message:s}),n.end()}catch(o){for(let c of s.content)delete c.partialJson,delete c.customInput;s.stopReason=t?.signal?.aborted?"aborted":"error",s.errorMessage=pe(de(o)),n.push({type:"error",reason:s.stopReason,error:s}),n.end()}})(),n},Gt=(e,r,t)=>{let n=t?.apiKey;if(!n)throw new Error(`No API key for provider: ${e.provider}`);let i={...le(e,r,t,n),toolChoice:t?.toolChoice},s=t?.reasoning?ce(e,t.reasoning):void 0;return Qe(e,r,{...i,reasoningEffort:s==="off"?void 0:s})};function et(e,r,t,n,i=K(J(r.messages),e.compat?.supportsOpenAIGrammarTools??!1)){let s=e.compat?.supportsStrictMode??!0,o=e.compat?.supportsOpenAIGrammarTools??!1,c=e.compat?.supportsAdditionalTools??!1,a=e.compat?.supportsToolSearch??!1,d=ae(r.messages,ye({supportsMidConvoSystemMessages:e.compat?.supportsMidConvoSystemMessages??!1,supportsAdditionalTools:c,supportsToolSearch:a})),p=G(e,r,Re,{includeSystemPrompt:!1,grammarToolInputProperties:i,supportsMidConvoSystemMessages:e.compat?.supportsMidConvoSystemMessages??!1,supportsAdditionalTools:c,supportsToolSearch:a,toolOptions:{strict:null,supportsStrictMode:s,supportsOpenAIGrammarTools:o}}),u=oe(r.messages),l=u?ne(u):"",f={model:e.id,store:!1,stream:!0,instructions:l||"You are a helpful assistant.",input:p,text:{verbosity:t?.textVerbosity||"low"},include:["reasoning.encrypted_content"],prompt_cache_key:n,tool_choice:t?.toolChoice??"auto",parallel_tool_calls:!0};if(t?.temperature!==void 0&&(f.temperature=t.temperature),t?.serviceTier!==void 0&&(f.service_tier=t.serviceTier),d.requestTools.length>0&&(f.tools=be(d.requestTools,{strict:null,supportsStrictMode:s,supportsOpenAIGrammarTools:o})),t?.reasoningEffort!==void 0){let m=t.reasoningEffort==="none"?e.thinkingLevelMap?.off===void 0?"none":e.thinkingLevelMap.off:e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort;m!==null&&(f.reasoning={effort:m,summary:t.reasoningSummary??"auto"})}else e.reasoning&&e.thinkingLevelMap?.off!==null&&(f.reasoning={effort:e.thinkingLevelMap?.off??"none"});return f}function tt(e,r){switch(r){case"flex":return .5;case"priority":return e.id==="gpt-5.5"?2.5:2;default:return 1}}function Ce(e,r,t){let n=tt(t,r);n!==1&&(e.cost.input*=n,e.cost.output*=n,e.cost.cacheRead*=n,e.cost.cacheWrite*=n,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite)}function xe(e,r){return e==="default"&&(r==="flex"||r==="priority")?r:e??r}function Oe(e){let t=(e&&e.trim().length>0?e:Be).replace(/\/+$/,"");return t.endsWith("/codex/responses")?t:t.endsWith("/codex")?`${t}/responses`:`${t}/codex/responses`}function rt(e){let r=new URL(Oe(e));return r.protocol==="https:"&&(r.protocol="wss:"),r.protocol==="http:"&&(r.protocol="ws:"),r.toString()}async function nt(e,r,t,n,i,s){await j(Ae(ut(e,s?.signal),r,n,s?.onProviderStreamEvent),r,t,n,{serviceTier:s?.serviceTier,grammarToolInputProperties:i,resolveServiceTier:xe,applyServiceTierPricing:(o,c)=>Ce(o,c,n)})}var M=class extends Error{code;payload;constructor(r,t){super(r),this.name="CodexApiError",this.code=t?.code,this.payload=t?.payload,this.cause=t?.cause}},B=class extends Error{payload;constructor(r,t){super(r),this.name="CodexProtocolError",this.payload=t?.payload,this.cause=t?.cause}},$=class extends Error{constructor(r){super(q(r)),this.name="ProviderStreamEventCallbackError",this.cause=r}};function st(e){return e instanceof M||e instanceof B||e instanceof $}function ot(e){return e instanceof M&&e.code===Je}function it(e){return e instanceof M&&e.code===He}function at(e){let r=e.error&&typeof e.error=="object"?e.error:void 0;return{code:typeof e.code=="string"?e.code:typeof r?.code=="string"?r.code:void 0,message:typeof e.message=="string"?e.message:typeof r?.message=="string"?r.message:void 0}}async function*Ae(e,r,t,n){for await(let i of e){try{await n?.(i,t)}catch(o){throw new $(o)}let s=typeof i.type=="string"?i.type:void 0;if(s){if(s==="error"){let{code:o,message:c}=at(i);throw new M(`Codex error: ${c||o||JSON.stringify(i)}`,{code:o,payload:i})}if(s==="response.failed"){let o=i.response,c=o?.error?.code,a=o?.error?.message;throw new M(a||"Codex response failed",{code:c,payload:i})}if(s==="response.done"||s==="response.completed"||s==="response.incomplete"){let o=i.response;typeof o?.end_turn=="boolean"&&(r.endTurn=o.end_turn);let c=o&&{...o,status:ct(o.status)};yield{...i,type:"response.completed",response:c};return}yield i}}}function ct(e){if(typeof e=="string")return Ke.has(e)?e:void 0}async function*ut(e,r){if(!e.body)return;let t=e.body.getReader(),n=new TextDecoder,i="",s=()=>{t.cancel().catch(()=>{})};r?.addEventListener("abort",s,{once:!0});try{for(;;){if(r?.aborted)throw new Error("Request was aborted");let{done:o,value:c}=await t.read();if(r?.aborted)throw new Error("Request was aborted");i+=o?n.decode():n.decode(c,{stream:!0}),o&&i.trim()&&(i+=`
5
-
6
- `);let a=i.indexOf(`
7
-
8
- `);for(;a!==-1;){let d=i.slice(0,a);i=i.slice(a+2);let p=d.split(`
9
- `).filter(u=>u.startsWith("data:")).map(u=>u.slice(5).trim());if(p.length>0){let u=p.join(`
10
- `).trim();if(u&&u!=="[DONE]")try{yield JSON.parse(u)}catch(l){throw new B(`Invalid Codex SSE JSON: ${q(l)}`,{cause:l,payload:u})}}a=i.indexOf(`
11
-
12
- `)}if(o)break}}finally{r?.removeEventListener("abort",s);try{await t.cancel()}catch{}try{t.releaseLock()}catch{}}}var ft="responses_websockets=2026-02-06",lt=300*1e3,dt=3300*1e3,w=new Map,P=new Map,U=new Set;function Z(e){let r=P.get(e);return r||(r={requests:0,connectionsCreated:0,connectionsReused:0,cachedContextRequests:0,storeTrueRequests:0,fullContextRequests:0,deltaRequests:0,lastInputItems:0,websocketFailures:0,sseFallbacks:0},P.set(e,r)),r}function jt(e){let r=P.get(e);return r?{...r}:void 0}function Vt(e){if(e){P.delete(e),U.delete(e);return}P.clear(),U.clear()}function pt(e){let r=t=>{t.idleTimer&&clearTimeout(t.idleTimer),R(t.socket,1e3,"debug_close")};if(e){for(let t of w.get(e)?.values()??[])r(t);w.delete(e);return}for(let t of w.values())for(let n of t.values())r(n);w.clear()}ue(pt);function Me(e){return e?U.has(e):!1}function ke(e){if(!e)return;let r=Z(e);r.sseFallbacks++,r.websocketFallbackActive=Me(e)}function mt(e,r){if(!e)return;U.add(e);let t=Z(e);t.websocketFailures++,t.lastWebSocketError=q(r),t.websocketFallbackActive=!0}var V=null;async function yt(e){if(!e&&V)return V;if(typeof process<"u"&&process.versions?.bun){let t=class extends WebSocket{constructor(n,i){let s={};Array.isArray(i)||typeof i=="string"?s={protocols:i}:s={...i};let o=he(n.toString().replace(/^wss:/,"https:").replace(/^ws:/,"http:"),e);super(n,{...s,...o?{proxy:o.toString()}:{}})}};return e||(V=t),t}let r=globalThis.WebSocket;return typeof r!="function"?null:r}var Y=class extends Error{code;reason;wasClean;constructor(r,t){super(r),this.name="WebSocketCloseError",this.code=t?.code,this.reason=t?.reason,this.wasClean=t?.wasClean}};function bt(e){let r=e.readyState;return typeof r=="number"?r:void 0}function I(e){let r=bt(e);return r===void 0||r===1}function ht(e){return Date.now()-e.createdAt>=dt}function R(e,r=1e3,t="done"){try{e.close(r,t)}catch{}}function Te(e,r,t){t.idleTimer&&clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{if(t.busy)return;R(t.socket,1e3,"idle_timeout");let n=w.get(e);n?.get(r)===t&&n.delete(r),n?.size===0&&w.delete(e)},lt)}async function X(e,r,t,n=$e,i){let s=await yt(i);if(!s)throw new Error("WebSocket transport is not available in this runtime");let o=H(r);return delete o["OpenAI-Beta"],new Promise((c,a)=>{let d=!1,p,u;try{u=new s(e,{headers:o})}catch(y){a(y instanceof Error?y:new Error(String(y)));return}let l=()=>{p&&(clearTimeout(p),p=void 0),u.removeEventListener("open",m),u.removeEventListener("error",h),u.removeEventListener("close",S),t?.removeEventListener("abort",k)},f=(y,C)=>{d||(d=!0,l(),C&&R(u,1e3,C),a(y))},m=()=>{d||(d=!0,l(),c(u))},h=y=>{f(We(y))},S=y=>{f(Le(y))},k=()=>{f(new Error("Request was aborted"),"aborted")};u.addEventListener("open",m),u.addEventListener("error",h),u.addEventListener("close",S),t?.addEventListener("abort",k),n>0&&(p=setTimeout(()=>{f(new Error(`WebSocket connect timeout after ${n}ms`),"connect_timeout")},n)),t?.aborted&&k()})}async function wt(e,r,t,n,i,s,o){if(!t){let u=await X(e,r,i,s,o);return{socket:u,reused:!1,release:()=>R(u)}}let c=w.get(t),a=c?.get(n);if(a){if(a.idleTimer&&(clearTimeout(a.idleTimer),a.idleTimer=void 0),!a.busy&&ht(a))R(a.socket,1e3,"connection_age_limit"),c?.delete(n),c?.size===0&&w.delete(t);else if(!a.busy&&I(a.socket))return a.busy=!0,{socket:a.socket,entry:a,reused:!0,release:({keep:u}={})=>{if(!u||!I(a.socket)){R(a.socket);let l=w.get(t);l?.get(n)===a&&l.delete(n),l?.size===0&&w.delete(t);return}a.busy=!1,Te(t,n,a)}};if(a.busy){let u=await X(e,r,i,s,o);return{socket:u,reused:!1,release:()=>{R(u)}}}I(a.socket)||(R(a.socket),c?.delete(n),c?.size===0&&w.delete(t))}let d=await X(e,r,i,s,o),p={socket:d,busy:!0,createdAt:Date.now()};return c=w.get(t),c||(c=new Map,w.set(t,c)),c.set(n,p),{socket:d,entry:p,reused:!1,release:({keep:u}={})=>{if(!u||!I(p.socket)){R(p.socket),p.idleTimer&&clearTimeout(p.idleTimer);let l=w.get(t);l?.get(n)===p&&l.delete(n),l?.size===0&&w.delete(t);return}p.busy=!1,Te(t,n,p)}}}function We(e){if(e&&typeof e=="object"){let r="message"in e?e.message:void 0;if(typeof r=="string"&&r.length>0)return new Error(r);let t="error"in e?e.error:void 0;if(t instanceof Error&&t.message.length>0)return t;if(t&&typeof t=="object"&&"message"in t){let n=t.message;if(typeof n=="string"&&n.length>0)return new Error(n)}}return new Error("WebSocket error")}function Le(e){if(e&&typeof e=="object"){let r="code"in e?e.code:void 0,t="reason"in e?e.reason:void 0,n="wasClean"in e?e.wasClean:void 0,i=typeof r=="number"?` ${r}`:"",s=typeof t=="string"&&t.length>0?` ${t}`:"";return!s&&r===ze&&(s=" message too big"),new Y(`WebSocket closed${i}${s}`.trim(),{code:typeof r=="number"?r:void 0,reason:typeof t=="string"&&t.length>0?t:void 0,wasClean:typeof n=="boolean"?n:void 0})}return new Error("WebSocket closed")}async function gt(e){if(typeof e=="string")return e;if(e instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(e));if(ArrayBuffer.isView(e)){let r=e;return new TextDecoder().decode(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}if(e&&typeof e=="object"&&"arrayBuffer"in e){let t=await e.arrayBuffer();return new TextDecoder().decode(new Uint8Array(t))}return null}async function*St(e,r,t){let n=[],i=null,s=!1,o=null,c=!1,a=()=>{if(!i)return;let f=i;i=null,f()},d=f=>{(async()=>{let m=null;try{if(!f||typeof f!="object"||!("data"in f)||(m=await gt(f.data),!m))return;let h=JSON.parse(m),S=typeof h.type=="string"?h.type:"";(S==="response.completed"||S==="response.done"||S==="response.incomplete")&&(c=!0,s=!0),n.push(h),a()}catch(h){o=new B(`Invalid Codex WebSocket JSON: ${q(h)}`,{cause:h,payload:m}),s=!0,a()}})()},p=f=>{o=We(f),s=!0,a()},u=f=>{if(c){s=!0,a();return}o||(o=Le(f)),s=!0,a()},l=()=>{o=new Error("Request was aborted"),s=!0,a()};e.addEventListener("message",d),e.addEventListener("error",p),e.addEventListener("close",u),r?.addEventListener("abort",l);try{for(;;){if(r?.aborted)throw new Error("Request was aborted");if(n.length>0){yield n.shift();continue}if(s)break;let f;await new Promise((m,h)=>{i=m,t!==void 0&&t>0&&(f=setTimeout(()=>{let S=new Error(`WebSocket idle timeout after ${t}ms`);o=S,s=!0,i=null,R(e,1e3,"idle_timeout"),h(S)},t))}).finally(()=>{f&&clearTimeout(f)})}if(o)throw o;if(!c)throw new Error("WebSocket stream closed before response.completed")}finally{e.removeEventListener("message",d),e.removeEventListener("error",p),e.removeEventListener("close",u),r?.removeEventListener("abort",l)}}function ve(e){let{input:r,previous_response_id:t,...n}=e;return n}function Et(e,r){return JSON.stringify(e??[])===JSON.stringify(r??[])}function _t(e,r){return JSON.stringify(ve(e))===JSON.stringify(ve(r))}function kt(e,r){if(!_t(e,r.lastRequestBody))return;let t=e.input??[],n=[...r.lastRequestBody.input??[],...r.lastResponseItems];if(t.length<n.length)return;let i=t.slice(0,n.length);if(Et(i,n))return t.slice(n.length)}function Tt(e,r){let t=e.continuation;if(!t)return r;let n=kt(r,t);return!n||!t.lastResponseId?(e.continuation=void 0,r):{...r,previous_response_id:t.lastResponseId,input:n}}async function*vt(e,r){let t=!1;for await(let n of e)t||(t=!0,r()),yield n}async function Rt(e,r,t,n,i,s,o,c,a,d,p,u,l){let{socket:f,entry:m,reused:h,release:S}=await wt(e,t,d,p,l?.signal,a,l?.env),k=!0,y=l?.transport==="websocket-cached"||l?.transport==="auto",C=r,T=y&&m?Tt(m,C):C,b=d?Z(d):void 0;b&&(b.requests++,h?b.connectionsReused++:b.connectionsCreated++,y&&b.cachedContextRequests++,T.store===!0&&b.storeTrueRequests++,b.lastInputItems=T.input?.length??0,T.previous_response_id?(b.deltaRequests++,b.lastDeltaInputItems=T.input?.length??0,b.lastPreviousResponseId=T.previous_response_id):(b.fullContextRequests++,b.lastDeltaInputItems=void 0,b.lastPreviousResponseId=void 0));try{if(f.send(JSON.stringify({type:"response.create",...T})),await j(vt(Ae(St(f,l?.signal,c),n,s,l?.onProviderStreamEvent),o),n,i,s,{serviceTier:l?.serviceTier,grammarToolInputProperties:u,resolveServiceTier:xe,applyServiceTierPricing:(x,O)=>Ce(x,O,s)}),l?.signal?.aborted)k=!1;else if(y&&m&&n.responseId){let x=G(s,se({messages:[n]}),Re,{includeSystemPrompt:!1,grammarToolInputProperties:u}).filter(O=>O.type!=="function_call_output"&&O.type!=="custom_tool_call_output");m.continuation={lastRequestBody:C,lastResponseId:n.responseId,lastResponseItems:x}}}catch(x){throw m&&(m.continuation=void 0),k=!1,x}finally{S({keep:k})}}async function Ct(e){let r=await e.text(),t=r||e.statusText||"Request failed",n;try{let s=JSON.parse(r)?.error;if(s){let o=s.code||s.type||"";if(/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(o)||e.status===429){let c=s.plan_type?` (${s.plan_type.toLowerCase()} plan)`:"",a=s.resets_at?Math.max(0,Math.round((s.resets_at*1e3-Date.now())/6e4)):void 0,d=a!==void 0?` Try again in ~${a} min.`:"";n=`You have hit your ChatGPT usage limit${c}.${d}`.trim()}t=s.message||n||t}}catch{}return{message:t,friendlyMessage:n}}function xt(e){try{let r=e.split(".");if(r.length!==3)throw new Error("Invalid token");let n=JSON.parse(atob(r[1]))?.[Pe]?.chatgpt_account_id;if(!n)throw new Error("No account ID in token");return n}catch{throw new Error("Failed to extract accountId from token")}}function De(e,r,t,n,i){let s=new Headers(e);for(let[o,c]of Object.entries(r||{}))s.set(o,c);for(let[o,c]of Object.entries(t||{}))c===null?s.delete(o):s.set(o,c);return s.set("Authorization",`Bearer ${i}`),s.set("chatgpt-account-id",n),s}function Ot(e,r,t,n,i,s){let o=De(e,r,t,n,i);return o.set("OpenAI-Beta","responses=experimental"),o.set("accept","text/event-stream"),o.set("content-type","application/json"),s&&(o.set("session-id",s),o.set("x-client-request-id",s)),o}function At(e,r,t,n,i,s){let o=De(e,r,t,n,i);return o.delete("accept"),o.delete("content-type"),o.delete("OpenAI-Beta"),o.delete("openai-beta"),o.set("OpenAI-Beta",ft),o.set("x-client-request-id",s),o.set("session-id",s),o}export{pt as closeOpenAICodexWebSocketSessions,jt as getOpenAICodexWebSocketDebugStats,Vt as resetOpenAICodexWebSocketDebugStats,Qe as stream,Gt as streamSimple};
@@ -1,9 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as ue,b as fe}from"./chunk-BGYR4ID3.js";import{a as ke}from"./chunk-XIECJESP.js";import{a as Te}from"./chunk-V3AQJSWR.js";import{a as he}from"./chunk-CVC66CFV.js";import{a as ne}from"./chunk-23PRJECN.js";import{a as me,b as ye}from"./chunk-FF7UELTU.js";import{a as se,b as re,c as oe,d as ie,e as ae,f as N,h as le,i as ce,k as pe,l as ge,o as de}from"./chunk-QBKCAIJG.js";import{C as j,F as G,J as Z,L as Q,o as U,p as V,y as z}from"./chunk-PZMGBKUR.js";import{a as ee}from"./chunk-6R73ICDB.js";import{c as X,d as Y}from"./chunk-SKHLZ6XY.js";import"./chunk-D6VMBA4C.js";import{a as b}from"./chunk-USBJFDJ6.js";import{a as te}from"./chunk-K4NTZEDJ.js";import{h as J}from"./chunk-6AKUD3CF.js";import"./chunk-OSEIQ7SS.js";import{b as W}from"./chunk-CXT5IR5T.js";import"./chunk-WHC7AYZD.js";function Re(e,n){if(!e)return!1;let t=n.toLowerCase();for(let[s,u]of Object.entries(e))if(s.toLowerCase()===t&&u!==null&&u.trim().length>0)return!0;return!1}function Ce(e,n,t){if(n)return n;if(Re(t,"authorization")||Re(t,"cf-aig-authorization"))return"unused";throw new Error(`No API key for provider: ${e}`)}function be(e){for(let n of e)if(n.role==="toolResult"||n.role==="assistant"&&n.content.some(t=>t.type==="toolCall"))return!0;return!1}function xe(e){return e.type==="text"}function Be(e){return e.type==="thinking"}function Pe(e){return e.type==="toolCall"}function Le(e){return e.type==="image"}function qe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function De(e){return(e.id===void 0||e.id===null||typeof e.id=="string")&&(e.format===void 0||typeof e.format=="string")&&(e.index===void 0||typeof e.index=="number")}function $(e){if(!qe(e)||!De(e))return!1;switch(e.type){case"reasoning.summary":return typeof e.summary=="string";case"reasoning.encrypted":return typeof e.data=="string";case"reasoning.text":return typeof e.text=="string"&&(e.signature===void 0||e.signature===null||typeof e.signature=="string");default:return!1}}function ze(e){if(e)try{let n=JSON.parse(e);return Array.isArray(n)&&n.length>0&&n.every($)?n:void 0}catch{return}}function je(e){if(e)try{let n=JSON.parse(e);return $(n)&&n.type==="reasoning.encrypted"&&typeof n.id=="string"&&n.id.length>0&&n.data.length>0?n:void 0}catch{return}}function _e(e,n){e.id??=n.id,e.format||=n.format,e.index??=n.index}function Ge(e,n){let t=e[e.length-1];if(n.type==="reasoning.text"&&t?.type==="reasoning.text"){t.text+=n.text,t.signature||=n.signature,_e(t,n);return}if(n.type==="reasoning.summary"&&t?.type==="reasoning.summary"){t.summary+=n.summary,_e(t,n);return}e.push({...n})}var Ne=["reasoning","reasoning_content","reasoning_text"];function $e(e){return Ne.includes(e)}function Me(e,n){return e||(ee("PI_CACHE_RETENTION",n)==="long"?"long":"short")}var He=(e,n,t)=>{let s=new W,u=z(n,q(e).supportsMidConvoSystemMessages);return(async()=>{let r={role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()},h,k=T=>{h!==void 0&&(T.thinkingSignature=JSON.stringify(h))};try{let T=Ce(e.provider,t?.apiKey,t?.headers),a=q(e),m=N(j(u.messages),a.supportsOpenAIGrammarTools),M=Me(t?.cacheRetention,t?.env),g=M==="none"?void 0:t?.sessionId,i=Ke(e,u,T,t?.headers,t?.identity,t?.fetch,g,a),f=We(e,u,t,a,M,m),p=await t?.onPayload?.(f,e);p!==void 0&&(f=p);let R={...t?.signal?{signal:t.signal}:{},...t?.timeoutMs!==void 0?{timeout:t.timeoutMs}:{},maxRetries:0},{data:A,response:I}=await ne(()=>i.chat.completions.create(f,R).withResponse(),{maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,signal:t?.signal});await t?.onResponse?.({status:I.status,headers:te(I.headers)},e),s.push({type:"start",partial:r});let O=null,E=null,S=!1,v=new Map,w=new Map,B=r.content,l=o=>B.indexOf(o),F=o=>{let c=o.customInput?.property;if(c===void 0)return"";let x=o.arguments[c];return typeof x=="string"?x:""},H=(o,c,x)=>{let d=o.customInput;if(!d)return;let C=oe(d.jsonBuffer,d.property,c,x);return o.arguments={[d.property]:c},C},Se=o=>{let c=l(o);if(c!==-1){if(o.type==="text")s.push({type:"text_end",contentIndex:c,content:o.text,partial:r});else if(o.type==="thinking")k(o),s.push({type:"thinking_end",contentIndex:c,content:o.thinking,partial:r});else if(o.type==="toolCall"){if(o.customInput){let x=H(o,F(o),!0);x!==void 0&&s.push({type:"toolcall_delta",contentIndex:c,delta:x,partial:r})}else Object.assign(o,X(o.partialArgs));delete o.partialArgs,delete o.customInput,delete o.streamIndex,s.push({type:"toolcall_end",contentIndex:c,toolCall:o,partial:r})}}},we=()=>(O||(O={type:"text",text:""},B.push(O),s.push({type:"text_start",contentIndex:l(O),partial:r})),O),K=o=>(E||(E={type:"thinking",thinking:"",thinkingSignature:o},B.push(E),s.push({type:"thinking_start",contentIndex:l(E),partial:r})),E),Fe=o=>{let c=typeof o.index=="number"?o.index:void 0,x=o.function?.name??o.custom?.name??"",d=c!==void 0?v.get(c):void 0;if(!d&&o.id&&(d=w.get(o.id)),!d){let C=o.custom&&!o.function?m.get(x)??"input":void 0,P=C!==void 0;d={type:"toolCall",id:o.id||"",name:x,arguments:P?{[C]:""}:{},partialArgs:P?void 0:"",customInput:P?{property:C,jsonBuffer:{input:"",started:!1,closed:!1}}:void 0,streamIndex:c},c!==void 0&&v.set(c,d),o.id&&w.set(o.id,d),B.push(d),s.push({type:"toolcall_start",contentIndex:l(d),partial:r})}if(c!==void 0&&d.streamIndex===void 0&&(d.streamIndex=c,v.set(c,d)),o.id&&w.set(o.id,d),!d.name&&x&&(d.name=x),o.custom&&!o.function&&!d.customInput){let C=m.get(d.name)??"input";d.arguments={[C]:""},d.customInput={property:C,jsonBuffer:{input:"",started:!1,closed:!1}},delete d.partialArgs}return d};for await(let o of A){if(await t?.onProviderStreamEvent?.(o,e),!o||typeof o!="object")continue;r.responseId||=o.id,typeof o.model=="string"&&o.model.length>0&&o.model!==e.id&&(r.responseModel||=o.model),o.usage&&(r.usage=Ae(o.usage,e));let c=Array.isArray(o.choices)?o.choices[0]:void 0;if(c){if(!o.usage&&c.usage&&(r.usage=Ae(c.usage,e)),c.finish_reason){r.rawStopReason=c.finish_reason;let x=rt(c.finish_reason);r.stopReason=x.stopReason,x.errorMessage&&(r.errorMessage=x.errorMessage),S=!0}if(c.delta){let x=["reasoning_content","reasoning","reasoning_text"],d=c.delta,C=null;for(let y of x){let _=d[y];if(typeof _=="string"&&_.length>0){C=y;break}}if(C){let y=d[C];if(typeof y=="string"&&y.length>0){let _=e.provider==="opencode-go"&&C==="reasoning"?"reasoning_content":C,L=K(_);L.thinking+=y,s.push({type:"thinking_delta",contentIndex:l(L),delta:y,partial:r})}}let P=c.delta.reasoning_details;if(Array.isArray(P))for(let y of P)$(y)&&(K(""),h??=[],Ge(h,y));if(c.delta.content!==null&&c.delta.content!==void 0&&c.delta.content.length>0){let y=we();y.text+=c.delta.content,s.push({type:"text_delta",contentIndex:l(y),delta:c.delta.content,partial:r})}if(c?.delta?.tool_calls)for(let y of c.delta.tool_calls){let _=Fe(y);!_.id&&y.id&&(_.id=y.id,w.set(y.id,_));let L=y.function?.name??y.custom?.name;!_.name&&L&&(_.name=L);let D="";if(y.function?.arguments)D=y.function.arguments,_.partialArgs=(_.partialArgs??"")+y.function.arguments,_.arguments=Y(_.partialArgs);else if(y.custom?.input){let Oe=F(_)+y.custom.input;D=H(_,Oe,!1)??""}s.push({type:"toolcall_delta",contentIndex:l(_),delta:D,partial:r})}}}}for(let o of B)Se(o);if(t?.signal?.aborted)throw new Error("Request was aborted");if(r.stopReason==="aborted")throw new Error("Request was aborted");if(!S&&!a.supportsFinishReason&&(r.stopReason=r.content.some(o=>o.type==="toolCall")?"toolUse":"stop"),r.stopReason==="error")throw new Error(r.errorMessage||"Provider returned an error stop reason");if(a.supportsFinishReason&&!S||r.stopReason==="pending")throw new Error("Stream ended without finish_reason");s.push({type:"done",reason:r.stopReason,message:r}),s.end()}catch(T){for(let m of r.content)m.type==="thinking"&&k(m),delete m.index,delete m.partialArgs,delete m.customInput,delete m.streamIndex;r.stopReason=t?.signal?.aborted?"aborted":"error",r.errorMessage=ye(me(T));let a=T?.error?.metadata?.raw;a&&!r.errorMessage.includes(String(a))&&(r.errorMessage+=`
5
- ${a}`),s.push({type:"error",reason:r.stopReason,error:r}),s.end()}})(),s},At=(e,n,t)=>{Ce(e.provider,t?.apiKey,t?.headers);let s={...ce(e,n,t,t?.apiKey),toolChoice:t?.toolChoice},u=t?.reasoning?Q(e,t.reasoning):void 0;return He(e,n,{...s,reasoningEffort:u==="off"?void 0:u,thinkingBudgets:t?.thinkingBudgets})};function Ke(e,n,t,s,u,r,h,k=q(e)){let T={...J(e,u),...e.headers};if(e.provider==="github-copilot"){let a=ue(n.messages),m=fe({messages:n.messages,hasImages:a});Object.assign(T,m)}return h&&k.sendSessionAffinityHeaders&&(k.sessionAffinityFormat==="openrouter"?T["x-session-id"]=h:(k.sessionAffinityFormat==="openai"&&(T.session_id=h),T["x-client-request-id"]=h,T["x-session-affinity"]=h)),s&&Object.assign(T,s),new he({apiKey:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:r,defaultHeaders:T})}function We(e,n,t,s=q(e),u=Me(t?.cacheRetention,t?.env),r=N(j(n.messages),s.supportsOpenAIGrammarTools)){let h=G(n.messages,s.supportsMidConvoSystemMessages===!0&&s.supportsMidConvoToolAdditions===!0?"additions":"none"),k=st(e,n,s,{grammarToolInputProperties:r}),T=Ze(s,u),a={model:e.id,messages:k,stream:!0,prompt_cache_key:e.baseUrl.includes("api.openai.com")&&u!=="none"||u==="long"&&s.supportsLongCacheRetention?ke(t?.sessionId):void 0,prompt_cache_retention:u==="long"&&s.supportsLongCacheRetention?"24h":void 0};s.supportsUsageInStreaming!==!1&&(a.stream_options={include_usage:!0}),s.supportsStore&&(a.store=!1),t?.maxTokens&&(s.maxTokensField==="max_tokens"?a.max_tokens=t.maxTokens:a.max_completion_tokens=t.maxTokens),t?.temperature!==void 0&&(a.temperature=t.temperature),h.requestTools.length>0?(a.tools=Ee(h.requestTools,s),s.zaiToolStream&&(a.tool_stream=!0)):be(n.messages)&&(a.tools=[]),T&&Qe(k,a.tools,T),t?.toolChoice&&(a.tool_choice=t.toolChoice),s.vllmPriority!==void 0&&(a.priority=s.vllmPriority);let m=Je(s),M=Ue(e,t,a);if(s.thinkingFormat==="zai"&&e.reasoning){let i=a;if(i.thinking=t?.reasoningEffort?{type:"enabled",clear_thinking:!1}:{type:"disabled"},t?.reasoningEffort&&s.supportsReasoningEffort){let f=e.thinkingLevelMap?.[t.reasoningEffort],p=f===void 0?t.reasoningEffort:f;typeof p=="string"&&(i.reasoning_effort=p)}}else if(s.thinkingFormat==="qwen"&&e.reasoning){if(a.enable_thinking=!!t?.reasoningEffort,t?.reasoningEffort&&s.supportsReasoningEffort){let i=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort;typeof i=="string"&&(a.reasoning_effort=i)}}else if(s.thinkingFormat==="qwen-chat-template"&&e.reasoning)a.chat_template_kwargs={enable_thinking:!!t?.reasoningEffort,preserve_thinking:!0};else if(s.thinkingFormat==="chat-template"&&e.reasoning){let i=ve(e,t,s.chatTemplateKwargs,M);i&&(a.chat_template_kwargs=i)}else if(s.thinkingFormat==="baseten"&&e.reasoning){let i=a,f=ve(e,t,s.chatTemplateArgs,M);if(f&&(i.chat_template_args=f),s.supportsReasoningEffort){let p=t?.reasoningEffort,R=p?e.thinkingLevelMap?.[p]:e.thinkingLevelMap?.off,A=R===void 0?p:R;typeof A=="string"&&(i.reasoning_effort=A)}}else if(s.thinkingFormat==="deepseek"&&e.reasoning)t?.reasoningEffort?a.thinking={type:"enabled"}:e.thinkingLevelMap?.off!==null&&(a.thinking={type:"disabled"}),t?.reasoningEffort&&s.supportsReasoningEffort&&(a.reasoning_effort=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort);else if(s.thinkingFormat==="openrouter"&&e.reasoning){let i=a;t?.reasoningEffort?i.reasoning={effort:e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort}:e.thinkingLevelMap?.off!==null&&(i.reasoning={effort:e.thinkingLevelMap?.off??"none"})}else if(s.thinkingFormat==="ant-ling"&&e.reasoning&&t?.reasoningEffort){let i=e.thinkingLevelMap?.[t.reasoningEffort];typeof i=="string"&&(a.reasoning={effort:i})}else if(s.thinkingFormat==="together"&&e.reasoning){let i=a;i.reasoning={enabled:!!t?.reasoningEffort},t?.reasoningEffort&&s.supportsReasoningEffort&&(i.reasoning_effort=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort)}else if(s.thinkingFormat==="string-thinking"&&e.reasoning){let i=a;t?.reasoningEffort?i.thinking=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort:e.thinkingLevelMap?.off!==null&&(i.thinking=e.thinkingLevelMap?.off??"none")}else if(t?.reasoningEffort&&e.reasoning&&s.supportsReasoningEffort)a.reasoning_effort=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort;else if(!t?.reasoningEffort&&e.reasoning&&s.supportsReasoningEffort){let i=e.thinkingLevelMap?.off;typeof i=="string"&&(a.reasoning_effort=i)}if(m&&M!==void 0&&Object.assign(a,{[m]:M}),e.compat?.openRouterRouting&&(a.provider=e.compat.openRouterRouting),e.compat?.vercelGatewayRouting){let i=e.compat.vercelGatewayRouting;if(i.only||i.order){let f={};i.only&&(f.only=i.only),i.order&&(f.order=i.order),a.providerOptions={gateway:f}}}let g=le(e,t?.reasoningEffort??"off",t?.samplingParams);return g&&Object.assign(a,g),a}function Je(e){if(e.thinkingTokenBudgetField)return e.thinkingTokenBudgetField;if(e.supportsThinkingTokenBudget)return"thinking_token_budget"}function Ue(e,n,t){if(!n?.reasoningEffort||!e.reasoning)return;let s=t.max_tokens??t.max_completion_tokens??e.maxTokens,u=ge(pe(n.reasoningEffort,n.thinkingBudgets),s);return u>0?u:void 0}function ve(e,n,t,s){let u={};for(let[r,h]of Object.entries(t)){let k=Ve(e,n,h,s);k!==void 0&&(u[r]=k)}return Object.keys(u).length>0?u:void 0}function Ve(e,n,t,s){if(typeof t!="object"||t===null)return t;let u=n?.reasoningEffort;if(!u&&t.omitWhenOff)return;if(t.$var==="thinking.enabled")return!!u;if(t.$var==="thinking.budget")return s;let r=u?e.thinkingLevelMap?.[u]:e.thinkingLevelMap?.off;return r===void 0?u:typeof r=="string"?r:void 0}function Ze(e,n){if(e.cacheControlFormat!=="anthropic"||n==="none")return;let t=n==="long"&&e.supportsLongCacheRetention?"1h":void 0;return{type:"ephemeral",...t?{ttl:t}:{}}}function Qe(e,n,t){Xe(e,t),et(n,t),Ye(e,t)}function Xe(e,n){for(let t of e)if(t.role==="system"||t.role==="developer"){tt(t,n);return}}function Ye(e,n){for(let t=e.length-1;t>=0;t--){let s=e[t];if((s.role==="user"||s.role==="assistant"||s.role==="tool")&&nt(s,n))return}}function et(e,n){if(!e||e.length===0)return;let t=e[e.length-1];t.cache_control=n}function tt(e,n){return Ie(e,n)}function nt(e,n){return e.role==="user"||e.role==="assistant"||e.role==="tool"?Ie(e,n):!1}function Ie(e,n){let t=e.content;if(typeof t=="string")return t.length===0?!1:(e.content=[{type:"text",text:t,cache_control:n}],!0);if(!Array.isArray(t))return!1;for(let s=t.length-1;s>=0;s--){let u=t[s];if(u?.type==="text"){let r=u;return r.cache_control=n,!0}}return!1}function st(e,n,t,s){let u=z(n,t.supportsMidConvoSystemMessages),r=[],h=g=>{if(g.includes("|")){let i=g.indexOf("|"),f=g.slice(0,i).replace(/[^a-zA-Z0-9_-]/g,"_"),p=g.slice(i+1).replace(/[^a-zA-Z0-9_-]/g,"_"),R=p.length>0?`${f}_${p}`:f;if(R.length<=40)return R;let A=Te(g).slice(0,8);return`${f.slice(0,Math.max(1,40-A.length-1))}_${A}`}return e.provider==="openai"&&g.length>40?g.slice(0,40):g},k=de(u.messages,e,g=>h(g)),T=G(u.messages,t.supportsMidConvoSystemMessages===!0&&t.supportsMidConvoToolAdditions===!0?"additions":"none"),a=e.reasoning&&t.supportsDeveloperRole?"developer":"system",m=null,M=0;for(let g=0;g<k.length;g++){let i=k[g];if(t.requiresAssistantAfterToolResult&&m==="toolResult"&&i.role==="user"&&r.push({role:"assistant",content:"I have processed the tool results."}),i.role==="system"){let f=M++>=T.foldedSystemMessages?i.toolsAdded??[]:[];if(f.length>0){let R={role:"system",tools:Ee(f,t)};r.push(R)}let p=g===0?U(i):V(i);p.length>0&&r.push({role:a,content:b(p)})}else if(i.role==="user")if(typeof i.content=="string")r.push({role:"user",content:b(i.content)});else{let f=i.content.filter(p=>p.type!=="text"||p.text.length>0).map(p=>p.type==="text"?{type:"text",text:b(p.text)}:{type:"image_url",image_url:{url:`data:${p.mimeType};base64,${p.data}`}});if(f.length===0)continue;r.push({role:"user",content:f})}else if(i.role==="assistant"){let f={role:"assistant",content:t.requiresAssistantAfterToolResult?"":null},p=i.content.filter(xe).filter(l=>l.text.trim().length>0).map(l=>({type:"text",text:b(l.text)})),R=p.map(l=>l.text).join(""),A=i.content.filter(Be),I=i.content.filter(Pe),O=A.map(l=>ze(l.thinkingSignature)).find(l=>l!==void 0),E=I.map(l=>je(l.thoughtSignature)).filter(l=>l!==void 0),S=O??(E.length>0?E:void 0),v=A.filter(l=>l.thinking.trim().length>0);if(v.length>0){if(t.requiresThinkingAsText){let l=v.map(F=>b(F.thinking)).join(`
6
-
7
- `);f.content=[{type:"text",text:l},...p]}else if(R.length>0&&(f.content=R),!S){let l=v[0].thinkingSignature;e.provider==="opencode-go"&&l==="reasoning"&&(l="reasoning_content"),l&&$e(l)&&(f[l]=v.map(F=>F.thinking).join(`
8
- `))}}else R.length>0&&(f.content=R);I.length>0&&(f.tool_calls=I.map(l=>{let F=s?.grammarToolInputProperties?.get(l.name);return F!==void 0?{id:l.id,type:"custom",custom:{name:l.name,input:b(re(l.name,l.arguments,F))}}:{id:l.id,type:"function",function:{name:l.name,arguments:JSON.stringify(l.arguments)}}})),S&&(f.reasoning_details=S),t.requiresReasoningContentOnAssistantMessages&&e.reasoning&&f.reasoning_content===void 0&&(f.reasoning_content="");let w=f.content;if(!(w!=null&&w.length>0)&&!f.tool_calls)continue;r.push(f)}else if(i.role==="toolResult"){let f=[],p=g;for(;p<k.length&&k[p].role==="toolResult";p++){let R=k[p],A=R.content.filter(xe).map(v=>v.text).join(`
9
- `),I=R.content.some(v=>v.type==="image"),E=A.trim().length>0?A:I?"(see attached image)":"(no tool output)",S={role:"tool",content:b(E),tool_call_id:R.toolCallId};if(t.requiresToolResultName&&R.toolName&&(S.name=R.toolName),r.push(S),I&&e.input.includes("image"))for(let v of R.content)Le(v)&&f.push({type:"image_url",image_url:{url:`data:${v.mimeType};base64,${v.data}`}})}g=p-1,f.length>0?(t.requiresAssistantAfterToolResult&&r.push({role:"assistant",content:"I have processed the tool results."}),r.push({role:"user",content:[{type:"text",text:"Attached image(s) from tool result:"},...f]}),m="user"):m="toolResult";continue}m=i.role}return r}function Ee(e,n){return e.map(t=>{let s=ae(t,n.supportsOpenAIGrammarTools);if(s)return{type:"custom",custom:{name:t.name,description:t.description,format:{type:"grammar",grammar:{syntax:s.format,definition:s.definition}}}};let u=ie(t,n.supportsStrictMode!==!1);return{type:"function",function:{name:t.name,description:t.description,parameters:se(t,u),...n.supportsStrictMode!==!1&&{strict:u??!1}}}})}function Ae(e,n){let t=e.prompt_tokens||0,s=e.prompt_tokens_details?.cached_tokens??e.prompt_cache_hit_tokens??e.cached_tokens??0,u=e.prompt_tokens_details?.cache_write_tokens||0,r=Math.max(0,t-s-u),h=e.completion_tokens||0,k={input:r,output:h,cacheRead:s,cacheWrite:u,reasoning:e.completion_tokens_details?.reasoning_tokens||0,totalTokens:r+h+s+u,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return Z(n,k),k}function rt(e){if(e===null)return{stopReason:"stop"};switch(e){case"stop":case"end":return{stopReason:"stop"};case"length":return{stopReason:"length"};case"function_call":case"tool_calls":return{stopReason:"toolUse"};case"content_filter":return{stopReason:"error",errorMessage:"Provider finish_reason: content_filter"};case"network_error":return{stopReason:"error",errorMessage:"Provider finish_reason: network_error"};default:return{stopReason:"error",errorMessage:`Provider finish_reason: ${e}`}}}function ot(e){let n=e.provider,t=e.baseUrl,s=n==="zai"||n==="zai-coding-cn"||t.includes("api.z.ai")||t.includes("open.bigmodel.cn"),u=n==="together"||t.includes("api.together.ai")||t.includes("api.together.xyz"),r=n==="moonshotai"||n==="moonshotai-cn"||t.includes("api.moonshot."),h=n==="openrouter"||t.includes("openrouter.ai"),k=n==="cloudflare-workers-ai"||t.includes("api.cloudflare.com"),T=n==="cloudflare-ai-gateway"||t.includes("gateway.ai.cloudflare.com"),a=n==="nvidia"||t.includes("integrate.api.nvidia.com"),m=n==="ant-ling"||t.includes("api.ant-ling.com"),M=n==="cerebras"||t.includes("cerebras.ai"),g=n==="deepseek"||t.toLowerCase().includes("deepseek.com"),i=a||M||n==="xai"||t.includes("api.x.ai")||u||t.includes("chutes.ai")||g||s||r||n==="opencode"||t.includes("opencode.ai")||k||T||m,f=t.includes("chutes.ai")||g||r||T||u||a||m||s,p=n==="xai"||t.includes("api.x.ai"),R=h&&(e.id.startsWith("anthropic/")||e.id.startsWith("openai/")),A=n==="openrouter"&&e.id.startsWith("anthropic/")?"anthropic":void 0;return{supportsStore:!i,supportsDeveloperRole:R||!i&&!h,supportsReasoningEffort:!p&&!s&&!r&&!u&&!T&&!a&&!m,supportsUsageInStreaming:!0,supportsFinishReason:!0,maxTokensField:f?"max_tokens":"max_completion_tokens",requiresToolResultName:!1,requiresAssistantAfterToolResult:!1,requiresThinkingAsText:!1,requiresReasoningContentOnAssistantMessages:g,thinkingFormat:g?"deepseek":s?"zai":u?"together":m?"ant-ling":h?"openrouter":"openai",openRouterRouting:{},vercelGatewayRouting:{},chatTemplateKwargs:{},chatTemplateArgs:{},zaiToolStream:!1,supportsThinkingTokenBudget:!1,thinkingTokenBudgetField:void 0,supportsStrictMode:!1,supportsOpenAIGrammarTools:!1,supportsMidConvoSystemMessages:!1,supportsMidConvoToolAdditions:!1,cacheControlFormat:A,sendSessionAffinityHeaders:h,sessionAffinityFormat:h?"openrouter":"openai",supportsLongCacheRetention:!(u||k||T||a||m)}}function q(e){let n=ot(e);return e.compat?{supportsStore:e.compat.supportsStore??n.supportsStore,supportsDeveloperRole:e.compat.supportsDeveloperRole??n.supportsDeveloperRole,supportsReasoningEffort:e.compat.supportsReasoningEffort??n.supportsReasoningEffort,supportsUsageInStreaming:e.compat.supportsUsageInStreaming??n.supportsUsageInStreaming,supportsFinishReason:e.compat.supportsFinishReason??n.supportsFinishReason,maxTokensField:e.compat.maxTokensField??n.maxTokensField,requiresToolResultName:e.compat.requiresToolResultName??n.requiresToolResultName,requiresAssistantAfterToolResult:e.compat.requiresAssistantAfterToolResult??n.requiresAssistantAfterToolResult,requiresThinkingAsText:e.compat.requiresThinkingAsText??n.requiresThinkingAsText,requiresReasoningContentOnAssistantMessages:e.compat.requiresReasoningContentOnAssistantMessages??n.requiresReasoningContentOnAssistantMessages,thinkingFormat:e.compat.thinkingFormat??n.thinkingFormat,openRouterRouting:e.compat.openRouterRouting??{},vercelGatewayRouting:e.compat.vercelGatewayRouting??n.vercelGatewayRouting,chatTemplateKwargs:e.compat.chatTemplateKwargs??n.chatTemplateKwargs,chatTemplateArgs:e.compat.chatTemplateArgs??n.chatTemplateArgs,zaiToolStream:e.compat.zaiToolStream??n.zaiToolStream,supportsThinkingTokenBudget:e.compat.supportsThinkingTokenBudget??n.supportsThinkingTokenBudget,thinkingTokenBudgetField:e.compat.thinkingTokenBudgetField??n.thinkingTokenBudgetField,supportsStrictMode:e.compat.supportsStrictMode??n.supportsStrictMode,supportsOpenAIGrammarTools:e.compat.supportsOpenAIGrammarTools??n.supportsOpenAIGrammarTools,supportsMidConvoSystemMessages:e.compat.supportsMidConvoSystemMessages??n.supportsMidConvoSystemMessages,supportsMidConvoToolAdditions:e.compat.supportsMidConvoToolAdditions??n.supportsMidConvoToolAdditions,cacheControlFormat:e.compat.cacheControlFormat??n.cacheControlFormat,sendSessionAffinityHeaders:e.compat.sendSessionAffinityHeaders??n.sendSessionAffinityHeaders,sessionAffinityFormat:e.compat.sessionAffinityFormat??n.sessionAffinityFormat,supportsLongCacheRetention:e.compat.supportsLongCacheRetention??n.supportsLongCacheRetention,vllmPriority:e.compat.vllmPriority}:n}export{st as convertMessages,He as stream,At as streamSimple};
@@ -1,6 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as A,b as O}from"./chunk-BGYR4ID3.js";import{a as G,b as U,c as N,d as D}from"./chunk-DXBSQXJL.js";import{a as L}from"./chunk-XIECJESP.js";import"./chunk-V3AQJSWR.js";import{a as x}from"./chunk-CVC66CFV.js";import{a as _}from"./chunk-23PRJECN.js";import{a as k,b}from"./chunk-FF7UELTU.js";import{f as P,h as I,i as w}from"./chunk-QBKCAIJG.js";import{C as y,F as C,L as M,y as R}from"./chunk-PZMGBKUR.js";import{a as E}from"./chunk-6R73ICDB.js";import"./chunk-SKHLZ6XY.js";import"./chunk-D6VMBA4C.js";import"./chunk-USBJFDJ6.js";import{a as S}from"./chunk-K4NTZEDJ.js";import{h as v}from"./chunk-6AKUD3CF.js";import"./chunk-OSEIQ7SS.js";import{b as T}from"./chunk-CXT5IR5T.js";import"./chunk-WHC7AYZD.js";var V=new Set(["openai","openai-codex","opencode"]),B=16,J="https://chatgpt.com/settings/usage",Q="You've reached your ChatGPT workspace's usage limit. Ask your workspace admin to increase it at admin.openai.com \u2192 Workspace \u2192 Usage limits.",Y="medium";function H(e,t){return e.provider==="openai"&&e.baseUrl==="https://api.openai.com/v1"&&t!==void 0&&!t.startsWith("sk-")}function F(e,t){if(!e)return!1;let r=t.toLowerCase();for(let[s,a]of Object.entries(e))if(s.toLowerCase()===r&&a!==null&&a.trim().length>0)return!0;return!1}function K(e,t,r){if(t)return t;if(F(r,"authorization")||F(r,"cf-aig-authorization"))return"unused";throw new Error(`No API key for provider: ${e}`)}function X(e){return e.provider==="openrouter"||e.baseUrl.includes("openrouter.ai")?"openrouter":"openai"}function q(e,t){return e||(E("PI_CACHE_RETENTION",t)==="long"?"long":"short")}function g(e){return{supportsDeveloperRole:e.compat?.supportsDeveloperRole??!0,supportsMidConvoSystemMessages:e.compat?.supportsMidConvoSystemMessages??!1,sessionAffinityFormat:e.compat?.sessionAffinityFormat??X(e),supportsLongCacheRetention:e.compat?.supportsLongCacheRetention??!0,supportsStrictMode:e.compat?.supportsStrictMode??!1,supportsOpenAIGrammarTools:e.compat?.supportsOpenAIGrammarTools??!1,supportsAdditionalTools:e.compat?.supportsAdditionalTools??!1,supportsToolSearch:e.compat?.supportsToolSearch??!1,supportsExplicitPromptCacheMode:e.compat?.supportsExplicitPromptCacheMode??!1,supportsMaxOutputTokens:e.compat?.supportsMaxOutputTokens??!0,supportsMidConvoEffort:e.compat?.supportsMidConvoEffort??!1}}function Z(e,t,r){if(!(!r.supportsMidConvoEffort||!t?.reasoningEffort||H(e,t.apiKey)))return e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort}function ee(e,t){return t==="long"&&e.supportsLongCacheRetention&&!e.supportsExplicitPromptCacheMode?"24h":void 0}function re(e,t){if(e.supportsExplicitPromptCacheMode){if(t==="none")return{mode:"explicit"};if(t==="long"&&e.supportsLongCacheRetention)return{ttl:"30m"}}}var te=(e,t,r)=>{let s=new T,a=R(t,g(e).supportsMidConvoSystemMessages);return(async()=>{let u=g(e),c=Z(e,r,u),o={role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,...c===void 0?{}:{providerThinkingLevel:c},usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{let i=K(e.provider,r?.apiKey,r?.headers),n=q(r?.cacheRetention,r?.env)==="none"?void 0:r?.sessionId,f=P(y(a.messages),u.supportsOpenAIGrammarTools),l=se(e,a,i,r?.headers,r?.identity,r?.fetch,n),d=oe(e,a,r,u,f,c),m=await r?.onPayload?.(d,e);m!==void 0&&(d=m);let W={...r?.signal?{signal:r.signal}:{},...r?.timeoutMs!==void 0?{timeout:r.timeoutMs}:{},maxRetries:0},{data:$,response:h}=await _(()=>l.responses.create(d,W).withResponse(),{maxRetries:r?.maxRetries,maxRetryDelayMs:r?.maxRetryDelayMs,signal:r?.signal});if(await r?.onResponse?.({status:h.status,headers:S(h.headers)},e),s.push({type:"start",partial:o}),await D($,o,s,e,{onProviderStreamEvent:r?.onProviderStreamEvent,serviceTier:r?.serviceTier,grammarToolInputProperties:f,applyServiceTierPricing:(j,z)=>ie(j,z,e)}),r?.signal?.aborted)throw new Error("Request was aborted");if(o.stopReason==="pending")throw new Error("OpenAI Responses stream ended without a stop reason");if(o.stopReason==="aborted"||o.stopReason==="error")throw new Error(o.errorMessage||"An unknown error occurred");s.push({type:"done",reason:o.stopReason,message:o}),s.end()}catch(i){for(let n of o.content)delete n.index,delete n.partialJson,delete n.customInput;o.stopReason=r?.signal?.aborted?"aborted":"error";let p=b(k(i),`${e.provider==="openai"?"OpenAI":e.provider} API error`);p.includes("subscription_sharing_usage_limit_exceeded")?o.errorMessage=`${p}
5
- Check your ChatGPT usage: ${J}`:p.includes("subscription_sharing_workplace_individual_usage_limit_exceeded")?o.errorMessage=`${p}
6
- ${Q}`:o.errorMessage=p,s.push({type:"error",reason:o.stopReason,error:o}),s.end()}})(),s},Ce=(e,t,r)=>{K(e.provider,r?.apiKey,r?.headers);let s={...w(e,t,r,r?.apiKey),toolChoice:r?.toolChoice},a=r?.reasoning?M(e,r.reasoning):void 0;return te(e,t,{...s,reasoningEffort:a==="off"?void 0:a})};function se(e,t,r,s,a,u,c){let o=g(e),i={...v(e,a),...e.headers};if(e.provider==="github-copilot"){let p=A(t.messages),n=O({messages:t.messages,hasImages:p});Object.assign(i,n)}return c&&(o.sessionAffinityFormat==="openrouter"?i["x-session-id"]=c:(o.sessionAffinityFormat==="openai"&&(i.session_id=c),i["x-client-request-id"]=c)),s&&Object.assign(i,s),new x({apiKey:r,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:u,defaultHeaders:i})}function oe(e,t,r,s,a,u){let c=C(t.messages,G(s)),o=U(e,t,V,{grammarToolInputProperties:a,supportsMidConvoSystemMessages:s.supportsMidConvoSystemMessages,supportsAdditionalTools:s.supportsAdditionalTools,supportsToolSearch:s.supportsToolSearch,toolOptions:{supportsStrictMode:s.supportsStrictMode,supportsOpenAIGrammarTools:s.supportsOpenAIGrammarTools},configurationUpdateEffort:u}),i=q(r?.cacheRetention,r?.env),p=H(e,r?.apiKey),n={model:e.id,input:o,stream:!0,prompt_cache_key:i==="none"?void 0:L(r?.sessionId),prompt_cache_retention:p?void 0:ee(s,i),prompt_cache_options:p?void 0:re(s,i),store:!1};r?.maxTokens&&s.supportsMaxOutputTokens&&!p&&(n.max_output_tokens=Math.max(r.maxTokens,B)),r?.temperature!==void 0&&!p&&(n.temperature=r?.temperature),r?.serviceTier!==void 0&&(n.service_tier=r.serviceTier),c.requestTools.length>0&&(n.tools=N(c.requestTools,{supportsStrictMode:s.supportsStrictMode,supportsOpenAIGrammarTools:s.supportsOpenAIGrammarTools})),r?.toolChoice!==void 0&&(n.tool_choice=r.toolChoice);let f=r?.reasoningEffort??(r?.reasoningSummary?"medium":void 0);if(e.reasoning){if(f){let d=r?.reasoningEffort?e.thinkingLevelMap?.[r.reasoningEffort]??r.reasoningEffort:f,m=u===void 0?d:Y;n.reasoning={effort:m,summary:r?.reasoningSummary||"auto"},n.include=["reasoning.encrypted_content"]}else e.provider!=="github-copilot"&&e.thinkingLevelMap?.off!==null&&(n.reasoning={effort:e.thinkingLevelMap?.off??"none"});e.provider==="xai"&&(n.include=["reasoning.encrypted_content"])}let l=I(e,f??"off",r?.samplingParams);return l&&Object.assign(n,l),n}function ne(e,t){switch(t){case"flex":return .5;case"priority":case"fast":return e.id==="gpt-5.5"?2.5:2;default:return 1}}function ie(e,t,r){let s=ne(r,t);s!==1&&(e.cost.input*=s,e.cost.output*=s,e.cost.cacheRead*=s,e.cost.cacheWrite*=s,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite)}export{te as stream,Ce as streamSimple};
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as k}from"./chunk-CVC66CFV.js";import{a as x}from"./chunk-23PRJECN.js";import{a as w,b as T}from"./chunk-FF7UELTU.js";import{a as _}from"./chunk-USBJFDJ6.js";import{a as y,b as R}from"./chunk-K4NTZEDJ.js";import{h as l}from"./chunk-6AKUD3CF.js";import"./chunk-WHC7AYZD.js";var H=async(e,s,t)=>{let r={api:e.api,provider:e.provider,model:e.id,output:[],stopReason:"stop",timestamp:Date.now()};try{let a=t?.apiKey;if(!a)throw new Error(`No API key for provider: ${e.provider}`);let i=b(e,a,t?.headers,t?.fetch,t?.identity),n=M(e,s),c=await t?.onPayload?.(n,e);c!==void 0&&(n=c);let o={...t?.signal?{signal:t.signal}:{},...t?.timeoutMs!==void 0?{timeout:t.timeoutMs}:{},maxRetries:0},{data:v,response:g}=await x(()=>i.chat.completions.create(n,o).withResponse(),{maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,signal:t?.signal});await t?.onResponse?.({status:g.status,headers:y(g.headers)},e);let u=v;r.responseId=u.id,u.usage&&(r.usage=P(u.usage,e));let p=u.choices[0];if(p){let m=p.message.content;typeof m=="string"&&m.length>0&&r.output.push({type:"text",text:m});for(let d of p.message.images??[]){let f=typeof d.image_url=="string"?d.image_url:d.image_url?.url;if(!f?.startsWith("data:"))continue;let h=f.match(/^data:([^;]+);base64,(.+)$/);h&&r.output.push({type:"image",mimeType:h[1],data:h[2]})}}return r}catch(a){return r.stopReason=t?.signal?.aborted?"aborted":"error",r.errorMessage=T(w(a)),r}};function b(e,s,t,r,a){return new k({apiKey:s,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:r,defaultHeaders:R(l(e,a),e.headers,t)})}function M(e,s){let t=s.input.map(r=>r.type==="text"?{type:"text",text:_(r.text)}:{type:"image_url",image_url:{url:`data:${r.mimeType};base64,${r.data}`}});return{model:e.id,messages:[{role:"user",content:t}],stream:!1,modalities:e.output.includes("text")?["image","text"]:["image"]}}function P(e,s){let t=e.prompt_tokens||0,r=e.prompt_tokens_details?.cached_tokens||0,a=e.prompt_tokens_details?.cache_write_tokens||0,i=a>0?Math.max(0,r-a):r,n=Math.max(0,t-i-a),c=e.completion_tokens||0,o={input:n,output:c,cacheRead:i,cacheWrite:a,totalTokens:n+c+i+a,cost:{input:s.cost.input/1e6*n,output:s.cost.output/1e6*c,cacheRead:s.cost.cacheRead/1e6*i,cacheWrite:s.cost.cacheWrite/1e6*a,total:0}};return o.cost.total=o.cost.input+o.cost.output+o.cost.cacheRead+o.cost.cacheWrite,o}export{H as generateImages};
@@ -1,10 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as y}from"./chunk-6R73ICDB.js";import{d as x}from"./chunk-SKHLZ6XY.js";import{c as h,d as p}from"./chunk-D6VMBA4C.js";import{a as k,b as w}from"./chunk-K4NTZEDJ.js";import{h as m}from"./chunk-6AKUD3CF.js";import{b as f}from"./chunk-CXT5IR5T.js";import"./chunk-WHC7AYZD.js";var g=class extends Error{code;diagnosticDetails;constructor(t,n,e){super(t),this.name="PiMessagesResponseError",this.code=n,this.diagnosticDetails=e}};function T(r){try{let t=JSON.parse(r),n=t?.error;return t&&typeof n=="object"&&n!==null&&!Array.isArray(n)?t:void 0}catch{return}}function R(r){return r.length>8192?`${r.slice(0,8192)}\u2026`:r}function S(r,t,n){let e=typeof n?.error?.message=="string"?n.error.message:void 0,s=typeof n?.error?.code=="string"?n.error.code:void 0,a=e??t,o=s?` (${s})`:"";return`${r.status} ${r.statusText}: ${a}${o}`}function _(r,t,n,e){let s=T(e),a=typeof s?.error?.code=="string"?s.error.code:void 0;return new g(S(n,e,s),a,{version:1,provider:r.provider,model:r.id,url:t.toString(),status:n.status,statusText:n.statusText,...s?.error===void 0?{}:{error:s.error},...s?{}:{body:R(e)},timestampMs:Date.now()})}function E(){return{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}function b(r,t){t&&p(r,{type:"pi_messages_rewrite",timestamp:Date.now(),details:{...t}})}function M(r){let t={role:"assistant",content:[],api:r.api,provider:r.provider,model:r.id,usage:E(),stopReason:"pending",timestamp:Date.now()},n=new Map;return e=>{switch(e.type){case"done":return Object.assign(t,{stopReason:e.reason,usage:e.usage,responseId:e.responseId}),e.providerThinkingLevel!==void 0&&(t.providerThinkingLevel=e.providerThinkingLevel),b(t,e.rewrite),{type:"done",reason:e.reason,message:t};case"error":return Object.assign(t,{stopReason:e.reason,usage:e.usage,errorMessage:e.errorMessage,responseId:e.responseId}),e.providerThinkingLevel!==void 0&&(t.providerThinkingLevel=e.providerThinkingLevel),b(t,e.rewrite),{type:"error",reason:e.reason,error:t};case"start":break;case"text_start":t.content[e.contentIndex]={type:"text",text:""};break;case"text_delta":t.content[e.contentIndex].text+=e.delta;break;case"text_end":Object.assign(t.content[e.contentIndex],{text:e.content,textSignature:e.contentSignature});break;case"thinking_start":t.content[e.contentIndex]={type:"thinking",thinking:""};break;case"thinking_delta":t.content[e.contentIndex].thinking+=e.delta;break;case"thinking_end":Object.assign(t.content[e.contentIndex],{thinking:e.content,thinkingSignature:e.contentSignature,redacted:e.redacted});break;case"toolcall_start":t.content[e.contentIndex]={type:"toolCall",id:e.id,name:e.toolName,arguments:{}},n.set(e.contentIndex,"");break;case"toolcall_delta":{let s=`${n.get(e.contentIndex)??""}${e.delta}`;n.set(e.contentIndex,s),t.content[e.contentIndex].arguments=x(s);break}case"toolcall_end":return Object.assign(t.content[e.contentIndex],e.toolCall),n.delete(e.contentIndex),{type:"toolcall_end",contentIndex:e.contentIndex,toolCall:t.content[e.contentIndex],partial:t}}return{...e,partial:t}}}async function*$(r){let t=new TextDecoder,n=r.getReader(),e="";try{for(;;){let{done:s,value:a}=await n.read();e+=s?t.decode():t.decode(a,{stream:!0}),e=e.replace(/\r\n/g,`
5
- `);let o=e.indexOf(`
6
-
7
- `);for(;o!==-1;){let c=I(e.slice(0,o));c&&(yield c),e=e.slice(o+2),o=e.indexOf(`
8
-
9
- `)}if(s)break}if(e.trim()){let s=I(e);s&&(yield s)}}finally{n.releaseLock()}}function I(r){let t=r.split(`
10
- `).find(n=>n.startsWith("data:"))?.slice(5).trim();return t&&t!=="[DONE]"?JSON.parse(t):void 0}function D(r,t,n){let e=n?"aborted":"error",s={role:"assistant",content:[],api:r.api,provider:r.provider,model:r.id,usage:E(),stopReason:e,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()};return!n&&t instanceof g&&p(s,h("pi_messages_response_failure",t,t.diagnosticDetails)),{type:"error",reason:e,error:s}}function O(r,t){return r||(y("PI_CACHE_RETENTION",t)==="long"?"long":void 0)}var P=(r,t,n)=>{let e=new f,s=M(r);return(async()=>{try{let a=n?.apiKey;if(!a)throw new Error(`No API key provided for provider "${r.provider}"`);let o=new URL(`${r.baseUrl.replace(/\/+$/u,"")}/messages`);n?.debug&&o.searchParams.set("debug","1");let c={model:r.id,context:t,options:{temperature:n?.temperature,maxTokens:n?.maxTokens,reasoning:n?.reasoning,cacheRetention:O(n?.cacheRetention,n?.env),sessionId:n?.sessionId,toolChoice:n?.toolChoice}},l=await n?.onPayload?.(c,r);l!==void 0&&(c=l);let i=await(n?.fetch??globalThis.fetch)(o,{method:"POST",headers:w(m(r,n?.identity),{authorization:`Bearer ${a}`,accept:"text/event-stream","content-type":"application/json"},n?.headers),body:JSON.stringify(c),signal:n?.signal});if(await n?.onResponse?.({status:i.status,headers:k(i.headers)},r),!i.ok){let d=await i.text();throw _(r,o,i,d)}if(!i.body)throw new Error(`${r.provider} response has no body`);for await(let d of $(i.body)){await n?.onProviderStreamEvent?.(d,r);let u=s(d);if(e.push(u),u.type==="done"||u.type==="error")return}throw new Error(`${r.provider} stream ended without a terminal event`)}catch(a){e.push(D(r,a,n?.signal?.aborted??!1))}})(),e},v=(r,t,n)=>{let e=n;return P(r,t,{...n,reasoning:n?.reasoning,toolChoice:n?.toolChoice,debug:e?.debug})};export{g as PiMessagesResponseError,P as stream,v as streamSimple};
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{b as _}from"./chunk-WEZWKMYU.js";import{a as p}from"./chunk-XBJOYU5Y.js";import{a as w}from"./chunk-XAXWLYH5.js";import"./chunk-IRWZ7UPF.js";import{a as f}from"./chunk-ILEML5IP.js";import"./chunk-WHC7AYZD.js";var v="127.0.0.1",m=1456,E="/oauth/callback",d=`http://${v}:${m}${E}`,A=6e4,g="browser",y="device-code",a="pi-gateway",O="gateway offline_access",S="urn:ietf:params:oauth:grant-type:device_code";async function L(o,r){let e=await fetch(new URL("/v1/oauth",o),{headers:{accept:"application/json"},signal:r});if(!e.ok)throw new Error(`Could not load Radius OAuth config from ${o}: ${e.status} ${await e.text()}`);let t=await e.json();if(typeof t.authorizationEndpoint!="string")throw new Error(`Invalid Radius OAuth config from ${o}`);return{authorizationEndpoint:t.authorizationEndpoint}}var c=class extends Error{status;oauthError;constructor(r,e,t,n){let i=e?t?`${e}: ${t}`:e:t||String(r);super(`${n}: ${i}`),this.status=r,this.oauthError=e}};async function R(o,r){let e=await o.text().catch(()=>""),t,n;if(e)try{let i=JSON.parse(e);t=typeof i.error=="string"?i.error:void 0,n=typeof i.error_description=="string"?i.error_description:void 0}catch{n=e}return new c(o.status,t,n,r)}async function u(o,r,e){let t;try{t=await fetch(new URL("/v1/oauth/token",o),{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:r,signal:e})}catch(i){throw e.aborted?new Error("Login cancelled"):i}if(!t.ok)throw await R(t,"Radius OAuth token request failed");let n=await t.json();return{type:"oauth",access:n.access_token,refresh:n.refresh_token,expires:Date.now()+n.expires_in*1e3-A,scope:n.scope}}async function C(o,r,e){let{verifier:t,challenge:n}=await w(),i=crypto.randomUUID(),l=new URL(r);l.search=new URLSearchParams({response_type:"code",client_id:a,redirect_uri:d,scope:O,code_challenge:n,code_challenge_method:"S256",handoff:"url",state:i}).toString();let h=await p({providerName:"Radius",host:v,port:m,path:E,state:i,complete:s=>u(o,new URLSearchParams({grant_type:"authorization_code",client_id:a,redirect_uri:d,code:s,code_verifier:t}),e.signal),signal:e.signal});e.notify({type:"progress",message:`Listening for OAuth callback on ${d}`}),e.notify({type:"auth_url",url:l.toString(),instructions:"Continue in your browser."});try{let s=await h.wait();if(!s)throw new Error("OAuth callback did not complete.");return s}finally{h.close()}}async function U(o,r){let e;try{e=await fetch(new URL("/v1/oauth/device",o),{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:a,scope:O}),signal:r})}catch(n){throw r.aborted?new Error("Login cancelled"):n}if(!e.ok)throw await R(e,"Radius OAuth device authorization failed");let t=await e.json();if(!t.device_code||!t.user_code||!t.verification_uri||!t.expires_in)throw new Error("Radius OAuth device authorization response is missing required fields");return{device_code:t.device_code,user_code:t.user_code,verification_uri:t.verification_uri,expires_in:t.expires_in,interval:t.interval}}async function x(o,r){let e=await U(o,r.signal);return r.notify({type:"device_code",userCode:e.user_code,verificationUri:e.verification_uri,intervalSeconds:e.interval,expiresInSeconds:e.expires_in}),f({intervalSeconds:e.interval,expiresInSeconds:e.expires_in,signal:r.signal,poll:async()=>{try{return{status:"complete",value:await u(o,new URLSearchParams({grant_type:S,client_id:a,device_code:e.device_code}),r.signal)}}catch(t){if(!(t instanceof c))throw t;switch(t.oauthError){case"authorization_pending":return{status:"pending"};case"slow_down":return{status:"slow_down"};case"expired_token":return{status:"failed",message:"Device authorization expired."};case"access_denied":return{status:"failed",message:"Device authorization was denied."};default:throw t}}}})}function b(o){let r=_(o.gateway);return{name:o.name,async login(e){let t=await e.prompt({type:"select",message:`Sign in to ${o.name}:`,options:[{id:g,label:"Sign in with browser (recommended)"},{id:y,label:"Sign in with device code (when signing in from another device)"}]});if(t===y)return x(r,e);if(t===g){let n=await L(r,e.signal);return C(r,n.authorizationEndpoint,e)}throw new Error(`Unknown ${o.name} sign-in method: ${t}`)},async refresh(e,t){return await u(r,new URLSearchParams({grant_type:"refresh_token",client_id:a,refresh_token:e.refresh}),t)},async toAuth(e){return{apiKey:e.access}}}}export{b as createRadiusOAuth};