@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
@@ -0,0 +1,22 @@
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{$ as Vt,A as Ut,B as Ot,D as At,F as kt,G as It,I as Pt,J as Ae,L as Mt,M as Lt,P as $t,Q as qt,R as Wt,S as Ht,T as Nt,X as jt,Z as x,aa as Dt,b as F,ba as Ft,ca as Gt,d as vt,da as Zt,i as Ct,j as de,k as Rt,l as bt,m as St,n as U,o as te,p as he,r as Et,t as Tt,u as Ve,w as xt,y as zt}from"./chunk-TMV2ZDOI.js";import{C as mt,H as gt,J as yt,e as ft,n as c,o as _t,p as je,q,s as wt,u as _,v as j,w as Oe}from"./chunk-W34AK4SK.js";import{c as zr,e as Ur}from"./chunk-WHC7AYZD.js";var Qt=zr(De=>{"use strict";var Jt=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,Ar=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,Xt=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,kr=/\\([\u000b\u0020-\u00ff])/g,Ir=/([\\"])/g,Kt=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;De.format=Pr;De.parse=Mr;function Pr(t){if(!t||typeof t!="object")throw new TypeError("argument obj is required");var e=t.parameters,r=t.type;if(!r||!Kt.test(r))throw new TypeError("invalid type");var o=r;if(e&&typeof e=="object")for(var n,i=Object.keys(e).sort(),a=0;a<i.length;a++){if(n=i[a],!Xt.test(n))throw new TypeError("invalid parameter name");o+="; "+n+"="+$r(e[n])}return o}function Mr(t){if(!t)throw new TypeError("argument string is required");var e=typeof t=="object"?Lr(t):t;if(typeof e!="string")throw new TypeError("argument string is required to be a string");var r=e.indexOf(";"),o=r!==-1?e.slice(0,r).trim():e.trim();if(!Kt.test(o))throw new TypeError("invalid media type");var n=new qr(o.toLowerCase());if(r!==-1){var i,a,s;for(Jt.lastIndex=r;a=Jt.exec(e);){if(a.index!==r)throw new TypeError("invalid parameter format");r+=a[0].length,i=a[1].toLowerCase(),s=a[2],s.charCodeAt(0)===34&&(s=s.slice(1,-1),s.indexOf("\\")!==-1&&(s=s.replace(kr,"$1"))),n.parameters[i]=s}if(r!==e.length)throw new TypeError("invalid parameter format")}return n}function Lr(t){var e;if(typeof t.getHeader=="function"?e=t.getHeader("content-type"):typeof t.headers=="object"&&(e=t.headers&&t.headers["content-type"]),typeof e!="string")throw new TypeError("content-type header is missing from object");return e}function $r(t){var e=String(t);if(Xt.test(e))return e;if(e.length>0&&!Ar.test(e))throw new TypeError("invalid parameter value");return'"'+e.replace(Ir,"\\$1")+'"'}function qr(t){this.parameters=Object.create(null),this.type=t}});var ke=class{constructor(e){this._client=e}async*callToolStream(e,r=Ae,o){let n=this._client,i={...o,task:o?.task??(n.isToolTask(e.name)?{}:void 0)},a=n.requestStream({method:"tools/call",params:e},r,i),s=n.getToolOutputValidator(e.name);for await(let l of a){if(l.type==="result"&&s){let d=l.result;if(!d.structuredContent&&!d.isError){yield{type:"error",error:new x(U.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(d.structuredContent)try{let h=s(d.structuredContent);if(!h.valid){yield{type:"error",error:new x(U.InvalidParams,`Structured content does not match the tool's output schema: ${h.errorMessage}`)};return}}catch(h){if(h instanceof x){yield{type:"error",error:h};return}yield{type:"error",error:new x(U.InvalidParams,`Failed to validate structured content: ${h instanceof Error?h.message:String(h)}`)};return}}yield l}}async getTask(e,r){return this._client.getTask({taskId:e},r)}async getTaskResult(e,r,o){return this._client.getTaskResult({taskId:e},r,o)}async listTasks(e,r){return this._client.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._client.cancelTask({taskId:e},r)}requestStream(e,r,o){return this._client.requestStream(e,r,o)}};function Ie(t,e){if(!(!t||e===null||typeof e!="object")){if(t.type==="object"&&t.properties&&typeof t.properties=="object"){let r=e,o=t.properties;for(let n of Object.keys(o)){let i=o[n];r[n]===void 0&&Object.prototype.hasOwnProperty.call(i,"default")&&(r[n]=i.default),r[n]!==void 0&&Ie(i,r[n])}}if(Array.isArray(t.anyOf))for(let r of t.anyOf)typeof r!="boolean"&&Ie(r,e);if(Array.isArray(t.oneOf))for(let r of t.oneOf)typeof r!="boolean"&&Ie(r,e)}}function Or(t){if(!t)return{supportsFormMode:!1,supportsUrlMode:!1};let e=t.form!==void 0,r=t.url!==void 0;return{supportsFormMode:e||!e&&!r,supportsUrlMode:r}}var Bt=class extends Vt{constructor(e,r){super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=r?.capabilities??{},this._jsonSchemaValidator=r?.jsonSchemaValidator??new Ft,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Mt,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",It,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Ot,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new ke(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Dt(this._capabilities,e)}setRequestHandler(e,r){let n=vt(e)?.method;if(!n)throw new Error("Schema is missing a method literal");let i=Ct(n);if(typeof i!="string")throw new Error("Schema method literal must be a string");let a=i;if(a==="elicitation/create"){let s=async(l,d)=>{let h=F(Ht,l);if(!h.success){let A=h.error instanceof Error?h.error.message:String(h.error);throw new x(U.InvalidParams,`Invalid elicitation request: ${A}`)}let{params:f}=h.data;f.mode=f.mode??"form";let{supportsFormMode:R,supportsUrlMode:w}=Or(this._capabilities.elicitation);if(f.mode==="form"&&!R)throw new x(U.InvalidParams,"Client does not support form-mode elicitation requests");if(f.mode==="url"&&!w)throw new x(U.InvalidParams,"Client does not support URL-mode elicitation requests");let S=await Promise.resolve(r(l,d));if(f.task){let A=F(Ve,S);if(!A.success){let Y=A.error instanceof Error?A.error.message:String(A.error);throw new x(U.InvalidParams,`Invalid task creation result: ${Y}`)}return A.data}let m=F(Nt,S);if(!m.success){let A=m.error instanceof Error?m.error.message:String(m.error);throw new x(U.InvalidParams,`Invalid elicitation result: ${A}`)}let v=m.data,M=f.mode==="form"?f.requestedSchema:void 0;if(f.mode==="form"&&v.action==="accept"&&v.content&&M&&this._capabilities.elicitation?.form?.applyDefaults)try{Ie(M,v.content)}catch{}return v};return super.setRequestHandler(e,s)}if(a==="sampling/createMessage"){let s=async(l,d)=>{let h=F($t,l);if(!h.success){let v=h.error instanceof Error?h.error.message:String(h.error);throw new x(U.InvalidParams,`Invalid sampling request: ${v}`)}let{params:f}=h.data,R=await Promise.resolve(r(l,d));if(f.task){let v=F(Ve,R);if(!v.success){let M=v.error instanceof Error?v.error.message:String(v.error);throw new x(U.InvalidParams,`Invalid task creation result: ${M}`)}return v.data}let S=f.tools||f.toolChoice?Wt:qt,m=F(S,R);if(!m.success){let v=m.error instanceof Error?m.error.message:String(m.error);throw new x(U.InvalidParams,`Invalid sampling result: ${v}`)}return m.data};return super.setRequestHandler(e,s)}return super.setRequestHandler(e,r)}assertCapability(e,r){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{let o=await this.request({method:"initialize",params:{protocolVersion:de,capabilities:this._capabilities,clientInfo:this._clientInfo}},Et,r);if(o===void 0)throw new Error(`Server sent invalid initialize result: ${o}`);if(!Rt.includes(o.protocolVersion))throw new Error(`Server's protocol version is not supported: ${o.protocolVersion}`);this._serverCapabilities=o.capabilities,this._serverVersion=o.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(o.protocolVersion),this._instructions=o.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(o){throw this.close(),o}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`);break;case"ping":break}}assertTaskCapability(e){Gt(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&Zt(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},he,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},jt,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},he,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},kt,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},At,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},xt,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},zt,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},Ut,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},he,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},he,r)}async callTool(e,r=Ae,o){if(this.isToolTaskRequired(e.name))throw new x(U.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let n=await this.request({method:"tools/call",params:e},r,o),i=this.getToolOutputValidator(e.name);if(i){if(!n.structuredContent&&!n.isError)throw new x(U.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(n.structuredContent)try{let a=i(n.structuredContent);if(!a.valid)throw new x(U.InvalidParams,`Structured content does not match the tool's output schema: ${a.errorMessage}`)}catch(a){throw a instanceof x?a:new x(U.InvalidParams,`Failed to validate structured content: ${a instanceof Error?a.message:String(a)}`)}}return n}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let r of e){if(r.outputSchema){let n=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,n)}let o=r.execution?.taskSupport;(o==="required"||o==="optional")&&this._cachedKnownTaskTools.add(r.name),o==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){let o=await this.request({method:"tools/list",params:e},Pt,r);return this.cacheToolMetadata(o.tools),o}_setupListChangedHandler(e,r,o,n){let i=Lt.safeParse(o);if(!i.success)throw new Error(`Invalid ${e} listChanged options: ${i.error.message}`);if(typeof o.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:a,debounceMs:s}=i.data,{onChanged:l}=o,d=async()=>{if(!a){l(null,null);return}try{let f=await n();l(null,f)}catch(f){let R=f instanceof Error?f:new Error(String(f));l(R,null)}},h=()=>{if(s){let f=this._listChangedDebounceTimers.get(e);f&&clearTimeout(f);let R=setTimeout(d,s);this._listChangedDebounceTimers.set(e,R)}else d()};this.setNotificationHandler(r,h)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var Yt=Ur(Qt(),1);function er(t){if(t)try{return Yt.default.parse(t).type}catch{let e=(t.split(";",1)[0]??"").trim().toLowerCase();return e===""||t.slice(e.length).includes(",")?void 0:e}}function re(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}function Pe(t=fetch,e){return e?async(r,o)=>{let n={...e,...o,headers:o?.headers?{...re(e.headers),...re(o.headers)}:e.headers};return t(r,n)}:t}var Wr=5,Hr=[301,302,303,307,308];function Nr(t,e){return t.protocol===e.protocol&&t.hostname===e.hostname&&t.port===e.port?!0:t.hostname===e.hostname&&t.protocol==="http:"&&t.port===""&&e.protocol==="https:"&&e.port===""}function tr(t,e){let r=Hr.includes(t.status)?t.headers.get("location"):null;try{return r?new URL(r,e):void 0}catch{return}}function Me(t,e,r,o,n=0){let i=tr(o,e),a=o.status===307||o.status===308||(r?.method??"GET").toUpperCase()==="GET";if(!i||n===Wr||!a)return;let s=new URL(e);if(!((i.username||i.password)&&(i.username!==s.username||i.password!==s.password)||!Nr(s,i)))return Promise.resolve(o.body?.cancel()).then(()=>t(i,{...r,redirect:"manual"})).then(d=>Me(t,i,r,d,n+1)??d)}var rr=new WeakSet;function oe(t){let e=(r,o)=>(t??fetch)(r,o);return rr.add(e),e}function $(t=fetch){return rr.has(t)?t:(e,r)=>r?.redirect==="error"||r?.redirect==="manual"?t(e,r):Promise.resolve(t(e,{...r,redirect:"manual"})).then(o=>Me(t,e,r,o)??o)}function se(t,e){if(t.type==="opaqueredirect")return"Redirect not followed: this runtime does not expose the redirect target";let r=t.url||e,o=tr(t,r);if(o)return o.username=o.password=o.search=o.hash="",o.protocol==="http:"&&new URL(r).protocol==="https:"?(o.protocol="https:",`Redirect to plain http not followed; try ${o.href} instead`):`Redirect to ${o.href} not followed`}var Fe;Fe=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(t=>t.webcrypto);async function jr(t){return(await Fe).getRandomValues(new Uint8Array(t))}async function Vr(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%e.length,o="";for(;o.length<t;){let n=await jr(t-o.length);for(let i of n)i<r&&(o+=e[i%e.length])}return o}async function Dr(t){return await Vr(t)}async function Fr(t){let e=await(await Fe).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Ge(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await Dr(t),r=await Fr(e);return{code_verifier:e,code_challenge:r}}var O=_t().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:gt.custom,message:"URL must be parseable",fatal:!0}),ft}).refine(t=>{let e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),sr=Oe({resource:c().url(),authorization_servers:_(O).optional(),jwks_uri:c().url().optional(),scopes_supported:_(c()).optional(),bearer_methods_supported:_(c()).optional(),resource_signing_alg_values_supported:_(c()).optional(),resource_name:c().optional(),resource_documentation:c().optional(),resource_policy_uri:c().url().optional(),resource_tos_uri:c().url().optional(),tls_client_certificate_bound_access_tokens:q().optional(),authorization_details_types_supported:_(c()).optional(),dpop_signing_alg_values_supported:_(c()).optional(),dpop_bound_access_tokens_required:q().optional()}),Ze=Oe({issuer:c(),authorization_endpoint:O,token_endpoint:O,registration_endpoint:O.optional(),scopes_supported:_(c()).optional(),response_types_supported:_(c()),response_modes_supported:_(c()).optional(),grant_types_supported:_(c()).optional(),token_endpoint_auth_methods_supported:_(c()).optional(),token_endpoint_auth_signing_alg_values_supported:_(c()).optional(),service_documentation:O.optional(),revocation_endpoint:O.optional(),revocation_endpoint_auth_methods_supported:_(c()).optional(),revocation_endpoint_auth_signing_alg_values_supported:_(c()).optional(),introspection_endpoint:c().optional(),introspection_endpoint_auth_methods_supported:_(c()).optional(),introspection_endpoint_auth_signing_alg_values_supported:_(c()).optional(),code_challenge_methods_supported:_(c()).optional(),client_id_metadata_document_supported:q().optional()}),Gr=Oe({issuer:c(),authorization_endpoint:O,token_endpoint:O,userinfo_endpoint:O.optional(),jwks_uri:O,registration_endpoint:O.optional(),scopes_supported:_(c()).optional(),response_types_supported:_(c()),response_modes_supported:_(c()).optional(),grant_types_supported:_(c()).optional(),acr_values_supported:_(c()).optional(),subject_types_supported:_(c()),id_token_signing_alg_values_supported:_(c()),id_token_encryption_alg_values_supported:_(c()).optional(),id_token_encryption_enc_values_supported:_(c()).optional(),userinfo_signing_alg_values_supported:_(c()).optional(),userinfo_encryption_alg_values_supported:_(c()).optional(),userinfo_encryption_enc_values_supported:_(c()).optional(),request_object_signing_alg_values_supported:_(c()).optional(),request_object_encryption_alg_values_supported:_(c()).optional(),request_object_encryption_enc_values_supported:_(c()).optional(),token_endpoint_auth_methods_supported:_(c()).optional(),token_endpoint_auth_signing_alg_values_supported:_(c()).optional(),display_values_supported:_(c()).optional(),claim_types_supported:_(c()).optional(),claims_supported:_(c()).optional(),service_documentation:c().optional(),claims_locales_supported:_(c()).optional(),ui_locales_supported:_(c()).optional(),claims_parameter_supported:q().optional(),request_parameter_supported:q().optional(),request_uri_parameter_supported:q().optional(),require_request_uri_registration:q().optional(),op_policy_uri:O.optional(),op_tos_uri:O.optional(),client_id_metadata_document_supported:q().optional()}),nr=j({...Gr.shape,...Ze.pick({code_challenge_methods_supported:!0}).shape}),ir=j({access_token:c(),id_token:c().optional(),token_type:c(),expires_in:yt.number().optional(),scope:c().optional(),refresh_token:c().optional(),issuer:c().optional().catch(void 0)}).strip(),ar=j({error:c(),error_description:c().optional(),error_uri:c().optional()}),or=O.optional().or(mt("").transform(()=>{})),Zr=j({redirect_uris:_(O),token_endpoint_auth_method:c().optional(),grant_types:_(c()).optional(),response_types:_(c()).optional(),client_name:c().optional(),client_uri:O.optional(),logo_uri:or,scope:c().optional(),contacts:_(c()).optional(),tos_uri:or,policy_uri:c().optional(),jwks_uri:O.optional(),jwks:wt().optional(),software_id:c().optional(),software_version:c().optional(),software_statement:c().optional()}).strip(),Br=j({client_id:c(),client_secret:c().optional(),client_id_issued_at:je().optional(),client_secret_expires_at:je().optional(),issuer:c().optional().catch(void 0)}).strip(),cr=Zr.merge(Br),qo=j({error:c(),error_description:c().optional()}).strip(),Wo=j({token:c(),token_type_hint:c().optional()}).strip();function lr(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function ur({requestedResource:t,configuredResource:e}){let r=typeof t=="string"?new URL(t):new URL(t.href),o=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==o.origin||r.pathname.length<o.pathname.length)return!1;let n=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",i=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return n.startsWith(i)}var E=class extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},pe=class extends E{};pe.errorCode="invalid_request";var G=class extends E{};G.errorCode="invalid_client";var Z=class extends E{};Z.errorCode="invalid_grant";var B=class extends E{};B.errorCode="unauthorized_client";var fe=class extends E{};fe.errorCode="unsupported_grant_type";var _e=class extends E{};_e.errorCode="invalid_scope";var we=class extends E{};we.errorCode="access_denied";var W=class extends E{};W.errorCode="server_error";var me=class extends E{};me.errorCode="temporarily_unavailable";var ge=class extends E{};ge.errorCode="unsupported_response_type";var ye=class extends E{};ye.errorCode="unsupported_token_type";var ve=class extends E{};ve.errorCode="invalid_token";var Ce=class extends E{};Ce.errorCode="method_not_allowed";var Re=class extends E{};Re.errorCode="too_many_requests";var J=class extends E{};J.errorCode="invalid_client_metadata";var be=class extends E{};be.errorCode="insufficient_scope";var Se=class extends E{};Se.errorCode="invalid_target";var dr={[pe.errorCode]:pe,[G.errorCode]:G,[Z.errorCode]:Z,[B.errorCode]:B,[fe.errorCode]:fe,[_e.errorCode]:_e,[we.errorCode]:we,[W.errorCode]:W,[me.errorCode]:me,[ge.errorCode]:ge,[ye.errorCode]:ye,[ve.errorCode]:ve,[Ce.errorCode]:Ce,[Re.errorCode]:Re,[J.errorCode]:J,[be.errorCode]:be,[Se.errorCode]:Se};var k=class extends Error{constructor(e){super(e??"Unauthorized")}};function Jr(t){return["client_secret_basic","client_secret_post","none"].includes(t)}var Be="code",Je="S256";function Xr(t,e){let r=t.client_secret!==void 0;return"token_endpoint_auth_method"in t&&t.token_endpoint_auth_method&&Jr(t.token_endpoint_auth_method)&&(e.length===0||e.includes(t.token_endpoint_auth_method))?t.token_endpoint_auth_method:e.length===0?r?"client_secret_basic":"none":r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function Kr(t,e,r,o){let{client_id:n,client_secret:i}=e;switch(t){case"client_secret_basic":Qr(n,i,r);return;case"client_secret_post":Yr(n,i,o);return;case"none":eo(n,o);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function Qr(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");let o=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${o}`)}function Yr(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function eo(t,e){e.set("client_id",t)}async function pr(t){let e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{let o=ar.parse(JSON.parse(r)),{error:n,error_description:i,error_uri:a}=o,s=dr[n]||W;return new s(i||"",a)}catch(o){let n=t instanceof Response?se(t,t.url):void 0,i=`${e?`HTTP ${e}: `:""}${n??`Invalid OAuth error response: ${o}. Raw body: ${r}`}`;return new W(i)}}function to(t,e){let[r,o]=[t,e];try{[r,o]=[new URL(t).href,new URL(e).href]}catch{}return r===o||r.endsWith("/")&&r.slice(0,-1)===o||o.endsWith("/")&&o.slice(0,-1)===r}function Qe(t,e){if(t)return typeof t.issuer!="string"?t.issuer==null?t:{...t,issuer:void 0}:to(t.issuer,e)?t:void 0}var ro=ir.omit({issuer:!0}),oo=cr.omit({issuer:!0});function fr(t,e){return new Error(`OAuth client information is bound to authorization server ${t.issuer} and is not presented to ${e}. Clear the stored client information, or correct \`expectedIssuer\`, if the authorization server has moved.`)}async function H(t,e){try{return await Xe(t,e)}catch(r){if(r instanceof G||r instanceof B)return await t.invalidateCredentials?.("all"),await Xe(t,e);if(r instanceof Z)return await t.invalidateCredentials?.("tokens"),await Xe(t,e);throw r}}async function Xe(t,{serverUrl:e,authorizationCode:r,scope:o,resourceMetadataUrl:n,fetchFn:i}){let a=await t.discoveryState?.(),s,l,d,h=n;if(!h&&a?.resourceMetadataUrl&&(h=new URL(a.resourceMetadataUrl)),a?.authorizationServerUrl){if(l=a.authorizationServerUrl,s=a.resourceMetadata,d=a.authorizationServerMetadata??await wr(l,{fetchFn:i}),!s)try{s=await _r(e,{resourceMetadataUrl:h},i)}catch{}(d!==a.authorizationServerMetadata||s!==a.resourceMetadata)&&await t.saveDiscoveryState?.({authorizationServerUrl:String(l),resourceMetadataUrl:h?.toString(),resourceMetadata:s,authorizationServerMetadata:d})}else{let C=await uo(e,{resourceMetadataUrl:h,fetchFn:i});l=C.authorizationServerUrl,d=C.authorizationServerMetadata,s=C.resourceMetadata,await t.saveDiscoveryState?.({authorizationServerUrl:String(l),resourceMetadataUrl:h?.toString(),resourceMetadata:s,authorizationServerMetadata:d})}let f=String(l),R=await no(e,t,s),w=R&&s&&!t.validateResourceURL?s.resource:R,S=o||s?.scopes_supported?.join(" ")||t.clientMetadata.scope,m=await Promise.resolve(t.clientInformation()),v=Qe(m,f),M=t.saveClientInformation!==void 0&&!!t.redirectUrl;if(m&&!v&&!M)throw fr(m,f);let A=v?.issuer==null?v:void 0,Y=async()=>{try{A&&await t.saveClientInformation?.({...A,issuer:f})}catch{}};if(!v){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let C=d?.client_id_metadata_document_supported===!0,I=t.clientMetadataUrl;if(I&&!so(I))throw new J(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${I}`);if(C&&I)v={client_id:I,issuer:f},await t.saveClientInformation?.(v);else{if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");v={...await wo(l,{metadata:d,clientMetadata:t.clientMetadata,scope:S,fetchFn:i}),issuer:f},await t.saveClientInformation(v)}}let Ne=!t.redirectUrl;if(r!==void 0||Ne){let C=await _o(t,l,{metadata:d,resource:w,authorizationCode:r,fetchFn:i});return await Y(),await t.saveTokens({...C,issuer:f}),"AUTHORIZED"}let p=Qe(await t.tokens(),f);if(p?.refresh_token&&p.issuer==null&&console.warn("[mcp-sdk] stored OAuth tokens have no 'issuer' property (saved by an earlier version, or by a provider that does not keep it) and are used as-is; make sure your OAuthClientProvider stores what saveTokens() and saveClientInformation() receive unchanged."),p?.refresh_token)try{let C=await fo(l,{metadata:d,clientInformation:v,refreshToken:p.refresh_token,resource:w,addClientAuthentication:t.addClientAuthentication,fetchFn:i});return await Y(),await t.saveTokens({...C,issuer:f}),"AUTHORIZED"}catch(C){if(!(!(C instanceof E)||C instanceof W))throw C}let u=t.state?await t.state():void 0,{authorizationUrl:y,codeVerifier:T}=await ho(l,{metadata:d,clientInformation:v,state:u,redirectUrl:t.redirectUrl,scope:S,resource:w});return await t.saveCodeVerifier(T),await t.redirectToAuthorization(y),"REDIRECT"}function so(t){if(!t)return!1;try{let e=new URL(t);return e.protocol==="https:"&&e.pathname!=="/"}catch{return!1}}async function no(t,e,r){let o=lr(t);if(e.validateResourceURL)return await e.validateResourceURL(o,r?.resource);if(r){if(!ur({requestedResource:o,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${o} (or origin)`);return new URL(r.resource)}}function ne(t){let e=t.headers.get("WWW-Authenticate");if(!e)return{};let[r,o]=e.split(" ");if(r.toLowerCase()!=="bearer"||!o)return{};let n=Ke(t,"resource_metadata")||void 0,i;if(n)try{i=new URL(n)}catch{}let a=Ke(t,"scope")||void 0,s=Ke(t,"error")||void 0;return{resourceMetadataUrl:i,scope:a,error:s}}function Ke(t,e){let r=t.headers.get("WWW-Authenticate");if(!r)return null;let o=new RegExp(`${e}=(?:"([^"]+)"|([^\\s,]+))`),n=r.match(o);return n?n[1]||n[2]:null}async function _r(t,e,r=fetch){let o=await co(t,"oauth-protected-resource",r,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!o||o.status===404)throw await o?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await o.body?.cancel(),new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return sr.parse(await o.json())}async function Ye(t,e,r=fetch){try{return await $(r)(t,{headers:e})}catch(o){if(o instanceof TypeError)return e?Ye(t,void 0,r):void 0;throw o}}function io(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function hr(t,e,r=fetch){return await Ye(t,{"MCP-Protocol-Version":e},r)}function ao(t,e){return!t||!t.ok&&t.status<500&&e!=="/"}async function co(t,e,r,o){let n=new URL(t),i=o?.protocolVersion??de,a;if(o?.metadataUrl)a=new URL(o.metadataUrl);else{let l=io(e,n.pathname);a=new URL(l,o?.metadataServerUrl??n),a.search=n.search}let s=await hr(a,i,r);if(!o?.metadataUrl&&ao(s,n.pathname)){let l=new URL(`/.well-known/${e}`,n);s=await hr(l,i,r)}return s}function lo(t){let e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",o=[];if(!r)return o.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),o.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),o;let n=e.pathname;return n.endsWith("/")&&(n=n.slice(0,-1)),o.push({url:new URL(`/.well-known/oauth-authorization-server${n}`,e.origin),type:"oauth"}),o.push({url:new URL(`/.well-known/openid-configuration${n}`,e.origin),type:"oidc"}),o.push({url:new URL(`${n}/.well-known/openid-configuration`,e.origin),type:"oidc"}),o}async function wr(t,{fetchFn:e=fetch,protocolVersion:r=de}={}){let o={"MCP-Protocol-Version":r,Accept:"application/json"},n=lo(t);for(let{url:i,type:a}of n){let s=await Ye(i,o,e);if(s){if(!s.ok){if(await s.body?.cancel(),s.status<500)continue;throw new Error(`HTTP ${s.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}return a==="oauth"?Ze.parse(await s.json()):nr.parse(await s.json())}}}async function uo(t,e){let r,o;try{r=await _r(t,{resourceMetadataUrl:e?.resourceMetadataUrl},e?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(o=r.authorization_servers[0])}catch{}o||(o=String(new URL("/",t)));let n=await wr(o,{fetchFn:e?.fetchFn});return{authorizationServerUrl:o,authorizationServerMetadata:n,resourceMetadata:r}}function mr(t){return typeof t=="string"?t:t.href}async function ho(t,{metadata:e,clientInformation:r,redirectUrl:o,scope:n,state:i,resource:a}){let s;if(e){if(s=new URL(e.authorization_endpoint),!e.response_types_supported.includes(Be))throw new Error(`Incompatible auth server: does not support response type ${Be}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(Je))throw new Error(`Incompatible auth server: does not support code challenge method ${Je}`)}else s=new URL("/authorize",t);let l=await Ge(),d=l.code_verifier,h=l.code_challenge;return s.searchParams.set("response_type",Be),s.searchParams.set("client_id",r.client_id),s.searchParams.set("code_challenge",h),s.searchParams.set("code_challenge_method",Je),s.searchParams.set("redirect_uri",String(o)),i&&s.searchParams.set("state",i),n&&s.searchParams.set("scope",n),n?.includes("offline_access")&&s.searchParams.append("prompt","consent"),a&&s.searchParams.set("resource",mr(a)),{authorizationUrl:s,codeVerifier:d}}function po(t,e,r){return new URLSearchParams({grant_type:"authorization_code",code:t,code_verifier:e,redirect_uri:String(r)})}async function gr(t,{metadata:e,tokenRequestParams:r,clientInformation:o,addClientAuthentication:n,resource:i,fetchFn:a}){let s=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t),l=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(i&&r.set("resource",mr(i)),n)await n(l,r,s,e);else if(o){let h=e?.token_endpoint_auth_methods_supported??[],f=Xr(o,h);Kr(f,o,l,r)}let d=await $(a??fetch)(s,{method:"POST",headers:l,body:r});if(!d.ok)throw await pr(d);return ro.parse(await d.json())}async function fo(t,{metadata:e,clientInformation:r,refreshToken:o,resource:n,addClientAuthentication:i,fetchFn:a}){let s=new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),l=await gr(t,{metadata:e,tokenRequestParams:s,clientInformation:r,addClientAuthentication:i,resource:n,fetchFn:a});return{refresh_token:o,...l}}async function _o(t,e,{metadata:r,resource:o,authorizationCode:n,fetchFn:i}={}){let a=async()=>{let h=await t.clientInformation(),f=Qe(h,String(e));if(h&&!f)throw fr(h,String(e));return f},s=await a(),l=t.clientMetadata.scope,d;if(t.prepareTokenRequest&&(d=await t.prepareTokenRequest(l)),!d){if(!n)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!t.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let h=await t.codeVerifier();d=po(n,h,t.redirectUrl)}return s??(s=await a()),gr(e,{metadata:r,tokenRequestParams:d,clientInformation:s,addClientAuthentication:t.addClientAuthentication,resource:o,fetchFn:i})}async function wo(t,{metadata:e,clientMetadata:r,scope:o,fetchFn:n}){let i;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(e.registration_endpoint)}else i=new URL("/register",t);let a=await $(n??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...o!==void 0?{scope:o}:{}})});if(!a.ok)throw await pr(a);return oo.parse(await a.json())}var Ee=class extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}},yr=10,mo=13,X=32;function et(t){}function Le(t){if(typeof t=="function")throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:e=et,onError:r=et,onRetry:o=et,onComment:n,maxBufferSize:i}=t,a=[],s=0,l=!0,d,h="",f=0,R,w=!1;function S(p){if(w)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(l&&(l=!1,p.charCodeAt(0)===239&&p.charCodeAt(1)===187&&p.charCodeAt(2)===191&&(p=p.slice(3))),a.length===0){let T=v(p);T!==""&&(a.push(T),s=T.length),m();return}if(p.indexOf(`
5
+ `)===-1&&p.indexOf("\r")===-1){a.push(p),s+=p.length,m();return}a.push(p);let u=a.join("");a.length=0,s=0;let y=v(u);y!==""&&(a.push(y),s=y.length),m()}function m(){i!==void 0&&(s+h.length<=i||(w=!0,a.length=0,s=0,d=void 0,h="",f=0,R=void 0,r(new Ee(`Buffered data exceeded max buffer size of ${i} characters`,{type:"max-buffer-size-exceeded"}))))}function v(p){let u=0;if(p.indexOf("\r")===-1){let y=p.indexOf(`
6
+ `,u);for(;y!==-1;){if(u===y){f>0&&e({id:d,event:R,data:h}),d=void 0,h="",f=0,R=void 0,u=y+1,y=p.indexOf(`
7
+ `,u);continue}let T=p.charCodeAt(u);if(vr(p,u,T)){let C=p.charCodeAt(u+5)===X?u+6:u+5,I=p.slice(C,y);if(f===0&&p.charCodeAt(y+1)===yr){e({id:d,event:R,data:I}),d=void 0,h="",R=void 0,u=y+2,y=p.indexOf(`
8
+ `,u);continue}h=f===0?I:`${h}
9
+ ${I}`,f++}else Cr(p,u,T)?R=p.slice(p.charCodeAt(u+6)===X?u+7:u+6,y)||void 0:M(p,u,y);u=y+1,y=p.indexOf(`
10
+ `,u)}return p.slice(u)}for(;u<p.length;){let y=p.indexOf("\r",u),T=p.indexOf(`
11
+ `,u),C=-1;if(y!==-1&&T!==-1?C=y<T?y:T:y!==-1?y===p.length-1?C=-1:C=y:T!==-1&&(C=T),C===-1)break;M(p,u,C),u=C+1,p.charCodeAt(u-1)===mo&&p.charCodeAt(u)===yr&&u++}return p.slice(u)}function M(p,u,y){if(u===y){Y();return}let T=p.charCodeAt(u);if(vr(p,u,T)){let ee=p.charCodeAt(u+5)===X?u+6:u+5,pt=p.slice(ee,y);h=f===0?pt:`${h}
12
+ ${pt}`,f++;return}if(Cr(p,u,T)){R=p.slice(p.charCodeAt(u+6)===X?u+7:u+6,y)||void 0;return}if(T===105&&p.charCodeAt(u+1)===100&&p.charCodeAt(u+2)===58){let ee=p.slice(p.charCodeAt(u+3)===X?u+4:u+3,y);ee.includes("\0")||(d=ee);return}if(T===58){if(n){let ee=p.slice(u,y);n(ee.slice(p.charCodeAt(u+1)===X?2:1))}return}let C=p.slice(u,y),I=C.indexOf(":");if(I===-1){A(C,"",C);return}let dt=C.slice(0,I),ht=C.charCodeAt(I+1)===X?2:1,xr=C.slice(I+ht);A(dt,xr,C)}function A(p,u,y){switch(p){case"event":R=u||void 0;break;case"data":h=f===0?u:`${h}
13
+ ${u}`,f++;break;case"id":u.includes("\0")||(d=u);break;case"retry":/^\d+$/.test(u)?o(parseInt(u,10)):r(new Ee(`Invalid \`retry\` value: "${u}"`,{type:"invalid-retry",value:u,line:y}));break;default:r(new Ee(`Unknown field "${p.length>20?`${p.slice(0,20)}\u2026`:p}"`,{type:"unknown-field",field:p,value:u,line:y}));break}}function Y(){f>0&&e({id:d,event:R,data:h}),d=void 0,h="",f=0,R=void 0}function Ne(p={}){if(p.consume&&a.length>0){let u=a.join("");M(u,0,u.length)}l=!0,d=void 0,h="",f=0,R=void 0,a.length=0,s=0,w=!1}return{feed:S,reset:Ne}}function vr(t,e,r){return r===100&&t.charCodeAt(e+1)===97&&t.charCodeAt(e+2)===116&&t.charCodeAt(e+3)===97&&t.charCodeAt(e+4)===58}function Cr(t,e,r){return r===101&&t.charCodeAt(e+1)===118&&t.charCodeAt(e+2)===101&&t.charCodeAt(e+3)===110&&t.charCodeAt(e+4)===116&&t.charCodeAt(e+5)===58}var $e=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:o,maxBufferSize:n}={}){let i;super({start(a){i=Le({onEvent:s=>{a.enqueue(s)},onError(s){typeof e=="function"&&e(s),(e==="terminate"||s.type==="max-buffer-size-exceeded")&&a.error(s)},onRetry:r,onComment:o,maxBufferSize:n})},transform(a){i.feed(a)}})}};var go={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},V=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},Rr=class{constructor(e,r){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Pe(r?.fetch,r?.requestInit),this._followRedirects=r?.redirectPolicy==="follow",this._followRedirects&&(this._fetch=oe(this._fetch),this._fetchWithInit=oe(this._fetchWithInit)),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??go}_unfollowedRedirect(e,r){let o=se(e,r);return o&&!this._followRedirects?`${o} (redirectPolicy: 'same-origin')`:o}async _authThenStart(){if(!this._authProvider)throw new k("No auth provider");let e;try{e=await H(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new k;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let o=await this._authProvider.tokens();o&&(e.Authorization=`Bearer ${o.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=re(this._requestInit?.headers);return new Headers({...e,...r})}async _startOrAuthSse(e){let{resumptionToken:r}=e;try{let o=await this._commonHeaders();o.set("Accept","text/event-stream"),r&&o.set("last-event-id",r);let n=this._fetch??fetch,i={method:"GET",headers:o,signal:this._abortController?.signal},a=await n(this._url,this._followRedirects?i:{...i,redirect:"manual"}),s=this._followRedirects?void 0:Me(n,this._url,i,a);if(s&&(a=await s),!a.ok){if(await a.body?.cancel(),a.status===401&&this._authProvider)return await this._authThenStart();if(a.status===405)return;throw new V(a.status,`Failed to open SSE stream: ${this._unfollowedRedirect(a,this._url)??a.statusText}`)}this._handleSseStream(a.body,e,!0)}catch(o){throw this.onerror?.(o),o}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,o=this._reconnectionOptions.reconnectionDelayGrowFactor,n=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(o,e),n)}_scheduleReconnection(e,r=0){let o=this._reconnectionOptions.maxRetries;if(r>=o){this.onerror?.(new Error(`Maximum reconnection attempts (${o}) exceeded.`));return}let n=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(i=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${i instanceof Error?i.message:String(i)}`)),this._scheduleReconnection(e,r+1)})},n)}_handleSseStream(e,r,o){if(!e)return;let{onresumptiontoken:n,replayMessageId:i}=r,a,s=!1,l=!1;(async()=>{try{let h=e.pipeThrough(new TextDecoderStream).pipeThrough(new $e({onRetry:w=>{this._serverRetryMs=w}})).getReader();for(;;){let{value:w,done:S}=await h.read();if(S)break;if(w.id&&(a=w.id,s=!0,n?.(w.id)),!!w.data&&(!w.event||w.event==="message"))try{let m=te.parse(JSON.parse(w.data));St(m)&&(l=!0,i!==void 0&&(m.id=i)),this.onmessage?.(m)}catch(m){this.onerror?.(m)}}(o||s)&&!l&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:n,replayMessageId:i},0)}catch(h){if(this.onerror?.(new Error(`SSE stream disconnected: ${h}`)),(o||s)&&!l&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:n,replayMessageId:i},0)}catch(w){this.onerror?.(new Error(`Failed to reconnect: ${w instanceof Error?w.message:String(w)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new k("No auth provider");if(await H(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new k("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,r){try{let{resumptionToken:o,onresumptiontoken:n}=r||{};if(o){this._startOrAuthSse({resumptionToken:o,replayMessageId:bt(e)?e.id:void 0}).catch(w=>this.onerror?.(w));return}let i=await this._commonHeaders();i.set("content-type","application/json"),i.set("accept","application/json, text/event-stream");let a={...this._requestInit,method:"POST",headers:i,body:JSON.stringify(e),signal:this._abortController?.signal},s=await $(this._fetch??fetch)(this._url,a),l=s.headers.get("mcp-session-id");if(l&&(this._sessionId=l),!s.ok){let w=await s.text().catch(()=>null);if(s.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new V(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:S,scope:m}=ne(s);if(this._resourceMetadataUrl=S,this._scope=m,await H(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new k;return this._hasCompletedAuthFlow=!0,this.send(e)}if(s.status===403&&this._authProvider){let{resourceMetadataUrl:S,scope:m,error:v}=ne(s);if(v==="insufficient_scope"){let M=s.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===M)throw new V(403,"Server returned 403 after trying upscoping");if(m&&(this._scope=m),S&&(this._resourceMetadataUrl=S),this._lastUpscopingHeader=M??void 0,await H(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new k;return this.send(e)}}throw new V(s.status,`Error POSTing to endpoint: ${this._unfollowedRedirect(s,this._url)??w}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,s.status===202){await s.body?.cancel(),Tt(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(w=>this.onerror?.(w));return}let h=(Array.isArray(e)?e:[e]).filter(w=>"method"in w&&"id"in w&&w.id!==void 0).length>0,f=s.headers.get("content-type"),R=er(f);if(h)if(R==="text/event-stream")this._handleSseStream(s.body,{onresumptiontoken:n},!1);else if(R==="application/json"){let w=await s.json(),S=Array.isArray(w)?w.map(m=>te.parse(m)):[te.parse(w)];for(let m of S)this.onmessage?.(m)}else throw await s.body?.cancel(),new V(-1,`Unexpected content type: ${f}`);else await s.body?.cancel()}catch(o){throw this.onerror?.(o),o}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},o=await $(this._fetch??fetch)(this._url,r);if(await o.body?.cancel(),!o.ok&&o.status!==405)throw new V(o.status,`Failed to terminate session: ${this._unfollowedRedirect(o,this._url)??o.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};var We=class extends Event{constructor(e,r){var o,n;super(e),this.code=(o=r?.code)!=null?o:void 0,this.message=(n=r?.message)!=null?n:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,o){return o(br(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(br(this),r)}};function yo(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function tt(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(tt).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${tt(t.cause)}`:t.message:`${t}`}function br(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var Er=t=>{throw TypeError(t)},lt=(t,e,r)=>e.has(t)||Er("Cannot "+r),g=(t,e,r)=>(lt(t,e,"read from private field"),r?r.call(t):e.get(t)),z=(t,e,r)=>e.has(t)?Er("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),b=(t,e,r,o)=>(lt(t,e,"write to private field"),e.set(t,r),r),N=(t,e,r)=>(lt(t,e,"access private method"),r),P,K,ie,qe,He,ze,le,Ue,D,ae,ue,ce,Te,L,rt,ot,st,Sr,nt,it,xe,at,ct,Q=class extends EventTarget{constructor(e,r){var o,n;super(),z(this,L),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,z(this,P),z(this,K),z(this,ie),z(this,qe),z(this,He),z(this,ze),z(this,le),z(this,Ue,null),z(this,D),z(this,ae),z(this,ue,null),z(this,ce,null),z(this,Te,null),z(this,ot,async i=>{var a;g(this,ae).reset();let{body:s,redirected:l,status:d,headers:h}=i;if(d===204){N(this,L,xe).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(l?b(this,ie,new URL(i.url)):b(this,ie,void 0),d!==200){N(this,L,xe).call(this,`Non-200 status code (${d})`,d);return}if(!(h.get("content-type")||"").startsWith("text/event-stream")){N(this,L,xe).call(this,'Invalid content type, expected "text/event-stream"',d);return}if(g(this,P)===this.CLOSED)return;b(this,P,this.OPEN);let f=new Event("open");if((a=g(this,Te))==null||a.call(this,f),this.dispatchEvent(f),typeof s!="object"||!s||!("getReader"in s)){N(this,L,xe).call(this,"Invalid response body, expected a web ReadableStream",d),this.close();return}let R=new TextDecoder,w=s.getReader(),S=!0;do{let{done:m,value:v}=await w.read();v&&g(this,ae).feed(R.decode(v,{stream:!m})),m&&(S=!1,g(this,ae).reset(),N(this,L,at).call(this))}while(S)}),z(this,st,i=>{b(this,D,void 0),!(i.name==="AbortError"||i.type==="aborted")&&N(this,L,at).call(this,tt(i))}),z(this,nt,i=>{typeof i.id=="string"&&b(this,Ue,i.id);let a=new MessageEvent(i.event||"message",{data:i.data,origin:g(this,ie)?g(this,ie).origin:g(this,K).origin,lastEventId:i.id||""});g(this,ce)&&(!i.event||i.event==="message")&&g(this,ce).call(this,a),this.dispatchEvent(a)}),z(this,it,i=>{b(this,ze,i)}),z(this,ct,()=>{b(this,le,void 0),g(this,P)===this.CONNECTING&&N(this,L,rt).call(this)});try{if(e instanceof URL)b(this,K,e);else if(typeof e=="string")b(this,K,new URL(e,vo()));else throw new Error("Invalid URL")}catch{throw yo("An invalid or illegal string was specified")}b(this,ae,Le({onEvent:g(this,nt),onRetry:g(this,it)})),b(this,P,this.CONNECTING),b(this,ze,3e3),b(this,He,(o=r?.fetch)!=null?o:globalThis.fetch),b(this,qe,(n=r?.withCredentials)!=null?n:!1),N(this,L,rt).call(this)}get readyState(){return g(this,P)}get url(){return g(this,K).href}get withCredentials(){return g(this,qe)}get onerror(){return g(this,ue)}set onerror(e){b(this,ue,e)}get onmessage(){return g(this,ce)}set onmessage(e){b(this,ce,e)}get onopen(){return g(this,Te)}set onopen(e){b(this,Te,e)}addEventListener(e,r,o){let n=r;super.addEventListener(e,n,o)}removeEventListener(e,r,o){let n=r;super.removeEventListener(e,n,o)}close(){g(this,le)&&clearTimeout(g(this,le)),g(this,P)!==this.CLOSED&&(g(this,D)&&g(this,D).abort(),b(this,P,this.CLOSED),b(this,D,void 0))}};P=new WeakMap,K=new WeakMap,ie=new WeakMap,qe=new WeakMap,He=new WeakMap,ze=new WeakMap,le=new WeakMap,Ue=new WeakMap,D=new WeakMap,ae=new WeakMap,ue=new WeakMap,ce=new WeakMap,Te=new WeakMap,L=new WeakSet,rt=function(){b(this,P,this.CONNECTING),b(this,D,new AbortController),g(this,He)(g(this,K),N(this,L,Sr).call(this)).then(g(this,ot)).catch(g(this,st))},ot=new WeakMap,st=new WeakMap,Sr=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...g(this,Ue)?{"Last-Event-ID":g(this,Ue)}:void 0},cache:"no-store",signal:(t=g(this,D))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},nt=new WeakMap,it=new WeakMap,xe=function(t,e){var r;g(this,P)!==this.CLOSED&&b(this,P,this.CLOSED);let o=new We("error",{code:e,message:t});(r=g(this,ue))==null||r.call(this,o),this.dispatchEvent(o)},at=function(t,e){var r;if(g(this,P)===this.CLOSED)return;b(this,P,this.CONNECTING);let o=new We("error",{code:e,message:t});(r=g(this,ue))==null||r.call(this,o),this.dispatchEvent(o),b(this,le,setTimeout(g(this,ct),g(this,ze)))},ct=new WeakMap,Q.CONNECTING=0,Q.OPEN=1,Q.CLOSED=2;function vo(){let t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}var ut=class extends Error{constructor(e,r,o){super(`SSE error: ${r}`),this.code=e,this.event=o}},Tr=class{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Pe(r?.fetch,r?.requestInit),this._followRedirects=r?.redirectPolicy==="follow",this._followRedirects&&(this._fetch=oe(this._fetch),this._fetchWithInit=oe(this._fetchWithInit))}_unfollowedRedirect(e,r){let o=se(e,r);return o&&!this._followRedirects?`${o} (redirectPolicy: 'same-origin')`:o}async _authThenStart(){if(!this._authProvider)throw new k("No auth provider");let e;try{e=await H(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new k;return await this._startOrAuth()}async _commonHeaders(){let e={};if(this._authProvider){let o=await this._authProvider.tokens();o&&(e.Authorization=`Bearer ${o.access_token}`)}this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=re(this._requestInit?.headers);return new Headers({...e,...r})}_startOrAuth(){let e=this?._eventSourceInit?.fetch??this._fetch??fetch,r=this._followRedirects?e:$(e),o;return new Promise((n,i)=>{this._eventSource=new Q(this._url.href,{...this._eventSourceInit,fetch:async(a,s)=>{let l=await this._commonHeaders();l.set("Accept","text/event-stream");let d=await r(a,{...s,headers:l});if(o=this._unfollowedRedirect(d,a),d.status===401&&d.headers.has("www-authenticate")){let{resourceMetadataUrl:h,scope:f}=ne(d);this._resourceMetadataUrl=h,this._scope=f}return d}}),this._abortController=new AbortController,this._eventSource.onerror=a=>{if(a.code===401&&this._authProvider){this._authThenStart().then(n,i);return}let s=new ut(a.code,o??a.message,a);i(s),this.onerror?.(s)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",a=>{let s=a;try{if(this._endpoint=new URL(s.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(l){i(l),this.onerror?.(l),this.close();return}n()}),this._eventSource.onmessage=a=>{let s=a,l;try{l=te.parse(JSON.parse(s.data))}catch(d){this.onerror?.(d);return}this.onmessage?.(l)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new k("No auth provider");if(await H(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new k("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(e){if(!this._endpoint)throw new Error("Not connected");try{let r=await this._commonHeaders();r.set("content-type","application/json");let o={...this._requestInit,method:"POST",headers:r,body:JSON.stringify(e),signal:this._abortController?.signal},n=await $(this._fetch??fetch)(this._endpoint,o);if(!n.ok){let i=await n.text().catch(()=>null);if(n.status===401&&this._authProvider){let{resourceMetadataUrl:a,scope:s}=ne(n);if(this._resourceMetadataUrl=a,this._scope=s,await H(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new k;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${n.status}): ${this._unfollowedRedirect(n,this._endpoint)??i}`)}await n.body?.cancel()}catch(r){throw this.onerror?.(r),r}}setProtocolVersion(e){this._protocolVersion=e}};function Co(t,e){let r=new Headers(t);for(let[o,n]of new Headers(e).entries())r.set(o,n);return r}function Ro(t,e){let r=t.headers.get("location");return r?new URL(r,e):null}async function bo(t){try{await t.body?.cancel()}catch{}}function ps(t,e=fetch){return async(r,o)=>{let n=new Request(r,o),i=new Request(n,{headers:Co(t,n.headers),redirect:"manual"}),a=new URL(i.url),s=await e(i),l=Ro(s,a);if(s.status<300||s.status>=400||!l)return s;throw await bo(s),new Error(`MCP redirect rejected: ${a.origin} -> ${l.origin}`)}}export{Bt as a,Rr as b,Tr as c,ps as d};
14
+ /*! Bundled license information:
15
+
16
+ content-type/index.js:
17
+ (*!
18
+ * content-type
19
+ * Copyright(c) 2015 Douglas Christopher Wilson
20
+ * MIT Licensed
21
+ *)
22
+ */
@@ -0,0 +1,5 @@
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{e as h}from"./chunk-JGUEIW2W.js";import{b as m,k as l}from"./chunk-T54CZKNJ.js";import*as o from"node:fs";import*as a from"node:path";var d=78,f=a.join(l,"app-stopped.json");function A(n,t,r,e){return r==="EADDRINUSE"?`Port ${n} is already in use by another process. Set CORTEX_UI_PORT in ${e} to a free port, then run \`cortex daemon restart\`.`:`Cannot listen on ${t}:${n} (${r??"unknown error"}). Check CORTEX_UI_PORT and CORTEX_UI_HOST in ${e}.`}function R(n,t=f){try{o.mkdirSync(a.dirname(t),{recursive:!0}),o.writeFileSync(t,JSON.stringify(n,null,2)+`
5
+ `)}catch{}}function _(n=f){try{let t=JSON.parse(o.readFileSync(n,"utf8"));return t&&typeof t.message=="string"?t:null}catch{return null}}function y(n=f){try{o.unlinkSync(n)}catch{}}import*as i from"path";var x="@cortex-agent/server";function O(n=process.execPath,t=m,r=process.platform){let e=r==="win32"?i.win32:i.posix,p=[e.dirname(n)],s=h(t,x,r);return s&&p.push(r==="win32"?s:e.join(s,"bin")),p}function w(n,t,r=process.platform){let e=r==="win32"?i.win32:i.posix,p=c=>{let u=e.normalize(c).replace(/[\\/]+$/,"");return r==="win32"?u.toLowerCase():u},s=n.split(e.delimiter).filter(Boolean),S=new Set(s.map(p));return[...t.filter(c=>!S.has(p(c))),...s].join(e.delimiter)}function C(){process.env.PATH=w(process.env.PATH??"",O())}export{d as a,A as b,R as c,_ as d,y as e,O as f,C as g};
@@ -1,4 +1,4 @@
1
1
  import { createRequire as __cortexCreateRequire } from 'node:module';
2
2
  const require = __cortexCreateRequire(import.meta.url);
3
3
  const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as u}from"./chunk-5M4PFLRW.js";import{d as n,z as p}from"./chunk-J5DVLUKY.js";import{existsSync as s}from"node:fs";import*as o from"node:path";import{pathToFileURL as l}from"node:url";var a=o.join(n,"hooks"),f=o.join(a,"overlay","register.mjs");function h(){return{user:p,builtin:u()?a:null}}function m(e,r=h()){let t=o.join(r.user,e);if(s(t)||!r.builtin)return{path:t,user:!0};let i=o.join(r.builtin,e);return s(i)?{path:i,user:!1}:{path:t,user:!0}}function O(e,r=h()){let t=m(e,r);return!t.user||!r.builtin?[t.path]:["--import",l(f).href,t.path]}export{h as a,m as b,O as c};
4
+ import{a as u}from"./chunk-5M4PFLRW.js";import{A as p,c as n}from"./chunk-T54CZKNJ.js";import{existsSync as s}from"node:fs";import*as o from"node:path";import{pathToFileURL as l}from"node:url";var a=o.join(n,"hooks"),f=o.join(a,"overlay","register.mjs");function h(){return{user:p,builtin:u()?a:null}}function m(e,r=h()){let t=o.join(r.user,e);if(s(t)||!r.builtin)return{path:t,user:!0};let i=o.join(r.builtin,e);return s(i)?{path:i,user:!1}:{path:t,user:!0}}function O(e,r=h()){let t=m(e,r);return!t.user||!r.builtin?[t.path]:["--import",l(f).href,t.path]}export{a,h as b,m as c,O as d};
@@ -1,4 +1,4 @@
1
1
  import { createRequire as __cortexCreateRequire } from 'node:module';
2
2
  const require = __cortexCreateRequire(import.meta.url);
3
3
  const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as e,b as t,c as o}from"./chunk-OISO5JXB.js";import"./chunk-WHC7AYZD.js";export{t as CheckResult,o as RouteResponse,e as Status};
4
+ function n(t){if(typeof t!="string"||!URL.canParse(t))return null;let r=new URL(t);return r.protocol==="https:"||r.protocol==="http:"?r.href:null}export{n as a};
@@ -0,0 +1,10 @@
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 p,c as S}from"./chunk-WHC7AYZD.js";var T=S((ur,qe)=>{"use strict";var Fe=["nodebuffer","arraybuffer","fragments"],We=typeof Blob<"u";We&&Fe.push("blob");qe.exports={BINARY_TYPES:Fe,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:We,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Y=S((dr,se)=>{"use strict";var{EMPTY_BUFFER:jt}=T(),pe=Buffer[Symbol.species];function Vt(t,e){if(t.length===0)return jt;if(t.length===1)return t[0];let s=Buffer.allocUnsafe(e),r=0;for(let i=0;i<t.length;i++){let n=t[i];s.set(n,r),r+=n.length}return r<e?new pe(s.buffer,s.byteOffset,r):s}function Ge(t,e,s,r,i){for(let n=0;n<i;n++)s[r+n]=t[n]^e[n&3]}function $e(t,e){for(let s=0;s<t.length;s++)t[s]^=e[s&3]}function zt(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function ge(t){if(ge.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new pe(t):ArrayBuffer.isView(t)?e=new pe(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),ge.readOnly=!1),e}se.exports={concat:Vt,mask:Ge,toArrayBuffer:zt,toBuffer:ge,unmask:$e};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=p("bufferutil");se.exports.mask=function(e,s,r,i,n){n<48?Ge(e,s,r,i,n):t.mask(e,s,r,i,n)},se.exports.unmask=function(e,s){e.length<32?$e(e,s):t.unmask(e,s)}}catch{}});var ze=S((_r,Ve)=>{"use strict";var je=Symbol("kDone"),ye=Symbol("kRun"),xe=class{constructor(e){this[je]=()=>{this.pending--,this[ye]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[ye]()}[ye](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[je])}}};Ve.exports=xe});var X=S((mr,Xe)=>{"use strict";var K=p("zlib"),He=Y(),Ht=ze(),{kStatusCode:Ye}=T(),Yt=Buffer[Symbol.species],Kt=Buffer.from([0,0,255,255]),ie=Symbol("permessage-deflate"),k=Symbol("total-length"),F=Symbol("callback"),N=Symbol("buffers"),W=Symbol("error"),re,Se=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!re){let s=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;re=new Ht(s)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[F];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let s=this._options,r=e.find(i=>!(s.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(s.serverMaxWindowBits===!1||typeof s.serverMaxWindowBits=="number"&&s.serverMaxWindowBits>i.server_max_window_bits)||typeof s.clientMaxWindowBits=="number"&&(typeof i.client_max_window_bits=="number"?s.clientMaxWindowBits>i.client_max_window_bits:!i.client_max_window_bits)));if(!r)throw new Error("None of the extension offers can be accepted");return s.serverNoContextTakeover&&(r.server_no_context_takeover=!0),s.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof s.serverMaxWindowBits=="number"&&(r.server_max_window_bits=s.serverMaxWindowBits),typeof s.clientMaxWindowBits=="number"?r.client_max_window_bits=s.clientMaxWindowBits:(r.client_max_window_bits===!0||s.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let s=e[0];if(this._options.clientNoContextTakeover===!1&&s.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!s.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(s.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&s.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return s}normalizeParams(e){return e.forEach(s=>{Object.keys(s).forEach(r=>{let i=s[r];if(i.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(i=i[0],r==="client_max_window_bits"){if(i!==!0){let n=+i;if(!Number.isInteger(n)||n<8||n>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=n}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else if(r==="server_max_window_bits"){let n=+i;if(!Number.isInteger(n)||n<8||n>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=n}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(i!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else throw new Error(`Unknown parameter "${r}"`);s[r]=i})}),e}decompress(e,s,r){re.add(i=>{this._decompress(e,s,(n,o)=>{i(),r(n,o)})})}compress(e,s,r){re.add(i=>{this._compress(e,s,(n,o)=>{i(),r(n,o)})})}_decompress(e,s,r){let i=this._isServer?"client":"server";if(!this._inflate){let n=`${i}_max_window_bits`,o=typeof this.params[n]!="number"?K.Z_DEFAULT_WINDOWBITS:this.params[n];this._inflate=K.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[ie]=this,this._inflate[k]=0,this._inflate[N]=[],this._inflate.on("error",Zt),this._inflate.on("data",Ke)}this._inflate[F]=r,this._inflate.write(e),s&&this._inflate.write(Kt),this._inflate.flush(()=>{let n=this._inflate[W];if(n){this._inflate.close(),this._inflate=null,r(n);return}let o=He.concat(this._inflate[N],this._inflate[k]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[k]=0,this._inflate[N]=[],s&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,s,r){let i=this._isServer?"server":"client";if(!this._deflate){let n=`${i}_max_window_bits`,o=typeof this.params[n]!="number"?K.Z_DEFAULT_WINDOWBITS:this.params[n];this._deflate=K.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[k]=0,this._deflate[N]=[],this._deflate.on("data",Xt)}this._deflate[F]=r,this._deflate.write(e),this._deflate.flush(K.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let n=He.concat(this._deflate[N],this._deflate[k]);s&&(n=new Yt(n.buffer,n.byteOffset,n.length-4)),this._deflate[F]=null,this._deflate[k]=0,this._deflate[N]=[],s&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),r(null,n)})}};Xe.exports=Se;function Xt(t){this[N].push(t),this[k]+=t.length}function Ke(t){if(this[k]+=t.length,this[ie]._maxPayload<1||this[k]<=this[ie]._maxPayload){this[N].push(t);return}this[W]=new RangeError("Max payload size exceeded"),this[W].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[W][Ye]=1009,this.removeListener("data",Ke),this.reset()}function Zt(t){if(this[ie]._inflate=null,this[W]){this[F](this[W]);return}t[Ye]=1007,this[F](t)}});var q=S((pr,ne)=>{"use strict";var{isUtf8:Ze}=p("buffer"),{hasBlob:Qt}=T(),Jt=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function es(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Ee(t){let e=t.length,s=0;for(;s<e;)if((t[s]&128)===0)s++;else if((t[s]&224)===192){if(s+1===e||(t[s+1]&192)!==128||(t[s]&254)===192)return!1;s+=2}else if((t[s]&240)===224){if(s+2>=e||(t[s+1]&192)!==128||(t[s+2]&192)!==128||t[s]===224&&(t[s+1]&224)===128||t[s]===237&&(t[s+1]&224)===160)return!1;s+=3}else if((t[s]&248)===240){if(s+3>=e||(t[s+1]&192)!==128||(t[s+2]&192)!==128||(t[s+3]&192)!==128||t[s]===240&&(t[s+1]&240)===128||t[s]===244&&t[s+1]>143||t[s]>244)return!1;s+=4}else return!1;return!0}function ts(t){return Qt&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}ne.exports={isBlob:ts,isValidStatusCode:es,isValidUTF8:Ee,tokenChars:Jt};if(Ze)ne.exports.isValidUTF8=function(t){return t.length<24?Ee(t):Ze(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=p("utf-8-validate");ne.exports.isValidUTF8=function(e){return e.length<32?Ee(e):t(e)}}catch{}});var nt=S((gr,it)=>{"use strict";var{Writable:ss}=p("stream"),Qe=X(),{BINARY_TYPES:rs,EMPTY_BUFFER:Je,kStatusCode:is,kWebSocket:ns}=T(),{concat:ve,toArrayBuffer:os,unmask:as}=Y(),{isValidStatusCode:fs,isValidUTF8:et}=q(),oe=Buffer[Symbol.species],v=0,tt=1,st=2,rt=3,be=4,we=5,ae=6,Oe=class extends ss{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||rs[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[ns]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=v}_write(e,s,r){if(this._opcode===8&&this._state==v)return r();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){r(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new oe(r.buffer,r.byteOffset+e,r.length-e),new oe(r.buffer,r.byteOffset,e)}let s=Buffer.allocUnsafe(e);do{let r=this._buffers[0],i=s.length-e;e>=r.length?s.set(this._buffers.shift(),i):(s.set(new Uint8Array(r.buffer,r.byteOffset,e),i),this._buffers[0]=new oe(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return s}startLoop(e){this._loop=!0;do switch(this._state){case v:this.getInfo(e);break;case tt:this.getPayloadLength16(e);break;case st:this.getPayloadLength64(e);break;case rt:this.getMask();break;case be:this.getData(e);break;case we:case ae:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let s=this.consume(2);if((s[0]&48)!==0){let i=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(i);return}let r=(s[0]&64)===64;if(r&&!this._extensions[Qe.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._fin=(s[0]&128)===128,this._opcode=s[0]&15,this._payloadLength=s[1]&127,this._opcode===0){if(r){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(!this._fragmented){let i=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let i=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(i);return}if(r){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let i=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(i);return}}else{let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(s[1]&128)===128,this._isServer){if(!this._masked){let i=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(i);return}}else if(this._masked){let i=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(i);return}this._payloadLength===126?this._state=tt:this._payloadLength===127?this._state=st:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let s=this.consume(8),r=s.readUInt32BE(0);if(r>Math.pow(2,21)-1){let i=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(i);return}this._payloadLength=r*Math.pow(2,32)+s.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let s=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(s);return}this._masked?this._state=rt:this._state=be}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=be}getData(e){let s=Je;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}s=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&as(s,this._mask)}if(this._opcode>7){this.controlMessage(s,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let r=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(r);return}if(this._compressed){this._state=we,this.decompress(s,e);return}s.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(s)),this.dataMessage(e)}decompress(e,s){this._extensions[Qe.extensionName].decompress(e,this._fin,(i,n)=>{if(i)return s(i);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");s(o);return}this._fragments.push(n)}this.dataMessage(s),this._state===v&&this.startLoop(s)})}dataMessage(e){if(!this._fin){this._state=v;return}let s=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=ve(r,s):this._binaryType==="arraybuffer"?i=os(ve(r,s)):this._binaryType==="blob"?i=new Blob(r):i=r,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=v):(this._state=ae,setImmediate(()=>{this.emit("message",i,!0),this._state=v,this.startLoop(e)}))}else{let i=ve(r,s);if(!this._skipUTF8Validation&&!et(i)){let n=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(n);return}this._state===we||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=v):(this._state=ae,setImmediate(()=>{this.emit("message",i,!1),this._state=v,this.startLoop(e)}))}}controlMessage(e,s){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Je),this.end();else{let r=e.readUInt16BE(0);if(!fs(r)){let n=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");s(n);return}let i=new oe(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!et(i)){let n=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");s(n);return}this._loop=!1,this.emit("conclude",r,i),this.end()}this._state=v;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=v):(this._state=ae,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=v,this.startLoop(s)}))}createError(e,s,r,i,n){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${s}`:s);return Error.captureStackTrace(o,this.createError),o.code=n,o[is]=i,o}};it.exports=Oe});var lt=S((xr,ft)=>{"use strict";var{Duplex:yr}=p("stream"),{randomFillSync:ls}=p("crypto"),{types:{isUint8Array:hs}}=p("util"),ot=X(),{EMPTY_BUFFER:cs,kWebSocket:us,NOOP:ds}=T(),{isBlob:G,isValidStatusCode:_s}=q(),{mask:at,toBuffer:P}=Y(),b=Symbol("kByteLength"),ms=Buffer.alloc(4),fe=8*1024,R,$=fe,w=0,ps=1,gs=2,Te=class t{constructor(e,s,r){this._extensions=s||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=w,this.onerror=ds,this[us]=void 0}static frame(e,s){let r,i=!1,n=2,o=!1;s.mask&&(r=s.maskBuffer||ms,s.generateMask?s.generateMask(r):($===fe&&(R===void 0&&(R=Buffer.alloc(fe)),ls(R,0,fe),$=0),r[0]=R[$++],r[1]=R[$++],r[2]=R[$++],r[3]=R[$++]),o=(r[0]|r[1]|r[2]|r[3])===0,n=6);let f;typeof e=="string"?(!s.mask||o)&&s[b]!==void 0?f=s[b]:(e=Buffer.from(e),f=e.length):(f=e.length,i=s.mask&&s.readOnly&&!o);let l=f;f>=65536?(n+=8,l=127):f>125&&(n+=2,l=126);let a=Buffer.allocUnsafe(i?f+n:n);return a[0]=s.fin?s.opcode|128:s.opcode,s.rsv1&&(a[0]|=64),a[1]=l,l===126?a.writeUInt16BE(f,2):l===127&&(a[2]=a[3]=0,a.writeUIntBE(f,4,6)),s.mask?(a[1]|=128,a[n-4]=r[0],a[n-3]=r[1],a[n-2]=r[2],a[n-1]=r[3],o?[a,e]:i?(at(e,r,a,n,f),[a]):(at(e,r,e,0,f),[a,e])):[a,e]}close(e,s,r,i){let n;if(e===void 0)n=cs;else{if(typeof e!="number"||!_s(e))throw new TypeError("First argument must be a valid error code number");if(s===void 0||!s.length)n=Buffer.allocUnsafe(2),n.writeUInt16BE(e,0);else{let f=Buffer.byteLength(s);if(f>123)throw new RangeError("The message must not be greater than 123 bytes");if(n=Buffer.allocUnsafe(2+f),n.writeUInt16BE(e,0),typeof s=="string")n.write(s,2);else if(hs(s))n.set(s,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[b]:n.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==w?this.enqueue([this.dispatch,n,!1,o,i]):this.sendFrame(t.frame(n,o),i)}ping(e,s,r){let i,n;if(typeof e=="string"?(i=Buffer.byteLength(e),n=!1):G(e)?(i=e.size,n=!1):(e=P(e),i=e.length,n=P.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[b]:i,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:9,readOnly:n,rsv1:!1};G(e)?this._state!==w?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==w?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}pong(e,s,r){let i,n;if(typeof e=="string"?(i=Buffer.byteLength(e),n=!1):G(e)?(i=e.size,n=!1):(e=P(e),i=e.length,n=P.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[b]:i,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:10,readOnly:n,rsv1:!1};G(e)?this._state!==w?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==w?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,s,r){let i=this._extensions[ot.extensionName],n=s.binary?2:1,o=s.compress,f,l;typeof e=="string"?(f=Buffer.byteLength(e),l=!1):G(e)?(f=e.size,l=!1):(e=P(e),f=e.length,l=P.readOnly),this._firstFragment?(this._firstFragment=!1,o&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=f>=i._threshold),this._compress=o):(o=!1,n=0),s.fin&&(this._firstFragment=!0);let a={[b]:f,fin:s.fin,generateMask:this._generateMask,mask:s.mask,maskBuffer:this._maskBuffer,opcode:n,readOnly:l,rsv1:o};G(e)?this._state!==w?this.enqueue([this.getBlobData,e,this._compress,a,r]):this.getBlobData(e,this._compress,a,r):this._state!==w?this.enqueue([this.dispatch,e,this._compress,a,r]):this.dispatch(e,this._compress,a,r)}getBlobData(e,s,r,i){this._bufferedBytes+=r[b],this._state=gs,e.arrayBuffer().then(n=>{if(this._socket.destroyed){let f=new Error("The socket was closed while the blob was being read");process.nextTick(ke,this,f,i);return}this._bufferedBytes-=r[b];let o=P(n);s?this.dispatch(o,s,r,i):(this._state=w,this.sendFrame(t.frame(o,r),i),this.dequeue())}).catch(n=>{process.nextTick(ys,this,n,i)})}dispatch(e,s,r,i){if(!s){this.sendFrame(t.frame(e,r),i);return}let n=this._extensions[ot.extensionName];this._bufferedBytes+=r[b],this._state=ps,n.compress(e,r.fin,(o,f)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");ke(this,l,i);return}this._bufferedBytes-=r[b],this._state=w,r.readOnly=!1,this.sendFrame(t.frame(f,r),i),this.dequeue()})}dequeue(){for(;this._state===w&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][b],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][b],this._queue.push(e)}sendFrame(e,s){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],s),this._socket.uncork()):this._socket.write(e[0],s)}};ft.exports=Te;function ke(t,e,s){typeof s=="function"&&s(e);for(let r=0;r<t._queue.length;r++){let i=t._queue[r],n=i[i.length-1];typeof n=="function"&&n(e)}}function ys(t,e,s){ke(t,e,s),t.onerror(e)}});var Ce=S((Sr,ht)=>{"use strict";var{tokenChars:Z}=q();function O(t,e,s){t[e]===void 0?t[e]=[s]:t[e].push(s)}function xs(t){let e=Object.create(null),s=Object.create(null),r=!1,i=!1,n=!1,o,f,l=-1,a=-1,h=-1,c=0;for(;c<t.length;c++)if(a=t.charCodeAt(c),o===void 0)if(h===-1&&Z[a]===1)l===-1&&(l=c);else if(c!==0&&(a===32||a===9))h===-1&&l!==-1&&(h=c);else if(a===59||a===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${c}`);h===-1&&(h=c);let g=t.slice(l,h);a===44?(O(e,g,s),s=Object.create(null)):o=g,l=h=-1}else throw new SyntaxError(`Unexpected character at index ${c}`);else if(f===void 0)if(h===-1&&Z[a]===1)l===-1&&(l=c);else if(a===32||a===9)h===-1&&l!==-1&&(h=c);else if(a===59||a===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${c}`);h===-1&&(h=c),O(s,t.slice(l,h),!0),a===44&&(O(e,o,s),s=Object.create(null),o=void 0),l=h=-1}else if(a===61&&l!==-1&&h===-1)f=t.slice(l,c),l=h=-1;else throw new SyntaxError(`Unexpected character at index ${c}`);else if(i){if(Z[a]!==1)throw new SyntaxError(`Unexpected character at index ${c}`);l===-1?l=c:r||(r=!0),i=!1}else if(n)if(Z[a]===1)l===-1&&(l=c);else if(a===34&&l!==-1)n=!1,h=c;else if(a===92)i=!0;else throw new SyntaxError(`Unexpected character at index ${c}`);else if(a===34&&t.charCodeAt(c-1)===61)n=!0;else if(h===-1&&Z[a]===1)l===-1&&(l=c);else if(l!==-1&&(a===32||a===9))h===-1&&(h=c);else if(a===59||a===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${c}`);h===-1&&(h=c);let g=t.slice(l,h);r&&(g=g.replace(/\\/g,""),r=!1),O(s,f,g),a===44&&(O(e,o,s),s=Object.create(null),o=void 0),f=void 0,l=h=-1}else throw new SyntaxError(`Unexpected character at index ${c}`);if(l===-1||n||a===32||a===9)throw new SyntaxError("Unexpected end of input");h===-1&&(h=c);let _=t.slice(l,h);return o===void 0?O(e,_,s):(f===void 0?O(s,_,!0):r?O(s,f,_.replace(/\\/g,"")):O(s,f,_),O(e,o,s)),e}function Ss(t){return Object.keys(t).map(e=>{let s=t[e];return Array.isArray(s)||(s=[s]),s.map(r=>[e].concat(Object.keys(r).map(i=>{let n=r[i];return Array.isArray(n)||(n=[n]),n.map(o=>o===!0?i:`${i}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}ht.exports={format:Ss,parse:xs}});var xt=S((Er,yt)=>{"use strict";var{kForOnEventAttribute:Q,kListener:Le}=T(),ct=Symbol("kCode"),ut=Symbol("kData"),dt=Symbol("kError"),_t=Symbol("kMessage"),mt=Symbol("kReason"),j=Symbol("kTarget"),pt=Symbol("kType"),gt=Symbol("kWasClean"),C=class{constructor(e){this[j]=null,this[pt]=e}get target(){return this[j]}get type(){return this[pt]}};Object.defineProperty(C.prototype,"target",{enumerable:!0});Object.defineProperty(C.prototype,"type",{enumerable:!0});var U=class extends C{constructor(e,s={}){super(e),this[ct]=s.code===void 0?0:s.code,this[mt]=s.reason===void 0?"":s.reason,this[gt]=s.wasClean===void 0?!1:s.wasClean}get code(){return this[ct]}get reason(){return this[mt]}get wasClean(){return this[gt]}};Object.defineProperty(U.prototype,"code",{enumerable:!0});Object.defineProperty(U.prototype,"reason",{enumerable:!0});Object.defineProperty(U.prototype,"wasClean",{enumerable:!0});var V=class extends C{constructor(e,s={}){super(e),this[dt]=s.error===void 0?null:s.error,this[_t]=s.message===void 0?"":s.message}get error(){return this[dt]}get message(){return this[_t]}};Object.defineProperty(V.prototype,"error",{enumerable:!0});Object.defineProperty(V.prototype,"message",{enumerable:!0});var J=class extends C{constructor(e,s={}){super(e),this[ut]=s.data===void 0?null:s.data}get data(){return this[ut]}};Object.defineProperty(J.prototype,"data",{enumerable:!0});var Es={addEventListener(t,e,s={}){for(let i of this.listeners(t))if(!s[Q]&&i[Le]===e&&!i[Q])return;let r;if(t==="message")r=function(n,o){let f=new J("message",{data:o?n:n.toString()});f[j]=this,le(e,this,f)};else if(t==="close")r=function(n,o){let f=new U("close",{code:n,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});f[j]=this,le(e,this,f)};else if(t==="error")r=function(n){let o=new V("error",{error:n,message:n.message});o[j]=this,le(e,this,o)};else if(t==="open")r=function(){let n=new C("open");n[j]=this,le(e,this,n)};else return;r[Q]=!!s[Q],r[Le]=e,s.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let s of this.listeners(t))if(s[Le]===e&&!s[Q]){this.removeListener(t,s);break}}};yt.exports={CloseEvent:U,ErrorEvent:V,Event:C,EventTarget:Es,MessageEvent:J};function le(t,e,s){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,s):t.call(e,s)}});var Ue=S((wr,Bt)=>{"use strict";var vs=p("events"),bs=p("https"),ws=p("http"),vt=p("net"),Os=p("tls"),{randomBytes:Ts,createHash:ks}=p("crypto"),{Duplex:vr,Readable:br}=p("stream"),{URL:Ne}=p("url"),B=X(),Cs=nt(),Ls=lt(),{isBlob:Ns}=q(),{BINARY_TYPES:St,CLOSE_TIMEOUT:Bs,EMPTY_BUFFER:he,GUID:Ps,kForOnEventAttribute:Be,kListener:Rs,kStatusCode:Us,kWebSocket:y,NOOP:bt}=T(),{EventTarget:{addEventListener:Is,removeEventListener:Ds}}=xt(),{format:Ms,parse:As}=Ce(),{toBuffer:Fs}=Y(),wt=Symbol("kAborted"),Pe=[8,13],L=["CONNECTING","OPEN","CLOSING","CLOSED"],Ws=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,d=class t extends vs{constructor(e,s,r){super(),this._binaryType=St[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=he,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,s===void 0?!r||r.protocols===void 0?s=[]:Array.isArray(r.protocols)?s=r.protocols:s=[r.protocols]:Array.isArray(s)||(typeof s=="object"&&s!==null?(r=s,r.protocols===void 0?s=[]:Array.isArray(r.protocols)?s=r.protocols:s=[r.protocols]):s=[s]),Ot(this,e,s,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){St.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,s,r){let i=new Cs({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),n=new Ls(e,this._extensions,r.generateMask);this._receiver=i,this._sender=n,this._socket=e,i[y]=this,n[y]=this,e[y]=this,i.on("conclude",$s),i.on("drain",js),i.on("error",Vs),i.on("message",zs),i.on("ping",Hs),i.on("pong",Ys),n.onerror=Ks,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),s.length>0&&e.unshift(s),e.on("close",Ct),e.on("data",ue),e.on("end",Lt),e.on("error",Nt),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[B.extensionName]&&this._extensions[B.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,s){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){E(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._sender.close(e,s,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),this._readyState=t.CLOSING,kt(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,s,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=s=void 0):typeof s=="function"&&(r=s,s=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Re(this,e,r);return}s===void 0&&(s=!this._isServer),this._sender.ping(e||he,s,r)}pong(e,s,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=s=void 0):typeof s=="function"&&(r=s,s=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Re(this,e,r);return}s===void 0&&(s=!this._isServer),this._sender.pong(e||he,s,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,s,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof s=="function"&&(r=s,s={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Re(this,e,r);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...s};this._extensions[B.extensionName]||(i.compress=!1),this._sender.send(e||he,i,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){E(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(d,"CONNECTING",{enumerable:!0,value:L.indexOf("CONNECTING")});Object.defineProperty(d.prototype,"CONNECTING",{enumerable:!0,value:L.indexOf("CONNECTING")});Object.defineProperty(d,"OPEN",{enumerable:!0,value:L.indexOf("OPEN")});Object.defineProperty(d.prototype,"OPEN",{enumerable:!0,value:L.indexOf("OPEN")});Object.defineProperty(d,"CLOSING",{enumerable:!0,value:L.indexOf("CLOSING")});Object.defineProperty(d.prototype,"CLOSING",{enumerable:!0,value:L.indexOf("CLOSING")});Object.defineProperty(d,"CLOSED",{enumerable:!0,value:L.indexOf("CLOSED")});Object.defineProperty(d.prototype,"CLOSED",{enumerable:!0,value:L.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(d.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(d.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Be])return e[Rs];return null},set(e){for(let s of this.listeners(t))if(s[Be]){this.removeListener(t,s);break}typeof e=="function"&&this.addEventListener(t,e,{[Be]:!0})}})});d.prototype.addEventListener=Is;d.prototype.removeEventListener=Ds;Bt.exports=d;function Ot(t,e,s,r){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Bs,protocolVersion:Pe[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,protocols:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=i.autoPong,t._closeTimeout=i.closeTimeout,!Pe.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${Pe.join(", ")})`);let n;if(e instanceof Ne)n=e;else try{n=new Ne(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}n.protocol==="http:"?n.protocol="ws:":n.protocol==="https:"&&(n.protocol="wss:"),t._url=n.href;let o=n.protocol==="wss:",f=n.protocol==="ws+unix:",l;if(n.protocol!=="ws:"&&!o&&!f?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:f&&!n.pathname?l="The URL's pathname is empty":n.hash&&(l="The URL contains a fragment identifier"),l){let u=new SyntaxError(l);if(t._redirects===0)throw u;ce(t,u);return}let a=o?443:80,h=Ts(16).toString("base64"),c=o?bs.request:ws.request,_=new Set,g;if(i.createConnection=i.createConnection||(o?Gs:qs),i.defaultPort=i.defaultPort||a,i.port=n.port||a,i.host=n.hostname.startsWith("[")?n.hostname.slice(1,-1):n.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":h,Connection:"Upgrade",Upgrade:"websocket"},i.path=n.pathname+n.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(g=new B({...i.perMessageDeflate,isServer:!1,maxPayload:i.maxPayload}),i.headers["Sec-WebSocket-Extensions"]=Ms({[B.extensionName]:g.offer()})),s.length){for(let u of s){if(typeof u!="string"||!Ws.test(u)||_.has(u))throw new SyntaxError("An invalid or duplicated subprotocol was specified");_.add(u)}i.headers["Sec-WebSocket-Protocol"]=s.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(n.username||n.password)&&(i.auth=`${n.username}:${n.password}`),f){let u=i.path.split(":");i.socketPath=u[0],i.path=u[1]}let m;if(i.followRedirects){if(t._redirects===0){t._originalIpc=f,t._originalSecure=o,t._originalHostOrSocketPath=f?i.socketPath:n.host;let u=r&&r.headers;if(r={...r,headers:{}},u)for(let[x,M]of Object.entries(u))r.headers[x.toLowerCase()]=M}else if(t.listenerCount("redirect")===0){let u=f?t._originalIpc?i.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:n.host===t._originalHostOrSocketPath;(!u||t._originalSecure&&!o)&&(delete i.headers.authorization,delete i.headers.cookie,u||delete i.headers.host,i.auth=void 0)}i.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),m=t._req=c(i),t._redirects&&t.emit("redirect",t.url,m)}else m=t._req=c(i);i.timeout&&m.on("timeout",()=>{E(t,m,"Opening handshake has timed out")}),m.on("error",u=>{m===null||m[wt]||(m=t._req=null,ce(t,u))}),m.on("response",u=>{let x=u.headers.location,M=u.statusCode;if(x&&i.followRedirects&&M>=300&&M<400){if(++t._redirects>i.maxRedirects){E(t,m,"Maximum redirects exceeded");return}m.abort();let z;try{z=new Ne(x,e)}catch{let A=new SyntaxError(`Invalid URL: ${x}`);ce(t,A);return}Ot(t,z,s,r)}else t.emit("unexpected-response",m,u)||E(t,m,`Unexpected server response: ${u.statusCode}`)}),m.on("upgrade",(u,x,M)=>{if(t.emit("upgrade",u),t.readyState!==d.CONNECTING)return;m=t._req=null;let z=u.headers.upgrade;if(z===void 0||z.toLowerCase()!=="websocket"){E(t,x,"Invalid Upgrade header");return}let De=ks("sha1").update(h+Ps).digest("base64");if(u.headers["sec-websocket-accept"]!==De){E(t,x,"Invalid Sec-WebSocket-Accept header");return}let A=u.headers["sec-websocket-protocol"],H;if(A!==void 0?_.size?_.has(A)||(H="Server sent an invalid subprotocol"):H="Server sent a subprotocol but none was requested":_.size&&(H="Server sent no subprotocol"),H){E(t,x,H);return}A&&(t._protocol=A);let Me=u.headers["sec-websocket-extensions"];if(Me!==void 0){if(!g){E(t,x,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let _e;try{_e=As(Me)}catch{E(t,x,"Invalid Sec-WebSocket-Extensions header");return}let Ae=Object.keys(_e);if(Ae.length!==1||Ae[0]!==B.extensionName){E(t,x,"Server indicated an extension that was not requested");return}try{g.accept(_e[B.extensionName])}catch{E(t,x,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[B.extensionName]=g}t.setSocket(x,M,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxBufferedChunks:i.maxBufferedChunks,maxFragments:i.maxFragments,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(m,t):m.end()}function ce(t,e){t._readyState=d.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function qs(t){return t.path=t.socketPath,vt.connect(t)}function Gs(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=vt.isIP(t.host)?"":t.host),Os.connect(t)}function E(t,e,s){t._readyState=d.CLOSING;let r=new Error(s);Error.captureStackTrace(r,E),e.setHeader?(e[wt]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ce,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Re(t,e,s){if(e){let r=Ns(e)?e.size:Fs(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(s){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${L[t.readyState]})`);process.nextTick(s,r)}}function $s(t,e){let s=this[y];s._closeFrameReceived=!0,s._closeMessage=e,s._closeCode=t,s._socket[y]!==void 0&&(s._socket.removeListener("data",ue),process.nextTick(Tt,s._socket),t===1005?s.close():s.close(t,e))}function js(){let t=this[y];t.isPaused||t._socket.resume()}function Vs(t){let e=this[y];e._socket[y]!==void 0&&(e._socket.removeListener("data",ue),process.nextTick(Tt,e._socket),e.close(t[Us])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Et(){this[y].emitClose()}function zs(t,e){this[y].emit("message",t,e)}function Hs(t){let e=this[y];e._autoPong&&e.pong(t,!this._isServer,bt),e.emit("ping",t)}function Ys(t){this[y].emit("pong",t)}function Tt(t){t.resume()}function Ks(t){let e=this[y];e.readyState!==d.CLOSED&&(e.readyState===d.OPEN&&(e._readyState=d.CLOSING,kt(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function kt(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Ct(){let t=this[y];if(this.removeListener("close",Ct),this.removeListener("data",ue),this.removeListener("end",Lt),t._readyState=d.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[y]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Et),t._receiver.on("finish",Et))}function ue(t){this[y]._receiver.write(t)||this.pause()}function Lt(){let t=this[y];t._readyState=d.CLOSING,t._receiver.end(),this.end()}function Nt(){let t=this[y];this.removeListener("error",Nt),this.on("error",bt),t&&(t._readyState=d.CLOSING,this.destroy())}});var Js=S((Tr,Ut)=>{"use strict";var Or=Ue(),{Duplex:Xs}=p("stream");function Pt(t){t.emit("close")}function Zs(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Rt(t){this.removeListener("error",Rt),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Qs(t,e){let s=!0,r=new Xs({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(n,o){let f=!o&&r._readableState.objectMode?n.toString():n;r.push(f)||t.pause()}),t.once("error",function(n){r.destroyed||(s=!1,r.destroy(n))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(i,n){if(t.readyState===t.CLOSED){n(i),process.nextTick(Pt,r);return}let o=!1;t.once("error",function(l){o=!0,n(l)}),t.once("close",function(){o||n(i),process.nextTick(Pt,r)}),s&&t.terminate()},r._final=function(i){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(i)});return}t._socket!==null&&(t._socket._writableState.finished?(i(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){i()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(i,n,o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(i,n,o)});return}t.send(i,o)},r.on("end",Zs),r.on("error",Rt),r}Ut.exports=Qs});var Dt=S((kr,It)=>{"use strict";var{tokenChars:er}=q();function tr(t){let e=new Set,s=-1,r=-1,i=0;for(i;i<t.length;i++){let o=t.charCodeAt(i);if(r===-1&&er[o]===1)s===-1&&(s=i);else if(i!==0&&(o===32||o===9))r===-1&&s!==-1&&(r=i);else if(o===44){if(s===-1)throw new SyntaxError(`Unexpected character at index ${i}`);r===-1&&(r=i);let f=t.slice(s,r);if(e.has(f))throw new SyntaxError(`The "${f}" subprotocol is duplicated`);e.add(f),s=r=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(s===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let n=t.slice(s,i);if(e.has(n))throw new SyntaxError(`The "${n}" subprotocol is duplicated`);return e.add(n),e}It.exports={parse:tr}});var cr=S((Lr,Gt)=>{"use strict";var sr=p("events"),de=p("http"),{Duplex:Cr}=p("stream"),{createHash:rr}=p("crypto"),Mt=Ce(),I=X(),ir=Dt(),nr=Ue(),{CLOSE_TIMEOUT:or,GUID:ar,kWebSocket:fr}=T(),lr=/^[+/0-9A-Za-z]{22}==$/,At=0,Ft=1,qt=2,Ie=class extends sr{constructor(e,s){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:or,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:nr,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=de.createServer((r,i)=>{let n=de.STATUS_CODES[426];i.writeHead(426,{"Content-Length":n.length,"Content-Type":"text/plain"}),i.end(n)}),this._server.listen(e.port,e.host,e.backlog,s)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=hr(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,n,o)=>{this.handleUpgrade(i,n,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=At}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===qt){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(ee,this);return}if(e&&this.once("close",e),this._state!==Ft)if(this._state=Ft,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(ee,this):process.nextTick(ee,this);else{let s=this._server;this._removeListeners(),this._removeListeners=this._server=null,s.close(()=>{ee(this)})}}shouldHandle(e){if(this.options.path){let s=e.url.indexOf("?");if((s!==-1?e.url.slice(0,s):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,s,r,i){s.on("error",Wt);let n=e.headers["sec-websocket-key"],o=e.headers.upgrade,f=+e.headers["sec-websocket-version"];if(e.method!=="GET"){D(this,e,s,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){D(this,e,s,400,"Invalid Upgrade header");return}if(n===void 0||!lr.test(n)){D(this,e,s,400,"Missing or invalid Sec-WebSocket-Key header");return}if(f!==13&&f!==8){D(this,e,s,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){te(s,400);return}let l=e.headers["sec-websocket-protocol"],a=new Set;if(l!==void 0)try{a=ir.parse(l)}catch{D(this,e,s,400,"Invalid Sec-WebSocket-Protocol header");return}let h=e.headers["sec-websocket-extensions"],c={};if(this.options.perMessageDeflate&&h!==void 0){let _=new I({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let g=Mt.parse(h);g[I.extensionName]&&(_.accept(g[I.extensionName]),c[I.extensionName]=_)}catch{D(this,e,s,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let _={origin:e.headers[`${f===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(_,(g,m,u,x)=>{if(!g)return te(s,m||401,u,x);this.completeUpgrade(c,n,a,e,s,r,i)});return}if(!this.options.verifyClient(_))return te(s,401)}this.completeUpgrade(c,n,a,e,s,r,i)}completeUpgrade(e,s,r,i,n,o,f){if(!n.readable||!n.writable)return n.destroy();if(n[fr])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>At)return te(n,503);let a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${rr("sha1").update(s+ar).digest("base64")}`],h=new this.options.WebSocket(null,void 0,this.options);if(r.size){let c=this.options.handleProtocols?this.options.handleProtocols(r,i):r.values().next().value;c&&(a.push(`Sec-WebSocket-Protocol: ${c}`),h._protocol=c)}if(e[I.extensionName]){let c=e[I.extensionName].params,_=Mt.format({[I.extensionName]:[c]});a.push(`Sec-WebSocket-Extensions: ${_}`),h._extensions=e}this.emit("headers",a,i),n.write(a.concat(`\r
5
+ `).join(`\r
6
+ `)),n.removeListener("error",Wt),h.setSocket(n,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(h),h.on("close",()=>{this.clients.delete(h),this._shouldEmitClose&&!this.clients.size&&process.nextTick(ee,this)})),f(h,i)}};Gt.exports=Ie;function hr(t,e){for(let s of Object.keys(e))t.on(s,e[s]);return function(){for(let r of Object.keys(e))t.removeListener(r,e[r])}}function ee(t){t._state=qt,t.emit("close")}function Wt(){this.destroy()}function te(t,e,s,r){s=s||de.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(s),...r},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${de.STATUS_CODES[e]}\r
7
+ `+Object.keys(r).map(i=>`${i}: ${r[i]}`).join(`\r
8
+ `)+`\r
9
+ \r
10
+ `+s)}function D(t,e,s,r,i,n){if(t.listenerCount("wsClientError")){let o=new Error(i);Error.captureStackTrace(o,D),t.emit("wsClientError",o,s,e)}else te(s,r,i,n)}});export{X as a,nt as b,lt as c,Ce as d,Ue as e,Js as f,Dt as g,cr as h};
@@ -0,0 +1,4 @@
1
+ import { createRequire as __cortexCreateRequire } from 'node:module';
2
+ const require = __cortexCreateRequire(import.meta.url);
3
+ const __cortexPackageRoot = new URL("../../", import.meta.url);
4
+ function l(e){return new RegExp(e.join("|"),"i")}var f=l(["GoUsageLimitError","FreeUsageLimitError","Monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing","subscription_sharing_usage_limit_exceeded","subscription_sharing_workplace_individual_usage_limit_exceeded",'"code"\\s*:\\s*"?1308(?![0-9])']),_=l(["overloaded","server_busy","servers are currently busy","currently experiencing high demand","model is at capacity","rate.?limit","too many requests","(?<![a-z0-9])(?:429|500|502|503|504|520|524)(?![a-z0-9])","service.?(?:is.?)?(?:temporarily.?)?unavailable","server.?error","internal.?error","provider.?returned.?(?:an.?)?error","exceeded request buffer limit while retrying upstream","unable to forward upstream","upstream.?request.?failed","upstream_stream_read_error","stream was interrupted","http/?2 stream failed","network.?error","connection.?error","connection.?refused","connection.?lost","connection.?closed","other side closed","fetch failed","request to \\S+ failed, reason:","getaddrinfo","(?<![a-z0-9_])(?:ECONNRESET|ECONNABORTED|ECONNREFUSED|ETIMEDOUT|EPIPE)(?![a-z0-9_])","connection reset by peer","ENOTFOUND","EAI_AGAIN","upstream.?connect","reset before headers","socket hang up","socket connection was closed","timed? out","timeout","terminated","websocket.?closed","websocket.?error","websocket.?connection.?limit.?reached","ended without","stream ended before message_stop","stream ended before a terminal response event","http2 request did not get a response","stream disconnected before completion","cut short after the reply had begun","pending stream has been canceled","retry delay","you can retry your request","try your request again","please retry your request","ResourceExhausted","subscription_sharing_usage_unavailable","subscription_sharing_user_unavailable"]),p=6e4;function E(e,r){let o=e.baseDelayMs*2**Math.max(0,r-1),t=Number.isSafeInteger(o)?o:Number.MAX_SAFE_INTEGER;return Math.min(t,e.maxAgentDelayMs??p)}var i=class extends Error{constructor(){super("Aborted")}};function R(e,r){return new Promise((o,t)=>{if(r?.aborted){t(new i);return}let u=setTimeout(o,e);r?.addEventListener("abort",()=>{clearTimeout(u),t(new i)},{once:!0})})}async function h(e,r,o,t){let u=r?.enabled?r.maxRetries:0,a=0,s;for(;;){let n=await e();if(n.stopReason==="aborted")return s&&await t?.onRetryFinished?.(!1,s.attempt),n;if(n.stopReason!=="error")return s&&await t?.onRetryFinished?.(!0,s.attempt),n;if(a>=u||!y(n))return s&&await t?.onRetryFinished?.(!1,s.attempt,n.errorMessage),n;a++,s={attempt:a,errorMessage:n.errorMessage||"Unknown error"};let d=E(r,a);await t?.onRetryScheduled?.(a,u,d,s.errorMessage);try{await R(d,o)}catch(c){if(await t?.onRetryFinished?.(!1,a,s.errorMessage),c instanceof i){let{errorMessage:g,...m}=n;return{...m,stopReason:"aborted"}}throw c}await t?.onRetryAttemptStart?.()}}function y(e){if(e.stopReason!=="error"||!e.errorMessage)return!1;let r=e.errorMessage;return f.test(r)?!1:_.test(r)}export{p as a,E as b,h as c,y as d};
@@ -0,0 +1,4 @@
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{c as f,d as u}from"./chunk-CSVTYYLP.js";import{Worker as m}from"node:worker_threads";function h(e){return new Uint8Array(e)}function p(e){return e!==null&&typeof e=="object"&&"type"in e&&e.type===f}function y(e){return new m(e)}async function w(e,t,n,s){let i=y(e);try{let c=h(t);return await new Promise((d,g)=>{let o=!1,l=r=>{o||(o=!0,d(r))},a=r=>{o||(o=!0,g(r))};i.on("message",r=>{p(r)&&("error"in r?a(new Error(r.error)):l(r.result))}),i.once("error",a),i.once("exit",r=>{o||a(new Error(`Image resize worker exited with code ${r}`))}),i.postMessage({inputBytes:c,mimeType:n,options:s},[c.buffer])})}finally{await i.terminate().catch(()=>{})}}async function z(e,t,n){let s=new URL("vendor/pi/dist/utils/image-resize.js",__cortexPackageRoot).href.endsWith(".ts"),i=new URL(s?"./image-resize-worker.ts":"./image-resize-worker.js",new URL("vendor/pi/dist/utils/image-resize.js",__cortexPackageRoot).href);if(typeof process.versions.bun=="string")try{return await w("./src/utils/image-resize-worker.ts",e,t,n)}catch{}try{return await w(i,e,t,n)}catch{return u(e,t,n)}}function I(e){if(!e.wasResized)return;let t=e.originalWidth/e.width;return`[Image: original ${e.originalWidth}x${e.originalHeight}, displayed at ${e.width}x${e.height}. Multiply coordinates by ${t.toFixed(2)} to map to original image.]`}export{z as a,I as b};
@@ -0,0 +1,4 @@
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 S}from"./chunk-V35MFAUQ.js";import{b as d}from"./chunk-52VCLZS5.js";import{b as p}from"./chunk-5M4PFLRW.js";import{e as u}from"./chunk-7W7VYUTK.js";import{c as l,j as f}from"./chunk-T54CZKNJ.js";import{e as R}from"./chunk-WHC7AYZD.js";var E=R(S(),1);import{copyFileSync as x,existsSync as L,mkdirSync as C,readdirSync as T,readFileSync as a,renameSync as F,constants as P}from"node:fs";import*as i from"node:path";var _={bash:"Bash",read:"Read",write:"Write",edit:"Edit",grep:"Grep",glob:"Glob",web_fetch:"WebFetch",web_search:"WebSearch",ask_user_question:"AskUserQuestion",enter_plan_mode:"EnterPlanMode",exit_plan_mode:"ExitPlanMode",todo_write:"TodoWrite",skill:"Skill",agent:"Agent"},h={bash:"bash",read:"read",write:"write",edit:"edit",grep:"grep",glob:"glob",web_fetch:"web_fetch",web_search:"web_search",todo_write:"todo_write",skill:"skill"},O={claude:_,pi:h},A={claude:m(_),pi:m(h)};function m(t){let e=new Map;for(let[n,r]of Object.entries(t))r&&e.set(r,n);return e}function U(t,e){return e.startsWith("mcp__")?e:A[t].get(e)??null}function g(t,e){return e.startsWith("mcp__")?e:O[t][e]??null}var b=u("agent-roles"),y=i.join(f,"agents"),w=i.join(l,"agents"),k="mcp__cortex-core__",j=new Set(Object.values(d).flat());function B(t){let n=(Array.isArray(t)?t.filter(r=>typeof r=="string"):typeof t=="string"?t.split(","):[]).map(r=>r.trim()).filter(Boolean);return n.length>0?n:void 0}function I(t){return t==="claude"||t==="pi"?t:void 0}function M(t){return typeof t=="string"&&t.trim()?t.trim():void 0}function W(t){let e=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)([\s\S]*)$/.exec(t);if(!e)return null;let n=(0,E.parse)(e[1]);return!n||typeof n.name!="string"||typeof n.description!="string"?null:{name:n.name,description:n.description,tools:B(n.tools),model:M(n.model),backend:I(n.backend),systemPrompt:e[2].trim()}}function D(t){try{return W(a(t,"utf8"))}catch{return null}}function Q(t=y,e=w){let n=new Map,r=p(e,t,".md"),o=[...r.filter(s=>s.origin==="builtin"),...r.filter(s=>s.origin!=="builtin")];for(let s of o){let c=D(s.path);c&&n.set(c.name,c)}return[...n.values()]}function H(t,e){let n=t.find(o=>o.name===e);if(n)return n;let r=t.map(o=>o.name).sort().join(", ")||"none";throw new Error(`Unknown subagent_type "${e}". Available roles: ${r}.`)}function J(t,e){if(!t.tools)return;let n=[];for(let r of t.tools){if(r.startsWith("mcp__")){n.push(r);continue}let o=g(e,r);if(o){n.push(o);continue}if(j.has(r)){n.push(e==="claude"?k+r:r);continue}e!=="claude"&&n.push(r)}return[...new Set(n)]}function Z(t={}){let e=t.rolesDir??y,n=t.defaultsDir??w;!t.legacyDir||L(e)||$(t.legacyDir,e,n)}function $(t,e,n){let r;try{r=T(t).filter(o=>o.endsWith(".md"))}catch{return}if(r.length){C(e,{recursive:!0});for(let o of r)N(i.join(t,o),i.join(n,o))||G(i.join(t,o),i.join(e,o));b.info(`Adopted ${r.length} role file(s) from ${t}`);try{F(t,`${t}.migrated`)}catch(o){b.warn(`Could not retire ${t}: ${o.message}`)}}}function N(t,e){try{return a(t,"utf8")===a(e,"utf8")}catch{return!1}}function G(t,e){try{x(t,e,P.COPYFILE_EXCL)}catch(n){let r=n.code;if(r==="EEXIST"||r==="ENOENT")return;throw n}}export{U as a,g as b,Q as c,H as d,J as e,Z as f};
@@ -1,4 +1,4 @@
1
1
  import { createRequire as __cortexCreateRequire } from 'node:module';
2
2
  const require = __cortexCreateRequire(import.meta.url);
3
3
  const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{statSync as h,watch as s}from"node:fs";import c from"node:path";var o=5e3;function i(e){if(!(e instanceof Error))return String(e);let r=e.code;return r?`${r}: ${e.message}`:e.message}function f(e){for(let r of e.splice(0))try{r.close()}catch{}}function u(e,r){try{e.poll?.()}catch(t){r(`${e.label} polling failed (${i(t)})`)}}function m(e,r,t){e.pollTimer=setInterval(()=>u(r,t),o),e.pollTimer.unref?.()}function w(e,r,t,n){if(e.failed||e.closed)return;e.failed=!0,f(e.watchers);let l=i(n);if(!r.poll)return t(`${r.label} watcher failed (${l}); watcher disabled`);t(`${r.label} watcher failed (${l}); polling every ${o}ms`),m(e,r,t)}function d(e){e.closed=!0,f(e.watchers),e.pollTimer&&clearInterval(e.pollTimer),e.pollTimer=null}function g(e){let r={watchers:[],pollTimer:null,failed:!1,closed:!1},t=e.warn??console.warn,n=l=>w(r,e,t,l);try{r.watchers=e.startWatching();for(let l of r.watchers)l.on("error",n)}catch(l){n(l)}return{close:()=>d(r)}}function $(e){let r=e.snapshot(),t=()=>{let l=e.snapshot();l!==r&&(r=l,e.onChange())},n=g({label:e.label,startWatching:()=>e.startWatching(t),poll:t,warn:e.warn});return t(),n}function W(e){try{let r=h(e);return`${r.size}:${r.mtimeMs}:${r.ctimeMs}:${r.ino}`}catch{return null}}function S(e){let r=c.basename(e.filePath);return $({label:e.label,snapshot:()=>W(e.filePath),onChange:e.onChange,warn:e.warn,startWatching:t=>{let n=s(c.dirname(e.filePath),(l,a)=>{(a===null||a.toString()===r)&&t()});return e.unref&&n.unref(),[n]}})}export{g as a,$ as b,S as c};
4
+ import{statSync as h,watch as s}from"node:fs";import c from"node:path";var o=5e3;function i(e){if(!(e instanceof Error))return String(e);let r=e.code;return r?`${r}: ${e.message}`:e.message}function f(e){for(let r of e.splice(0))try{r.close()}catch{}}function u(e,r){try{e.poll?.()}catch(t){r(`${e.label} polling failed (${i(t)})`)}}function m(e,r,t){e.pollTimer=setInterval(()=>u(r,t),o),e.pollTimer.unref?.()}function w(e,r,t,n){if(e.failed||e.closed)return;e.failed=!0,f(e.watchers);let l=i(n);if(!r.poll)return t(`${r.label} watcher failed (${l}); watcher disabled`);t(`${r.label} watcher failed (${l}); polling every ${o}ms`),m(e,r,t)}function d(e){e.closed=!0,f(e.watchers),e.pollTimer&&clearInterval(e.pollTimer),e.pollTimer=null}function g(e){let r={watchers:[],pollTimer:null,failed:!1,closed:!1},t=e.warn??console.warn,n=l=>w(r,e,t,l);try{r.watchers=e.startWatching();for(let l of r.watchers)l.on("error",n)}catch(l){n(l)}return{close:()=>d(r)}}function $(e){let r=e.snapshot(),t=()=>{let l=e.snapshot();l!==r&&(r=l,e.onChange())},n=g({label:e.label,startWatching:()=>e.startWatching(t),poll:t,warn:e.warn});return t(),n}function W(e){try{let r=h(e);return`${r.size}:${r.mtimeMs}:${r.ctimeMs}:${r.ino}`}catch{return null}}function S(e){let r=c.basename(e.filePath);return $({label:e.label,snapshot:()=>W(e.filePath),onChange:e.onChange,warn:e.warn,startWatching:t=>{let n=s(c.dirname(e.filePath),(l,a)=>{(a===null||a.toString()===r)&&t()});return e.unref&&n.unref(),[n]}})}export{o as a,i as b,g as c,$ as d,S as e};
@@ -0,0 +1,6 @@
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,c as A,e as P}from"./chunk-WHC7AYZD.js";var N=A((pe,$)=>{$.exports={name:"dotenv",version:"16.6.1",description:"Loads environment variables from .env file",main:"lib/main.js",types:"lib/main.d.ts",exports:{".":{types:"./lib/main.d.ts",require:"./lib/main.js",default:"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},scripts:{"dts-check":"tsc --project tests/types/tsconfig.json",lint:"standard",pretest:"npm run lint && npm run dts-check",test:"tap run --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov",prerelease:"npm test",release:"standard-version"},repository:{type:"git",url:"git://github.com/motdotla/dotenv.git"},homepage:"https://github.com/motdotla/dotenv#readme",funding:"https://dotenvx.com",keywords:["dotenv","env",".env","environment","variables","config","settings"],readmeFilename:"README.md",license:"BSD-2-Clause",devDependencies:{"@types/node":"^18.11.3",decache:"^4.6.2",sinon:"^14.0.1",standard:"^17.0.0","standard-version":"^9.5.0",tap:"^19.2.0",typescript:"^4.8.4"},engines:{node:">=12"},browser:{fs:!1}}});var C=A((ue,d)=>{var T=m("fs"),D=m("path"),U=m("os"),K=m("crypto"),M=N(),I=M.version,Y=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function F(e){let t={},n=e.toString();n=n.replace(/\r\n?/mg,`
5
+ `);let s;for(;(s=Y.exec(n))!=null;){let c=s[1],r=s[2]||"";r=r.trim();let a=r[0];r=r.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),a==='"'&&(r=r.replace(/\\n/g,`
6
+ `),r=r.replace(/\\r/g,"\r")),t[c]=r}return t}function G(e){e=e||{};let t=w(e);e.path=t;let n=l.configDotenv(e);if(!n.parsed){let a=new Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw a.code="MISSING_DATA",a}let s=j(e).split(","),c=s.length,r;for(let a=0;a<c;a++)try{let i=s[a].trim(),f=q(n,i);r=l.decrypt(f.ciphertext,f.key);break}catch(i){if(a+1>=c)throw i}return l.parse(r)}function W(e){console.log(`[dotenv@${I}][WARN] ${e}`)}function _(e){console.log(`[dotenv@${I}][DEBUG] ${e}`)}function b(e){console.log(`[dotenv@${I}] ${e}`)}function j(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function q(e,t){let n;try{n=new URL(t)}catch(i){if(i.code==="ERR_INVALID_URL"){let f=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw f.code="INVALID_DOTENV_KEY",f}throw i}let s=n.password;if(!s){let i=new Error("INVALID_DOTENV_KEY: Missing key part");throw i.code="INVALID_DOTENV_KEY",i}let c=n.searchParams.get("environment");if(!c){let i=new Error("INVALID_DOTENV_KEY: Missing environment part");throw i.code="INVALID_DOTENV_KEY",i}let r=`DOTENV_VAULT_${c.toUpperCase()}`,a=e.parsed[r];if(!a){let i=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${r} in your .env.vault file.`);throw i.code="NOT_FOUND_DOTENV_ENVIRONMENT",i}return{ciphertext:a,key:s}}function w(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(let n of e.path)T.existsSync(n)&&(t=n.endsWith(".vault")?n:`${n}.vault`);else t=e.path.endsWith(".vault")?e.path:`${e.path}.vault`;else t=D.resolve(process.cwd(),".env.vault");return T.existsSync(t)?t:null}function x(e){return e[0]==="~"?D.join(U.homedir(),e.slice(1)):e}function H(e){let t=!!(e&&e.debug),n=e&&"quiet"in e?e.quiet:!0;(t||!n)&&b("Loading env from encrypted .env.vault");let s=l._parseVault(e),c=process.env;return e&&e.processEnv!=null&&(c=e.processEnv),l.populate(c,s,e),{parsed:s}}function B(e){let t=D.resolve(process.cwd(),".env"),n="utf8",s=!!(e&&e.debug),c=e&&"quiet"in e?e.quiet:!0;e&&e.encoding?n=e.encoding:s&&_("No encoding is specified. UTF-8 is used by default");let r=[t];if(e&&e.path)if(!Array.isArray(e.path))r=[x(e.path)];else{r=[];for(let h of e.path)r.push(x(h))}let a,i={};for(let h of r)try{let p=l.parse(T.readFileSync(h,{encoding:n}));l.populate(i,p,e)}catch(p){s&&_(`Failed to load ${h} ${p.message}`),a=p}let f=process.env;if(e&&e.processEnv!=null&&(f=e.processEnv),l.populate(f,i,e),s||!c){let h=Object.keys(i).length,p=[];for(let y of r)try{let g=D.relative(process.cwd(),y);p.push(g)}catch(g){s&&_(`Failed to load ${y} ${g.message}`),a=g}b(`injecting env (${h}) from ${p.join(",")}`)}return a?{parsed:i,error:a}:{parsed:i}}function X(e){if(j(e).length===0)return l.configDotenv(e);let t=w(e);return t?l._configVault(e):(W(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`),l.configDotenv(e))}function J(e,t){let n=Buffer.from(t.slice(-64),"hex"),s=Buffer.from(e,"base64"),c=s.subarray(0,12),r=s.subarray(-16);s=s.subarray(12,-16);try{let a=K.createDecipheriv("aes-256-gcm",n,c);return a.setAuthTag(r),`${a.update(s)}${a.final()}`}catch(a){let i=a instanceof RangeError,f=a.message==="Invalid key length",h=a.message==="Unsupported state or unable to authenticate data";if(i||f){let p=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw p.code="INVALID_DOTENV_KEY",p}else if(h){let p=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw p.code="DECRYPTION_FAILED",p}else throw a}}function Q(e,t,n={}){let s=!!(n&&n.debug),c=!!(n&&n.override);if(typeof t!="object"){let r=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw r.code="OBJECT_REQUIRED",r}for(let r of Object.keys(t))Object.prototype.hasOwnProperty.call(e,r)?(c===!0&&(e[r]=t[r]),s&&_(c===!0?`"${r}" is already defined and WAS overwritten`:`"${r}" is already defined and was NOT overwritten`)):e[r]=t[r]}var l={configDotenv:B,_configVault:H,_parseVault:G,config:X,decrypt:J,parse:F,populate:Q};d.exports.configDotenv=l.configDotenv;d.exports._configVault=l._configVault;d.exports._parseVault=l._parseVault;d.exports.config=l.config;d.exports.decrypt=l.decrypt;d.exports.parse=l.parse;d.exports.populate=l.populate;d.exports=l});import*as O from"fs";import*as o from"path";import*as R from"os";import{fileURLToPath as oe}from"url";var V=P(C(),1);import{readFileSync as z}from"node:fs";import{homedir as Z}from"node:os";import*as E from"node:path";var S="CORTEX_AISTATUS_HOME",ee="CORTEX_GATEWAY_HOME";function te(e){try{return(0,V.parse)(z(E.join(e,".env")))}catch(t){if(t.code!=="ENOENT")throw t}return{}}function re(e,t,n){let s=r=>r[S]??r[ee],c=s(e)??s(t);if(c===void 0)return E.join(n,".aistatus");if(!E.isAbsolute(c))throw new Error(`${S} must be an absolute path`);return E.join(E.resolve(c),".aistatus")}function L(e,t=process.env,n=Z()){return re(t,te(e),n)}var ne=o.dirname(oe(new URL("dist/core/paths.js",__cortexPackageRoot).href)),k=o.resolve(ne,"..",".."),_e=o.join(k,"defaults");var ge=k;var u=process.env.CORTEX_HOME?o.resolve(process.env.CORTEX_HOME):o.join(R.homedir(),".cortex");function se(){let e=process.env.CORTEX_AGENT_CWD;if(!e)return u;let t=o.resolve(e);if(!o.isAbsolute(e)||!O.existsSync(t)||!O.statSync(t).isDirectory())throw new Error(`CORTEX_AGENT_CWD must be an absolute path to an existing directory: ${e}`);return t}var ae=se();function ce(e){return o.resolve(e??ae)}function me(e){return ce(e?.workspaceDir??void 0)}var De=L(o.join(u,"config")),Oe=o.join(u,"config"),v=o.join(u,"data"),Te=o.join(v,"quota-stop.json"),Ie=o.join(v,"claude"),Re=o.join(v,"claude-accounts"),ye=o.join(v,"pi-accounts"),Ae=o.join(R.homedir(),".claude"),Ne=o.join(v,"daemon.pid"),xe=o.join(v,"daemon-child.pid"),be=o.join(v,".restart"),ie=o.join(u,"context"),je=process.env.CORTEX_PROJECTS_DIR?o.resolve(process.env.CORTEX_PROJECTS_DIR):o.join(ie,"projects"),le=o.join(u,"tmp"),we=o.join(u,"workspaces");function Ce(e){let t="workspace/";if(!e.startsWith(t))return null;let n=e.slice(t.length),s=o.resolve(le),c=o.resolve(s,n);return c!==s&&!c.startsWith(s+o.sep)?null:c}var Se=o.join(u,"plugins"),Ve=o.join(u,"prompts"),Le=o.join(u,"hooks"),ke=o.join(u,"logs");export{C as a,k as b,_e as c,ge as d,u as e,ae as f,ce as g,me as h,De as i,Oe as j,v as k,Te as l,Ie as m,Re as n,ye as o,Ae as p,Ne as q,xe as r,be as s,ie as t,je as u,le as v,we as w,Ce as x,Se as y,Ve as z,Le as A,ke as B};