@cortex-agent/server 2026.10.28 → 2026.12.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (401) hide show
  1. package/LICENSE +255 -21
  2. package/README.md +36 -7
  3. package/THIRD_PARTY_NOTICES.txt +1990 -593
  4. package/defaults/hooks/cortex-hook-api.mjs +2 -1
  5. package/defaults/hooks/quota-stop.mjs +37 -0
  6. package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +23 -15
  7. package/defaults/prompts/clean-workspace.md +5 -0
  8. package/dist/agent-adapter/claude/remote-mcp-proxy.js +1 -1
  9. package/dist/chunks/agent-runner-LVZVKBZX.js +4 -0
  10. package/dist/chunks/anthropic-messages-TT6454AA.js +8 -0
  11. package/dist/chunks/azure-openai-responses-52LR2XZD.js +4 -0
  12. package/dist/chunks/bedrock-converse-stream-EOZGYUNY.js +60 -0
  13. package/dist/chunks/bowser-MLGGLXTZ.js +20 -0
  14. package/dist/chunks/child-runner-SMG2VOU5.js +4 -0
  15. package/dist/chunks/chunk-24DH4IR5.js +4 -0
  16. package/dist/chunks/chunk-25XKBRDT.js +70 -0
  17. package/dist/chunks/chunk-2ABET62E.js +23 -0
  18. package/dist/chunks/chunk-2BVUA256.js +4 -0
  19. package/dist/chunks/{chunk-LEUENXI2.js → chunk-2WFL62UO.js} +1 -1
  20. package/dist/chunks/{chunk-OZGBWAT2.js → chunk-2YTYYG4K.js} +1 -1
  21. package/dist/chunks/chunk-335SSANX.js +4 -0
  22. package/dist/chunks/chunk-377OPTXX.js +17 -0
  23. package/dist/chunks/chunk-3EZNVLBF.js +129 -0
  24. package/dist/chunks/chunk-3O6ZG5HA.js +7 -0
  25. package/dist/chunks/{chunk-6AKUD3CF.js → chunk-3XLHL5YT.js} +1 -1
  26. package/dist/chunks/chunk-4HRI75GU.js +4 -0
  27. package/dist/chunks/chunk-4JBYLRPM.js +57 -0
  28. package/dist/chunks/chunk-4KKV7VKE.js +4 -0
  29. package/dist/chunks/chunk-4KQHDDC5.js +4 -0
  30. package/dist/chunks/chunk-4SWD4JMP.js +33 -0
  31. package/dist/chunks/chunk-52VCLZS5.js +4 -0
  32. package/dist/chunks/chunk-54P7TSY3.js +10 -0
  33. package/dist/chunks/chunk-5DVSAXOI.js +7 -0
  34. package/dist/chunks/chunk-5F3A62YS.js +4 -0
  35. package/dist/chunks/{chunk-XNSSUVT6.js → chunk-5FHETFZM.js} +1 -1
  36. package/dist/chunks/{chunk-A34TDMIC.js → chunk-5LBLRAHS.js} +1 -1
  37. package/dist/chunks/chunk-5UYVNA3W.js +4 -0
  38. package/dist/chunks/chunk-6G3OYMCV.js +21 -0
  39. package/dist/chunks/chunk-7GGPYU5E.js +30 -0
  40. package/dist/chunks/chunk-7TYSMLUV.js +4 -0
  41. package/dist/chunks/chunk-7W7VYUTK.js +5 -0
  42. package/dist/chunks/chunk-AXYAZTTN.js +6 -0
  43. package/dist/chunks/{chunk-BGVHA2D4.js → chunk-B3NB243Z.js} +1 -1
  44. package/dist/chunks/chunk-BKYP6AGM.js +8 -0
  45. package/dist/chunks/chunk-BVEDNESB.js +4 -0
  46. package/dist/chunks/chunk-BWDJS6A4.js +12 -0
  47. package/dist/chunks/chunk-C6YVF7EI.js +4 -0
  48. package/dist/chunks/chunk-CEJIYYVE.js +15 -0
  49. package/dist/chunks/chunk-CI2RHH74.js +50 -0
  50. package/dist/chunks/chunk-CMSOOLJB.js +4 -0
  51. package/dist/chunks/chunk-CSVTYYLP.js +4 -0
  52. package/dist/chunks/chunk-DE5EGVKG.js +6 -0
  53. package/dist/chunks/{chunk-E6BYRULL.js → chunk-DK3RPZOQ.js} +1 -1
  54. package/dist/chunks/{chunk-YPK2CAIZ.js → chunk-DK4UCK7L.js} +1 -1
  55. package/dist/chunks/chunk-DYLBVUAU.js +4 -0
  56. package/dist/chunks/chunk-FDC2GRBK.js +27 -0
  57. package/dist/chunks/chunk-FE7HH5JS.js +18 -0
  58. package/dist/chunks/chunk-FYD57YRO.js +436 -0
  59. package/dist/chunks/chunk-G264APQN.js +5 -0
  60. package/dist/chunks/chunk-G4JYZFEO.js +11 -0
  61. package/dist/chunks/chunk-GFFM56U2.js +4 -0
  62. package/dist/chunks/chunk-GOS3P7KS.js +132 -0
  63. package/dist/chunks/chunk-HVN37UXD.js +4 -0
  64. package/dist/chunks/chunk-IA6IODY3.js +4 -0
  65. package/dist/chunks/{chunk-HU6UIDEJ.js → chunk-IGZWZP7Z.js} +1 -1
  66. package/dist/chunks/{chunk-NR6U3WIZ.js → chunk-IJ7XFQMI.js} +1 -1
  67. package/dist/chunks/chunk-IMMGYDAB.js +6 -0
  68. package/dist/chunks/chunk-IOWBF7UK.js +10 -0
  69. package/dist/chunks/{chunk-HALUQ7ZF.js → chunk-ITGCWQFK.js} +1 -1
  70. package/dist/chunks/chunk-IVZ7QUEG.js +4 -0
  71. package/dist/chunks/{chunk-YAEVYJAR.js → chunk-IWY2HIFK.js} +1 -1
  72. package/dist/chunks/{chunk-KGJZAYQD.js → chunk-J7OBATRN.js} +1 -1
  73. package/dist/chunks/{chunk-QWAQHHRS.js → chunk-JGUEIW2W.js} +1 -1
  74. package/dist/chunks/chunk-JKL3AK5D.js +106 -0
  75. package/dist/chunks/chunk-JZ7U7RUK.js +351 -0
  76. package/dist/chunks/chunk-KJUQCCB5.js +4 -0
  77. package/dist/chunks/chunk-KST6OY76.js +10 -0
  78. package/dist/chunks/chunk-KZSAFVSY.js +129 -0
  79. package/dist/chunks/chunk-LD2ZSH3M.js +903 -0
  80. package/dist/chunks/chunk-LE6QPXN6.js +7 -0
  81. package/dist/chunks/chunk-LEAV3FFG.js +4 -0
  82. package/dist/chunks/chunk-LIIZI3HY.js +5 -0
  83. package/dist/chunks/chunk-LP72AF56.js +45 -0
  84. package/dist/chunks/{chunk-FXDIR3SQ.js → chunk-MJQ2D2OP.js} +1 -1
  85. package/dist/chunks/{chunk-6LZK4DDH.js → chunk-NHHR4DCF.js} +1 -1
  86. package/dist/chunks/chunk-NW4GW47L.js +4 -0
  87. package/dist/chunks/chunk-OALEJ6FG.js +60 -0
  88. package/dist/chunks/chunk-OIV4DIMB.js +4 -0
  89. package/dist/chunks/chunk-OJ37ZWBG.js +4 -0
  90. package/dist/chunks/chunk-OZXMPBUX.js +4 -0
  91. package/dist/chunks/{chunk-3THJYAEF.js → chunk-PG7452XE.js} +1 -1
  92. package/dist/chunks/chunk-PJCUB7YJ.js +4 -0
  93. package/dist/chunks/chunk-PTS3J4DQ.js +6 -0
  94. package/dist/chunks/{chunk-PXS5SHOV.js → chunk-PVVEEBUU.js} +1 -1
  95. package/dist/chunks/chunk-Q7BZLPBU.js +8 -0
  96. package/dist/chunks/{chunk-FOJQXLL2.js → chunk-QC66ZXPP.js} +1 -1
  97. package/dist/chunks/chunk-QXFWIL4C.js +4 -0
  98. package/dist/chunks/{chunk-PFMEUFJ7.js → chunk-R2CCD4OF.js} +1 -1
  99. package/dist/chunks/chunk-R6CGBSTC.js +22 -0
  100. package/dist/chunks/chunk-RG5GP4RB.js +5 -0
  101. package/dist/chunks/{chunk-D3NXKK2L.js → chunk-RW2F2QNP.js} +1 -1
  102. package/dist/chunks/{models-L5VF4I5O-XXNJYQMQ.js → chunk-RWPO3NZ3.js} +1 -1
  103. package/dist/chunks/chunk-SAJD4EKE.js +10 -0
  104. package/dist/chunks/chunk-SDUS2H3E.js +4 -0
  105. package/dist/chunks/chunk-SIHGKM4E.js +4 -0
  106. package/dist/chunks/chunk-SKHFU5DI.js +4 -0
  107. package/dist/chunks/{chunk-STUHNKQS.js → chunk-SM45TH22.js} +1 -1
  108. package/dist/chunks/chunk-T54CZKNJ.js +6 -0
  109. package/dist/chunks/chunk-TKFFQNAP.js +19 -0
  110. package/dist/chunks/chunk-TMV2ZDOI.js +18 -0
  111. package/dist/chunks/chunk-TRXLIL7V.js +4 -0
  112. package/dist/chunks/{chunk-SUFW24P4.js → chunk-UEEW2R4E.js} +1 -1
  113. package/dist/chunks/chunk-UHXPRU6G.js +10 -0
  114. package/dist/chunks/chunk-UPQVWHZ3.js +4 -0
  115. package/dist/chunks/{chunk-JERCOLY3.js → chunk-V35MFAUQ.js} +4 -6
  116. package/dist/chunks/chunk-V7K3KNDM.js +4 -0
  117. package/dist/chunks/chunk-VHX2GHBF.js +4 -0
  118. package/dist/chunks/chunk-VOAKRJ4R.js +4 -0
  119. package/dist/chunks/{chunk-X2GYYRVM.js → chunk-VW7TLY3P.js} +1 -1
  120. package/dist/chunks/chunk-W34AK4SK.js +65 -0
  121. package/dist/chunks/{chunk-REBNWCKI.js → chunk-WU7RNAZD.js} +1 -1
  122. package/dist/chunks/chunk-WZC4TDDM.js +6 -0
  123. package/dist/chunks/chunk-WZYS2HAK.js +4 -0
  124. package/dist/chunks/chunk-X2TKJ7KR.js +11 -0
  125. package/dist/chunks/{chunk-H2FP6DG4.js → chunk-X5ND4H4P.js} +1 -1
  126. package/dist/chunks/{chunk-4U7XXM4W.js → chunk-Y3AOGNDT.js} +1 -1
  127. package/dist/chunks/chunk-Y6DGVTKM.js +6 -0
  128. package/dist/chunks/{chunk-KENCMLRE.js → chunk-YAEHSSR4.js} +1 -1
  129. package/dist/chunks/chunk-YWPBE5LP.js +4 -0
  130. package/dist/chunks/chunk-ZAVX7G2M.js +15 -0
  131. package/dist/chunks/chunk-ZD2M73XA.js +19 -0
  132. package/dist/chunks/chunk-ZD4O6NPV.js +4 -0
  133. package/dist/chunks/chunk-ZNAMETPQ.js +4 -0
  134. package/dist/chunks/chunk-ZY6N5LVQ.js +4 -0
  135. package/dist/chunks/chunk-ZYQ4TDTT.js +81 -0
  136. package/dist/chunks/cli-VB2N7HEK.js +55 -0
  137. package/dist/chunks/cloudflare-workers-ai-system-one-YKU742EC.js +4 -0
  138. package/dist/chunks/context-CI2FKEQE.js +4 -0
  139. package/dist/chunks/cost-CZRRSIUF.js +5 -0
  140. package/dist/chunks/dist-QCNQN6DY.js +4 -0
  141. package/dist/chunks/easter-egg-3d-XR5S2O3T.js +4 -0
  142. package/dist/chunks/{event-streams-3JSFPOTZ.js → event-streams-AVE4MSS6.js} +1 -1
  143. package/dist/chunks/{execution-repo-ZLJTBWFC.js → execution-repo-5TLV2NM4.js} +1 -1
  144. package/dist/chunks/{executions-6ARGR3IO.js → executions-I3UUIGSL.js} +1 -1
  145. package/dist/chunks/file-Y5G56IUT.js +4 -0
  146. package/dist/chunks/github-copilot-BRU2SRRZ.js +4 -0
  147. package/dist/chunks/google-generative-ai-ZF5QEUZV.js +4 -0
  148. package/dist/chunks/google-vertex-4PJZZI3Y.js +4 -0
  149. package/dist/chunks/init-A6GY656J.js +4 -0
  150. package/dist/chunks/{install-cli-4IZCSDFZ.js → install-cli-FALWKQYO.js} +1 -1
  151. package/dist/chunks/{interaction-ask-G5T3H3CG.js → interaction-ask-O5HGF6CH.js} +1 -1
  152. package/dist/chunks/{interaction-plan-E5V42MUP.js → interaction-plan-JTVDN3BC.js} +1 -1
  153. package/dist/chunks/kimi-coding-ZCIBMDZ6.js +4 -0
  154. package/dist/chunks/{llama-cpp-classify-OTXZWCMW.js → llama-cpp-classify-NRUXAIGQ.js} +3 -3
  155. package/dist/chunks/local-client-stop-RS4AHNF4.js +4 -0
  156. package/dist/chunks/{memory-cli-PYOILNN5.js → memory-cli-DIT4DQF3.js} +1 -1
  157. package/dist/chunks/meta-JQH66YU7.js +4 -0
  158. package/dist/chunks/mistral-conversations-CXHOECUV.js +7 -0
  159. package/dist/chunks/model-resolver-GIBPYRKP.js +4 -0
  160. package/dist/chunks/monitor-Z2HKNY5E.js +4 -0
  161. package/dist/chunks/{node-PTK2HCDV.js → node-DAO3SX7O.js} +1 -1
  162. package/dist/chunks/{openai-codex-2REL6UQU.js → openai-codex-JULCKICT.js} +1 -1
  163. package/dist/chunks/openai-codex-responses-U6DGMGDK.js +12 -0
  164. package/dist/chunks/openai-completions-PP4XLLOM.js +9 -0
  165. package/dist/chunks/{openai-decisions-2N6ZRPZC.js → openai-decisions-JU6QQKEM.js} +1 -1
  166. package/dist/chunks/openai-responses-2SG757TL.js +6 -0
  167. package/dist/chunks/openrouter-images-32M7YZWC.js +4 -0
  168. package/dist/chunks/pi-messages-VSINMXN4.js +10 -0
  169. package/dist/chunks/radius-THYKWV4E.js +4 -0
  170. package/dist/chunks/remote-ops-2WBEFQ3E.js +14 -0
  171. package/dist/chunks/runner-5MKMRTIN.js +4 -0
  172. package/dist/chunks/runtime-DST3H5JP.js +4 -0
  173. package/dist/chunks/schedule-cli-V7Y2BBVY.js +4 -0
  174. package/dist/chunks/slack-R7SEJYMY.js +4 -0
  175. package/dist/chunks/start-ui-http-7K5JOLPU.js +43 -0
  176. package/dist/chunks/subagent-Z5IQ4L54.js +4 -0
  177. package/dist/chunks/{time-KEHDQT6K.js → time-P6PE52WL.js} +1 -1
  178. package/dist/chunks/tool-shims-YCXZWTST.js +4 -0
  179. package/dist/chunks/typesafe-system-one-M2DABJSZ.js +4 -0
  180. package/dist/chunks/ui-board-HQIE4RZG.js +5 -0
  181. package/dist/chunks/ui-decision-YBZDS4YW.js +4 -0
  182. package/dist/chunks/{ui-file-GVH53O3X.js → ui-file-SRD4ILBS.js} +1 -1
  183. package/dist/chunks/ui-view-Z25MTZT7.js +4 -0
  184. package/dist/chunks/virtual-modules-H4DXPJZB.js +4 -0
  185. package/dist/chunks/waitpoint-M6JZBSLT.js +5 -0
  186. package/dist/chunks/workers-SQ2R32TK.js +4 -0
  187. package/dist/client-bundle/client.mjs +273 -93
  188. package/dist/client-bundle/manifest.json +2 -2
  189. package/dist/core/pi-sdk.js +1 -1
  190. package/dist/domain/auth/cc-auth-cli.js +1 -1
  191. package/dist/domain/mcp/bundled-server.js +1 -1
  192. package/dist/domain/mcp/feishu/client.js +4 -0
  193. package/dist/entry/app.js +151 -559
  194. package/dist/entry/browser-cli.js +10 -10
  195. package/dist/entry/cli.js +1 -1
  196. package/dist/entry/cortex-cli.js +1 -1
  197. package/dist/entry/daemon.js +4 -4
  198. package/dist/entry/hook-cli.js +2 -2
  199. package/dist/entry/production-app-bootstrap.js +1 -1
  200. package/dist/entry/production-evidence-export-cli.js +1 -1
  201. package/dist/entry/signal-cli.js +2 -2
  202. package/dist/tui/index.js +41 -41
  203. package/package.json +3 -3
  204. package/vendor/pi/CHANGELOG.md +330 -0
  205. package/vendor/pi/dist/codemode-worker.js +2 -0
  206. package/vendor/pi/dist/core/export-html/ansi-to-html.js +57 -20
  207. package/vendor/pi/dist/core/export-html/template.css +9 -0
  208. package/vendor/pi/dist/core/export-html/template.js +166 -46
  209. package/vendor/pi/dist/core/export-html/tool-renderer.js +5 -3
  210. package/vendor/pi/dist/core/extensions/loader.js +1 -1
  211. package/vendor/pi/dist/extensions/codemode/execute.js +15 -13
  212. package/vendor/pi/dist/modes/interactive/theme/theme.js +36 -23
  213. package/vendor/pi/dist/utils/image-resize-worker.js +1 -1
  214. package/vendor/pi/dist/utils/image-resize.js +1 -1
  215. package/vendor/pi/docs/cli.md +35 -12
  216. package/vendor/pi/docs/custom-provider.md +2 -0
  217. package/vendor/pi/docs/environment-variables.md +2 -0
  218. package/vendor/pi/docs/extensions.md +3192 -225
  219. package/vendor/pi/docs/keybindings.md +2 -2
  220. package/vendor/pi/docs/llama-cpp.md +27 -19
  221. package/vendor/pi/docs/mcp.md +6 -4
  222. package/vendor/pi/docs/message-types.md +1 -1
  223. package/vendor/pi/docs/models-configuration.md +9 -3
  224. package/vendor/pi/docs/models.md +2 -1
  225. package/vendor/pi/docs/nvidia-rtx-llama-cpp.md +5 -5
  226. package/vendor/pi/docs/packages.md +24 -0
  227. package/vendor/pi/docs/prompt-templates.md +1 -1
  228. package/vendor/pi/docs/providers.md +4 -2
  229. package/vendor/pi/docs/quickstart.md +7 -3
  230. package/vendor/pi/docs/rpc-commands.md +1 -1
  231. package/vendor/pi/docs/rpc.md +4 -2
  232. package/vendor/pi/docs/sessions.md +17 -3
  233. package/vendor/pi/docs/settings.md +6 -5
  234. package/vendor/pi/docs/slash-commands.md +3 -2
  235. package/vendor/pi/docs/terminal-setup.md +3 -1
  236. package/vendor/pi/docs/tmux.md +6 -0
  237. package/vendor/pi/docs/tui.md +4 -0
  238. package/vendor/pi/docs/windows.md +27 -0
  239. package/vendor/pi/examples/extensions/README.md +2 -1
  240. package/vendor/pi/examples/extensions/custom-provider-anthropic/index.ts +27 -31
  241. package/vendor/pi/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  242. package/vendor/pi/examples/extensions/custom-provider-anthropic/package.json +1 -1
  243. package/vendor/pi/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  244. package/vendor/pi/examples/extensions/debug-provider.ts +2 -2
  245. package/vendor/pi/examples/extensions/gondolin/index.ts +4 -7
  246. package/vendor/pi/examples/extensions/gondolin/package-lock.json +19 -29
  247. package/vendor/pi/examples/extensions/gondolin/package.json +2 -2
  248. package/vendor/pi/examples/extensions/plan-mode/index.ts +23 -13
  249. package/vendor/pi/examples/extensions/plan-mode/utils.ts +42 -16
  250. package/vendor/pi/examples/extensions/preset.ts +2 -0
  251. package/vendor/pi/examples/extensions/reload-runtime.ts +17 -5
  252. package/vendor/pi/examples/extensions/subagent/README.md +14 -11
  253. package/vendor/pi/examples/extensions/subagent/index.ts +392 -171
  254. package/vendor/pi/examples/extensions/todo.ts +7 -0
  255. package/vendor/pi/examples/extensions/tools.ts +2 -0
  256. package/vendor/pi/examples/extensions/with-deps/package-lock.json +2 -2
  257. package/vendor/pi/examples/extensions/with-deps/package.json +1 -1
  258. package/vendor/pi/examples/tsconfig.json +208 -0
  259. package/vendor/pi/package.json +15 -16
  260. package/vendor/pi/schemas/models.schema.json +66 -37
  261. package/vendor/pi/schemas/settings.schema.json +18 -1
  262. package/vendor/pi-ai/bedrock.js +1 -1
  263. package/vendor/pi-ai/oauth-load.js +1 -1
  264. package/web/dist/assets/{board-math-css-BPXakv_3.js → board-math-css-DKX6FcUS.js} +1 -1
  265. package/web/dist/assets/index-D11wi0uG.js +540 -0
  266. package/web/dist/assets/index-JedYumhY.css +1 -0
  267. package/web/dist/assets/{index-WCm6wwmM.js → index-jl30Gy8P.js} +1 -1
  268. package/web/dist/assets/pdf-worker-DdZgk2mV.js +57 -0
  269. package/web/dist/assets/pdf.worker.min-Bz_KHX45.js +55 -0
  270. package/web/dist/index.html +2 -2
  271. package/web/dist/theme.css +22 -0
  272. package/dist/chunks/anthropic-messages-M3SMXACA.js +0 -8
  273. package/dist/chunks/api-GM53PHIL-GFHEXXE6.js +0 -4
  274. package/dist/chunks/azure-openai-responses-76YWXHSB.js +0 -4
  275. package/dist/chunks/bedrock-converse-stream-5UPX4NTQ.js +0 -58
  276. package/dist/chunks/child-runner-3GHOWGZP.js +0 -4
  277. package/dist/chunks/chunk-2ZNLUY2U.js +0 -128
  278. package/dist/chunks/chunk-3F6WW7HR.js +0 -13
  279. package/dist/chunks/chunk-3OKHUVEM.js +0 -7
  280. package/dist/chunks/chunk-3YHOCPQU.js +0 -10
  281. package/dist/chunks/chunk-4EX2JJWB.js +0 -4
  282. package/dist/chunks/chunk-4LLH5OWM.js +0 -10
  283. package/dist/chunks/chunk-52T37Y47.js +0 -8
  284. package/dist/chunks/chunk-7MU2AKNM.js +0 -4
  285. package/dist/chunks/chunk-AAA3UBIS.js +0 -4
  286. package/dist/chunks/chunk-ASYQHJVQ.js +0 -9
  287. package/dist/chunks/chunk-BKHDWCRT.js +0 -79
  288. package/dist/chunks/chunk-CQLH4UVX.js +0 -4
  289. package/dist/chunks/chunk-CVC66CFV.js +0 -33
  290. package/dist/chunks/chunk-D6UA4BZC.js +0 -19
  291. package/dist/chunks/chunk-DGMNI4AO.js +0 -4
  292. package/dist/chunks/chunk-DHSA5ACV.js +0 -125
  293. package/dist/chunks/chunk-DPQPXBTP.js +0 -68
  294. package/dist/chunks/chunk-DXBSQXJL.js +0 -18
  295. package/dist/chunks/chunk-E7ZMYIY6.js +0 -30
  296. package/dist/chunks/chunk-EQITBTJC.js +0 -10
  297. package/dist/chunks/chunk-EXJA5RIX.js +0 -357
  298. package/dist/chunks/chunk-FF7UELTU.js +0 -4
  299. package/dist/chunks/chunk-FH74NME3.js +0 -115
  300. package/dist/chunks/chunk-FOQ7VLIL.js +0 -17
  301. package/dist/chunks/chunk-FX6MOGLR.js +0 -11
  302. package/dist/chunks/chunk-G2V65UBA.js +0 -4
  303. package/dist/chunks/chunk-HGPBHTVD.js +0 -6
  304. package/dist/chunks/chunk-J5DVLUKY.js +0 -6
  305. package/dist/chunks/chunk-JW2HFMTF.js +0 -4
  306. package/dist/chunks/chunk-KDYEGGMW.js +0 -4
  307. package/dist/chunks/chunk-KIGMAATV.js +0 -23
  308. package/dist/chunks/chunk-KIU5FAPY.js +0 -5
  309. package/dist/chunks/chunk-KIWMQPH7.js +0 -739
  310. package/dist/chunks/chunk-L6VCIGWS.js +0 -11
  311. package/dist/chunks/chunk-LACGULCN.js +0 -10
  312. package/dist/chunks/chunk-LMSQZ6TQ.js +0 -4
  313. package/dist/chunks/chunk-MEPASGPP.js +0 -6
  314. package/dist/chunks/chunk-MFAEUHMV.js +0 -28
  315. package/dist/chunks/chunk-NAA7GF6Q.js +0 -5
  316. package/dist/chunks/chunk-NKDMKRSB.js +0 -68
  317. package/dist/chunks/chunk-NKXV32S6.js +0 -4
  318. package/dist/chunks/chunk-NVX5IPRN.js +0 -4
  319. package/dist/chunks/chunk-O3JW2F7D.js +0 -8
  320. package/dist/chunks/chunk-OE4KH3NJ.js +0 -4
  321. package/dist/chunks/chunk-OISO5JXB.js +0 -4
  322. package/dist/chunks/chunk-OPYXNSMY.js +0 -4
  323. package/dist/chunks/chunk-OSEIQ7SS.js +0 -4
  324. package/dist/chunks/chunk-P52RMIYX.js +0 -6
  325. package/dist/chunks/chunk-PBJ5MPPX.js +0 -60
  326. package/dist/chunks/chunk-PZMGBKUR.js +0 -13
  327. package/dist/chunks/chunk-PZMXHA6X.js +0 -9
  328. package/dist/chunks/chunk-Q7CE3UIE.js +0 -133
  329. package/dist/chunks/chunk-QBKCAIJG.js +0 -4
  330. package/dist/chunks/chunk-QEOFEETJ.js +0 -4
  331. package/dist/chunks/chunk-QUUEQRIT.js +0 -4
  332. package/dist/chunks/chunk-RA6HKFBV.js +0 -4
  333. package/dist/chunks/chunk-REPYBMQS.js +0 -4
  334. package/dist/chunks/chunk-SKHLZ6XY.js +0 -9
  335. package/dist/chunks/chunk-TAWLERZA.js +0 -4
  336. package/dist/chunks/chunk-TWAEABGG.js +0 -52
  337. package/dist/chunks/chunk-TZFLHVOQ.js +0 -7
  338. package/dist/chunks/chunk-UD3NMUHR.js +0 -12
  339. package/dist/chunks/chunk-UNVEZI57.js +0 -4
  340. package/dist/chunks/chunk-VQUPKMDR.js +0 -4
  341. package/dist/chunks/chunk-W25TB3PU.js +0 -4
  342. package/dist/chunks/chunk-W5LGYSPZ.js +0 -4
  343. package/dist/chunks/chunk-WEZWKMYU.js +0 -4
  344. package/dist/chunks/chunk-XAJLZR7C.js +0 -28
  345. package/dist/chunks/chunk-XH6FMP3N.js +0 -71
  346. package/dist/chunks/chunk-XSRZHN63.js +0 -4
  347. package/dist/chunks/chunk-Y3GFB5XM.js +0 -8
  348. package/dist/chunks/chunk-YG7OEPR2.js +0 -6
  349. package/dist/chunks/chunk-YHIWOGVL.js +0 -4
  350. package/dist/chunks/chunk-YKKEI5GI.js +0 -4
  351. package/dist/chunks/chunk-YZSHTWNM.js +0 -92
  352. package/dist/chunks/chunk-Z4H3VDHI.js +0 -4
  353. package/dist/chunks/cli-5DBTRMHU.js +0 -53
  354. package/dist/chunks/client-XOGYH5UR.js +0 -4
  355. package/dist/chunks/cloudflare-workers-ai-system-one-32JCFHI3.js +0 -4
  356. package/dist/chunks/config-DJSQI77S-335IXHSM.js +0 -4
  357. package/dist/chunks/context-VCQH5OB6.js +0 -4
  358. package/dist/chunks/cost-PGGFI7QJ.js +0 -5
  359. package/dist/chunks/dist-PUKMZ7GW.js +0 -4
  360. package/dist/chunks/easter-egg-3d-MO4MOEVF.js +0 -4
  361. package/dist/chunks/es5-VNTQPCKX.js +0 -4
  362. package/dist/chunks/file-7BN7RCAY.js +0 -4
  363. package/dist/chunks/gateway-UCRPMR75.js +0 -36
  364. package/dist/chunks/github-copilot-HAI2DA62.js +0 -4
  365. package/dist/chunks/google-generative-ai-2VXWLHWI.js +0 -4
  366. package/dist/chunks/google-vertex-UA36QP2U.js +0 -4
  367. package/dist/chunks/init-HA7FAQ73.js +0 -4
  368. package/dist/chunks/kimi-coding-HMJRKCPA.js +0 -4
  369. package/dist/chunks/local-client-stop-SQRU7ZZM.js +0 -4
  370. package/dist/chunks/meta-KY3LNFV2.js +0 -4
  371. package/dist/chunks/mistral-conversations-34F66L3O.js +0 -7
  372. package/dist/chunks/model-resolver-N3DTAQ2S.js +0 -4
  373. package/dist/chunks/openai-codex-responses-ZBVHREB3.js +0 -12
  374. package/dist/chunks/openai-completions-VVIB26SH.js +0 -9
  375. package/dist/chunks/openai-responses-735XA2ZX.js +0 -6
  376. package/dist/chunks/openrouter-images-3IKETHAC.js +0 -4
  377. package/dist/chunks/pi-messages-I3E4ZFHA.js +0 -10
  378. package/dist/chunks/radius-HXRZVBDB.js +0 -4
  379. package/dist/chunks/remote-ops-BALZYKH6.js +0 -14
  380. package/dist/chunks/runner-PLVZDGHB.js +0 -4
  381. package/dist/chunks/runtime-6YLTA2ZD.js +0 -4
  382. package/dist/chunks/schedule-cli-OLASBBYJ.js +0 -4
  383. package/dist/chunks/slack-WAGSPZUX.js +0 -4
  384. package/dist/chunks/start-ui-http-QALT7C3P.js +0 -43
  385. package/dist/chunks/subagent-E3UC7ZHC.js +0 -4
  386. package/dist/chunks/tool-shims-Q6P6UXVC.js +0 -4
  387. package/dist/chunks/typesafe-system-one-6ULACYD4.js +0 -4
  388. package/dist/chunks/ui-board-4GYW6KKW.js +0 -5
  389. package/dist/chunks/ui-decision-U2FXSEC2.js +0 -4
  390. package/dist/chunks/ui-view-O7PLANT7.js +0 -4
  391. package/dist/chunks/virtual-modules-IDC5YKZJ.js +0 -4
  392. package/dist/chunks/waitpoint-2FGQBIAC.js +0 -5
  393. package/dist/chunks/workers-XN4PSTH6.js +0 -4
  394. package/vendor/aistatus/gateway-cli.js +0 -21
  395. package/vendor/pi/examples/extensions/sandbox/index.ts +0 -321
  396. package/vendor/pi/examples/extensions/sandbox/package-lock.json +0 -92
  397. package/vendor/pi/examples/extensions/sandbox/package.json +0 -19
  398. package/web/dist/assets/index-BHZpFXhc.js +0 -525
  399. package/web/dist/assets/index-DqWMdMkh.css +0 -1
  400. package/web/dist/assets/pdf-worker-Hp15W1QJ.js +0 -57
  401. package/web/dist/assets/pdf.worker.min-DnhTvCwe.js +0 -55
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{D as a,E as b,F as c}from"./chunk-KIU5FAPY.js";import"./chunk-Y6ZEVVL5.js";import"./chunk-LMSQZ6TQ.js";import"./chunk-JERCOLY3.js";import"./chunk-BGVHA2D4.js";import"./chunk-OE4KH3NJ.js";import"./chunk-5M4PFLRW.js";import"./chunk-MEPASGPP.js";import"./chunk-STUHNKQS.js";import"./chunk-Q4UGYGU5.js";import"./chunk-W5LGYSPZ.js";import"./chunk-NAA7GF6Q.js";import"./chunk-J5DVLUKY.js";import"./chunk-WHC7AYZD.js";export{a as buildChildEnv,c as childResult,b as runPiChild};
@@ -1,128 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as Ae,b as Oe,c as De,d as Ne,e as Fe,f as Pe,g as je,h as Ft,i as Le,j as Me}from"./chunk-6LZK4DDH.js";import{C as Be,G as Ke,J as Je,a as Pt,k as Ue,u as Ge,v as Ve,w as jt,x as He,y as We}from"./chunk-ASYQHJVQ.js";import{b as _e,c as Ce,d as Te,e as ke}from"./chunk-O3JW2F7D.js";import{e as Xe,h as qe}from"./chunk-HU6UIDEJ.js";import{m as Ee,o as xe,p as Re}from"./chunk-TZFLHVOQ.js";import{a as be,b as Se}from"./chunk-QEOFEETJ.js";import{a as Ie}from"./chunk-DGMNI4AO.js";import{b as ge,h as $e}from"./chunk-SUFW24P4.js";import{a as ze}from"./chunk-PMG4YGDU.js";import{l as fe,p as we,r as ve}from"./chunk-3YHOCPQU.js";import{a as ye}from"./chunk-PFMEUFJ7.js";import{b as yt}from"./chunk-W5LGYSPZ.js";import{a as Nt,b as wt,c as me,e as c}from"./chunk-E7ZMYIY6.js";import{c as de,e as pe}from"./chunk-NAA7GF6Q.js";import{a as Ot,c as ut,d as M,f as he,l as Dt}from"./chunk-J5DVLUKY.js";import{c as ps,e as ct}from"./chunk-WHC7AYZD.js";var Vt=ps((gr,hi)=>{"use strict";var Gt={to(t,e){return e?`\x1B[${e+1};${t+1}H`:`\x1B[${t+1}G`},move(t,e){let i="";return t<0?i+=`\x1B[${-t}D`:t>0&&(i+=`\x1B[${t}C`),e<0?i+=`\x1B[${-e}A`:e>0&&(i+=`\x1B[${e}B`),i},up:(t=1)=>`\x1B[${t}A`,down:(t=1)=>`\x1B[${t}B`,forward:(t=1)=>`\x1B[${t}C`,backward:(t=1)=>`\x1B[${t}D`,nextLine:(t=1)=>"\x1B[E".repeat(t),prevLine:(t=1)=>"\x1B[F".repeat(t),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},ks={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},Es={screen:"\x1B[2J",up:(t=1)=>"\x1B[1J".repeat(t),down:(t=1)=>"\x1B[J".repeat(t),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(t){let e="";for(let i=0;i<t;i++)e+=this.line+(i<t-1?Gt.up():"");return t&&(e+=Gt.left),e}};hi.exports={cursor:Gt,scroll:ks,erase:Es,beep:"\x07"}});var cs=ct(Ot(),1);import{mkdirSync as ft,writeFileSync as B,copyFileSync as as,existsSync as U,readFileSync as ce,readdirSync as In}from"fs";import{randomBytes as ts}from"crypto";import{execSync as ot}from"child_process";import*as p from"path";import*as H from"os";import{createInterface as bn}from"readline/promises";import{stdin as Rt}from"process";import{existsSync as Qs}from"node:fs";import{execSync as tn}from"node:child_process";import*as Ri from"node:path";import{styleText as Ht}from"node:util";import{stdout as Bt,stdin as pi}from"node:process";import*as Y from"node:readline";import xs from"node:readline";var Ye=(()=>{let t=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return e=>{let i=0;for(t.lastIndex=0;t.test(e);)i+=1;return e.length-i}})(),Ze=t=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,Qe=t=>t===8987||t===9001||t>=12272&&t<=12287||t>=12289&&t<=12350||t>=12441&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12783&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=65040&&t<=65049||t>=65072&&t<=65106||t>=65108&&t<=65126||t>=65128&&t<=65131||t>=127488&&t<=127490||t>=127504&&t<=127547||t>=127552&&t<=127560||t>=131072&&t<=196605||t>=196608&&t<=262141;var ms=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,fs=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,ti=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,gs=/\t{1,1000}/y,ei=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),$s=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,ys=new RegExp("\\p{M}+","gu"),ws={limit:1/0,ellipsis:""},ii=(t,e={},i={})=>{let s=e.limit??1/0,n=e.ellipsis??"",r=e?.ellipsisWidth??(n?ii(n,ws,i).width:0),o=0,a=i.controlWidth??0,u=i.tabWidth??8,h=i.emojiWidth??2,g=2,d=i.regularWidth??1,f=i.wideWidth??g,$=[[$s,d],[ms,o],[fs,a],[gs,u],[ei,h],[ti,f]],m=0,v=0,b=t.length,T=0,A=!1,O=b,L=Math.max(0,s-r),_=0,D=0,k=0,x=0;t:for(;;){if(D>_||v>=b&&v>m){let N=t.slice(_,D)||t.slice(m,v);T=0;for(let K of N.replaceAll(ys,"")){let P=K.codePointAt(0)||0;if(Ze(P)?x=g:Qe(P)?x=f:x=d,k+x>L&&(O=Math.min(O,Math.max(_,m)+T)),k+x>s){A=!0;break t}T+=K.length,k+=x}_=D=0}if(v>=b)break t;for(let N=0,K=$.length;N<K;N++){let[P,gt]=$[N];if(P.lastIndex=v,P.test(t)){if(T=P===ti?Ye(t.slice(v,P.lastIndex)):P===ei?1:P.lastIndex-v,x=T*gt,k+x>L&&(O=Math.min(O,v+Math.floor((L-k)/gt))),k+x>s){A=!0;break t}k+=x,_=m,D=v,v=m=P.lastIndex;continue t}}v+=1}return{width:A?L:k,index:A?O:b,truncated:A,ellipsed:A&&s>=r}},si=ii;var vs={limit:1/0,ellipsis:"",ellipsisWidth:0},Is=(t,e={})=>si(t,vs,e).width,j=Is;var vt="\x1B",ci="\x9B",bs=39,Mt="\x07",ui="[",Ss="]",li="m",Ut=`${Ss}8;;`,ni=new RegExp(`(?:\\${ui}(?<code>\\d+)m|\\${Ut}(?<uri>.*)${Mt})`,"y"),ri=t=>{if(t>=30&&t<=37||t>=90&&t<=97)return 39;if(t>=40&&t<=47||t>=100&&t<=107)return 49;if(t===1||t===2)return 22;if(t===3)return 23;if(t===4)return 24;if(t===7)return 27;if(t===8)return 28;if(t===9)return 29;if(t===0)return 0},oi=t=>`${vt}${ui}${t}${li}`,ai=t=>`${vt}${Ut}${t}${Mt}`,Lt=(t,e,i)=>{let s=e[Symbol.iterator](),n=!1,r=!1,o=t.at(-1),a=o===void 0?0:j(o),u=s.next(),h=s.next(),g=0;for(;!u.done;){let d=u.value,f=j(d);a+f<=i?t[t.length-1]+=d:(t.push(d),a=0),(d===vt||d===ci)&&(n=!0,r=e.startsWith(Ut,g+1)),n?r?d===Mt&&(n=!1,r=!1):d===li&&(n=!1):(a+=f,a===i&&!h.done&&(t.push(""),a=0)),u=h,h=s.next(),g+=d.length}o=t.at(-1),!a&&o!==void 0&&o.length&&t.length>1&&(t[t.length-2]+=t.pop())},_s=t=>{let e=t.split(" "),i=e.length;for(;i&&!j(e[i-1]);)i--;return i===e.length?t:e.slice(0,i).join(" ")+e.slice(i).join("")},Cs=(t,e,i={})=>{if(i.trim!==!1&&t.trim()==="")return"";let s="",n,r,o=t.split(" "),a=[""],u=0;for(let d=0;d<o.length;d++){let f=o[d];if(i.trim!==!1){let m=a.at(-1)??"",v=m.trimStart();m.length!==v.length&&(a[a.length-1]=v,u=j(v))}d!==0&&(u>=e&&(i.wordWrap===!1||i.trim===!1)&&(a.push(""),u=0),(u||i.trim===!1)&&(a[a.length-1]+=" ",u++));let $=j(f);if(i.hard&&$>e){let m=e-u,v=1+Math.floor(($-m-1)/e);Math.floor(($-1)/e)<v&&a.push(""),Lt(a,f,e),u=j(a.at(-1)??"");continue}if(u+$>e&&u&&$){if(i.wordWrap===!1&&u<e){Lt(a,f,e),u=j(a.at(-1)??"");continue}a.push(""),u=0}if(u+$>e&&i.wordWrap===!1){Lt(a,f,e),u=j(a.at(-1)??"");continue}a[a.length-1]+=f,u+=$}i.trim!==!1&&(a=a.map(d=>_s(d)));let h=a.join(`
5
- `),g=!1;for(let d=0;d<h.length;d++){let f=h[d];if(s+=f,g)g=!1;else if(g=f>="\uD800"&&f<="\uDBFF",g)continue;if(f===vt||f===ci){ni.lastIndex=d+1;let m=ni.exec(h)?.groups;if(m?.code!==void 0){let v=Number.parseFloat(m.code);n=v===bs?void 0:v}else m?.uri!==void 0&&(r=m.uri.length===0?void 0:m.uri)}if(h[d+1]===`
6
- `){r&&(s+=ai(""));let $=n?ri(n):void 0;n&&$&&(s+=oi($))}else f===`
7
- `&&(n&&ri(n)&&(s+=oi(n)),r&&(s+=ai(r)))}return s},Ts=/\r?\n/;function J(t,e,i){return String(t).normalize().split(Ts).map(s=>Cs(s,e,i)).join(`
8
- `)}var F=ct(Vt(),1);import{ReadStream as di}from"node:tty";function tt(t,e,i){if(!i.some(o=>!o.disabled))return t;let s=t+e,n=Math.max(i.length-1,0),r=s<0?n:s>n?0:s;return i[r]?.disabled?tt(r,e<0?-1:1,i):r}var Rs=["up","down","left","right","space","enter","cancel"],As=["January","February","March","April","May","June","July","August","September","October","November","December"],R={actions:new Set(Rs),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,date:{monthNames:[...As],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:(t,e)=>`There are only ${t} days in ${e}`,afterMin:t=>`Date must be on or after ${t.toISOString().slice(0,10)}`,beforeMax:t=>`Date must be on or before ${t.toISOString().slice(0,10)}`}}};function Kt(t,e){if(typeof t=="string")return R.aliases.get(t)===e;for(let i of t)if(i!==void 0&&Kt(i,e))return!0;return!1}function Os(t,e){if(t===e)return;let i=t.split(`
9
- `),s=e.split(`
10
- `),n=Math.max(i.length,s.length),r=[];for(let o=0;o<n;o++)i[o]!==s[o]&&r.push(o);return{lines:r,numLinesBefore:i.length,numLinesAfter:s.length,numLines:n}}var Ds=globalThis.process.platform.startsWith("win"),Wt=Symbol("clack:cancel");function nt(t){return t===Wt}function It(t,e){let i=t;i.isTTY&&i.setRawMode(e)}function mi({input:t=pi,output:e=Bt,overwrite:i=!0,hideCursor:s=!0}={}){let n=Y.createInterface({input:t,output:e,prompt:"",tabSize:1});Y.emitKeypressEvents(t,n),t instanceof di&&t.isTTY&&t.setRawMode(!0);let r=(o,{name:a,sequence:u})=>{let h=String(o);if(Kt([h,a,u],"cancel")){s&&e.write(F.cursor.show),process.exit(0);return}if(!i)return;Y.moveCursor(e,a==="return"?0:-1,a==="return"?-1:0,()=>{Y.clearLine(e,1,()=>{t.once("keypress",r)})})};return s&&e.write(F.cursor.hide),t.once("keypress",r),()=>{t.off("keypress",r),s&&e.write(F.cursor.show),t instanceof di&&t.isTTY&&!Ds&&t.setRawMode(!1),n.terminal=!1,n.close()}}var lt=t=>"columns"in t&&typeof t.columns=="number"?t.columns:80,Jt=t=>"rows"in t&&typeof t.rows=="number"?t.rows:20;function Z(t,e,i,s=i,n=i,r){let o=lt(t??Bt);return J(e,o-i.length,{hard:!0,trim:!1}).split(`
11
- `).map((a,u,h)=>{let g=r?r(a,u):a;return u===0?`${s}${g}`:u===h.length-1?`${n}${g}`:`${i}${g}`}).join(`
12
- `)}function fi(t,e){if("~standard"in t){let i=t["~standard"].validate(e);if(i instanceof Promise)throw new TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");return i.issues?.at(0)?.message}return t(e)}var et=class{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(e,i=!0){let{input:s=pi,output:n=Bt,render:r,signal:o,...a}=e;this.opts=a,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=r.bind(this),this._track=i,this._abortSignal=o,this.input=s,this.output=n}unsubscribe(){this._subscribers.clear()}setSubscriber(e,i){let s=this._subscribers.get(e)??[];s.push(i),this._subscribers.set(e,s)}on(e,i){this.setSubscriber(e,{cb:i})}once(e,i){this.setSubscriber(e,{cb:i,once:!0})}emit(e,...i){let s=this._subscribers.get(e)??[],n=[];for(let r of s)r.cb(...i),r.once&&n.push(()=>s.splice(s.indexOf(r),1));for(let r of n)r()}prompt(){return new Promise(e=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),e(Wt);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=xs.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),It(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(F.cursor.show),this.output.off("resize",this.render),It(this.input,!1),e(this.value)}),this.once("cancel",()=>{this.output.write(F.cursor.show),this.output.off("resize",this.render),It(this.input,!1),e(Wt)})})}_isActionKey(e,i){return e===" "}_shouldSubmit(e,i){return!0}_setValue(e){this.value=e,this.emit("value",this.value)}_setUserInput(e,i){this.userInput=e??"",this.emit("userInput",this.userInput),i&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(e,i){if(this._track&&i.name!=="return"&&(i.name&&this._isActionKey(e,i)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),i?.name&&(!this._track&&R.aliases.has(i.name)&&this.emit("cursor",R.aliases.get(i.name)),R.actions.has(i.name)&&this.emit("cursor",i.name)),e&&(e.toLowerCase()==="y"||e.toLowerCase()==="n")&&this.emit("confirm",e.toLowerCase()==="y"),this.emit("key",e,i),i?.name==="return"&&this._shouldSubmit(e,i)){if(this.opts.validate){let s=fi(this.opts.validate,this.value);s&&(this.error=s instanceof Error?s.message:s,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}Kt([e,i?.name,i?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
13
- `),It(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=J(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
14
- `).length-1;this.output.write(F.cursor.move(-999,e*-1))}render(){let e=J(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state==="initial")this.output.write(F.cursor.hide);else{let i=Os(this._prevFrame,e),s=Jt(this.output);if(this.restoreCursor(),i){let n=Math.max(0,i.numLinesAfter-s),r=Math.max(0,i.numLinesBefore-s),o=i.lines.find(a=>a>=n);if(o===void 0){this._prevFrame=e;return}if(i.lines.length===1){this.output.write(F.cursor.move(0,o-r)),this.output.write(F.erase.lines(1));let a=e.split(`
15
- `);this.output.write(a[o]),this._prevFrame=e,this.output.write(F.cursor.move(0,a.length-o-1));return}else if(i.lines.length>1){if(n<r)o=n;else{let u=o-r;u>0&&this.output.write(F.cursor.move(0,u))}this.output.write(F.erase.down());let a=e.split(`
16
- `).slice(o);this.output.write(a.join(`
17
- `)),this._prevFrame=e;return}}this.output.write(F.erase.down())}this.output.write(e),this.state==="initial"&&(this.state="active"),this._prevFrame=e}}};var bt=class extends et{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(e){super(e,!1),this.value=!!e.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",i=>{this.output.write(F.cursor.move(0,-1)),this.value=i,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}};var St=class extends et{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter(e=>e.disabled!==!0)}toggleAll(){let e=this._enabledOptions,i=this.value!==void 0&&this.value.length===e.length;this.value=i?[]:e.map(s=>s.value)}toggleInvert(){let e=this.value;if(!e)return;let i=this._enabledOptions.filter(s=>!e.includes(s.value));this.value=i.map(s=>s.value)}toggleValue(){this.value===void 0&&(this.value=[]);let e=this.value.includes(this._value);this.value=e?this.value.filter(i=>i!==this._value):[...this.value,this._value]}constructor(e){super(e,!1),this.options=e.options,this.value=[...e.initialValues??[]];let i=Math.max(this.options.findIndex(({value:s})=>s===e.cursorAt),0);this.cursor=this.options[i]?.disabled?tt(i,1,this.options):i,this.on("key",(s,n)=>{n.name==="a"&&this.toggleAll(),n.name==="i"&&this.toggleInvert()}),this.on("cursor",s=>{switch(s){case"left":case"up":this.cursor=tt(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=tt(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}},gi=class extends et{_mask="\u2022";get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state==="submit"||this.state==="cancel")return this.masked;let e=this.userInput;if(this.cursor>=e.length)return`${this.masked}${Ht(["inverse","hidden"],"_")}`;let i=this.masked,s=i.slice(0,this.cursor),n=i.slice(this.cursor,this.cursor+1),r=i.slice(this.cursor+1);return`${s}${Ht("inverse",n)}${r}`}clear(){this._clearUserInput()}constructor({mask:e,...i}){super(i),this._mask=e??"\u2022",this.on("userInput",s=>{this._setValue(s)}),this.on("finalize",()=>{this.value===void 0&&(this.value="")})}},$i=class extends et{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){let e=this._selectedValue;this.value=e===void 0?void 0:e.value}constructor(e){super(e,!1),this.options=e.options;let i=this.options.findIndex(({value:n})=>n===e.initialValue),s=i===-1?0:i;this.cursor=this.options[s]?.disabled?tt(s,1,this.options):s,this.changeValue(),this.on("cursor",n=>{switch(n){case"left":case"up":this.cursor=tt(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=tt(this.cursor,1,this.options);break}this.changeValue()})}};var _t=class extends et{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${this.userInput}\u2588`;let i=e.slice(0,this.cursor),s=e.slice(this.cursor,this.cursor+1),n=e.slice(this.cursor+1);return`${i}${Ht("inverse",s)}${n}`}get cursor(){return this._cursor}constructor(e){super({...e,initialUserInput:e.initialUserInput??e.initialValue}),this.on("userInput",i=>{this._setValue(i)}),this.on("finalize",()=>{this.value||(this.value=e.defaultValue),this.value===void 0&&(this.value="")})}};import{styleText as l,stripVTControlCharacters as Dr}from"node:util";import V from"node:process";var dt=ct(Vt(),1);function Ns(){return V.platform!=="win32"?V.env.TERM!=="linux":!!V.env.CI||!!V.env.WT_SESSION||!!V.env.TERMINUS_SUBLIME||V.env.ConEmuTask==="{cmd::Cmder}"||V.env.TERM_PROGRAM==="Terminus-Sublime"||V.env.TERM_PROGRAM==="vscode"||V.env.TERM==="xterm-256color"||V.env.TERM==="alacritty"||V.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Xt=Ns(),Fs=()=>process.env.CI==="true";var I=(t,e)=>Xt?t:e,Ps=I("\u25C6","*"),bi=I("\u25A0","x"),Si=I("\u25B2","x"),kt=I("\u25C7","o"),js=I("\u250C","T"),w=I("\u2502","|"),W=I("\u2514","\u2014"),jr=I("\u2510","T"),Lr=I("\u2518","\u2014"),qt=I("\u25CF",">"),Tt=I("\u25CB"," "),Ls=I("\u25FB","[\u2022]"),yi=I("\u25FC","[+]"),wi=I("\u25FB","[ ]"),Ms=I("\u25AA","\u2022"),vi=I("\u2500","-"),Us=I("\u256E","+"),Gs=I("\u251C","+"),Vs=I("\u256F","+"),Hs=I("\u2570","+"),Mr=I("\u256D","+"),Ws=I("\u25CF","\u2022"),Bs=I("\u25C6","*"),Ks=I("\u25B2","!"),Js=I("\u25A0","x"),pt=t=>{switch(t){case"initial":case"active":return l("cyan",Ps);case"cancel":return l("red",bi);case"error":return l("yellow",Si);case"submit":return l("green",kt)}},_i=t=>{switch(t){case"initial":case"active":return l("cyan",w);case"cancel":return l("red",w);case"error":return l("yellow",w);case"submit":return l("green",w)}};function Ci(t,e){let i=[`${e?`${l("cyan",w)} `:""}${t.join(" \u2022 ")}`];return e&&i.push(l("cyan",W)),i}var Ii=(t,e,i,s,n,r=!1)=>{let o=e,a=0;if(r)for(let u=s-1;u>=i;u--){let h=t[u];if(h&&(o-=h.length),a++,o<=n)break}else for(let u=i;u<s;u++){let h=t[u];if(h&&(o-=h.length),a++,o<=n)break}return{lineCount:o,removals:a}},zt=({cursor:t,options:e,style:i,output:s=process.stdout,maxItems:n=Number.POSITIVE_INFINITY,columnPadding:r=0,rowPadding:o=4})=>{let a=lt(s)-r,u=Jt(s),h=l("dim","..."),g=Math.max(u-o,0),d=Math.max(Math.min(n,g),5),f=0;t>=d-3&&(f=Math.max(Math.min(t-d+3,e.length-d),0));let $=d<e.length&&f>0,m=d<e.length&&f+d<e.length,v=Math.min(f+d,e.length),b=[],T=0;$&&T++,m&&T++;let A=f+($?1:0),O=v-(m?1:0);for(let _=A;_<O;_++){let D=e[_],k=D?i(D,_===t):"",x=J(k,a,{hard:!0,trim:!1}).split(`
18
- `);b.push(x),T+=x.length}if(T>g){let _=0,D=0,k=T,x=t-A,N=g,K=()=>Ii(b,k,0,x,N),P=()=>Ii(b,k,x+1,b.length,N,!0);$?({lineCount:k,removals:_}=K(),k>N&&(m||(N-=1),{lineCount:k,removals:D}=P())):(m||(N-=1),{lineCount:k,removals:D}=P(),k>N&&(N-=1,{lineCount:k,removals:_}=K())),_>0&&($=!0,b.splice(0,_)),D>0&&(m=!0,b.splice(b.length-D,D))}let L=[];$&&L.push(h);for(let _ of b)for(let D of _)L.push(D);return m&&L.push(h),L};var it=t=>{let e=t.active??"Yes",i=t.inactive??"No";return new bt({active:e,inactive:i,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue??!0,render(){let s=t.withGuide??R.withGuide,n=`${pt(this.state)} `,r=s?`${l("gray",w)} `:"",o=Z(t.output,t.message,r,n),a=`${s?`${l("gray",w)}
19
- `:""}${o}
20
- `,u=this.value?e:i;switch(this.state){case"submit":{let h=s?`${l("gray",w)} `:"";return`${a}${h}${l("dim",u)}`}case"cancel":{let h=s?`${l("gray",w)} `:"";return`${a}${h}${l(["strikethrough","dim"],u)}${s?`
21
- ${l("gray",w)}`:""}`}default:{let h=s?`${l("cyan",w)} `:"",g=s?l("cyan",W):"";return`${a}${h}${this.value?`${l("green",qt)} ${e}`:`${l("dim",Tt)} ${l("dim",e)}`}${t.vertical?s?`
22
- ${l("cyan",w)} `:`
23
- `:` ${l("dim","/")} `}${this.value?`${l("dim",Tt)} ${l("dim",i)}`:`${l("green",qt)} ${i}`}
24
- ${g}
25
- `}}}}).prompt()};var Xs=[`${l("dim","\u2191/\u2193")} to navigate`,`${l("dim","Space:")} select`,`${l("dim","Enter:")} confirm`],ht=(t,e)=>t.split(`
26
- `).map(i=>e(i)).join(`
27
- `),Yt=t=>{let e=(n,r)=>{let o=n.label??String(n.value);return r==="disabled"?`${l("gray",wi)} ${ht(o,a=>l(["strikethrough","gray"],a))}${n.hint?` ${l("dim",`(${n.hint??"disabled"})`)}`:""}`:r==="active"?`${l("cyan",Ls)} ${o}${n.hint?` ${l("dim",`(${n.hint})`)}`:""}`:r==="selected"?`${l("green",yi)} ${ht(o,a=>l("dim",a))}${n.hint?` ${l("dim",`(${n.hint})`)}`:""}`:r==="cancelled"?`${ht(o,a=>l(["strikethrough","dim"],a))}`:r==="active-selected"?`${l("green",yi)} ${o}${n.hint?` ${l("dim",`(${n.hint})`)}`:""}`:r==="submitted"?`${ht(o,a=>l("dim",a))}`:`${l("dim",wi)} ${ht(o,a=>l("dim",a))}`},i=t.required??!0,s=t.showInstructions??!0;return new St({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValues:t.initialValues,required:i,cursorAt:t.cursorAt,validate(n){if(i&&(n===void 0||n.length===0))return`Please select at least one option.
28
- ${l("reset",l("dim",`Press ${l(["gray","bgWhite","inverse"]," space ")} to select, ${l("gray",l("bgWhite",l("inverse"," enter ")))} to submit`))}`},render(){let n=t.withGuide??R.withGuide,r=Z(t.output,t.message,n?`${_i(this.state)} `:"",`${pt(this.state)} `),o=`${n?`${l("gray",w)}
29
- `:""}${r}
30
- `,a=this.value??[],u=(h,g)=>{if(h.disabled)return e(h,"disabled");let d=a.includes(h.value);return g&&d?e(h,"active-selected"):d?e(h,"selected"):e(h,g?"active":"inactive")};switch(this.state){case"submit":{let h=this.options.filter(({value:d})=>a.includes(d)).map(d=>e(d,"submitted")).join(l("dim",", "))||l("dim","none"),g=Z(t.output,h,n?`${l("gray",w)} `:"");return`${o}${g}`}case"cancel":{let h=this.options.filter(({value:d})=>a.includes(d)).map(d=>e(d,"cancelled")).join(l("dim",", "));if(h.trim()==="")return`${o}${l("gray",w)}`;let g=Z(t.output,h,n?`${l("gray",w)} `:"");return`${o}${g}${n?`
31
- ${l("gray",w)}`:""}`}case"error":{let h=n?`${l("yellow",w)} `:"",g=this.error.split(`
32
- `).map(($,m)=>m===0?`${n?`${l("yellow",W)} `:""}${l("yellow",$)}`:` ${$}`).join(`
33
- `),d=o.split(`
34
- `).length,f=g.split(`
35
- `).length+1;return`${o}${h}${zt({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:h.length,rowPadding:d+f,style:u}).join(`
36
- ${h}`)}
37
- ${g}
38
- `}default:{let h=n?`${l("cyan",w)} `:"",g=o.split(`
39
- `).length,d=s?Ci(Xs,n):n?[l("cyan",W)]:[],f=d.join(`
40
- `),$=d.length+1;return`${o}${h}${zt({output:t.output,options:this.options,cursor:this.cursor,maxItems:t.maxItems,columnPadding:h.length,rowPadding:g+$,style:u}).join(`
41
- ${h}`)}
42
- ${f}
43
- `}}}}).prompt()};var y={message:(t=[],{symbol:e=l("gray",w),secondarySymbol:i=l("gray",w),output:s=process.stdout,spacing:n=1,withGuide:r}={})=>{let o=[],a=r??R.withGuide,u=a?i:"",h=a?`${e} `:"",g=a?`${i} `:"";for(let f=0;f<n;f++)o.push(u);let d=Array.isArray(t)?t:t.split(`
44
- `);if(d.length>0){let[f,...$]=d;f.length>0?o.push(`${h}${f}`):o.push(a?e:"");for(let m of $)m.length>0?o.push(`${g}${m}`):o.push(a?i:"")}s.write(`${o.join(`
45
- `)}
46
- `)},info:(t,e)=>{y.message(t,{...e,symbol:l("blue",Ws)})},success:(t,e)=>{y.message(t,{...e,symbol:l("green",Bs)})},step:(t,e)=>{y.message(t,{...e,symbol:l("green",kt)})},warn:(t,e)=>{y.message(t,{...e,symbol:l("yellow",Ks)})},warning:(t,e)=>{y.warn(t,e)},error:(t,e)=>{y.message(t,{...e,symbol:l("red",Js)})}},Ti=(t="",e)=>{let i=e?.output??process.stdout,s=e?.withGuide??R.withGuide?`${l("gray",W)} `:"";i.write(`${s}${l("red",t)}
47
-
48
- `)},ki=(t="",e)=>{let i=e?.output??process.stdout,s=e?.withGuide??R.withGuide?`${l("gray",js)} `:"";i.write(`${s}${t}
49
- `)},Ei=(t="",e)=>{let i=e?.output??process.stdout,s=e?.withGuide??R.withGuide?`${l("gray",w)}
50
- ${l("gray",W)} `:"";i.write(`${s}${t}
51
-
52
- `)};var qs=t=>t,zs=(t,e,i)=>{let s={hard:!0,trim:!1},n=J(t,e,s).split(`
53
- `),r=n.reduce((u,h)=>Math.max(j(h),u),0),o=n.map(i).reduce((u,h)=>Math.max(j(h),u),0),a=e-(o-r);return J(t,a,s)},mt=(t="",e="",i)=>{let s=i?.output??V.stdout,n=i?.withGuide??R.withGuide,r=i?.format??qs,o=["",...zs(t,lt(s)-6,r).split(`
54
- `).map(r),""],a=j(e),u=Math.max(o.reduce((f,$)=>{let m=j($);return m>f?m:f},0),a)+2,h=o.map(f=>`${l("gray",w)} ${f}${" ".repeat(u-j(f))}${l("gray",w)}`).join(`
55
- `),g=n?`${l("gray",w)}
56
- `:"",d=n?Gs:Hs;s.write(`${g}${l("green",kt)} ${l("reset",e)} ${l("gray",vi.repeat(Math.max(u-a-1,1))+Us)}
57
- ${h}
58
- ${l("gray",d+vi.repeat(u+2)+Vs)}
59
- `)},st=t=>new gi({validate:t.validate,mask:t.mask??Ms,signal:t.signal,input:t.input,output:t.output,render(){let e=t.withGuide??R.withGuide,i=`${e?`${l("gray",w)}
60
- `:""}${pt(this.state)} ${t.message}
61
- `,s=this.userInputWithCursor,n=this.masked;switch(this.state){case"error":{let r=e?`${l("yellow",w)} `:"",o=e?`${l("yellow",W)} `:"",a=n??"";return t.clearOnError&&this.clear(),`${i.trim()}
62
- ${r}${a}
63
- ${o}${l("yellow",this.error)}
64
- `}case"submit":{let r=e?`${l("gray",w)} `:"",o=n?l("dim",n):"";return`${i}${r}${o}`}case"cancel":{let r=e?`${l("gray",w)} `:"",o=n?l(["strikethrough","dim"],n):"";return`${i}${r}${o}${n&&e?`
65
- ${l("gray",w)}`:""}`}default:{let r=e?`${l("cyan",w)} `:"",o=e?l("cyan",W):"";return`${i}${r}${s}
66
- ${o}
67
- `}}}}).prompt();var Ys=t=>l("magenta",t),xi=({indicator:t="dots",onCancel:e,output:i=process.stdout,cancelMessage:s,errorMessage:n,frames:r=Xt?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:o=Xt?80:120,signal:a,...u}={})=>{let h=Fs(),g,d,f=!1,$=!1,m="",v,b=performance.now(),T=lt(i),A=u?.styleFrame??Ys,O=C=>{let G=C>1?n??R.messages.error:s??R.messages.cancel;$=C===1,f&&(at(G,C),$&&typeof e=="function"&&e())},L=()=>O(2),_=()=>O(1),D=()=>{process.on("uncaughtExceptionMonitor",L),process.on("unhandledRejection",L),process.on("SIGINT",_),process.on("SIGTERM",_),process.on("exit",O),a&&a.addEventListener("abort",_)},k=()=>{process.removeListener("uncaughtExceptionMonitor",L),process.removeListener("unhandledRejection",L),process.removeListener("SIGINT",_),process.removeListener("SIGTERM",_),process.removeListener("exit",O),a&&a.removeEventListener("abort",_)},x=()=>{if(v===void 0)return;h&&i.write(`
68
- `);let C=J(v,T,{hard:!0,trim:!1}).split(`
69
- `);C.length>1&&i.write(dt.cursor.up(C.length-1)),i.write(dt.cursor.to(0)),i.write(dt.erase.down())},N=C=>C.replace(/\.+$/,""),K=C=>{let G=(performance.now()-C)/1e3,X=Math.floor(G/60),q=Math.floor(G%60);return X>0?`[${X}m ${q}s]`:`[${q}s]`},P=u.withGuide??R.withGuide,gt=(C="")=>{f=!0,g=mi({output:i}),m=N(C),b=performance.now(),P&&i.write(`${l("gray",w)}
70
- `);let G=0,X=0;D(),d=setInterval(()=>{if(h&&m===v)return;x(),v=m;let q=A(r[G]),$t;if(h)$t=`${q} ${m}...`;else if(t==="timer")$t=`${q} ${m} ${K(b)}`;else{let ds=".".repeat(Math.floor(X)).slice(0,3);$t=`${q} ${m}${ds}`}let hs=J($t,T,{hard:!0,trim:!1});i.write(hs),G=G+1<r.length?G+1:0,X=X<4?X+.125:0},o)},at=(C="",G=0,X=!1)=>{if(!f)return;f=!1,clearInterval(d),x();let q=G===0?l("green",kt):G===1?l("red",bi):l("red",Si);m=C??m,X||(t==="timer"?i.write(`${q} ${m} ${K(b)}
71
- `):i.write(`${q} ${m}
72
- `)),k(),g()};return{start:gt,stop:(C="")=>at(C,0),message:(C="")=>{m=N(C??m)},cancel:(C="")=>at(C,1),error:(C="")=>at(C,2),clear:()=>at("",0,!0),get isCancelled(){return $}}},Ur={light:I("\u2500","-"),heavy:I("\u2501","="),block:I("\u2588","#")};var Zs=[`${l("dim","\u2191/\u2193")} to navigate`,`${l("dim","Enter:")} confirm`],Ct=(t,e)=>t.includes(`
73
- `)?t.split(`
74
- `).map(i=>e(i)).join(`
75
- `):e(t),rt=t=>{let e=(s,n)=>{if(s===void 0)return"";let r=s.label??String(s.value);switch(n){case"disabled":return`${l("gray",Tt)} ${Ct(r,o=>l("gray",o))}${s.hint?` ${l("dim",`(${s.hint??"disabled"})`)}`:""}`;case"selected":return`${Ct(r,o=>l("dim",o))}`;case"active":return`${l("green",qt)} ${r}${s.hint?` ${l("dim",`(${s.hint})`)}`:""}`;case"cancelled":return`${Ct(r,o=>l(["strikethrough","dim"],o))}`;default:return`${l("dim",Tt)} ${Ct(r,o=>l("dim",o))}`}},i=t.showInstructions??!0;return new $i({options:t.options,signal:t.signal,input:t.input,output:t.output,initialValue:t.initialValue,render(){let s=t.withGuide??R.withGuide,n=`${pt(this.state)} `,r=`${_i(this.state)} `,o=Z(t.output,t.message,r,n),a=`${s?`${l("gray",w)}
76
- `:""}${o}
77
- `;switch(this.state){case"submit":{let u=s?`${l("gray",w)} `:"",h=Z(t.output,e(this.options[this.cursor],"selected"),u);return`${a}${h}`}case"cancel":{let u=s?`${l("gray",w)} `:"",h=Z(t.output,e(this.options[this.cursor],"cancelled"),u);return`${a}${h}${s?`
78
- ${l("gray",w)}`:""}`}default:{let u=s?`${l("cyan",w)} `:"",h=a.split(`
79
- `).length,g=i?Ci(Zs,s):s?[l("cyan",W)]:[],d=g.join(`
80
- `),f=g.length+1;return`${a}${u}${zt({output:t.output,cursor:this.cursor,options:this.options,maxItems:t.maxItems,columnPadding:u.length,rowPadding:h+f,style:($,m)=>e($,$.disabled?"disabled":m?"active":"inactive")}).join(`
81
- ${u}`)}
82
- ${d}
83
- `}}}}).prompt()};var Gr=`${l("gray",w)} `;var Q=t=>new _t({validate:t.validate,placeholder:t.placeholder,defaultValue:t.defaultValue,initialValue:t.initialValue,output:t.output,signal:t.signal,input:t.input,render(){let e=t?.withGuide??R.withGuide,i=`${`${e?`${l("gray",w)}
84
- `:""}${pt(this.state)} `}${t.message}
85
- `,s=t.placeholder&&t.placeholder.length>0?l("inverse",t.placeholder[0])+l("dim",t.placeholder.slice(1)):l(["inverse","hidden"],"_"),n=this.userInput?this.userInputWithCursor:s,r=this.value??"";switch(this.state){case"error":{let o=this.error?` ${l("yellow",this.error)}`:"",a=e?`${l("yellow",w)} `:"",u=e?l("yellow",W):"";return`${i.trim()}
86
- ${a}${n}
87
- ${u}${o}
88
- `}case"submit":{let o=r?` ${l("dim",r)}`:"",a=e?l("gray",w):"";return`${i}${a}${o}`}case"cancel":{let o=r?` ${l(["strikethrough","dim"],r)}`:"",a=e?l("gray",w):"";return`${i}${a}${o}${r.trim()?`
89
- ${a}`:""}`}default:{let o=e?`${l("cyan",w)} `:"",a=e?l("cyan",W):"";return`${i}${o}${n}
90
- ${a}
91
- `}}}}).prompt();var Ai=be;function Oi(){return process.platform==="win32"?"https://git-scm.com/download/win (Git for Windows, including Git Bash)":process.platform==="darwin"?"xcode-select --install (or brew install git if you use Homebrew)":"Install Git via your package manager or https://git-scm.com/downloads"}function Qt(){return Ai()?!0:process.platform!=="win32"?(y.info(c("init.git.optional")),!1):(y.warn(c("init.git.required")),y.info(c("init.git.manualHint",{hint:Oi()})),!1)}function Di(t){if(!Qs(Ri.join(t,".git")))try{tn("git init",{cwd:t,stdio:"pipe"})}catch(e){y.warn(c("init.git.initFailed",{message:e instanceof Error?e.message:String(e)}))}}import{randomUUID as nn}from"node:crypto";import{execSync as en}from"node:child_process";function te(t){if(nt(t))throw new S(c("init.auth.cancelled"),130);return t}function sn(t){let e=i=>process.stderr.write(`${i}
92
- `);if(t.kind==="auth_url"){e(c("init.auth.openBrowser",{url:t.url}));return}if(t.kind==="device_code"){e(c("init.auth.deviceCode",{url:t.verificationUri,code:t.userCode}));return}if(e(t.message),t.kind==="info")for(let i of t.links??[])e(i.url)}function Ni(){let t=process.stderr;return{async select(e,i,s){if(!i.length)throw new S(c("init.auth.noCapabilities"));return te(await rt({message:e,options:i,output:t,signal:s}))},async secret(e,i){return te(await st({message:e,output:t,signal:i}))},async confirm(e){return te(await it({message:e,initialValue:!1,output:t}))},notify:sn}}async function Fi(t,e){let i=e?null:await import("./init-HA7FAQ73.js"),s=e??{installed:()=>i.isBackendInstalled("claude"),install:()=>en(i.getInstallCommand("claude"),{stdio:"pipe",timeout:12e4})};if(s.installed())return!0;if(!await t.confirm(c("init.auth.installPrompt")))return!1;try{s.install()}catch{throw new S(c("init.auth.installFailed"))}if(!s.installed())throw new S(c("init.auth.pathMissing"));return!0}var S=class extends Error{exitCode;constructor(e,i=1){super(e),this.exitCode=i}};function rn(){return ze({name:"cortex auth login",description:c("init.auth.help"),usage:"cortex auth login [--backend pi|claude] [--provider ID] [--auth-type oauth|api_key]",options:[{flag:"--backend pi|claude",description:c("init.auth.backendOption")},{flag:"--provider ID",description:c("init.auth.providerOption")},{flag:"--auth-type oauth|api_key",description:c("init.auth.typeOption")},{flag:"--help, -h",description:c("cmd.auth.cli.helpDescription")}],examples:[{description:c("init.auth.exampleProvider"),command:"cortex auth login"},{description:c("init.auth.exampleClaude"),command:"cortex auth login --backend claude --provider anthropic --auth-type oauth"}],labels:{usage:c("cmd.auth.cli.helpUsage"),commands:c("cmd.auth.cli.helpCommands"),options:c("cmd.auth.cli.helpOptions"),examples:c("cmd.auth.cli.helpExamples")}})}function on(t){let e={},i={"--backend":"backend","--provider":"provider","--auth-type":"authType"};for(let s=0;s<t.length;s+=2){let n=i[t[s]];if(!n||!t[s+1]||t[s+1].startsWith("--")||e[n])throw new S(c("init.auth.invalidOptions"));e[n]=t[s+1]}if(e.backend&&!["pi","claude"].includes(e.backend))throw new S(c("init.auth.invalidBackend"));if(e.authType&&!["oauth","api_key"].includes(e.authType))throw new S(c("init.auth.invalidType"));return e}async function an(t,e){let i=t.backend??await e.ui.select(c("init.auth.backend"),[{value:"pi",label:c("init.auth.bundled")},{value:"claude",label:"Claude Code"}]),n=(await e.readStatus()).accounts.filter(u=>u.backend===i&&u.capabilities.length),r=t.provider??await e.ui.select(c("init.auth.provider"),n.map(u=>({value:u.provider,label:`${u.label} (${c(`cmd.auth.state.${u.state}`)})`}))),o=n.find(u=>u.provider===r);if(!o)throw new S(c("init.auth.unavailable"));let a=t.authType??await e.ui.select(c("init.auth.type"),o.capabilities.map(u=>({value:u,label:c(`init.auth.${u}`)})));if(!o.capabilities.includes(a))throw new S(c("init.auth.unsupported",{values:o.capabilities.join(", ")}));if(i==="claude"&&!await e.ensureClaude())throw new S(c("init.auth.installDeclined"),130);return{backend:i,provider:r,authType:a,channel:"cli",sessionId:nn()}}async function cn(t,e,i){let s=t.pendingPrompt,n=AbortSignal.any([i,AbortSignal.timeout(Math.max(1,Date.parse(t.expiresAt)-Date.now()))]),r;try{r=s.kind==="select"?await e.ui.select(s.message,(s.options??[]).map(o=>({value:o.id,label:o.label})),n):await e.ui.secret(s.message,n),n.throwIfAborted()}catch(o){throw i.aborted?new S(c("init.auth.cancelled"),130):n.aborted?new S(c("init.auth.expired")):o}return e.service.respond(t.flowId,r)}async function un(t,e,i){let s=t,n="";for(;!["done","failed","cancelled"].includes(s.step);){if(i.aborted)throw new S(c("init.auth.cancelled"),130);if(Date.now()>=Date.parse(s.expiresAt))throw new S(c("init.auth.expired"));let r=JSON.stringify(s.notice);if(s.notice&&n!==r&&e.ui.notify(s.notice),n=r,s.pendingPrompt){s=await cn(s,e,i);continue}await new Promise(a=>setTimeout(a,150));let o=e.service.getState(s.flowId);if(!o)throw new S(c("init.auth.expired"));s=o}return s}async function ln(t,e){let i=await an(t,e),s=await e.service.start(i),n,r=new AbortController,o=()=>r.abort();process.once("SIGINT",o);try{n=await un(s,e,r.signal)}catch(u){throw await e.service.cancel(s.flowId).catch(()=>{}),r.signal.aborted?new S(c("init.auth.cancelled"),130):u}finally{process.removeListener("SIGINT",o)}if(n.step!=="done")throw new S(c(n.step==="cancelled"?"init.auth.cancelled":"init.auth.failed"),n.step==="cancelled"?130:1);let a=await e.sync(i.backend);return{exitCode:0,stderr:"",stdout:JSON.stringify({ok:!0,backend:i.backend,provider:i.provider,authType:i.authType,state:"done",sync:a,inferenceVerified:!1})}}function ee(){let t=Ni();return{tty:!!process.stdin.isTTY&&!!process.stderr.isTTY,readStatus:Be,ui:t,service:Ke,ensureClaude:()=>Fi(t),sync:async e=>{let i=await We({backends:[e]});return{...i,reason:i.reason&&i.reason!=="no-endpoints"?"sync-failed":i.reason}}}}async function Pi(t,e=ee()){if(t.includes("--help")||t.includes("-h"))return{exitCode:0,stdout:rn(),stderr:""};let i=de({consoleToStderr:!0,files:!1,console:!1});try{let s=on(t);if(!e.tty)throw new S(c("init.auth.ttyRequired"));return await ln(s,e)}catch(s){let n=s instanceof S?s:new S(c("init.auth.failed"));return{exitCode:n.exitCode,stdout:JSON.stringify({ok:!1,state:n.exitCode===130?"cancelled":"failed"}),stderr:n.message}}finally{i()}}function ie(t){return[...new Set(t.accounts.filter(e=>[e,...e.credentials??[]].some(i=>i.state==="logged-in"||i.state==="expiring")).map(e=>e.backend))]}async function ji(t,e){try{let i=await t.readStatus();return e({step:"auth",state:ie(i).length?"configured":!i.piRuntime.available||i.accounts.some(s=>s.state==="unknown")?"unknown":"needs-login",inferenceVerified:!1,accounts:i.accounts.map(s=>({backend:s.backend,provider:s.provider,state:s.state})),runtimeAvailable:i.piRuntime.available}),i}catch{return e({step:"auth",state:"unknown",reason:"detection-failed",inferenceVerified:!1}),null}}async function Li(t,e,i=ee()){let s=await ji(i,e);if(!t)return s?ie(s):[];for(;;){let n=s?ie(s):[];i.ui.notify({kind:"info",message:s?s.accounts.map(o=>`${o.backend} / ${o.label}: ${c(`cmd.auth.state.${o.state}`)}`).join(`
93
- `):c("init.auth.detectionFailed")});let r=await i.ui.select(c("init.auth.setup"),[...n.length?[{value:"continue",label:c("init.auth.continue")}]:[],{value:"login",label:c("init.auth.login")},{value:"rescan",label:c("init.auth.rescan")},{value:"skip",label:c("init.auth.skip")}]);if(r==="skip")return[];if(r==="continue")return n;if(r==="login"){let o=await Pi([],{...i,sync:async()=>({configured:!1,endpoints:0,defaultSet:!1,favorites:[],reason:"deferred-to-init"})});if(o.exitCode===130)throw new S(c("init.cancel"),130);i.ui.notify({kind:"info",message:o.stderr||c("init.auth.saved")})}s=await ji(i,e)}}import{existsSync as hn,mkdirSync as dn,readFileSync as Ui,writeFileSync as pn}from"node:fs";import Mi from"node:path";function Gi(t){if(t===void 0)return;let e=fe.safeParse(t);return e.success?e.data:void 0}function mn(t){if(!hn(t))return{};let e=JSON.parse(Ui(t,"utf8"));if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must contain a JSON object`);return e}function Vi(t,e){let i=Mi.join(e.configDir,"settings.json"),s=mn(i);dn(e.configDir,{recursive:!0}),pn(i,`${JSON.stringify({...s,telemetryEnabled:t.enabled},null,2)}
94
- `,"utf8");let n=Mi.join(e.storeDir,"telemetry","install-id");t.installId&&!fn(n)&&ve(t.installId,n)}function fn(t){try{return we(Ui(t,"utf8").trim())}catch{return!1}}var Ki=ct(Ot(),1);import*as Bi from"readline";import*as se from"path";function ne(t,e,i){let s=`${e}=${i}`,n=t===""?[]:t.replace(/\n+$/,"").split(`
95
- `),r=new RegExp(`^\\s*(?:export\\s+)?${e}\\s*=`),o=n.map(a=>r.test(a)).lastIndexOf(!0);if(o>=0){if(n[o]===s)return t;n[o]=s}else n.push(s);return n.join(`
96
- `)+`
97
- `}function xt(t,e,i){return yt(t,s=>ne(s,e,i),{mode:384})}function Hi(){return["Manage Feishu user-identity login (FEISHU_AUTH_MODE=user)","","Usage: cortex feishu <login|status|logout> [options]",""," login Authorize a Feishu user account via the OAuth device flow"," (prints a URL to open in any browser \u2014 no redirect URI needed)"," status Show the current auth mode and stored user-token state"," logout Delete the stored user token","","Options:"," --scope <scopes> Override the requested scopes (default: docx/sheets/bitable/wiki +"," space:document:delete \u2014 an all-\u514D\u5BA1 set; offline_access is always"," added). The review-gated drive:drive / drive:drive:readonly are"," avoided; add the latter via --scope for docx canonical URLs."," --manual Use the legacy authorize-URL + paste-the-code flow instead"," --redirect-uri <url> Redirect URI for --manual only (default: $FEISHU_REDIRECT_URI)"," --help, -h Show this help"].join(`
98
- `)}function gn(t){let e=Bi.createInterface({input:process.stdin,output:process.stdout});return new Promise(i=>e.question(t,s=>{e.close(),i(s)}))}function Wi(t,e){let i=t.indexOf(e);return i!==-1&&t[i+1]?t[i+1]:void 0}function Et(t){return t?new Date(t).toISOString():"unknown"}async function Ji(t,e={}){let i=t[0];if(!i||i==="--help"||i==="-h")return{exitCode:i?0:1,stdout:Hi(),stderr:""};let s=e.env??process.env;e.loadDotenv!==!1&&!e.env&&Ki.config({path:se.join(Dt,".env")});let n=e.tokenFile??Oe(),r=s.FEISHU_DOMAIN||void 0;switch(i){case"login":{let o=s.FEISHU_APP_ID,a=s.FEISHU_APP_SECRET;if(!o||!a)return{exitCode:1,stdout:"",stderr:"Missing FEISHU_APP_ID / FEISHU_APP_SECRET. Run `cortex init` or set them in the .env first.\n"};let u=Wi(t,"--scope")??s.FEISHU_USER_SCOPE??Ae,h=r==="lark"?"lark (larksuite.com)":"feishu (feishu.cn)",g=e.envFile??se.join(Dt,".env"),d=async()=>{if(e.loadDotenv===!1)return!1;try{return await xt(g,"FEISHU_AUTH_MODE","user"),!0}catch{return!1}},f=(m,v)=>({exitCode:0,stderr:"",stdout:["","Logged in as Feishu user.",` region: ${h}`,` scope: ${m.scope??"(default)"}`,` access expires: ${Et(m.access_expires_at)}`,` refresh expires:${Et(m.refresh_expires_at)}`,` token file: ${n}`,"",v?`FEISHU_AUTH_MODE=user written to ${g} \u2014 restart Cortex for doc tools to use this identity.`:"Set FEISHU_AUTH_MODE=user in your .env and restart Cortex for doc tools to use this identity.",""].join(`
99
- `)});if(t.includes("--manual")){let m=Wi(t,"--redirect-uri")??s.FEISHU_REDIRECT_URI;if(!m)return{exitCode:1,stdout:"",stderr:`--manual needs a redirect URI. Set FEISHU_REDIRECT_URI (registered in the Feishu app console) or pass --redirect-uri.
100
- `};let v=De({appId:o,redirectUri:m,scope:u,state:"cortex",domain:r});process.stdout.write(["1) Open this URL in a browser and authorize:","",` ${v}`,"","2) After authorizing you will be redirected to your redirect URI."," Copy the authorization code (the `code` query param) \u2014 or the whole redirected URL.",""].join(`
101
- `));let T=await(e.prompt??gn)("Paste the code or callback URL: "),A=Ne(T);if(!A)return{exitCode:1,stdout:"",stderr:`Could not read an authorization code from the input.
102
- `};try{let O=await Fe({appId:o,appSecret:a,code:A,redirectUri:m,domain:r,fetchImpl:e.fetchImpl,now:e.now});return Ft(O,n),f(O,await d())}catch(O){return{exitCode:1,stdout:"",stderr:`Login failed: ${O.message}
103
- `}}}let $;try{$=await Pe({appId:o,appSecret:a,scope:u,domain:r,fetchImpl:e.fetchImpl})}catch(m){return{exitCode:1,stdout:"",stderr:`${m.message}
104
- `}}process.stdout.write([`Authorizing a Feishu user account (region: ${h}).`,"","1) Open this URL in a browser and confirm:","",` ${$.verification_uri_complete}`,...$.user_code?["",` verification code: ${$.user_code}`]:[],"","2) Waiting for authorization"].join(`
105
- `));try{let m=await je({appId:o,appSecret:a,deviceCode:$.device_code,interval:$.interval,expiresIn:$.expires_in,domain:r,fetchImpl:e.fetchImpl,now:e.now,sleep:e.sleep,onPending:()=>process.stdout.write(".")});return Ft(m,n),f(m,await d())}catch(m){return{exitCode:1,stdout:"",stderr:`
106
- Login failed: ${m.message}
107
- `}}}case"status":{let o=s.FEISHU_AUTH_MODE==="user"?"user":"bot",a=Le(n),u=[`Feishu auth mode: ${o}`,`Token file: ${n}`];if(!a)u.push("User token: not logged in (no token stored)."),o==="user"&&u.push("Doc tools will fail until you run `cortex feishu login`.");else{let h=(e.now??Date.now)(),g=h<a.access_expires_at,d=h<a.refresh_expires_at,f=g?"valid":d?"expired (refreshable)":"expired (re-login needed)";u.push(`User token: logged in \u2014 ${f}`,` scope: ${a.scope??"(default)"}`,` access expires: ${Et(a.access_expires_at)}`,` refresh expires:${Et(a.refresh_expires_at)}`)}return{exitCode:0,stdout:u.join(`
108
- `)+`
109
- `,stderr:""}}case"logout":return{exitCode:0,stderr:"",stdout:Me(n)?`Removed stored Feishu user token (${n}).
110
- `:`No stored Feishu user token to remove.
111
- `};default:return{exitCode:1,stdout:"",stderr:`Unknown subcommand '${i}'.
112
-
113
- ${Hi()}
114
- `}}}var oe=ct(Ot(),1);import{existsSync as Xi,readFileSync as qi}from"fs";import*as re from"path";var $n=["cortexui://localhost","http://cortexui.localhost","tauri://localhost","http://tauri.localhost"],yn=3004;function zi(t,e){if(Xi(t))try{return oe.parse(qi(t,"utf-8"))[e]?.trim()||void 0}catch{return}}async function wn(t){let e=re.join(t,"settings.json"),i=!1;return await yt(e,s=>{let n={};if(s.trim()){let a=JSON.parse(s);if(!a||typeof a!="object"||Array.isArray(a))throw new TypeError("settings.json must contain a JSON object");n=a}let r=Array.isArray(n.uiCorsOrigins)?n.uiCorsOrigins.filter(a=>typeof a=="string"):[],o=$n.filter(a=>!r.includes(a));return o.length===0?s:(i=!0,`${JSON.stringify({...n,uiCorsOrigins:[...r,...o]},null,2)}
115
- `)}),i}async function Yi(t){let e=re.join(t.configDir,".env"),i=Xi(e)?oe.parse(qi(e,"utf-8")):{},s=vn(t.port,i.CORTEX_UI_PORT),n={...i},{clientToken:r,generated:o}=$e({envPath:e,env:n}),a=o.length>0;return Se(i)||(await xt(e,"CORTEX_UI_HTTP","1"),a=!0),(i.CORTEX_UI_PORT||"").trim()!==String(s)&&(await xt(e,"CORTEX_UI_PORT",String(s)),a=!0),await wn(t.configDir)&&(a=!0),{url:`http://127.0.0.1:${s}`,token:r,port:s,changed:a}}function vn(t,e){let i=t??(e?.trim()?Number(e):yn);if(!Number.isInteger(i)||i<1||i>65535)throw new Error("Invalid local UI port; choose a port between 1 and 65535 and retry.");return i}function ae(t){if(t!==void 0){if(t==="127.0.0.1")return"127.0.0.1";throw new Error("--answers clientListenHost must be the literal 127.0.0.1")}}function Zi(t){if(t===void 0)return;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("--answers localClient must be an object with enabled: true or false");let{enabled:e}=t;if(typeof e!="boolean")throw new Error("--answers localClient.enabled must be true or false");return{enabled:e}}async function Qi(t,e,i,s){if(!e.localClient?.enabled)return i();try{await Xe(t,e.machineName),i(),await qe(t,e.machineName),s({step:"local-client",state:"ok",device:e.machineName})}catch(n){throw s({step:"local-client",state:"error",reason:n.message}),n}}var us=pe("init");function Sn(t){let e=t?p.resolve(t):process.env.CORTEX_HOME?p.resolve(process.env.CORTEX_HOME):p.join(H.homedir(),".cortex"),i=p.join(e,"context");return{DATA_DIR:e,CONFIG_DIR:p.join(e,"config"),STORE_DIR:p.join(e,"data"),CONTEXT_DIR:i,PROJECTS_DIR:process.env.CORTEX_PROJECTS_DIR?p.resolve(process.env.CORTEX_PROJECTS_DIR):p.join(i,"projects"),WORKSPACE_DIR:p.join(e,"tmp")}}function es(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function is(t){if(!t||typeof t!="object")return;let{mode:e,model:i}=t;if(!(typeof e!="string"||typeof i!="string")&&!(!e.trim()||!i.trim()))return{mode:e.trim(),model:i.trim()}}function _n(t){if(!t||typeof t!="object")return;let{enabled:e,port:i}=t;return e!==!0?void 0:{enabled:!0,port:typeof i=="number"&&Number.isInteger(i)&&i>0&&i<65536?i:void 0}}function Cn(t){let e;try{e=JSON.parse(t)}catch(a){throw new Error(`--answers file is not valid JSON: ${a.message}`)}if(!e||typeof e!="object"||Array.isArray(e))throw new Error("--answers file must contain a JSON object");let i=e,s=es(i.backends).filter(a=>a==="claude"||a==="pi"),n=[];for(let a of es(i.platforms)){let u=a.trim().toLowerCase();(u==="slack"||u==="feishu")&&!n.includes(u)&&n.push(u)}let r=i.gatewayUsage??{},o=r.enabled===!0?{enabled:!0,name:typeof r.name=="string"?r.name:"",org:typeof r.org=="string"?r.org:"",email:typeof r.email=="string"?r.email:""}:r.enabled===!1?{enabled:!1}:void 0;return{lang:typeof i.lang=="string"?Nt(i.lang):wt(),backends:s.length>0?s:i.backends===void 0?["pi"]:["claude"],machineName:typeof i.machineName=="string"&&i.machineName.trim()?i.machineName.trim():H.hostname(),gpuCount:typeof i.gpuCount=="number"?i.gpuCount:le(),platforms:n,slackConfig:i.slackConfig,feishuConfig:i.feishuConfig,gatewayUsage:o,telemetry:Gi(i.telemetry),installService:i.installService===!0,defaultChoice:is(i.defaultChoice),favorites:Array.isArray(i.favorites)?i.favorites.map(is).filter(a=>!!a):void 0,localUi:_n(i.localUi),localClient:Zi(i.localClient),clientListenHost:ae(i.clientListenHost)}}function At(t){if(!t)return;let e=t.trim();if(!e)return;let i=e.indexOf(":");if(!(i<=0||i===e.length-1))return{mode:e.substring(0,i).trim(),model:e.substring(i+1).trim()}}function Tn(t){if(!t)return;let e=t.trim();if(!e)return;let i=[];for(let s of e.split(",")){let n=At(s.trim());n&&i.push(n)}return i.length>0?i:void 0}function kn(t){let e=["# Cortex Configuration","# Generated by `cortex init`","",`CORTEX_MACHINE=${t.machineName}`,"","# Auth tokens \u2014 WS client (cortex-client \u2194 server) + webhook bearer. Required (fail-closed).","# Remote cortex-client machines must share CORTEX_CLIENT_TOKEN. Rotate by editing here + restart.",`CORTEX_CLIENT_TOKEN=${ts(32).toString("hex")}`,`CORTEX_WEBHOOK_TOKEN=${ts(32).toString("hex")}`],i=ae(t.clientListenHost);return i!==void 0&&e.push(`CORTEX_CLIENT_HOST=${i}`),t.platforms.length>0&&(e.push(`CORTEX_PLATFORM=${t.platforms.join(",")}`),e.push(""),t.slackConfig&&(e.push("# Slack configuration"),e.push(`SLACK_BOT_TOKEN=${t.slackConfig.botToken}`),e.push(`SLACK_SIGNING_SECRET=${t.slackConfig.signingSecret}`),e.push(`SLACK_APP_TOKEN=${t.slackConfig.appToken}`),e.push("")),t.feishuConfig&&(e.push("# Feishu configuration"),e.push(`FEISHU_APP_ID=${t.feishuConfig.appId}`),e.push(`FEISHU_APP_SECRET=${t.feishuConfig.appSecret}`),t.feishuConfig.domain&&e.push(`FEISHU_DOMAIN=${t.feishuConfig.domain}`),e.push(`FEISHU_AUTH_MODE=${t.feishuConfig.authMode??"bot"}`))),e.push(""),e.join(`
116
- `)}function En(){return JSON.stringify({defaultAgent:"main"})}function zo(t,e){let i=c("init.config.found"),s=c("init.config.missing");return[c("init.config.title"),` INSTALL_ROOT: ${t.INSTALL_ROOT}`,` DATA_DIR: ${t.DATA_DIR}`,` CONFIG_DIR: ${t.CONFIG_DIR}`,` STORE_DIR: ${t.STORE_DIR}`,` CONTEXT_DIR: ${t.CONTEXT_DIR}`,` PROJECTS_DIR: ${t.PROJECTS_DIR}`,` WORKSPACE_DIR: ${t.WORKSPACE_DIR}`,"",c("init.config.statusTitle"),` DATA_DIR: ${e.dataDirExists?c("init.config.initialized"):c("init.config.notInitialized")}`,` .env: ${e.dotEnvExists?i:s}`,` mcp-config.json: ${e.mcpConfigExists?i:s}`,` agent-state: ${e.modeJsonExists?i:s}`].join(`
117
- `)}var ue={claude:{bin:"claude",npmPackage:"@anthropic-ai/claude-code",labelKey:"init.backend.label.claude",loginHintKey:"init.backend.loginHint.claude"},pi:{bin:null,npmPackage:null,labelKey:"init.backend.label.pi",loginHintKey:"init.backend.loginHint.pi"}},ss=JSON.stringify({display_information:{name:"Cortex",description:"Autonomous research agent",background_color:"#2c2d30"},features:{bot_user:{display_name:"Cortex",always_online:!0}},oauth_config:{scopes:{bot:["chat:write","im:history","im:write","reactions:read","reactions:write","users:read","commands","app_mentions:read","channels:history","channels:read","groups:history","files:read","files:write","emoji:read","pins:read","pins:write"]}},settings:{event_subscriptions:{bot_events:["message.im","message.channels","message.groups","app_mention"]},interactivity:{is_enabled:!1},org_deploy_enabled:!1,socket_mode_enabled:!0,token_rotation_enabled:!1}},null,2);function xn(t){if(process.stdout.isTTY){let i=Buffer.from(t,"utf-8").toString("base64");return process.stdout.write(`\x1B]52;c;${i}\x07`),!0}let e=process.platform==="darwin"?[["pbcopy",[]]]:process.platform==="win32"?[["clip",[]]]:[["xclip",["-selection","clipboard"]],["wl-copy",[]],["xsel",["--clipboard","--input"]]];for(let[i,s]of e)try{let n=[i,...s].join(" ");return ot(n,{input:t,stdio:"pipe",timeout:3e3}),!0}catch{continue}return!1}async function Rn(t){if(process.stdin.isTTY)return process.stdout.write(c("init.clipboard.prompt")),new Promise(e=>{let i=process.stdin.isRaw??!1;try{process.stdin.setRawMode(!0),process.stdin.resume()}catch{process.stdout.write("\r\x1B[K"),e();return}let s=n=>{let r=n.toString();process.stdout.write("\b \b");try{process.stdin.setRawMode(i),process.stdin.pause()}catch{}process.stdin.removeListener("data",s),process.stdout.write("\r\x1B[K"),r.toLowerCase()==="c"&&(xn(t)?y.success(c("init.clipboard.copied")):(y.warn(c("init.clipboard.failed")),y.info(c("init.clipboard.manual")))),e()};process.stdin.on("data",s)})}function An(t){if(!U(t))return null;try{let e=ce(t,"utf-8"),i={};for(let s of e.split(`
118
- `)){let n=s.trim();if(!n||n.startsWith("#"))continue;let r=n.indexOf("=");if(r===-1)continue;let o=n.substring(0,r).trim(),a=n.substring(r+1).trim();o==="SLACK_SIGNING_SECRET"?i.signingSecret=a:o==="SLACK_APP_TOKEN"?i.appToken=a:o==="SLACK_BOT_TOKEN"&&(i.botToken=a)}return!i.signingSecret&&!i.appToken&&!i.botToken?null:i}catch{return null}}function On(t){let{bin:e}=ue[t];if(!e)return!0;let i=process.platform==="win32"?"where":"which";try{return ot(`${i} ${e}`,{stdio:"pipe"}),!0}catch{return!1}}function Dn(t){let{npmPackage:e}=ue[t];return e?`npm install -g ${e}`:null}function le(){try{let t=ot("nvidia-smi --query-gpu=count --format=csv,noheader",{stdio:"pipe",encoding:"utf-8",timeout:5e3}),e=parseInt(t.trim(),10);return Number.isFinite(e)?e:0}catch{return 0}}async function Nn(t){for(let e of t){let i=ue[e],s=c(i.labelKey),n=Dn(e);if(!n)y.success(c("init.backend.bundled",{label:s}));else if(On(e))y.success(c("init.backend.alreadyInstalled",{label:s}));else{let r=xi();r.start(c("init.backend.installing",{label:s}));try{ot(n,{stdio:"pipe",timeout:12e4}),r.stop(c("init.backend.installed",{label:s}))}catch{r.stop(c("init.backend.installFailed",{label:s})),y.error(c("init.backend.installFailedHint",{command:n}))}}}}function ns(t,e,i,s="system"){let n=s==="user";return["[Unit]","Description=Cortex Agent Server","After=network.target","","[Service]","Type=simple",...n?[]:[`User=${t}`],`ExecStart=${JSON.stringify(e.node)} ${JSON.stringify(e.daemon)}`,`Environment=CORTEX_HOME=${i}`,"Restart=on-failure","RestartSec=5","","[Install]",n?"WantedBy=default.target":"WantedBy=multi-user.target",""].join(`
119
- `)}function Fn(t,e){return['<?xml version="1.0" encoding="UTF-8"?>','<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">','<plist version="1.0">',"<dict>"," <key>Label</key>"," <string>cc.cortex.agent-server</string>"," <key>ProgramArguments</key>"," <array>",` <string>${rs(t.node)}</string>`,` <string>${rs(t.daemon)}</string>`," </array>"," <key>EnvironmentVariables</key>"," <dict>"," <key>CORTEX_HOME</key>",` <string>${e}</string>`," </dict>"," <key>RunAtLoad</key>"," <true/>"," <key>KeepAlive</key>"," <true/>"," <key>StandardOutPath</key>",` <string>${e}/logs/cortex-stdout.log</string>`," <key>StandardErrorPath</key>",` <string>${e}/logs/cortex-stderr.log</string>`,"</dict>","</plist>",""].join(`
120
- `)}function rs(t){return t.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function Pn(){return{node:process.execPath,daemon:p.join(ut,"dist","entry","daemon.js")}}function jn(){if(process.platform==="win32")return!1;try{return ot("sudo -n true",{stdio:"pipe"}),!0}catch{return!1}}function Ln(t){let e=H.userInfo().username,i=Pn(),s=process.platform;if(s==="darwin"){let n="cc.cortex.agent-server.plist",r=Fn(i,t),o=p.join(H.homedir(),"Library","LaunchAgents",n);B(o,r),y.success(c("init.service.launchdWritten",{path:o})),y.info(c("init.service.launchdStartHint",{path:o}))}else if(s==="linux"){let n=ns(e,i,t,"system"),r="cortex.service",o=`/etc/systemd/system/${r}`,a=p.join(H.homedir(),".config","systemd","user");try{ft(a,{recursive:!0});let u=p.join(a,r);B(u,ns(e,i,t,"user")),y.success(c("init.service.systemdUserWritten",{path:u})),y.info(c("init.service.systemdUserEnableHint"));return}catch{}if(jn())try{let u=p.join(H.tmpdir(),r);B(u,n),ot(`sudo cp ${u} ${o} && sudo systemctl daemon-reload`,{stdio:"pipe"}),y.success(c("init.service.systemdInstalled",{path:o})),y.info(c("init.service.systemdEnableHint"))}catch(u){y.warn(c("init.service.systemInstallFailed",{message:u.message}))}else{let u=p.join(t,"config",r);B(u,n),y.warn(c("init.service.noSudo")),y.info(c("init.service.manualInstallHint",{localPath:u,systemPath:o}))}}else y.warn(c("init.service.unsupported",{platform:s}))}function E(t){nt(t)&&(Ti(c("init.cancel")),process.exit(0))}async function Mn(t){mt(ss,c("init.slack.manifestTitle")),mt(c("init.slack.guide"),c("init.slack.guideTitle")),await Rn(ss);let e=t&&(t.signingSecret||t.appToken||t.botToken),i,s,n;if(e){y.info(c("init.slack.prefillFound"));let r=await Q({message:c("init.slack.skipPrompt"),placeholder:c("init.slack.skipPlaceholder"),defaultValue:""});E(r),r.trim()===""&&(i=t.signingSecret,s=t.appToken,n=t.botToken)}return i||(i=await st({message:c("init.slack.signingSecretPrompt"),validate(r){if(!r)return c("init.slack.signingSecretRequired")}}),E(i),s=await st({message:c("init.slack.appTokenPrompt"),validate(r){if(!r)return c("init.slack.appTokenRequired");if(!r.startsWith("xapp-"))return c("init.slack.appTokenPrefix")}}),E(s),n=await st({message:c("init.slack.botTokenPrompt"),validate(r){if(!r)return c("init.slack.botTokenRequired");if(!r.startsWith("xoxb-"))return c("init.slack.botTokenPrefix")}}),E(n)),{signingSecret:i,appToken:s,botToken:n}}async function Un(){mt(c("init.feishu.guide"),c("init.feishu.guideTitle"));let t=await Q({message:c("init.feishu.appIdPrompt"),validate(o){if(!o)return c("init.feishu.appIdRequired")}});E(t);let e=await st({message:c("init.feishu.appSecretPrompt"),validate(o){if(!o)return c("init.feishu.appSecretRequired")}});E(e);let i=await Q({message:c("init.feishu.domainPrompt"),placeholder:c("init.feishu.domainPlaceholder")});E(i);let s=i.trim().toLowerCase(),n=s==="feishu"||s==="lark"?s:void 0,r=await rt({message:c("init.feishu.authModePrompt"),options:[{value:"bot",label:c("init.feishu.authModeBotLabel"),hint:c("init.feishu.authModeBotHint")},{value:"user",label:c("init.feishu.authModeUserLabel"),hint:c("init.feishu.authModeUserHint")}],initialValue:"user"});return E(r),{appId:t,appSecret:e,domain:n,authMode:r}}async function Gn(t,e,i={}){let s=i.cmdFeishuImpl??Ji,n=i.stdout??(u=>process.stdout.write(u)),r={...process.env,FEISHU_APP_ID:t.appId,FEISHU_APP_SECRET:t.appSecret};t.domain&&(r.FEISHU_DOMAIN=t.domain);let o=p.join(e,"feishu-user-token.json"),a=await s(["login"],{env:r,tokenFile:o,loadDotenv:!1});return a.stdout&&n(a.stdout),a.exitCode!==0&&a.stderr&&n(a.stderr),a}async function Vn(t){let e=wt(),i=await rt({message:"Select language / \u9009\u62E9\u8BED\u8A00",options:[{value:"en",label:"English"},{value:"zh",label:"\u4E2D\u6587 (Simplified Chinese)"}],initialValue:e});E(i);let s=i;me(s),ki(c("init.intro"));let n=["pi"];y.info(c("init.auth.piFirst"));let r=await Yt({message:c("init.platform.prompt"),options:[{value:"slack",label:c("init.platform.slackLabel"),hint:c("init.platform.slackHint")},{value:"feishu",label:c("init.platform.feishuLabel")}],required:!1});E(r);let o=r,a,u;if(o.includes("slack")){let b=p.join(t.CONFIG_DIR,".env"),T=An(b);a=await Mn(T??void 0)}o.includes("feishu")&&(u=await Un(),u.authMode==="user"&&(y.info(c("init.feishu.loginStarting")),(await Gn(u,t.CONFIG_DIR)).exitCode===0?y.success(c("init.feishu.loginComplete")):y.warn(c("init.feishu.loginIncomplete"))));let h=H.hostname(),g=await Q({message:c("init.machine.prompt"),placeholder:h,defaultValue:h,validate(b){if(!b)return c("init.machine.required")}});E(g);let d=le();d>0?y.success(c("init.machine.gpuDetected",{count:d})):y.info(c("init.machine.gpuNone")),mt(c("init.gateway.note"),c("init.gateway.noteTitle"));let f=await it({message:c("init.gateway.enablePrompt"),initialValue:!0});E(f);let $={enabled:!1};if(f){let b=await Q({message:c("init.gateway.namePrompt"),placeholder:c("init.gateway.namePlaceholder")});E(b);let T=await Q({message:c("init.gateway.orgPrompt"),placeholder:c("init.gateway.orgPlaceholder")});E(T);let A=await Q({message:c("init.gateway.emailPrompt"),placeholder:c("init.gateway.emailPlaceholder")});E(A),$={enabled:!0,name:b,org:T,email:A}}let m=await Hn(),v=await it({message:c("init.serviceRegister.prompt"),initialValue:!0});return E(v),{lang:s,backends:n,machineName:g,gpuCount:d,platforms:o,slackConfig:a,feishuConfig:u,gatewayUsage:$,telemetry:m,installService:v}}async function Hn(){let t=await it({message:c("init.telemetry.prompt"),initialValue:!0});return E(t),{enabled:t}}async function Wn(){let t=[],e=bn({input:Rt});for await(let i of e)t.push(i);return us.info("Cortex Initialization (non-interactive)"),Jn(t)}function Bn(t=""){let e=t.split(",").map(i=>i.trim().toLowerCase());return[...new Set(e.filter(i=>i==="slack"||i==="feishu"))]}function Kn(t,e){let i,s,n=7;if(e.includes("slack")&&t.length>=n+3&&(i={signingSecret:t[n]||"",appToken:t[n+1]||"",botToken:t[n+2]||""},n+=3),e.includes("feishu")&&t.length>=n+3){let r=(t[n+2]||"").trim().toLowerCase();s={appId:t[n]||"",appSecret:t[n+1]||"",domain:r==="feishu"||r==="lark"?r:void 0},n+=3}return{slackConfig:i,feishuConfig:s,cursor:n}}function Jn(t){let[e,i,s,n,r,o,a]=t,u=(e||"pi").split(",").map(m=>m.trim()).filter(m=>m==="claude"||m==="pi"),h=Bn(i),{slackConfig:g,feishuConfig:d,cursor:f}=Kn(t,h),$=s?.trim().toLowerCase();return{lang:process.env.CORTEX_LANG?Nt(process.env.CORTEX_LANG):wt(),backends:u.length>0?u:["claude"],machineName:H.hostname(),gpuCount:le(),platforms:h,slackConfig:g,feishuConfig:d,gatewayUsage:$==="y"?{enabled:!0,name:n||"",org:r||"",email:o||""}:$==="n"?{enabled:!1}:void 0,installService:a?.toLowerCase()==="y",defaultChoice:At(t[f]),favorites:Tn(t[f+1])}}function Xn(t){let e=[t.DATA_DIR,t.CONFIG_DIR,t.STORE_DIR,p.join(t.DATA_DIR,"logs","sessions"),t.WORKSPACE_DIR,t.PROJECTS_DIR,p.join(t.CONTEXT_DIR,"user"),p.join(t.CONTEXT_DIR,"decisions"),p.join(t.CONTEXT_DIR,"scans"),p.join(t.CONTEXT_DIR,"ideas"),p.join(t.CONTEXT_DIR,"retrospectives"),p.join(t.DATA_DIR,".claude","hooks"),p.join(t.DATA_DIR,".claude","rules"),p.join(t.DATA_DIR,"plugins"),p.join(t.DATA_DIR,"prompts","directives"),p.join(t.DATA_DIR,"prompts","systemPrompts"),p.join(t.DATA_DIR,"prompts","promptTemplates"),p.join(t.DATA_DIR,"hooks"),p.join(t.DATA_DIR,"plan"),p.join(t.DATA_DIR,"logs","sessions-pi")];for(let i of e)ft(i,{recursive:!0})}function z(t,e,i){if(!U(t)||U(e)&&!i)return!1;let s=p.dirname(e);return U(s)||ft(s,{recursive:!0}),as(t,e),!0}function ls(t,e,i){if(U(t)){ft(e,{recursive:!0});for(let s of In(t,{withFileTypes:!0})){let n=p.join(t,s.name),r=p.join(e,s.name);if(s.isDirectory())ls(n,r,i);else if(s.isFile()){if(U(r)&&!i)continue;as(n,r)}}}}function qn(t,e){z(p.join(M,"AGENTS.md"),p.join(t.DATA_DIR,"AGENTS.md"),!1),z(p.join(M,"gitignore"),p.join(t.DATA_DIR,".gitignore"),!1),z(p.join(M,".claude","settings.json"),p.join(t.DATA_DIR,".claude","settings.json"),!1),z(p.join(M,"context","AGENTS.md"),p.join(t.CONTEXT_DIR,"AGENTS.md"),!1),z(p.join(M,"context","projects","AGENTS.md"),p.join(t.PROJECTS_DIR,"AGENTS.md"),!1),z(p.join(M,"context","scans","AGENTS.md"),p.join(t.CONTEXT_DIR,"scans","AGENTS.md"),!1),z(p.join(M,"context","ideas","AGENTS.md"),p.join(t.CONTEXT_DIR,"ideas","AGENTS.md"),!1),z(p.join(M,"context","user","AGENTS.md"),p.join(t.CONTEXT_DIR,"user","AGENTS.md"),!1),z(p.join(M,"config","budget.json"),p.join(t.CONFIG_DIR,"budget.json"),e),Ue(p.join(M,"config",Pt),p.join(t.CONFIG_DIR,Pt)),ls(p.join(M,"context","decisions"),p.join(t.CONTEXT_DIR,"decisions"),e)}function zn(t){let e=[["mcp-config.json",_e(ut)],["mcp-config-core.json",Ce(ut)],["mcp-config-empty.json",Te()],["mcp-config-interaction.json",ke(ut)]];for(let[i,s]of e)B(p.join(t,i),JSON.stringify(s,null,2))}function Yn(t,e,i){zn(t.CONFIG_DIR);let s=p.join(t.STORE_DIR,"agent-state.json");(!U(s)&&!U(p.join(t.STORE_DIR,"mode.json"))||i)&&B(s,En());let n=p.join(t.CONFIG_DIR,"preferences.json");(!U(n)||i)&&B(n,JSON.stringify({lang:e.lang},null,2)+`
121
- `);let r=p.join(t.CONFIG_DIR,"machines.json");if(!U(r)||i){let o={cortexPath:t.DATA_DIR,gpuCount:e.gpuCount},a={[e.machineName]:o};B(r,JSON.stringify(a,null,2)+`
122
- `)}}function Zn(t,e){let i=p.join(t.STORE_DIR,"schedules.json");if(U(i)&&!e)return;let s=p.join(M,"data","schedules.json");if(!U(s))return;let n="",r=Date.now(),o=ce(s,"utf-8");o=o.replace(/__ADMIN_CHANNEL__/g,n);let a=JSON.parse(o);for(let u of a.tasks)u.createdAt===0&&(u.createdAt=r);ft(p.dirname(i),{recursive:!0}),B(i,JSON.stringify(a,null,2)+`
123
- `)}function Qn(t,e,i){let s=p.join(t.CONFIG_DIR,".env"),n=U(s);if(n&&!i)return;let r=kn(e);if(!n){B(s,r);return}let o=ce(s,"utf8"),a=(0,cs.parse)(o);for(let u of r.split(`
124
- `)){let h=u.match(/^([A-Z_]+)=(.*)$/);if(!h)continue;let[,g,d]=h;(g==="CORTEX_CLIENT_TOKEN"||g==="CORTEX_WEBHOOK_TOKEN")&&a[g]?.trim()||(o=ne(o,g,d))}B(s,o)}async function tr(t){if(!jt(t)?.default)return!0;let e=await it({message:c("init.gatewaySetup.overwritePrompt"),initialValue:!1});return E(e),e}async function er(t,e){if(!await tr(e))return{overwrite:!1};let i=Ge(t);if(!i.length)return{overwrite:!0};let s=u=>`${u.mode}:${u.model}`,n=i.map(u=>({value:s(u),label:`${u.mode} / ${u.model}`})),r=await rt({message:c("init.gatewaySetup.defaultPrompt"),options:n,initialValue:s(Ve(t)??i[0])});E(r);let o=await Yt({message:c("init.gatewaySetup.favoritesPrompt"),options:n,required:!1,initialValues:[r]});E(o);let a=new Set([r,...o]);return{defaultChoice:At(r),favorites:[...a].map(u=>At(u)),overwrite:!0}}function ir(t,e){let i=t.map(r=>` ${r.mode}/${r.endpoint}: ${r.models.slice(0,3).join(", ")}${r.models.length>3?", ...":""} (${r.keys.length>0?"with key":"passthrough"})`).join(`
125
- `);y.success(c("init.gatewaySetup.discovered",{count:t.length,summary:i}));let{path:s,result:n}=xe(t,e);if(y.success(c("init.gatewaySetup.gatewayWritten",{path:s})),n.droppedFromDiscovery.length>0){let r=n.droppedFromDiscovery.map(o=>`${o.mode}/${o.endpoint}`).join(", ");y.warn(c("init.gatewaySetup.preservedModes",{count:n.droppedFromDiscovery.length,list:r})),y.info(c("init.gatewaySetup.preservedModesHint"))}return n.endpoints}function sr(t,e){let i=jt(t);y.info(c("init.gatewaySetup.generatedModels",{names:i.favorites.map(r=>r.model).join(", "),default:i.default.model}));let s=Re(e,t);if(!s.length)return;let n=s.map(r=>` - ${r.model}: ${r.reason}`).join(`
126
- `);y.warn(c("init.gatewaySetup.modelIssues",{count:s.length,lines:n})),y.info(c("init.gatewaySetup.modelIssuesHint"))}async function os(t,e,i,s,n=!1){let r=await Ee(t);if(!r.some(h=>h.models.length>0))return y.warn(c("init.gatewaySetup.noBackends")),y.info(c("init.gatewaySetup.rerunHint")),!1;let o=ir(r,i),a=n?await er(r,e.CONFIG_DIR):{...s,overwrite:!!s?.defaultChoice},u=He(r,{...a,outputDir:e.CONFIG_DIR});return y.success(c("init.gatewaySetup.modelsWritten",{path:u})),sr(e.CONFIG_DIR,o),!0}function nr(){let t=process.stdout,e=t.write.bind(t);return t.write=((i,s,n)=>process.stderr.write(i,s,n)),{emit(i){e(`${JSON.stringify(i)}
127
- `)},restore(){t.write=e}}}async function Yo(t={}){let e=Sn(t.homeDir),i=t.force??!1,s=t.jsonEvents?nr():null;try{await cr(e,i,t,s)}finally{s?.restore()}}function rr(t,e,i){e.gatewayUsage&&Je(e.gatewayUsage,i.gatewayConfigDir),e.telemetry&&Vi(e.telemetry,{configDir:t.CONFIG_DIR,storeDir:t.STORE_DIR})}async function or(t,e,i,s,n){let r=a=>n?.emit(a),o=await Li(s,a=>{r(a),!n&&!s&&process.stdout.write(`${JSON.stringify(a)}
128
- `)});if(s){let a=o.length>0&&await os(o,t,i.gatewayConfigDir,e,!0);r({step:"gateway",state:a?"ok":"skip"});return}try{let a=await os(e.backends,t,i.gatewayConfigDir,e);r({step:"gateway",state:a?"ok":"skip",reason:a?void 0:"no-backend-login"})}catch(a){us.warn(`Gateway setup failed (non-interactive): ${a.message}`),r({step:"gateway",state:"skip",reason:a.message})}}function ar(t,e,i){let s=e.localClient?.enabled?!1:i;Qn(t,e,s),qn(t,s),Yn(t,e,s),Zn(t,s)}async function cr(t,e,i,s){let n=h=>s?.emit(h),r=i.answers??(Rt.isTTY&&!i.jsonEvents?await Vn(t):i.jsonEvents&&Rt.isTTY?Cn("{}"):await Wn()),o=!i.answers&&!i.jsonEvents&&Rt.isTTY;n({step:"answers",state:"ok",machine:r.machineName,backends:r.backends}),await Nn(r.backends),n({step:"backends",state:"ok"});let a=Qt();Xn(t),a&&Di(t.DATA_DIR),n({step:"home",state:"ok",home:t.DATA_DIR}),await Qi(t,r,()=>ar(t,r,e),n),n({step:"config",state:"ok"}),rr(t,r,i);let u=null;r.localUi?.enabled&&(u=await Yi({configDir:t.CONFIG_DIR,port:r.localUi.port}),y.success(c("init.localUi.enabled",{url:u.url})),n({step:"local-ui",state:"ok",url:u.url,port:u.port})),r.installService&&(Ln(t.DATA_DIR),n({step:"service",state:"ok"})),await or(t,r,i,!!o,s),Ei(c("init.outro",{dataDir:t.DATA_DIR})),r.telemetry?.enabled!==!1&&p.resolve(t.DATA_DIR)===p.resolve(he)&&Ie("server_init_completed"),n({step:"result",state:"ok",home:t.DATA_DIR,version:ye,clientToken:zi(p.join(t.CONFIG_DIR,".env"),ge)??null,uiUrl:u?.url??null})}export{Ai as a,Oi as b,Qt as c,S as d,Pi as e,Ji as f,Yi as g,Sn as h,Cn as i,kn as j,En as k,zo as l,ss as m,On as n,Dn as o,ns as p,Fn as q,Gn as r,Jn as s,z as t,Yn as u,Qn as v,Yo as w,ar as x};
@@ -1,13 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{B as Ct,C as bt,E as Rt,G as St,H as zt,J as xt,K as Ue,M as Et,N as Tt,Q as Ut,R as Ot,S as kt,T as At,U as Mt,Y as Pt,_ as z,a as dt,aa as It,ba as Lt,c as B,ca as qt,da as $t,e as pt,ea as Ht,k as le,l as ft,m as _t,n as mt,o as O,p as te,q as ue,s as wt,u as gt,v as He,x as yt,z as vt}from"./chunk-FOQ7VLIL.js";import{C as lt,H as ut,I as ht,a as it,n as c,o as at,p as $e,q,s as ct,u as _,v as D,w as Te}from"./chunk-DPQPXBTP.js";var Oe=class{constructor(e){this._client=e}async*callToolStream(e,t=Ue,s){let o=this._client,i={...s,task:s?.task??(o.isToolTask(e.name)?{}:void 0)},a=o.requestStream({method:"tools/call",params:e},t,i),n=o.getToolOutputValidator(e.name);for await(let u of a){if(u.type==="result"&&n){let p=u.result;if(!p.structuredContent&&!p.isError){yield{type:"error",error:new z(O.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(p.structuredContent)try{let d=n(p.structuredContent);if(!d.valid){yield{type:"error",error:new z(O.InvalidParams,`Structured content does not match the tool's output schema: ${d.errorMessage}`)};return}}catch(d){if(d instanceof z){yield{type:"error",error:d};return}yield{type:"error",error:new z(O.InvalidParams,`Failed to validate structured content: ${d instanceof Error?d.message:String(d)}`)};return}}yield u}}async getTask(e,t){return this._client.getTask({taskId:e},t)}async getTaskResult(e,t,s){return this._client.getTaskResult({taskId:e},t,s)}async listTasks(e,t){return this._client.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._client.cancelTask({taskId:e},t)}requestStream(e,t,s){return this._client.requestStream(e,t,s)}};function ke(r,e){if(!(!r||e===null||typeof e!="object")){if(r.type==="object"&&r.properties&&typeof r.properties=="object"){let t=e,s=r.properties;for(let o of Object.keys(s)){let i=s[o];t[o]===void 0&&Object.prototype.hasOwnProperty.call(i,"default")&&(t[o]=i.default),t[o]!==void 0&&ke(i,t[o])}}if(Array.isArray(r.anyOf))for(let t of r.anyOf)typeof t!="boolean"&&ke(t,e);if(Array.isArray(r.oneOf))for(let t of r.oneOf)typeof t!="boolean"&&ke(t,e)}}function dr(r){if(!r)return{supportsFormMode:!1,supportsUrlMode:!1};let e=r.form!==void 0,t=r.url!==void 0;return{supportsFormMode:e||!e&&!t,supportsUrlMode:t}}var Wt=class extends It{constructor(e,t){super(t),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=t?.capabilities??{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new qt,t?.listChanged&&(this._pendingListChangedConfig=t.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Et,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",zt,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",bt,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new Oe(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Lt(this._capabilities,e)}setRequestHandler(e,t){let o=pt(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if(dt(o)){let n=o;i=n._zod?.def?.value??n.value}else{let n=o;i=n._def?.value??n.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");let a=i;if(a==="elicitation/create"){let n=async(u,p)=>{let d=B(At,u);if(!d.success){let M=d.error instanceof Error?d.error.message:String(d.error);throw new z(O.InvalidParams,`Invalid elicitation request: ${M}`)}let{params:f}=d.data;f.mode=f.mode??"form";let{supportsFormMode:m,supportsUrlMode:g}=dr(this._capabilities.elicitation);if(f.mode==="form"&&!m)throw new z(O.InvalidParams,"Client does not support form-mode elicitation requests");if(f.mode==="url"&&!g)throw new z(O.InvalidParams,"Client does not support URL-mode elicitation requests");let R=await Promise.resolve(t(u,p));if(f.task){let M=B(He,R);if(!M.success){let E=M.error instanceof Error?M.error.message:String(M.error);throw new z(O.InvalidParams,`Invalid task creation result: ${E}`)}return M.data}let v=B(Mt,R);if(!v.success){let M=v.error instanceof Error?v.error.message:String(v.error);throw new z(O.InvalidParams,`Invalid elicitation result: ${M}`)}let C=v.data,I=f.mode==="form"?f.requestedSchema:void 0;if(f.mode==="form"&&C.action==="accept"&&C.content&&I&&this._capabilities.elicitation?.form?.applyDefaults)try{ke(I,C.content)}catch{}return C};return super.setRequestHandler(e,n)}if(a==="sampling/createMessage"){let n=async(u,p)=>{let d=B(Ut,u);if(!d.success){let C=d.error instanceof Error?d.error.message:String(d.error);throw new z(O.InvalidParams,`Invalid sampling request: ${C}`)}let{params:f}=d.data,m=await Promise.resolve(t(u,p));if(f.task){let C=B(He,m);if(!C.success){let I=C.error instanceof Error?C.error.message:String(C.error);throw new z(O.InvalidParams,`Invalid task creation result: ${I}`)}return C.data}let R=f.tools||f.toolChoice?kt:Ot,v=B(R,m);if(!v.success){let C=v.error instanceof Error?v.error.message:String(v.error);throw new z(O.InvalidParams,`Invalid sampling result: ${C}`)}return v.data};return super.setRequestHandler(e,n)}return super.setRequestHandler(e,t)}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),e.sessionId===void 0)try{let s=await this.request({method:"initialize",params:{protocolVersion:le,capabilities:this._capabilities,clientInfo:this._clientInfo}},wt,t);if(s===void 0)throw new Error(`Server sent invalid initialize result: ${s}`);if(!ft.includes(s.protocolVersion))throw new Error(`Server's protocol version is not supported: ${s.protocolVersion}`);this._serverCapabilities=s.capabilities,this._serverVersion=s.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(s.protocolVersion),this._instructions=s.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(s){throw this.close(),s}}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){$t(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&Ht(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},ue,e)}async complete(e,t){return this.request({method:"completion/complete",params:e},Pt,t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},ue,t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},St,t)}async listPrompts(e,t){return this.request({method:"prompts/list",params:e},Rt,t)}async listResources(e,t){return this.request({method:"resources/list",params:e},yt,t)}async listResourceTemplates(e,t){return this.request({method:"resources/templates/list",params:e},vt,t)}async readResource(e,t){return this.request({method:"resources/read",params:e},Ct,t)}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},ue,t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},ue,t)}async callTool(e,t=Ue,s){if(this.isToolTaskRequired(e.name))throw new z(O.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let o=await this.request({method:"tools/call",params:e},t,s),i=this.getToolOutputValidator(e.name);if(i){if(!o.structuredContent&&!o.isError)throw new z(O.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(o.structuredContent)try{let a=i(o.structuredContent);if(!a.valid)throw new z(O.InvalidParams,`Structured content does not match the tool's output schema: ${a.errorMessage}`)}catch(a){throw a instanceof z?a:new z(O.InvalidParams,`Failed to validate structured content: ${a instanceof Error?a.message:String(a)}`)}}return o}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 t of e){if(t.outputSchema){let o=this._jsonSchemaValidator.getValidator(t.outputSchema);this._cachedToolOutputValidators.set(t.name,o)}let s=t.execution?.taskSupport;(s==="required"||s==="optional")&&this._cachedKnownTaskTools.add(t.name),s==="required"&&this._cachedRequiredTaskTools.add(t.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){let s=await this.request({method:"tools/list",params:e},xt,t);return this.cacheToolMetadata(s.tools),s}_setupListChangedHandler(e,t,s,o){let i=Tt.safeParse(s);if(!i.success)throw new Error(`Invalid ${e} listChanged options: ${i.error.message}`);if(typeof s.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:a,debounceMs:n}=i.data,{onChanged:u}=s,p=async()=>{if(!a){u(null,null);return}try{let f=await o();u(null,f)}catch(f){let m=f instanceof Error?f:new Error(String(f));u(m,null)}},d=()=>{if(n){let f=this._listChangedDebounceTimers.get(e);f&&clearTimeout(f);let m=setTimeout(p,n);this._listChangedDebounceTimers.set(e,m)}else p()};this.setNotificationHandler(t,d)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};function re(r){return r?r instanceof Headers?Object.fromEntries(r.entries()):Array.isArray(r)?Object.fromEntries(r):{...r}:{}}function Ae(r=fetch,e){return e?async(t,s)=>{let o={...e,...s,headers:s?.headers?{...re(e.headers),...re(s.headers)}:e.headers};return r(t,o)}:r}var We;We=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(r=>r.webcrypto);async function pr(r){return(await We).getRandomValues(new Uint8Array(r))}async function fr(r){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",t=Math.pow(2,8)-Math.pow(2,8)%e.length,s="";for(;s.length<r;){let o=await pr(r-s.length);for(let i of o)i<t&&(s+=e[i%e.length])}return s}async function _r(r){return await fr(r)}async function mr(r){let e=await(await We).subtle.digest("SHA-256",new TextEncoder().encode(r));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Ne(r){if(r||(r=43),r<43||r>128)throw`Expected a length between 43 and 128. Received ${r}.`;let e=await _r(r),t=await mr(e);return{code_verifier:e,code_challenge:t}}var k=at().superRefine((r,e)=>{if(!URL.canParse(r))return e.addIssue({code:ut.custom,message:"URL must be parseable",fatal:!0}),it}).refine(r=>{let e=new URL(r);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),Dt=Te({resource:c().url(),authorization_servers:_(k).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()}),De=Te({issuer:c(),authorization_endpoint:k,token_endpoint:k,registration_endpoint:k.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:k.optional(),revocation_endpoint:k.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()}),wr=Te({issuer:c(),authorization_endpoint:k,token_endpoint:k,userinfo_endpoint:k.optional(),jwks_uri:k,registration_endpoint:k.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:k.optional(),op_tos_uri:k.optional(),client_id_metadata_document_supported:q().optional()}),jt=D({...wr.shape,...De.pick({code_challenge_methods_supported:!0}).shape}),Vt=D({access_token:c(),id_token:c().optional(),token_type:c(),expires_in:ht.number().optional(),scope:c().optional(),refresh_token:c().optional()}).strip(),Ft=D({error:c(),error_description:c().optional(),error_uri:c().optional()}),Nt=k.optional().or(lt("").transform(()=>{})),gr=D({redirect_uris:_(k),token_endpoint_auth_method:c().optional(),grant_types:_(c()).optional(),response_types:_(c()).optional(),client_name:c().optional(),client_uri:k.optional(),logo_uri:Nt,scope:c().optional(),contacts:_(c()).optional(),tos_uri:Nt,policy_uri:c().optional(),jwks_uri:k.optional(),jwks:ct().optional(),software_id:c().optional(),software_version:c().optional(),software_statement:c().optional()}).strip(),yr=D({client_id:c(),client_secret:c().optional(),client_id_issued_at:$e().optional(),client_secret_expires_at:$e().optional()}).strip(),Bt=gr.merge(yr),ss=D({error:c(),error_description:c().optional()}).strip(),os=D({token:c(),token_type_hint:c().optional()}).strip();function Zt(r){let e=typeof r=="string"?new URL(r):new URL(r.href);return e.hash="",e}function Gt({requestedResource:r,configuredResource:e}){let t=typeof r=="string"?new URL(r):new URL(r.href),s=typeof e=="string"?new URL(e):new URL(e.href);if(t.origin!==s.origin||t.pathname.length<s.pathname.length)return!1;let o=t.pathname.endsWith("/")?t.pathname:t.pathname+"/",i=s.pathname.endsWith("/")?s.pathname:s.pathname+"/";return o.startsWith(i)}var S=class extends Error{constructor(e,t){super(e),this.errorUri=t,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}},he=class extends S{};he.errorCode="invalid_request";var Z=class extends S{};Z.errorCode="invalid_client";var G=class extends S{};G.errorCode="invalid_grant";var J=class extends S{};J.errorCode="unauthorized_client";var de=class extends S{};de.errorCode="unsupported_grant_type";var pe=class extends S{};pe.errorCode="invalid_scope";var fe=class extends S{};fe.errorCode="access_denied";var $=class extends S{};$.errorCode="server_error";var _e=class extends S{};_e.errorCode="temporarily_unavailable";var me=class extends S{};me.errorCode="unsupported_response_type";var we=class extends S{};we.errorCode="unsupported_token_type";var ge=class extends S{};ge.errorCode="invalid_token";var ye=class extends S{};ye.errorCode="method_not_allowed";var ve=class extends S{};ve.errorCode="too_many_requests";var K=class extends S{};K.errorCode="invalid_client_metadata";var Ce=class extends S{};Ce.errorCode="insufficient_scope";var be=class extends S{};be.errorCode="invalid_target";var Jt={[he.errorCode]:he,[Z.errorCode]:Z,[G.errorCode]:G,[J.errorCode]:J,[de.errorCode]:de,[pe.errorCode]:pe,[fe.errorCode]:fe,[$.errorCode]:$,[_e.errorCode]:_e,[me.errorCode]:me,[we.errorCode]:we,[ge.errorCode]:ge,[ye.errorCode]:ye,[ve.errorCode]:ve,[K.errorCode]:K,[Ce.errorCode]:Ce,[be.errorCode]:be};var A=class extends Error{constructor(e){super(e??"Unauthorized")}};function vr(r){return["client_secret_basic","client_secret_post","none"].includes(r)}var je="code",Ve="S256";function Cr(r,e){let t=r.client_secret!==void 0;return"token_endpoint_auth_method"in r&&r.token_endpoint_auth_method&&vr(r.token_endpoint_auth_method)&&(e.length===0||e.includes(r.token_endpoint_auth_method))?r.token_endpoint_auth_method:e.length===0?t?"client_secret_basic":"none":t&&e.includes("client_secret_basic")?"client_secret_basic":t&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":t?"client_secret_post":"none"}function br(r,e,t,s){let{client_id:o,client_secret:i}=e;switch(r){case"client_secret_basic":Rr(o,i,t);return;case"client_secret_post":Sr(o,i,s);return;case"none":zr(o,s);return;default:throw new Error(`Unsupported client authentication method: ${r}`)}}function Rr(r,e,t){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");let s=btoa(`${r}:${e}`);t.set("Authorization",`Basic ${s}`)}function Sr(r,e,t){t.set("client_id",r),e&&t.set("client_secret",e)}function zr(r,e){e.set("client_id",r)}async function Yt(r){let e=r instanceof Response?r.status:void 0,t=r instanceof Response?await r.text():r;try{let s=Ft.parse(JSON.parse(t)),{error:o,error_description:i,error_uri:a}=s,n=Jt[o]||$;return new n(i||"",a)}catch(s){let o=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${s}. Raw body: ${t}`;return new $(o)}}async function H(r,e){try{return await Fe(r,e)}catch(t){if(t instanceof Z||t instanceof J)return await r.invalidateCredentials?.("all"),await Fe(r,e);if(t instanceof G)return await r.invalidateCredentials?.("tokens"),await Fe(r,e);throw t}}async function Fe(r,{serverUrl:e,authorizationCode:t,scope:s,resourceMetadataUrl:o,fetchFn:i}){let a=await r.discoveryState?.(),n,u,p,d=o;if(!d&&a?.resourceMetadataUrl&&(d=new URL(a.resourceMetadataUrl)),a?.authorizationServerUrl){if(u=a.authorizationServerUrl,n=a.resourceMetadata,p=a.authorizationServerMetadata??await Xt(u,{fetchFn:i}),!n)try{n=await Qt(e,{resourceMetadataUrl:d},i)}catch{}(p!==a.authorizationServerMetadata||n!==a.resourceMetadata)&&await r.saveDiscoveryState?.({authorizationServerUrl:String(u),resourceMetadataUrl:d?.toString(),resourceMetadata:n,authorizationServerMetadata:p})}else{let E=await Ar(e,{resourceMetadataUrl:d,fetchFn:i});u=E.authorizationServerUrl,p=E.authorizationServerMetadata,n=E.resourceMetadata,await r.saveDiscoveryState?.({authorizationServerUrl:String(u),resourceMetadataUrl:d?.toString(),resourceMetadata:n,authorizationServerMetadata:p})}let f=await Er(e,r,n),m=s||n?.scopes_supported?.join(" ")||r.clientMetadata.scope,g=await Promise.resolve(r.clientInformation());if(!g){if(t!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let E=p?.client_id_metadata_document_supported===!0,F=r.clientMetadataUrl;if(F&&!xr(F))throw new K(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${F}`);if(E&&F)g={client_id:F},await r.saveClientInformation?.(g);else{if(!r.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let l=await qr(u,{metadata:p,clientMetadata:r.clientMetadata,scope:m,fetchFn:i});await r.saveClientInformation(l),g=l}}let R=!r.redirectUrl;if(t!==void 0||R){let E=await Lr(r,u,{metadata:p,resource:f,authorizationCode:t,fetchFn:i});return await r.saveTokens(E),"AUTHORIZED"}let v=await r.tokens();if(v?.refresh_token)try{let E=await Ir(u,{metadata:p,clientInformation:g,refreshToken:v.refresh_token,resource:f,addClientAuthentication:r.addClientAuthentication,fetchFn:i});return await r.saveTokens(E),"AUTHORIZED"}catch(E){if(!(!(E instanceof S)||E instanceof $))throw E}let C=r.state?await r.state():void 0,{authorizationUrl:I,codeVerifier:M}=await Mr(u,{metadata:p,clientInformation:g,state:C,redirectUrl:r.redirectUrl,scope:m,resource:f});return await r.saveCodeVerifier(M),await r.redirectToAuthorization(I),"REDIRECT"}function xr(r){if(!r)return!1;try{let e=new URL(r);return e.protocol==="https:"&&e.pathname!=="/"}catch{return!1}}async function Er(r,e,t){let s=Zt(r);if(e.validateResourceURL)return await e.validateResourceURL(s,t?.resource);if(t){if(!Gt({requestedResource:s,configuredResource:t.resource}))throw new Error(`Protected resource ${t.resource} does not match expected ${s} (or origin)`);return new URL(t.resource)}}function se(r){let e=r.headers.get("WWW-Authenticate");if(!e)return{};let[t,s]=e.split(" ");if(t.toLowerCase()!=="bearer"||!s)return{};let o=Be(r,"resource_metadata")||void 0,i;if(o)try{i=new URL(o)}catch{}let a=Be(r,"scope")||void 0,n=Be(r,"error")||void 0;return{resourceMetadataUrl:i,scope:a,error:n}}function Be(r,e){let t=r.headers.get("WWW-Authenticate");if(!t)return null;let s=new RegExp(`${e}=(?:"([^"]+)"|([^\\s,]+))`),o=t.match(s);return o?o[1]||o[2]:null}async function Qt(r,e,t=fetch){let s=await Or(r,"oauth-protected-resource",t,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!s||s.status===404)throw await s?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!s.ok)throw await s.body?.cancel(),new Error(`HTTP ${s.status} trying to load well-known OAuth protected resource metadata.`);return Dt.parse(await s.json())}async function Ze(r,e,t=fetch){try{return await t(r,{headers:e})}catch(s){if(s instanceof TypeError)return e?Ze(r,void 0,t):void 0;throw s}}function Tr(r,e="",t={}){return e.endsWith("/")&&(e=e.slice(0,-1)),t.prependPathname?`${e}/.well-known/${r}`:`/.well-known/${r}${e}`}async function Kt(r,e,t=fetch){return await Ze(r,{"MCP-Protocol-Version":e},t)}function Ur(r,e){return!r||r.status>=400&&r.status<500&&e!=="/"}async function Or(r,e,t,s){let o=new URL(r),i=s?.protocolVersion??le,a;if(s?.metadataUrl)a=new URL(s.metadataUrl);else{let u=Tr(e,o.pathname);a=new URL(u,s?.metadataServerUrl??o),a.search=o.search}let n=await Kt(a,i,t);if(!s?.metadataUrl&&Ur(n,o.pathname)){let u=new URL(`/.well-known/${e}`,o);n=await Kt(u,i,t)}return n}function kr(r){let e=typeof r=="string"?new URL(r):r,t=e.pathname!=="/",s=[];if(!t)return s.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),s.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),s;let o=e.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),s.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,e.origin),type:"oauth"}),s.push({url:new URL(`/.well-known/openid-configuration${o}`,e.origin),type:"oidc"}),s.push({url:new URL(`${o}/.well-known/openid-configuration`,e.origin),type:"oidc"}),s}async function Xt(r,{fetchFn:e=fetch,protocolVersion:t=le}={}){let s={"MCP-Protocol-Version":t,Accept:"application/json"},o=kr(r);for(let{url:i,type:a}of o){let n=await Ze(i,s,e);if(n){if(!n.ok){if(await n.body?.cancel(),n.status>=400&&n.status<500)continue;throw new Error(`HTTP ${n.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}return a==="oauth"?De.parse(await n.json()):jt.parse(await n.json())}}}async function Ar(r,e){let t,s;try{t=await Qt(r,{resourceMetadataUrl:e?.resourceMetadataUrl},e?.fetchFn),t.authorization_servers&&t.authorization_servers.length>0&&(s=t.authorization_servers[0])}catch{}s||(s=String(new URL("/",r)));let o=await Xt(s,{fetchFn:e?.fetchFn});return{authorizationServerUrl:s,authorizationServerMetadata:o,resourceMetadata:t}}async function Mr(r,{metadata:e,clientInformation:t,redirectUrl:s,scope:o,state:i,resource:a}){let n;if(e){if(n=new URL(e.authorization_endpoint),!e.response_types_supported.includes(je))throw new Error(`Incompatible auth server: does not support response type ${je}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(Ve))throw new Error(`Incompatible auth server: does not support code challenge method ${Ve}`)}else n=new URL("/authorize",r);let u=await Ne(),p=u.code_verifier,d=u.code_challenge;return n.searchParams.set("response_type",je),n.searchParams.set("client_id",t.client_id),n.searchParams.set("code_challenge",d),n.searchParams.set("code_challenge_method",Ve),n.searchParams.set("redirect_uri",String(s)),i&&n.searchParams.set("state",i),o&&n.searchParams.set("scope",o),o?.includes("offline_access")&&n.searchParams.append("prompt","consent"),a&&n.searchParams.set("resource",a.href),{authorizationUrl:n,codeVerifier:p}}function Pr(r,e,t){return new URLSearchParams({grant_type:"authorization_code",code:r,code_verifier:e,redirect_uri:String(t)})}async function er(r,{metadata:e,tokenRequestParams:t,clientInformation:s,addClientAuthentication:o,resource:i,fetchFn:a}){let n=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",r),u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(i&&t.set("resource",i.href),o)await o(u,t,n,e);else if(s){let d=e?.token_endpoint_auth_methods_supported??[],f=Cr(s,d);br(f,s,u,t)}let p=await(a??fetch)(n,{method:"POST",headers:u,body:t});if(!p.ok)throw await Yt(p);return Vt.parse(await p.json())}async function Ir(r,{metadata:e,clientInformation:t,refreshToken:s,resource:o,addClientAuthentication:i,fetchFn:a}){let n=new URLSearchParams({grant_type:"refresh_token",refresh_token:s}),u=await er(r,{metadata:e,tokenRequestParams:n,clientInformation:t,addClientAuthentication:i,resource:o,fetchFn:a});return{refresh_token:s,...u}}async function Lr(r,e,{metadata:t,resource:s,authorizationCode:o,fetchFn:i}={}){let a=r.clientMetadata.scope,n;if(r.prepareTokenRequest&&(n=await r.prepareTokenRequest(a)),!n){if(!o)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!r.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let p=await r.codeVerifier();n=Pr(o,p,r.redirectUrl)}let u=await r.clientInformation();return er(e,{metadata:t,tokenRequestParams:n,clientInformation:u??void 0,addClientAuthentication:r.addClientAuthentication,resource:s,fetchFn:i})}async function qr(r,{metadata:e,clientMetadata:t,scope:s,fetchFn:o}){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",r);let a=await(o??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...t,...s!==void 0?{scope:s}:{}})});if(!a.ok)throw await Yt(a);return Bt.parse(await a.json())}var Re=class extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}},tr=10,$r=13,Y=32;function Ge(r){}function Me(r){if(typeof r=="function")throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:e=Ge,onError:t=Ge,onRetry:s=Ge,onComment:o,maxBufferSize:i}=r,a=[],n=0,u=!0,p,d="",f=0,m,g=!1;function R(h){if(g)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(u&&(u=!1,h.charCodeAt(0)===239&&h.charCodeAt(1)===187&&h.charCodeAt(2)===191&&(h=h.slice(3))),a.length===0){let T=C(h);T!==""&&(a.push(T),n=T.length),v();return}if(h.indexOf(`
5
- `)===-1&&h.indexOf("\r")===-1){a.push(h),n+=h.length,v();return}a.push(h);let l=a.join("");a.length=0,n=0;let y=C(l);y!==""&&(a.push(y),n=y.length),v()}function v(){i!==void 0&&(n+d.length<=i||(g=!0,a.length=0,n=0,p=void 0,d="",f=0,m=void 0,t(new Re(`Buffered data exceeded max buffer size of ${i} characters`,{type:"max-buffer-size-exceeded"}))))}function C(h){let l=0;if(h.indexOf("\r")===-1){let y=h.indexOf(`
6
- `,l);for(;y!==-1;){if(l===y){f>0&&e({id:p,event:m,data:d}),p=void 0,d="",f=0,m=void 0,l=y+1,y=h.indexOf(`
7
- `,l);continue}let T=h.charCodeAt(l);if(rr(h,l,T)){let U=h.charCodeAt(l+5)===Y?l+6:l+5,N=h.slice(U,y);if(f===0&&h.charCodeAt(y+1)===tr){e({id:p,event:m,data:N}),p=void 0,d="",m=void 0,l=y+2,y=h.indexOf(`
8
- `,l);continue}d=f===0?N:`${d}
9
- ${N}`,f++}else sr(h,l,T)?m=h.slice(h.charCodeAt(l+6)===Y?l+7:l+6,y)||void 0:I(h,l,y);l=y+1,y=h.indexOf(`
10
- `,l)}return h.slice(l)}for(;l<h.length;){let y=h.indexOf("\r",l),T=h.indexOf(`
11
- `,l),U=-1;if(y!==-1&&T!==-1?U=y<T?y:T:y!==-1?y===h.length-1?U=-1:U=y:T!==-1&&(U=T),U===-1)break;I(h,l,U),l=U+1,h.charCodeAt(l-1)===$r&&h.charCodeAt(l)===tr&&l++}return h.slice(l)}function I(h,l,y){if(l===y){E();return}let T=h.charCodeAt(l);if(rr(h,l,T)){let ee=h.charCodeAt(l+5)===Y?l+6:l+5,nt=h.slice(ee,y);d=f===0?nt:`${d}
12
- ${nt}`,f++;return}if(sr(h,l,T)){m=h.slice(h.charCodeAt(l+6)===Y?l+7:l+6,y)||void 0;return}if(T===105&&h.charCodeAt(l+1)===100&&h.charCodeAt(l+2)===58){let ee=h.slice(h.charCodeAt(l+3)===Y?l+4:l+3,y);p=ee.includes("\0")?void 0:ee;return}if(T===58){if(o){let ee=h.slice(l,y);o(ee.slice(h.charCodeAt(l+1)===Y?2:1))}return}let U=h.slice(l,y),N=U.indexOf(":");if(N===-1){M(U,"",U);return}let lr=U.slice(0,N),ur=U.charCodeAt(N+1)===Y?2:1,hr=U.slice(N+ur);M(lr,hr,U)}function M(h,l,y){switch(h){case"event":m=l||void 0;break;case"data":d=f===0?l:`${d}
13
- ${l}`,f++;break;case"id":p=l.includes("\0")?void 0:l;break;case"retry":/^\d+$/.test(l)?s(parseInt(l,10)):t(new Re(`Invalid \`retry\` value: "${l}"`,{type:"invalid-retry",value:l,line:y}));break;default:t(new Re(`Unknown field "${h.length>20?`${h.slice(0,20)}\u2026`:h}"`,{type:"unknown-field",field:h,value:l,line:y}));break}}function E(){f>0&&e({id:p,event:m,data:d}),p=void 0,d="",f=0,m=void 0}function F(h={}){if(h.consume&&a.length>0){let l=a.join("");I(l,0,l.length)}u=!0,p=void 0,d="",f=0,m=void 0,a.length=0,n=0,g=!1}return{feed:R,reset:F}}function rr(r,e,t){return t===100&&r.charCodeAt(e+1)===97&&r.charCodeAt(e+2)===116&&r.charCodeAt(e+3)===97&&r.charCodeAt(e+4)===58}function sr(r,e,t){return t===101&&r.charCodeAt(e+1)===118&&r.charCodeAt(e+2)===101&&r.charCodeAt(e+3)===110&&r.charCodeAt(e+4)===116&&r.charCodeAt(e+5)===58}var Pe=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:s,maxBufferSize:o}={}){let i;super({start(a){i=Me({onEvent:n=>{a.enqueue(n)},onError(n){typeof e=="function"&&e(n),(e==="terminate"||n.type==="max-buffer-size-exceeded")&&a.error(n)},onRetry:t,onComment:s,maxBufferSize:o})},transform(a){i.feed(a)}})}};var Hr={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},j=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},or=class{constructor(e,t){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=Ae(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??Hr}async _authThenStart(){if(!this._authProvider)throw new A("No auth provider");let e;try{e=await H(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(t){throw this.onerror?.(t),t}if(e!=="AUTHORIZED")throw new A;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let s=await this._authProvider.tokens();s&&(e.Authorization=`Bearer ${s.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let t=re(this._requestInit?.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){let{resumptionToken:t}=e;try{let s=await this._commonHeaders();s.set("Accept","text/event-stream"),t&&s.set("last-event-id",t);let o=await(this._fetch??fetch)(this._url,{method:"GET",headers:s,signal:this._abortController?.signal});if(!o.ok){if(await o.body?.cancel(),o.status===401&&this._authProvider)return await this._authThenStart();if(o.status===405)return;throw new j(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,e,!0)}catch(s){throw this.onerror?.(s),s}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,s=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*Math.pow(s,e),o)}_scheduleReconnection(e,t=0){let s=this._reconnectionOptions.maxRetries;if(t>=s){this.onerror?.(new Error(`Maximum reconnection attempts (${s}) exceeded.`));return}let o=this._getNextReconnectionDelay(t);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,t+1)})},o)}_handleSseStream(e,t,s){if(!e)return;let{onresumptiontoken:o,replayMessageId:i}=t,a,n=!1,u=!1;(async()=>{try{let d=e.pipeThrough(new TextDecoderStream).pipeThrough(new Pe({onRetry:g=>{this._serverRetryMs=g}})).getReader();for(;;){let{value:g,done:R}=await d.read();if(R)break;if(g.id&&(a=g.id,n=!0,o?.(g.id)),!!g.data&&(!g.event||g.event==="message"))try{let v=te.parse(JSON.parse(g.data));mt(v)&&(u=!0,i!==void 0&&(v.id=i)),this.onmessage?.(v)}catch(v){this.onerror?.(v)}}(s||n)&&!u&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:o,replayMessageId:i},0)}catch(d){if(this.onerror?.(new Error(`SSE stream disconnected: ${d}`)),(s||n)&&!u&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:o,replayMessageId:i},0)}catch(g){this.onerror?.(new Error(`Failed to reconnect: ${g instanceof Error?g.message:String(g)}`))}}})()}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 A("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 A("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,t){try{let{resumptionToken:s,onresumptiontoken:o}=t||{};if(s){this._startOrAuthSse({resumptionToken:s,replayMessageId:_t(e)?e.id:void 0}).catch(m=>this.onerror?.(m));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},n=await(this._fetch??fetch)(this._url,a),u=n.headers.get("mcp-session-id");if(u&&(this._sessionId=u),!n.ok){let m=await n.text().catch(()=>null);if(n.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new j(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:g,scope:R}=se(n);if(this._resourceMetadataUrl=g,this._scope=R,await H(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new A;return this._hasCompletedAuthFlow=!0,this.send(e)}if(n.status===403&&this._authProvider){let{resourceMetadataUrl:g,scope:R,error:v}=se(n);if(v==="insufficient_scope"){let C=n.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===C)throw new j(403,"Server returned 403 after trying upscoping");if(R&&(this._scope=R),g&&(this._resourceMetadataUrl=g),this._lastUpscopingHeader=C??void 0,await H(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new A;return this.send(e)}}throw new j(n.status,`Error POSTing to endpoint: ${m}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,n.status===202){await n.body?.cancel(),gt(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(m=>this.onerror?.(m));return}let d=(Array.isArray(e)?e:[e]).filter(m=>"method"in m&&"id"in m&&m.id!==void 0).length>0,f=n.headers.get("content-type");if(d)if(f?.includes("text/event-stream"))this._handleSseStream(n.body,{onresumptiontoken:o},!1);else if(f?.includes("application/json")){let m=await n.json(),g=Array.isArray(m)?m.map(R=>te.parse(R)):[te.parse(m)];for(let R of g)this.onmessage?.(R)}else throw await n.body?.cancel(),new j(-1,`Unexpected content type: ${f}`);else await n.body?.cancel()}catch(s){throw this.onerror?.(s),s}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},s=await(this._fetch??fetch)(this._url,t);if(await s.body?.cancel(),!s.ok&&s.status!==405)throw new j(s.status,`Failed to terminate session: ${s.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,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}};var Le=class extends Event{constructor(e,t){var s,o;super(e),this.code=(s=t?.code)!=null?s:void 0,this.message=(o=t?.message)!=null?o:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,t,s){return s(nr(this),t)}[Symbol.for("Deno.customInspect")](e,t){return e(nr(this),t)}};function Wr(r){let e=globalThis.DOMException;return typeof e=="function"?new e(r,"SyntaxError"):new SyntaxError(r)}function Je(r){return r instanceof Error?"errors"in r&&Array.isArray(r.errors)?r.errors.map(Je).join(", "):"cause"in r&&r.cause instanceof Error?`${r}: ${Je(r.cause)}`:r.message:`${r}`}function nr(r){return{type:r.type,message:r.message,code:r.code,defaultPrevented:r.defaultPrevented,cancelable:r.cancelable,timeStamp:r.timeStamp}}var ar=r=>{throw TypeError(r)},st=(r,e,t)=>e.has(r)||ar("Cannot "+t),w=(r,e,t)=>(st(r,e,"read from private field"),t?t.call(r):e.get(r)),x=(r,e,t)=>e.has(r)?ar("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),b=(r,e,t,s)=>(st(r,e,"write to private field"),e.set(r,t),t),W=(r,e,t)=>(st(r,e,"access private method"),t),P,Q,oe,Ie,qe,xe,ae,Ee,V,ne,ce,ie,Se,L,Ke,Ye,Qe,ir,Xe,et,ze,tt,rt,X=class extends EventTarget{constructor(e,t){var s,o;super(),x(this,L),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,x(this,P),x(this,Q),x(this,oe),x(this,Ie),x(this,qe),x(this,xe),x(this,ae),x(this,Ee,null),x(this,V),x(this,ne),x(this,ce,null),x(this,ie,null),x(this,Se,null),x(this,Ye,async i=>{var a;w(this,ne).reset();let{body:n,redirected:u,status:p,headers:d}=i;if(p===204){W(this,L,ze).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(u?b(this,oe,new URL(i.url)):b(this,oe,void 0),p!==200){W(this,L,ze).call(this,`Non-200 status code (${p})`,p);return}if(!(d.get("content-type")||"").startsWith("text/event-stream")){W(this,L,ze).call(this,'Invalid content type, expected "text/event-stream"',p);return}if(w(this,P)===this.CLOSED)return;b(this,P,this.OPEN);let f=new Event("open");if((a=w(this,Se))==null||a.call(this,f),this.dispatchEvent(f),typeof n!="object"||!n||!("getReader"in n)){W(this,L,ze).call(this,"Invalid response body, expected a web ReadableStream",p),this.close();return}let m=new TextDecoder,g=n.getReader(),R=!0;do{let{done:v,value:C}=await g.read();C&&w(this,ne).feed(m.decode(C,{stream:!v})),v&&(R=!1,w(this,ne).reset(),W(this,L,tt).call(this))}while(R)}),x(this,Qe,i=>{b(this,V,void 0),!(i.name==="AbortError"||i.type==="aborted")&&W(this,L,tt).call(this,Je(i))}),x(this,Xe,i=>{typeof i.id=="string"&&b(this,Ee,i.id);let a=new MessageEvent(i.event||"message",{data:i.data,origin:w(this,oe)?w(this,oe).origin:w(this,Q).origin,lastEventId:i.id||""});w(this,ie)&&(!i.event||i.event==="message")&&w(this,ie).call(this,a),this.dispatchEvent(a)}),x(this,et,i=>{b(this,xe,i)}),x(this,rt,()=>{b(this,ae,void 0),w(this,P)===this.CONNECTING&&W(this,L,Ke).call(this)});try{if(e instanceof URL)b(this,Q,e);else if(typeof e=="string")b(this,Q,new URL(e,Nr()));else throw new Error("Invalid URL")}catch{throw Wr("An invalid or illegal string was specified")}b(this,ne,Me({onEvent:w(this,Xe),onRetry:w(this,et)})),b(this,P,this.CONNECTING),b(this,xe,3e3),b(this,qe,(s=t?.fetch)!=null?s:globalThis.fetch),b(this,Ie,(o=t?.withCredentials)!=null?o:!1),W(this,L,Ke).call(this)}get readyState(){return w(this,P)}get url(){return w(this,Q).href}get withCredentials(){return w(this,Ie)}get onerror(){return w(this,ce)}set onerror(e){b(this,ce,e)}get onmessage(){return w(this,ie)}set onmessage(e){b(this,ie,e)}get onopen(){return w(this,Se)}set onopen(e){b(this,Se,e)}addEventListener(e,t,s){let o=t;super.addEventListener(e,o,s)}removeEventListener(e,t,s){let o=t;super.removeEventListener(e,o,s)}close(){w(this,ae)&&clearTimeout(w(this,ae)),w(this,P)!==this.CLOSED&&(w(this,V)&&w(this,V).abort(),b(this,P,this.CLOSED),b(this,V,void 0))}};P=new WeakMap,Q=new WeakMap,oe=new WeakMap,Ie=new WeakMap,qe=new WeakMap,xe=new WeakMap,ae=new WeakMap,Ee=new WeakMap,V=new WeakMap,ne=new WeakMap,ce=new WeakMap,ie=new WeakMap,Se=new WeakMap,L=new WeakSet,Ke=function(){b(this,P,this.CONNECTING),b(this,V,new AbortController),w(this,qe)(w(this,Q),W(this,L,ir).call(this)).then(w(this,Ye)).catch(w(this,Qe))},Ye=new WeakMap,Qe=new WeakMap,ir=function(){var r;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...w(this,Ee)?{"Last-Event-ID":w(this,Ee)}:void 0},cache:"no-store",signal:(r=w(this,V))==null?void 0:r.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},Xe=new WeakMap,et=new WeakMap,ze=function(r,e){var t;w(this,P)!==this.CLOSED&&b(this,P,this.CLOSED);let s=new Le("error",{code:e,message:r});(t=w(this,ce))==null||t.call(this,s),this.dispatchEvent(s)},tt=function(r,e){var t;if(w(this,P)===this.CLOSED)return;b(this,P,this.CONNECTING);let s=new Le("error",{code:e,message:r});(t=w(this,ce))==null||t.call(this,s),this.dispatchEvent(s),b(this,ae,setTimeout(w(this,rt),w(this,xe)))},rt=new WeakMap,X.CONNECTING=0,X.OPEN=1,X.CLOSED=2;function Nr(){let r="document"in globalThis?globalThis.document:void 0;return r&&typeof r=="object"&&"baseURI"in r&&typeof r.baseURI=="string"?r.baseURI:void 0}var ot=class extends Error{constructor(e,t,s){super(`SSE error: ${t}`),this.code=e,this.event=s}},cr=class{constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=t?.eventSourceInit,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=Ae(t?.fetch,t?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new A("No auth provider");let e;try{e=await H(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(t){throw this.onerror?.(t),t}if(e!=="AUTHORIZED")throw new A;return await this._startOrAuth()}async _commonHeaders(){let e={};if(this._authProvider){let s=await this._authProvider.tokens();s&&(e.Authorization=`Bearer ${s.access_token}`)}this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let t=re(this._requestInit?.headers);return new Headers({...e,...t})}_startOrAuth(){let e=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((t,s)=>{this._eventSource=new X(this._url.href,{...this._eventSourceInit,fetch:async(o,i)=>{let a=await this._commonHeaders();a.set("Accept","text/event-stream");let n=await e(o,{...i,headers:a});if(n.status===401&&n.headers.has("www-authenticate")){let{resourceMetadataUrl:u,scope:p}=se(n);this._resourceMetadataUrl=u,this._scope=p}return n}}),this._abortController=new AbortController,this._eventSource.onerror=o=>{if(o.code===401&&this._authProvider){this._authThenStart().then(t,s);return}let i=new ot(o.code,o.message,o);s(i),this.onerror?.(i)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",o=>{let i=o;try{if(this._endpoint=new URL(i.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(a){s(a),this.onerror?.(a),this.close();return}t()}),this._eventSource.onmessage=o=>{let i=o,a;try{a=te.parse(JSON.parse(i.data))}catch(n){this.onerror?.(n);return}this.onmessage?.(a)}})}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 A("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 A("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 t=await this._commonHeaders();t.set("content-type","application/json");let s={...this._requestInit,method:"POST",headers:t,body:JSON.stringify(e),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._endpoint,s);if(!o.ok){let i=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){let{resourceMetadataUrl:a,scope:n}=se(o);if(this._resourceMetadataUrl=a,this._scope=n,await H(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new A;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${o.status}): ${i}`)}await o.body?.cancel()}catch(t){throw this.onerror?.(t),t}}setProtocolVersion(e){this._protocolVersion=e}};function Dr(r,e){let t=new Headers(r);for(let[s,o]of new Headers(e).entries())t.set(s,o);return t}function jr(r,e){let t=r.headers.get("location");return t?new URL(t,e):null}async function Vr(r){try{await r.body?.cancel()}catch{}}function Os(r,e=fetch){return async(t,s)=>{let o=new Request(t,s),i=new Request(o,{headers:Dr(r,o.headers),redirect:"manual"}),a=new URL(i.url),n=await e(i),u=jr(n,a);if(n.status<300||n.status>=400||!u)return n;throw await Vr(n),new Error(`MCP redirect rejected: ${a.origin} -> ${u.origin}`)}}export{Wt as a,or as b,cr as c,Os as d};
@@ -1,7 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{e as a}from"./chunk-E7ZMYIY6.js";import{e as R}from"./chunk-NAA7GF6Q.js";import{n as O}from"./chunk-J5DVLUKY.js";import{spawn as At}from"node:child_process";import{randomUUID as V}from"node:crypto";var C=1800*1e3,k=200,Z=8,Q="***",tt=R("login-flow"),S=class extends Error{code;name="LoginFlowError";constructor(e,n,r){super(n,r===void 0?void 0:{cause:r}),this.code=e}};function I(t){if(!t||typeof t!="object")return!1;let e=t;return e.name==="LoginFlowError"&&typeof e.message=="string"&&typeof e.code=="string"}function et(t){let n=(t instanceof Error?t.message:typeof t=="string"?t:"").split(`
5
- `).map(r=>r.trim()).find(Boolean)??"";return n.length>k?`${n.slice(0,k-1)}\u2026`:n}function nt(t,e){let n=et(e),r=t.replace(/[.。]\s*$/u,"");return!n||n===t||n===r?t:a("ux.auth.failureDetail",{message:r,detail:n})}var rt=new Set(["done","failed","cancelled"]),l=new Map,h=new Map;function F(t){return`${t.backend}\0${t.provider}`}function d(t){let e=new Error(t);return e.name="AbortError",e}function m(t){return rt.has(t.state.step)}function ot(t){if(!t)return null;let e=t.options?.map(n=>({...n}));return e?{...t,options:e}:{...t}}function it(t){return t?t.kind!=="info"||!t.links?{...t}:{...t,links:t.links.map(e=>({...e}))}:null}function D(t){return t?{...t}:null}function c(t){t.state.revision+=1}function _(t){return{...t.state,pendingPrompt:ot(t.state.pendingPrompt),notice:it(t.state.notice),outcome:D(t.state.outcome)}}function E(t){h.get(t.pairKey)===t.state.flowId&&h.delete(t.pairKey)}function T(t){let e=t.pending;return e?(e.signal?.removeEventListener("abort",e.onAbort),t.pending=null,t.state.pendingPrompt=null,c(t),e):null}function N(t,e){t.controller.signal.aborted||t.controller.abort(d(e))}function U(t){l.get(t.state.flowId)===t&&(l.delete(t.state.flowId),E(t),clearTimeout(t.timer),t.secrets.clear(),m(t)||N(t,"Login flow expired."),T(t)?.reject(d("Login flow expired.")))}function w(t){let e=l.get(t);return e?Date.now()<e.expiresAtMs?e:(U(e),null):null}function st(t){let e=w(t);if(!e)throw new Error(a("ux.auth.flowNotFound"));return e}function A(t){let e=st(t);if(m(e))throw new Error(a("ux.auth.flowNotActive"));return e}function at(t,e){let n={id:e,kind:t.type,message:t.message};return t.type==="select"?n.options=t.options.map(r=>({...r})):t.placeholder&&(n.placeholder=t.placeholder),n}function ut(t,e){t.pending===e&&(T(t),t.state.step==="prompt"&&(t.state.step="running"),e.reject(d("Authentication prompt aborted.")))}async function ct(t,e){let n=A(t);if(n.pending)throw new Error("Login flow already has a pending prompt.");if(e.signal?.aborted)throw d("Authentication prompt aborted.");return c(n),n.state.step="prompt",n.state.pendingPrompt=at(e,n.state.revision),new Promise((r,o)=>{let i={resolve:r,reject:o,signal:e.signal};i.onAbort=()=>ut(n,i),n.pending=i,e.signal?.addEventListener("abort",i.onAbort,{once:!0})})}function lt(t){if(t.type==="info"){let e=t.links?.map(n=>({...n}));return e?{kind:"info",message:t.message,links:e}:{kind:"info",message:t.message}}return t.type==="auth_url"?{kind:"auth_url",url:t.url,instructions:t.instructions}:t.type==="device_code"?{kind:"device_code",userCode:t.userCode,verificationUri:t.verificationUri,intervalSeconds:t.intervalSeconds,expiresInSeconds:t.expiresInSeconds}:{kind:"progress",message:t.message}}function dt(t){return{signal:t.controller.signal,prompt:e=>ct(t.state.flowId,e),notify:e=>{let n=A(t.state.flowId);n.state.notice=lt(e),c(n)}}}function H(t){return l.get(t.state.flowId)===t&&!m(t)}var b=new Set;function Dt(t){return b.add(t),()=>{b.delete(t)}}function pt(t){for(let e of b)try{e(t)}catch{}}function ft(t,e){H(t)&&(t.state.step="done",t.state.pendingPrompt=null,c(t),t.state.outcome=D(e),t.state.error=null,t.state.errorCode=null,t.secrets.clear(),E(t),pt({backend:t.state.backend,provider:e.provider||t.state.provider||"",authType:e.authType}))}function g(t,e){return[...e].filter(r=>r.length>=Z).sort((r,o)=>o.length-r.length).reduce((r,o)=>r.split(o).join(Q),t)}function ht(t,e,n){e!=="secret"&&e!=="manual_code"||(t.secrets.add(n),t.secrets.add(n.trim()))}function gt(t){let e=I(t)&&t.cause!==void 0?t.cause:t;return e instanceof Error?I(e)?e.message:e.stack??e.message:String(e)}function mt(t,e){if(!H(t))return;let n=I(e)?e:null,r=`login ${t.state.backend}/${t.state.provider} failed (${n?.code??"unexpected"}):`;tt.warn(r,g(gt(e),t.secrets)),t.state.step="failed",t.state.pendingPrompt=null,c(t),t.state.outcome=null;let o=n?.message??nt(a("ux.auth.loginFailed"),e);t.state.error=g(o,t.secrets),t.state.errorCode=n?.code??null,t.secrets.clear(),E(t)}function _t(t,e){Promise.resolve().then(()=>e(dt(t))).then(n=>ft(t,n),n=>mt(t,n))}function Et(t){let e=h.get(F(t));if(!e)return null;let n=w(e);return!n||m(n)?null:n}function j(t){let e=T(t);t.state.step="cancelled",c(t),t.state.outcome=null,t.state.error=null,t.state.errorCode=null,t.secrets.clear(),E(t),N(t,"Login flow cancelled."),e?.reject(d("Login flow cancelled."))}function Tt(t){let e=Date.now(),o={state:{flowId:V(),revision:0,backend:t.backend,provider:t.provider,authType:t.authType,step:"running",pendingPrompt:null,notice:null,channel:t.channel,sessionId:t.sessionId,createdAt:new Date(e).toISOString(),expiresAt:new Date(e+C).toISOString(),outcome:null,error:null,errorCode:null},pairKey:F(t),expiresAtMs:e+C,controller:new AbortController,pending:null,secrets:new Set};return o.timer=setTimeout(()=>U(o),C),o.timer.unref(),o}async function Nt(t,e){let n=Et(t);n&&j(n);let r=Tt(t);return l.set(r.state.flowId,r),h.set(r.pairKey,r.state.flowId),_t(r,e),_(r)}async function Ut(t,e,n){let r=A(t);if(n!==void 0&&r.state.pendingPrompt&&r.state.pendingPrompt.id!==n)throw new S("stale_prompt",a("ux.auth.flowNotWaiting"));let o=r.state.pendingPrompt?.kind,i=T(r);if(!i)throw new Error(a("ux.auth.flowNotWaiting"));return o&&ht(r,o,e),r.state.step="running",i.resolve(e),_(r)}async function Ht(t){let e=A(t);return j(e),_(e)}function jt(t){let e=w(t);return e?_(e):null}var Ct=1800*1e3,G=64*1024,$=200,z="Paste code here if prompted >",B=/https:\/\/claude\.com\/cai\/oauth\/authorize\?[^\s\x1b]+/,St=/\x1B\[[0-?]*[ -/]*[@-~]/g,It=/\x1B\][^\x07]*(?:\x07|\x1B\\)/g,bt=["HOME","PATH","SHELL","USER","LOGNAME","LANG","LC_ALL","LC_CTYPE","TERM","TZ","TMPDIR","TMP","TEMP","XDG_CONFIG_HOME","XDG_CACHE_HOME","XDG_DATA_HOME","HTTPS_PROXY","HTTP_PROXY","NO_PROXY","https_proxy","http_proxy","no_proxy","SSL_CERT_FILE","SSL_CERT_DIR","NODE_EXTRA_CA_CERTS"],y=class extends Error{code;name="ClaudeAuthCliError";constructor(e,n){super(n),this.code=e}};function u(t,e){return new y(t,e)}function X(t,e){return e?`${t.replace(/\.$/,"")}: ${e}`:t}function wt(t=process.env){let e={BROWSER:"true",CLAUDE_CONFIG_DIR:O};for(let n of bt)t[n]!==void 0&&(e[n]=t[n]);return e}function P(t,e){return(e.spawn??At)(e.executable??"claude",t,{env:wt(e.env),stdio:["pipe","pipe","pipe"]})}function p(t,e=""){return u(t,X({claude_auth_login_failed:"Claude authentication login failed.",claude_auth_logout_failed:"Claude authentication logout failed.",claude_auth_status_failed:"Claude authentication status check failed."}[t]??"Claude authentication command failed.",e))}var L=class{child;options;resolve;reject;settled=!1;timer;onAbort=()=>this.stop(u("claude_auth_cancelled","Claude authentication was cancelled."));constructor(e,n,r,o,i){this.child=e,this.options=r,this.resolve=o,this.reject=i,this.timer=setTimeout(()=>this.stop(u("claude_auth_timeout","Claude authentication timed out.")),n.timeoutMs??Ct),r.signal?.addEventListener("abort",this.onAbort,{once:!0}),e.once("error",s=>this.finish(p(r.failureCode,s.message))),e.once("close",s=>this.finish(s===0?void 0:p(r.failureCode,W(r.output)))),r.signal?.aborted&&this.onAbort()}cleanup(){clearTimeout(this.timer),this.options.signal?.removeEventListener("abort",this.onAbort)}finish(e){this.settled||(this.settled=!0,this.cleanup(),e?this.reject(e):this.resolve())}stop(e){if(!this.settled){this.settled=!0,this.cleanup(),this.options.onStop?.(e);try{this.child.kill("SIGTERM")}catch{}this.reject(e)}}};function M(t,e,n){return new Promise((r,o)=>{new L(t,e,n,r,o)})}function x(t,e){let n=t+String(e);return n.length<=G?n:n.slice(-G)}function K(t){return t.replace(It,"").replace(St,"")}function yt(t){let e=t.trim();return e&&!/[\r\n]/.test(e)?e:null}function v(t){let e={text:"",secrets:[]},n=r=>{e.text=x(e.text,r)};return t.stdout.on("data",n),t.stderr.on("data",n),e}function W(t){let e=K(t.text).split(z).join(`
6
- `).split(/\r\n|\r|\n/).map(r=>r.trim()).filter(r=>r&&!B.test(r)),n=g(e.at(-1)??"",t.secrets);return n.length>$?`${n.slice(0,$-1)}\u2026`:n}async function Lt(t,e){let n=P(["auth","status","--json"],t),r="";n.stdout.on("data",i=>{r=x(r,i)});let o=v(n);return await M(n,t,{signal:e,failureCode:"claude_auth_status_failed",output:o}),r}function Pt(t){try{let e=JSON.parse(t.trim());if(typeof e.loggedIn!="boolean")throw new Error("missing loggedIn");return{loggedIn:e.loggedIn,authMethod:typeof e.authMethod=="string"?e.authMethod:null,apiProvider:typeof e.apiProvider=="string"?e.apiProvider:null}}catch{throw u("claude_auth_status_invalid","Claude authentication status was invalid.")}}async function Y(t={},e){return Pt(await Lt(t,e))}function q(t,e,n){if(!t.settled){if(t.settled=!0,n)try{t.child.kill("SIGTERM")}catch{}t.reject(e)}}function Mt(t,e){t.settled=!0,t.output.secrets.push(e);try{t.child.stdin.write(`${e}
7
- `),t.options.onCodeSubmitted?.(),t.resolve()}catch{try{t.child.kill("SIGTERM")}catch{}t.reject(p("claude_auth_login_failed"))}}async function xt(t,e){try{let n=yt(await t.options.onAuthorization(e));if(!n)throw p("claude_auth_login_failed");if(t.settled||t.options.signal?.aborted)return;Mt(t,n)}catch{q(t,p("claude_auth_login_failed"),!0)}}function vt(t,e){t.buffer=x(t.buffer,e);let n=K(t.buffer),r=n.match(B)?.[0];t.started||!r||!n.includes(z)||(t.started=!0,xt(t,r))}function Ot(t,e,n,r){return new Promise((o,i)=>{let s={child:t,options:e,output:n,buffer:"",started:!1,settled:!1,resolve:o,reject:i},f=J=>vt(s,J);t.stdout.on("data",f),t.stderr.on("data",f),t.once("close",()=>q(s,r()??u("claude_auth_login_protocol",X("Claude authentication did not complete browser authorization.",W(n))),!1))})}async function Xt(t,e={}){let n=P(["auth","login","--claudeai"],e),r=v(n),o=null,i=Ot(n,t,r,()=>o);await Promise.all([i,M(n,e,{signal:t.signal,failureCode:"claude_auth_login_failed",output:r,onStop:f=>{o=f}})]);let s=await Y(e,t.signal);if(!s.loggedIn)throw u("claude_auth_not_logged_in","Claude Code did not persist the login.");return s}async function Kt(t={}){let e=P(["auth","logout"],t),n=v(e);if(await M(e,t,{failureCode:"claude_auth_logout_failed",output:n}),(await Y(t)).loggedIn)throw u("claude_auth_still_logged_in","Claude Code remained logged in after logout.")}export{C as a,S as b,I as c,nt as d,Dt as e,g as f,gt as g,Nt as h,Ut as i,Ht as j,jt as k,y as l,wt as m,Y as n,Xt as o,Kt as p};
@@ -1,10 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{d as K,f as V}from"./chunk-MEPASGPP.js";import{a as J}from"./chunk-PFMEUFJ7.js";import{J as t}from"./chunk-DPQPXBTP.js";import{d as G}from"./chunk-E7ZMYIY6.js";import{e as $}from"./chunk-NAA7GF6Q.js";import{e as z}from"./chunk-QWAQHHRS.js";import{c as _,m as X}from"./chunk-J5DVLUKY.js";var A=1,q=64*1024,I=200,Pt="other",Yt="custom",Ht="mcp_other",c=t.string().regex(/^[A-Za-z0-9._:/@[\]-]{1,80}$/),o=t.number().int().nonnegative(),u=t.number().nonnegative(),f=t.iso.datetime(),ye=t.string().regex(/^\d{4}-\d{2}-\d{2}$/),b=t.string().max(40),y=t.string().max(300),O={ttftMs:[500,1e3,2e3,5e3,1e4,3e4,6e4],turnDurationS:[5,15,30,60,120,300,600,1800,3600],contextPct:[10,25,50,75,90,100],turnsPerSession:[1,2,5,10,20,50,100],webLoadMs:[200,500,1e3,2e3,5e3,1e4]};function d(e){return t.array(o).length(O[e].length+1)}function Bt(e,n){let r=O[e],s=r.findIndex(i=>n<=i);return s===-1?r.length:s}function Xt(e){return new Array(O[e].length+1).fill(0)}var ge=t.object({schema:t.literal(A),installId:t.uuid(),sentAt:f,version:b,channel:t.enum(["release","dev"]),installForm:t.enum(["desktop","npm","other"]),os:t.enum(["linux","darwin","win32","android","other"]),osRelease:t.string().max(20),arch:t.string().max(20),nodeMajor:t.number().int().nullable(),uiLang:t.enum(["en","zh","other"])}),Re=["server","daemon","web","desktop","android"],Le=["uncaughtException","unhandledRejection","childExit","renderError","windowError","panic"],ve=["desktop","android","browser"],we=t.object({type:t.literal("crash"),at:f,component:t.enum(Re),kind:t.enum(Le),errorName:t.string().max(80),message:y,stack:t.string().max(8e3),groupKey:t.string().max(200),uptimeS:u.nullable(),route:t.string().max(80).nullable(),buildStamp:t.string().max(60).nullable(),client:t.enum(ve).nullable(),exit:t.object({code:t.number().int().nullable(),signal:t.string().max(20).nullable(),backoffMs:o}).nullable(),suppressed:o}),Ae=t.object({type:t.literal("heartbeat"),at:f,backends:t.array(t.enum(["claude","pi"])).max(2),claudeBilling:t.enum(["plan","api","none"]),piProviders:t.array(c).max(60),projects:o,onlineClients:o,clientPlatforms:t.partialRecord(t.enum(["linux","darwin","win32","other"]),o),activeSessions24h:o,uptimeH:u,settings:t.record(c,t.boolean())}),Ie=["network","permission","npm","disk","timeout","other"],Oe=t.object({type:t.literal("upgrade"),at:f,from:b,to:b,method:t.enum(["auto","prompt","manual"]),stage:t.enum(["installed","failed","confirmed","unconfirmed","version-changed"]),durationS:u.nullable(),failure:t.object({class:t.enum(Ie),message:y}).nullable()}),Me=t.object({type:t.literal("migration_failure"),at:f,migration:c,errorClass:t.enum(["io","parse","permission","other"]),message:y}),ke=["setup_started","server_installed","server_install_failed","init_completed","init_failed","daemon_started","daemon_start_failed"],Ne=["server_init_completed","provider_authed","first_session","first_turn_completed","first_remote_client","first_worker","first_schedule"];var je=t.object({type:t.literal("funnel"),at:f,source:t.enum(["desktop-setup","server"]),step:t.enum([...ke,...Ne]),detail:c.nullable()}),Ce=["auth","rate_limit","network","adapter_crash","timeout","other"],De=t.object({backend:t.enum(["claude","pi"]),provider:c,model:c,billing:t.enum(["plan","api"]).nullable(),customApi:c.nullable(),outcomes:t.object({completed:o,failed:o,cancelled:o,rateLimited:o}),failures:t.partialRecord(t.enum(Ce),o),retries:o,fallbacks:o,ttftMs:d("ttftMs"),durationS:d("turnDurationS"),contextPctAtEnd:d("contextPct"),compactions:t.object({auto:o,manual:o}),tokens:t.object({input:o,output:o,cacheRead:o,cacheWrite:o})}),Fe=["session_created","worker_spawned","subagent_run","board_opened","schedule_created","schedule_fired","waitpoint_created","waitpoint_signaled","browser_session","plan_submitted","plan_approved","plan_rejected","ask_user_asked","ask_user_answered","remote_client_connected"],Ue=["desktop","android","browser","feishu","slack","tui","other"],W=t.object({completed:o,failed:o,cancelled:o}),Pe=t.object({type:t.literal("daily"),day:ye,turns:t.array(De).max(100),features:t.partialRecord(t.enum(Fe),o),messagesByChannel:t.partialRecord(t.enum(Ue),o),uiOps:t.record(c,o),tools:t.array(t.object({name:c,calls:o,errors:o})).max(200),agent:t.object({userInterrupts:o,superseded:o,turnsPerSession:d("turnsPerSession"),workers:W,subagents:W}),perf:t.object({startups:t.array(t.record(c,u)).max(10),eventLoop:t.object({windows:o,p99MedianMs:u,p99MaxMs:u}),web:t.object({loads:o,ttfbMs:d("webLoadMs"),firstRenderMs:d("webLoadMs"),interactiveMs:d("webLoadMs")}),sseReconnects:o,remoteClientDisconnects:o}),errors:t.object({byModule:t.record(c,o),samples:t.array(t.object({module:c,groupKey:t.string().max(200),message:y,count:o})).max(5)})}),g=t.discriminatedUnion("type",[we,Ae,Oe,Me,je,Pe]),Z=t.object({envelope:ge,events:t.array(g).min(1).max(I)}),$t=t.discriminatedUnion("kind",[t.object({kind:t.literal("crash"),crashKind:t.enum(["renderError","windowError","unhandledRejection"]),errorName:t.string().max(200),message:t.string().max(2e3),stack:t.string().max(2e4),route:t.string().max(80).nullable(),buildStamp:t.string().max(60).nullable(),uptimeS:u.nullable()}),t.object({kind:t.literal("native_crash"),component:t.enum(["desktop","android"]),at:f,message:t.string().max(2e3),stack:t.string().max(2e4),appVersion:b}),t.object({kind:t.literal("load"),ttfbMs:u.nullable(),firstRenderMs:u.nullable(),interactiveMs:u.nullable()}),t.object({kind:t.literal("sse_reconnect"),count:t.number().int().min(1).max(1e3)})]),Kt="x-cortex-client",Vt=t.object({enabled:t.boolean(),installId:t.uuid().optional()});import{randomUUID as He}from"node:crypto";import{mkdirSync as Be,readFileSync as Xe,writeFileSync as $e}from"node:fs";import Ke from"node:path";import T from"node:path";var R=T.join(X,"telemetry"),M=T.join(R,"install-id"),x=T.join(R,"outbox.jsonl"),k=T.join(R,"state.json"),Ye="rollup-";function Wt(e,n=R){return T.join(n,`${Ye}${e}.json`)}var N=new Map,Ve=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Q(e){return typeof e=="string"&&Ve.test(e)}function Ge(e){try{let n=Xe(e,"utf8").trim();return Q(n)?n.toLowerCase():null}catch{return null}}function ee(e,n){Be(Ke.dirname(e),{recursive:!0}),$e(e,`${n}
5
- `,{encoding:"utf8",mode:384})}function te(e=M){let n=Ge(e),r=n??N.get(e)??He();if(!n)try{ee(e,r)}catch{}return N.set(e,r),r}function nn(e,n=M){if(!Q(e))throw new Error("install id must be a UUID");ee(n,e.toLowerCase()),N.set(n,e.toLowerCase())}import{existsSync as We,statSync as qe}from"node:fs";import Ze from"node:path";import{readFileSync as Je}from"node:fs";import ze from"node:path";var ne=ze.join(_,"dist","build-info.json"),j;function oe(e){if(typeof e!="string"||e.trim()==="")return null;try{let n=new URL(e.trim());return n.protocol==="https:"||n.protocol==="http:"?n.toString():null}catch{return null}}function re(e){try{let n=JSON.parse(Je(e,"utf8"));return oe(n.telemetryEndpoint)}catch{return null}}function se(e=process.env,n=ne){let r=oe(e.CORTEX_TELEMETRY_ENDPOINT);return r||(n!==ne?re(n):(j===void 0&&(j=re(n)),j))}function Qe(e){if(e===void 0)return!1;let n=e.trim().toLowerCase();return n!==""&&n!=="0"&&n!=="false"&&n!=="no"&&n!=="off"}function et(e){return e.CORTEX_TELEMETRY?.trim()==="0"?"env":Qe(e.DO_NOT_TRACK)?"do-not-track":e.CORTEX_CONFIG_IMMUTABLE==="1"?"sealed":null}function tt(e){let n=e.env.CORTEX_TELEMETRY?.trim()==="1",r=e.devCheckout?"dev":"release",s=a=>({active:!1,reason:a,channel:r,endpoint:e.endpoint}),i=et(e.env);return i?s(i):e.settingEnabled?e.devCheckout&&!n?s("dev"):e.endpoint?{active:!0,reason:null,channel:r,endpoint:e.endpoint}:s("no-endpoint"):s("setting")}var ie;function nt(){let e=process.env.CORTEX_REPO;try{return!!e&&qe(e).isDirectory()}catch{return!1}}function rt(){return ie??=We(Ze.join(_,"src","entry"))||nt(),ie}function C(e=process.env){return tt({settingEnabled:K().telemetryEnabled,env:e,devCheckout:rt(),endpoint:se(e)})}function h(){return C().active}import{mkdirSync as ot,readFileSync as st,writeFileSync as it}from"node:fs";import at from"node:path";var ae={lastHeartbeatAt:null,lastVersion:null,funnelSent:[],pendingUpgrade:null};function D(e=k){try{let n=JSON.parse(st(e,"utf8"));return{...ae,...n,funnelSent:Array.isArray(n.funnelSent)?n.funnelSent.filter(r=>typeof r=="string"):[]}}catch{return{...ae}}}function ce(e,n=k){let r=e(D(n));try{ot(at.dirname(n),{recursive:!0}),it(n,`${JSON.stringify(r,null,2)}
6
- `,"utf8")}catch{}return r}import ct from"node:os";var lt=["linux","darwin","win32","android"];function ut(e=process.env,n=_){return e.CORTEX_NPM_PREFIX?.trim()?"desktop":z(n,"@cortex-agent/server")?"npm":"other"}function mt(e){return lt.includes(e)?e:"other"}function pt(e){return(e.split(".")[0]??"").slice(0,20)}function le(e,n=new Date){return{schema:A,installId:te(),sentAt:n.toISOString(),version:J.slice(0,40),channel:e,installForm:ut(),os:mt(process.platform),osRelease:pt(ct.release()),arch:process.arch.slice(0,20),nodeMajor:Number.parseInt(process.versions.node,10),uiLang:G()}}import{appendFileSync as dt,existsSync as ft,mkdirSync as Et,readFileSync as _t,renameSync as ht,rmSync as v,statSync as Tt,writeFileSync as xt}from"node:fs";import St from"node:path";var ue=2*1024*1024,bt=Math.floor(ue*.75);function F(e){return`${e.slice(0,-6)}.sending.jsonl`}function L(e){try{return _t(e,"utf8").split(`
7
- `).filter(n=>n.trim()!=="")}catch{return[]}}function me(e,n){let r=0,s=e.length;for(;s>0&&r+Buffer.byteLength(e[s-1])+1<=n;)s-=1,r+=Buffer.byteLength(e[s])+1;return e.slice(s)}function U(e,n){if(n.length===0)return void v(e,{force:!0});xt(e,`${n.join(`
8
- `)}
9
- `,"utf8")}function yt(e,n){Tt(e).size<=n||U(e,me(L(e),Math.floor(n*.75)))}function pe(e,n=x,r=ue){let s=g.safeParse(e);if(!s.success)return!1;try{return Et(St.dirname(n),{recursive:!0}),dt(n,`${JSON.stringify(s.data)}
10
- `,"utf8"),yt(n,r),!0}catch{return!1}}function de(e=x){let n=F(e);if(ft(e)){let r=`${e}.${process.pid}.tmp`;try{ht(e,r),U(n,me([...L(n),...L(r)],bt)),v(r,{force:!0})}catch{}}return L(n).flatMap(r=>gt(r))}function gt(e){try{let n=g.safeParse(JSON.parse(e));return n.success?[n.data]:[]}catch{return[]}}function fe(e,n=x){try{U(F(n),e.map(r=>JSON.stringify(r)))}catch{}}function Ee(e=x){v(e,{force:!0}),v(F(e),{force:!0})}var _e=$("telemetry"),Rt=1e4,Lt=2048;function he(e){let n=q-Lt,r=[],s=[],i=0;for(let a of e){let p=Buffer.byteLength(JSON.stringify(a))+1;p>n||((s.length>=I||i+p>n)&&(r.push(s),s=[],i=0),s.push(a),i+=p)}return s.length>0&&r.push(s),r}function vt(e,n){return n?"sent":e>=400&&e<500?"rejected":"retry"}async function Te(e,n,r,s=fetch){let i=Z.safeParse({envelope:n,events:r});if(!i.success)return"rejected";try{let a=await s(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(i.data),signal:AbortSignal.timeout(Rt)});a.body?.cancel?.().catch(()=>{});let p=vt(a.status,a.ok);return p!=="sent"&&_e.debug(`telemetry upload ${p}: HTTP ${a.status}`),p}catch(a){return _e.debug(`telemetry upload failed: ${a.message}`),"retry"}}var S=class{now;failures=0;nextAt=0;constructor(n=Date.now){this.now=n}ready(){return this.now()>=this.nextAt}succeeded(){this.failures=0,this.nextAt=0}failed(){this.failures+=1;let n=Math.min(6e4*2**(this.failures-1),360*6e4);this.nextAt=this.now()+n}};var wt=1440*60*1e3,At=600*1e3,It=3e4,Ot=2e3,Y=[],w=new S,l=null,P=null,m=null,xe=0;function Hn(e){Y.push(e)}function E(){return l?.options.now?.()??Date.now()}function H(e){for(let n of Y)try{e(n)?.()}catch{}}function B(){try{Ee()}catch{}H(e=>e.wipe)}function Mt(e,n={}){if(!h())return!1;let r=pe(e);return r&&n.urgent&&Se(Ot),r}function Se(e){let n=E()+e;!l||m&&xe<=n||(m&&clearTimeout(m),xe=n,m=setTimeout(()=>{m=null,be()},e),m.unref?.())}async function kt(e,n){let r=he(n);for(let s=0;s<r.length;s+=1){let i=le(e.channel,new Date(E()));if(await Te(e.endpoint,i,r[s],l?.options.fetchImpl)==="retry")return w.failed(),r.slice(s).flat()}return w.succeeded(),[]}async function Nt(){let e=C();if(!e.active||!e.endpoint||!w.ready())return;let n=de();fe(n.length===0?[]:await kt(e,n))}function be(){return P??=Nt().catch(()=>{}).finally(()=>{P=null}),P}async function jt(){let e=Date.parse(D().lastHeartbeatAt??"")||0;if(!l||E()-e<wt)return;let n=await l.options.collectHeartbeat().catch(()=>null);!n||!Mt(n)||ce(r=>({...r,lastHeartbeatAt:new Date(E()).toISOString()}))}async function Ct(e){for(let n of Y)try{await n.finalize?.(e)}catch{}}async function Bn(){if(!h())return B();H(e=>e.persist),!(!l||E()-l.bootAt<Dt(l.options))&&(await Ct(E()),await jt(),await be())}function Dt(e){if(e.firstDelayMs!==void 0)return e.firstDelayMs;let n=Number.parseInt(process.env.CORTEX_TELEMETRY_FIRST_DELAY_S??"",10);return Number.isFinite(n)&&n>=0?n*1e3:At}function Ft(e){e.includes("telemetryEnabled")&&!h()&&B()}function Xn(e){if(!l){if(l={options:e,bootAt:e.now?.()??Date.now(),unsubscribe:V(Ft)},w=new S(()=>E()),!h())return B();Se(It)}}function $n(){m&&clearTimeout(m),m=null,l?.unsubscribe(),l=null,h()&&H(e=>e.persist)}export{Pt as a,Yt as b,Ht as c,Bt as d,Xt as e,ve as f,Fe as g,Ue as h,Pe as i,$t as j,Kt as k,Vt as l,R as m,Ye as n,Wt as o,Q as p,te as q,nn as r,C as s,h as t,D as u,ce as v,Hn as w,Mt as x,Bn as y,Xn as z,$n as A};
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{c as f,d}from"./chunk-G2V65UBA.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 u(e,t,n,s){let i=y(e);try{let c=h(t);return await new Promise((g,w)=>{let o=!1,l=r=>{o||(o=!0,g(r))},a=r=>{o||(o=!0,w(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{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 u("./src/utils/image-resize-worker.ts",e,t,n)}catch{}try{return await u(i,e,t,n)}catch{return d(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};