@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,7 +1,7 @@
1
1
  import { createRequire as __cortexCreateRequire } from 'node:module';
2
2
  const require = __cortexCreateRequire(import.meta.url);
3
3
  const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{n as f,v as d,y as m,z as g}from"./chunk-BUZQBTV2.js";import{a as l}from"./chunk-NRD57ICT.js";import{a as p}from"./chunk-Z24SBRJK.js";import{mkdirSync as M,readFileSync as z,rmSync as N,writeFileSync as F}from"node:fs";import _ from"node:path";var h=3600*1e3,H=20,A=_.join(f,"crash-limits.json");function P(e,t){try{let r=JSON.parse(z(e,"utf8"));return r.day===t&&r.groups&&typeof r.sentToday=="number"?r:{day:t,sentToday:0,groups:r.groups??{}}}catch{return{day:t,sentToday:0,groups:{}}}}function E(e,t,r){for(let[s,n]of Object.entries(t.groups))r-n.lastSentAt>24*h&&n.suppressed===0&&delete t.groups[s];try{M(_.dirname(e),{recursive:!0}),F(e,JSON.stringify(t),"utf8")}catch{}}function S(e,t=Date.now(),r=A){let s=P(r,new Date(t).toISOString().slice(0,10)),n=s.groups[e]??{lastSentAt:0,suppressed:0};return t-n.lastSentAt<h||s.sentToday>=H?(s.groups[e]={...n,suppressed:n.suppressed+1},E(r,s,t),{send:!1,suppressed:n.suppressed+1}):(s.groups[e]={lastSentAt:t,suppressed:0},s.sentToday+=1,E(r,s,t),{send:!0,suppressed:n.suppressed})}function R(e=A){N(e,{force:!0})}var Z=/ at (\S+):(\d+):\d+\s*$/,K=/^\s*at (\S+):(\d+):\d+\s*$/,v=/^[A-Za-z0-9._-]+$/,D=/^[A-Za-z0-9_-]+-\d+\.\d+\.\d+[A-Za-z0-9.+-]*$/,G=/^(?:core|std|alloc|proc_macro|test)$/;function x(e){return!/^(?:[A-Za-z]:\/|\/|~)/.test(e)}function X(e){return e.split("/").every(s=>v.test(s)&&s!=="..")&&e.length<=120?e:null}function j(e){let t=e.lastIndexOf("/src/");if(t<0)return null;let r=e.slice(0,t).split("/").pop()??"";return D.test(r)||e.includes("/library/")&&G.test(r)?`${r}/${e.slice(t+1)}`:e.slice(t+1)}function U(e){let t=e.replace(/\\/g,"/").replace(/^\.\//,"");return X(x(t)?t:j(t)??"")}function T(e){let t=e?U(e[1]):null;return t?`panic@${t}:${e[2]}`:null}function W(e){for(let t of e.split(`
4
+ import{n as f,v as d,y as m,z as g}from"./chunk-KST6OY76.js";import{a as l}from"./chunk-R2CCD4OF.js";import{b as p}from"./chunk-T54CZKNJ.js";import{mkdirSync as M,readFileSync as z,rmSync as N,writeFileSync as F}from"node:fs";import _ from"node:path";var h=3600*1e3,H=20,A=_.join(f,"crash-limits.json");function P(e,t){try{let r=JSON.parse(z(e,"utf8"));return r.day===t&&r.groups&&typeof r.sentToday=="number"?r:{day:t,sentToday:0,groups:r.groups??{}}}catch{return{day:t,sentToday:0,groups:{}}}}function E(e,t,r){for(let[s,n]of Object.entries(t.groups))r-n.lastSentAt>24*h&&n.suppressed===0&&delete t.groups[s];try{M(_.dirname(e),{recursive:!0}),F(e,JSON.stringify(t),"utf8")}catch{}}function S(e,t=Date.now(),r=A){let s=P(r,new Date(t).toISOString().slice(0,10)),n=s.groups[e]??{lastSentAt:0,suppressed:0};return t-n.lastSentAt<h||s.sentToday>=H?(s.groups[e]={...n,suppressed:n.suppressed+1},E(r,s,t),{send:!1,suppressed:n.suppressed+1}):(s.groups[e]={lastSentAt:t,suppressed:0},s.sentToday+=1,E(r,s,t),{send:!0,suppressed:n.suppressed})}function R(e=A){N(e,{force:!0})}var Z=/ at (\S+):(\d+):\d+\s*$/,K=/^\s*at (\S+):(\d+):\d+\s*$/,v=/^[A-Za-z0-9._-]+$/,D=/^[A-Za-z0-9_-]+-\d+\.\d+\.\d+[A-Za-z0-9.+-]*$/,G=/^(?:core|std|alloc|proc_macro|test)$/;function x(e){return!/^(?:[A-Za-z]:\/|\/|~)/.test(e)}function X(e){return e.split("/").every(s=>v.test(s)&&s!=="..")&&e.length<=120?e:null}function j(e){let t=e.lastIndexOf("/src/");if(t<0)return null;let r=e.slice(0,t).split("/").pop()??"";return D.test(r)||e.includes("/library/")&&G.test(r)?`${r}/${e.slice(t+1)}`:e.slice(t+1)}function U(e){let t=e.replace(/\\/g,"/").replace(/^\.\//,"");return X(x(t)?t:j(t)??"")}function T(e){let t=e?U(e[1]):null;return t?`panic@${t}:${e[2]}`:null}function W(e){for(let t of e.split(`
5
5
  `)){let r=K.exec(t);if(r&&x(r[1].replace(/\\/g,"/")))return T(r)}return null}function y(e,t){return T(Z.exec(e))??W(t)??"panic@unknown"}import i from"node:os";var V=300,C=30,Y=8e3;function B(){try{return i.userInfo().username}catch{return""}}function J(){return{installRoot:p,homeDir:i.homedir(),username:B(),hostname:i.hostname()}}function I(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $(e){let t=e.replace(/\\/g,"/").replace(/\/+$/,""),r=t.replace(/\//g,"\\");return[...new Set([t,r])].filter(s=>s.length>1)}function q(e,t){let r=e;for(let s of $(t)){let n=new RegExp(`(?:file:\\/\\/\\/?)?${I(s)}([\\\\/][^\\s:'"()<>]*)`,"g");r=r.replace(n,(o,c)=>c.slice(1).replace(/\\/g,"/"))}return r}var Q=/\b([a-z][a-z0-9+.-]*):\/\/([^\s/?#'"()<>]*)([^\s?#'"()<>]*)(?:[?#][^\s'"()<>]*)?/gi,ee=new Set(["localhost","127.0.0.1","[::1]"]);function te(e){return e.replace(Q,(t,r,s,n)=>{let o=s.replace(/^[^@]*@/,""),c=o.replace(/:\d+$/,"").toLowerCase(),a=r.toLowerCase()==="cortexui"||ee.has(c);return r.toLowerCase()==="file"?"<path>":`${r}://${a?o:"<host>"}${n}`})}var re=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g,se=/\b(?:sk|pk|rk|ghp|gho|ghs|ghu|github_pat|xox[abposr]|glpat|AKIA|AIza)[-_A-Za-z0-9]{8,}/g,ne=/\b[0-9a-fA-F]{32,}\b/g,oe=/[A-Za-z0-9+_=-]{32,}/g,ce=/\b(?!127\.0\.0\.1\b)(?!0\.0\.0\.0\b)(?:\d{1,3}\.){3}\d{1,3}\b/g;function ae(e){return e.replace(re,"<email>").replace(se,"<secret>").replace(ne,"<secret>").replace(oe,t=>/\d/.test(t)&&/[A-Za-z]/.test(t)?"<secret>":t).replace(ce,"<ip>")}var ie=/(?<![\w.:/\\<>-])\/(?:[^\s:'"()<>,;]+)/g,ue=/\b[A-Za-z]:[\\/][^\s:'"()<>,;]*/g,pe=/\\\\[^\s\\:'"()<>]+\\[^\s:'"()<>,;]*/g;function le(e){return e.replace(pe,"<path>").replace(ue,"<path>").replace(ie,"<path>")}function fe(e,t){let r=e;for(let n of $(t.homeDir))r=r.split(n).join("<home>");let s=[[t.hostname,"<host>"],[t.username,"<user>"]];for(let[n,o]of[...s].sort((c,a)=>a[0].length-c[0].length))n.length<3||(r=r.replace(new RegExp(`(?<![A-Za-z0-9])${I(n)}(?![A-Za-z0-9])`,"gi"),o));return r}function b(e,t=J()){let r=q(e,t.installRoot);return fe(le(ae(te(r))),t)}function u(e,t){return b(e,t).slice(0,V)}function k(e,t){let r=b(e,t).split(`
6
6
  `),s=r.findIndex(o=>/^\s*at\s/.test(o));return(s===-1?r.slice(0,C+1):r.slice(0,s+C)).join(`
7
7
  `).slice(0,Y)}var de=/^\s*at\s+(?:(\S+)\s+)?\(?((?:dist|src)\/[^\s:()]+)/,me=/(?:^|[\s@(])((?:[a-z]+:\/\/[^\s/]+)?\/assets\/[^\s:()]+)/;function O(e,t){for(let r of t.split(`
@@ -1,4 +1,4 @@
1
1
  import { createRequire as __cortexCreateRequire } from 'node:module';
2
2
  const require = __cortexCreateRequire(import.meta.url);
3
3
  const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as l}from"./chunk-VPVSKJGX.js";import{e as R}from"./chunk-WHC7AYZD.js";var _=R(l(),1);import*as u from"node:fs";import*as a from"node:net";import*as T from"node:os";import*as n from"node:path";var s="CORTEX_UI_PORT",E=26789,N="CORTEX_UI_HOST",f="127.0.0.1",C="/tui",m=26999,I="CORTEX_CLIENT_PORT",x=["WEBHOOK_PORT","CORTEX_TUI_PORT"];function c(e){let r=(e??"").trim();if(!/^\d+$/.test(r))return null;let t=Number(r);return t>=1&&t<=65535?t:null}function i(e=process.env){let r=e.CORTEX_HOME?n.resolve(e.CORTEX_HOME):n.join(T.homedir(),".cortex");return n.join(r,"config",".env")}function O(e,r){try{return _.parse(u.readFileSync(e))[r]}catch{return}}function d(e=process.env,r=i(e)){let t=r===null?void 0:O(r,s);return c(e[s])??c(t)??E}function v(e=process.env,r=i(e)){return`http://127.0.0.1:${d(e,r)}`}function h(e=process.env,r=i(e)){return(e.CORTEX_CLIENT_TOKEN||O(r,"CORTEX_CLIENT_TOKEN")||"").trim()}var p=new Set;function A(e,r){for(let t of x)!e[t]||p.has(t)||(p.add(t),r(`${t} is no longer used and is ignored: every endpoint is served on ${s} (${d(e)}). Remove ${t} from your environment or ${i(e)}.`))}function P(e,r=f){return new Promise(t=>{let o=a.createServer();o.unref(),o.once("error",()=>t(!1)),o.listen({port:e,host:r,exclusive:!0},()=>o.close(()=>t(!0)))})}async function $(e=f,r=E,t=m){for(let o=r;o<=t;o++)if(await P(o,e))return o;throw new Error(`No free port between ${r} and ${t}; set ${s} to a free port and retry.`)}export{s as a,E as b,N as c,f as d,C as e,I as f,c as g,d as h,v as i,h as j,A as k,P as l,$ as m};
4
+ import{a as l}from"./chunk-T54CZKNJ.js";import{e as R}from"./chunk-WHC7AYZD.js";var _=R(l(),1);import*as u from"node:fs";import*as a from"node:net";import*as T from"node:os";import*as n from"node:path";var s="CORTEX_UI_PORT",E=26789,N="CORTEX_UI_HOST",f="127.0.0.1",C="/tui",m=26999,I="CORTEX_CLIENT_PORT",x=["WEBHOOK_PORT","CORTEX_TUI_PORT"];function c(e){let r=(e??"").trim();if(!/^\d+$/.test(r))return null;let t=Number(r);return t>=1&&t<=65535?t:null}function i(e=process.env){let r=e.CORTEX_HOME?n.resolve(e.CORTEX_HOME):n.join(T.homedir(),".cortex");return n.join(r,"config",".env")}function O(e,r){try{return _.parse(u.readFileSync(e))[r]}catch{return}}function d(e=process.env,r=i(e)){let t=r===null?void 0:O(r,s);return c(e[s])??c(t)??E}function v(e=process.env,r=i(e)){return`http://127.0.0.1:${d(e,r)}`}function h(e=process.env,r=i(e)){return(e.CORTEX_CLIENT_TOKEN||O(r,"CORTEX_CLIENT_TOKEN")||"").trim()}var p=new Set;function A(e,r){for(let t of x)!e[t]||p.has(t)||(p.add(t),r(`${t} is no longer used and is ignored: every endpoint is served on ${s} (${d(e)}). Remove ${t} from your environment or ${i(e)}.`))}function P(e,r=f){return new Promise(t=>{let o=a.createServer();o.unref(),o.once("error",()=>t(!1)),o.listen({port:e,host:r,exclusive:!0},()=>o.close(()=>t(!0)))})}async function $(e=f,r=E,t=m){for(let o=r;o<=t;o++)if(await P(o,e))return o;throw new Error(`No free port between ${r} and ${t}; set ${s} to a free port and retry.`)}export{s as a,E as b,N as c,f as d,C as e,I as f,c as g,d as h,v as i,h as j,A as k,P as l,$ as m};
@@ -0,0 +1,12 @@
1
+ import { createRequire as __cortexCreateRequire } from 'node:module';
2
+ const require = __cortexCreateRequire(import.meta.url);
3
+ const __cortexPackageRoot = new URL("../../", import.meta.url);
4
+ import{c as b,e as M}from"./chunk-WHC7AYZD.js";var O=b(n=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0});n.Allow=n.ALL=n.COLLECTION=n.ATOM=n.SPECIAL=n.INF=n._INFINITY=n.INFINITY=n.NAN=n.BOOL=n.NULL=n.OBJ=n.ARR=n.NUM=n.STR=void 0;n.STR=1;n.NUM=2;n.ARR=4;n.OBJ=8;n.NULL=16;n.BOOL=32;n.NAN=64;n.INFINITY=128;n._INFINITY=256;n.INF=n.INFINITY|n._INFINITY;n.SPECIAL=n.NULL|n.BOOL|n.INF|n.NAN;n.ATOM=n.STR|n.NUM|n.SPECIAL;n.COLLECTION=n.ARR|n.OBJ;n.ALL=n.ATOM|n.COLLECTION;n.Allow={STR:n.STR,NUM:n.NUM,ARR:n.ARR,OBJ:n.OBJ,NULL:n.NULL,BOOL:n.BOOL,NAN:n.NAN,INFINITY:n.INFINITY,_INFINITY:n._INFINITY,INF:n.INF,SPECIAL:n.SPECIAL,ATOM:n.ATOM,COLLECTION:n.COLLECTION,ALL:n.ALL};n.default=n.Allow});var L=b(f=>{"use strict";var B=f&&f.__createBinding||(Object.create?(function(i,e,r,t){t===void 0&&(t=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(i,t,s)}):(function(i,e,r,t){t===void 0&&(t=r),i[t]=e[r]})),S=f&&f.__exportStar||function(i,e){for(var r in i)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&B(e,i,r)};Object.defineProperty(f,"__esModule",{value:!0});f.Allow=f.MalformedJSON=f.PartialJSON=f.parseJSON=f.parse=void 0;var c=O();Object.defineProperty(f,"Allow",{enumerable:!0,get:function(){return c.Allow}});S(O(),f);var p=class extends Error{};f.PartialJSON=p;var N=class extends Error{};f.MalformedJSON=N;function m(i,e=c.Allow.ALL){if(typeof i!="string")throw new TypeError(`expecting str, got ${typeof i}`);if(!i.trim())throw new Error(`${i} is empty`);return U(i.trim(),e)}f.parseJSON=m;var U=(i,e)=>{let r=i.length,t=0,s=a=>{throw new p(`${a} at position ${t}`)},u=a=>{throw new N(`${a} at position ${t}`)},d=()=>(o(),t>=r&&s("Unexpected end of input"),i[t]==='"'?y():i[t]==="{"?v():i[t]==="["?J():i.substring(t,t+4)==="null"||c.Allow.NULL&e&&r-t<4&&"null".startsWith(i.substring(t))?(t+=4,null):i.substring(t,t+4)==="true"||c.Allow.BOOL&e&&r-t<4&&"true".startsWith(i.substring(t))?(t+=4,!0):i.substring(t,t+5)==="false"||c.Allow.BOOL&e&&r-t<5&&"false".startsWith(i.substring(t))?(t+=5,!1):i.substring(t,t+8)==="Infinity"||c.Allow.INFINITY&e&&r-t<8&&"Infinity".startsWith(i.substring(t))?(t+=8,1/0):i.substring(t,t+9)==="-Infinity"||c.Allow._INFINITY&e&&1<r-t&&r-t<9&&"-Infinity".startsWith(i.substring(t))?(t+=9,-1/0):i.substring(t,t+3)==="NaN"||c.Allow.NAN&e&&r-t<3&&"NaN".startsWith(i.substring(t))?(t+=3,NaN):k()),y=()=>{let a=t,h=!1;for(t++;t<r&&(i[t]!=='"'||h&&i[t-1]==="\\");)h=i[t]==="\\"?!h:!1,t++;if(i.charAt(t)=='"')try{return JSON.parse(i.substring(a,++t-Number(h)))}catch(l){u(String(l))}else if(c.Allow.STR&e)try{return JSON.parse(i.substring(a,t-Number(h))+'"')}catch{return JSON.parse(i.substring(a,i.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},v=()=>{t++,o();let a={};try{for(;i[t]!=="}";){if(o(),t>=r&&c.Allow.OBJ&e)return a;let h=y();o(),t++;try{let l=d();a[h]=l}catch(l){if(c.Allow.OBJ&e)return a;throw l}o(),i[t]===","&&t++}}catch{if(c.Allow.OBJ&e)return a;s("Expected '}' at end of object")}return t++,a},J=()=>{t++;let a=[];try{for(;i[t]!=="]";)a.push(d()),o(),i[t]===","&&t++}catch{if(c.Allow.ARR&e)return a;s("Expected ']' at end of array")}return t++,a},k=()=>{if(t===0){i==="-"&&u("Not sure what '-' is");try{return JSON.parse(i)}catch(h){if(c.Allow.NUM&e)try{return JSON.parse(i.substring(0,i.lastIndexOf("e")))}catch{}u(String(h))}}let a=t;for(i[t]==="-"&&t++;i[t]&&",]}".indexOf(i[t])===-1;)t++;t==r&&!(c.Allow.NUM&e)&&s("Unterminated number literal");try{return JSON.parse(i.substring(a,t))}catch{i.substring(a,t)==="-"&&s("Not sure what '-' is");try{return JSON.parse(i.substring(a,i.lastIndexOf("e")))}catch(l){u(String(l))}}},o=()=>{for(;t<r&&`
5
+ \r `.includes(i[t]);)t++};return d()},F=m;f.parse=F});var I=M(L(),1),x=new Set(['"',"\\","/","b","f","n","r","t"]);function $(i){let e=i.codePointAt(0);return e!==void 0&&e>=0&&e<=31}function D(i){switch(i){case"\b":return"\\b";case"\f":return"\\f";case`
6
+ `:return"\\n";case"\r":return"\\r";case" ":return"\\t";default:return`\\u${i.codePointAt(0)?.toString(16).padStart(4,"0")??"0000"}`}}function E(i){let e="",r=!1;for(let t=0;t<i.length;t++){let s=i[t];if(!r){e+=s,s==='"'&&(r=!0);continue}if(s==='"'){e+=s,r=!1;continue}if(s==="\\"){let u=i[t+1];if(u===void 0){e+="\\\\";continue}if(u==="u"){let d=i.slice(t+2,t+6);if(/^[0-9a-fA-F]{4}$/.test(d)){e+=`\\u${d}`,t+=5;continue}}if(x.has(u)){e+=`\\${u}`,t+=1;continue}e+="\\\\";continue}e+=$(s)?D(s):s}return e}function T(i){try{return JSON.parse(i)}catch(e){let r=E(i);if(r!==i)return JSON.parse(r);throw e}}function g(i){if(!i?.trim())return{arguments:{}};try{let e=T(i);if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("Tool arguments must be a JSON object");return{arguments:e}}catch(e){return{arguments:{},argumentsError:`${e instanceof Error?e.message:String(e)}
7
+
8
+ Received arguments:
9
+ ${i}`}}}function ie(i){if(!i||i.trim()==="")return{};try{return T(i)}catch{try{return(0,I.parse)(i)??{}}catch{try{return(0,I.parse)(E(i))??{}}catch{return{}}}}}var Y=32,W={kind:"root"},H=256,z=8,G=64,C=/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/,V=/^(-?(?:0|[1-9]\d*)(?:\.\d+)?)[eE][+-]?$/,R=[["true",!0],["false",!1],["null",null]],X=34,q=92,A=class{#t=void 0;#u=!1;#e=[];#r=void 0;#i="";#a=void 0;#f=0;#o=0;#n=!1;#d=void 0;#h=[];append(e){this.#o+=H+z*e.length,this.#h=[],this.#r!==void 0&&(this.#r.change=void 0);let r=0;for(;r<e.length&&!this.#u;){let t=this.#r;t!==void 0?r=this.#O(t,e,r):this.#i!==""?r=this.#I(e,r):this.#y(e[r++])}return this.#h}snapshot(){if(!this.#n)return this.#d;let e=this.#T(),r=this.#f+(e===void 0?0:1);return r>this.#o?this.#d:(this.#o-=r,this.#n=!1,this.#d=this.#w(e),this.#d)}#O(e,r,t){let s=t;for(let u=t;u<r.length;u++){let d=r.charCodeAt(u);if(e.escape!==""){if(this.#m(e,r[u])){s=u+1;continue}s=u}if(d===X)return u>s&&this.#s(e,r.slice(s,u)),this.#L(e),u+1;d===q&&(u>s&&this.#s(e,r.slice(s,u)),e.escape="\\",s=u+1)}return r.length>s&&this.#s(e,r.slice(s)),r.length}#I(e,r){let t=r;for(;t<e.length&&!Q(e[t]);)t++;return t>r&&(this.#i+=e.slice(r,t),this.#a!==void 0&&(this.#n=!0)),t<e.length&&this.#E(),t}#y(e){switch(e){case" ":case" ":case`
10
+ `:case"\r":return;case'"':this.#b();return;case"{":case"[":this.#g(e==="{"?{}:[]);return;case"}":case"]":this.#_();return;case":":{let r=this.#e.at(-1);r!==void 0&&!Array.isArray(r.container)&&r.phase==="colon"&&(r.phase="value");return}case",":{let r=this.#e.at(-1);r!==void 0&&(r.phase=Array.isArray(r.container)?"value":"key");return}default:this.#i=e,this.#a=this.#p(),this.#a!==void 0&&(this.#n=!0)}}#p(){let e=this.#e.at(-1);if(e===void 0)return this.#t===void 0?W:void 0;if(Array.isArray(e.container))return{kind:"element",index:e.container.length};if((e.phase==="value"||e.phase==="colon")&&e.key!==void 0)return{kind:"member",key:e.key}}#b(){let e=this.#e.at(-1);if(e!==void 0&&!Array.isArray(e.container)&&(e.phase==="key"||e.phase==="comma")){this.#r={target:"key",slot:void 0,text:"",escape:"",path:void 0,change:void 0};return}let r=this.#p(),t=this.#N(r);this.#r={target:"value",slot:r,text:"",escape:"",path:t,change:void 0},this.#l(r,""),t!==void 0&&(this.#r.change=this.#c({kind:"set",path:t,value:""}))}#N(e){if(e===void 0)return;if(e.kind==="root")return[];let r=this.#e.at(-1);if(r.reportsInside)return[...r.path,e.kind==="member"?e.key:e.index]}#c(e){return this.#h.push(e),e}#m(e,r){if(e.escape==="\\"){let s=K[r];return s!==void 0?(e.escape="",this.#s(e,s),!0):r==="u"?(e.escape="\\u",!0):(e.escape="",this.#s(e,"\\"),!1)}if(Z(r)){if(e.escape+=r,e.escape.length<6)return!0;let s=String.fromCharCode(Number.parseInt(e.escape.slice(2),16));return e.escape="",this.#s(e,s),!0}let t=e.escape;return e.escape="",this.#s(e,t),!1}#s(e,r){if(e.text+=r,e.target!=="value"||(this.#l(e.slot,e.text),e.path===void 0))return;let t=e.change;if(t!==void 0&&this.#h.at(-1)===t){t.kind==="set"?t.value=t.value+r:t.text+=r;return}e.change=this.#c({kind:"append",path:e.path,text:r})}#L(e){this.#r=void 0;let r=this.#e.at(-1);if(e.target==="key"){if(r===void 0)return;r.key=e.text,r.phase="colon";return}this.#A(r)}#E(){let e=this.#i,r=this.#a;this.#i="",this.#a=void 0;let t=j(e);if(t!==void 0){this.#l(r,t);let s=this.#N(r);s!==void 0&&this.#c({kind:"set",path:s,value:t})}this.#A(this.#e.at(-1))}#T(){let e=this.#a,r=this.#i;if(e===void 0||r===""||r.length>G)return;let t=ee(r);return t===void 0?void 0:{slot:e,value:t}}#g(e){let r=this.#p(),t=this.#N(r);this.#l(r,e),this.#e.push({container:e,slot:r,path:t,reportsInside:t!==void 0&&t.length<Y,size:0,key:void 0,phase:Array.isArray(e)?"value":"key"}),this.#f+=1,this.#n=!0,t!==void 0&&this.#c({kind:"set",path:t,value:Array.isArray(e)?[]:{}})}#_(){let e=this.#e.pop();e!==void 0&&(this.#f-=e.size+1,this.#n=!0,e.path!==void 0&&!e.reportsInside&&this.#c({kind:"set",path:e.path,value:e.container}),this.#A(this.#e.at(-1)))}#A(e){if(e===void 0){this.#t!==void 0&&(this.#u=!0);return}e.phase="comma"}#l(e,r){if(e===void 0)return;if(this.#n=!0,e.kind==="root"){this.#t=r;return}let t=this.#e.at(-1);if(e.kind==="element"){let u=t.container;e.index===u.length&&(t.size++,this.#f++),u[e.index]=r;return}let s=t.container;Object.hasOwn(s,e.key)||(t.size++,this.#f++),P(s,e.key,r)}#w(e){if(this.#e.length===0)return e?.slot.kind==="root"?e.value:this.#t;let r,t;for(let s=this.#e.length-1;s>=0;s--){let u=this.#e[s],d=Array.isArray(u.container)?u.container.slice():{...u.container};s===this.#e.length-1&&e!==void 0&&w(d,e.slot,e.value),r!==void 0&&t!==void 0&&w(d,t,r),r=d,t=u.slot}return t?.kind==="root"?r:this.#t}},_=class{#t="";#u=new A;#e=void 0;#r={};get text(){return this.#t}append(e){return this.#t+=e,this.#u.append(e),this.#i()}replace(e){if(e.startsWith(this.#t)){let r=e.slice(this.#t.length);return{delta:r,arguments:r===""?this.#i():this.append(r)}}return this.#t="",this.#u=new A,{delta:void 0,arguments:this.append(e)}}finish(){return g(this.#t)}#i(){let e=this.#u.snapshot();return e===this.#e?this.#r:(this.#e=e,this.#r=typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{},this.#r)}},K={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
11
+ `,r:"\r",t:" "};function Q(i){return i===" "||i===" "||i===`
12
+ `||i==="\r"||i===","||i===":"||i==="{"||i==="}"||i==="["||i==="]"||i==='"'}function Z(i){return i>="0"&&i<="9"||i>="a"&&i<="f"||i>="A"&&i<="F"}function j(i){for(let[e,r]of R)if(i===e)return r;return C.test(i)?Number(i):void 0}function ee(i){for(let[r,t]of R)if(r.startsWith(i))return t;if(C.test(i))return Number(i);let e=V.exec(i);return e===null?void 0:Number(e[1])}function w(i,e,r){e.kind==="element"?i[e.index]=r:e.kind==="member"&&P(i,e.key,r)}function P(i,e,r){e==="__proto__"?Object.defineProperty(i,e,{value:r,writable:!0,enumerable:!0,configurable:!0}):i[e]=r}export{E as a,T as b,g as c,ie as d,A as e,_ as f};
@@ -0,0 +1,4 @@
1
+ import { createRequire as __cortexCreateRequire } from 'node:module';
2
+ const require = __cortexCreateRequire(import.meta.url);
3
+ const __cortexPackageRoot = new URL("../../", import.meta.url);
4
+ import{d as ae}from"./chunk-PTS3J4DQ.js";import{a as de,b as fe,d as pe}from"./chunk-IMMGYDAB.js";import{f as g,h as M}from"./chunk-OJ37ZWBG.js";import{a as D}from"./chunk-OKRK6JPY.js";import{a as ue,f as le}from"./chunk-B3NB243Z.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-LIIZI3HY.js";import{c as te}from"./chunk-TRXLIL7V.js";import{e as m}from"./chunk-7W7VYUTK.js";import{a as We,j as w,m as N,n as re,o as oe}from"./chunk-T54CZKNJ.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};
@@ -0,0 +1,15 @@
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{W as S}from"./chunk-2BVUA256.js";import{accessSync as T,constants as C}from"node:fs";import{delimiter as E,join as _,win32 as g}from"node:path";import{spawn as v,spawnSync as P}from"child_process";function D(t){let n=g.normalize(t).toLowerCase(),e=process.env.SystemRoot;return e?/^[a-z]:[\\/]/i.test(e)?["System32","Sysnative"].some(r=>n===g.join(e,r,"bash.exe").toLowerCase()):!1:/^[a-z]:\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(n)}function y(t){return D(t)?{shell:t,args:["-s"],commandTransport:"stdin"}:{shell:t,args:["-c"]}}function p(t){try{return T(t,C.F_OK),!0}catch{return!1}}function m(t){if(process.platform==="win32"){try{let n=P("where",[t],{encoding:"utf-8",timeout:5e3,windowsHide:!0});if(n.status===0&&n.stdout){let e=n.stdout.trim().split(/\r?\n/)[0];if(e&&p(e))return e}}catch{}return null}try{let n=P("which",[t],{encoding:"utf-8",timeout:5e3});if(n.status===0&&n.stdout){let e=n.stdout.trim().split(/\r?\n/)[0];if(e)return e}}catch{}return null}function $(t){if(t){if(p(t))return y(t);throw new Error(`Custom shell path not found: ${t}`)}if(process.platform==="win32"){let e=[],r=process.env.ProgramFiles;r&&e.push(`${r}\\Git\\bin\\bash.exe`);let o=process.env["ProgramFiles(x86)"];o&&e.push(`${o}\\Git\\bin\\bash.exe`);for(let s of e)if(p(s))return y(s);let i=m("bash.exe");if(i)return y(i);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
+ ${e.map(s=>` ${s}`).join(`
11
+ `)}`)}if(p("/bin/bash"))return y("/bin/bash");let n=m("bash");return n?y(n):{shell:"sh",args:["-c"]}}var k=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command"];function R(){if(process.platform!=="win32")throw new Error("The powershell tool is only available on Windows.");let t=m("pwsh.exe"),n=process.env.ProgramFiles;if(!t&&n){let r=g.join(n,"PowerShell","7","pwsh.exe");p(r)&&(t=r)}t??=m("powershell.exe");let e=process.env.SystemRoot;if(!t&&e){let r=g.join(e,"System32","WindowsPowerShell","v1.0","powershell.exe");p(r)&&(t=r)}if(!t)throw new Error("No PowerShell executable found. Install PowerShell or add powershell.exe/pwsh.exe to PATH.");return{shell:t,args:[...k]}}function X(){let t=S(),n=Object.keys(process.env).find(s=>s.toLowerCase()==="path")??"PATH",e=process.env[n]??"",i=e.split(E).filter(Boolean).includes(t)?e:[t,e].filter(Boolean).join(E);return{...process.env,[n]:i}}function W(t){return t.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\uFFF9-\uFFFB]/g,"")}var w=new Set;function z(t){w.add(t)}function K(t){w.delete(t)}function U(){for(let t of w)I(t);w.clear()}function I(t){if(process.platform==="win32")try{v(_(process.env.SystemRoot||"C:\\Windows","System32","taskkill.exe"),["/F","/T","/PID",String(t)],{stdio:"ignore",detached:!0,windowsHide:!0}).once("error",()=>{})}catch{}else{if(process.platform==="darwin")try{process.kill(-t,"SIGSTOP")}catch{}try{process.kill(-t,"SIGKILL")}catch{try{process.kill(t,"SIGKILL")}catch{}}}}var q=2e3,J=51200;function b(t){if(t.length===0)return[];let n=t.split(`
12
+ `);return t.endsWith(`
13
+ `)&&n.pop(),n}function Q(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/(1024*1024)).toFixed(1)}MB`}function V(t,n={}){let e=n.maxLines??2e3,r=n.maxBytes??51200,o=Buffer.byteLength(t,"utf-8"),i=b(t),s=i.length;if(s<=e&&o<=r)return{content:t,truncated:!1,truncatedBy:null,totalLines:s,totalBytes:o,outputLines:s,outputBytes:o,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:e,maxBytes:r};if(Buffer.byteLength(i[0],"utf-8")>r)return{content:"",truncated:!0,truncatedBy:"bytes",totalLines:s,totalBytes:o,outputLines:0,outputBytes:0,lastLinePartial:!1,firstLineExceedsLimit:!0,maxLines:e,maxBytes:r};let a=[],l=0,f="lines";for(let c=0;c<i.length&&c<e;c++){let h=i[c],L=Buffer.byteLength(h,"utf-8")+(c>0?1:0);if(l+L>r){f="bytes";break}a.push(h),l+=L}a.length>=e&&l<=r&&(f="lines");let d=a.join(`
14
+ `),x=Buffer.byteLength(d,"utf-8");return{content:d,truncated:!0,truncatedBy:f,totalLines:s,totalBytes:o,outputLines:a.length,outputBytes:x,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:e,maxBytes:r}}function Z(t,n={}){let e=n.maxLines??2e3,r=n.maxBytes??51200,o=Buffer.byteLength(t,"utf-8"),i=b(t),s=i.length;if(s<=e&&o<=r)return{content:t,truncated:!1,truncatedBy:null,totalLines:s,totalBytes:o,outputLines:s,outputBytes:o,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines:e,maxBytes:r};let u=[],a=0,l="lines",f=!1;for(let c=i.length-1;c>=0&&u.length<e;c--){let h=i[c],L=Buffer.byteLength(h,"utf-8")+(u.length>0?1:0);if(a+L>r){if(l="bytes",u.length===0){let B=M(h,r);u.unshift(B),a=Buffer.byteLength(B,"utf-8"),f=!0}break}u.unshift(h),a+=L}u.length>=e&&a<=r&&(l="lines");let d=u.join(`
15
+ `),x=Buffer.byteLength(d,"utf-8");return{content:d,truncated:!0,truncatedBy:l,totalLines:s,totalBytes:o,outputLines:u.length,outputBytes:x,lastLinePartial:f,firstLineExceedsLimit:!1,maxLines:e,maxBytes:r}}function M(t,n){let e=Buffer.from(t,"utf-8");if(e.length<=n)return t;let r=e.length-n;for(;r<e.length&&(e[r]&192)===128;)r++;return e.slice(r).toString("utf-8")}function tt(t,n=500){return t.length<=n?{text:t,wasTruncated:!1}:{text:`${G(t,n)}... [truncated]`,wasTruncated:!0}}function G(t,n){let e=Math.max(0,n);return A(t.charCodeAt(e-1))&&F(t.charCodeAt(e))?t.slice(0,e-1):t.slice(0,e)}function et(t,n){if(n<=0)return"";let e=Math.max(0,t.length-n);return F(t.charCodeAt(e))&&A(t.charCodeAt(e-1))?t.slice(e+1):t.slice(e)}function A(t){return t>=55296&&t<=56319}function F(t){return t>=56320&&t<=57343}export{$ as a,R as b,X as c,W as d,z as e,K as f,U as g,I as h,q as i,J as j,Q as k,V as l,Z as m,tt as n,G as o,et as p};
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __cortexCreateRequire } from 'node:module';
2
2
  const require = __cortexCreateRequire(import.meta.url);
3
3
  const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{d as Le,e as Me,f as Ue,g as He,h,i as Ge,l as Ke,w as Ve}from"./chunk-KDPY2YA3.js";import{a as Je,b as Be,c as We,d as qe,e as Xe,h as S,i as L}from"./chunk-W6AKCEYF.js";import{a as ue,b as de,d as me}from"./chunk-FP7ML72L.js";import{a as De,b as we,c as Ee,d as Pe,e as _e,f as je,i as Ae,j as Re,k as Oe,l as Te,m as Ne}from"./chunk-WBSE3EF3.js";import{C as P,u as k,v as $e}from"./chunk-3ORG56I5.js";import{f as ve,m as Ie}from"./chunk-2VVRTJQN.js";import{a as Se}from"./chunk-5NRGVROY.js";import{a as E}from"./chunk-LEAV3FFG.js";import{a as he}from"./chunk-2ATTYCRJ.js";import{b as ae,c as ce,h as le}from"./chunk-KUDK7GPS.js";import{f as ke}from"./chunk-BDLKI2NT.js";import{L as be,n as Ce,o as ye}from"./chunk-JJDEQ6N2.js";import{h as pe}from"./chunk-QUXPMNFQ.js";import{a as _,b as m,c as Fe}from"./chunk-PMG4YGDU.js";import{d as xe}from"./chunk-R52AVUQB.js";import{a as b,b as ge,c as w,e as F}from"./chunk-LP7T32PW.js";import{a as N}from"./chunk-NRD57ICT.js";import{b as oe,q as se}from"./chunk-TX46YMGI.js";import{e as Z}from"./chunk-AVXDF7AG.js";import{e as c}from"./chunk-3CPIMAYX.js";import{e as ie}from"./chunk-VBN2JSER.js";import{b as fe}from"./chunk-NXZS5PEW.js";import{a as ee,d as y,i as te,j as ne,o as p,p as T,q as re}from"./chunk-Z24SBRJK.js";import{a as jt}from"./chunk-VPVSKJGX.js";import{e as _t}from"./chunk-WHC7AYZD.js";import{fork as A}from"child_process";import*as d from"path";import*as wt from"net";import{fileURLToPath as On}from"url";import{existsSync as f,readdirSync as Tn,readFileSync as X,unlinkSync as z}from"fs";var Ye=_t(jt(),1);import*as u from"node:fs";import*as l from"node:path";import{fileURLToPath as At}from"node:url";function Rt(e){if(typeof e!="string")return;let t=e.trim();if(!(!t||t==="null"||t==="undefined"))return t}function Ot(e){let t=e.match(/^v?(\d+)/);return t?Number(t[1]):0}function Tt(e){let t=l.join(e.paths.CONFIG_DIR,".env"),n={},r=e.readText(t);if(r!=null)try{n=e.parseDotenv(r)}catch{n={}}return i=>Rt(e.env[i]??n[i])}function Nt(e){let t=e.defaultSelection()?.backend??"claude";return t==="pi"?{id:"backend-runtime",label:"Backend runtime",status:"pass",detail:"backend: pi runs in-process from the bundled SDK (no CLI needed)"}:e.commandExists("claude")?{id:"backend-runtime",label:"Backend runtime",status:"pass",detail:`claude found on PATH (backend: ${t})`}:{id:"backend-runtime",label:"Backend runtime",status:"warn",detail:`claude not on PATH (backend: ${t})`,hint:"Install/login the claude CLI"}}function Ft(e){return e.commandExists("git")?{id:"git",label:"git",status:"pass",detail:"usable on PATH"}:(e.platform??process.platform)==="win32"?{id:"git",label:"git",status:"fail",detail:"unavailable",hint:"Install Git for Windows \u2014 shell tools require Git Bash"}:{id:"git",label:"git",status:"warn",detail:"unavailable (optional)",hint:"Install Git to enable version history and Git-sourced extensions"}}function Lt(e){let t=[],n=Ot(e.nodeVersion);t.push(n>=e.requiredNodeMajor?{id:"node-version",label:"Node version",status:"pass",detail:`${e.nodeVersion} (>=${e.requiredNodeMajor})`}:{id:"node-version",label:"Node version",status:"warn",detail:`${e.nodeVersion} \u2014 Cortex requires Node >=${e.requiredNodeMajor}`,hint:"Upgrade Node.js"}),t.push(Ft(e)),t.push(Nt(e));let r=l.join(e.paths.STORE_DIR,l.basename(p)),i=e.fileExists(r)?e.readText(r):null,o=i?Number(i.trim()):NaN;return Number.isFinite(o)&&e.pidAlive(o)?t.push({id:"daemon",label:"Daemon",status:"pass",detail:`running (pid ${o})`}):t.push({id:"daemon",label:"Daemon",status:"skip",detail:"not running",hint:"Start with `cortex daemon`"}),{title:"Runtime & Process",checks:t}}function Mt(e,t){let n=[];for(let[r,i]of Object.entries(t.paths))t.fileExists(i)?t.isWritable(i)||n.push(`${r} not writable (${i})`):n.push(`${r} missing (${i})`);e.push(n.length===0?{id:"dirs",label:"Data directories",status:"pass",detail:"present and writable"}:{id:"dirs",label:"Data directories",status:"fail",detail:n.join("; "),hint:"run `cortex doctor --fix` or `cortex init`",fixable:!0})}function Ut(e,t,n){let r=l.join(t.paths.CONFIG_DIR,".env");e.push(t.fileExists(r)?{id:"env-file",label:".env file",status:"pass",detail:r}:{id:"env-file",label:".env file",status:"fail",detail:`missing (${r})`,hint:"run `cortex init`"});let i=[ae,ce].filter(o=>!n(o));e.push(i.length===0?{id:"auth-tokens",label:"Auth tokens",status:"pass",detail:"client + webhook tokens set"}:{id:"auth-tokens",label:"Auth tokens",status:"fail",detail:`missing: ${i.join(", ")}`,hint:"run `cortex doctor --fix` to generate",fixable:!0})}function Qe(e){let t=e.defaultSelection();return t?.backend!=="claude"||!t.connection||t.connection===oe?null:t.connection}function Ht(e){let t=Qe(e);return t!==null&&e.claudeConnections().includes(t)}function Gt(e,t){let n=Qe(t);n===null?e.push({id:"claude-connection",label:"Claude connection",status:"skip",detail:"default does not use a key connection"}):t.claudeConnections().includes(n)?e.push({id:"claude-connection",label:"Claude connection",status:"pass",detail:`${n} configured`}):e.push({id:"claude-connection",label:"Claude connection",status:"warn",detail:`${n} is not configured`,hint:"add the connection in Settings or pick another model"})}function Kt(e,t){let{CONFIG_DIR:n,STORE_DIR:r}=t.paths,i=l.join(r,"agent-state.json"),o=t.fileExists(i)?"agent-state.json":"mode.json";zt(e,t,t.fileExists(i)?i:l.join(r,"mode.json"),"mode-json",o,"warn"),e.push(Yt(t,l.join(n,"models.json")));let s=l.join(n,"mcp-config.json");t.fileExists(s)?Ze(t.readText(s))?e.push({id:"mcp-config",label:"mcp-config.json",status:"pass",detail:"valid"}):e.push({id:"mcp-config",label:"mcp-config.json",status:"warn",detail:"invalid JSON",hint:"run `cortex doctor --fix` to regenerate",fixable:!0}):e.push({id:"mcp-config",label:"mcp-config.json",status:"warn",detail:`missing (${s})`,hint:"run `cortex doctor --fix` to regenerate",fixable:!0})}var M="See docs/backends.md#remote-login",Vt=new Set(["expired","logged-out"]),Jt="Reinstall the Cortex server package \u2014 the PI SDK ships with it";async function Bt(e){let t=e.resolvePiSdk();if(!t)return{id:"pi-runtime",label:"PI runtime",status:"warn",detail:`bundled PI SDK not resolvable (${k})`,hint:Jt};try{let n=await e.loadPiRuntime();if(n.available&&typeof n.runtime.login=="function"){let r=n.version??t.version,i=r?` ${r}`:"";return{id:"pi-runtime",label:"PI runtime",status:"pass",detail:`in-process SDK ${t.package}${i}; login export found`}}}catch{}return{id:"pi-runtime",label:"PI runtime",status:"warn",detail:"bundled PI runtime or login export unavailable",hint:M}}function ze(e,t){return t&&(e.connection??null)===null&&e.backend==="claude"&&e.provider==="anthropic"&&e.state==="logged-out"}function Wt(e,t){let n=e.accounts.filter(a=>a.inUse),r=n.filter(a=>ze(a,t)),i=n.filter(a=>Vt.has(a.state)&&!ze(a,t)),o=[...new Set(i.map(a=>a.provider))].sort();if(i.length>0)return{id:"backend-auth",label:"Backend authentication",status:"warn",detail:`${n.length} in use; ${i.length} expired or logged out: ${o.join(", ")}`,hint:M};let s=r.length>0?"; on a key connection: anthropic":"";return{id:"backend-auth",label:"Backend authentication",status:"pass",detail:`${n.length} in use; 0 expired or logged out${s}`}}async function qt(e,t){try{return Wt(await e.getAuthStatus(),t)}catch{return{id:"backend-auth",label:"Backend authentication",status:"warn",detail:"authentication summary unavailable",hint:M}}}async function Xt(e,t){let n=[];return Mt(n,e),Ut(n,e,t),Gt(n,e),Kt(n,e),n.push(...await Promise.all([Bt(e),qt(e,Ht(e))])),{title:"Backend Install / Login",checks:n}}function Ze(e){if(e==null)return!1;try{return JSON.parse(e),!0}catch{return!1}}function zt(e,t,n,r,i,o){if(!t.fileExists(n)){e.push({id:r,label:i,status:o,detail:`missing (${n})`});return}e.push(Ze(t.readText(n))?{id:r,label:i,status:"pass",detail:"valid"}:{id:r,label:i,status:o,detail:"invalid JSON"})}function Yt(e,t){let n={id:"models",label:"models.json"};if(!e.fileExists(t))return{...n,status:"warn",detail:`missing (${t})`,hint:"run `cortex init`"};try{let r=JSON.parse(e.readText(t)??"");if(r?.default&&(r.default=se(r.default)),ye(r?.default),!Array.isArray(r?.favorites))throw new Error("missing `favorites` array");return r.favorites.forEach(Ce),{...n,status:"pass",detail:`default: ${r.default.model}; favorites: ${r.favorites.length}`}}catch(r){return{...n,status:"fail",detail:r.message,hint:"re-run `cortex init`"}}}function Qt(e,t){let n=[],i=(t("CORTEX_PLATFORM")??"slack").split(",").map(o=>o.trim().toLowerCase()).filter(Boolean);n.push({id:"platform",label:"Platform",status:"pass",detail:`configured: ${i.join(", ")||"(none)"}`});for(let o of i)if(o==="slack"){let s=[],a=t("SLACK_BOT_TOKEN"),g=t("SLACK_SIGNING_SECRET"),O=t("SLACK_APP_TOKEN");a?a.startsWith("xoxb-")||s.push("SLACK_BOT_TOKEN should start with xoxb-"):s.push("SLACK_BOT_TOKEN missing"),g||s.push("SLACK_SIGNING_SECRET missing"),O?O.startsWith("xapp-")||s.push("SLACK_APP_TOKEN should start with xapp-"):s.push("SLACK_APP_TOKEN missing"),n.push(s.length===0?{id:"slack-creds",label:"Slack credentials",status:"pass",detail:"bot / signing / app tokens present"}:{id:"slack-creds",label:"Slack credentials",status:"fail",detail:s.join("; "),hint:"set Slack tokens in .env (see `cortex init`)"})}else if(o==="feishu"){let s=[];t("FEISHU_APP_ID")||s.push("FEISHU_APP_ID missing"),t("FEISHU_APP_SECRET")||s.push("FEISHU_APP_SECRET missing"),n.push(s.length===0?{id:"feishu-creds",label:"Feishu credentials",status:"pass",detail:"app id / secret present"}:{id:"feishu-creds",label:"Feishu credentials",status:"fail",detail:s.join("; "),hint:"set FEISHU_APP_ID / FEISHU_APP_SECRET in .env"})}else o==="test"?n.push({id:"test-platform",label:"Test platform",status:"skip",detail:"mock adapter (test only)"}):n.push({id:`platform-${o}`,label:`Platform: ${o}`,status:"warn",detail:"unknown platform name"});return{title:"Messaging Platform",checks:n}}async function U(e){let t=Tt(e),n=[Lt(e),await Xt(e,t),Qt(e,t)],r={pass:0,warn:0,fail:0,skip:0};for(let i of n)for(let o of i.checks)r[o.status]++;return{sections:n,counts:r,ok:r.fail===0}}async function et(e,t,n){let r=new Map;for(let s of e.sections)for(let a of s.checks)a.fixable&&(a.status==="fail"||a.status==="warn")&&r.set(a.id,a);let i=[],o=l.join(t.paths.CONFIG_DIR,".env");if(r.has("dirs")){for(let s of[t.paths.DATA_DIR,t.paths.CONFIG_DIR,t.paths.STORE_DIR])n.mkdirp(s);i.push({id:"dirs",label:"Data directories",applied:!0,detail:"created missing directories"})}if(r.has("auth-tokens")){n.ensureEnvFile(o);let s=n.ensureAuthTokens(o);i.push({id:"auth-tokens",label:"Auth tokens",applied:s.length>0,detail:s.length>0?`generated: ${s.join(", ")}`:"already present"})}return r.has("mcp-config")&&(n.regenerateMcpConfig(),i.push({id:"mcp-config",label:"mcp-config.json",applied:!0,detail:"regenerated"})),i}function Zt(e){if(e==="git")return he();let t=process.env.PATH||"",n=process.platform==="win32"?(process.env.PATHEXT||".EXE;.CMD;.BAT").split(";"):[""];for(let r of t.split(l.delimiter))if(r)for(let i of n){let o=l.join(r,e+i);try{if(u.existsSync(o))return!0}catch{}}return!1}function en(){let e;try{e=l.dirname(At(import.meta.resolve(k)))}catch{return null}for(;;){try{let n=JSON.parse(u.readFileSync(l.join(e,"package.json"),"utf8"));if(n?.name===k)return{package:k,version:typeof n.version=="string"?n.version:null}}catch{}let t=l.dirname(e);if(t===e)return{package:k,version:null};e=t}}function tt(){return{env:process.env,paths:{DATA_DIR:y,CONFIG_DIR:te,STORE_DIR:ne},nodeVersion:process.version,requiredNodeMajor:20,fileExists:e=>{try{return u.existsSync(e)}catch{return!1}},isWritable:e=>{try{return u.accessSync(e,u.constants.W_OK),!0}catch{return!1}},readText:e=>{try{return u.readFileSync(e,"utf8")}catch{return null}},parseDotenv:e=>(0,Ye.parse)(e),commandExists:Zt,pidAlive:b,resolvePiSdk:en,loadPiRuntime:()=>$e(),getAuthStatus:()=>P(),defaultSelection:tn,claudeConnections:()=>be.claudeConnections().filter(e=>e.kind==="key"||e.kind==="account").map(e=>e.id)}}function tn(){try{let e=Ie();return e?{backend:e.backend,connection:e.backend==="claude"?ke(e):null}:null}catch{return null}}function nt(){return{mkdirp:e=>{u.mkdirSync(e,{recursive:!0})},ensureEnvFile:e=>{u.existsSync(e)||(u.mkdirSync(l.dirname(e),{recursive:!0}),u.writeFileSync(e,""))},ensureAuthTokens:e=>le({envPath:e}).generated,regenerateMcpConfig:()=>ve()}}function nn(){return _({name:"cortex doctor",description:"Health-check the Cortex installation \u2014 runtime, backend/login, messaging platform.",usage:"cortex doctor [options]",options:[{flag:"--fix",description:"Apply safe, idempotent repairs (generate missing tokens, create dirs, rebuild mcp-config)"},{flag:"--json",description:"Emit the report as JSON"},{flag:"--help, -h",description:"Show this help"}],examples:[{description:"Run a read-only diagnosis",command:"cortex doctor"},{description:"Diagnose and auto-repair fixable issues",command:"cortex doctor --fix"},{description:"Machine-readable output",command:"cortex doctor --json"}]})}var rn={pass:"[OK] ",warn:"[WARN]",fail:"[FAIL]",skip:"[--] "};function on(e,t){let n=["Cortex Doctor",""];for(let s of e.sections){n.push(s.title);for(let a of s.checks)n.push(` ${rn[a.status]} ${a.label} \u2014 ${a.detail}`),a.hint&&(a.status==="fail"||a.status==="warn")&&n.push(` \u21B3 ${a.hint}`);n.push("")}if(t.length>0){n.push("Fixes applied:");for(let s of t)n.push(` ${s.applied?"[OK] ":"[--] "} ${s.label} \u2014 ${s.detail}`);n.push("")}let{pass:r,warn:i,fail:o}=e.counts;return n.push(`Summary: ${r} passed, ${i} warning${i===1?"":"s"}, ${o} failed`),(o>0||i>0)&&e.sections.some(a=>a.checks.some(g=>g.fixable&&(g.status==="fail"||g.status==="warn")))&&n.push("Run `cortex doctor --fix` to auto-repair fixable issues."),n.join(`
4
+ import{d as Le,e as Me,f as Ue,g as He,h,i as Ge,l as Ke,w as Ve}from"./chunk-KZSAFVSY.js";import{a as Je,b as Be,c as We,d as qe,e as Xe,h as S,i as L}from"./chunk-Q7BZLPBU.js";import{a as ue,b as de,d as me}from"./chunk-WU7RNAZD.js";import{a as De,b as we,c as Ee,d as Pe,e as _e,f as je,i as Ae,j as Re,k as Oe,l as Te,m as Ne}from"./chunk-FDC2GRBK.js";import{a as k,b as $e,i as P}from"./chunk-G264APQN.js";import{f as ve,m as Ie}from"./chunk-HVN37UXD.js";import{a as Se}from"./chunk-5NRGVROY.js";import{a as E}from"./chunk-LEAV3FFG.js";import{a as he}from"./chunk-4HRI75GU.js";import{b as ae,c as ce,h as le}from"./chunk-UEEW2R4E.js";import{c as ke}from"./chunk-VHX2GHBF.js";import{L as be,n as Ce,o as ye}from"./chunk-C6YVF7EI.js";import{h as pe}from"./chunk-BVEDNESB.js";import{a as _,b as m,c as Fe}from"./chunk-PMG4YGDU.js";import{d as xe}from"./chunk-RG5GP4RB.js";import{a as b,b as ge,c as w,e as F}from"./chunk-YAEHSSR4.js";import{a as N}from"./chunk-R2CCD4OF.js";import{b as oe,q as se}from"./chunk-LIIZI3HY.js";import{e as Z}from"./chunk-TRXLIL7V.js";import{e as c}from"./chunk-7GGPYU5E.js";import{e as ie}from"./chunk-7W7VYUTK.js";import{b as fe}from"./chunk-JGUEIW2W.js";import{a as jt,b as ee,e as y,j as te,k as ne,q as p,r as T,s as re}from"./chunk-T54CZKNJ.js";import{e as _t}from"./chunk-WHC7AYZD.js";import{fork as A}from"child_process";import*as d from"path";import*as wt from"net";import{fileURLToPath as On}from"url";import{existsSync as f,readdirSync as Tn,readFileSync as X,unlinkSync as z}from"fs";var Ye=_t(jt(),1);import*as u from"node:fs";import*as l from"node:path";import{fileURLToPath as At}from"node:url";function Rt(e){if(typeof e!="string")return;let t=e.trim();if(!(!t||t==="null"||t==="undefined"))return t}function Ot(e){let t=e.match(/^v?(\d+)/);return t?Number(t[1]):0}function Tt(e){let t=l.join(e.paths.CONFIG_DIR,".env"),n={},r=e.readText(t);if(r!=null)try{n=e.parseDotenv(r)}catch{n={}}return i=>Rt(e.env[i]??n[i])}function Nt(e){let t=e.defaultSelection()?.backend??"claude";return t==="pi"?{id:"backend-runtime",label:"Backend runtime",status:"pass",detail:"backend: pi runs in-process from the bundled SDK (no CLI needed)"}:e.commandExists("claude")?{id:"backend-runtime",label:"Backend runtime",status:"pass",detail:`claude found on PATH (backend: ${t})`}:{id:"backend-runtime",label:"Backend runtime",status:"warn",detail:`claude not on PATH (backend: ${t})`,hint:"Install/login the claude CLI"}}function Ft(e){return e.commandExists("git")?{id:"git",label:"git",status:"pass",detail:"usable on PATH"}:(e.platform??process.platform)==="win32"?{id:"git",label:"git",status:"fail",detail:"unavailable",hint:"Install Git for Windows \u2014 shell tools require Git Bash"}:{id:"git",label:"git",status:"warn",detail:"unavailable (optional)",hint:"Install Git to enable version history and Git-sourced extensions"}}function Lt(e){let t=[],n=Ot(e.nodeVersion);t.push(n>=e.requiredNodeMajor?{id:"node-version",label:"Node version",status:"pass",detail:`${e.nodeVersion} (>=${e.requiredNodeMajor})`}:{id:"node-version",label:"Node version",status:"warn",detail:`${e.nodeVersion} \u2014 Cortex requires Node >=${e.requiredNodeMajor}`,hint:"Upgrade Node.js"}),t.push(Ft(e)),t.push(Nt(e));let r=l.join(e.paths.STORE_DIR,l.basename(p)),i=e.fileExists(r)?e.readText(r):null,o=i?Number(i.trim()):NaN;return Number.isFinite(o)&&e.pidAlive(o)?t.push({id:"daemon",label:"Daemon",status:"pass",detail:`running (pid ${o})`}):t.push({id:"daemon",label:"Daemon",status:"skip",detail:"not running",hint:"Start with `cortex daemon`"}),{title:"Runtime & Process",checks:t}}function Mt(e,t){let n=[];for(let[r,i]of Object.entries(t.paths))t.fileExists(i)?t.isWritable(i)||n.push(`${r} not writable (${i})`):n.push(`${r} missing (${i})`);e.push(n.length===0?{id:"dirs",label:"Data directories",status:"pass",detail:"present and writable"}:{id:"dirs",label:"Data directories",status:"fail",detail:n.join("; "),hint:"run `cortex doctor --fix` or `cortex init`",fixable:!0})}function Ut(e,t,n){let r=l.join(t.paths.CONFIG_DIR,".env");e.push(t.fileExists(r)?{id:"env-file",label:".env file",status:"pass",detail:r}:{id:"env-file",label:".env file",status:"fail",detail:`missing (${r})`,hint:"run `cortex init`"});let i=[ae,ce].filter(o=>!n(o));e.push(i.length===0?{id:"auth-tokens",label:"Auth tokens",status:"pass",detail:"client + webhook tokens set"}:{id:"auth-tokens",label:"Auth tokens",status:"fail",detail:`missing: ${i.join(", ")}`,hint:"run `cortex doctor --fix` to generate",fixable:!0})}function Qe(e){let t=e.defaultSelection();return t?.backend!=="claude"||!t.connection||t.connection===oe?null:t.connection}function Ht(e){let t=Qe(e);return t!==null&&e.claudeConnections().includes(t)}function Gt(e,t){let n=Qe(t);n===null?e.push({id:"claude-connection",label:"Claude connection",status:"skip",detail:"default does not use a key connection"}):t.claudeConnections().includes(n)?e.push({id:"claude-connection",label:"Claude connection",status:"pass",detail:`${n} configured`}):e.push({id:"claude-connection",label:"Claude connection",status:"warn",detail:`${n} is not configured`,hint:"add the connection in Settings or pick another model"})}function Kt(e,t){let{CONFIG_DIR:n,STORE_DIR:r}=t.paths,i=l.join(r,"agent-state.json"),o=t.fileExists(i)?"agent-state.json":"mode.json";zt(e,t,t.fileExists(i)?i:l.join(r,"mode.json"),"mode-json",o,"warn"),e.push(Yt(t,l.join(n,"models.json")));let s=l.join(n,"mcp-config.json");t.fileExists(s)?Ze(t.readText(s))?e.push({id:"mcp-config",label:"mcp-config.json",status:"pass",detail:"valid"}):e.push({id:"mcp-config",label:"mcp-config.json",status:"warn",detail:"invalid JSON",hint:"run `cortex doctor --fix` to regenerate",fixable:!0}):e.push({id:"mcp-config",label:"mcp-config.json",status:"warn",detail:`missing (${s})`,hint:"run `cortex doctor --fix` to regenerate",fixable:!0})}var M="See docs/backends.md#remote-login",Vt=new Set(["expired","logged-out"]),Jt="Reinstall the Cortex server package \u2014 the PI SDK ships with it";async function Bt(e){let t=e.resolvePiSdk();if(!t)return{id:"pi-runtime",label:"PI runtime",status:"warn",detail:`bundled PI SDK not resolvable (${k})`,hint:Jt};try{let n=await e.loadPiRuntime();if(n.available&&typeof n.runtime.login=="function"){let r=n.version??t.version,i=r?` ${r}`:"";return{id:"pi-runtime",label:"PI runtime",status:"pass",detail:`in-process SDK ${t.package}${i}; login export found`}}}catch{}return{id:"pi-runtime",label:"PI runtime",status:"warn",detail:"bundled PI runtime or login export unavailable",hint:M}}function ze(e,t){return t&&(e.connection??null)===null&&e.backend==="claude"&&e.provider==="anthropic"&&e.state==="logged-out"}function Wt(e,t){let n=e.accounts.filter(a=>a.inUse),r=n.filter(a=>ze(a,t)),i=n.filter(a=>Vt.has(a.state)&&!ze(a,t)),o=[...new Set(i.map(a=>a.provider))].sort();if(i.length>0)return{id:"backend-auth",label:"Backend authentication",status:"warn",detail:`${n.length} in use; ${i.length} expired or logged out: ${o.join(", ")}`,hint:M};let s=r.length>0?"; on a key connection: anthropic":"";return{id:"backend-auth",label:"Backend authentication",status:"pass",detail:`${n.length} in use; 0 expired or logged out${s}`}}async function qt(e,t){try{return Wt(await e.getAuthStatus(),t)}catch{return{id:"backend-auth",label:"Backend authentication",status:"warn",detail:"authentication summary unavailable",hint:M}}}async function Xt(e,t){let n=[];return Mt(n,e),Ut(n,e,t),Gt(n,e),Kt(n,e),n.push(...await Promise.all([Bt(e),qt(e,Ht(e))])),{title:"Backend Install / Login",checks:n}}function Ze(e){if(e==null)return!1;try{return JSON.parse(e),!0}catch{return!1}}function zt(e,t,n,r,i,o){if(!t.fileExists(n)){e.push({id:r,label:i,status:o,detail:`missing (${n})`});return}e.push(Ze(t.readText(n))?{id:r,label:i,status:"pass",detail:"valid"}:{id:r,label:i,status:o,detail:"invalid JSON"})}function Yt(e,t){let n={id:"models",label:"models.json"};if(!e.fileExists(t))return{...n,status:"warn",detail:`missing (${t})`,hint:"run `cortex init`"};try{let r=JSON.parse(e.readText(t)??"");if(r?.default&&(r.default=se(r.default)),ye(r?.default),!Array.isArray(r?.favorites))throw new Error("missing `favorites` array");return r.favorites.forEach(Ce),{...n,status:"pass",detail:`default: ${r.default.model}; favorites: ${r.favorites.length}`}}catch(r){return{...n,status:"fail",detail:r.message,hint:"re-run `cortex init`"}}}function Qt(e,t){let n=[],i=(t("CORTEX_PLATFORM")??"slack").split(",").map(o=>o.trim().toLowerCase()).filter(Boolean);n.push({id:"platform",label:"Platform",status:"pass",detail:`configured: ${i.join(", ")||"(none)"}`});for(let o of i)if(o==="slack"){let s=[],a=t("SLACK_BOT_TOKEN"),g=t("SLACK_SIGNING_SECRET"),O=t("SLACK_APP_TOKEN");a?a.startsWith("xoxb-")||s.push("SLACK_BOT_TOKEN should start with xoxb-"):s.push("SLACK_BOT_TOKEN missing"),g||s.push("SLACK_SIGNING_SECRET missing"),O?O.startsWith("xapp-")||s.push("SLACK_APP_TOKEN should start with xapp-"):s.push("SLACK_APP_TOKEN missing"),n.push(s.length===0?{id:"slack-creds",label:"Slack credentials",status:"pass",detail:"bot / signing / app tokens present"}:{id:"slack-creds",label:"Slack credentials",status:"fail",detail:s.join("; "),hint:"set Slack tokens in .env (see `cortex init`)"})}else if(o==="feishu"){let s=[];t("FEISHU_APP_ID")||s.push("FEISHU_APP_ID missing"),t("FEISHU_APP_SECRET")||s.push("FEISHU_APP_SECRET missing"),n.push(s.length===0?{id:"feishu-creds",label:"Feishu credentials",status:"pass",detail:"app id / secret present"}:{id:"feishu-creds",label:"Feishu credentials",status:"fail",detail:s.join("; "),hint:"set FEISHU_APP_ID / FEISHU_APP_SECRET in .env"})}else o==="test"?n.push({id:"test-platform",label:"Test platform",status:"skip",detail:"mock adapter (test only)"}):n.push({id:`platform-${o}`,label:`Platform: ${o}`,status:"warn",detail:"unknown platform name"});return{title:"Messaging Platform",checks:n}}async function U(e){let t=Tt(e),n=[Lt(e),await Xt(e,t),Qt(e,t)],r={pass:0,warn:0,fail:0,skip:0};for(let i of n)for(let o of i.checks)r[o.status]++;return{sections:n,counts:r,ok:r.fail===0}}async function et(e,t,n){let r=new Map;for(let s of e.sections)for(let a of s.checks)a.fixable&&(a.status==="fail"||a.status==="warn")&&r.set(a.id,a);let i=[],o=l.join(t.paths.CONFIG_DIR,".env");if(r.has("dirs")){for(let s of[t.paths.DATA_DIR,t.paths.CONFIG_DIR,t.paths.STORE_DIR])n.mkdirp(s);i.push({id:"dirs",label:"Data directories",applied:!0,detail:"created missing directories"})}if(r.has("auth-tokens")){n.ensureEnvFile(o);let s=n.ensureAuthTokens(o);i.push({id:"auth-tokens",label:"Auth tokens",applied:s.length>0,detail:s.length>0?`generated: ${s.join(", ")}`:"already present"})}return r.has("mcp-config")&&(n.regenerateMcpConfig(),i.push({id:"mcp-config",label:"mcp-config.json",applied:!0,detail:"regenerated"})),i}function Zt(e){if(e==="git")return he();let t=process.env.PATH||"",n=process.platform==="win32"?(process.env.PATHEXT||".EXE;.CMD;.BAT").split(";"):[""];for(let r of t.split(l.delimiter))if(r)for(let i of n){let o=l.join(r,e+i);try{if(u.existsSync(o))return!0}catch{}}return!1}function en(){let e;try{e=l.dirname(At(import.meta.resolve(k)))}catch{return null}for(;;){try{let n=JSON.parse(u.readFileSync(l.join(e,"package.json"),"utf8"));if(n?.name===k)return{package:k,version:typeof n.version=="string"?n.version:null}}catch{}let t=l.dirname(e);if(t===e)return{package:k,version:null};e=t}}function tt(){return{env:process.env,paths:{DATA_DIR:y,CONFIG_DIR:te,STORE_DIR:ne},nodeVersion:process.version,requiredNodeMajor:20,fileExists:e=>{try{return u.existsSync(e)}catch{return!1}},isWritable:e=>{try{return u.accessSync(e,u.constants.W_OK),!0}catch{return!1}},readText:e=>{try{return u.readFileSync(e,"utf8")}catch{return null}},parseDotenv:e=>(0,Ye.parse)(e),commandExists:Zt,pidAlive:b,resolvePiSdk:en,loadPiRuntime:()=>$e(),getAuthStatus:()=>P(),defaultSelection:tn,claudeConnections:()=>be.claudeConnections().filter(e=>e.kind==="key"||e.kind==="account").map(e=>e.id)}}function tn(){try{let e=Ie();return e?{backend:e.backend,connection:e.backend==="claude"?ke(e):null}:null}catch{return null}}function nt(){return{mkdirp:e=>{u.mkdirSync(e,{recursive:!0})},ensureEnvFile:e=>{u.existsSync(e)||(u.mkdirSync(l.dirname(e),{recursive:!0}),u.writeFileSync(e,""))},ensureAuthTokens:e=>le({envPath:e}).generated,regenerateMcpConfig:()=>ve()}}function nn(){return _({name:"cortex doctor",description:"Health-check the Cortex installation \u2014 runtime, backend/login, messaging platform.",usage:"cortex doctor [options]",options:[{flag:"--fix",description:"Apply safe, idempotent repairs (generate missing tokens, create dirs, rebuild mcp-config)"},{flag:"--json",description:"Emit the report as JSON"},{flag:"--help, -h",description:"Show this help"}],examples:[{description:"Run a read-only diagnosis",command:"cortex doctor"},{description:"Diagnose and auto-repair fixable issues",command:"cortex doctor --fix"},{description:"Machine-readable output",command:"cortex doctor --json"}]})}var rn={pass:"[OK] ",warn:"[WARN]",fail:"[FAIL]",skip:"[--] "};function on(e,t){let n=["Cortex Doctor",""];for(let s of e.sections){n.push(s.title);for(let a of s.checks)n.push(` ${rn[a.status]} ${a.label} \u2014 ${a.detail}`),a.hint&&(a.status==="fail"||a.status==="warn")&&n.push(` \u21B3 ${a.hint}`);n.push("")}if(t.length>0){n.push("Fixes applied:");for(let s of t)n.push(` ${s.applied?"[OK] ":"[--] "} ${s.label} \u2014 ${s.detail}`);n.push("")}let{pass:r,warn:i,fail:o}=e.counts;return n.push(`Summary: ${r} passed, ${i} warning${i===1?"":"s"}, ${o} failed`),(o>0||i>0)&&e.sections.some(a=>a.checks.some(g=>g.fixable&&(g.status==="fail"||g.status==="warn")))&&n.push("Run `cortex doctor --fix` to auto-repair fixable issues."),n.join(`
5
5
  `).trimEnd()+`
6
6
  `}async function rt(e,t){if(e.includes("--help")||e.includes("-h"))return{exitCode:0,stdout:nn(),stderr:""};let n=e.includes("--json"),r=e.includes("--fix"),i=t?.diag??tt(),o=t?.fix??nt(),s=await U(i),a=[];r&&(a=await et(s,i,o),s=await U(i));let g=n?JSON.stringify({...s,fixes:r?a:void 0},null,2)+`
7
7
  `:on(s,a);return{exitCode:s.ok?0:1,stdout:g,stderr:""}}var it=["list","add","remove"];function sn(){return{validValues:c("provider.cli.validValues"),hint:c("provider.cli.hint")}}function x(e,t){return{exitCode:1,stdout:"",stderr:m(e,{...t,labels:sn()})}}function ot(){return _({name:"cortex auth provider",description:c("provider.cli.description"),usage:"cortex auth provider <list|add|remove> [options]",commands:[{name:"list",description:c("provider.cli.listDescription")},{name:"add",description:c("provider.cli.addDescription")},{name:"remove",description:c("provider.cli.removeDescription")}],options:[{flag:"--name <name>",description:c("provider.cli.nameDescription")},{flag:"--api <api>",description:`${c("provider.cli.apiDescription")} (${E.join(" | ")})`},{flag:"--url <url>",description:c("provider.cli.urlDescription")},{flag:"--key <key|->",description:c("provider.cli.keyDescription")},{flag:"--model <id>",description:c("provider.cli.modelDescription")},{flag:"--dry-run",description:c("provider.cli.dryRunDescription")},{flag:"--json",description:c("provider.cli.jsonDescription")},{flag:"--help, -h",description:c("provider.cli.helpDescription")}],examples:[{description:c("provider.cli.exampleAdd"),command:"cortex auth provider add --name my-vllm --api anthropic-messages --url http://127.0.0.1:8100 --model Model-27B"},{description:c("provider.cli.exampleAddPiped"),command:"pass show my-endpoint | cortex auth provider add --name my-proxy --api openai-completions --url https://proxy.example.com/v1 --model small --key -"},{description:c("provider.cli.exampleList"),command:"cortex auth provider list --json"},{description:c("provider.cli.exampleRemove"),command:"cortex auth provider remove --name my-vllm --dry-run"}],labels:{usage:c("cmd.auth.cli.helpUsage"),commands:c("cmd.auth.cli.helpCommands"),options:c("cmd.auth.cli.helpOptions"),examples:c("cmd.auth.cli.helpExamples")}})}var an=new Set(["--name","--api","--url","--key"]);function cn(e){let t=new Map,n=[],r=!1,i=!1;for(let o=0;o<e.length;o+=1){let s=e[o];if(s==="--json"){r=!0;continue}if(s==="--dry-run"){i=!0;continue}if(s==="--model"||an.has(s)){let a=e[o+1];if(a===void 0||a.startsWith("--"))return x(c("provider.cli.flagNeedsValue",{flag:s}),{hint:"cortex auth provider --help"});o+=1,s==="--model"?n.push(a):t.set(s,a);continue}return x(c("provider.cli.unknownFlag",{flag:s}),{validValues:["--name","--api","--url","--key","--model","--dry-run","--json"],hint:"cortex auth provider --help"})}return{values:t,models:n,json:r,dryRun:i}}function H(e){return c(`provider.issue.${e}`)}function ln(e){return e.routed?c("provider.cli.listItem",{name:e.name,api:e.api,upstream:e.upstreamUrl??""}):c("provider.cli.listItemUnrouted",{name:e.name,api:e.api})}function un(e,t){let n=Ee(t);return e.json?{exitCode:0,stdout:JSON.stringify({ok:!0,providers:n},null,2),stderr:""}:{exitCode:0,stdout:n.length===0?c("provider.cli.listEmpty"):n.map(ln).join(`
@@ -25,7 +25,7 @@ Start it with: cortex daemon
25
25
  `),process.exit(1)),f(W)||(v.error(`TUI entry not found: ${W}`),v.error("Run `npm run build` first."),process.exit(1));let r=["--port",String(n)];t.resume&&r.push("--resume"),t.project&&r.push("--project",t.project),A(W,r,{stdio:"inherit"}).on("exit",o=>process.exit(o??0)),await new Promise(()=>{})}function R(){if(!f(p))return{result:{exitCode:0,stdout:`Cortex daemon is not running.
26
26
  `,stderr:""}};let e=w(p);if(e===null){try{z(p)}catch{}return{result:{exitCode:0,stdout:`Cortex daemon is not running (removed corrupted PID file).
27
27
  `,stderr:""}}}if(!ge(p,e)){try{z(p)}catch{}return{result:{exitCode:0,stdout:`Cortex daemon is not running (removed stale PID file for PID ${e}).
28
- `,stderr:""}}}return{pid:e}}async function Mn(){let e=R();if("result"in e)return It(e.result);let t=await Un(e.pid);return t.daemonGone?It(t.result):t.result}async function It(e){let{exitCode:t,stdout:n,stderr:r}=e;try{let{stopLaunchedLocalClients:i}=await import("./local-client-stop-5YOLXGYT.js");for(let{device:o,pid:s,outcome:a}of await i())a==="stopped"&&(n+=`Stopped local client ${o} (PID ${s}).
28
+ `,stderr:""}}}return{pid:e}}async function Mn(){let e=R();if("result"in e)return It(e.result);let t=await Un(e.pid);return t.daemonGone?It(t.result):t.result}async function It(e){let{exitCode:t,stdout:n,stderr:r}=e;try{let{stopLaunchedLocalClients:i}=await import("./local-client-stop-RS4AHNF4.js");for(let{device:o,pid:s,outcome:a}of await i())a==="stopped"&&(n+=`Stopped local client ${o} (PID ${s}).
29
29
  `),a==="unverified"&&(r+=`Left local client ${o} (PID ${s}) running: could not confirm the process is its client.
30
30
  `),a==="survived"&&(t=1,r+=`Local client ${o} (PID ${s}) did not exit.
31
31
  `)}catch(i){r+=`Could not stop the local client: ${i.message||String(i)}
@@ -44,7 +44,7 @@ Start it with: cortex daemon
44
44
  `}}return{exitCode:0,stdout:`Sent ${n} to app.js (PID ${t}). Daemon will restart it automatically.
45
45
  `,stderr:""}}function Vn(){let e={INSTALL_ROOT:ee,...h()},t=d.join(e.CONFIG_DIR,".env"),n=d.join(e.CONFIG_DIR,"mcp-config.json"),r=d.join(e.STORE_DIR,"agent-state.json"),i=d.join(e.STORE_DIR,"mode.json"),o=0;try{o=Tn(e.STORE_DIR).length}catch{}let s={dataDirExists:f(e.DATA_DIR)&&o>0,dotEnvExists:f(t),mcpConfigExists:f(n),modeJsonExists:f(r)||f(i)};return Ke(e,s)}function Dt(e,t){let n=e.indexOf(t);return n!==-1&&e[n+1]?e[n+1]:void 0}async function Jn(e){if(e.includes("--help")||e.includes("-h"))return{exitCode:0,stdout:Je(),stderr:""};let t=Dt(e,"--home"),n=Dt(e,"--answers");try{let r=n?Ge(X(d.resolve(n),"utf-8")):void 0;return await Ve({homeDir:t,force:e.includes("--force"),answers:r,jsonEvents:e.includes("--json")}),{exitCode:0,stdout:"",stderr:""}}catch(r){return r instanceof Le&&r.exitCode===130?{exitCode:130,stdout:"",stderr:c("init.cancel")}:{exitCode:1,stdout:"",stderr:r.message||String(r)}}}function Bn(){let e=re;try{return F(e),{exitCode:0,stdout:`Restart trigger touched: ${e}
46
46
  If a daemon is running it will drain and respawn app.js.
47
- `,stderr:""}}catch(t){return{exitCode:1,stdout:"",stderr:`Could not write ${e}: ${t.message||String(t)}`}}}async function Wn(e){let{runCli:t,getInstallHelp:n}=await import("./install-cli-ABBD7DO5.js");return e.includes("--help")||e.includes("-h")?{exitCode:0,stdout:n(),stderr:""}:t(e)}function qn(e){return e[1]==="--hard"?$t(!1):e[1]==="--force"?$t(!0):Kn()}function Xn(e){return e[0]==="stop"?Mn():e[0]==="status"?Hn():e[0]==="restart"?qn(e):null}async function zn(e){let t=Xn(e);return t||(e.includes("--help")||e.includes("-h")?{exitCode:0,stdout:S(),stderr:""}:e.includes("--version")||e.includes("-V")?{exitCode:0,stdout:`${N}
47
+ `,stderr:""}}catch(t){return{exitCode:1,stdout:"",stderr:`Could not write ${e}: ${t.message||String(t)}`}}}async function Wn(e){let{runCli:t,getInstallHelp:n}=await import("./install-cli-FALWKQYO.js");return e.includes("--help")||e.includes("-h")?{exitCode:0,stdout:n(),stderr:""}:t(e)}function qn(e){return e[1]==="--hard"?$t(!1):e[1]==="--force"?$t(!0):Kn()}function Xn(e){return e[0]==="stop"?Mn():e[0]==="status"?Hn():e[0]==="restart"?qn(e):null}async function zn(e){let t=Xn(e);return t||(e.includes("--help")||e.includes("-h")?{exitCode:0,stdout:S(),stderr:""}:e.includes("--version")||e.includes("-V")?{exitCode:0,stdout:`${N}
48
48
  `,stderr:""}:{exitCode:0,stdout:"",stderr:`'daemon' must be run from the main entry point, not imported.
49
- Use: node dist/entry/cli.js daemon`})}var Yn={init:e=>Jn(e),config:()=>({exitCode:0,stdout:Vn(),stderr:""}),auth:(e,t)=>ct(e,t.getAuthStatus??P,t.customProviderStores??we()),doctor:e=>rt(e),feishu:e=>Ue(e),restart:()=>Bn(),ui:e=>mt(e),client:e=>bt(e),path:e=>St(e),install:e=>Wn(e),schedule:async e=>(await import("./schedule-cli-4T4YC5V5.js")).runScheduleCli(e),memory:async e=>(await import("./memory-cli-5SSF6YJM.js")).runMemoryCli(e),start:()=>({exitCode:0,stdout:"",stderr:`'start' must be run from the main entry point, not imported.
49
+ Use: node dist/entry/cli.js daemon`})}var Yn={init:e=>Jn(e),config:()=>({exitCode:0,stdout:Vn(),stderr:""}),auth:(e,t)=>ct(e,t.getAuthStatus??P,t.customProviderStores??we()),doctor:e=>rt(e),feishu:e=>Ue(e),restart:()=>Bn(),ui:e=>mt(e),client:e=>bt(e),path:e=>St(e),install:e=>Wn(e),schedule:async e=>(await import("./schedule-cli-V7Y2BBVY.js")).runScheduleCli(e),memory:async e=>(await import("./memory-cli-DIT4DQF3.js")).runMemoryCli(e),start:()=>({exitCode:0,stdout:"",stderr:`'start' must be run from the main entry point, not imported.
50
50
  Use: node dist/entry/cli.js start`}),daemon:e=>zn(e)};async function q(e,t={}){if(e.length===0||e[0]==="--help"||e[0]==="-h")return{exitCode:0,stdout:S(),stderr:""};let n=Yn[e[0]];return n?n(e.slice(1),t):{exitCode:1,stdout:"",stderr:`Unknown command: '${e[0]}'. Use --help to see available commands.`}}function Qn(){let e=process.argv.slice(2);(e.length===0||e[0]==="--help"||e[0]==="-h")&&(console.log(S()),process.exit(0));let t=e[0],n=e.slice(1);if((n.includes("--help")||n.includes("-h"))&&(t==="daemon"&&(console.log(S()),process.exit(0)),t==="start"&&(console.log(S()),process.exit(0)),t==="tui"&&(console.log(Be()),process.exit(0))),(n.includes("--version")||n.includes("-V"))&&t==="daemon"&&(console.log(N),process.exit(0)),t==="start"){f(B)||(v.error(`Entry not found: ${B}`),v.error("Run `npm run build` first."),process.exit(1)),A(B,[],{cwd:y,stdio:"inherit",env:{...process.env}}).on("exit",i=>process.exit(i??0));return}if(t==="daemon"){if(n[0]==="restart-self"){q(["daemon","stop"]).then(async i=>{i.stdout&&console.log(i.stdout),i.stderr&&console.error(i.stderr),f(D)||(v.error(`Entry not found: ${D}`),v.error("Run `npm run build` first."),process.exit(1)),console.log("Starting daemon..."),A(D,[],{cwd:y,detached:!0,stdio:"ignore",env:{...process.env}}),process.exit(0)});return}if(n[0]==="stop"||n[0]==="status"||n[0]==="restart"){q(e).then(i=>{i.stdout&&console.log(i.stdout),i.stderr&&console.error(i.stderr),process.exit(i.exitCode)});return}f(D)||(v.error(`Entry not found: ${D}`),v.error("Run `npm run build` first."),process.exit(1));let r={cwd:y,windowsHide:!0,detached:!0,stdio:"ignore",env:{...process.env}};A(D,[],r),process.exit(0)}if(t==="tui"){Ln(n);return}q(e).then(r=>{r.stdout&&console.log(r.stdout),r.stderr&&console.error(r.stderr),process.exit(r.exitCode)})}fe(new URL("dist/entry/cli.js",__cortexPackageRoot).href)&&Qn();export{Nn as a,Fn as b,Ln as c,Vn as d,q as e,Qn as f};
@@ -1,4 +1,4 @@
1
1
  import { createRequire as __cortexCreateRequire } from 'node:module';
2
2
  const require = __cortexCreateRequire(import.meta.url);
3
3
  const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{b as H}from"./chunk-UT6DGZDO.js";import{m as B}from"./chunk-ETIBCA2S.js";import{a as J,b as Y}from"./chunk-WZYS2HAK.js";import{C as v,E as P,H as C,K as x,U as L,V as Z,W as D,Z as p,_ as I,a as f,c as T,d as b,e as g,f as R,g as G,h as W,i as F,n as u,v as _,x as E,z as k}from"./chunk-TMV2ZDOI.js";import{a as U,b as z,d as X}from"./chunk-5T7IX5KN.js";import{i as V}from"./chunk-OE4KH3NJ.js";import{a as N}from"./chunk-NRD57ICT.js";import{D as j}from"./chunk-W34AK4SK.js";import{e as O}from"./chunk-VBN2JSER.js";import{b as q}from"./chunk-NXZS5PEW.js";var Q=Symbol.for("mcp.completable");function A(s){return!!s&&typeof s=="object"&&Q in s}function ee(s){return s[Q]?.complete}var K;(function(s){s.Completable="McpCompletable"})(K||(K={}));var ce=/^[A-Za-z0-9._-]{1,128}$/;function de(s){let e=[];if(s.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(s.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${s.length})`]};if(s.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),s.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(s.startsWith("-")||s.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(s.startsWith(".")||s.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!ce.test(s)){let t=s.split("").filter(r=>!/[A-Za-z0-9._-]/.test(r)).filter((r,o,a)=>a.indexOf(r)===o);return e.push(`Tool name contains invalid characters: ${t.map(r=>`"${r}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function ue(s,e){if(e.length>0){console.warn(`Tool name validation warning for "${s}":`);for(let t of e)console.warn(` - ${t}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function M(s){let e=de(s);return ue(s,e.warnings),e.isValid}var y=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,r){let o={taskSupport:"required",...t.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,o,t._meta,r)}};function pe(s,e){let t=0,r=[s];for(;r.length>0;){let o=r.pop();if(!(o===null||typeof o!="object"))if(Array.isArray(o))for(let a of o){if(++t>e)return t;a!==null&&typeof a=="object"&&r.push(a)}else for(let a in o){if(!Object.prototype.hasOwnProperty.call(o,a))continue;if(++t>e)return t;let n=o[a];n!==null&&typeof n=="object"&&r.push(n)}}return t}function me(s){if(!(s===void 0||s===1/0)){if(typeof s!="number"||Number.isNaN(s)||s<1)throw new RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(s)}`);return s}}var S=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new J(e,t),this._maxToolInputElements=me(t?.maxToolInputElements),t?.capabilities?.tools&&this.setToolRequestHandlers(),t?.capabilities?.resources&&this.setResourceRequestHandlers(),t?.capabilities?.prompts&&this.setPromptRequestHandlers()}get experimental(){return this._experimental||(this._experimental={tasks:new y(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(h(C)),this.server.assertCanSetRequestHandler(h(x)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(C,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let r={name:e,title:t.title,description:t.description,inputSchema:(()=>{let o=g(t.inputSchema);return o?I(o,{strictUnions:!0,pipeStrategy:"input"}):he})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let o=g(t.outputSchema);o&&(r.outputSchema=I(o,{strictUnions:!0,pipeStrategy:"output"}))}return r})})),this.server.setRequestHandler(x,async(e,t)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new p(u.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new p(u.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,a=r.execution?.taskSupport,n="createTask"in r.handler;if((a==="required"||a==="optional")&&!n)throw new p(u.InternalError,`Tool ${e.params.name} has taskSupport '${a}' but was not registered with registerToolTask`);if(a==="required"&&!o)throw new p(u.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(a==="optional"&&!o&&n)return await this.handleAutomaticTaskPolling(r,e,t);let i=await this.validateToolInput(r,e.params.arguments,e.params.name),c=await this.executeToolHandler(r,i,t);return o||await this.validateToolOutput(r,c,e.params.name),c}catch(r){if(r instanceof p&&r.code===u.UrlElicitationRequired)throw r;return this.createToolError(r instanceof Error?r.message:String(r))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,r){if(this._maxToolInputElements!==void 0&&pe(t,this._maxToolInputElements)>this._maxToolInputElements)throw new p(u.InvalidParams,`Invalid arguments for tool ${r}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!e.inputSchema)return;let a=g(e.inputSchema)??e.inputSchema,n=await T(a,t??{});if(!n.success){let i="error"in n?n.error:"Unknown error",c=R(i);throw new p(u.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${c}`)}return n.data}async validateToolOutput(e,t,r){if(!e.outputSchema||!("content"in t)||t.isError)return;if(!t.structuredContent)throw new p(u.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let o=g(e.outputSchema),a=await T(o,t.structuredContent);if(!a.success){let n="error"in a?a.error:"Unknown error",i=R(n);throw new p(u.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${i}`)}}async executeToolHandler(e,t,r){let o=e.handler;if("createTask"in o){if(!r.taskStore)throw new Error("No task store provided.");let n={...r,taskStore:r.taskStore};if(e.inputSchema){let i=o;return await Promise.resolve(i.createTask(t,n))}else{let i=o;return await Promise.resolve(i.createTask(n))}}if(e.inputSchema){let n=o;return await Promise.resolve(n(t,r))}else{let n=o;return await Promise.resolve(n(r))}}async handleAutomaticTaskPolling(e,t,r){if(!r.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,t.params.arguments,t.params.name),a=e.handler,n={...r,taskStore:r.taskStore},i=o?await Promise.resolve(a.createTask(o,n)):await Promise.resolve(a.createTask(n)),c=i.task.taskId,l=i.task,m=l.pollInterval??5e3;for(;l.status!=="completed"&&l.status!=="failed"&&l.status!=="cancelled";){await new Promise(le=>setTimeout(le,m));let d=await r.taskStore.getTask(c);if(!d)throw new p(u.InternalError,`Task ${c} not found during polling`);l=d}return await r.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(h(L)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(L,async e=>{switch(e.params.ref.type){case"ref/prompt":return Z(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return D(e),this.handleResourceCompletion(e,e.params.ref);default:throw new p(u.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){let r=this._registeredPrompts[t.name];if(!r)throw new p(u.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new p(u.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return w;let a=b(r.argsSchema)?.[e.params.argument.name];if(!A(a))return w;let n=ee(a);if(!n)return w;let i=await n(e.params.argument.value,e.params.context);return re(i)}async handleResourceCompletion(e,t){let r=Object.values(this._registeredResourceTemplates).find(n=>n.resourceTemplate.uriTemplate.toString()===t.uri);if(!r){if(this._registeredResources[t.uri])return w;throw new p(u.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=r.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return w;let a=await o(e.params.argument.value,e.params.context);return re(a)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(h(_)),this.server.assertCanSetRequestHandler(h(E)),this.server.assertCanSetRequestHandler(h(k)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(_,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([a,n])=>n.enabled).map(([a,n])=>({uri:a,name:n.name,...n.metadata})),o=[];for(let a of Object.values(this._registeredResourceTemplates)){if(!a.resourceTemplate.listCallback)continue;let n=await a.resourceTemplate.listCallback(t);for(let i of n.resources)o.push({...a.metadata,...i})}return{resources:[...r,...o]}}),this.server.setRequestHandler(E,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,r])=>({name:t,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(k,async(e,t)=>{let r=new URL(e.params.uri),o=this._registeredResources[r.toString()];if(o){if(!o.enabled)throw new p(u.InvalidParams,`Resource ${r} disabled`);return o.readCallback(r,t)}for(let a of Object.values(this._registeredResourceTemplates)){let n=a.resourceTemplate.uriTemplate.match(r.toString());if(n)return a.readCallback(r,n,t)}throw new p(u.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(h(v)),this.server.assertCanSetRequestHandler(h(P)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(v,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?fe(t.argsSchema):void 0}))})),this.server.setRequestHandler(P,async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new p(u.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new p(u.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let o=g(r.argsSchema),a=await T(o,e.params.arguments??{});if(!a.success){let c="error"in a?a.error:"Unknown error",l=R(c);throw new p(u.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${l}`)}let n=a.data,i=r.callback;return await Promise.resolve(i(n,t))}else{let o=r.callback;return await Promise.resolve(o(t))}}),this._promptHandlersInitialized=!0)}resource(e,t,...r){let o;typeof r[0]=="object"&&(o=r.shift());let a=r[0];if(typeof t=="string"){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);let n=this._createRegisteredResource(e,void 0,t,o,a);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let n=this._createRegisteredResourceTemplate(e,void 0,t,o,a);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}registerResource(e,t,r,o){if(typeof t=="string"){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);let a=this._createRegisteredResource(e,r.title,t,r,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let a=this._createRegisteredResourceTemplate(e,r.title,t,r,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}_createRegisteredResource(e,t,r,o,a){let n={name:e,title:t,metadata:o,readCallback:a,enabled:!0,disable:()=>n.update({enabled:!1}),enable:()=>n.update({enabled:!0}),remove:()=>n.update({uri:null}),update:i=>{typeof i.uri<"u"&&i.uri!==r&&(delete this._registeredResources[r],i.uri&&(this._registeredResources[i.uri]=n)),typeof i.name<"u"&&(n.name=i.name),typeof i.title<"u"&&(n.title=i.title),typeof i.metadata<"u"&&(n.metadata=i.metadata),typeof i.callback<"u"&&(n.readCallback=i.callback),typeof i.enabled<"u"&&(n.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResources[r]=n,n}_createRegisteredResourceTemplate(e,t,r,o,a){let n={resourceTemplate:r,title:t,metadata:o,readCallback:a,enabled:!0,disable:()=>n.update({enabled:!1}),enable:()=>n.update({enabled:!0}),remove:()=>n.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(delete this._registeredResourceTemplates[e],l.name&&(this._registeredResourceTemplates[l.name]=n)),typeof l.title<"u"&&(n.title=l.title),typeof l.template<"u"&&(n.resourceTemplate=l.template),typeof l.metadata<"u"&&(n.metadata=l.metadata),typeof l.callback<"u"&&(n.readCallback=l.callback),typeof l.enabled<"u"&&(n.enabled=l.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=n;let i=r.uriTemplate.variableNames;return Array.isArray(i)&&i.some(l=>!!r.completeCallback(l))&&this.setCompletionRequestHandler(),n}_createRegisteredPrompt(e,t,r,o,a){let n={title:t,description:r,argsSchema:o===void 0?void 0:f(o),callback:a,enabled:!0,disable:()=>n.update({enabled:!1}),enable:()=>n.update({enabled:!0}),remove:()=>n.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredPrompts[e],i.name&&(this._registeredPrompts[i.name]=n)),typeof i.title<"u"&&(n.title=i.title),typeof i.description<"u"&&(n.description=i.description),typeof i.argsSchema<"u"&&(n.argsSchema=f(i.argsSchema)),typeof i.callback<"u"&&(n.callback=i.callback),typeof i.enabled<"u"&&(n.enabled=i.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=n,o&&Object.values(o).some(c=>{let l=c instanceof j?c._def?.innerType:c;return A(l)})&&this.setCompletionRequestHandler(),n}_createRegisteredTool(e,t,r,o,a,n,i,c,l){M(e);let m={title:t,description:r,inputSchema:te(o),outputSchema:te(a),annotations:n,execution:i,_meta:c,handler:l,enabled:!0,disable:()=>m.update({enabled:!1}),enable:()=>m.update({enabled:!0}),remove:()=>m.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(typeof d.name=="string"&&M(d.name),delete this._registeredTools[e],d.name&&(this._registeredTools[d.name]=m)),typeof d.title<"u"&&(m.title=d.title),typeof d.description<"u"&&(m.description=d.description),typeof d.paramsSchema<"u"&&(m.inputSchema=f(d.paramsSchema)),typeof d.outputSchema<"u"&&(m.outputSchema=f(d.outputSchema)),typeof d.callback<"u"&&(m.handler=d.callback),typeof d.annotations<"u"&&(m.annotations=d.annotations),typeof d._meta<"u"&&(m._meta=d._meta),typeof d.enabled<"u"&&(m.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=m,this.setToolRequestHandlers(),this.sendToolListChanged(),m}tool(e,...t){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let r,o,a,n;if(typeof t[0]=="string"&&(r=t.shift()),t.length>1){let c=t[0];if($(c))o=t.shift(),t.length>1&&typeof t[0]=="object"&&t[0]!==null&&!$(t[0])&&(n=t.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(l=>typeof l=="object"&&l!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);n=t.shift()}}let i=t[0];return this._createRegisteredTool(e,void 0,r,o,a,n,{taskSupport:"forbidden"},void 0,i)}registerTool(e,t,r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:a,inputSchema:n,outputSchema:i,annotations:c,_meta:l}=t;return this._createRegisteredTool(e,o,a,n,i,c,{taskSupport:"forbidden"},l,r)}prompt(e,...t){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let r;typeof t[0]=="string"&&(r=t.shift());let o;t.length>1&&(o=t.shift());let a=t[0],n=this._createRegisteredPrompt(e,void 0,r,o,a);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),n}registerPrompt(e,t,r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:a,argsSchema:n}=t,i=this._createRegisteredPrompt(e,o,a,n,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var he={type:"object",properties:{}};function se(s){return s!==null&&typeof s=="object"&&"parse"in s&&typeof s.parse=="function"&&"safeParse"in s&&typeof s.safeParse=="function"}function oe(s){return"_def"in s||"_zod"in s||se(s)}function $(s){return typeof s!="object"||s===null||oe(s)?!1:Object.keys(s).length===0?!0:Object.values(s).some(se)}function te(s){if(s){if($(s))return f(s);if(!oe(s))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return s}}function fe(s){let e=b(s);return e?Object.entries(e).map(([t,r])=>{let o=G(r),a=W(r);return{name:t,description:o,required:!a}}):[]}function h(s){let t=b(s)?.method;if(!t)throw new Error("Schema is missing a method literal");let r=F(t);if(typeof r=="string")return r;throw new Error("Schema method literal must be a string")}function re(s){return{completion:{values:s.slice(0,100),total:s.length,hasMore:s.length>100}}}var w={completion:{values:[],hasMore:!1}};function ne(s,e){let t=s.tool,r=new Map;s.tool=((...n)=>{let i=t.apply(s,n);return i&&(n[0]==="agent"||n[0]==="worker_spawn")&&r.set(n[0],i),i});try{e()}finally{s.tool=t}let o=r.get("worker_spawn");r.get("agent")&&o&&o.update({description:B(o.description??"")})}var ae=O("mcp-bundled"),ge=async s=>{let[{registerRemoteOpsTools:e},{registerTimeTools:t},{registerSubagentTools:r}]=await Promise.all([import("./remote-ops-O5CR4RGA.js"),import("./time-P6PE52WL.js"),import("./subagent-OZGUOV3J.js")]);return o=>{e(o,s),t(o),r(o,s)}},we=async s=>{let[{registerCostTools:e},{registerExecutionTools:t},{registerContextTools:r},{registerWaitpointTools:o}]=await Promise.all([import("./cost-OOO32GLC.js"),import("./executions-BN6OLLVM.js"),import("./context-GQKWKFRM.js"),import("./waitpoint-W5M3BE55.js")]);return a=>{e(a),t(a),r(a,s),o(a,s)}},Te=async s=>{let[{registerInteractionPlanTools:e,interactionDepsFor:t},{registerInteractionAskTools:r}]=await Promise.all([import("./interaction-plan-C446T2GZ.js"),import("./interaction-ask-EE2UPR3Q.js")]),o=t(s);return a=>{e(a,o),r(a,o)}},be=async s=>{let{registerSlackTools:e,slackDepsFor:t}=await import("./slack-2CGM4SMY.js"),r=t(s);return o=>e(o,r)},Re=async s=>{let[{registerFileTools:e},{buildFeishuClientFromEnv:t}]=await Promise.all([import("./file-H572PL2Z.js"),import("../domain/mcp/feishu/client.js")]),r=t();return o=>e(o,{client:r,fallbackChannel:s.channel,ctx:s})},ye=async s=>{let[{registerUiFileTools:e},{registerUiViewTools:t},{registerUiDecisionTools:r},{registerUiBoardTools:o}]=await Promise.all([import("./ui-file-6PLXHSTB.js"),import("./ui-view-6MDU4GXY.js"),import("./ui-decision-6HHNROIT.js"),import("./ui-board-H4INJD6C.js")]);return a=>{e(a,s),t(a,s),r(a,s),o(a,s)}},Se=async s=>{let{registerWorkerTools:e}=await import("./workers-GTFP75MS.js");return t=>e(t,s)},_e=async s=>{let{registerWorkerReportTools:e}=await import("./workers-GTFP75MS.js");return t=>e(t,s)},Ee={"cortex-core":ge,"cortex-ext":we,"cortex-interaction-bridge":Te,"cortex-slack":be,"cortex-feishu":Re,"cortex-web":ye,"cortex-workers":Se,"cortex-worker-report":_e};function ke(s,e){let t=e instanceof Error?e.message:String(e);ae.error(`Skipping MCP bundle ${s}: ${t}`)}async function ve(s,e,t=(o,a)=>Ee[o](a),r=ke){return(await Promise.all(s.map(async a=>{try{let n=await t(a,e);return i=>{try{n(i)}catch(c){r(a,c)}}}catch(n){return r(a,n),null}}))).filter(a=>a!==null)}async function ie(s,e){let t=await ve(s,e),r=new S({name:z,version:N});return V(r,o=>ne(o,()=>t.forEach(a=>a(o))),e.toolAllowlist),r}async function Pe(){let s=process.env[U]??process.argv[2],e=X(s);if(e.includes("cortex-ext")){let{executionRepo:r}=await import("./execution-repo-XXL4FXC6.js");r.follow()}await(await ie(e,H())).connect(new Y)}q(new URL("dist/domain/mcp/bundled-server.js",__cortexPackageRoot).href)&&Pe().catch(s=>{ae.error(s),process.exit(1)});async function et(s,e){return ie(s,H(e))}export{ve as a,ie as b,Pe as c,et as d};
4
+ import{b as H}from"./chunk-ZNAMETPQ.js";import{p as B}from"./chunk-4KQHDDC5.js";import{a as J,b as Y}from"./chunk-WZYS2HAK.js";import{C as v,E as P,H as C,K as x,U as L,V as Z,W as D,Z as p,_ as I,a as f,c as T,d as b,e as g,f as R,g as G,h as W,i as F,n as u,v as _,x as E,z as k}from"./chunk-TMV2ZDOI.js";import{a as U,b as z,d as X}from"./chunk-5T7IX5KN.js";import{i as V}from"./chunk-52VCLZS5.js";import{a as N}from"./chunk-R2CCD4OF.js";import{D as j}from"./chunk-W34AK4SK.js";import{e as O}from"./chunk-7W7VYUTK.js";import{b as q}from"./chunk-JGUEIW2W.js";var Q=Symbol.for("mcp.completable");function A(s){return!!s&&typeof s=="object"&&Q in s}function ee(s){return s[Q]?.complete}var K;(function(s){s.Completable="McpCompletable"})(K||(K={}));var ce=/^[A-Za-z0-9._-]{1,128}$/;function de(s){let e=[];if(s.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(s.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${s.length})`]};if(s.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),s.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(s.startsWith("-")||s.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(s.startsWith(".")||s.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!ce.test(s)){let t=s.split("").filter(r=>!/[A-Za-z0-9._-]/.test(r)).filter((r,n,a)=>a.indexOf(r)===n);return e.push(`Tool name contains invalid characters: ${t.map(r=>`"${r}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function ue(s,e){if(e.length>0){console.warn(`Tool name validation warning for "${s}":`);for(let t of e)console.warn(` - ${t}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function M(s){let e=de(s);return ue(s,e.warnings),e.isValid}var y=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,r){let n={taskSupport:"required",...t.execution};if(n.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,n,t._meta,r)}};function pe(s,e){let t=0,r=[s];for(;r.length>0;){let n=r.pop();if(!(n===null||typeof n!="object"))if(Array.isArray(n))for(let a of n){if(++t>e)return t;a!==null&&typeof a=="object"&&r.push(a)}else for(let a in n){if(!Object.prototype.hasOwnProperty.call(n,a))continue;if(++t>e)return t;let o=n[a];o!==null&&typeof o=="object"&&r.push(o)}}return t}function me(s){if(!(s===void 0||s===1/0)){if(typeof s!="number"||Number.isNaN(s)||s<1)throw new RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(s)}`);return s}}var S=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new J(e,t),this._maxToolInputElements=me(t?.maxToolInputElements),t?.capabilities?.tools&&this.setToolRequestHandlers(),t?.capabilities?.resources&&this.setResourceRequestHandlers(),t?.capabilities?.prompts&&this.setPromptRequestHandlers()}get experimental(){return this._experimental||(this._experimental={tasks:new y(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(h(C)),this.server.assertCanSetRequestHandler(h(x)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(C,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let r={name:e,title:t.title,description:t.description,inputSchema:(()=>{let n=g(t.inputSchema);return n?I(n,{strictUnions:!0,pipeStrategy:"input"}):he})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let n=g(t.outputSchema);n&&(r.outputSchema=I(n,{strictUnions:!0,pipeStrategy:"output"}))}return r})})),this.server.setRequestHandler(x,async(e,t)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new p(u.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new p(u.InvalidParams,`Tool ${e.params.name} disabled`);let n=!!e.params.task,a=r.execution?.taskSupport,o="createTask"in r.handler;if((a==="required"||a==="optional")&&!o)throw new p(u.InternalError,`Tool ${e.params.name} has taskSupport '${a}' but was not registered with registerToolTask`);if(a==="required"&&!n)throw new p(u.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(a==="optional"&&!n&&o)return await this.handleAutomaticTaskPolling(r,e,t);let i=await this.validateToolInput(r,e.params.arguments,e.params.name),c=await this.executeToolHandler(r,i,t);return n||await this.validateToolOutput(r,c,e.params.name),c}catch(r){if(r instanceof p&&r.code===u.UrlElicitationRequired)throw r;return this.createToolError(r instanceof Error?r.message:String(r))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,t,r){if(this._maxToolInputElements!==void 0&&pe(t,this._maxToolInputElements)>this._maxToolInputElements)throw new p(u.InvalidParams,`Invalid arguments for tool ${r}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!e.inputSchema)return;let a=g(e.inputSchema)??e.inputSchema,o=await T(a,t??{});if(!o.success){let i="error"in o?o.error:"Unknown error",c=R(i);throw new p(u.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${c}`)}return o.data}async validateToolOutput(e,t,r){if(!e.outputSchema||!("content"in t)||t.isError)return;if(!t.structuredContent)throw new p(u.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let n=g(e.outputSchema),a=await T(n,t.structuredContent);if(!a.success){let o="error"in a?a.error:"Unknown error",i=R(o);throw new p(u.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${i}`)}}async executeToolHandler(e,t,r){let n=e.handler;if("createTask"in n){if(!r.taskStore)throw new Error("No task store provided.");let o={...r,taskStore:r.taskStore};if(e.inputSchema){let i=n;return await Promise.resolve(i.createTask(t,o))}else{let i=n;return await Promise.resolve(i.createTask(o))}}if(e.inputSchema){let o=n;return await Promise.resolve(o(t,r))}else{let o=n;return await Promise.resolve(o(r))}}async handleAutomaticTaskPolling(e,t,r){if(!r.taskStore)throw new Error("No task store provided for task-capable tool.");let n=await this.validateToolInput(e,t.params.arguments,t.params.name),a=e.handler,o={...r,taskStore:r.taskStore},i=n?await Promise.resolve(a.createTask(n,o)):await Promise.resolve(a.createTask(o)),c=i.task.taskId,l=i.task,m=l.pollInterval??5e3;for(;l.status!=="completed"&&l.status!=="failed"&&l.status!=="cancelled";){await new Promise(le=>setTimeout(le,m));let d=await r.taskStore.getTask(c);if(!d)throw new p(u.InternalError,`Task ${c} not found during polling`);l=d}return await r.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(h(L)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(L,async e=>{switch(e.params.ref.type){case"ref/prompt":return Z(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return D(e),this.handleResourceCompletion(e,e.params.ref);default:throw new p(u.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,t){let r=this._registeredPrompts[t.name];if(!r)throw new p(u.InvalidParams,`Prompt ${t.name} not found`);if(!r.enabled)throw new p(u.InvalidParams,`Prompt ${t.name} disabled`);if(!r.argsSchema)return w;let a=b(r.argsSchema)?.[e.params.argument.name];if(!A(a))return w;let o=ee(a);if(!o)return w;let i=await o(e.params.argument.value,e.params.context);return re(i)}async handleResourceCompletion(e,t){let r=Object.values(this._registeredResourceTemplates).find(o=>o.resourceTemplate.uriTemplate.toString()===t.uri);if(!r){if(this._registeredResources[t.uri])return w;throw new p(u.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let n=r.resourceTemplate.completeCallback(e.params.argument.name);if(!n)return w;let a=await n(e.params.argument.value,e.params.context);return re(a)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(h(_)),this.server.assertCanSetRequestHandler(h(E)),this.server.assertCanSetRequestHandler(h(k)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(_,async(e,t)=>{let r=Object.entries(this._registeredResources).filter(([a,o])=>o.enabled).map(([a,o])=>({uri:a,name:o.name,...o.metadata})),n=[];for(let a of Object.values(this._registeredResourceTemplates)){if(!a.resourceTemplate.listCallback)continue;let o=await a.resourceTemplate.listCallback(t);for(let i of o.resources)n.push({...a.metadata,...i})}return{resources:[...r,...n]}}),this.server.setRequestHandler(E,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([t,r])=>({name:t,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(k,async(e,t)=>{let r=new URL(e.params.uri),n=this._registeredResources[r.toString()];if(n){if(!n.enabled)throw new p(u.InvalidParams,`Resource ${r} disabled`);return n.readCallback(r,t)}for(let a of Object.values(this._registeredResourceTemplates)){let o=a.resourceTemplate.uriTemplate.match(r.toString());if(o)return a.readCallback(r,o,t)}throw new p(u.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(h(v)),this.server.assertCanSetRequestHandler(h(P)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(v,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?fe(t.argsSchema):void 0}))})),this.server.setRequestHandler(P,async(e,t)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new p(u.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new p(u.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let n=g(r.argsSchema),a=await T(n,e.params.arguments??{});if(!a.success){let c="error"in a?a.error:"Unknown error",l=R(c);throw new p(u.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${l}`)}let o=a.data,i=r.callback;return await Promise.resolve(i(o,t))}else{let n=r.callback;return await Promise.resolve(n(t))}}),this._promptHandlersInitialized=!0)}resource(e,t,...r){let n;typeof r[0]=="object"&&(n=r.shift());let a=r[0];if(typeof t=="string"){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);let o=this._createRegisteredResource(e,void 0,t,n,a);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,void 0,t,n,a);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}registerResource(e,t,r,n){if(typeof t=="string"){if(this._registeredResources[t])throw new Error(`Resource ${t} is already registered`);let a=this._createRegisteredResource(e,r.title,t,r,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let a=this._createRegisteredResourceTemplate(e,r.title,t,r,n);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}_createRegisteredResource(e,t,r,n,a){let o={name:e,title:t,metadata:n,readCallback:a,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({uri:null}),update:i=>{typeof i.uri<"u"&&i.uri!==r&&(delete this._registeredResources[r],i.uri&&(this._registeredResources[i.uri]=o)),typeof i.name<"u"&&(o.name=i.name),typeof i.title<"u"&&(o.title=i.title),typeof i.metadata<"u"&&(o.metadata=i.metadata),typeof i.callback<"u"&&(o.readCallback=i.callback),typeof i.enabled<"u"&&(o.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResources[r]=o,o}_createRegisteredResourceTemplate(e,t,r,n,a){let o={resourceTemplate:r,title:t,metadata:n,readCallback:a,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(delete this._registeredResourceTemplates[e],l.name&&(this._registeredResourceTemplates[l.name]=o)),typeof l.title<"u"&&(o.title=l.title),typeof l.template<"u"&&(o.resourceTemplate=l.template),typeof l.metadata<"u"&&(o.metadata=l.metadata),typeof l.callback<"u"&&(o.readCallback=l.callback),typeof l.enabled<"u"&&(o.enabled=l.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=o;let i=r.uriTemplate.variableNames;return Array.isArray(i)&&i.some(l=>!!r.completeCallback(l))&&this.setCompletionRequestHandler(),o}_createRegisteredPrompt(e,t,r,n,a){let o={title:t,description:r,argsSchema:n===void 0?void 0:f(n),callback:a,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredPrompts[e],i.name&&(this._registeredPrompts[i.name]=o)),typeof i.title<"u"&&(o.title=i.title),typeof i.description<"u"&&(o.description=i.description),typeof i.argsSchema<"u"&&(o.argsSchema=f(i.argsSchema)),typeof i.callback<"u"&&(o.callback=i.callback),typeof i.enabled<"u"&&(o.enabled=i.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=o,n&&Object.values(n).some(c=>{let l=c instanceof j?c._def?.innerType:c;return A(l)})&&this.setCompletionRequestHandler(),o}_createRegisteredTool(e,t,r,n,a,o,i,c,l){M(e);let m={title:t,description:r,inputSchema:te(n),outputSchema:te(a),annotations:o,execution:i,_meta:c,handler:l,enabled:!0,disable:()=>m.update({enabled:!1}),enable:()=>m.update({enabled:!0}),remove:()=>m.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(typeof d.name=="string"&&M(d.name),delete this._registeredTools[e],d.name&&(this._registeredTools[d.name]=m)),typeof d.title<"u"&&(m.title=d.title),typeof d.description<"u"&&(m.description=d.description),typeof d.paramsSchema<"u"&&(m.inputSchema=f(d.paramsSchema)),typeof d.outputSchema<"u"&&(m.outputSchema=f(d.outputSchema)),typeof d.callback<"u"&&(m.handler=d.callback),typeof d.annotations<"u"&&(m.annotations=d.annotations),typeof d._meta<"u"&&(m._meta=d._meta),typeof d.enabled<"u"&&(m.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=m,this.setToolRequestHandlers(),this.sendToolListChanged(),m}tool(e,...t){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let r,n,a,o;if(typeof t[0]=="string"&&(r=t.shift()),t.length>1){let c=t[0];if($(c))n=t.shift(),t.length>1&&typeof t[0]=="object"&&t[0]!==null&&!$(t[0])&&(o=t.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(l=>typeof l=="object"&&l!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);o=t.shift()}}let i=t[0];return this._createRegisteredTool(e,void 0,r,n,a,o,{taskSupport:"forbidden"},void 0,i)}registerTool(e,t,r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:n,description:a,inputSchema:o,outputSchema:i,annotations:c,_meta:l}=t;return this._createRegisteredTool(e,n,a,o,i,c,{taskSupport:"forbidden"},l,r)}prompt(e,...t){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let r;typeof t[0]=="string"&&(r=t.shift());let n;t.length>1&&(n=t.shift());let a=t[0],o=this._createRegisteredPrompt(e,void 0,r,n,a);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}registerPrompt(e,t,r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:n,description:a,argsSchema:o}=t,i=this._createRegisteredPrompt(e,n,a,o,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var he={type:"object",properties:{}};function se(s){return s!==null&&typeof s=="object"&&"parse"in s&&typeof s.parse=="function"&&"safeParse"in s&&typeof s.safeParse=="function"}function oe(s){return"_def"in s||"_zod"in s||se(s)}function $(s){return typeof s!="object"||s===null||oe(s)?!1:Object.keys(s).length===0?!0:Object.values(s).some(se)}function te(s){if(s){if($(s))return f(s);if(!oe(s))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return s}}function fe(s){let e=b(s);return e?Object.entries(e).map(([t,r])=>{let n=G(r),a=W(r);return{name:t,description:n,required:!a}}):[]}function h(s){let t=b(s)?.method;if(!t)throw new Error("Schema is missing a method literal");let r=F(t);if(typeof r=="string")return r;throw new Error("Schema method literal must be a string")}function re(s){return{completion:{values:s.slice(0,100),total:s.length,hasMore:s.length>100}}}var w={completion:{values:[],hasMore:!1}};function ne(s,e){let t=s.tool,r=new Map;s.tool=((...o)=>{let i=t.apply(s,o);return i&&(o[0]==="agent"||o[0]==="worker_spawn")&&r.set(o[0],i),i});try{e()}finally{s.tool=t}let n=r.get("worker_spawn");r.get("agent")&&n&&n.update({description:B(n.description??"")})}var ae=O("mcp-bundled"),ge=async s=>{let[{registerRemoteOpsTools:e},{registerTimeTools:t},{registerSubagentTools:r}]=await Promise.all([import("./remote-ops-2WBEFQ3E.js"),import("./time-P6PE52WL.js"),import("./subagent-Z5IQ4L54.js")]);return n=>{e(n,s),t(n),r(n,s)}},we=async s=>{let[{registerCostTools:e},{registerExecutionTools:t},{registerContextTools:r},{registerWaitpointTools:n},{registerMonitorTools:a}]=await Promise.all([import("./cost-CZRRSIUF.js"),import("./executions-I3UUIGSL.js"),import("./context-CI2FKEQE.js"),import("./waitpoint-M6JZBSLT.js"),import("./monitor-Z2HKNY5E.js")]);return o=>{e(o),t(o),r(o,s),n(o,s),a(o,s)}},Te=async s=>{let[{registerInteractionPlanTools:e,interactionDepsFor:t},{registerInteractionAskTools:r}]=await Promise.all([import("./interaction-plan-JTVDN3BC.js"),import("./interaction-ask-O5HGF6CH.js")]),n=t(s);return a=>{e(a,n),r(a,n)}},be=async s=>{let{registerSlackTools:e,slackDepsFor:t}=await import("./slack-R7SEJYMY.js"),r=t(s);return n=>e(n,r)},Re=async s=>{let[{registerFileTools:e},{buildFeishuClientFromEnv:t}]=await Promise.all([import("./file-Y5G56IUT.js"),import("../domain/mcp/feishu/client.js")]),r=t();return n=>e(n,{client:r,fallbackChannel:s.channel,ctx:s})},ye=async s=>{let[{registerUiFileTools:e},{registerUiViewTools:t},{registerUiDecisionTools:r},{registerUiBoardTools:n}]=await Promise.all([import("./ui-file-SRD4ILBS.js"),import("./ui-view-Z25MTZT7.js"),import("./ui-decision-YBZDS4YW.js"),import("./ui-board-HQIE4RZG.js")]);return a=>{e(a,s),t(a,s),r(a,s),n(a,s)}},Se=async s=>{let{registerWorkerTools:e}=await import("./workers-SQ2R32TK.js");return t=>e(t,s)},_e=async s=>{let{registerWorkerReportTools:e}=await import("./workers-SQ2R32TK.js");return t=>e(t,s)},Ee={"cortex-core":ge,"cortex-ext":we,"cortex-interaction-bridge":Te,"cortex-slack":be,"cortex-feishu":Re,"cortex-web":ye,"cortex-workers":Se,"cortex-worker-report":_e};function ke(s,e){let t=e instanceof Error?e.message:String(e);ae.error(`Skipping MCP bundle ${s}: ${t}`)}async function ve(s,e,t=(n,a)=>Ee[n](a),r=ke){return(await Promise.all(s.map(async a=>{try{let o=await t(a,e);return i=>{try{o(i)}catch(c){r(a,c)}}}catch(o){return r(a,o),null}}))).filter(a=>a!==null)}async function ie(s,e){let t=await ve(s,e),r=new S({name:z,version:N});return V(r,n=>ne(n,()=>t.forEach(a=>a(n))),e.toolAllowlist),r}async function Pe(){let s=process.env[U]??process.argv[2],e=X(s);if(e.includes("cortex-ext")){let{executionRepo:r}=await import("./execution-repo-5TLV2NM4.js");r.follow()}await(await ie(e,H())).connect(new Y)}q(new URL("dist/domain/mcp/bundled-server.js",__cortexPackageRoot).href)&&Pe().catch(s=>{ae.error(s),process.exit(1)});async function et(s,e){return ie(s,H(e))}export{ve as a,ie as b,Pe as c,et as d};
@@ -0,0 +1,4 @@
1
+ import { createRequire as __cortexCreateRequire } from 'node:module';
2
+ const require = __cortexCreateRequire(import.meta.url);
3
+ const __cortexPackageRoot = new URL("../../", import.meta.url);
4
+ function L(t,e){if(e+8>t.length)return 1;let r=(t[e]<<8|t[e+1])===18761,n=i=>r?t[i]|t[i+1]<<8:t[i]<<8|t[i+1],o=(i=>r?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)(e+4),c=e+o;if(c+2>t.length)return 1;let f=n(c);for(let i=0;i<f;i++){let l=c+2+i*12;if(l+12>t.length)return 1;if(n(l)===274){let d=n(l+8);return d>=1&&d<=8?d:1}}return 1}function v(t){let e=2;for(;e<t.length-1;){if(t[e]!==255)return-1;let u=t[e+1];if(u===255){e++;continue}if(u===225){if(e+4>=t.length)return-1;let n=e+4;if(n+6>t.length)return-1;if(I(t,n))return n+6}if(e+4>t.length)return-1;let r=t[e+2]<<8|t[e+3];e+=2+r}return-1}function A(t){let e=12;for(;e+8<=t.length;){let u=String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3]),r=t[e+4]|t[e+5]<<8|t[e+6]<<16|t[e+7]<<24,n=e+8;if(u==="EXIF")return n+r>t.length?-1:r>=6&&I(t,n)?n+6:n;e=n+r+r%2}return-1}function I(t,e){return t[e]===69&&t[e+1]===120&&t[e+2]===105&&t[e+3]===102&&t[e+4]===0&&t[e+5]===0}function N(t){let e=-1;return t.length>=2&&t[0]===255&&t[1]===216?e=v(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&&(e=A(t)),e===-1?1:L(t,e)}function F(t,e,u){let r=e.get_width(),n=e.get_height(),a=e.get_raw_pixels(),o=new Uint8Array(a.length);for(let c=0;c<n;c++)for(let f=0;f<r;f++){let i=(c*r+f)*4,l=u(f,c,r,n)*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,n,r)}function M(t,e,u){let r=N(u);if(r===1)return e;switch(r){case 2:return t.fliph(e),e;case 3:return t.fliph(e),t.flipv(e),e;case 4:return t.flipv(e),e;case 5:{let n=F(t,e,(a,o,c,f)=>a*f+(f-1-o));return t.fliph(n),n}case 6:return F(t,e,(n,a,o,c)=>n*c+(c-1-a));case 7:{let n=F(t,e,(a,o,c,f)=>(c-1-a)*f+o);return t.fliph(n),n}case 8:return F(t,e,(n,a,o,c)=>(o-1-n)*c+a);default:return e}}import{createRequire as U}from"module";import*as w from"path";import{fileURLToPath as B}from"url";var q=U(new URL("vendor/pi/dist/utils/photon.js",__cortexPackageRoot).href),m=q("fs"),W="photon_rs_bg.wasm",p=null,R=null;function C(t){return typeof t=="string"?t:t instanceof URL?B(t):null}function D(){let t=w.dirname(process.execPath);return[w.join(t,W),w.join(t,"photon",W),w.join(process.cwd(),W)]}function Q(){let t=m.readFileSync.bind(m),e=D(),u=m,r=((...n)=>{let[a,o]=n;if(C(a)?.endsWith(W))try{return t(...n)}catch(f){let i=f;if(i?.code&&i.code!=="ENOENT")throw f;for(let l of e)if(m.existsSync(l))return o===void 0?t(l):t(l,o);throw f}return t(...n)});try{u.readFileSync=r}catch{Object.defineProperty(m,"readFileSync",{value:r,writable:!0,configurable:!0})}return()=>{try{u.readFileSync=t}catch{Object.defineProperty(m,"readFileSync",{value:t,writable:!0,configurable:!0})}}}async function T(){return p||R||(R=(async()=>{let t=Q();try{return p=await import("@silvia-odwyer/photon-node"),p}catch{return p=null,p}finally{t()}})(),R)}var y="pi:image-resize-response",J=4.5*1024*1024,X={maxWidth:2e3,maxHeight:2e3,maxBytes:J,jpegQuality:80};function j(t,e){let u=Buffer.from(t).toString("base64");return{data:u,encodedSize:Buffer.byteLength(u,"utf-8"),mimeType:e}}async function b(t,e,u){let r={...X,...u},n=Math.ceil(t.byteLength/3)*4,a=await T();if(!a)return null;let o;try{let H=function(S,x,z){let _=a.resize(o,S,x,a.SamplingFilter.Lanczos3);try{let P=[j(_.get_bytes(),"image/png")];for(let E of z)P.push(j(_.get_bytes_jpeg(E),"image/jpeg"));return P}finally{_.free()}},c=a.PhotonImage.new_from_byteslice(t);o=M(a,c,t),o!==c&&c.free();let f=o.get_width(),i=o.get_height(),l=e.split("/")[1]??"png";if(f<=r.maxWidth&&i<=r.maxHeight&&n<r.maxBytes)return{data:Buffer.from(t).toString("base64"),mimeType:e||`image/${l}`,originalWidth:f,originalHeight:i,width:f,height:i,wasResized:!1};let d=f,g=i;d>r.maxWidth&&(g=Math.round(g*r.maxWidth/d),d=r.maxWidth),g>r.maxHeight&&(d=Math.round(d*r.maxHeight/g),g=r.maxHeight);let k=Array.from(new Set([r.jpegQuality,85,70,55,40])),h=d,s=g;for(;;){let[S,x,...z]=H(h,s,k),_=x&&x.encodedSize<S.encodedSize?[x,S]:[S,x];for(let O of[..._,...z])if(O&&O.encodedSize<r.maxBytes)return{data:O.data,mimeType:O.mimeType,originalWidth:f,originalHeight:i,width:h,height:s,wasResized:!0};if(h===1&&s===1)break;let P=h===1?1:Math.max(1,Math.floor(h*.75)),E=s===1?1:Math.max(1,Math.floor(s*.75));if(P===h&&E===s)break;h=P,s=E}return null}catch{return null}finally{o&&o.free()}}export{M as a,T as b,y as c,b as d};
@@ -0,0 +1,6 @@
1
+ import { createRequire as __cortexCreateRequire } from 'node:module';
2
+ const require = __cortexCreateRequire(import.meta.url);
3
+ const __cortexPackageRoot = new URL("../../", import.meta.url);
4
+ import{a as X}from"./chunk-D6VMBA4C.js";import{c as Z,g as ee}from"./chunk-3XLHL5YT.js";import{a as V,b as B,d as Q}from"./chunk-X2TKJ7KR.js";import{a as T}from"./chunk-NW4GW47L.js";import{d as Me}from"./chunk-WHC7AYZD.js";function ve(n,e){let r=n!==void 0&&n.length>0,t=e!==void 0&&e.length>0;if(!(!r&&!t))return{role:"system",content:n??"",...t?{toolsAdded:e}:{},timestamp:0}}function j(n){let e=ve(n.systemPrompt,n.tools);return{messages:e?[e,...n.messages]:n.messages}}function C(n){return n.role==="system"}function te(n){let e=n[0];return e&&C(e)?e:void 0}function Fe(n){return te(n)?n.slice(1):n}function D(n){let e=new Map;for(let r of n)if(C(r)){for(let t of r.toolsRemoved??[])e.delete(t.name);for(let t of r.toolsAdded??[])e.set(t.name,t)}return[...e.values()]}function re(n){let e=[],r=new Map,t;for(let i of n){if(!C(i))continue;t??=i.timestamp;let o=V(i.content);o.length>0&&e.push(o);for(let[c,d]of Object.entries(i.sections??{}))d===null?r.delete(c):r.set(c,d)}let s=D(n);if(!(t===void 0&&s.length===0))return{role:"system",content:e.join(`
5
+
6
+ `),...r.size>0?{sections:Object.fromEntries(r)}:{},...s.length>0?{toolsAdded:s}:{},timestamp:t??0}}function Je(n){let e=re(n);return e?B(e):""}function xe(n){let e=re(n.messages),r=n.messages.filter(t=>t.role!=="system");return{messages:e?[e,...r]:r}}function Xe(n,e){return e?n:xe(n)}function N(n){return{name:n.name,description:n.description,parameters:JSON.parse(JSON.stringify(n.parameters)),...n.constrainedSampling===void 0?{}:{constrainedSampling:n.constrainedSampling}}}function L(n,e){return JSON.stringify(N(n))===JSON.stringify(N(e))}function Ve(n,e){let r=new Map(n.map(s=>[s.name,s])),t=new Map(e.map(s=>[s.name,s]));return{toolsAdded:e.filter(s=>{let i=r.get(s.name);return i===void 0||!L(i,s)}).map(N),toolsRemoved:n.filter(s=>{let i=t.get(s.name);return i===void 0||!L(s,i)}).map(s=>({name:s.name}))}}function Be(n){let e=new Map;for(let r of n)if(C(r))for(let t of r.toolsAdded??[])e.set(t.name,t);return[...e.values()]}function Qe(n){let e=new Map;for(let r of n)if(C(r))for(let t of r.toolsAdded??[]){let s=e.get(t.name);if(s!==void 0&&!L(s,t))return!0;e.set(t.name,t)}return!1}function Ze(n){return ne(n.filter(C))>=0}function ne(n){let e=new Set,r=-1;for(let t=0;t<n.length;t++){let s=n[t];(s.toolsRemoved?.length??0)>0&&(r=t);for(let i of s.toolsAdded??[])e.has(i.name)&&(r=t),e.add(i.name)}return r}function et(n,e){let r=n.filter(C);if(e==="none")return{requestTools:D(r),foldedSystemMessages:r.length};if(e==="changes")return{requestTools:[],foldedSystemMessages:0};let t=Math.max(te(n)?1:0,ne(r)+1);return{requestTools:D(r.slice(0,t)),foldedSystemMessages:t}}var Ye={};Me(Ye,{AI_TELEMETRY_SCHEMA:()=>q,ModelsError:()=>f,calculateCost:()=>We,clampThinkingLevel:()=>ze,createModels:()=>je,createProvider:()=>Ke,getModelType:()=>S,getSupportedThinkingLevels:()=>we,hasApi:()=>Ue,isModelType:()=>A,modelsAreEqual:()=>He});var Ae=function(n,e){return typeof n=="string"&&/^\.\.?\//.test(n)?n.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(r,t,s,i,o){return t?e?".jsx":".js":s&&(!i||!o)?r:s+i+"."+o.toLowerCase()+"js"}):n},se=n=>import(Ae(n));function Se(){return globalThis.process?.env}function ie(){return{async env(n){let e=Se()?.[n];return typeof e=="string"&&e.trim().length>0?e:void 0},async fileExists(n){try{let e=await se("node:fs/promises"),r=n;return r.startsWith("~")&&(r=(await se("node:os")).homedir()+r.slice(1)),await e.access(r),!0}catch{return!1}}}}function oe(n){if(n.reason!==void 0)return n.reason;let e=new Error("The operation was aborted");return e.name="AbortError",e}function v(n){return n??new AbortController().signal}function x(n,e){return e.aborted?(n.catch(()=>{}),Promise.reject(oe(e))):new Promise((r,t)=>{let s=!1,i=()=>e.removeEventListener("abort",o),o=()=>{s||(s=!0,i(),t(oe(e)))};e.addEventListener("abort",o,{once:!0}),n.then(c=>{s||(s=!0,i(),r(c))},c=>{s||(s=!0,i(),t(c))}),e.aborted&&o()})}var _=class{credentials=new Map;chains=new Map;enqueue(e,r,t){let s=v(t?.signal),i=this.chains.get(e)??Promise.resolve(),o=(async()=>(await i.catch(()=>{}),s.throwIfAborted(),r()))(),c=o.catch(()=>{});return this.chains.set(e,c),c.then(()=>{this.chains.get(e)===c&&this.chains.delete(e)}),x(o,s)}async read(e,r){return r?.signal?.throwIfAborted(),this.credentials.get(e)}async list(e){return e?.signal?.throwIfAborted(),[...this.credentials].map(([r,t])=>({providerId:r,type:t.type}))}modify(e,r,t){return this.enqueue(e,async()=>{let s=this.credentials.get(e),i=await r(s);return t?.signal?.throwIfAborted(),i!==void 0&&this.credentials.set(e,i),i??s},t)}delete(e,r){return this.enqueue(e,async()=>{this.credentials.delete(e)},r)}};var f=class extends Error{code;constructor(e,r,t){super(Ce(r,t?.cause),t),this.name="ModelsError",this.code=e}};function Ce(n,e){if(e==null)return n;let r=X(e).trim();return!r||n.includes(r)?n:`${n}: ${r}`}function U(n,e,r,t){let s=v(t?.signal);return x(Te(n,e,r,t,s),s)}async function Te(n,e,r,t,s){s.throwIfAborted();let i=t?.env?Ee(r,t.env):r;if(t?.apiKey!==void 0&&n.auth.apiKey)return K(i,n.auth.apiKey,n.id,{type:"api_key",key:t.apiKey,env:t.env},s);let o=await _e(e,n.id,s);if(o){if(o.type==="oauth"&&n.auth.oauth)return Oe(e,n.id,n.auth.oauth,o,s,t?.minOAuthValidityMs);if(o.type==="api_key"&&n.auth.apiKey){let c=t?.env?{...o,env:{...o.env,...t.env}}:o;return K(i,n.auth.apiKey,n.id,c,s)}return}return n.auth.apiKey?K(i,n.auth.apiKey,n.id,void 0,s):void 0}function Ee(n,e){return{env:async r=>e[r]||await n.env(r),fileExists:r=>n.fileExists(r)}}var ke=300*1e3,Pe=15e3;async function W(n,e,r,t,s){let i,o=new AbortController,c=()=>o.abort(s.reason);s.addEventListener("abort",c,{once:!0}),s.aborted&&c();try{i=await n.modify(e,async d=>{if(s.removeEventListener("abort",c),s.throwIfAborted(),d?.type==="oauth"&&t(d))try{return await r.refresh(d,AbortSignal.timeout(Pe))}catch(h){throw new f("oauth",`OAuth refresh failed for ${e}`,{cause:h})}},{signal:o.signal})}catch(d){throw d instanceof f?d:(s.throwIfAborted(),new f("auth",`Credential store modify failed for ${e}`,{cause:d}))}finally{s.removeEventListener("abort",c)}return i?.type==="oauth"?i:void 0}async function Oe(n,e,r,t,s,i){let o=Math.max(ke,i??0),c=h=>Date.now()+o>=h.expires,d=t;if(c(d)){let h=await W(n,e,r,c,s);if(!h)return;if(d=h,i!==void 0&&c(d))throw new f("oauth",`OAuth refresh returned a token that expires too soon for ${e}`)}try{return{auth:await r.toAuth(d),source:"OAuth"}}catch(h){throw new f("oauth",`OAuth auth derivation failed for ${e}`,{cause:h})}}async function K(n,e,r,t,s){try{return await e.resolve({ctx:n,credential:t,signal:s})}catch(i){throw new f("auth",`API key auth failed for provider ${r}`,{cause:i})}}async function _e(n,e,r){try{return await n.read(e,{signal:r})}catch(t){throw new f("auth",`Credential store read failed for ${e}`,{cause:t})}}var R=class{entries=new Map;async read(e,r){r?.signal?.throwIfAborted();let t=this.entries.get(e);return t?structuredClone(t):void 0}async write(e,r,t){t?.signal?.throwIfAborted(),this.entries.set(e,structuredClone(r))}async delete(e,r){r?.signal?.throwIfAborted(),this.entries.delete(e)}};function z(n,e){let r=new Map;for(let t of e)for(let[s,i]of Object.entries(t.metrics??{}))r.set(s,i);return{counter:t=>n.counter(t,r.get(t)),upDownCounter:t=>n.upDownCounter(t,r.get(t)),histogram:t=>n.histogram(t,r.get(t))}}async function Re(n,e){return e(H)}var Ie=Object.freeze({add:()=>{}}),qe=Object.freeze({add:()=>{}}),$e=Object.freeze({record:()=>{}}),I=Object.freeze({counter:()=>Ie,upDownCounter:()=>qe,histogram:()=>$e}),ae=Object.freeze({inject:()=>{},extract:()=>E}),H={metrics:I,propagation:ae,startSpan:Re,addLink:()=>{},addEvent:()=>{},setAttributes:()=>{},setStatus:()=>{}};Object.freeze(H);var E=H;var gt=performance.timeOrigin;function ce(n){return(r,t,s)=>n.startSpan({name:r,attributes:t},i=>s(i,ce(i)))}function de(n,e){return ce(n)}var k={type:"string",description:"Provider identifier.",required:!0},P={type:"string",description:"Requested model identifier.",required:!0},le={type:"string",description:"Normalized stop reason.",values:["pending","stop","length","toolUse","error","aborted","deferred"]},ue={description:"One logical model request, including authentication and provider setup.",parents:{kind:"any"},startAttributes:{provider:k,api:{type:"string",description:"API identifier.",required:!0},model:P,reasoning:{type:"string",description:"Scalar requested reasoning level.",required:!1}},endAttributes:{stop:le,"usage.input":{type:"number",description:"Uncached input tokens."},"usage.output":{type:"number",description:"Output tokens."},"usage.cache_read":{type:"number",description:"Cache-read tokens."},"usage.cache_write":{type:"number",description:"Cache-write tokens."},"cost.total":{type:"number",description:"Total request cost in USD."},"response.id":{type:"string",description:"Provider response identifier.",cardinality:"high"}},events:{"pi.ai.first_chunk":{description:"First normalized stream event delivered.",attributes:{}},"pi.ai.block":{description:"A completed content block; content is never recorded.",attributes:{type:{type:"string",description:"Block kind.",values:["text","thinking","tool_call"],required:!0},index:{type:"number",description:"Content block index.",required:!0},chars:{type:"number",description:"UTF-16 character count.",required:!0},tool:{type:"string",description:"Tool name, for tool-call blocks only.",required:!1}}}},status:{default:"ok",errorWhen:"Stop reason is error: provider_error with at most 500 error-message characters. Aborted stays ok."}},q={version:1,spans:{"pi.ai.request":ue,"pi.ai.poll":{...ue,description:"One deferred-response poll, not the deferred request's lifetime."}},metrics:{"pi.ai.request.duration":{kind:"histogram",description:"Logical request or poll duration.",unit:"ms",attributes:{provider:k,model:P,stop:{...le,required:!0}}},"pi.ai.first_chunk.duration":{kind:"histogram",description:"Time to the first normalized stream event.",unit:"ms",attributes:{provider:k,model:P}},"pi.ai.tokens":{kind:"counter",description:"Reported model token usage; pending and deferred polls are excluded.",unit:"token",attributes:{provider:k,model:P,kind:{type:"string",description:"Token usage category.",values:["input","output","cache_read","cache_write"],required:!0}}},"pi.ai.cost":{kind:"counter",description:"Reported model cost; pending and deferred polls are excluded.",unit:"USD",attributes:{provider:k,model:P}}}};function De(n){let e=z(n,[q]);return{requestDuration:e.histogram("pi.ai.request.duration"),firstChunkDuration:e.histogram("pi.ai.first_chunk.duration"),tokens:e.counter("pi.ai.tokens"),cost:e.counter("pi.ai.cost")}}var fe=new WeakMap;function $(n,e,r){let t=performance.now(),s={provider:n.provider,model:n.id},i=e?.telemetry?.metrics??I,o=fe.get(i);o||(o=De(i),fe.set(i,o));let{requestDuration:c,firstChunkDuration:d,tokens:h,cost:b}=o,g,M,w=!0,y=new Map,a=new Promise(u=>{M=u}),l=u=>(g=u,a),p={...s,api:n.api,...typeof e?.reasoning=="string"?{reasoning:e.reasoning}:{}},m=de(e?.telemetry??E,[q]);return m(r?"pi.ai.poll":"pi.ai.request",p,l),{onEvent(u){if(w&&(w=!1,g.addEvent("pi.ai.first_chunk"),d.record(performance.now()-t,s,g)),u.type==="toolcall_delta")y.set(u.contentIndex,(y.get(u.contentIndex)??0)+u.delta.length);else if(u.type==="text_end"||u.type==="thinking_end")g.addEvent("pi.ai.block",{type:u.type==="text_end"?"text":"thinking",index:u.contentIndex,chars:u.content.length});else if(u.type==="toolcall_end"){let be=y.get(u.contentIndex)??0;y.delete(u.contentIndex),g.addEvent("pi.ai.block",{type:"tool_call",index:u.contentIndex,chars:be,tool:u.toolCall.name})}},onResult(u){u&&(g.setAttributes({stop:u.stopReason,"usage.input":u.usage.input,"usage.output":u.usage.output,"usage.cache_read":u.usage.cacheRead,"usage.cache_write":u.usage.cacheWrite,"cost.total":u.usage.cost.total,"response.id":u.responseId}),u.stopReason==="error"&&g.setStatus({status:"error",error:{name:"provider_error",message:Q(u.errorMessage??"",0,500)}}),c.record(performance.now()-t,{...s,stop:u.stopReason},g),(!r||u.stopReason!=="pending"&&u.stopReason!=="deferred")&&(h.add(u.usage.input,{...s,kind:"input"}),h.add(u.usage.output,{...s,kind:"output"}),h.add(u.usage.cacheRead,{...s,kind:"cache_read"}),h.add(u.usage.cacheWrite,{...s,kind:"cache_write"}),b.add(u.usage.cost.total,s))),M()}}}function S(n){return n.type??"chat"}function A(n,e){return S(n)===e}function he(n){if(!A(n,"chat"))throw new f("provider",`Model ${n.provider}/${n.id} is not a chat model`)}function pe(n){if(!A(n,"image"))throw new f("provider",`Model ${n.provider}/${n.id} is not an image model`)}function me(n){if(!A(n,"classifier"))throw new f("provider",`Model ${n.provider}/${n.id} is not a classifier model`)}function ge(n,e){if(e.images?.length&&!n.input.includes("image"))throw new f("provider",`Model ${n.provider}/${n.id} does not accept image input`)}function Y(n,e,r=!1){return{api:n.api,provider:n.provider,model:n.id,output:[],stopReason:r?"aborted":"error",errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()}}function G(n,e,r=!1){return{api:n.api,provider:n.provider,model:n.id,answers:{},stopReason:r?"aborted":"error",errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()}}var Ne={chat:!0,image:!0,classifier:!0};function ye(n){return Object.hasOwn(Ne,S(n))}function Le(n){return{...n,models:n.models.filter(ye)}}function F(n,e){if(!n&&!e)return;let r={...n};for(let[t,s]of Object.entries(e??{})){let i=t.toLowerCase();for(let o of Object.keys(r))o.toLowerCase()===i&&delete r[o];r[t]=s}return r}var J=class{providers=new Map;credentials;modelsStore;authContext;identity;refreshGenerations=new Map;refreshControllers=new Map;publicationChains=new Map;constructor(e){this.credentials=e?.credentials??new _,this.modelsStore=e?.modelsStore??new R,this.authContext=e?.authContext??ie(),this.identity=e?.identity}setProvider(e){this.supersedeProviderRefresh(e.id),this.providers.set(e.id,e)}deleteProvider(e){this.supersedeProviderRefresh(e),this.providers.delete(e)}clearProviders(){for(let e of new Set([...this.providers.keys(),...this.refreshControllers.keys()]))this.supersedeProviderRefresh(e);this.providers.clear()}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}getModels(e){if(e!==void 0){let t=this.providers.get(e);if(!t)return[];try{return t.getModels()}catch{return[]}}let r=[];for(let t of this.providers.values())try{r.push(...t.getModels())}catch{}return r}getAllModels(e){if(e!==void 0){let t=this.providers.get(e);if(!t)return[];try{return t.getAllModels?.()??t.getModels()}catch{return[]}}let r=[];for(let t of this.providers.values())try{r.push(...t.getAllModels?.()??t.getModels())}catch{}return r}getModelsOfType(e,r){return this.getAllModels(r).filter(t=>A(t,e))}getModel(e,r){return this.getModels(e).find(t=>t.id===r)}getModelOfType(e,r,t){return this.getModelsOfType(e,r).find(s=>s.id===t)}supersedeProviderRefresh(e){let r=(this.refreshGenerations.get(e)??0)+1;this.refreshGenerations.set(e,r);let t=this.refreshControllers.get(e);return t&&(this.refreshControllers.delete(e),t.abort()),r}beginProviderRefresh(e){let r=this.supersedeProviderRefresh(e),t=new AbortController;return this.refreshControllers.set(e,t),{generation:r,controller:t}}publishProviderModels(e,r,t,s){let i=this.publicationChains.get(e)??Promise.resolve(),o=(async()=>(await i.catch(()=>{}),t.aborted||this.refreshGenerations.get(e)!==r||(s.persist===null?await this.modelsStore.delete(e,{signal:t}):s.persist!==void 0&&await this.modelsStore.write(e,structuredClone(s.persist),{signal:t}),t.aborted||this.refreshGenerations.get(e)!==r)?!1:(s.update?.(),!0)))(),c=o.catch(()=>{});return this.publicationChains.set(e,c),c.then(()=>{this.publicationChains.get(e)===c&&this.publicationChains.delete(e)}),x(o,t)}async runProviderRefreshPhase(e,r,t,s,i,o){let c=await this.modelsStore.read(e.id,{signal:o});await e.refreshModels({credential:r,stored:c?Le(structuredClone(c)):void 0,publish:d=>this.publishProviderModels(e.id,i,o,d),allowNetwork:t,force:t?s:void 0,signal:o,baseUrl:e.baseUrl})}async refresh(e={}){let r=e.allowNetwork??!0,t=v(e.signal),s=new Map;if(t.aborted)return{aborted:!0,errors:s};let i=e.providers?new Set(e.providers):void 0,o=Array.from(this.providers.values()).filter(d=>d.refreshModels!==void 0&&(!i||i.has(d.id))),c=Promise.all(o.map(async d=>{let{generation:h,controller:b}=this.beginProviderRefresh(d.id),g=AbortSignal.any([t,b.signal]),M=(async()=>{let w,y;try{w=await this.readCredential(d.id,g)}catch(l){y=l}if(await this.runProviderRefreshPhase(d,w,!1,void 0,h,g),y!==void 0)throw y;if(!r||g.aborted)return;let a=await this.resolveNetworkRefresh(d,w,g);a&&await this.runProviderRefreshPhase(d,a.credential,!0,e.force,h,g)})();try{await x(M,g)}catch(w){g.aborted||s.set(d.id,w instanceof Error?w:new f("model_source",`Model refresh failed for ${d.id}`,{cause:w}))}finally{this.refreshControllers.get(d.id)===b&&this.refreshControllers.delete(d.id)}}));try{await x(c,t)}catch(d){if(!t.aborted)throw d}return{aborted:t.aborted,errors:new Map(s)}}async resolveNetworkRefresh(e,r,t){if(e.refreshModelsAuth==="configured")return await this.checkProviderAuth(e,r,t)?{}:void 0;let s=await this.resolveRefreshCredential(e,r,t);return s?{credential:s}:void 0}async resolveRefreshCredential(e,r,t){if(r?.type==="oauth"){let c=e.auth.oauth;return c?Date.now()<r.expires?r:t.aborted?void 0:W(this.credentials,e.id,c,d=>Date.now()>=d.expires,t):void 0}let s=e.auth.apiKey;if(!s)return;let i=r?.type==="api_key"?r:void 0,o=await s.resolve({ctx:this.authContext,credential:i,signal:t});if(o)return{type:"api_key",key:o.auth.apiKey,env:o.env}}async readCredential(e,r){try{return await this.credentials.read(e,{signal:r})}catch(t){throw new f("auth",`Credential store read failed for ${e}`,{cause:t})}}async checkProviderAuth(e,r,t){if(r?.type==="oauth")return e.auth.oauth?{source:"OAuth",type:"oauth"}:void 0;let s=e.auth.apiKey;if(!s)return;if(s.check)try{return await s.check({ctx:this.authContext,credential:r?.type==="api_key"?r:void 0,signal:t})}catch(o){throw new f("auth",`API key auth check failed for provider ${e.id}`,{cause:o})}let i=await U(e,this.credentials,this.authContext,{signal:t});return i?{source:i.source,type:"api_key"}:void 0}checkAuth(e,r){let t=v(r?.signal),s=(async()=>{t.throwIfAborted();let i=this.providers.get(e);if(i)return this.checkProviderAuth(i,await this.readCredential(e,t),t)})();return x(s,t)}async getAuthenticatedProviders(e,r){r.throwIfAborted();let t=e?[this.providers.get(e)].filter(i=>i!==void 0):this.getProviders();return(await Promise.all(t.map(async i=>{let o=await this.readCredential(i.id,r);return{provider:i,credential:o,auth:await this.checkProviderAuth(i,o,r)}}))).filter(i=>i.auth!==void 0)}getAvailable(e,r){let t=v(r?.signal),s=(async()=>(await this.getAuthenticatedProviders(e,t)).flatMap(({provider:o,credential:c})=>{let d=o.getModels();return o.filterModels?.(d,c)??d}))();return x(s,t)}async getAvailableOfType(e,r,t){return(await this.getAllAvailable(r,t)).filter(s=>A(s,e))}getAllAvailable(e,r){let t=v(r?.signal),s=(async()=>(await this.getAuthenticatedProviders(e,t)).flatMap(({provider:o,credential:c})=>{let d=o.getAllModels?.()??o.getModels();if(o.filterAllModels)return o.filterAllModels(d,c);if(!o.filterModels)return d;let h=new Set(o.filterModels(o.getModels(),c).map(b=>b.id));return d.filter(b=>!A(b,"chat")||h.has(b.id))}))();return x(s,t)}async getAuth(e,r){let t=v(r?.signal),s=typeof e=="string"?e:e.provider,i=this.providers.get(s);if(!i)return;let o=await U(i,this.credentials,this.authContext,{...r,signal:t});return!o||typeof e=="string"||!e.headers?o:{...o,auth:{...o.auth,headers:F(o.auth.headers,e.headers)}}}async login(e,r,t,s){let i=v(t.signal);i.throwIfAborted();let o=this.providers.get(e);if(!o)throw new f("provider",`Unknown provider: ${e}`);let c=r==="oauth"?o.auth.oauth:o.auth.apiKey;if(!c?.login)throw new f("auth",`${o.name} does not support ${r} login`);let d=c.login({...t,signal:i},s),h=await x(d,i),b=!1,g,M=new Promise(y=>{g=y}),w=this.credentials.modify(e,async()=>(b=!0,g?.(),h),{signal:i});w.catch(()=>{});try{await new Promise((y,a)=>{let l=()=>{b||a(i.reason)};i.addEventListener("abort",l,{once:!0}),Promise.race([M,w]).then(()=>{i.removeEventListener("abort",l),y()},p=>{i.removeEventListener("abort",l),a(p)}),i.aborted&&l()}),await w}catch(y){throw i.throwIfAborted(),new f("auth",`Credential store modify failed for ${e}`,{cause:y})}return h}async logout(e,r){let t=v(r?.signal);t.throwIfAborted();try{await this.credentials.delete(e,{signal:t})}catch(s){throw t.throwIfAborted(),new f("auth",`Credential store delete failed for ${e}`,{cause:s})}}requireProvider(e){let r=this.providers.get(e.provider);if(!r)throw new f("provider",`Unknown provider: ${e.provider}`);return r}requireChatProvider(e){return he(e),this.requireProvider(e)}async applyAuth(e,r){this.requireProvider(e);let t=await this.getAuth(e,{apiKey:r?.apiKey,env:r?.env,signal:r?.signal});if(!t)throw new f("auth",`Provider is not configured: ${e.provider}`);let s=t.auth,i=r?.apiKey??s.apiKey,o=s.baseUrl?{...e,baseUrl:s.baseUrl}:e,c=r&&"sessionId"in r&&typeof r.sessionId=="string"?r.sessionId:void 0,d=F(F(ee(o,c),s.headers),r?.headers);r?.transformHeaders&&(d=await r.transformHeaders(d??{}));let h=t.env||r?.env?{...t.env??{},...r?.env??{}}:void 0,b=Z(this.identity,r?.identity),{transformHeaders:g,...M}=r??{},w={...M,apiKey:i,headers:d,env:h,...b===void 0?{}:{identity:b}};return{requestModel:o,requestOptions:w}}stream(e,r,t){let s=j(r);return T(e,async()=>{let i=this.requireChatProvider(e),{requestModel:o,requestOptions:c}=await this.applyAuth(e,t);return i.stream(o,s,c)},$(e,t,!1),t?.signal)}async complete(e,r,t){return this.stream(e,r,t).result()}streamSimple(e,r,t){let s=j(r);return T(e,async()=>{let i=this.requireChatProvider(e),{requestModel:o,requestOptions:c}=await this.applyAuth(e,t);return i.streamSimple(o,s,c)},$(e,t,!1),t?.signal)}async completeSimple(e,r,t){return this.streamSimple(e,r,t).result()}streamDeferred(e,r,t){return T(e,async()=>{let s=this.requireChatProvider(e);if(!s.fetchDeferred)throw new f("provider",`Provider ${e.provider} does not support deferred responses`);let{requestModel:i,requestOptions:o}=await this.applyAuth(e,t);return s.fetchDeferred(i,r,o)},$(e,t,!0),t?.signal)}async fetchDeferred(e,r,t){return this.streamDeferred(e,r,t).result()}async cancelDeferred(e,r,t){let s=this.requireChatProvider(e);if(!s.cancelDeferred)throw new f("provider",`Provider ${e.provider} does not support deferred responses`);let{requestModel:i,requestOptions:o}=await this.applyAuth(e,t);await s.cancelDeferred(i,r,o)}async generateImages(e,r,t){try{pe(e);let s=this.requireProvider(e);if(!s.generateImages)throw new f("provider",`Provider ${e.provider} does not support image generation`);let{requestModel:i,requestOptions:o}=await this.applyAuth(e,t);return await s.generateImages(i,r,o)}catch(s){return Y(e,s,t?.signal?.aborted)}}async classify(e,r,t){try{me(e),ge(e,r);let s=this.requireProvider(e);if(!s.classify)throw new f("provider",`Provider ${e.provider} does not support classification`);let{requestModel:i,requestOptions:o}=await this.applyAuth(e,t);return await s.classify(i,r,o)}catch(s){return G(e,s,t?.signal?.aborted)}}};function je(n){return new J(n)}function Ke(n){let e=n.api&&typeof n.api.stream=="function"?n.api:void 0,r=e||!n.api?void 0:n.api,t=n.images,s=n.classifiers,i=e?[e]:Object.values(r??{}).filter(a=>a!==void 0),o=Object.values(t??{}).filter(a=>a!==void 0),c=Object.values(s??{}).filter(a=>a!==void 0);if(i.length===0&&o.length===0&&c.length===0)throw new Error(`Provider ${n.id}: at least one of "api", "images", or "classifiers" is required.`);let d=n.models,h=[],b=n.fetchModels,g=()=>{let a=[...d];for(let l of h){let p=a.findIndex(m=>S(m)===S(l)&&m.id===l.id);p>=0?a[p]=l:a.push(l)}return a},M=a=>e??r?.[a.api],w=(a,l,p)=>{let m=M(a);return m?l(m):T(a,async()=>{throw new f("stream",`Provider ${n.id} has no API implementation for "${a.api}"`)},void 0,p)},y={id:n.id,name:n.name??n.id,baseUrl:n.baseUrl,headers:n.headers,auth:n.auth,getModels:()=>g().filter(a=>A(a,"chat")),getAllModels:g,refreshModels:b?async a=>{if(a.stored){let m=a.stored.models.filter(u=>u.provider===n.id).map(u=>u);if(!await a.publish({update:()=>{h=m}}))return}if(!a.allowNetwork||a.signal.aborted)return;let l=await b(a);if(a.signal.aborted)return;let p=l.filter(ye);await a.publish({persist:{models:p,checkedAt:Date.now()},update:()=>{h=p}})}:void 0,filterModels:n.filterModels,filterAllModels:n.filterAllModels,stream:(a,l,p)=>w(a,m=>m.stream(a,l,p),p?.signal),streamSimple:(a,l,p)=>w(a,m=>m.streamSimple(a,l,p),p?.signal)};return i.some(a=>a.fetchDeferred!==void 0)&&(y.fetchDeferred=(a,l,p)=>T(a,async()=>{let m=M(a);if(!m?.fetchDeferred)throw new f("provider",`Provider ${n.id} does not support deferred responses for "${a.api}"`);return m.fetchDeferred(a,l,p)},void 0,p?.signal)),i.some(a=>a.cancelDeferred!==void 0)&&(y.cancelDeferred=async(a,l,p)=>{let m=M(a);if(!m?.cancelDeferred)throw new f("provider",`Provider ${n.id} cannot cancel deferred responses for "${a.api}"`);await m.cancelDeferred(a,l,p)}),t&&o.length>0&&(y.generateImages=async(a,l,p)=>{let m=t[a.api];return m?m.generateImages(a,l,p):Y(a,new f("provider",`Provider ${n.id} has no image generation implementation for "${a.api}"`))}),s&&c.length>0&&(y.classify=async(a,l,p)=>{let m=s[a.api];return m?m.classify(a,l,p):G(a,new f("provider",`Provider ${n.id} has no classifier implementation for "${a.api}"`))}),y}function Ue(n,e){return A(n,"chat")&&n.api===e}function We(n,e){let r=e.input+e.cacheRead+e.cacheWrite,t=n.cost,s=-1;for(let c of n.cost.tiers??[])r>c.inputTokensAbove&&c.inputTokensAbove>s&&(t=c,s=c.inputTokensAbove);let i=e.cacheWrite1h??0,o=e.cacheWrite-i;return e.cost.input=t.input/1e6*e.input,e.cost.output=t.output/1e6*e.output,e.cost.cacheRead=t.cacheRead/1e6*e.cacheRead,e.cost.cacheWrite=(t.cacheWrite*o+t.input*2*i)/1e6,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite,e.cost.totalFromProvider=!1,e.cost}var O=["off","minimal","low","medium","high","xhigh","max"];function we(n){return n.reasoning?O.filter(e=>{let r=n.thinkingLevelMap?.[e];return r===null?!1:e==="xhigh"||e==="max"?r!==void 0:!0}):["off"]}function ze(n,e){let r=we(n);if(r.includes(e))return e;let t=O.indexOf(e);if(t===-1)return r[0]??"off";for(let s=t;s<O.length;s++){let i=O[s];if(r.includes(i))return i}for(let s=t-1;s>=0;s--){let i=O[s];if(r.includes(i))return i}return r[0]??"off"}function He(n,e){return!n||!e?!1:S(n)===S(e)&&n.id===e.id&&n.provider===e.provider}export{ie as a,_ as b,f as c,R as d,q as e,S as f,A as g,he as h,pe as i,me as j,ge as k,Y as l,G as m,ve as n,j as o,te as p,Fe as q,D as r,re as s,Je as t,xe as u,Xe as v,N as w,L as x,Ve as y,Be as z,Qe as A,Ze as B,et as C,je as D,Ke as E,Ue as F,We as G,we as H,ze as I,He as J,Ye as K};
@@ -1,4 +1,4 @@
1
1
  import { createRequire as __cortexCreateRequire } from 'node:module';
2
2
  const require = __cortexCreateRequire(import.meta.url);
3
3
  const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as f,b as c,c as $,d as m}from"./chunk-KGJZAYQD.js";import{a as w,b as g}from"./chunk-FF7UELTU.js";var b={"TypeSafe-Danger-Zone-Images":"true"};function E(e,t,s){if(!f(t))throw new Error(`${e} returned invalid probabilities for ${s}`);return Object.fromEntries(Object.entries(t).map(([i,r])=>[i,c(e,r,`probability for ${s}.${i}`)]))}function I(e,t,s){if(!f(t))throw new Error(`${e} returned an unexpected response`);let i=[];for(let[r,n]of Object.entries(s.questions)){let o=t[r];if(!f(o))throw new Error(`${e} did not return an answer for ${r}`);if(n.type==="choice"){if(o.type!=="choice"||typeof o.choice!="string")throw new Error(`${e} did not return a choice answer for ${r}`);i.push([r,{type:"choice",choice:o.choice,probabilities:E(e,o.probabilities,r),confidence:c(e,o.confidence,`confidence for ${r}`)}])}else if(n.type==="score"){if(o.type!=="score")throw new Error(`${e} did not return a score answer for ${r}`);i.push([r,{type:"score",score:c(e,o.score,`score for ${r}`),confidence:c(e,o.confidence,`confidence for ${r}`)}])}else{if(o.type!=="noul")throw new Error(`${e} did not return a bool answer for ${r}`);i.push([r,{type:"bool",probability:c(e,o.noul,`probability for ${r}`)}])}}return Object.fromEntries(i)}var O={"image/png":"png","image/jpeg":"jpeg"},T=new Set(["image/png","image/jpeg","image/webp"]),h=4;function A(e,t,s,i,r){if(s==="images"){if(i.length>h)throw new Error(`${e} accepts at most ${h} images for ${t.id}, got ${i.length}`);r.images=i.map(o=>{if(!T.has(o.mimeType))throw new Error(`${e} accepts PNG, JPEG, and WebP images for ${t.id}, got ${o.mimeType}`);return`data:${o.mimeType};base64,${o.data}`});return}if(s==="state-image-urls"){let o=i.map(a=>({type:"image_url",image_url:{url:`data:${a.mimeType};base64,${a.data}`}}));r.state=[...o,r.state];return}let n={};i.forEach((o,a)=>{let p=O[o.mimeType];if(!p)throw new Error(`${e} accepts PNG and JPEG images for ${t.id}, got ${o.mimeType}`);n[`<image-${a+1}>`]={type:"image",format:p,data_base64:o.data}}),r.assets=n,r.state=[...Object.keys(n),r.state]}function _(e){return{state:e.state,questions:Object.fromEntries(Object.entries(e.questions).map(([t,s])=>[t,s.type==="bool"?{...s,type:"noul"}:s]))}}async function R(e,t,s,i){let r={api:t.api,provider:t.provider,model:t.id,answers:{},stopReason:"stop",timestamp:Date.now()};try{if(t.api!==e.api)throw new Error(`Unsupported classifier API: ${t.api}`);let n=_(s),o=i;if(s.images?.length){if(!t.input.includes("image"))throw new Error(`${e.label} does not support image input for ${t.id}`);let d=e.detectCompat(t),y=t.compat?.imageInput??d.imageInput;A(e.label,t,y,s.images,n),(t.compat?.sendImageOptInHeader??d.sendImageOptInHeader)&&(o={...i,headers:{...b,...i?.headers}})}let a=await $(e.label,e.url(t),t,e.payload(t,n),o),p=e.output(a),u=m(p.usage,t);return u&&(r.usage=u),r.answers=I(e.label,p.answers,s),r}catch(n){return r.stopReason=i?.signal?.aborted?"aborted":"error",r.errorMessage=g(w(n),`${e.label} error`),r}}export{R as a};
4
+ import{a as f,b as c,c as $,d as m}from"./chunk-J7OBATRN.js";import{a as w,c as g}from"./chunk-ZD4O6NPV.js";var b={"TypeSafe-Danger-Zone-Images":"true"};function E(e,t,s){if(!f(t))throw new Error(`${e} returned invalid probabilities for ${s}`);return Object.fromEntries(Object.entries(t).map(([i,r])=>[i,c(e,r,`probability for ${s}.${i}`)]))}function I(e,t,s){if(!f(t))throw new Error(`${e} returned an unexpected response`);let i=[];for(let[r,n]of Object.entries(s.questions)){let o=t[r];if(!f(o))throw new Error(`${e} did not return an answer for ${r}`);if(n.type==="choice"){if(o.type!=="choice"||typeof o.choice!="string")throw new Error(`${e} did not return a choice answer for ${r}`);i.push([r,{type:"choice",choice:o.choice,probabilities:E(e,o.probabilities,r),confidence:c(e,o.confidence,`confidence for ${r}`)}])}else if(n.type==="score"){if(o.type!=="score")throw new Error(`${e} did not return a score answer for ${r}`);i.push([r,{type:"score",score:c(e,o.score,`score for ${r}`),confidence:c(e,o.confidence,`confidence for ${r}`)}])}else{if(o.type!=="noul")throw new Error(`${e} did not return a bool answer for ${r}`);i.push([r,{type:"bool",probability:c(e,o.noul,`probability for ${r}`)}])}}return Object.fromEntries(i)}var O={"image/png":"png","image/jpeg":"jpeg"},T=new Set(["image/png","image/jpeg","image/webp"]),h=4;function A(e,t,s,i,r){if(s==="images"){if(i.length>h)throw new Error(`${e} accepts at most ${h} images for ${t.id}, got ${i.length}`);r.images=i.map(o=>{if(!T.has(o.mimeType))throw new Error(`${e} accepts PNG, JPEG, and WebP images for ${t.id}, got ${o.mimeType}`);return`data:${o.mimeType};base64,${o.data}`});return}if(s==="state-image-urls"){let o=i.map(a=>({type:"image_url",image_url:{url:`data:${a.mimeType};base64,${a.data}`}}));r.state=[...o,r.state];return}let n={};i.forEach((o,a)=>{let p=O[o.mimeType];if(!p)throw new Error(`${e} accepts PNG and JPEG images for ${t.id}, got ${o.mimeType}`);n[`<image-${a+1}>`]={type:"image",format:p,data_base64:o.data}}),r.assets=n,r.state=[...Object.keys(n),r.state]}function _(e){return{state:e.state,questions:Object.fromEntries(Object.entries(e.questions).map(([t,s])=>[t,s.type==="bool"?{...s,type:"noul"}:s]))}}async function R(e,t,s,i){let r={api:t.api,provider:t.provider,model:t.id,answers:{},stopReason:"stop",timestamp:Date.now()};try{if(t.api!==e.api)throw new Error(`Unsupported classifier API: ${t.api}`);let n=_(s),o=i;if(s.images?.length){if(!t.input.includes("image"))throw new Error(`${e.label} does not support image input for ${t.id}`);let d=e.detectCompat(t),y=t.compat?.imageInput??d.imageInput;A(e.label,t,y,s.images,n),(t.compat?.sendImageOptInHeader??d.sendImageOptInHeader)&&(o={...i,headers:{...b,...i?.headers}})}let a=await $(e.label,e.url(t),t,e.payload(t,n),o),p=e.output(a),u=m(p.usage,t);return u&&(r.usage=u),r.answers=I(e.label,p.answers,s),r}catch(n){return r.stopReason=i?.signal?.aborted?"aborted":"error",r.errorMessage=g(w(n),`${e.label} error`),r}}export{R as a};
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __cortexCreateRequire } from 'node:module';
2
2
  const require = __cortexCreateRequire(import.meta.url);
3
3
  const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as K}from"./chunk-V35MFAUQ.js";import{e as I}from"./chunk-AVXDF7AG.js";import{e as A}from"./chunk-VBN2JSER.js";import{s as S}from"./chunk-Z24SBRJK.js";import{e as Y}from"./chunk-WHC7AYZD.js";var j=Y(K(),1);import*as u from"fs";import*as f from"path";var b=A("index-regen"),C=["experiments","knowledge","patterns"],X=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,H=/^([A-Za-z_][\w-]*):(?:\s|$)/;function N(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function J(t){let s={},r=null,i=[],c=()=>{if(!r)return;let o=i.join(`
4
+ import{a as K}from"./chunk-V35MFAUQ.js";import{e as I}from"./chunk-TRXLIL7V.js";import{e as A}from"./chunk-7W7VYUTK.js";import{u as S}from"./chunk-T54CZKNJ.js";import{e as Y}from"./chunk-WHC7AYZD.js";var j=Y(K(),1);import*as u from"fs";import*as f from"path";var b=A("index-regen"),C=["experiments","knowledge","patterns"],X=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,H=/^([A-Za-z_][\w-]*):(?:\s|$)/;function N(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function J(t){let s={},r=null,i=[],c=()=>{if(!r)return;let o=i.join(`
5
5
  `);try{let n=(0,j.parse)(o);s[r]=N(n)?n[r]:null}catch{s[r]=o.slice(r.length+1).trim()}};for(let o of t.split(/\r?\n/)){let n=H.exec(o);n?(c(),r=n[1],i=[o]):r&&i.push(o)}return c(),s}function B(t){let s=X.exec(t);if(!s)return{meta:{},valid:!0};try{let r=(0,j.parse)(s[1]);if(N(r))return{meta:r,valid:!0}}catch{}return{meta:J(s[1]),valid:!1}}function w(t){return Array.isArray(t)?t.map(s=>String(s)):[]}function V(t){let s=new Map,r;try{r=u.readFileSync(f.join(t,"_meta","access-log.jsonl"),"utf8")}catch{return s}for(let i of r.split(`
6
6
  `)){if(!i.trim())continue;let c;try{c=JSON.parse(i)}catch{continue}if(typeof c.file!="string")continue;let o=typeof c.ts=="string"?c.ts:null,n=s.get(c.file);if(!n){s.set(c.file,{refs:1,lastRef:o});continue}n.refs++,o&&(!n.lastRef||o>n.lastRef)&&(n.lastRef=o)}return s}var q={refs:0,lastRef:null};function z(t){let s;try{s=u.readdirSync(t).sort()}catch{return[]}let r=[];for(let i of s){if(i==="index.md"||i.startsWith("_")||i.startsWith(".")||!i.endsWith(".md"))continue;let c;try{c=u.readFileSync(f.join(t,i),"utf8")}catch{continue}let{meta:o,valid:n}=B(c);o.id===void 0||o.id===null||o.id===""||(n||b.warn(`${f.join(t,i)}: frontmatter is not valid YAML, read key by key`),r.push({id:String(o.id),filename:i,meta:o,validFrontmatter:n}))}return r}var Z=["invalidated"],G=["superseded","deprecated"],Q=["refined","stale"];function m(t){let s=t.meta.status;return s==null?"":String(s)}function T(t){if(!t)return!0;let s=t.toLowerCase();return!(Z.some(r=>s.startsWith(r))||G.some(r=>s.startsWith(r))||Q.includes(s))}function k(t){return t.toLowerCase().startsWith("invalidated")}var ee={experiments:"Use when: reviewing past experiment results, checking what has been tried, or looking for related prior work before designing a new experiment.",knowledge:"Use when: applying validated facts/principles to current work, checking if a question has already been answered, or verifying assumptions against established knowledge.",patterns:"Use when: looking for cross-experiment regularities, anti-patterns to avoid, or established best practices before making design decisions."},te="> Auto-generated from YAML frontmatter; Refs / Last ref come from _meta/access-log.jsonl. Do not edit manually. Not tracked by git.";function a(t,s){if(t==null)return"";let r=(typeof t=="object"?JSON.stringify(t):String(t)).replace(/\s*\r?\n\s*/g," ");return s!==void 0&&(r=r.slice(0,s)),r.replace(/\|/g,"\\|")}function g(t,...s){for(let r of s){let i=t.meta[r];if(i!=null&&i!=="")return i}}function L(t){return w(t.meta.tags).slice(0,4).map(s=>`\`${a(s)}\``).join(", ")}function _(t,s){I(f.join(t,"index.md"),s)}function ne(t,s){let r=z(t),i=f.basename(t),c=ee[i]||"",o=new Date().toISOString().slice(0,19),n=[`# ${s}`,""];if(c&&n.push(c,""),n.push(te,`> Last updated: ${o}`,""),r.length===0){n.push("_No entries._",""),_(t,n.join(`
7
7
  `));return}let W=V(f.dirname(t)),p=e=>W.get(e.filename)??q,x=e=>`${p(e).refs} | ${p(e).lastRef?.slice(0,10)??""}`,d=r.filter(e=>T(m(e))),y=r.filter(e=>k(m(e))),$=r.filter(e=>!T(m(e))&&!k(m(e)));d.sort((e,l)=>{let h=p(l).refs-p(e).refs;return h!==0?h:String(l.meta.date??"").localeCompare(String(e.meta.date??""))});let F=r.some(e=>e.id.startsWith("EXP-")),O=r.some(e=>e.id.startsWith("K-"));if(n.push(`## Active (${d.length} entries)`,""),F){n.push("| ID | Date | Summary | Tags | Refs | Last ref | Links |"),n.push("|----|------|---------|------|------|----------|-------|");for(let e of d){let l=w(e.meta.links).map(h=>a(h)).join(", ");n.push(`| ${a(e.id)} | ${a(e.meta.date)} | ${a(g(e,"summary")??"\u2014",100)} | ${L(e)} | ${x(e)} | ${l} |`)}}else if(O){n.push("| ID | Title | Source | Refs | Last ref |"),n.push("|----|-------|--------|------|----------|");for(let e of d)n.push(`| ${a(e.id)} | ${a(g(e,"title","summary")??"\u2014")} | ${a(e.meta.source)} | ${x(e)} |`)}else{n.push("| ID | Summary | Tags | Sources | Refs | Last ref |"),n.push("|----|---------|------|---------|------|----------|");for(let e of d){let l=w(e.meta["source-experiments"]).map(h=>a(h)).join(", ");n.push(`| ${a(e.id)} | ${a(g(e,"summary","title")??"\u2014")} | ${L(e)} | ${l} | ${x(e)} |`)}}if(y.length>0){n.push("",`## Invalidated (${y.length} entries)`,""),n.push("> These entries have been proven wrong. Do NOT use their conclusions. Kept for audit trail only."),n.push(""),n.push("| ID | Date | Summary | Invalidated By | Refs |"),n.push("|----|------|---------|----------------|------|");for(let e of y){let l=m(e).replace(/^invalidated:/i,"").trim();n.push(`| ${a(e.id)} | ${a(e.meta.date)} | ${a(g(e,"summary","title")??"\u2014",80)} | ${a(l)} | ${p(e).refs} |`)}}if($.length>0){n.push("",`## Superseded / Deprecated (${$.length} entries)`,""),n.push("| ID | Date | Summary | Status | Refs |"),n.push("|----|------|---------|--------|------|");for(let e of $)n.push(`| ${a(e.id)} | ${a(e.meta.date)} | ${a(g(e,"summary","title")??"\u2014",80)} | ${a(m(e))} | ${p(e).refs} |`)}let D=5,R=14,M=Date.now(),P=d.filter(e=>p(e).refs>=D).map(e=>e.id),U=d.filter(e=>{if(p(e).refs>0)return!1;let l=e.meta.date?new Date(String(e.meta.date)):null;return!l||isNaN(l.getTime())?!1:(M-l.getTime())/864e5>R}).map(e=>e.id),E=d.filter(e=>m(e).toLowerCase().startsWith("challenged")),v=r.filter(e=>!e.validFrontmatter);n.push("","## Stats"),n.push(`- Total: ${r.length} (${d.length} active, ${y.length} invalidated, ${$.length} superseded/deprecated)`),E.length>0&&n.push(`- Challenged (under review): ${E.map(e=>e.id).join(", ")}`),n.push(`- Hot (refs >= ${D}): ${P.slice(0,10).join(", ")||"none"}`),n.push(`- Cold (refs=0, age>${R}d): ${U.slice(0,10).join(", ")||"none"}`),v.length>0&&n.push(`- Invalid YAML frontmatter (fix the file): ${v.map(e=>e.filename).join(", ")}`),n.push(""),_(t,n.join(`
@@ -0,0 +1,4 @@
1
+ import { createRequire as __cortexCreateRequire } from 'node:module';
2
+ const require = __cortexCreateRequire(import.meta.url);
3
+ const __cortexPackageRoot = new URL("../../", import.meta.url);
4
+ import{d as s}from"./chunk-X2TKJ7KR.js";var l="https://radius.pi.dev";function u(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let r=t;return typeof r.id=="string"&&typeof r.name=="string"&&typeof r.reasoning=="boolean"&&Array.isArray(r.input)&&typeof r.cost=="object"&&r.cost!==null&&!Array.isArray(r.cost)&&typeof r.contextWindow=="number"&&typeof r.maxTokens=="number"}function a(t){if(typeof t!="object"||t===null||Array.isArray(t))return;let{baseUrl:r,models:e}=t;if(!(typeof r!="string"||!Array.isArray(e)))return{baseUrl:r,models:e.filter(u).map(o=>({...o}))}}function y(t){return(/^https?:\/\//iu.test(t)?t:`https://${t}`).replace(/\/+$/u,"")}function f(t){return a(t?.gatewayConfig)}function c(t,r){return r.models.map(e=>({...e,api:"pi-messages",provider:t,baseUrl:r.baseUrl}))}function m(t,r){let e=f(r);return e?c(t,e):[]}function d(t){let r=t.trim();return r.length>512?`${s(r,0,512)}\u2026`:r}async function w(t,r,e){let o={accept:"application/json"};r&&(o.authorization=`Bearer ${r}`);let n=await fetch(new URL("/v1/config",t),{headers:o,signal:e});if(!n.ok)throw new Error(`Could not load Radius config from ${t}: ${n.status}: ${d(await n.text())}`);let i=a(await n.json());if(!i)throw new Error(`Invalid Radius config from ${t}`);return i}export{l as a,y as b,c,m as d,w as e};