@cortex-agent/server 2026.11.17 → 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 (338) hide show
  1. package/README.md +5 -5
  2. package/THIRD_PARTY_NOTICES.txt +860 -294
  3. package/defaults/hooks/quota-stop.mjs +37 -0
  4. package/defaults/prompts/clean-workspace.md +5 -0
  5. package/dist/agent-adapter/claude/remote-mcp-proxy.js +1 -1
  6. package/dist/chunks/agent-runner-LVZVKBZX.js +4 -0
  7. package/dist/chunks/anthropic-messages-TT6454AA.js +8 -0
  8. package/dist/chunks/azure-openai-responses-52LR2XZD.js +4 -0
  9. package/dist/chunks/bedrock-converse-stream-EOZGYUNY.js +60 -0
  10. package/dist/chunks/child-runner-SMG2VOU5.js +4 -0
  11. package/dist/chunks/chunk-24DH4IR5.js +4 -0
  12. package/dist/chunks/chunk-25XKBRDT.js +70 -0
  13. package/dist/chunks/{chunk-VTL3Z2OP.js → chunk-2ABET62E.js} +1 -1
  14. package/dist/chunks/chunk-2BVUA256.js +4 -0
  15. package/dist/chunks/{chunk-4YLAGSDM.js → chunk-2WFL62UO.js} +1 -1
  16. package/dist/chunks/{chunk-LQTFDC67.js → chunk-335SSANX.js} +1 -1
  17. package/dist/chunks/chunk-377OPTXX.js +17 -0
  18. package/dist/chunks/chunk-3EZNVLBF.js +129 -0
  19. package/dist/chunks/{chunk-V6X7Y62J.js → chunk-3O6ZG5HA.js} +1 -1
  20. package/dist/chunks/{chunk-6AKUD3CF.js → chunk-3XLHL5YT.js} +1 -1
  21. package/dist/chunks/{chunk-2ATTYCRJ.js → chunk-4HRI75GU.js} +1 -1
  22. package/dist/chunks/chunk-4JBYLRPM.js +57 -0
  23. package/dist/chunks/chunk-4KKV7VKE.js +4 -0
  24. package/dist/chunks/chunk-4KQHDDC5.js +4 -0
  25. package/dist/chunks/chunk-4SWD4JMP.js +33 -0
  26. package/dist/chunks/chunk-52VCLZS5.js +4 -0
  27. package/dist/chunks/chunk-54P7TSY3.js +10 -0
  28. package/dist/chunks/chunk-5DVSAXOI.js +7 -0
  29. package/dist/chunks/chunk-5F3A62YS.js +4 -0
  30. package/dist/chunks/{chunk-S3MR37DL.js → chunk-5FHETFZM.js} +1 -1
  31. package/dist/chunks/{chunk-CEGSDGYQ.js → chunk-5LBLRAHS.js} +1 -1
  32. package/dist/chunks/chunk-5UYVNA3W.js +4 -0
  33. package/dist/chunks/chunk-6G3OYMCV.js +21 -0
  34. package/dist/chunks/chunk-7GGPYU5E.js +30 -0
  35. package/dist/chunks/chunk-7TYSMLUV.js +4 -0
  36. package/dist/chunks/chunk-7W7VYUTK.js +5 -0
  37. package/dist/chunks/chunk-AXYAZTTN.js +6 -0
  38. package/dist/chunks/chunk-B3NB243Z.js +4 -0
  39. package/dist/chunks/{chunk-XPPZ6Y3X.js → chunk-BKYP6AGM.js} +1 -1
  40. package/dist/chunks/{chunk-QUXPMNFQ.js → chunk-BVEDNESB.js} +1 -1
  41. package/dist/chunks/chunk-BWDJS6A4.js +12 -0
  42. package/dist/chunks/chunk-C6YVF7EI.js +4 -0
  43. package/dist/chunks/chunk-CEJIYYVE.js +15 -0
  44. package/dist/chunks/{chunk-5PAW3DEU.js → chunk-CI2RHH74.js} +4 -4
  45. package/dist/chunks/{chunk-OFEPDNRB.js → chunk-CMSOOLJB.js} +1 -1
  46. package/dist/chunks/chunk-CSVTYYLP.js +4 -0
  47. package/dist/chunks/chunk-DE5EGVKG.js +6 -0
  48. package/dist/chunks/{chunk-E6BYRULL.js → chunk-DK3RPZOQ.js} +1 -1
  49. package/dist/chunks/{chunk-ROVKOIHF.js → chunk-DK4UCK7L.js} +1 -1
  50. package/dist/chunks/chunk-DYLBVUAU.js +4 -0
  51. package/dist/chunks/{chunk-WBSE3EF3.js → chunk-FDC2GRBK.js} +1 -1
  52. package/dist/chunks/chunk-FE7HH5JS.js +18 -0
  53. package/dist/chunks/chunk-FYD57YRO.js +436 -0
  54. package/dist/chunks/chunk-G264APQN.js +5 -0
  55. package/dist/chunks/chunk-G4JYZFEO.js +11 -0
  56. package/dist/chunks/chunk-GFFM56U2.js +4 -0
  57. package/dist/chunks/chunk-GOS3P7KS.js +132 -0
  58. package/dist/chunks/{chunk-2VVRTJQN.js → chunk-HVN37UXD.js} +1 -1
  59. package/dist/chunks/{chunk-53TQNK7Z.js → chunk-IGZWZP7Z.js} +1 -1
  60. package/dist/chunks/{chunk-AFTBQRPN.js → chunk-IJ7XFQMI.js} +1 -1
  61. package/dist/chunks/{chunk-U23S37TT.js → chunk-IMMGYDAB.js} +1 -1
  62. package/dist/chunks/chunk-IOWBF7UK.js +10 -0
  63. package/dist/chunks/{chunk-MGYYSX7Y.js → chunk-ITGCWQFK.js} +1 -1
  64. package/dist/chunks/{chunk-QEL6CMLE.js → chunk-IVZ7QUEG.js} +1 -1
  65. package/dist/chunks/{chunk-EE3WT25T.js → chunk-IWY2HIFK.js} +1 -1
  66. package/dist/chunks/{chunk-KGJZAYQD.js → chunk-J7OBATRN.js} +1 -1
  67. package/dist/chunks/{chunk-NXZS5PEW.js → chunk-JGUEIW2W.js} +1 -1
  68. package/dist/chunks/chunk-JZ7U7RUK.js +351 -0
  69. package/dist/chunks/{chunk-VIMHSW6J.js → chunk-KJUQCCB5.js} +1 -1
  70. package/dist/chunks/{chunk-BUZQBTV2.js → chunk-KST6OY76.js} +1 -1
  71. package/dist/chunks/{chunk-KDPY2YA3.js → chunk-KZSAFVSY.js} +2 -2
  72. package/dist/chunks/chunk-LD2ZSH3M.js +903 -0
  73. package/dist/chunks/{chunk-RYLSRII6.js → chunk-LE6QPXN6.js} +1 -1
  74. package/dist/chunks/{chunk-TX46YMGI.js → chunk-LIIZI3HY.js} +1 -1
  75. package/dist/chunks/{chunk-3CZPBLB3.js → chunk-MJQ2D2OP.js} +1 -1
  76. package/dist/chunks/{chunk-P7TVR4GY.js → chunk-NHHR4DCF.js} +1 -1
  77. package/dist/chunks/chunk-NW4GW47L.js +4 -0
  78. package/dist/chunks/chunk-OALEJ6FG.js +60 -0
  79. package/dist/chunks/chunk-OIV4DIMB.js +4 -0
  80. package/dist/chunks/{chunk-T73GHMFB.js → chunk-OJ37ZWBG.js} +1 -1
  81. package/dist/chunks/{chunk-7GEBDPTT.js → chunk-OZXMPBUX.js} +1 -1
  82. package/dist/chunks/chunk-PG7452XE.js +4 -0
  83. package/dist/chunks/chunk-PJCUB7YJ.js +4 -0
  84. package/dist/chunks/{chunk-RA2BUYI3.js → chunk-PTS3J4DQ.js} +1 -1
  85. package/dist/chunks/{chunk-2ROGTDM2.js → chunk-PVVEEBUU.js} +1 -1
  86. package/dist/chunks/{chunk-W6AKCEYF.js → chunk-Q7BZLPBU.js} +1 -1
  87. package/dist/chunks/{chunk-SY2HV3V5.js → chunk-QC66ZXPP.js} +1 -1
  88. package/dist/chunks/chunk-QXFWIL4C.js +4 -0
  89. package/dist/chunks/{chunk-NRD57ICT.js → chunk-R2CCD4OF.js} +1 -1
  90. package/dist/chunks/{chunk-R52AVUQB.js → chunk-RG5GP4RB.js} +1 -1
  91. package/dist/chunks/{chunk-IKLTEWA3.js → chunk-RW2F2QNP.js} +1 -1
  92. package/dist/chunks/{chunk-XEBEWR6Y.js → chunk-RWPO3NZ3.js} +1 -1
  93. package/dist/chunks/chunk-SDUS2H3E.js +4 -0
  94. package/dist/chunks/chunk-SIHGKM4E.js +4 -0
  95. package/dist/chunks/{chunk-NNBSSISP.js → chunk-SKHFU5DI.js} +1 -1
  96. package/dist/chunks/{chunk-STUHNKQS.js → chunk-SM45TH22.js} +1 -1
  97. package/dist/chunks/chunk-T54CZKNJ.js +6 -0
  98. package/dist/chunks/chunk-TRXLIL7V.js +4 -0
  99. package/dist/chunks/{chunk-KUDK7GPS.js → chunk-UEEW2R4E.js} +1 -1
  100. package/dist/chunks/chunk-UHXPRU6G.js +10 -0
  101. package/dist/chunks/chunk-UPQVWHZ3.js +4 -0
  102. package/dist/chunks/{chunk-BDLKI2NT.js → chunk-VHX2GHBF.js} +1 -1
  103. package/dist/chunks/chunk-VOAKRJ4R.js +4 -0
  104. package/dist/chunks/{chunk-FP7ML72L.js → chunk-WU7RNAZD.js} +1 -1
  105. package/dist/chunks/chunk-WZC4TDDM.js +6 -0
  106. package/dist/chunks/chunk-X2TKJ7KR.js +11 -0
  107. package/dist/chunks/{chunk-H4QZ2P3Z.js → chunk-X5ND4H4P.js} +1 -1
  108. package/dist/chunks/{chunk-5A6CA5TM.js → chunk-Y3AOGNDT.js} +1 -1
  109. package/dist/chunks/chunk-Y6DGVTKM.js +6 -0
  110. package/dist/chunks/{chunk-LP7T32PW.js → chunk-YAEHSSR4.js} +1 -1
  111. package/dist/chunks/chunk-YWPBE5LP.js +4 -0
  112. package/dist/chunks/chunk-ZAVX7G2M.js +15 -0
  113. package/dist/chunks/chunk-ZD2M73XA.js +19 -0
  114. package/dist/chunks/chunk-ZD4O6NPV.js +4 -0
  115. package/dist/chunks/chunk-ZNAMETPQ.js +4 -0
  116. package/dist/chunks/chunk-ZY6N5LVQ.js +4 -0
  117. package/dist/chunks/chunk-ZYQ4TDTT.js +81 -0
  118. package/dist/chunks/cli-VB2N7HEK.js +55 -0
  119. package/dist/chunks/cloudflare-workers-ai-system-one-YKU742EC.js +4 -0
  120. package/dist/chunks/context-CI2FKEQE.js +4 -0
  121. package/dist/chunks/cost-CZRRSIUF.js +5 -0
  122. package/dist/chunks/dist-QCNQN6DY.js +4 -0
  123. package/dist/chunks/{easter-egg-3d-CZH7AYZ7.js → easter-egg-3d-XR5S2O3T.js} +1 -1
  124. package/dist/chunks/execution-repo-5TLV2NM4.js +4 -0
  125. package/dist/chunks/{executions-BN6OLLVM.js → executions-I3UUIGSL.js} +1 -1
  126. package/dist/chunks/file-Y5G56IUT.js +4 -0
  127. package/dist/chunks/github-copilot-BRU2SRRZ.js +4 -0
  128. package/dist/chunks/google-generative-ai-ZF5QEUZV.js +4 -0
  129. package/dist/chunks/google-vertex-4PJZZI3Y.js +4 -0
  130. package/dist/chunks/init-A6GY656J.js +4 -0
  131. package/dist/chunks/{install-cli-ABBD7DO5.js → install-cli-FALWKQYO.js} +1 -1
  132. package/dist/chunks/{interaction-ask-EE2UPR3Q.js → interaction-ask-O5HGF6CH.js} +1 -1
  133. package/dist/chunks/{interaction-plan-C446T2GZ.js → interaction-plan-JTVDN3BC.js} +1 -1
  134. package/dist/chunks/kimi-coding-ZCIBMDZ6.js +4 -0
  135. package/dist/chunks/{llama-cpp-classify-IA2F2H7A.js → llama-cpp-classify-NRUXAIGQ.js} +3 -3
  136. package/dist/chunks/local-client-stop-RS4AHNF4.js +4 -0
  137. package/dist/chunks/memory-cli-DIT4DQF3.js +11 -0
  138. package/dist/chunks/meta-JQH66YU7.js +4 -0
  139. package/dist/chunks/mistral-conversations-CXHOECUV.js +7 -0
  140. package/dist/chunks/model-resolver-GIBPYRKP.js +4 -0
  141. package/dist/chunks/monitor-Z2HKNY5E.js +4 -0
  142. package/dist/chunks/openai-codex-responses-U6DGMGDK.js +12 -0
  143. package/dist/chunks/openai-completions-PP4XLLOM.js +9 -0
  144. package/dist/chunks/{openai-decisions-P5UX7BWY.js → openai-decisions-JU6QQKEM.js} +1 -1
  145. package/dist/chunks/openai-responses-2SG757TL.js +6 -0
  146. package/dist/chunks/openrouter-images-32M7YZWC.js +4 -0
  147. package/dist/chunks/pi-messages-VSINMXN4.js +10 -0
  148. package/dist/chunks/radius-THYKWV4E.js +4 -0
  149. package/dist/chunks/remote-ops-2WBEFQ3E.js +14 -0
  150. package/dist/chunks/runner-5MKMRTIN.js +4 -0
  151. package/dist/chunks/runtime-DST3H5JP.js +4 -0
  152. package/dist/chunks/schedule-cli-V7Y2BBVY.js +4 -0
  153. package/dist/chunks/slack-R7SEJYMY.js +4 -0
  154. package/dist/chunks/start-ui-http-7K5JOLPU.js +43 -0
  155. package/dist/chunks/subagent-Z5IQ4L54.js +4 -0
  156. package/dist/chunks/tool-shims-YCXZWTST.js +4 -0
  157. package/dist/chunks/typesafe-system-one-M2DABJSZ.js +4 -0
  158. package/dist/chunks/ui-board-HQIE4RZG.js +5 -0
  159. package/dist/chunks/ui-decision-YBZDS4YW.js +4 -0
  160. package/dist/chunks/{ui-file-6PLXHSTB.js → ui-file-SRD4ILBS.js} +1 -1
  161. package/dist/chunks/ui-view-Z25MTZT7.js +4 -0
  162. package/dist/chunks/virtual-modules-H4DXPJZB.js +4 -0
  163. package/dist/chunks/{waitpoint-W5M3BE55.js → waitpoint-M6JZBSLT.js} +1 -1
  164. package/dist/chunks/workers-SQ2R32TK.js +4 -0
  165. package/dist/client-bundle/client.mjs +229 -62
  166. package/dist/client-bundle/manifest.json +2 -2
  167. package/dist/core/pi-sdk.js +1 -1
  168. package/dist/domain/auth/cc-auth-cli.js +1 -1
  169. package/dist/domain/mcp/bundled-server.js +1 -1
  170. package/dist/domain/mcp/feishu/client.js +1 -1
  171. package/dist/entry/app.js +138 -556
  172. package/dist/entry/browser-cli.js +1 -1
  173. package/dist/entry/cli.js +1 -1
  174. package/dist/entry/cortex-cli.js +1 -1
  175. package/dist/entry/daemon.js +3 -3
  176. package/dist/entry/hook-cli.js +1 -1
  177. package/dist/entry/production-app-bootstrap.js +1 -1
  178. package/dist/entry/production-evidence-export-cli.js +1 -1
  179. package/dist/entry/signal-cli.js +1 -1
  180. package/dist/tui/index.js +1 -1
  181. package/package.json +1 -1
  182. package/vendor/pi/CHANGELOG.md +330 -0
  183. package/vendor/pi/dist/codemode-worker.js +2 -0
  184. package/vendor/pi/dist/core/export-html/ansi-to-html.js +57 -20
  185. package/vendor/pi/dist/core/export-html/template.css +9 -0
  186. package/vendor/pi/dist/core/export-html/template.js +166 -46
  187. package/vendor/pi/dist/core/export-html/tool-renderer.js +5 -3
  188. package/vendor/pi/dist/core/extensions/loader.js +1 -1
  189. package/vendor/pi/dist/extensions/codemode/execute.js +15 -13
  190. package/vendor/pi/dist/modes/interactive/theme/theme.js +36 -23
  191. package/vendor/pi/dist/utils/image-resize-worker.js +1 -1
  192. package/vendor/pi/dist/utils/image-resize.js +1 -1
  193. package/vendor/pi/docs/cli.md +35 -12
  194. package/vendor/pi/docs/custom-provider.md +2 -0
  195. package/vendor/pi/docs/environment-variables.md +2 -0
  196. package/vendor/pi/docs/extensions.md +3192 -225
  197. package/vendor/pi/docs/keybindings.md +2 -2
  198. package/vendor/pi/docs/llama-cpp.md +27 -19
  199. package/vendor/pi/docs/mcp.md +6 -4
  200. package/vendor/pi/docs/message-types.md +1 -1
  201. package/vendor/pi/docs/models-configuration.md +9 -3
  202. package/vendor/pi/docs/models.md +2 -1
  203. package/vendor/pi/docs/nvidia-rtx-llama-cpp.md +5 -5
  204. package/vendor/pi/docs/packages.md +24 -0
  205. package/vendor/pi/docs/prompt-templates.md +1 -1
  206. package/vendor/pi/docs/providers.md +4 -2
  207. package/vendor/pi/docs/quickstart.md +7 -3
  208. package/vendor/pi/docs/rpc-commands.md +1 -1
  209. package/vendor/pi/docs/rpc.md +4 -2
  210. package/vendor/pi/docs/sessions.md +17 -3
  211. package/vendor/pi/docs/settings.md +6 -5
  212. package/vendor/pi/docs/slash-commands.md +3 -2
  213. package/vendor/pi/docs/terminal-setup.md +3 -1
  214. package/vendor/pi/docs/tmux.md +6 -0
  215. package/vendor/pi/docs/tui.md +4 -0
  216. package/vendor/pi/docs/windows.md +27 -0
  217. package/vendor/pi/examples/extensions/README.md +2 -1
  218. package/vendor/pi/examples/extensions/custom-provider-anthropic/index.ts +27 -31
  219. package/vendor/pi/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  220. package/vendor/pi/examples/extensions/custom-provider-anthropic/package.json +1 -1
  221. package/vendor/pi/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  222. package/vendor/pi/examples/extensions/debug-provider.ts +2 -2
  223. package/vendor/pi/examples/extensions/gondolin/index.ts +4 -7
  224. package/vendor/pi/examples/extensions/gondolin/package-lock.json +19 -29
  225. package/vendor/pi/examples/extensions/gondolin/package.json +2 -2
  226. package/vendor/pi/examples/extensions/plan-mode/index.ts +23 -13
  227. package/vendor/pi/examples/extensions/plan-mode/utils.ts +42 -16
  228. package/vendor/pi/examples/extensions/preset.ts +2 -0
  229. package/vendor/pi/examples/extensions/reload-runtime.ts +17 -5
  230. package/vendor/pi/examples/extensions/subagent/README.md +14 -11
  231. package/vendor/pi/examples/extensions/subagent/index.ts +392 -171
  232. package/vendor/pi/examples/extensions/todo.ts +7 -0
  233. package/vendor/pi/examples/extensions/tools.ts +2 -0
  234. package/vendor/pi/examples/extensions/with-deps/package-lock.json +2 -2
  235. package/vendor/pi/examples/extensions/with-deps/package.json +1 -1
  236. package/vendor/pi/examples/tsconfig.json +208 -0
  237. package/vendor/pi/package.json +15 -16
  238. package/vendor/pi/schemas/models.schema.json +66 -37
  239. package/vendor/pi/schemas/settings.schema.json +18 -1
  240. package/vendor/pi-ai/bedrock.js +1 -1
  241. package/vendor/pi-ai/oauth-load.js +1 -1
  242. package/web/dist/assets/{board-math-css-BgIyUG-C.js → board-math-css-DKX6FcUS.js} +1 -1
  243. package/web/dist/assets/index-D11wi0uG.js +540 -0
  244. package/web/dist/assets/index-JedYumhY.css +1 -0
  245. package/web/dist/assets/{index-C2eMpcuI.js → index-jl30Gy8P.js} +1 -1
  246. package/web/dist/index.html +2 -2
  247. package/dist/chunks/anthropic-messages-M732OMEE.js +0 -8
  248. package/dist/chunks/azure-openai-responses-RAKTV6JY.js +0 -4
  249. package/dist/chunks/bedrock-converse-stream-WNUGNZ27.js +0 -62
  250. package/dist/chunks/child-runner-MO5RT6FH.js +0 -4
  251. package/dist/chunks/chunk-3CPIMAYX.js +0 -30
  252. package/dist/chunks/chunk-3ORG56I5.js +0 -8
  253. package/dist/chunks/chunk-4EX2JJWB.js +0 -4
  254. package/dist/chunks/chunk-5DF5WJNM.js +0 -60
  255. package/dist/chunks/chunk-7GAYFN52.js +0 -18
  256. package/dist/chunks/chunk-AVXDF7AG.js +0 -4
  257. package/dist/chunks/chunk-BJGYGEZO.js +0 -6
  258. package/dist/chunks/chunk-BZDIAI5M.js +0 -125
  259. package/dist/chunks/chunk-CK3P345X.js +0 -133
  260. package/dist/chunks/chunk-CVC66CFV.js +0 -33
  261. package/dist/chunks/chunk-ETIBCA2S.js +0 -4
  262. package/dist/chunks/chunk-FF7UELTU.js +0 -4
  263. package/dist/chunks/chunk-FX6MOGLR.js +0 -11
  264. package/dist/chunks/chunk-G2V65UBA.js +0 -4
  265. package/dist/chunks/chunk-HGPBHTVD.js +0 -6
  266. package/dist/chunks/chunk-IYVZHGUQ.js +0 -5
  267. package/dist/chunks/chunk-JJDEQ6N2.js +0 -4
  268. package/dist/chunks/chunk-KDYEGGMW.js +0 -4
  269. package/dist/chunks/chunk-L6VCIGWS.js +0 -11
  270. package/dist/chunks/chunk-LACGULCN.js +0 -10
  271. package/dist/chunks/chunk-LAWOWPZX.js +0 -363
  272. package/dist/chunks/chunk-NNTQUHLO.js +0 -877
  273. package/dist/chunks/chunk-OE4KH3NJ.js +0 -4
  274. package/dist/chunks/chunk-OSEIQ7SS.js +0 -4
  275. package/dist/chunks/chunk-PZMGBKUR.js +0 -13
  276. package/dist/chunks/chunk-QBKCAIJG.js +0 -4
  277. package/dist/chunks/chunk-QMSSIDRQ.js +0 -70
  278. package/dist/chunks/chunk-QUUEQRIT.js +0 -4
  279. package/dist/chunks/chunk-RA6HKFBV.js +0 -4
  280. package/dist/chunks/chunk-RDW6FRF5.js +0 -4
  281. package/dist/chunks/chunk-RF4JLYBX.js +0 -6
  282. package/dist/chunks/chunk-SFX7V5O2.js +0 -10
  283. package/dist/chunks/chunk-SKHLZ6XY.js +0 -9
  284. package/dist/chunks/chunk-STCNHXPJ.js +0 -6
  285. package/dist/chunks/chunk-UT6DGZDO.js +0 -4
  286. package/dist/chunks/chunk-VBN2JSER.js +0 -5
  287. package/dist/chunks/chunk-VK5J556O.js +0 -4
  288. package/dist/chunks/chunk-VPVSKJGX.js +0 -6
  289. package/dist/chunks/chunk-VQUPKMDR.js +0 -4
  290. package/dist/chunks/chunk-WEZWKMYU.js +0 -4
  291. package/dist/chunks/chunk-XYSXL3KX.js +0 -4
  292. package/dist/chunks/chunk-Y3GFB5XM.js +0 -8
  293. package/dist/chunks/chunk-YAAKL3QS.js +0 -80
  294. package/dist/chunks/chunk-YB5LUJHS.js +0 -65
  295. package/dist/chunks/chunk-YKKEI5GI.js +0 -4
  296. package/dist/chunks/chunk-Z24SBRJK.js +0 -4
  297. package/dist/chunks/cli-5DBTRMHU.js +0 -53
  298. package/dist/chunks/cloudflare-workers-ai-system-one-32JCFHI3.js +0 -4
  299. package/dist/chunks/context-GQKWKFRM.js +0 -4
  300. package/dist/chunks/cost-OOO32GLC.js +0 -5
  301. package/dist/chunks/dist-V5FRMUFH.js +0 -4
  302. package/dist/chunks/execution-repo-XXL4FXC6.js +0 -4
  303. package/dist/chunks/file-H572PL2Z.js +0 -4
  304. package/dist/chunks/github-copilot-HAI2DA62.js +0 -4
  305. package/dist/chunks/google-generative-ai-2G4ITOZL.js +0 -4
  306. package/dist/chunks/google-vertex-PACHCMRZ.js +0 -4
  307. package/dist/chunks/init-75F4V7SK.js +0 -4
  308. package/dist/chunks/kimi-coding-HMJRKCPA.js +0 -4
  309. package/dist/chunks/local-client-stop-5YOLXGYT.js +0 -4
  310. package/dist/chunks/memory-cli-5SSF6YJM.js +0 -11
  311. package/dist/chunks/meta-KY3LNFV2.js +0 -4
  312. package/dist/chunks/mistral-conversations-VHP63CDS.js +0 -7
  313. package/dist/chunks/model-resolver-FVJNZ6NA.js +0 -4
  314. package/dist/chunks/openai-codex-responses-EHJ4AZBE.js +0 -12
  315. package/dist/chunks/openai-completions-CRAGQFCE.js +0 -9
  316. package/dist/chunks/openai-responses-IZ22NVQ7.js +0 -6
  317. package/dist/chunks/openrouter-images-W2JAMSRH.js +0 -4
  318. package/dist/chunks/pi-messages-MJEEQU2R.js +0 -10
  319. package/dist/chunks/radius-ZM7ZRMXF.js +0 -4
  320. package/dist/chunks/remote-ops-O5CR4RGA.js +0 -14
  321. package/dist/chunks/runner-S6R3US24.js +0 -4
  322. package/dist/chunks/runtime-6YLTA2ZD.js +0 -4
  323. package/dist/chunks/schedule-cli-4T4YC5V5.js +0 -4
  324. package/dist/chunks/slack-2CGM4SMY.js +0 -4
  325. package/dist/chunks/start-ui-http-3D7QNHGB.js +0 -43
  326. package/dist/chunks/subagent-OZGUOV3J.js +0 -4
  327. package/dist/chunks/tool-shims-IA2WELXJ.js +0 -4
  328. package/dist/chunks/typesafe-system-one-6ULACYD4.js +0 -4
  329. package/dist/chunks/ui-board-H4INJD6C.js +0 -5
  330. package/dist/chunks/ui-decision-6HHNROIT.js +0 -4
  331. package/dist/chunks/ui-view-6MDU4GXY.js +0 -4
  332. package/dist/chunks/virtual-modules-OFI7QKYH.js +0 -4
  333. package/dist/chunks/workers-GTFP75MS.js +0 -4
  334. package/vendor/pi/examples/extensions/sandbox/index.ts +0 -321
  335. package/vendor/pi/examples/extensions/sandbox/package-lock.json +0 -92
  336. package/vendor/pi/examples/extensions/sandbox/package.json +0 -19
  337. package/web/dist/assets/index-9lyu2S6W.css +0 -1
  338. package/web/dist/assets/index-C-hpzey7.js +0 -532
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as d}from"./chunk-OKRK6JPY.js";var h="Model override: pi provider/model[:thinking], claude model ID. Default: role model, then parent model.",A="Backend override. Default: role backend, then parent backend.",D="Delegate isolated, one-shot work; children cannot delegate. Give self-contained prompts. Choose one mode: single, parallel, or chain. Supports both backends. Set clean for work that must not be shaped by Cortex context: the child runs in a fresh workspace with its brief and the files you list in files, copied to inputs/. Its brief must stand alone, name those files as inputs/<name>, and include external paths only when the user explicitly authorizes access, stating the allowed operations. Its result ends with the workspace path, where it leaves its output.",G="Run in a fresh workspace without Cortex context. Implied by files.",P="Files or directories (absolute or ~ paths) copied into the workspace inputs/. Implies clean.",g=["description","prompt","subagent_type"];function T(e,n){if(e!=null){if(e==="claude"||e==="pi")return e;throw new Error(`${n} backend must be "claude" or "pi".`)}}function S(e){for(let n of g)if(typeof e[n]!="string"||e[n].trim()==="")throw new Error(`Agent task requires a non-empty ${n}.`);T(e.backend,"Agent task"),y(e)}function y(e){if(e.clean!==void 0&&typeof e.clean!="boolean")throw new Error("Agent task clean must be a boolean.");let n=e.files;if(n!==void 0&&(!Array.isArray(n)||n.some(o=>typeof o!="string"||o.trim()==="")))throw new Error("Agent task files must be a list of non-empty paths.")}function f(e,n){if(n.length===0)throw new Error(`${e} requires at least one task.`);if(n.length>8)throw new Error(`Agent ${e} task maximum is 8.`);for(let o of n)S(o);return{mode:e,tasks:n}}function v(e){let n=e??{},o=g.some(s=>s in n),t=Array.isArray(n.parallel),r=Array.isArray(n.chain);if(Number(o)+Number(t)+Number(r)!==1)throw new Error("Provide exactly one Agent mode: single fields, parallel, or chain.");if(t)return f("parallel",n.parallel);if(r)return f("chain",n.chain);let i=n;return S(i),{mode:"single",tasks:[i]}}var N=24,u=480;function j(e){let n=e.subagentClaudeModels;return[...n?E(n.map(t=>({backend:"claude",id:t.id})),e.claudeModel):I(e.claudeModel),...e.subagentPiModels??[]]}var x={model:h,backend:A},k="Role name, such as explore, general-purpose, or plan.",C="Role name for single mode, such as explore, general-purpose, or plan.";function X(e){let n=(e.roles??[]).map(r=>({name:r.name.trim(),summary:r.summary.trim()})).filter(r=>r.name!=="").sort((r,i)=>r.name.localeCompare(i.name)),o=e.models??[],t=n.length>0?` Available here: ${U(n)}.`:"";return{subagentType:n.length>0?`Role name.${t}`:k,subagentTypeSingle:n.length>0?`Role name for single mode.${t}`:C,...x,catalog:$(o)}}function H(e){let n=[];for(let o of e){let t=o.name.trim();t&&n.push({name:t,summary:O(o.description)})}return n}function I(e,n=d){let o=n.length>0?n:d;return E(o.map(t=>({backend:"claude",id:t})),e)}function E(e,n){let o=n?.trim();return!o||e.some(t=>t.id===o)?e:[...e,{backend:"claude",id:o}]}function Y(e){let n=[];for(let o of e){let t=o.id.trim();if(!t)continue;let r=o.provider.trim();n.push(r?{backend:"pi",provider:r,id:t}:{backend:"pi",id:t})}return n}function q(e){return JSON.stringify(e)}function z(e){return e?M(e):null}function M(e){if(!e)return[];let n;try{n=JSON.parse(e)}catch{return[]}if(!Array.isArray(n))return[];let o=n,t=[];for(let r of o){if(!w(r))continue;let{backend:i,provider:s,id:c}=r;if(i!=="claude"&&i!=="pi"||typeof c!="string"||!c.trim())continue;let l={backend:i,id:c.trim()};typeof s=="string"&&s.trim()&&(l.provider=s.trim()),t.push(l)}return t}function w(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function O(e){let n=e.trim(),o=n.indexOf(". "),t=o>=0?n.slice(0,o):n;return t.endsWith(".")&&(t=t.slice(0,-1)),t.length>80&&(t=`${t.slice(0,80)}\u2026`),t}function R(e){let n=e.id.trim();if(!n)return null;if(e.backend==="claude")return n;let o=e.provider?.trim()??"";return o?`${o}/${n}`:n}function B(e){let n=new Set,o=[];for(let t of e){let r=R(t);if(!r)continue;let i=`${t.backend}:${r}`;n.has(i)||(n.add(i),o.push({backend:t.backend,name:r}))}return o.sort((t,r)=>t.backend===r.backend?t.name.localeCompare(r.name):t.backend==="claude"?-1:1),o}var b=" Known models \u2014 ";function $(e){let n=B(e),o=["claude","pi"].flatMap(t=>{let r=n.filter(i=>i.backend===t).map(i=>i.name);return r.length?[`${t}: ${r.join(", ")}`]:[]});return o.length?`${b}${o.join("; ")}.`:""}function J(e){return e.split(b)[0]}function U(e){let n=e.slice(0,N),o=e.length-n.length,t=o>0?` (+${o} more)`:"",r=n.map(a=>a.summary?`${a.name} \u2014 ${a.summary}`:a.name).join("; ");if(r.length+t.length<=u)return r+t;let i=n.map(a=>a.name).join(", ");if(i.length+t.length<=u)return i+t;let s=[],c=0;for(let a of n){let p=a.name.length+(s.length>0?2:0),m=e.length-(s.length+1),_=m>0?` (+${m} more)`.length:0;if(c+p+_>u)break;s.push(a.name),c+=p}let l=e.length-s.length;return s.join(", ")+(l>0?` (+${l} more)`:"")}export{D as a,G as b,P as c,v as d,j as e,X as f,H as g,Y as h,q as i,z as j,M as k,$ as l,J as m};
@@ -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
- function y(t){if(!(t instanceof Error))return{message:u(t),messageCarriesBody:!1};let e=t,n=d(e),s=o(e),r=s===void 0||t.message.includes(s);return{status:n,body:s,message:t.message,messageCarriesBody:r}}function d(t){if(typeof t.statusCode=="number")return t.statusCode;if(typeof t.status=="number")return t.status;if(typeof t.$metadata?.httpStatusCode=="number")return t.$metadata.httpStatusCode;if(typeof t.$response?.statusCode=="number")return t.$response.statusCode}function o(t){let e=f(t);if(e===void 0)return;let n=e.trim();if(n.length!==0)return c(n,4e3)}function f(t){if(typeof t.body=="string")return t.body;if(i(t.error))return u(t.error);let e=t.$response?.body;if(typeof e=="string")return e;if(!a(e)&&i(e))return u(e)}function a(t){return typeof t=="object"&&t!==null&&"pipe"in t&&typeof t.pipe=="function"}function i(t){if(typeof t!="object"||t===null)return!1;let e=Object.getPrototypeOf(t);return e!==Object.prototype&&e!==null?!1:Object.keys(t).length>0}function p(t,e){return t.messageCarriesBody||t.status===void 0||t.body===void 0?e!==void 0&&t.status!==void 0?`${e} (${t.status}): ${t.message}`:t.message:e!==void 0?`${e} (${t.status}): ${t.body}`:`${t.status}: ${t.body}`}function c(t,e){return t.length<=e?t:`${t.slice(0,e)}... [truncated ${t.length-e} chars]`}function u(t){try{let e=JSON.stringify(t);return e===void 0?String(t):e}catch{return String(t)}}export{y as a,p as b};
@@ -1,11 +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{Q as p}from"./chunk-QUUEQRIT.js";import{accessSync as w,constants as m}from"node:fs";import{delimiter as u,join as x,win32 as c}from"node:path";import{spawn as y,spawnSync as d}from"child_process";function g(e){let o=c.normalize(e).toLowerCase(),t=process.env.SystemRoot;return t?/^[a-z]:[\\/]/i.test(t)?["System32","Sysnative"].some(n=>o===c.join(t,n,"bash.exe").toLowerCase()):!1:/^[a-z]:\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(o)}function i(e){return g(e)?{shell:e,args:["-s"],commandTransport:"stdin"}:{shell:e,args:["-c"]}}function r(e){try{return w(e,m.F_OK),!0}catch{return!1}}function l(e){if(process.platform==="win32"){try{let o=d("where",[e],{encoding:"utf-8",timeout:5e3,windowsHide:!0});if(o.status===0&&o.stdout){let t=o.stdout.trim().split(/\r?\n/)[0];if(t&&r(t))return t}}catch{}return null}try{let o=d("which",[e],{encoding:"utf-8",timeout:5e3});if(o.status===0&&o.stdout){let t=o.stdout.trim().split(/\r?\n/)[0];if(t)return t}}catch{}return null}function E(e){if(e){if(r(e))return i(e);throw new Error(`Custom shell path not found: ${e}`)}if(process.platform==="win32"){let t=[],n=process.env.ProgramFiles;n&&t.push(`${n}\\Git\\bin\\bash.exe`);let f=process.env["ProgramFiles(x86)"];f&&t.push(`${f}\\Git\\bin\\bash.exe`);for(let s of t)if(r(s))return i(s);let a=l("bash.exe");if(a)return i(a);throw new Error(`No bash shell found. Options:
5
- 1. Install Git for Windows: https://git-scm.com/download/win
6
- 2. Add your bash to PATH (Cygwin, MSYS2, etc.)
7
- 3. Set shellPath in settings.json
8
-
9
- Searched Git Bash in:
10
- ${t.map(s=>` ${s}`).join(`
11
- `)}`)}if(r("/bin/bash"))return i("/bin/bash");let o=l("bash");return o?i(o):{shell:"sh",args:["-c"]}}var P=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command"];function B(){if(process.platform!=="win32")throw new Error("The powershell tool is only available on Windows.");let e=l("pwsh.exe"),o=process.env.ProgramFiles;if(!e&&o){let n=c.join(o,"PowerShell","7","pwsh.exe");r(n)&&(e=n)}e??=l("powershell.exe");let t=process.env.SystemRoot;if(!e&&t){let n=c.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe");r(n)&&(e=n)}if(!e)throw new Error("No PowerShell executable found. Install PowerShell or add powershell.exe/pwsh.exe to PATH.");return{shell:e,args:[...P]}}function k(){let e=p(),o=Object.keys(process.env).find(s=>s.toLowerCase()==="path")??"PATH",t=process.env[o]??"",a=t.split(u).filter(Boolean).includes(e)?t:[e,t].filter(Boolean).join(u);return{...process.env,[o]:a}}function L(e){return e.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\uFFF9-\uFFFB]/g,"")}var h=new Set;function D(e){h.add(e)}function j(e){h.delete(e)}function I(){for(let e of h)S(e);h.clear()}function S(e){if(process.platform==="win32")try{y(x(process.env.SystemRoot||"C:\\Windows","System32","taskkill.exe"),["/F","/T","/PID",String(e)],{stdio:"ignore",detached:!0,windowsHide:!0}).once("error",()=>{})}catch{}else try{process.kill(-e,"SIGKILL")}catch{try{process.kill(e,"SIGKILL")}catch{}}}export{E as a,B as b,k as c,L as d,D as e,j as f,I as g,S as h};
@@ -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
- function k(t,n){if(n+8>t.length)return 1;let e=(t[n]<<8|t[n+1])===18761,r=i=>e?t[i]|t[i+1]<<8:t[i]<<8|t[i+1],o=(i=>e?t[i]|t[i+1]<<8|t[i+2]<<16|t[i+3]<<24:(t[i]<<24|t[i+1]<<16|t[i+2]<<8|t[i+3])>>>0)(n+4),c=n+o;if(c+2>t.length)return 1;let f=r(c);for(let i=0;i<f;i++){let l=c+2+i*12;if(l+12>t.length)return 1;if(r(l)===274){let h=r(l+8);return h>=1&&h<=8?h:1}}return 1}function L(t){let n=2;for(;n<t.length-1;){if(t[n]!==255)return-1;let u=t[n+1];if(u===255){n++;continue}if(u===225){if(n+4>=t.length)return-1;let r=n+4;if(r+6>t.length)return-1;if(W(t,r))return r+6}if(n+4>t.length)return-1;let e=t[n+2]<<8|t[n+3];n+=2+e}return-1}function v(t){let n=12;for(;n+8<=t.length;){let u=String.fromCharCode(t[n],t[n+1],t[n+2],t[n+3]),e=t[n+4]|t[n+5]<<8|t[n+6]<<16|t[n+7]<<24,r=n+8;if(u==="EXIF")return r+e>t.length?-1:e>=6&&W(t,r)?r+6:r;n=r+e+e%2}return-1}function W(t,n){return t[n]===69&&t[n+1]===120&&t[n+2]===105&&t[n+3]===102&&t[n+4]===0&&t[n+5]===0}function A(t){let n=-1;return t.length>=2&&t[0]===255&&t[1]===216?n=L(t):t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80&&(n=v(t)),n===-1?1:k(t,n)}function P(t,n,u){let e=n.get_width(),r=n.get_height(),a=n.get_raw_pixels(),o=new Uint8Array(a.length);for(let c=0;c<r;c++)for(let f=0;f<e;f++){let i=(c*e+f)*4,l=u(f,c,e,r)*4;o[l]=a[i],o[l+1]=a[i+1],o[l+2]=a[i+2],o[l+3]=a[i+3]}return new t.PhotonImage(o,r,e)}function I(t,n,u){let e=A(u);if(e===1)return n;switch(e){case 2:return t.fliph(n),n;case 3:return t.fliph(n),t.flipv(n),n;case 4:return t.flipv(n),n;case 5:{let r=P(t,n,(a,o,c,f)=>a*f+(f-1-o));return t.fliph(r),r}case 6:return P(t,n,(r,a,o,c)=>r*c+(c-1-a));case 7:{let r=P(t,n,(a,o,c,f)=>(c-1-a)*f+o);return t.fliph(r),r}case 8:return P(t,n,(r,a,o,c)=>(o-1-r)*c+a);default:return n}}import{createRequire as N}from"module";import*as w from"path";import{fileURLToPath as U}from"url";var B=N(new URL("vendor/pi/dist/utils/photon.js",__cortexPackageRoot).href),m=B("fs"),O="photon_rs_bg.wasm",p=null,E=null;function q(t){return typeof t=="string"?t:t instanceof URL?U(t):null}function C(){let t=w.dirname(process.execPath);return[w.join(t,O),w.join(t,"photon",O),w.join(process.cwd(),O)]}function D(){let t=m.readFileSync.bind(m),n=C(),u=m,e=((...r)=>{let[a,o]=r;if(q(a)?.endsWith(O))try{return t(...r)}catch(f){let i=f;if(i?.code&&i.code!=="ENOENT")throw f;for(let l of n)if(m.existsSync(l))return o===void 0?t(l):t(l,o);throw f}return t(...r)});try{u.readFileSync=e}catch{Object.defineProperty(m,"readFileSync",{value:e,writable:!0,configurable:!0})}return()=>{try{u.readFileSync=t}catch{Object.defineProperty(m,"readFileSync",{value:t,writable:!0,configurable:!0})}}}async function M(){return p||E||(E=(async()=>{let t=D();try{return p=await import("@silvia-odwyer/photon-node"),p}catch{return p=null,p}finally{t()}})(),E)}var V="pi:image-resize-response",Q=4.5*1024*1024,X={maxWidth:2e3,maxHeight:2e3,maxBytes:Q,jpegQuality:80};function T(t,n){let u=Buffer.from(t).toString("base64");return{data:u,encodedSize:Buffer.byteLength(u,"utf-8"),mimeType:n}}async function y(t,n,u){let e={...X,...u},r=Math.ceil(t.byteLength/3)*4,a=await M();if(!a)return null;let o;try{let z=function(F,S,_){let x=a.resize(o,F,S,a.SamplingFilter.Lanczos3);try{let R=[T(x.get_bytes(),"image/png")];for(let H of _)R.push(T(x.get_bytes_jpeg(H),"image/jpeg"));return R}finally{x.free()}},c=a.PhotonImage.new_from_byteslice(t);o=I(a,c,t),o!==c&&c.free();let f=o.get_width(),i=o.get_height(),l=n.split("/")[1]??"png";if(f<=e.maxWidth&&i<=e.maxHeight&&r<e.maxBytes)return{data:Buffer.from(t).toString("base64"),mimeType:n||`image/${l}`,originalWidth:f,originalHeight:i,width:f,height:i,wasResized:!1};let h=f,g=i;h>e.maxWidth&&(g=Math.round(g*e.maxWidth/h),h=e.maxWidth),g>e.maxHeight&&(h=Math.round(h*e.maxHeight/g),g=e.maxHeight);let j=Array.from(new Set([e.jpegQuality,85,70,55,40])),d=h,s=g;for(;;){let F=z(d,s,j);for(let x of F)if(x.encodedSize<e.maxBytes)return{data:x.data,mimeType:x.mimeType,originalWidth:f,originalHeight:i,width:d,height:s,wasResized:!0};if(d===1&&s===1)break;let S=d===1?1:Math.max(1,Math.floor(d*.75)),_=s===1?1:Math.max(1,Math.floor(s*.75));if(S===d&&_===s)break;d=S,s=_}return null}catch{return null}finally{o&&o.free()}}export{I as a,M as b,V as c,y as d};
@@ -1,6 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as _}from"./chunk-EQIMHXC4.js";import{f as g,h as b}from"./chunk-RA6HKFBV.js";import{G as h,d as S,h as a,m as p}from"./chunk-QUUEQRIT.js";import{e as I}from"./chunk-WHC7AYZD.js";var k=I(_(),1);import{existsSync as E,mkdirSync as O,readFileSync as A,writeFileSync as J}from"node:fs";import{homedir as G}from"node:os";import{dirname as y,join as m}from"node:path";var q=["settings.json","mcp.json","extensions","skills","prompts","themes","SYSTEM.md","APPEND_SYSTEM.md"];function v(e){return S(a(e))}function B(e,t){let r=v(t);for(;;){let n=e[r];if(n===!0||n===!1)return{path:r,decision:n};let o=y(r);if(o===r)return null;r=o}}function L(e){let t=v(e),r=y(t);return r===t?void 0:r}function te(e,t){let r=v(e),n=[{label:"Trust",trusted:!0,updates:[{path:r,decision:!0}],savedPath:r}],o=L(e);return o!==void 0&&n.push({label:`Trust parent folder (${o})`,trusted:!0,updates:[{path:o,decision:!0},{path:r,decision:null}],savedPath:o}),t?.includeSessionOnly&&n.push({label:"Trust (this session only)",trusted:!0,updates:[]}),n.push({label:"Do not trust",trusted:!1,updates:[{path:r,decision:!1}],savedPath:r}),t?.includeSessionOnly&&n.push({label:"Do not trust (this session only)",trusted:!1,updates:[]}),n}function j(e){if(!E(e))return{};let t;try{t=JSON.parse(p(A(e,"utf-8")))}catch(n){let o=n instanceof Error?n.message:String(n);throw new Error(`Failed to read trust store ${e}: ${o}`)}if(typeof t!="object"||t===null||Array.isArray(t))throw new Error(`Invalid trust store ${e}: expected an object`);let r={};for(let[n,o]of Object.entries(t)){if(o!==!0&&o!==!1&&o!==null)throw new Error(`Invalid trust store ${e}: value for ${JSON.stringify(n)} must be true, false, or null`);r[n]=o}return r}function U(e,t){let r={};for(let n of Object.keys(t).sort()){let o=t[n];(o===!0||o===!1||o===null)&&(r[n]=o)}O(y(e),{recursive:!0}),J(e,`${JSON.stringify(r,null,2)}
5
- `,"utf-8")}function Y(e){let t=y(e);O(t,{recursive:!0});let r=10,n=20,o;for(let i=1;i<=r;i++)try{return k.default.lockSync(t,{realpath:!1,lockfilePath:`${e}.lock`})}catch(s){if((typeof s=="object"&&s!==null&&"code"in s?String(s.code):void 0)!=="ELOCKED"||i===r)throw s;o=s;let c=Date.now();for(;Date.now()-c<n;);}throw o instanceof Error?o:new Error("Failed to acquire trust store lock")}function P(e,t){let r=Y(e);try{return t()}finally{r()}}function ne(e){let t=S(a(process.env.HOME||G())),r=m(t,".agents","skills"),n=S(a(e)),o=m(n,h);if(q.some(i=>E(m(o,i))))return!0;for(;;){let i=m(n,".agents","skills");if(i!==r&&E(i))return!0;let s=y(n);if(s===n)return!1;n=s}}var C=class{trustPath;constructor(t){this.trustPath=m(a(t),"trust.json")}get(t){return this.getEntry(t)?.decision??null}getEntry(t){return P(this.trustPath,()=>{let r=j(this.trustPath);return B(r,t)})}set(t,r){this.setMany([{path:t,decision:r}])}setMany(t){P(this.trustPath,()=>{let r=j(this.trustPath);for(let{path:n,decision:o}of t){let i=v(n);o===null?delete r[i]:r[i]=o}U(this.trustPath,r)})}};import{spawn as z}from"node:child_process";function ie(e){let[t,r]=process.platform==="darwin"?["open",[e]]:process.platform==="win32"?["rundll32",["url.dll,FileProtocolHandler",e]]:["xdg-open",[e]];z(t,r,{stdio:"ignore",detached:!0}).on("error",()=>{}).unref()}import{existsSync as w,mkdirSync as H,readFileSync as N,writeFileSync as K}from"node:fs";import{dirname as Q,join as D}from"node:path";var M=["enabled","exposure","toolExposure"];function F(e){return e.command===void 0&&e.url===void 0&&e.type===void 0}function l(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function T(e,t,r){let{servers:n,errors:o}=r;if(!w(e))return;let i;try{i=JSON.parse(p(N(e,"utf8")))}catch(s){o.push(`${e}: ${s instanceof Error?s.message:String(s)}`);return}if(!l(i)||i.mcpServers!==void 0&&!l(i.mcpServers)){o.push(`${e}: expected an object with an "mcpServers" object`);return}typeof i.autoEnableCodemode=="boolean"?r.autoEnableCodemode=i.autoEnableCodemode:i.autoEnableCodemode!==void 0&&o.push(`${e}: autoEnableCodemode must be a boolean`);for(let[s,u]of Object.entries(i.mcpServers??{})){if(t==="project"&&l(u)&&F(u)){let d=n.get(s),R=Object.keys(u).filter(f=>!M.includes(f));if(!d)o.push(`${e}: server "${s}" needs "command" or "url", or a global server to override`);else if(R.length>0)o.push(`${e}: server "${s}": an override can only set ${M.join(", ")}`);else{let f=b(s,{...d.config,...u});typeof f=="string"?o.push(`${e}: ${f}`):n.set(s,{...d,config:f,override:e})}continue}let c=b(s,u);if(typeof c=="string"){o.push(`${e}: ${c}`);continue}let x=[...n.keys()].find(d=>d!==s&&g(d)===g(s));if(x){o.push(`${e}: server "${s}" conflicts with "${x}"`);continue}if(t==="project"&&"url"in c&&c.auth){o.push(`${e}: server "${s}": auth is only allowed in the global mcp.json`);continue}n.set(s,{name:s,config:c,source:e,scope:t})}}function me(e){let t={servers:new Map,errors:[]};T(D(e.agentDir,"mcp.json"),"global",t);let r=e.projectTrusted?D(e.cwd,h,"mcp.json"):void 0;return r&&T(r,"project",t),{servers:[...t.servers.values()],...t.autoEnableCodemode===void 0?{}:{autoEnableCodemode:t.autoEnableCodemode},errors:t.errors,...r?{projectConfig:r}:{}}}function ye(e,t,r,n={}){$(e,(o,i)=>{let s=o?.[t];if(s===void 0&&n.override&&(s={},i.mcpServers={...o,[t]:s}),!l(s))throw new Error(`${e} does not define MCP server "${t}"`);let u=F(s);return r.enabled!==void 0&&(r.enabled&&!u?delete s.enabled:s.enabled=r.enabled),r.exposure!==void 0&&(r.exposure==="codemode"&&!u?delete s.exposure:s.exposure=r.exposure),!0})}function Se(e,t,r){let n=!1;return $(e,(o,i)=>{let s=o??{};return n=s[t]!==void 0,s[t]=r,i.mcpServers=s,!0}),n}function he(e,t){if(!w(e))return!1;let r=!1;return $(e,n=>!n||n[t]===void 0?!1:(delete n[t],r=!0,!0)),r}function $(e,t){let r=w(e)?p(N(e,"utf8")):void 0,n=r===void 0?{}:JSON.parse(r);if(!l(n)||n.mcpServers!==void 0&&!l(n.mcpServers))throw new Error(`${e}: expected an object with an "mcpServers" object`);let o=l(n.mcpServers)?n.mcpServers:void 0;if(!t(o,n))return;let i=r&&/^([ \t]+)\S/m.exec(r)?.[1]||" ";H(Q(e),{recursive:!0}),K(e,`${JSON.stringify(n,null,i)}
6
- `)}export{te as a,ne as b,C as c,ie as d,me as e,ye as f,Se as g,he as h};
@@ -1,5 +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 B,c as v}from"./chunk-Y6ZEVVL5.js";import{d as V}from"./chunk-U23S37TT.js";import{f as G}from"./chunk-T73GHMFB.js";import{a as _,b as $,e as H}from"./chunk-NNBSSISP.js";import{a as A}from"./chunk-OE4KH3NJ.js";import{a as K}from"./chunk-VK5J556O.js";import{e as j}from"./chunk-STCNHXPJ.js";import{e as F}from"./chunk-VBN2JSER.js";import{b as L,u as X,x as W}from"./chunk-Z24SBRJK.js";function S(){return{input:0,output:0,cacheRead:0,cacheWrite:0,cost:0,contextTokens:0,turns:0}}function g(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function z(t,e){t.input+=e.input,t.output+=e.output,t.cacheRead+=e.cacheRead,t.cacheWrite+=e.cacheWrite,t.cost+=e.cost,t.contextTokens=e.contextTokens||t.contextTokens,t.turns+=e.turns}function mt(t,e){t.input+=e.input,t.output+=e.output,t.cacheRead+=e.cacheRead,t.cacheWrite+=e.cacheWrite,t.cost+=e.cost,t.contextTokens+=e.contextTokens,t.turns+=e.turns}function ge(t){let e=S();for(let n of t)mt(e,n.usage);return e}import*as Y from"node:path";function gt(t,e,n){return t.hasTrustRequiringProjectResources(e)?new t.ProjectTrustStore(n).get(e)===!0:!0}function _t(t,e,n){return n===null||!e||e<=n?t:e-n+Math.min(t,Math.floor(n/2))}function yt(t){let e=t.getCompactionReserveTokens.bind(t);t.getCompactionReserveTokens=n=>_t(e(n),n?.contextWindow,j().maxContextTokens)}function Et(t){if(process.platform!=="win32")return;let e=process.env.CORTEX_GIT_BASH_PATH;if(!e)return;let n=t.getShellPath.bind(t);t.getShellPath=()=>n()??e}function J(t,e,n){let o=t.SettingsManager.create(e,n,{projectTrusted:gt(t,e,n)});return o.getCacheWarmingMode=()=>"off",yt(o),Et(o),o}var b=F("pi-subagent");function Tt(t,e,n){if(!e.model)return{model:void 0,thinkingLevel:void 0};let o=e.provider?`${e.provider}/${e.model}`:e.model,r=t.resolveCliModel({cliModel:e.thinking?`${o}:${e.thinking}`:o,modelRuntime:n});if(r.error)throw new Error(r.error);return r.warning&&b.warn(`PI subagent model resolution: ${r.warning}`),{model:r.model,thinkingLevel:r.thinkingLevel}}async function ht(t,e){let n=J(t,e.cwd,e.agentDir),o=await t.ModelRuntime.create({authPath:G(e.agentDir),modelsPath:Y.join(e.agentDir,"models.json"),allowModelNetwork:!1});return await V(o,e.agentDir),t.createAgentSessionServices({cwd:e.cwd,agentDir:e.agentDir,settingsManager:n,modelRuntime:o,resourceLoaderOptions:{noExtensions:!0,extensionFactories:e.extensions,appendSystemPrompt:e.appendSystemPrompt,noContextFiles:e.noContextFiles===!0}})}async function Q(t){let e=await K(),n=await ht(e,t);for(let i of n.diagnostics)i.type==="error"&&b.warn(`PI subagent session: ${i.message}`);let{model:o,thinkingLevel:r}=Tt(e,t,n.modelRuntime),s=await e.createAgentSessionFromServices({services:n,sessionManager:e.SessionManager.inMemory(t.cwd),model:o,thinkingLevel:r,tools:t.tools});return await s.session.bindExtensions({mode:"print",onError:i=>b.warn(`PI subagent extension ${i.extensionPath} failed on ${i.event}: ${String(i.error)}`)}),{session:s.session,dispose:()=>s.session.dispose()}}function T(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(!n||typeof n!="object"||n.type!=="image")continue;let o=n,r=o.source;r&&r.type==="base64"&&typeof r.data=="string"&&r.data?e.push({mimeType:typeof r.media_type=="string"?r.media_type:"",data:r.data}):typeof o.data=="string"&&o.data&&e.push({mimeType:typeof o.mimeType=="string"?o.mimeType:"",data:o.data})}return e}function Z(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.mimeType=="string"&&typeof e.data=="string"&&e.data.length>0}function Ae(t,e,n=!1){if(!e||!t)return;let o=r=>{try{e(r)}catch{}};return{forChild(r,s){let i=`${t}#${r}`,c=n&&r>0;return(a,m)=>{let d=Rt(i,s,m,a);for(let f=0;f<d.length;f++)o(c&&f===0?{...d[f],prompt:s.prompt}:d[f]);d.length&&(c=!1)}}}}function Ct(t,e,n){return{ref:t,type:e.subagent_type,description:e.description,model:n.model??null,backend:"pi",...e.clean?{clean:!0}:{}}}function Rt(t,e,n,o){let r=Ct(t,e,n),s=o.type;if(s==="tool_execution_start"){let m=o.toolCallId,d=o.toolName;return typeof m!="string"||typeof d!="string"?[]:[{...r,kind:"tool_use",toolUseId:`${t}:${m}`,name:d,input:o.args??{}}]}if(s==="tool_execution_end")return It(r,o);let i=N(o);if(!i||i.role!=="assistant")return[];let c=typeof i.model=="string"?i.model:r.model,a=P(i);return a?[{...r,model:c,kind:"assistant_text",text:a}]:[]}function It(t,e){let n=e.toolCallId;if(typeof n!="string")return[];let o=T(e.result?.content);return[{...t,kind:"tool_result",toolUseId:`${t.ref}:${n}`,ok:e.isError!==!0,content:kt(e.result),...o.length?{images:o}:{}}]}function N(t){return t.type!=="message_end"||!t.message||typeof t.message!="object"?null:t.message}function P(t){let e=t.content;return typeof e=="string"?e:Array.isArray(e)?e.filter(n=>!!n&&typeof n=="object"&&n.type==="text"&&typeof n.text=="string").map(n=>n.text).join(`
5
- `):""}function kt(t){if(typeof t=="string")return t;if(!t||typeof t!="object")return"";let e=t.content;return typeof e=="string"?e:Array.isArray(e)?e.filter(n=>n&&typeof n=="object"&&n.type==="text").map(n=>String(n.text??"")).join(""):""}function Ne(t,e,n,o){return{ref:t,type:e.subagent_type,description:e.description,model:null,backend:n,kind:"end",status:o}}function xt(t){let e=t.name;return t.backend==="claude"?e:_("pi",e)??e}function q(t){if(t.kind==="end")return t.status?[{type:"subagent_end",parentToolUseId:t.ref,status:t.status}]:[];let e={parentToolUseId:t.ref,type:t.type||null,description:t.description||null,...t.prompt?{prompt:t.prompt}:{},model:t.model,...t.clean?{clean:!0}:{}};return t.kind==="tool_use"?[{type:"tool_use",toolUseId:t.toolUseId,name:xt(t),input:t.input??{},subagent:e}]:t.kind==="tool_result"?[{type:"tool_result",toolUseId:t.toolUseId,ok:t.ok!==!1,content:t.content??"",subagent:e,...t.images?.length?{images:t.images}:{}}]:[{type:"assistant_text",text:t.text,subagent:e}]}var Ot=new Set(["pending","in_progress","completed"]);function tt(t){return typeof t=="string"?t:""}function At(t){return typeof t=="string"&&Ot.has(t)?t:"pending"}function St(t){if(!t||typeof t!="object")return null;let e=t,n=tt(e.content).trim(),o=tt(e.activeForm).trim()||n;return!n&&!o?null:{content:n||o,activeForm:o,status:At(e.status)}}function bt(t,e=Date.now()){if(!t||typeof t!="object")return null;let n=t.todos;if(!Array.isArray(n))return null;let o=[];for(let i of n){let c=St(i);c&&o.push(c)}let r=0,s=null;for(let i of o)i.status==="completed"?r+=1:i.status==="in_progress"&&s===null&&(s=i.activeForm);return{items:o,total:o.length,completed:r,activeLabel:s,updatedAt:e}}function et(t,e,n,o=Date.now()){return _(t,e)!=="todo_write"?null:bt(n,o)}function Ue(t,e=40){if(!t||t.total===0)return"";let n=`${t.completed}/${t.total}`,o=t.activeLabel?.trim();if(!o)return n;let r=o.length>e?`${o.slice(0,e-1).trimEnd()}\u2026`:o;return`${n} \xB7 ${r}`}function je(){return{turnProgressCount:0,pendingCompletion:D()}}function $e(t,e){let n=t;if(typeof n.type!="string")return[];let o=n.type;if(o==="message_update")return wt(n);if(o==="tool_execution_start")return Dt(n);if(o==="tool_execution_end")return Ut(n);if(o==="agent_end")return Lt(n,e);if(o==="agent_settled")return Xt(e);if(o==="compaction_start")return[{type:"context_compacted",trigger:typeof n.reason=="string"&&n.reason.length>0?n.reason:"auto"}];if(o==="message_end")return e.turnProgressCount++,[{type:"turn_progress",numTurns:e.turnProgressCount}];if(o==="cortex_subagent_event"){let r=Vt(n.notice);return r?q(r):[]}if(o==="cortex_subagent_usage")return Ht(n.report,e);if(o==="auto_retry_start")return Pt(n);if(o==="extension_error"){let r=n.error;return[{type:"error",message:typeof r=="string"&&r.length>0?r:"extension error",fatal:!1}]}return o==="extension_ui_request"?zt(n):[]}function R(t){return t!==null&&typeof t=="object"?t:void 0}function ot(t){let e=R(t),n=e?.id??e?.responseId;return typeof n=="string"?n:void 0}function nt(t,e){let n=R(t)?.content;return!Array.isArray(n)||typeof e!="number"?!1:R(n[e])?.redacted===!0}function Nt(t,e){let n=e.redacted===!0||nt(t.message,e.contentIndex)||nt(e.partial,e.contentIndex),o=e.type==="thinking_end"?e.content:e.delta;if(n||typeof o!="string"||o.length===0)return[];let r=ot(t.message),s=r!==void 0&&typeof e.contentIndex=="number"?`${r}:t${e.contentIndex}`:void 0;return e.type==="thinking_end"?[{type:"assistant_thinking",text:o,...s!==void 0?{blockId:s}:{}}]:s!==void 0?[{type:"assistant_thinking_delta",text:o,blockId:s}]:[]}function Pt(t){let e=t.attempt;if(typeof e!="number")return[];let n=typeof t.errorMessage=="string"?t.errorMessage:null;return[{type:"api_retry",attempt:e,error:n}]}function wt(t){let e=R(t.assistantMessageEvent);if(!e)return[];if(e.type==="thinking_delta"||e.type==="thinking_end")return Nt(t,e);if(e.type!=="text_delta"||typeof e.delta!="string"||e.delta.length===0)return[];let n=ot(t.message);return[{type:"assistant_text",text:e.delta,...n!==void 0?{blockId:n}:{}}]}function Dt(t){let e=t.toolCallId,n=t.toolName,o=t.args??{};if(typeof e!="string"||typeof n!="string")return[];let r=_("pi",n)??n,s=[{type:"tool_use",toolUseId:e,name:r,input:o}],i=et("pi",n,o);return i&&s.push({type:"todo_update",toolUseId:e,snapshot:i}),s}function Ut(t){let e=t.toolCallId;if(typeof e!="string")return[];let n=t.isError===!0,o=t.result,r="",s=[];if(o&&typeof o=="object"){let c=o.content;Array.isArray(c)?(r=c.filter(a=>l(a).type==="text").map(a=>String(l(a).text??"")).join(""),s=T(c)):typeof c=="string"&&(r=c)}return[{type:"tool_result",toolUseId:e,ok:!n,content:r,...s.length?{images:s}:{}}]}function rt(t,e){if(t.type!=="tool_execution_end"||!e?.input||e.input.includes("image"))return t;let n=l(t.result),o=n.content;return!Array.isArray(o)||!o.some(r=>l(r).type==="image")?t:{...t,result:{...n,content:o.filter(r=>l(r).type!=="image")}}}function D(){return{numTurns:0,totalCostUsd:null,error:null}}function Mt(){return{...D(),provider:"",model:"",tokensIn:0,tokensOut:0,cacheReadTokens:0,cacheWriteTokens:0,inputReported:!0,outputReported:!0,cacheReadReported:!0,cacheWriteReported:!0}}function Lt(t,e){let n=Array.isArray(t.messages)?t.messages:[],o=Wt(n);if(Kt(e,o),o.provider==="")return[];let r=C(o.tokensIn,o.inputReported),s=C(o.tokensOut,o.outputReported),i=C(o.cacheReadTokens,o.cacheReadReported),c=C(o.cacheWriteTokens,o.cacheWriteReported),a=vt(r,i,c);return[{type:"cost_record",provider:o.provider,model:o.model,tokens_in:o.tokensIn,tokens_out:o.tokensOut,prompt_tokens:a,cached_tokens:i,input_tokens:r,output_tokens:s,cache_read_tokens:i,cache_creation_tokens:c,provider_requests:o.numTurns>0?o.numTurns:null,cost_usd:o.totalCostUsd}]}function Xt(t){let e=t.pendingCompletion;t.pendingCompletion=D();let n={type:"turn_complete",numTurns:e.numTurns,totalCostUsd:e.totalCostUsd};return e.error===null?[n]:[{...n,error:e.error}]}function Wt(t){let e=Mt();for(let n of t){let o=l(n);o.role==="assistant"&&(e.numTurns++,Ft(e,o),jt(e,o),Bt(e,o))}return e}function Ft(t,e){let n=e.provider,o=e.model;t.provider===""&&typeof n=="string"&&n.length>0&&(t.provider=n),t.model===""&&typeof o=="string"&&o.length>0&&(t.model=o)}function jt(t,e){if(t.error!==null||e.stopReason!=="error")return;let n=e.errorMessage;t.error=typeof n=="string"&&n.length>0?n:"PI agent reported an error during execution"}function $t(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0}function h(t,e,n){return $t(n)?[t+n,e]:[t,!1]}function Bt(t,e){let n=l(e.usage);[t.tokensIn,t.inputReported]=h(t.tokensIn,t.inputReported,n.input),[t.tokensOut,t.outputReported]=h(t.tokensOut,t.outputReported,n.output),[t.cacheReadTokens,t.cacheReadReported]=h(t.cacheReadTokens,t.cacheReadReported,n.cacheRead),[t.cacheWriteTokens,t.cacheWriteReported]=h(t.cacheWriteTokens,t.cacheWriteReported,n.cacheWrite);let o=l(n.cost).total;typeof o=="number"&&isFinite(o)&&(t.totalCostUsd=(t.totalCostUsd??0)+o)}function C(t,e){return e?t:null}function vt(...t){return t.some(e=>e===null)?null:t.reduce((e,n)=>e+n,0)}function Kt(t,e){let n=t.pendingCompletion;n.numTurns+=e.numTurns,n.totalCostUsd=st(n.totalCostUsd,e.totalCostUsd),n.error=e.error}function st(t,e){return t===null&&e===null?null:(t??0)+(e??0)}function Ht(t,e){let n=l(t),o=n.provider;if(typeof o!="string"||o==="")return[];let r=l(n.usage),s=E(r.input),i=E(r.output),c=E(r.cacheRead),a=E(r.cacheWrite),m=E(r.turns),d=w(r.cost);e.pendingCompletion.totalCostUsd=st(e.pendingCompletion.totalCostUsd,d);let f=n.model,O=n.connection;return[{type:"cost_record",provider:o,connection:typeof O=="string"&&O!==""?O:o,model:typeof f=="string"?f:"",tokens_in:s,tokens_out:i,prompt_tokens:s+c+a,cached_tokens:c,input_tokens:s,output_tokens:i,cache_read_tokens:c,cache_creation_tokens:a,provider_requests:m>0?m:null,cost_usd:d}]}function Gt(t){return t==="completed"||t==="failed"||t==="killed"}function Vt(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t,{ref:n,kind:o}=e;if(typeof n!="string"||!n||o!=="tool_use"&&o!=="tool_result"&&o!=="assistant_text"&&o!=="end")return null;let r={ref:n,kind:o,type:typeof e.type=="string"?e.type:"",description:typeof e.description=="string"?e.description:"",...typeof e.prompt=="string"?{prompt:e.prompt}:{},model:typeof e.model=="string"?e.model:null};if(o==="tool_use")return typeof e.name!="string"||typeof e.toolUseId!="string"?null:(r.name=e.name,r.toolUseId=e.toolUseId,r.input=e.input??{},r);if(o==="tool_result"){if(typeof e.toolUseId!="string")return null;r.toolUseId=e.toolUseId,r.ok=e.ok!==!1,r.content=typeof e.content=="string"?e.content:"";let s=Array.isArray(e.images)?e.images.filter(Z):[];return s.length&&(r.images=s),r}return o==="end"?Gt(e.status)?(r.status=e.status,r):null:typeof e.text!="string"||!e.text?null:(r.text=e.text,r)}function zt(t){let e=t.id,n=t.method;if(typeof e!="string"||typeof n!="string")return[];if(n!=="select"&&n!=="confirm"&&n!=="input"&&n!=="editor")return[];let o=t.title,r=typeof o=="string"&&o.length>0?o:`${n} request`,s;if(n==="select"){let i=t.options,c=Array.isArray(i)?i.map(String):void 0;s={question:r},c&&(s.options=c)}else if(n==="confirm"){let i=t.message,c=typeof i=="string"&&i.length>0?`: ${i}`:"";s={question:r+c,options:["Yes","No"]}}else n==="editor"?s={question:r,multi:!0}:s={question:r};return[{type:"ask_user_question",toolUseId:e,questions:[s]}]}function Be(t,e=null){let n=l(l(t).contextUsage),o=n.contextWindow;if(typeof o!="number"||!Number.isFinite(o)||o<=0)return null;let r=w(n.tokens);if(e===null||o<=e){let i=w(n.percent);return{usedTokens:r,contextWindow:o,percent:i,accuracy:"estimate"}}let s=r===null?null:r/e*100;return{usedTokens:r,contextWindow:e,percent:s,accuracy:"estimate"}}function E(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?Math.floor(t):0}function w(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}function l(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function it(t){return t??"direct"}var ct="CORTEX_PI_MCP_COMPOSITION",I="CORTEX_PI_INTERACTION_BRIDGE",k="CORTEX_PI_TEAM_LEAD",x="CORTEX_PI_TEAM_WORKER",at="CORTEX_PI_CLEAN_WORKSPACE",ut="CORTEX_PI_HOME_AGENT_DIR",Jt=["SLACK_CHANNEL","FEISHU_CHANNEL","CORTEX_SESSION_ID","CORTEX_PROFILE","CORTEX_MODE","CORTEX_BACKEND","CORTEX_MODEL","CORTEX_PROVIDER","CORTEX_THINKING","CORTEX_CONNECTION","CORTEX_PROJECT","CORTEX_SESSION_NAME","CORTEX_EXECUTION_ID","CORTEX_CALLBACK_SOURCE","CORTEX_SCHEDULE_TASK_ID","CORTEX_CONFIG_IMMUTABLE","CORTEX_PRODUCTION_AUTH_FILE","CORTEX_WEBHOOK_BENCHMARK_ONLY","CORTEX_PI_ALLOWED_TOOLS","CORTEX_PI_SUBAGENT",ct,I,k,x,at,ut,A];function u(t,e,n){n!=null&&n!==""&&(t[e]=String(n))}function Yt(t,e){let n=e.context;u(t,"CORTEX_MODEL",n?.selection?.model),u(t,"CORTEX_PROVIDER",n?.selection?.provider),u(t,"CORTEX_THINKING",n?.selection?.thinking),u(t,"CORTEX_CONNECTION",n?.selection?.connection),u(t,"CORTEX_SESSION_ID",n?.trackSessionId??e.sessionId),u(t,"CORTEX_CALLBACK_SOURCE",e.callbackSource),u(t,"CORTEX_SCHEDULE_TASK_ID",e.scheduleTaskId),u(t,"CORTEX_PROJECT",n?.project),u(t,"CORTEX_EXECUTION_ID",n?.executionId)}function Qt(t,e=process.env){let n={...e,...t.routeEnv??{}};for(let o of Jt)delete n[o];for(let o of t.unsetEnv??[])delete n[o];return n.PI_CODING_AGENT_DIR=t.piAgentDir,t.piHomeAgentDir&&t.piHomeAgentDir!==t.piAgentDir&&(n[ut]=t.piHomeAgentDir),n.CORTEX_BACKEND="pi",t.channel&&(n.SLACK_CHANNEL=t.channel,n.FEISHU_CHANNEL=t.channel),u(n,"CORTEX_PI_ALLOWED_TOOLS",t.allowedTools),u(n,ct,t.mcpComposition),t.mcpToolAllowlist!==void 0&&t.mcpToolAllowlist!==null&&(n[A]=JSON.stringify(t.mcpToolAllowlist)),t.enableInteractionBridge===!0&&(n[I]="1"),t.enableTeamLead===!0&&(n[k]="1"),t.enableTeamWorker===!0&&(n[x]="1"),u(n,"CORTEX_PI_SUBAGENT",t.subagentMarker),u(n,at,t.cleanWorkspace),Yt(n,t),n}function Zt(t){return t.replace(/\[.*?\]$/,"")}function qt(t){return t?(Array.isArray(t)?t:[t]).filter(e=>e.length>0):[]}function te(t){let e=t.tools.canonical&&t.tools.canonical.length>0?t.tools.canonical.map(n=>$("claude",n)).filter(n=>!!n).join(","):void 0;return t.tools.rawClaude??e}function ee(t){return t.env.sets?.CORTEX_PI_SUBAGENT==="1"?"1":void 0}function ne(t,e){return e!=="direct"?[]:[...t.mcp.servers??[]]}function ze(t,e){let n=it(t.mcp.composition),o=ee(t),r=Qt({sessionId:t.resume.backendSessionId,channel:t.context.channel,callbackSource:t.context.callbackSource,scheduleTaskId:t.context.scheduleTaskId,routeEnv:t.env.sets,unsetEnv:t.env.unsets,context:t.env.context,piAgentDir:e.agentDir,piHomeAgentDir:e.homeAgentDir,allowedTools:te(t),mcpComposition:n,mcpToolAllowlist:t.mcp.allowlist,enableInteractionBridge:n==="direct"&&t.flags.isUserInitiated===!0&&o===void 0,enableTeamLead:n==="direct"&&t.flags.teamLead===!0&&o===void 0,enableTeamWorker:n==="direct"&&t.flags.teamWorker===!0&&o===void 0,subagentMarker:o,cleanWorkspace:t.flags.clean?e.cwd:null},t.env.pinned);return{sessionKey:t.engineKey,cwd:e.cwd,agentDir:e.agentDir,sessionDir:e.sessionDir,sessionPath:e.sessionPath,provider:t.model.provider??null,model:t.model.id?Zt(t.model.id):null,benchmarkMaxOutputTokens:t.model.benchmarkMaxOutputTokens,thinking:t.model.thinking??null,systemPrompt:t.prompt.system||null,appendSystemPrompt:qt(t.prompt.append),skillPaths:t.flags.disableSkills?[]:[...t.plugins.skillDirs??[],...t.plugins.dirs??[]],disableHooks:t.flags.disableHooks===!0,...t.flags.clean?{noContextFiles:!0}:{},reportsProviderQuota:!0,pluginMcpServers:ne(t,n),env:r,streamDeltas:e.streamDeltas}}var oe=new Set(["CORTEX_EXECUTION_ID"]);function Je(t){let{sessionPath:e,env:n,...o}=t,r=Object.entries(n).filter(([s])=>!oe.has(s)).sort(([s],[i])=>s<i?-1:s>i?1:0);return JSON.stringify({...o,env:r})}import{existsSync as re,mkdirSync as U,readFileSync as se,promises as y}from"node:fs";import*as pt from"node:os";import*as p from"node:path";var dt="inputs",lt="clean-workspace.md";function tn(t){return t?.clean===!0&&t.workspaceDir?t.workspaceDir:null}function en(t,e=X){U(e,{recursive:!0});for(let n=1;;n++){let o=p.join(e,n===1?t:`${t}-${n}`);if(ie(o))return U(p.join(o,dt)),o}}function ie(t){try{return U(t),!0}catch(e){if(e.code==="EEXIST")return!1;throw e}}async function nn(t,e,n){let o=p.join(t,dt);await y.mkdir(o,{recursive:!0});let r=B(n||p.basename(e)),s=p.join(o,r);if(await ce(e,s))return s;let{destPath:i}=await v(o,r);return await y.cp(e,i,{recursive:!0}),i}async function ce(t,e){let[n,o]=await Promise.all([y.stat(t).catch(()=>null),y.stat(e).catch(()=>null)]);if(!n?.isFile()||!o?.isFile()||n.size!==o.size)return!1;let[r,s]=await Promise.all([y.readFile(t),y.readFile(e)]);return r.equals(s)}function on(t,e){let n=t==="~"||t.startsWith("~/")?p.join(pt.homedir(),t.slice(1)):t;return p.resolve(e,n)}function ft(t){let e=p.join(W,lt),n=re(e)?e:p.join(L,"prompts",lt);return se(n,"utf8").replaceAll("{{workspace}}",t).trim()}function ae(t,e){let n={...t,PI_CODING_AGENT_DIR:e,CORTEX_PI_SUBAGENT:"1"};return delete n[I],delete n[k],delete n[x],n}async function fn(t){let{task:e,role:n}=t,o=t.model??{},r=t.createSession??Q,s=t.workspace??null,i=await r({cwd:s??t.cwd,agentDir:t.agentDir,provider:o.provider??null,model:o.model??null,thinking:o.thinking??null,tools:H(n,"pi"),appendSystemPrompt:[...n.systemPrompt?[n.systemPrompt]:[],...s?[ft(s)]:[]],...s?{noContextFiles:!0}:{},extensions:t.childExtensions(ae(t.parentEnv,t.agentDir),o.provider??null)});try{let c=await ue(i,e,t.signal,t.forward);return c.model||(c.model=o.model),c}finally{i.dispose()}}async function ue(t,e,n,o){if(n?.aborted)throw new Error("Subagent was aborted.");let r={output:"",usage:S()},s=t.session.subscribe(c=>{pe(r,rt(c,t.session.model),o)}),i=()=>{t.session.abort().catch(()=>{})};n?.addEventListener("abort",i,{once:!0});try{await t.session.prompt(`Task: ${e.prompt}`)}finally{n?.removeEventListener("abort",i),s()}if(n?.aborted)throw new Error("Subagent was aborted.");return le(e,r)}function le(t,e){return{description:t.description,prompt:t.prompt,subagentType:t.subagent_type,output:e.output,usage:e.usage,model:e.model,provider:e.provider,backend:"pi",stopReason:e.stopReason,errorMessage:e.errorMessage}}function pe(t,e,n){if(n)try{n(e,t)}catch{}let o=N(e);o&&(de(t,o),me(t,o))}function de(t,e){if(e.role!=="assistant")return;let n=e.usage,o=n?.cost;z(t.usage,{input:g(n?.input),output:g(n?.output),cacheRead:g(n?.cacheRead),cacheWrite:g(n?.cacheWrite),cost:g(o?.total),contextTokens:g(n?.totalTokens),turns:1})}function M(t,e){return typeof t=="string"?t:e}function fe(t,e){let n=typeof e.stopReason=="string"?e.stopReason:void 0;if(!n){t.errorMessage=M(e.errorMessage,t.errorMessage);return}t.stopReason=n,t.errorMessage=typeof e.errorMessage=="string"?e.errorMessage:void 0}function me(t,e){e.role==="assistant"&&(t.output=P(e)||t.output,t.model=M(e.model,t.model),t.provider=M(e.provider,t.provider),fe(t,e))}export{bt as a,et as b,Ue as c,it as d,T as e,Ne as f,q as g,je as h,$e as i,rt as j,Be as k,ct as l,I as m,k as n,x as o,at as p,ut as q,ze as r,Je as s,J as t,Q as u,S as v,ge as w,Ae as x,Rt as y,tn as z,en as A,nn as B,on as C,ft as D,ae as E,fn as F,le as G};
@@ -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 ae}from"./chunk-RA2BUYI3.js";import{a as de,b as fe,d as pe}from"./chunk-U23S37TT.js";import{f as g,h as M}from"./chunk-T73GHMFB.js";import{a as D}from"./chunk-OKRK6JPY.js";import{a as ue,f as le}from"./chunk-VK5J556O.js";import{a,b as _,d as ie,e as ce,f as C,g as x,h as se,j as f,l as T,m as P,o as Y}from"./chunk-TX46YMGI.js";import{c as te}from"./chunk-AVXDF7AG.js";import{e as m}from"./chunk-VBN2JSER.js";import{i as w,k as N,l as re,m as oe}from"./chunk-Z24SBRJK.js";import{a as We}from"./chunk-VPVSKJGX.js";import{e as qe}from"./chunk-WHC7AYZD.js";import*as Te from"node:path";var he=qe(We(),1);import{execFile as Qe,execFileSync as Je}from"child_process";import{createHash as Ze}from"crypto";import{readFileSync as en}from"fs";import*as L from"path";var nn="oauth-2025-04-20",ke="2023-06-01",tn=6e4,rn=2e3,on=5e3;function G(e,n){try{return e(n)}catch{return null}}function z(e){return e.readFile??(n=>en(n,"utf8"))}function v(e){if(typeof e!="string")return;let n=e.trim();if(!(!n||n==="undefined"||n==="null"))return n}function cn(e){let n=G(e,L.join(w,".env"));if(n===null)return{};try{return(0,he.parse)(n)}catch{return{}}}function sn(e={}){let n=cn(z(e)),t=v(n.CLAUDE_CODE_OAUTH_TOKEN);return{ANTHROPIC_API_KEY:v(n.ANTHROPIC_API_KEY),ANTHROPIC_BASE_URL:v(n.ANTHROPIC_BASE_URL),CLAUDE_CODE_OAUTH_TOKEN:t,CLAUDE_CODE_OAUTH_TOKEN_EXPIRES_AT:t?v(n.CLAUDE_CODE_OAUTH_TOKEN_EXPIRES_AT):void 0}}function un(e={}){return x(f(e.connectionsFile??a)).find(n=>!n.baseUrl&&n.authStyle==="x-api-key")??null}function ln(e){return{"x-api-key":e,"anthropic-version":ke}}function R(e){return{authorization:`Bearer ${e}`,"anthropic-beta":nn,"anthropic-version":ke}}function X(e={}){return e.claudeConfigDir??N}function an(e={}){return L.join(X(e),".credentials.json")}function y(e){return typeof e=="string"&&e.trim()?e.trim():null}function me(e){return typeof e!="number"||!Number.isFinite(e)||Number.isNaN(new Date(e).getTime())?null:e}function ge(e){let n;try{n=JSON.parse(e)?.claudeAiOauth}catch{return null}if(!n||typeof n!="object"||Array.isArray(n))return null;let t=n,r={accessToken:y(t.accessToken),refreshToken:y(t.refreshToken),expiresAt:me(t.expiresAt),refreshExpiresAt:me(t.refreshTokenExpiresAt)};return r.accessToken||r.refreshToken?r:null}function ve(e={}){let n=G(z(e),an(e));return n===null?null:ge(n)}function ye(e,n){if(!e?.accessToken)return null;let t=(n.now??Date.now)();return e.expiresAt!==null&&e.expiresAt-tn<=t?null:e.accessToken}function Ae(e){return ye(ve(e),e)}function Ut(e={}){let n=Ae(e);return n?R(n):null}function _e(e){let n=G(z(e),L.join(X(e),".claude.json"));if(n===null)return null;try{let t=JSON.parse(n)?.oauthAccount;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Ht(e={}){return y(_e(e)?.organizationUuid)}function Ft(e={}){let n=_e(e);return n?{email:y(n.emailAddress),organization:y(n.organizationName),plan:y(n.organizationType)??y(n.billingType)}:null}function A(e={}){if(q(e))return{source:"claude-store",token:null};let n=v((e.env??process.env).CLAUDE_CODE_OAUTH_TOKEN);if(n)return{source:"env-oauth-token",token:n};let t=sn(e).CLAUDE_CODE_OAUTH_TOKEN;return t?{source:"dotenv-oauth-token",token:t}:null}function Ce(e={}){let n=un(e);if(n)return{headers:ln(n.key),source:"connection-api-key"};let t=A(e);if(!t)return null;if(t.source!=="claude-store")return{headers:R(t.token),source:t.source};let r=Ae(e);return r?{headers:R(r),source:"claude-credentials"}:null}function Ee(e={}){return`Claude Code-credentials-${Ze("sha256").update(X(e).normalize("NFC")).digest("hex").slice(0,8)}`}function dn(e){try{return Je("security",["find-generic-password","-s",e],{stdio:"ignore",timeout:rn}),!0}catch{return!1}}function fn(e){return new Promise(n=>{try{Qe("security",["find-generic-password","-s",e,"-w"],{encoding:"utf8",timeout:on},(t,r)=>n(t?null:r.trim()||null))}catch{n(null)}})}async function be(e={}){if((e.platform??process.platform)!=="darwin")return null;let r=await(e.readKeychain??fn)(Ee(e)),o=ye(r===null?null:ge(r),e);return o?{headers:R(o),source:"claude-keychain"}:null}function q(e={}){return ve(e)?!0:(e.platform??process.platform)!=="darwin"?!1:(e.probeKeychain??dn)(Ee(e))}var pn=Te.join(w,".env"),E="api";function Oe(){return x(f()).find(e=>e.id===E)??null}function Yt(){return[Oe()?.key,A()?.token].filter(e=>!!e)}function mn(e){let n=v(e);if(!n||/[\s"\\]/.test(n))throw new Error("Enter a valid Anthropic API key.");return n}function hn(e,n){return new RegExp(`^[ \\t]*(?:export[ \\t]+)?${e}[ \\t]*=.*$`,n)}function kn(e,n){let t=hn(n,"gm");return e.replace(new RegExp(`${t.source}(?:\\r?\\n|$)`,"gm"),"")}async function Ie(e){await te(pn,n=>e.reduce(kn,n),{mode:384})}async function Gt(e){let n=mn(e),t=Oe();T(t?{...t,key:n}:{id:E,backend:"claude",label:E,authStyle:"x-api-key",key:n,billing:"metered"})}async function zt(){P({backend:"claude",id:E}),await Ie(["ANTHROPIC_API_KEY"])}async function Xt(){await Ie(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN_EXPIRES_AT"]),delete process.env.CLAUDE_CODE_OAUTH_TOKEN,delete process.env.CLAUDE_CODE_OAUTH_TOKEN_EXPIRES_AT}var gn=["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL"];function qt(e=process.env){for(let n of gn)delete e[n];A()?.source==="claude-store"&&(delete e.CLAUDE_CODE_OAUTH_TOKEN,delete e.CLAUDE_CODE_OAUTH_TOKEN_EXPIRES_AT)}import Se from"node:fs";import U from"node:path";var vn=32,yn=[_,E];function An(e,n){let r=e.normalize("NFKD").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+/,"").slice(0,vn).replace(/-+$/,"")||"account";if(!n.has(r))return r;for(let o=2;;o++)if(!n.has(`${r}-${o}`))return`${r}-${o}`}function _n(e,n){let t=f(n.file??a).map(o=>o.id),r=[...yn,e.provider?.trim()??"",...n.reservedIds??[]];return new Set([...t,...r].filter(Boolean))}function Cn(e){let n=[];return e.label.trim()||n.push("label-required"),e.backend==="pi"&&!e.provider?.trim()&&n.push("provider-required"),n}function En(e,n){let t=e.label.trim();return e.backend==="claude"?{id:n,backend:"claude",type:"account",label:t,pending:!0}:{id:n,backend:"pi",type:"account",label:t,provider:e.provider.trim(),pending:!0}}function Zt(e,n={}){let t=Cn(e);if(t.length>0)return{ok:!1,errors:t};let r=En(e,An(e.label.trim(),_n(e,n)));try{T(r,n.file??a)}catch{return{ok:!1,errors:["write-failed"]}}return{ok:!0,account:r}}function O(e,n=a){let t=f(n).find(r=>r.backend===e.backend&&r.id===e.id);return t&&C(t)?t:null}function er(e,n=a){let t=O(e,n);if(!t?.pending)return;let{pending:r,...o}=t;T(o,n)}function nr(e,n=a){return O(e,n)?P(e,n):!1}function tr(e=a){return f(e).filter(n=>C(n)&&!!n.pending)}function bn(e,n={}){let t=M(e,n.accountsDir);return Se.mkdirSync(t,{recursive:!0,mode:448}),ae({agentDir:t}),t}function fr(e,n={}){Se.rmSync(M(e,n.accountsDir),{recursive:!0,force:!0})}function Tn(e,n={}){return g(M(e,n.accountsDir))}function we(e,n={}){return fe(Tn(e.id,n),e.provider)}function pr(e,n={}){if(e.backend!=="pi"||!e.connection)return;let t=O({backend:"pi",id:e.connection},n.file??a);if(!(t?.backend!=="pi"||t.pending||t.provider!==e.provider))return{connection:t.id,agentDir:bn(t.id,n)}}function mr(e,n={}){let t=U.resolve(e);if(U.dirname(t)!==U.resolve(n.accountsDir??oe))return null;let r=O({backend:"pi",id:U.basename(t)},n.file??a);return r?.backend==="pi"?r:null}function Ne(e){return new Promise(n=>{setTimeout(n,e).unref?.()})}var b=class{options;entries=[];nextRefreshAt=0;inFlight=null;refreshQueued=!1;now;constructor(n){this.options=n,this.now=n.now??Date.now}peek(){let n=this.options.clone;return n?this.entries.map(n):[...this.entries]}get(){let n=this.peek();return this.now()>=this.nextRefreshAt&&!this.inFlight&&this.startRefresh(),n}async ensure(n){if(this.entries.length>0)return this.get();!this.inFlight&&this.now()>=this.nextRefreshAt&&this.startRefresh();let t=this.inFlight;return t&&await Promise.race([t,Ne(n)]),this.peek()}async settle(n){this.refresh();let t=!1,r=Ne(n).then(()=>{t=!0});for(;this.inFlight&&!t;)await Promise.race([this.inFlight,r]);return this.peek()}refresh(){if(!this.inFlight){this.startRefresh();return}this.refreshQueued=!0}startRefresh(){let n=Promise.resolve().then(this.options.scan).then(t=>this.accept(t)).catch(t=>this.reject(t)).finally(()=>this.finishRefresh(n));this.inFlight=n}finishRefresh(n){this.inFlight===n&&(this.inFlight=null,this.refreshQueued&&(this.refreshQueued=!1,this.startRefresh()))}accept(n){let{key:t,clone:r}=this.options,o=new Set,i=[];for(let c of n){if(t){let s=t(c);if(o.has(s))continue;o.add(s)}i.push(r?r(c):c)}this.entries=i,this.nextRefreshAt=this.now()+this.options.cacheTtlMs}reject(n){this.nextRefreshAt=this.now()+this.options.retryMs;let t=n instanceof Error?n.message:"unknown";this.options.logFailure?.(t)}};import*as xe from"node:path";var On=["off","minimal","low","medium","high","xhigh","max"];function In(e){let n=e;if(!n||typeof n!="object"||!("reasoning"in n)&&!("thinkingLevelMap"in n))return;if(!n.reasoning)return[];let t=n.thinkingLevelMap;return On.filter(r=>{let o=t?.[r];return o===null?!1:r==="xhigh"||r==="max"?o!==void 0:!0})}async function Pe(e){let{ModelRuntime:n}=await ue(),t=await n.create({authPath:e.authPath,modelsPath:e.modelsPath,allowModelNetwork:!1});return e.agentDir&&await pe(t,e.agentDir),(await t.getAvailable()).map(o=>{let i=In(o);return{provider:o.provider,model:o.id,...i?{thinkingLevels:i}:{}}})}function W(){return Pe({authPath:g(),modelsPath:le()})}function Ar(e){return Pe({authPath:g(e),modelsPath:xe.join(e,"models.json"),agentDir:e})}var Sn=m("pi-adapter"),wn=5*6e4,Nn=3e4,De=12e3;function xn(e={}){let n=new b({scan:e.scan??W,now:e.now,cacheTtlMs:e.cacheTtlMs??wn,retryMs:e.retryMs??Nn,key:r=>`${r.provider}\0${r.model}`,clone:r=>({...r}),logFailure:r=>Sn.info(`PI provider refresh failed: ${r}`)}),t=()=>n.get();return{getProviders:()=>Array.from(new Set(t().map(r=>r.provider))),getModels:t,peekModels:()=>n.peek(),ensureModels:(r=De)=>n.ensure(r),refresh:()=>n.refresh(),rescan:(r=De)=>n.settle(r)}}var Me=W;function Tr(e){Me=e}var H=xn({scan:()=>Me()});function I(e){return JSON.stringify([e.backend,e.provider,e.model])}var F={claude:["low","medium","high","xhigh","max"],pi:["off","minimal","low","medium","high","xhigh","max"]};function Pn(e,n){return F[e]?.includes(n)??!1}var Re=/^[a-zA-Z0-9_-]+$/;function Dn(e){let n=e;if(!n||n.backend!=="claude"&&n.backend!=="pi")throw new Error("Invalid backend");if(typeof n.model!="string"||!n.model.trim())throw new Error("Model must be a non-empty string");if(!(n.backend==="claude"?n.provider===null:typeof n.provider=="string"&&Re.test(n.provider)))throw new Error("Invalid provider: PI requires a provider; Claude requires null")}function Ir(e){Dn(e);let n=e;if(n.thinking!==null&&!Pn(n.backend,n.thinking))throw new Error(`Invalid thinking for backend '${n.backend}'`);Mn(n)}function Mn(e){let{backend:n,connection:t}=e;if(t!==null){if(t===void 0)throw new Error("Invalid connection: a selection must name one, or null for the default");if(typeof t!="string"||!Re.test(t))throw new Error("Invalid connection")}}function Sr(e){let{backend:n,provider:t,model:r,thinking:o}=e;return{backend:n,provider:t,model:r,thinking:o,connection:e.connection??null}}import d from"node:fs";import p from"node:path";var Rn=m("claude-account-dir"),Ln=new Set([".credentials.json",".claude.json","backups"]),Un=["projects"],Le="settings.json";function K(e,n={}){if(!ie.test(e))throw new Error(`Invalid account id: ${e}`);return p.join(n.accountsDir??re,e)}function Hn(e){try{return d.lstatSync(e)}catch{return null}}function Fn(e){try{return p.resolve(p.dirname(e),d.readlinkSync(e))}catch{return null}}function Kn(e,n){let t=Hn(n);return t?t.isSymbolicLink()?Fn(n)===e?!1:(d.unlinkSync(n),!0):p.basename(n)!==Le?!1:(d.rmSync(n,{force:!0}),!0):!0}function $n(e,n,t,r){if(!Kn(e,n))return;let o=t?r==="win32"?"junction":"dir":"file";try{d.symlinkSync(e,n,o)}catch(i){p.basename(n)===Le?d.copyFileSync(e,n):Rn.warn(`Could not link ${n}: ${i.message}`)}}function jn(e){for(let n of d.readdirSync(e,{withFileTypes:!0})){let t=p.join(e,n.name);n.isSymbolicLink()&&!d.existsSync(t)&&d.unlinkSync(t)}}function Rr(e,n={}){let t=K(e,n),r=n.sharedDir??N,o=n.platform??process.platform;d.mkdirSync(t,{recursive:!0,mode:448});for(let i of Un)d.mkdirSync(p.join(r,i),{recursive:!0});jn(t);for(let i of d.readdirSync(r,{withFileTypes:!0}))Ln.has(i.name)||$n(p.join(r,i.name),p.join(t,i.name),i.isDirectory(),o);return t}function Lr(e,n={}){let t=K(e,n),r;try{r=d.readdirSync(t,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return;throw o}for(let o of r)o.isSymbolicLink()&&d.unlinkSync(p.join(t,o.name));d.rmSync(t,{recursive:!0,force:!0})}function Vn(){return{id:_,backend:"claude",provider:null,kind:"subscription",label:"Claude subscription",baseUrl:null,billing:"subscription",authenticated:!0,keyHint:null,models:null}}function Bn(e){return{id:e.id,backend:"claude",provider:null,kind:"key",label:e.label,baseUrl:e.baseUrl??null,authStyle:e.authStyle,billing:e.billing,authenticated:!0,keyHint:Y(e.key),models:e.models??null}}function Yn(e){return{id:e.id,backend:"claude",provider:null,kind:"account",label:e.label,baseUrl:null,billing:"subscription",authenticated:!0,keyHint:null,models:null}}function Gn(e){let n=ce(e);return{id:e.id,backend:"pi",provider:e.provider,kind:n?"custom":"override",label:e.label??e.provider,baseUrl:e.baseUrl,...n?{api:e.api}:{},billing:"metered",authenticated:n?!0:!!e.key,keyHint:Y(e.key),models:n?e.models.map(t=>t.id):null}}function zn(e,n){return{id:e.id,backend:"pi",provider:e.provider,kind:"account",label:e.label,baseUrl:null,billing:Jn(e.provider,n),authenticated:!0,keyHint:null,models:null}}function Xn(e,n){let t=[];for(let r of n){if(r.backend!=="pi")continue;let o=we(r,{accountsDir:e.piAccountsDir});o&&t.push(zn(r,o))}return t}function qn(e){let n=e.claude??{},t=o=>q({...n,claudeConfigDir:K(o.id,{accountsDir:e.claudeAccountsDir})}),r=A(n)?[Vn()]:[];for(let o of f(e.file??a))o.backend==="claude"&&(C(o)?!o.pending&&t(o)&&r.push(Yn(o)):r.push(Bn(o)));return r}function Wn(e={}){let n=e.claude??{},t=()=>f(e.file??a),r=()=>A(n)?.source??null,o=()=>qn(e),i=()=>se(t()).map(Gn),c=()=>t().filter(l=>C(l)&&!l.pending),s=l=>o().find(k=>k.id===l)??null,u=l=>i().find(k=>k.provider===l)??null,h=()=>de(e.piAuthPath??g()),B=l=>Xn(e,c()).filter(k=>l===void 0||k.provider===l);return{list:()=>[...o(),...i(),...B()],claudeConnections:o,piConnections:i,findClaude:s,findPi:u,piAccounts:B,accounts:c,hasClaude:()=>o().length>0,claudeSubscriptionSource:r,defaultClaudeConnection:()=>o()[0]?.id??null,billingOf:l=>l.backend==="claude"?Qn(l.connection,o(),c()):B(l.provider??void 0).find(k=>k.id===l.connection)?.billing??Zn(l.provider,u,h)}}function Qn(e,n,t){let r=e??n[0]?.id??_;return r===_||t.some(o=>o.backend==="claude"&&o.id===r)?"subscription":n.find(o=>o.id===r)?.billing??"metered"}var Ue=new Set(["openai-codex","google-gemini-cli","google-antigravity"]);function Jn(e,n){return Ue.has(e)||n==="oauth"?"subscription":"metered"}function Zn(e,n,t){return!e||n(e)?.keyHint?"metered":Ue.has(e)||t().has(e)?"subscription":"metered"}var $=Wn();var He=m("anthropic-models"),et=30*6e4,nt=5*6e4,tt=8e3,rt=1e4,ot=1e3,it=1e6,j="[1m]",ct=["low","medium","high","xhigh","max"];function S(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var st="https://api.anthropic.com";function ut(e){if(!S(e))return null;let n=e.effort;if(!S(n)||n.supported!==!0)return null;let t=ct.filter(r=>{let o=n[r];return S(o)&&o.supported===!0});return t.length>0?[...t]:null}function lt(e){if(!S(e))return null;let n=typeof e.id=="string"?e.id.trim():"";if(!n)return null;let t=typeof e.display_name=="string"?e.display_name.trim():"",r=e.max_input_tokens;return{id:n,displayName:t||null,maxInputTokens:typeof r=="number"&&Number.isFinite(r)?r:null,effortLevels:ut(e.capabilities)}}async function at(e={}){let n=Ce(e)??await be(e);if(!n)throw new Error("no Anthropic credential available to the daemon");let t=e.fetchImpl??fetch,r=`${st}/v1/models?limit=${ot}`,o=await t(r,{method:"GET",headers:n.headers,signal:AbortSignal.timeout(rt)});if(!o.ok)throw new Error(`models request failed: HTTP ${o.status}`);let i=await o.json(),c=S(i)?i.data:null;if(!Array.isArray(c))throw new Error("models response carried no data array");let s=[];for(let u of c){let h=lt(u);h&&s.push(h)}return He.debug(`discovered ${s.length} Anthropic models via ${n.source}`),s}function dt(e){return e.endsWith(j)?e.slice(0,-j.length):e}function ft(e,n){return e.startsWith(`${n}-`)&&/^\d{8}$/.test(e.slice(n.length+1))}function Fe(e,n=D){let t=[],r=new Set,o=i=>{r.has(i)||(r.add(i),t.push(i))};for(let i of e)o(i.id),(i.maxInputTokens??0)>=it&&o(`${i.id}${j}`);for(let i of n){let c=dt(i);e.some(u=>u.id===c||ft(u.id,c))||o(i)}return t}function Ke(e){let n={};for(let t of e)t.effortLevels&&(n[t.id]=[...t.effortLevels],n[`${t.id}${j}`]=[...t.effortLevels]);return n}function pt(e={}){let n=new b({scan:e.fetchModels??(()=>at()),now:e.now,cacheTtlMs:e.cacheTtlMs??et,retryMs:e.retryMs??nt,key:t=>t.id,clone:t=>({...t,effortLevels:t.effortLevels?[...t.effortLevels]:null}),logFailure:t=>He.info(`Anthropic model discovery failed: ${t}`)});return{get:()=>n.get(),ensure:(t=tt)=>n.ensure(t)}}var Q=pt();var V=class{routes=new Map;claude;pi;piAccounts;constructor(n){this.claude=n.filter(t=>t.backend==="claude"),this.pi=n.filter(t=>t.backend==="pi"&&t.kind!=="account"),this.piAccounts=n.filter(t=>t.backend==="pi"&&t.kind==="account")}addClaude(n,t){if(this.claude.length===0)return;let r=this.claude.flatMap(i=>i.models??[]),o=this.add({backend:"claude",provider:null},"builtin",[...n,...r],t);o.modelConnections=kt(this.claude,o.models,new Set(n))}addPiScan(n){for(let[t,r]of mt(n)){let o=Object.fromEntries(r.filter(i=>i.thinkingLevels).map(i=>[i.model,i.thinkingLevels]));this.add({backend:"pi",provider:t},"pi",r.map(i=>i.model),o)}}addPiConnections(){for(let n of this.pi){let t=this.add({backend:"pi",provider:n.provider},"connection",n.models??[]);n.kind==="custom"&&(t.source="custom")}}build(){return[...this.routes.values()]}add(n,t,r,o={}){let i=JSON.stringify([n.backend,n.provider]),c=this.routes.get(i)??this.newRoute(n,t);this.routes.set(i,c);for(let s of r)c.models.includes(s)||c.models.push(s);for(let[s,u]of Object.entries(o))c.modelThinking[s]??=[...u];return c}newRoute(n,t){let r=n.backend==="claude"?this.claude.map(o=>o.id):[n.provider,...this.piAccounts.filter(o=>o.provider===n.provider).map(o=>o.id)];return{...n,connections:r,models:[],source:t,modelThinking:{},modelConnections:{}}}};function mt(e){let n=new Map;for(let t of e){let r=n.get(t.provider)??[];r.some(o=>o.model===t.model)||r.push(t),n.set(t.provider,r)}return n}function ht(e,n,t,r){return e.models?e.models.includes(n):r.has(n)||!t.some(o=>o.models?.includes(n))}function kt(e,n,t){let r={};for(let o of n){let i=e.filter(c=>ht(c,o,e,t));i.length>0&&i.length<e.length&&(r[o]=i.map(c=>c.id))}return r}function gt(){return{connections:()=>$.list(),claudeModels:{get:()=>Q.get(),ensure:()=>Q.ensure()},piModels:{peek:()=>H.peekModels(),ensure:()=>H.ensureModels(),rescan:()=>H.rescan()}}}function vt(){return{claude:[...F.claude],pi:[...F.pi]}}function $e(e,n,t){let r=new V(e),o=Fe(n,D);return r.addClaude(o,Ke(n)),r.addPiScan(t),r.addPiConnections(),{routes:r.build(),piPending:t.length===0,thinkingLevels:vt()}}function yt(e={}){let n={...gt(),...e},t=o=>o.some(i=>i.backend==="claude"),r=async o=>{let i=n.connections(),[c,s]=await Promise.all([t(i)?n.claudeModels.ensure():Promise.resolve([]),o()]);return $e(i,c,s)};return{load:()=>r(()=>n.piModels.ensure()),reload:()=>r(()=>n.piModels.rescan?n.piModels.rescan():n.piModels.ensure()),peek(){let o=n.connections(),i=t(o)?n.claudeModels.get():[];return $e(o,i,n.piModels.peek())}}}var je=yt();function Ve(e,n){return e.routes.find(t=>t.backend===n.backend&&t.provider===n.provider)}function Be(e,n){return Ve(e,n)?.modelThinking[n.model]??e.thinkingLevels[n.backend]}function J(e,n){let t=Ve(e,{backend:"claude",provider:null});return t?t.modelConnections[n]??t.connections:[]}function ro(e,n){return e.routes.filter(t=>t.models.includes(n)).map(t=>({backend:t.backend,provider:t.provider,model:n}))}var ee=m("selection");function Ye(e){let n=null,t=e.catalog??(()=>je.peek());return{inventory:e.inventory??$,catalog:()=>n??=t(),memory:e.memory,defaults:e.defaults}}function At(e){return e.request??e.session??e.draft??e.defaults.selection()}function _t(e,n,t){if(!(e.backend!==void 0&&e.model===void 0&&e.provider===void 0)&&(e.backend===void 0||e.backend===n?.backend))return n;let o=t.defaults.selection();if(o?.backend===e.backend)return o;let i=t.defaults.forBackend(e.backend);return i?{...i,thinking:t.memory()[I(i)]?.thinking??null,connection:null}:null}var Ct=/^[a-zA-Z0-9_-]+$/;function Et(e,n){let t=e.backend??n?.backend,r=e.model??n?.model;if(!t||r===void 0)return{ok:!1,reason:"no-model-for-backend"};let o=e.provider!==void 0?e.provider:t==="claude"?null:n?.provider??null;return typeof r!="string"||!r.trim()?{ok:!1,reason:"invalid-model"}:(t==="claude"?o===null:t==="pi"&&typeof o=="string"&&Ct.test(o))?{ok:!0,value:{backend:t,provider:o,model:r}}:{ok:!1,reason:"provider-not-supported"}}function ne(e,n){return!!e&&I(e)===I(n)}function bt(e,n,t,r,o){return ne(n,r)&&(t||e.model===void 0)?n.thinking:o.memory()[I(r)]?.thinking??null}function Tt(e,n,t,r,o){let i=bt(e,n,t,r,o),c=ne(n,r),s=e.thinking!==void 0&&!(c&&e.thinking===i),u=s?e.thinking:i;if(u===null)return{ok:!0,value:null};let h=Be(o.catalog(),r);return h.includes(u)?{ok:!0,value:u}:s?{ok:!1,reason:"invalid-thinking",allowed:h}:{ok:!0,value:null}}function Ot(e){return e.inventory.claudeConnections().map(n=>n.id)}function It(e,n){return!e||e.backend!==n.backend||n.backend==="pi"&&e.provider!==n.provider?null:e.connection??null}function St(e,n,t,r){let o=It(n,t);return e.connection!==void 0&&e.connection!==o?wt(e.connection,t,r):t.backend==="pi"?{ok:!0,value:ze(o,t.provider,r)}:{ok:!0,value:Nt(o,ne(n,t),t.model,r)}}function Ge(e,n){return n.inventory.piAccounts(e).map(t=>t.id)}function wt(e,n,t){if(e===null)return{ok:!0,value:null};let r=n.backend==="pi"?[n.provider,...Ge(n.provider,t)]:Ot(t);return r.includes(e)?{ok:!0,value:e===n.provider?null:e}:{ok:!1,reason:"invalid-connection",allowed:r}}function Nt(e,n,t,r){return e===null?null:r.inventory.findClaude(e)?n||J(r.catalog(),t).includes(e)?e:null:(ee.warn(`Connection '${e}' no longer exists; the selection falls back to the default connection`),null)}function ze(e,n,t){return e===null||Ge(n,t).includes(e)?e:(ee.warn(`Account '${e}' is not signed in to ${n}; the selection falls back to its default login`),null)}function Xe(e,n){if(e.backend==="pi")return ze(e.connection,e.provider??"",n);if(e.connection&&n.inventory.findClaude(e.connection))return e.connection;e.connection&&ee.warn(`Connection '${e.connection}' no longer exists; using the default connection`);let t=n.inventory.defaultClaudeConnection(),r=J(n.catalog(),e.model);return t!==null&&r.includes(t)?t:r[0]??t}function Z(e,n){let t=e;return{ok:!1,reason:t.reason,...t.allowed?{allowed:t.allowed}:{},base:n}}function lo(e,n={}){let t=Ye(e),r=At(e),o=_t(n,r,t),i=Et(n,o);if(!i.ok)return Z(i,r);let c=Tt(n,o,o===r,i.value,t);if(!c.ok)return Z(c,r);let s=St(n,o,i.value,t);if(!s.ok)return Z(s,r);let u={...i.value,thinking:c.value,connection:s.value};return{ok:!0,selection:u,effective:{...u,connection:Xe(u,t)},base:r}}function ao(e,n={}){let t=Ye({...n,defaults:xt,memory:()=>({})}),r={backend:"claude",provider:null,model:e.model??"",thinking:null,connection:e.connection};return Xe(r,t)}var xt={selection:()=>null,forBackend:()=>null};export{ve as a,Ut as b,Ht as c,Ft as d,A as e,q as f,Fe as g,Q as h,Ar as i,Tr as j,H as k,I as l,Pn as m,Dn as n,Ir as o,Sr as p,K as q,Rr as r,Lr as s,E as t,Yt as u,Gt as v,zt as w,Xt as x,qt as y,Zt as z,O as A,er as B,nr as C,tr as D,bn as E,fr as F,Tn as G,we as H,pr as I,mr as J,Wn as K,$ as L,je as M,Ve as N,J as O,ro as P,lo as Q,ao as R};
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as n}from"./chunk-6R73ICDB.js";var a=function(_,E){return typeof _=="string"&&/^\.\.?\//.test(_)?_.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(e,I,t,i,r){return I?E?".jsx":".js":t&&(!i||!r)?e:t+i+"."+r.toLowerCase()+"js"}):_},A=null,s=null,N=null,O=_=>import(a(_)),T="node:fs",c="node:os",K="node:path";typeof process<"u"&&(process.versions?.node||process.versions?.bun)&&(O(T).then(_=>{A=_.existsSync}),O(c).then(_=>{s=_.homedir}),O(K).then(_=>{N=_.join}));var P="ANTHROPIC_AUTH_TOKEN",C="ANTHROPIC_OAUTH_TOKEN",R="ANTHROPIC_API_KEY",d="ANTHROPIC_FEDERATION_RULE_ID",p="ANTHROPIC_ORGANIZATION_ID",L="ANTHROPIC_SERVICE_ACCOUNT_ID",S="ANTHROPIC_IDENTITY_TOKEN_FILE",D="ANTHROPIC_WORKSPACE_ID",o=null;function l(_){let E=_?.GOOGLE_APPLICATION_CREDENTIALS;if(E)return A?A(E):!1;if(o===null){if(!A||!s||!N)return typeof process<"u"&&(process.versions?.node||process.versions?.bun)||(o=!1),!1;let e=n("GOOGLE_APPLICATION_CREDENTIALS",_);e?o=A(e):o=A(N(s(),".config","gcloud","application_default_credentials.json"))}return o}function u(_){if(_==="github-copilot")return["COPILOT_GITHUB_TOKEN"];if(_==="anthropic")return[P,C,R];let e={"ant-ling":"ANT_LING_API_KEY","qwen-token-plan":"QWEN_TOKEN_PLAN_API_KEY","qwen-token-plan-cn":"QWEN_TOKEN_PLAN_CN_API_KEY","qwen-token-plan-individual":"QWEN_TOKEN_PLAN_API_KEY",openai:"OPENAI_API_KEY",azure:"AZURE_OPENAI_API_KEY",nvidia:"NVIDIA_API_KEY",deepseek:"DEEPSEEK_API_KEY",google:"GEMINI_API_KEY","google-vertex":"GOOGLE_CLOUD_API_KEY",groq:"GROQ_API_KEY",cerebras:"CEREBRAS_API_KEY",xai:"XAI_API_KEY",typesafe:"TYPESAFE_API_KEY",radius:"RADIUS_API_KEY",openrouter:"OPENROUTER_API_KEY","vercel-ai-gateway":"AI_GATEWAY_API_KEY",zai:"ZAI_API_KEY","zai-coding-cn":"ZAI_CODING_CN_API_KEY",mistral:"MISTRAL_API_KEY",minimax:"MINIMAX_API_KEY","minimax-cn":"MINIMAX_CN_API_KEY",moonshotai:"MOONSHOT_API_KEY","moonshotai-cn":"MOONSHOT_API_KEY",huggingface:"HF_TOKEN",fireworks:"FIREWORKS_API_KEY",together:"TOGETHER_API_KEY",baseten:"BASETEN_API_KEY",opencode:"OPENCODE_API_KEY","opencode-go":"OPENCODE_API_KEY","kimi-coding":"KIMI_API_KEY",meta:"META_API_KEY","cloudflare-workers-ai":"CLOUDFLARE_API_KEY","cloudflare-ai-gateway":"CLOUDFLARE_API_KEY",xiaomi:"XIAOMI_API_KEY","xiaomi-token-plan-cn":"XIAOMI_TOKEN_PLAN_CN_API_KEY","xiaomi-token-plan-ams":"XIAOMI_TOKEN_PLAN_AMS_API_KEY","xiaomi-token-plan-sgp":"XIAOMI_TOKEN_PLAN_SGP_API_KEY"}[_];return e?[e]:void 0}function f(_,E){let e=u(_);if(!e)return;let I=e.filter(t=>!!n(t,E));return I.length>0?I:void 0}function x(_,E){let e=f(_,E);if(e?.[0]){let I=_==="anthropic"?e.find(t=>t!==P):e[0];if(I)return n(I,E)}if(_==="google-vertex"){let I=l(E),t=!!(n("GOOGLE_CLOUD_PROJECT",E)||n("GCLOUD_PROJECT",E)),i=!!n("GOOGLE_CLOUD_LOCATION",E);if(I&&t&&i)return"<authenticated>"}if(_==="amazon-bedrock"&&(n("AWS_PROFILE",E)||n("AWS_ACCESS_KEY_ID",E)&&n("AWS_SECRET_ACCESS_KEY",E)||n("AWS_BEARER_TOKEN_BEDROCK",E)||n("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI",E)||n("AWS_CONTAINER_CREDENTIALS_FULL_URI",E)||n("AWS_WEB_IDENTITY_TOKEN_FILE",E)))return"<authenticated>"}export{P as a,C as b,R as c,d,p as e,L as f,S as g,D as h,f as i,x as j};
@@ -1,11 +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,e as pe,h as we,l as me,m as _e,n as z,o as b,p as ge,r as x,s as W,t as ye,u as Se,v as ke}from"./chunk-Y3GFB5XM.js";import{a as st}from"./chunk-EQIMHXC4.js";import{a as le,b as he}from"./chunk-IRWZ7UPF.js";import{f as fe}from"./chunk-RA6HKFBV.js";import{E as ue,H as de,M as q}from"./chunk-QUUEQRIT.js";import{e as it}from"./chunk-WHC7AYZD.js";import{homedir as Je}from"node:os";import{basename as Pt,join as Ot,resolve as It}from"node:path";import{setTimeout as Lt}from"node:timers/promises";import{pathToFileURL as $t}from"node:url";import{createServer as ot}from"node:http";function at(t){return t.ok?"Authorization complete. You may close this window.":t.details?`${t.message}
5
-
6
- ${t.details}`:t.message}var S=class t{redirectUrl;server;paths;timeoutMs;renderPage;pending=new Map;constructor(e,r,n,s,i){this.server=e,this.redirectUrl=r,this.paths=n,this.timeoutMs=s,this.renderPage=i}static async listen(e={}){let r=e.host??"127.0.0.1",n=e.redirectHost??r,s=e.path??"/callback",i,o=ot((c,u)=>i?.handle(c.url??"/",u));await new Promise((c,u)=>{o.once("error",u),o.listen(e.port??0,r,()=>{o.off("error",u),c()})});let a=o.address();if(!a||typeof a=="string")throw new Error("OAuth callback server did not bind to TCP");return i=new t(o,`http://${n.includes(":")?`[${n}]`:n}:${a.port}${s}`,[s,...e.extraPaths??[]],e.timeoutMs??5*6e4,e.renderPage),i}waitForCallback(e,r){if(this.pending.has(e))throw new Error("OAuth state is already pending");return new Promise((n,s)=>{let i=setTimeout(()=>{this.pending.delete(e),s(new Error("OAuth callback timed out"))},this.timeoutMs);this.pending.set(e,{resolve:n,reject:s,timer:i,path:r})})}async close(){for(let e of this.pending.values())clearTimeout(e.timer),e.reject(new Error("OAuth callback server closed"));this.pending.clear(),await new Promise((e,r)=>{this.server.close(n=>n?r(n):e())})}reply(e,r,n){this.renderPage?(e.writeHead(r,{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}),e.end(this.renderPage(n))):e.writeHead(r,{"content-type":"text/plain; charset=utf-8"}).end(at(n))}handle(e,r){let n=new URL(e,this.redirectUrl);if(!this.paths.includes(n.pathname)){this.reply(r,404,{ok:!1,message:"Not found"});return}let s=n.searchParams.get("state"),i=s?this.pending.get(s):void 0;if(!s||!i){this.reply(r,400,{ok:!1,message:"Invalid or expired OAuth state"});return}if(clearTimeout(i.timer),this.pending.delete(s),i.path!==void 0&&n.pathname!==i.path){i.reject(new Error("The authorization response arrived on another redirect URI")),this.reply(r,400,{ok:!1,message:"Unexpected redirect URI"});return}let o=n.searchParams.get("error");if(o){let u=n.searchParams.get("error_description")??o;i.reject(new Error(u)),this.reply(r,200,{ok:!1,message:"Authorization failed. You may close this window.",details:u});return}let a=n.searchParams.get("code");if(!a){i.reject(new Error("OAuth callback did not include an authorization code")),this.reply(r,400,{ok:!1,message:"Missing authorization code"});return}let c=n.searchParams.get("iss");i.resolve({code:a,state:s,...c?{iss:c}:{}}),this.reply(r,200,{ok:!0})}};var p=class extends Error{code;errorUri;constructor(e,r,n){super(r||e),this.name="OAuthError",this.code=e,this.errorUri=n}},y=class extends Error{expected;received;constructor(e,r){let n=s=>s===void 0?"none":JSON.stringify(s);super(`OAuth issuer mismatch: expected ${n(e)}, received ${n(r)}`),this.name="OAuthIssuerMismatchError",this.expected=e,this.received=r}},k=class extends Error{endpoint;constructor(e){super(`Refusing to send OAuth credentials to non-HTTPS endpoint ${e}`),this.name="OAuthInsecureEndpointError",this.endpoint=e}},M=class extends Error{status;body;constructor(e,r){super(`OAuth dynamic client registration failed with status ${e}: ${r}`),this.name="OAuthRegistrationError",this.status=e,this.body=r}},f=class extends Error{constructor(){super("MCP OAuth authorization requires user interaction"),this.name="McpOAuthAuthorizationRequiredError"}};function O(t,e){if(!z(t))throw new Error(`Invalid ${e}`);return t}function I(t){return Object.fromEntries(Object.entries(t).filter(([,e])=>e!==void 0))}function E(t,e){if(typeof t!="string"||t.length===0)throw new Error(`Invalid ${e}`);return t}function J(t){return t==null||t===""}function P(t,e){if(!J(t))return E(t,e)}function m(t,e){if(t!=null){if(!Array.isArray(t)||t.some(r=>typeof r!="string"))throw new Error(`Invalid ${e}`);return[...t]}}function v(t,e){let r=E(t,e);if(!URL.canParse(r))throw new Error(`Invalid ${e}`);let n=new URL(r);if(["javascript:","data:","vbscript:"].includes(n.protocol))throw new Error(`Invalid ${e}`);return r}function ct(t,e){return J(t)?void 0:v(t,e)}function ve(t){let e=O(t,"OAuth protected resource metadata");return I({...e,resource:v(e.resource,"OAuth protected resource metadata resource"),authorization_servers:m(e.authorization_servers,"authorization_servers")?.map(r=>v(r,"authorization server URL")),scopes_supported:m(e.scopes_supported,"scopes_supported")})}function Y(t){let e=O(t,"authorization server metadata"),r=m(e.response_types_supported,"response_types_supported");if(!r)throw new Error("Invalid response_types_supported");return I({...e,issuer:v(e.issuer,"authorization server issuer"),authorization_endpoint:v(e.authorization_endpoint,"authorization endpoint"),token_endpoint:v(e.token_endpoint,"token endpoint"),registration_endpoint:ct(e.registration_endpoint,"registration endpoint"),scopes_supported:m(e.scopes_supported,"scopes_supported"),response_types_supported:r,grant_types_supported:m(e.grant_types_supported,"grant_types_supported"),token_endpoint_auth_methods_supported:m(e.token_endpoint_auth_methods_supported,"token_endpoint_auth_methods_supported"),code_challenge_methods_supported:m(e.code_challenge_methods_supported,"code_challenge_methods_supported"),client_id_metadata_document_supported:typeof e.client_id_metadata_document_supported=="boolean"?e.client_id_metadata_document_supported:void 0,authorization_response_iss_parameter_supported:typeof e.authorization_response_iss_parameter_supported=="boolean"?e.authorization_response_iss_parameter_supported:void 0})}function Ue(t){let e=O(t,"OAuth token response"),r=J(e.expires_in)?void 0:Number(e.expires_in);if(r!==void 0&&!Number.isFinite(r))throw new Error("Invalid expires_in");return I({access_token:E(e.access_token,"access_token"),token_type:E(e.token_type,"token_type"),expires_in:r,scope:P(e.scope,"scope"),refresh_token:P(e.refresh_token,"refresh_token"),id_token:P(e.id_token,"id_token")})}function Re(t){let e=O(t,"OAuth client registration response");return I({...e,client_id:E(e.client_id,"client_id"),client_secret:P(e.client_secret,"client_secret"),client_id_issued_at:typeof e.client_id_issued_at=="number"?e.client_id_issued_at:void 0,client_secret_expires_at:typeof e.client_secret_expires_at=="number"?e.client_secret_expires_at:void 0,redirect_uris:m(e.redirect_uris,"redirect_uris")??[]})}function $(t){t?.body?.cancel().catch(()=>{})}function Ae(t){return t>=400&&t<500||t===502}function Me(t){return t.endsWith("/")?t.slice(0,-1):t}function L(t,e){let r=t.match(new RegExp(String.raw`(?:^|[,\s])${e}=(?:"([^"]*)"|([^\s,]+))`,"i"));return r?.[1]||r?.[2]||void 0}function H(t){if(!t)return{};let e=t.trimStart().split(/\s+/,1)[0]?.toLowerCase();if(e!=="bearer"&&e!=="dpop")return{};let r=L(t,"resource_metadata"),n;if(r)try{n=new URL(r)}catch{}return{resourceMetadataUrl:n,scope:L(t,"scope"),error:L(t,"error"),errorDescription:L(t,"error_description")}}async function D(t,e,r,n){return e(t,{headers:{Accept:"application/json","MCP-Protocol-Version":r},signal:n})}async function Ee(t,e={}){let r=new URL(t),n=e.fetch??globalThis.fetch,s=e.protocolVersion??b,i=await D(e.resourceMetadataUrl?new URL(e.resourceMetadataUrl):new URL(`/.well-known/oauth-protected-resource${Me(r.pathname)}`,r.origin),n,s,e.signal);if(!e.resourceMetadataUrl&&r.pathname!=="/"&&Ae(i.status)&&($(i),i=await D(new URL("/.well-known/oauth-protected-resource",r.origin),n,s,e.signal)),!i.ok)throw $(i),new Error(`HTTP ${i.status} loading OAuth protected resource metadata`);return ve(await i.json())}function Te(t){let e=new URL(t),r=Me(e.pathname),n=[{url:new URL(`/.well-known/oauth-authorization-server${r}`,e.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${r}`,e.origin),type:"oidc"}];return r&&n.push({url:new URL(`${r}/.well-known/openid-configuration`,e.origin),type:"oidc"}),n}async function N(t,e={}){let r=e.fetch??globalThis.fetch;for(let{url:n}of Te(t)){let s=await D(n,r,e.protocolVersion??b,e.signal);if(!s.ok){if($(s),Ae(s.status))continue;throw new Error(`HTTP ${s.status} loading authorization server metadata from ${n}`)}let i=Y(await s.json());if(!e.skipIssuerValidation){let o=String(t),a=c=>c.endsWith("/")?c.slice(0,-1):c;if(a(i.issuer)!==a(o))throw new y(o,i.issuer)}return i}}async function Z(t,e={}){let r;try{r=await Ee(t,{resourceMetadataUrl:e.resourceMetadataUrl,fetch:e.fetch,signal:e.signal})}catch(s){if(s instanceof TypeError)throw s}if(e.authorizationServerMetadataUrl){let s=e.authorizationServerMetadataUrl,i=await D(s,e.fetch??globalThis.fetch,b,e.signal);if(!i.ok)throw $(i),new Error(`HTTP ${i.status} loading authorization server metadata from ${s}`);let o=Y(await i.json());return{authorizationServerUrl:o.issuer,authorizationServerMetadata:o,resourceMetadata:r}}let n=r?.authorization_servers?.[0]??String(new URL("/",t));return{authorizationServerUrl:n,authorizationServerMetadata:await N(n,{fetch:e.fetch,skipIssuerValidation:e.skipIssuerValidation,signal:e.signal}),resourceMetadata:r}}function Ce(t){let e=new URL(t);return e.hash="",e}function G(t,e){if(!e)return;let r=Ce(t),n=new URL(e.resource);if(r.origin!==n.origin)throw new Error(`Protected resource ${e.resource} does not match MCP server ${r}`);let s=r.pathname.endsWith("/")?r.pathname:`${r.pathname}/`,i=n.pathname.endsWith("/")?n.pathname:`${n.pathname}/`;if(!s.startsWith(i))throw new Error(`Protected resource ${e.resource} does not match MCP server ${r}`);return e.resource}function be(t){return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t==="::1"}function ut(t){return t.some(r=>{if(!URL.canParse(r))return!1;let n=new URL(r);return n.protocol!=="http:"&&n.protocol!=="https:"||be(n.hostname)})?"native":"web"}function xe(t){let e=new URL(t);if(e.protocol!=="https:"&&!be(e.hostname))throw new k(e.href);return e}function dt(t,e){let r="token_endpoint_auth_method"in t?t.token_endpoint_auth_method:void 0;return r&&["client_secret_basic","client_secret_post","none"].includes(r)&&(e.length===0||e.includes(r))?r:e.length===0?t.client_secret?"client_secret_basic":"none":t.client_secret&&e.includes("client_secret_basic")?"client_secret_basic":t.client_secret&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":t.client_secret?"client_secret_post":"none"}function lt(t,e,r,n){if(t==="client_secret_basic"){if(!e.client_secret)throw new Error("client_secret_basic requires a client secret");r.set("Authorization",`Basic ${Buffer.from(`${e.client_id}:${e.client_secret}`).toString("base64")}`)}else n.set("client_id",e.client_id),t==="client_secret_post"&&e.client_secret&&n.set("client_secret",e.client_secret)}async function ht(){let t=crypto.getRandomValues(new Uint8Array(32)),e=Buffer.from(t).toString("base64url"),r=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return{verifier:e,challenge:Buffer.from(r).toString("base64url")}}async function Pe(t,e){let r=e.metadata;if(r&&!r.response_types_supported.includes("code"))throw new Error("Authorization server does not support authorization codes");if(r?.code_challenge_methods_supported&&!r.code_challenge_methods_supported.includes("S256"))throw new Error("Authorization server does not support PKCE S256");let n=new URL(r?.authorization_endpoint??new URL("/authorize",t)),{verifier:s,challenge:i}=await ht();return n.searchParams.set("response_type","code"),n.searchParams.set("client_id",e.clientInformation.client_id),n.searchParams.set("code_challenge",i),n.searchParams.set("code_challenge_method","S256"),n.searchParams.set("redirect_uri",String(e.redirectUrl)),e.state&&n.searchParams.set("state",e.state),e.scope&&n.searchParams.set("scope",e.scope),e.scope?.split(/\s+/).includes("offline_access")&&n.searchParams.set("prompt","consent"),e.resource&&n.searchParams.set("resource",e.resource),{authorizationUrl:n,codeVerifier:s}}async function Oe(t,e,r){let n=xe(e.metadata?.token_endpoint??new URL("/token",t)),s=new Headers({Accept:"application/json","content-type":"application/x-www-form-urlencoded"});e.resource&&r.set("resource",e.resource),e.addClientAuthentication?await e.addClientAuthentication(s,r,n,e.metadata):lt(dt(e.clientInformation,e.metadata?.token_endpoint_auth_methods_supported??[]),e.clientInformation,s,r);let i=await(e.fetch??globalThis.fetch)(n,{method:"POST",headers:s,body:r,signal:e.signal}),o=await i.text(),a;try{a=JSON.parse(o)}catch{}if(z(a)&&typeof a.error=="string")throw new p(a.error,typeof a.error_description=="string"?a.error_description:a.error,typeof a.error_uri=="string"?a.error_uri:void 0);if(!i.ok)throw new p("server_error",`HTTP ${i.status}: ${o}`);return Ue(a)}async function Ie(t,e){let r=e.metadata?.registration_endpoint;if(e.metadata&&!r)throw new Error("Authorization server does not support dynamic client registration");let n=await(e.fetch??globalThis.fetch)(new URL(r??new URL("/register",t)),{method:"POST",headers:{Accept:"application/json","content-type":"application/json"},body:JSON.stringify({...e.clientMetadata,application_type:e.clientMetadata.application_type??ut(e.clientMetadata.redirect_uris),...e.scope?{scope:e.scope}:{}}),signal:e.signal});if(!n.ok)throw new M(n.status,await n.text());return Re(await n.json())}async function Le(t,e){return Oe(t,e,new URLSearchParams({grant_type:"authorization_code",code:e.code,code_verifier:e.codeVerifier,redirect_uri:String(e.redirectUrl)}))}async function $e(t,e){let r=await Oe(t,e,new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken}));return{refresh_token:e.refreshToken,...r}}function ze(t,e){return t.scope===void 0&&e?{...t,scope:e}:t}function X(t,e){if(!e)return;let r=[t,e].flatMap(n=>n?.split(/\s+/).filter(Boolean)??[]);return[...new Set(r)].join(" ")}async function Q(t,e){let r=e.authorizationServerMetadataUrl&&xe(e.authorizationServerMetadataUrl),n=r?void 0:await t.discoveryState?.(),s=n?.authorizationServerUrl?{authorizationServerUrl:n.authorizationServerUrl,authorizationServerMetadata:n.authorizationServerMetadata??await N(n.authorizationServerUrl,{fetch:e.fetch,skipIssuerValidation:e.skipIssuerValidation,signal:e.signal}),resourceMetadata:n.resourceMetadata}:await Z(e.serverUrl,{resourceMetadataUrl:e.resourceMetadataUrl,authorizationServerMetadataUrl:r,fetch:e.fetch,skipIssuerValidation:e.skipIssuerValidation,signal:e.signal});r||await t.saveDiscoveryState?.({...s,...e.resourceMetadataUrl?{resourceMetadataUrl:e.resourceMetadataUrl.href}:{}});let i=s.authorizationServerMetadata,o=G(e.serverUrl,s.resourceMetadata),a=e.scope||s.resourceMetadata?.scopes_supported?.join(" ")||t.clientMetadata.scope,c=await t.clientInformation(),u=c?void 0:t.clientMetadataDocument?.(i);if(u){let d=new URL(u.url);if(d.protocol!=="https:"||d.pathname==="/")throw new Error("Invalid OAuth client metadata URL")}let l=c??(u&&{client_id:u.url});if(!l){if(e.authorizationCode)throw new Error("OAuth client information is missing during code exchange");if(!t.saveClientInformation)throw new Error("OAuth client information cannot be persisted");l=await Ie(s.authorizationServerUrl,{metadata:i,clientMetadata:t.clientMetadata,scope:a,fetch:e.fetch,signal:e.signal}),await t.saveClientInformation(l)}let w=u?.redirectUrl??t.redirectUrl,_={metadata:i,clientInformation:l,resource:o,addClientAuthentication:t.addClientAuthentication,fetch:e.fetch,signal:e.signal};if(e.authorizationCode){let d=e.iss;if((d!==void 0||i?.authorization_response_iss_parameter_supported)&&d!==i?.issuer)throw new y(i?.issuer,d);let B=await Le(s.authorizationServerUrl,{..._,code:e.authorizationCode,codeVerifier:await t.codeVerifier(),redirectUrl:w});return await t.saveTokens(ze(B,a)),"AUTHORIZED"}let h=e.skipRefresh?void 0:await t.tokens();if(h?.refresh_token)try{let d=await $e(s.authorizationServerUrl,{..._,refreshToken:h.refresh_token});return await t.saveTokens(ze(d,h.scope)),"AUTHORIZED"}catch(d){if(e.signal?.aborted||d instanceof k||d instanceof p&&d.code!=="server_error")throw d}let R=await t.state?.(),A=await Pe(s.authorizationServerUrl,{metadata:i,clientInformation:l,redirectUrl:w,scope:a,state:R,resource:o});return await t.saveCodeVerifier(A.codeVerifier),await t.redirectToAuthorization(A.authorizationUrl),"REDIRECT"}async function T(t,e){try{return await Q(t,e)}catch(r){if(r instanceof p&&["invalid_client","unauthorized_client"].includes(r.code))return await t.invalidateCredentials?.("all"),Q(t,e);if(r instanceof p&&r.code==="invalid_grant")return await t.invalidateCredentials?.("tokens"),Q(t,e);throw r}}var j=class{value;load(){return this.value===void 0?void 0:structuredClone(this.value)}save(e){this.value=structuredClone(e)}},C=class{redirectUrl;clientMetadata;clientMetadataDocument;serverUrl;configuredClient;store;onRedirect;writes=Promise.resolve();constructor(e){this.serverUrl=String(new URL(e.serverUrl)),this.redirectUrl=String(e.redirectUrl),this.clientMetadata={...e.clientMetadata,redirect_uris:e.clientMetadata.redirect_uris??[this.redirectUrl],grant_types:e.clientMetadata.grant_types??["authorization_code","refresh_token"],response_types:e.clientMetadata.response_types??["code"],token_endpoint_auth_method:e.clientMetadata.token_endpoint_auth_method??(e.clientSecret?"client_secret_post":"none")},this.clientMetadataDocument=e.clientMetadataDocument,this.configuredClient=e.clientId?{client_id:e.clientId,...e.clientSecret?{client_secret:e.clientSecret}:{}}:void 0,this.store=e.store??new j,this.onRedirect=e.onRedirect}async state(){let e=(await this.load()).oauthState;if(e)return e;let r=Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("hex");return await this.update(n=>({...n,oauthState:r})),r}async clientInformation(){return this.configuredClient??(await this.load()).clientInformation}async saveClientInformation(e){this.configuredClient||await this.update(r=>({...r,clientInformation:e}))}async tokens(){return(await this.load()).tokens}async saveTokens(e){let r=e.expires_in===void 0?void 0:Date.now()+e.expires_in*1e3;await this.update(n=>{let s={...n,tokens:e};return r===void 0?delete s.tokensExpireAt:s.tokensExpireAt=r,s})}async redirectToAuthorization(e){await this.onRedirect(e)}async saveCodeVerifier(e){await this.update(r=>({...r,codeVerifier:e}))}async codeVerifier(){let e=(await this.load()).codeVerifier;if(!e)throw new Error("No OAuth PKCE code verifier is stored");return e}async invalidateCredentials(e){await this.update(r=>{let n={...r};return(e==="all"||e==="client")&&delete n.clientInformation,(e==="all"||e==="tokens")&&(delete n.tokens,delete n.tokensExpireAt),(e==="all"||e==="verifier")&&delete n.codeVerifier,(e==="all"||e==="discovery")&&delete n.discovery,e==="all"&&delete n.oauthState,n})}async saveDiscoveryState(e){await this.update(r=>({...r,discovery:e}))}async discoveryState(){return(await this.load()).discovery}async load(){return await this.writes,this.own(await this.store.load())}async update(e){this.writes=this.writes.then(async()=>{await this.store.save(e(this.own(await this.store.load())))}),await this.writes}own(e){return e?.serverUrl===this.serverUrl?e:{serverUrl:this.serverUrl}}};import{createHash as Ne}from"node:crypto";import{mkdirSync as ft}from"node:fs";import{join as De}from"node:path";var je=it(st(),1);var ne="127.0.0.1",V="/callback",He="https://pi.dev/oauth",pt=`http://${ne}${V}`,wt=3e4,mt=15e3,_t=2e4,gt=25e3,ee=100;function Fe(t){let e=new URL(t.callbackUrl??`http://${ne}${V}`),r=e.hostname.replace(/^\[|\]$/g,""),n=e.port?Number(e.port):t.callbackPort,s;return e.port?s=t.callbackUrl:n!==void 0&&(e.port=String(n),s=e.href),{host:r==="localhost"?ne:r,redirectHost:r,port:n,path:e.pathname,fixedRedirectUrl:s}}function yt(...t){let e=[...new Set(t.flatMap(r=>r?.split(/\s+/).filter(Boolean)??[]))];return e.length>0?e.join(" "):void 0}function F(t){if(!t?.trim())return{};let e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function te(t){return`${JSON.stringify(t,null,2)}
7
- `}function re(t,e){let r=String(new URL(e));return{key:`${fe(t)}|${r}`,legacyKey:r}}var ie=class{backend;lockDir;constructor(e,r){this.backend=e??new we(De(q(),"mcp-auth.json")),this.lockDir=e?r:q()}forServer(e,r){let{key:n,legacyKey:s}=re(e,r);return{load:()=>this.backend.withLock(i=>{let o=F(i);return o[n]||!o[s]?{result:o[n]}:(o[n]=o[s],delete o[s],{result:o[n],next:te(o)})}),save:i=>this.write(o=>{o[n]=i}),withRefreshLock:i=>this.withRefreshLock(n,i)}}async withRefreshLock(e,r){if(!this.lockDir)return r();ft(this.lockDir,{recursive:!0,mode:448});let n=Ne("sha256").update(e).digest("hex").slice(0,16),s=await je.default.lock(De(this.lockDir,`mcp-auth-refresh-${n}`),{realpath:!1,stale:_t,retries:{retries:gt/ee,factor:1,minTimeout:ee,maxTimeout:ee},onCompromised:()=>{}});try{return await r()}finally{await s().catch(()=>{})}}tokens(e,r){let{key:n,legacyKey:s}=re(e,r),i=this.backend.withLock(o=>({result:F(o)}));return(i[n]??i[s])?.tokens}remove(e,r){let{key:n,legacyKey:s}=re(e,r);return this.backend.withLock(i=>{let o=F(i),a=n in o?n:s in o?s:void 0;return a?(delete o[a],{result:!0,next:te(o)}):{result:!1}})}write(e){this.backend.withLock(r=>{let n=F(r);return e(n),{result:void 0,next:te(n)}})}};function Ve(t=globalThis.fetch){return(e,r)=>{let n=AbortSignal.timeout(mt);return t(e,{...r,signal:r?.signal?AbortSignal.any([r.signal,n]):n})}}function se(t){return t&&"redirect_uris"in t?t.redirect_uris:[]}function Be(t){let e=new URL(t);return e.hash="",Ne("sha256").update(e.href).digest().subarray(0,9).toString("base64url")}function St(t,e,r){if(!r?.client_id_metadata_document_supported||!r.token_endpoint_auth_methods_supported?.includes("none"))throw new Error('The authorization server does not support Client ID Metadata Documents for public clients; remove oauth.clientRegistration "cimd"');if(r.authorization_response_iss_parameter_supported)return{url:`${He}/client.json`,redirectUrl:e};let n=Be(t),s=new URL(e);return s.pathname=`${V}/${n}`,{url:`${He}/${n}/client.json`,redirectUrl:s.href}}function qe(t,e,r,n,s){return new C({serverUrl:t,redirectUrl:n,clientMetadata:{client_name:r.clientName??ue},clientMetadataDocument:r.clientRegistration==="cimd"?i=>St(t,n,i):void 0,clientId:r.clientId,clientSecret:r.clientSecret,store:e,onRedirect:s})}function Ke(t){let{serverUrl:e,store:r}=t,n,s=(i,o=globalThis.fetch,a)=>(n??=r.withRefreshLock(async()=>{let c=await r.load();if(c?.tokens?.access_token!==i)return;if(!c?.tokens?.refresh_token)throw new f;let u=t.settings(),l=Fe(u).fixedRedirectUrl??se(c.clientInformation)[0]??pt,w=qe(e,r,u,l,()=>{});if(await T(w,{serverUrl:e,resourceMetadataUrl:a?.resourceMetadataUrl,authorizationServerMetadataUrl:u.authServerMetadataUrl,scope:a?.scope,fetch:Ve(o)})==="REDIRECT")throw new f}).finally(()=>{n=void 0}),n);return{token:async()=>{await n?.catch(()=>{});let i=await r.load(),o=i?.tokens?.access_token;return!(i?.tokensExpireAt!==void 0&&i.tokensExpireAt-wt<=Date.now())||!i?.tokens?.refresh_token?o:(await s(o).catch(()=>{}),(await r.load())?.tokens?.access_token)},onUnauthorized:async i=>{let o=H(i.response.headers.get("www-authenticate"));if(t.onChallenge(o),o.error==="insufficient_scope")throw new f;await s(i.token,i.fetch,o)},settled:async()=>{await n?.catch(()=>{})}}}var U=class extends Error{constructor(){super("Sign-in cancelled"),this.name="McpSignInCancelledError"}};function kt(t,e,r){let n;try{n=new URL(t.trim())}catch{throw new Error("Expected the full redirect URL from the browser address bar")}if(n.origin!==r.origin||n.pathname!==r.pathname)throw new Error("The redirect URL does not match this sign-in's redirect URI");let s=n.searchParams.get("error");if(s)throw new Error(n.searchParams.get("error_description")??s);if(n.searchParams.get("state")!==e)throw new Error("The redirect URL belongs to a different sign-in");let i=n.searchParams.get("code");if(!i)throw new Error("The redirect URL does not contain an authorization code");return{code:i,iss:n.searchParams.get("iss")??void 0}}async function vt(t,e,r,n,s){let i=new AbortController,o=s?AbortSignal.any([i.signal,s]):i.signal,a=t.waitForCallback(e,r.pathname),c=n.promptForRedirectUrl(o).then(u=>{if(!u?.trim())throw new U;return kt(u,e,r)});try{return await Promise.race([a,c])}finally{i.abort(),a.catch(()=>{}),c.catch(()=>{})}}async function Ut(t,e,r,n){let s={host:t.host,redirectHost:t.redirectHost,path:t.path,extraPaths:e,renderPage:i=>i.ok?le("Signed in to the MCP server. You may now close this page."):he(i.message,i.details)};try{return await S.listen({...s,port:r??0})}catch(i){if(n||r===void 0)throw i;return S.listen(s)}}async function Rt(t){let{serverUrl:e,store:r,settings:n,signal:s}=t;if(s?.aborted)throw new U;let i=await r.load(),o=t.challenge?.error==="insufficient_scope",a=Fe(n),c=se(i?.clientInformation)[0],u=a.port??(c&&Number(new URL(c).port)||void 0),l=n.clientRegistration==="cimd",w=await Ut(a,l?[`${V}/${Be(e)}`]:[],u,a.port!==void 0),_=a.fixedRedirectUrl??w.redirectUrl;try{if(i){let g={...i};delete g.oauthState,n.clientId||(l?!i.clientInformation:se(i.clientInformation).includes(_))||(delete g.clientInformation,delete g.tokens,delete g.tokensExpireAt),await r.save(g)}let h,R=qe(e,r,n,_,g=>{h=g}),A={serverUrl:e,fetch:Ve(),signal:s,resourceMetadataUrl:t.challenge?.resourceMetadataUrl,authorizationServerMetadataUrl:n.authServerMetadataUrl,scope:yt(n.scope,o?X(i?.tokens?.scope,t.challenge?.scope):t.challenge?.scope)};if(await T(R,{...A,skipRefresh:o})==="AUTHORIZED")return;if(!h)throw new Error("OAuth flow did not produce an authorization URL");let B=await R.state(),tt=new URL(h.searchParams.get("redirect_uri")??_);t.prompt.showAuthorizationUrl(h);let{code:rt,iss:nt}=await vt(w,B,tt,t.prompt,s);await T(R,{...A,authorizationCode:rt,iss:nt})}catch(h){throw s?.aborted?new U:h}finally{await w.close()}}import{appendFileSync as At,mkdirSync as Mt,renameSync as Et,statSync as Tt}from"node:fs";import{dirname as Ct}from"node:path";var We=5*1024*1024;function zt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function bt(t){if(typeof t=="string")return t;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}function xt(t,e,r=new Date){let n=zt(e)?e:{data:e},s=typeof n.level=="string"?n.level:"info",i=typeof n.logger=="string"&&n.logger?` ${n.logger}:`:"",o=bt(n.data).replace(/\r?\n/g,`
8
- `);return`${r.toISOString()} [${t}] ${s}${i} ${o}
9
- `}var oe=class{path;size;constructor(e){this.path=e}write(e,r){let n=xt(e,r);try{this.size===void 0&&(Mt(Ct(this.path),{recursive:!0}),this.size=this.currentSize()),this.size>We&&(this.currentSize()>We&&Et(this.path,`${this.path}.1`),this.size=this.currentSize()),At(this.path,n),this.size+=Buffer.byteLength(n)}catch{}}currentSize(){try{return Tt(this.path).size}catch{return 0}}};var Dt=60,Ye=2e3,Ze=[250,1e3];function ae(t){return t instanceof Error?t.message:String(t)}function Ge(t){return t instanceof W?t.status===408||t.status===429||t.status>=500&&t.status!==501:t instanceof TypeError}function Qe(t){let e="url"in t.config?t.config.auth?.provider:void 0;return`MCP server "${t.name}" requires sign-in. Run ${e?`/login ${e}`:"/mcp"} to sign in.`}function Ht(t){let{config:e}=t;return!("url"in e)||e.auth?!1:!Object.keys(e.headers??{}).some(r=>r.toLowerCase()==="authorization")}function ce(t){return t==="~"?Je():t.startsWith("~/")||process.platform==="win32"&&t.startsWith("~\\")?Ot(Je(),t.slice(2)):t}function br(t,e,r){let{config:n,name:s}=t;if("url"in n)return new ke({url:n.url,headers:pe(n.headers,`MCP server "${s}"`),authProvider:r});let i={};for(let[o,a]of Object.entries(n.env??{}))i[o]=K(a,`MCP server "${s}" env "${o}"`);return new x({command:ce(n.command),args:n.args?.map(ce),cwd:It(e,ce(n.cwd??".")),env:i,stderr:"pipe"})}async function et(t,e){try{return await t()}catch(r){if(r instanceof _e&&r.code===me.methodNotFound)return e;throw r}}function Nt(t,e={}){return et(()=>t.listResourceTemplates(e),[])}var Xe=class{entry;state="connecting";error;tools=[];hasResources=!1;instructions;challenge;client;opening;shutdown=new AbortController;stderrTail;cwd;createTransport;authProvider;onTools;onChange;log;constructor(e){this.entry=e.entry,this.cwd=e.cwd,this.createTransport=e.createTransport,this.onTools=e.onTools,this.onChange=e.onChange,this.log=e.log;let r=this.oauthUrl,n="url"in this.entry.config?this.entry.config.auth?.provider:void 0;this.authProvider=r?Ke({serverUrl:r,store:e.credentials.forServer(this.entry.name,r),settings:()=>this.oauthSettings(),onChallenge:s=>{this.challenge=s}}):n?{token:async()=>e.providerToken?.(n),settled:async()=>{}}:void 0}get name(){return this.entry.name}get closed(){return this.shutdown.signal.aborted}get timeoutMs(){return(this.entry.config.timeout??Dt)*1e3}get oauthUrl(){return Ht(this.entry)&&"url"in this.entry.config?this.entry.config.url:void 0}oauthSettings(){let e="url"in this.entry.config?this.entry.config.oauth:void 0;return e?{clientId:e.clientId,clientSecret:e.clientSecret===void 0?void 0:K(e.clientSecret,`MCP server "${this.entry.name}" oauth.clientSecret`),callbackPort:e.callbackPort,callbackUrl:e.callbackUrl,scope:e.scope,clientName:e.clientName,clientRegistration:e.clientRegistration,authServerMetadataUrl:e.authServerMetadataUrl?new URL(e.authServerMetadataUrl):void 0}:{}}getClient(){return this.closed?Promise.reject(new Error(`MCP server "${this.entry.name}" is shut down`)):this.client?.connectionState==="connected"?Promise.resolve(this.client):(this.opening??=this.open().finally(()=>{this.opening=void 0}),this.opening)}callTool(e,r,n){return this.withClient(s=>s.callTool(e,r,n))}readResource(e,r){return this.withClient(n=>n.readResource(e,r),!0)}resourcesPage(e,r){return this.withClient(n=>n.listResourcesPage(e,r),!0)}resourceTemplatesPage(e,r){return this.withClient(n=>et(()=>n.listResourceTemplatesPage(e,r),{resourceTemplates:[]}),!0)}allResources(e){return this.withClient(r=>r.listResources(e),!0)}allResourceTemplates(e){return this.withClient(r=>Nt(r,e),!0)}async withClient(e,r=!1){for(let n=1;;n++){let s=await this.getClient();try{return await e(s)}catch(i){if(r&&n===1&&i instanceof W&&Ge(i)){await new Promise(o=>setTimeout(o,Ze[0]));continue}if(i instanceof Se&&n===1){this.client===s&&(this.client=void 0);continue}throw this.needsSignIn(i)?(await this.dropClient(s),this.markNeedsAuth(),new Error(Qe(this.entry))):i}}}async reconnect(){await this.opening?.catch(()=>{}),this.client&&await this.dropClient(this.client),await this.getClient()}async signOut(){await this.opening?.catch(()=>{}),this.client&&await this.dropClient(this.client),this.closed||this.markNeedsAuth()}needsSignIn(e){return e instanceof f||this.authProvider!==void 0&&e instanceof ye}markNeedsAuth(){this.state="needs-auth",this.error=void 0,this.changed()}changed(){this.onChange?.(this)}async dropClient(e){this.client===e&&(this.client=void 0),await e.close().catch(()=>{})}async open(){this.state="connecting",this.changed();let e="url"in this.entry.config?Ze:[];for(let r=0;;r++){this.stderrTail=void 0;try{return await this.connectOnce()}catch(n){let s=e[r];if(this.closed||s===void 0||!Ge(n))throw this.connectFailed(n);if(await Lt(s,void 0,{signal:this.shutdown.signal}).catch(()=>{}),this.closed)throw this.connectFailed(n)}}}async connectOnce(){let e=new ge({name:"pi",version:de,requestTimeoutMs:this.timeoutMs,roots:[{uri:$t(this.cwd).href,name:Pt(this.cwd)}]}),r=this.log;r&&e.onNotification("notifications/message",o=>r.write(this.entry.name,o));let n,s=()=>(n??=e.close().catch(()=>{}),n);this.shutdown.signal.addEventListener("abort",s,{once:!0});let i;try{i=this.createTransport(this.entry,this.cwd,this.authProvider),await e.connect(i),e.onNotification("notifications/tools/list_changed",()=>{this.refreshTools(e)});let o=i instanceof x?i:void 0;e.onClose(()=>this.handleClientClose(e,o));let a=e.serverCapabilities?.tools?await e.listTools():[];if(this.closed)throw new Error("shut down while connecting");if(e.connectionState!=="connected")throw new Error("connection closed during setup");return this.client=e,this.tools=a,this.hasResources=e.serverCapabilities?.resources!==void 0,this.instructions=e.instructions?.trim()||void 0,this.state="connected",this.error=void 0,this.onTools(this),this.changed(),e}catch(o){throw await s(),i instanceof x&&(this.stderrTail=i.stderr.trim().slice(-Ye)||void 0),o}finally{this.shutdown.signal.removeEventListener("abort",s)}}connectFailed(e){return this.needsSignIn(e)&&!this.closed?(this.markNeedsAuth(),new Error(Qe(this.entry))):(this.state=this.closed?"closed":"failed",this.error=this.stderrTail?`${ae(e)}
10
- ${this.stderrTail}`:ae(e),this.changed(),new Error(`MCP server "${this.entry.name}" failed to connect: ${this.error}`))}handleClientClose(e,r){if(this.client!==e||this.closed)return;this.client=void 0,this.state="disconnected";let n=r?.stderr.trim().slice(-Ye);this.error=n?`Connection closed
11
- ${n}`:"Connection closed",this.changed()}async refreshTools(e){try{let r=await e.listTools();if(this.client!==e||this.closed)return;this.tools=r,this.onTools(this)}catch(r){this.error=`Failed to refresh tools: ${ae(r)}`}this.changed()}async close(){this.shutdown.abort(),this.state="closed",this.changed();let e=this.client;this.client=void 0,await Promise.all([e?.close().catch(()=>{}),this.opening?.catch(()=>{})]),await this.authProvider?.settled()}};export{ie as a,U as b,Rt as c,oe as d,br as e,Xe as f};