@cortex-agent/server 2026.10.28 → 2026.12.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (401) hide show
  1. package/LICENSE +255 -21
  2. package/README.md +36 -7
  3. package/THIRD_PARTY_NOTICES.txt +1990 -593
  4. package/defaults/hooks/cortex-hook-api.mjs +2 -1
  5. package/defaults/hooks/quota-stop.mjs +37 -0
  6. package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +23 -15
  7. package/defaults/prompts/clean-workspace.md +5 -0
  8. package/dist/agent-adapter/claude/remote-mcp-proxy.js +1 -1
  9. package/dist/chunks/agent-runner-LVZVKBZX.js +4 -0
  10. package/dist/chunks/anthropic-messages-TT6454AA.js +8 -0
  11. package/dist/chunks/azure-openai-responses-52LR2XZD.js +4 -0
  12. package/dist/chunks/bedrock-converse-stream-EOZGYUNY.js +60 -0
  13. package/dist/chunks/bowser-MLGGLXTZ.js +20 -0
  14. package/dist/chunks/child-runner-SMG2VOU5.js +4 -0
  15. package/dist/chunks/chunk-24DH4IR5.js +4 -0
  16. package/dist/chunks/chunk-25XKBRDT.js +70 -0
  17. package/dist/chunks/chunk-2ABET62E.js +23 -0
  18. package/dist/chunks/chunk-2BVUA256.js +4 -0
  19. package/dist/chunks/{chunk-LEUENXI2.js → chunk-2WFL62UO.js} +1 -1
  20. package/dist/chunks/{chunk-OZGBWAT2.js → chunk-2YTYYG4K.js} +1 -1
  21. package/dist/chunks/chunk-335SSANX.js +4 -0
  22. package/dist/chunks/chunk-377OPTXX.js +17 -0
  23. package/dist/chunks/chunk-3EZNVLBF.js +129 -0
  24. package/dist/chunks/chunk-3O6ZG5HA.js +7 -0
  25. package/dist/chunks/{chunk-6AKUD3CF.js → chunk-3XLHL5YT.js} +1 -1
  26. package/dist/chunks/chunk-4HRI75GU.js +4 -0
  27. package/dist/chunks/chunk-4JBYLRPM.js +57 -0
  28. package/dist/chunks/chunk-4KKV7VKE.js +4 -0
  29. package/dist/chunks/chunk-4KQHDDC5.js +4 -0
  30. package/dist/chunks/chunk-4SWD4JMP.js +33 -0
  31. package/dist/chunks/chunk-52VCLZS5.js +4 -0
  32. package/dist/chunks/chunk-54P7TSY3.js +10 -0
  33. package/dist/chunks/chunk-5DVSAXOI.js +7 -0
  34. package/dist/chunks/chunk-5F3A62YS.js +4 -0
  35. package/dist/chunks/{chunk-XNSSUVT6.js → chunk-5FHETFZM.js} +1 -1
  36. package/dist/chunks/{chunk-A34TDMIC.js → chunk-5LBLRAHS.js} +1 -1
  37. package/dist/chunks/chunk-5UYVNA3W.js +4 -0
  38. package/dist/chunks/chunk-6G3OYMCV.js +21 -0
  39. package/dist/chunks/chunk-7GGPYU5E.js +30 -0
  40. package/dist/chunks/chunk-7TYSMLUV.js +4 -0
  41. package/dist/chunks/chunk-7W7VYUTK.js +5 -0
  42. package/dist/chunks/chunk-AXYAZTTN.js +6 -0
  43. package/dist/chunks/{chunk-BGVHA2D4.js → chunk-B3NB243Z.js} +1 -1
  44. package/dist/chunks/chunk-BKYP6AGM.js +8 -0
  45. package/dist/chunks/chunk-BVEDNESB.js +4 -0
  46. package/dist/chunks/chunk-BWDJS6A4.js +12 -0
  47. package/dist/chunks/chunk-C6YVF7EI.js +4 -0
  48. package/dist/chunks/chunk-CEJIYYVE.js +15 -0
  49. package/dist/chunks/chunk-CI2RHH74.js +50 -0
  50. package/dist/chunks/chunk-CMSOOLJB.js +4 -0
  51. package/dist/chunks/chunk-CSVTYYLP.js +4 -0
  52. package/dist/chunks/chunk-DE5EGVKG.js +6 -0
  53. package/dist/chunks/{chunk-E6BYRULL.js → chunk-DK3RPZOQ.js} +1 -1
  54. package/dist/chunks/{chunk-YPK2CAIZ.js → chunk-DK4UCK7L.js} +1 -1
  55. package/dist/chunks/chunk-DYLBVUAU.js +4 -0
  56. package/dist/chunks/chunk-FDC2GRBK.js +27 -0
  57. package/dist/chunks/chunk-FE7HH5JS.js +18 -0
  58. package/dist/chunks/chunk-FYD57YRO.js +436 -0
  59. package/dist/chunks/chunk-G264APQN.js +5 -0
  60. package/dist/chunks/chunk-G4JYZFEO.js +11 -0
  61. package/dist/chunks/chunk-GFFM56U2.js +4 -0
  62. package/dist/chunks/chunk-GOS3P7KS.js +132 -0
  63. package/dist/chunks/chunk-HVN37UXD.js +4 -0
  64. package/dist/chunks/chunk-IA6IODY3.js +4 -0
  65. package/dist/chunks/{chunk-HU6UIDEJ.js → chunk-IGZWZP7Z.js} +1 -1
  66. package/dist/chunks/{chunk-NR6U3WIZ.js → chunk-IJ7XFQMI.js} +1 -1
  67. package/dist/chunks/chunk-IMMGYDAB.js +6 -0
  68. package/dist/chunks/chunk-IOWBF7UK.js +10 -0
  69. package/dist/chunks/{chunk-HALUQ7ZF.js → chunk-ITGCWQFK.js} +1 -1
  70. package/dist/chunks/chunk-IVZ7QUEG.js +4 -0
  71. package/dist/chunks/{chunk-YAEVYJAR.js → chunk-IWY2HIFK.js} +1 -1
  72. package/dist/chunks/{chunk-KGJZAYQD.js → chunk-J7OBATRN.js} +1 -1
  73. package/dist/chunks/{chunk-QWAQHHRS.js → chunk-JGUEIW2W.js} +1 -1
  74. package/dist/chunks/chunk-JKL3AK5D.js +106 -0
  75. package/dist/chunks/chunk-JZ7U7RUK.js +351 -0
  76. package/dist/chunks/chunk-KJUQCCB5.js +4 -0
  77. package/dist/chunks/chunk-KST6OY76.js +10 -0
  78. package/dist/chunks/chunk-KZSAFVSY.js +129 -0
  79. package/dist/chunks/chunk-LD2ZSH3M.js +903 -0
  80. package/dist/chunks/chunk-LE6QPXN6.js +7 -0
  81. package/dist/chunks/chunk-LEAV3FFG.js +4 -0
  82. package/dist/chunks/chunk-LIIZI3HY.js +5 -0
  83. package/dist/chunks/chunk-LP72AF56.js +45 -0
  84. package/dist/chunks/{chunk-FXDIR3SQ.js → chunk-MJQ2D2OP.js} +1 -1
  85. package/dist/chunks/{chunk-6LZK4DDH.js → chunk-NHHR4DCF.js} +1 -1
  86. package/dist/chunks/chunk-NW4GW47L.js +4 -0
  87. package/dist/chunks/chunk-OALEJ6FG.js +60 -0
  88. package/dist/chunks/chunk-OIV4DIMB.js +4 -0
  89. package/dist/chunks/chunk-OJ37ZWBG.js +4 -0
  90. package/dist/chunks/chunk-OZXMPBUX.js +4 -0
  91. package/dist/chunks/{chunk-3THJYAEF.js → chunk-PG7452XE.js} +1 -1
  92. package/dist/chunks/chunk-PJCUB7YJ.js +4 -0
  93. package/dist/chunks/chunk-PTS3J4DQ.js +6 -0
  94. package/dist/chunks/{chunk-PXS5SHOV.js → chunk-PVVEEBUU.js} +1 -1
  95. package/dist/chunks/chunk-Q7BZLPBU.js +8 -0
  96. package/dist/chunks/{chunk-FOJQXLL2.js → chunk-QC66ZXPP.js} +1 -1
  97. package/dist/chunks/chunk-QXFWIL4C.js +4 -0
  98. package/dist/chunks/{chunk-PFMEUFJ7.js → chunk-R2CCD4OF.js} +1 -1
  99. package/dist/chunks/chunk-R6CGBSTC.js +22 -0
  100. package/dist/chunks/chunk-RG5GP4RB.js +5 -0
  101. package/dist/chunks/{chunk-D3NXKK2L.js → chunk-RW2F2QNP.js} +1 -1
  102. package/dist/chunks/{models-L5VF4I5O-XXNJYQMQ.js → chunk-RWPO3NZ3.js} +1 -1
  103. package/dist/chunks/chunk-SAJD4EKE.js +10 -0
  104. package/dist/chunks/chunk-SDUS2H3E.js +4 -0
  105. package/dist/chunks/chunk-SIHGKM4E.js +4 -0
  106. package/dist/chunks/chunk-SKHFU5DI.js +4 -0
  107. package/dist/chunks/{chunk-STUHNKQS.js → chunk-SM45TH22.js} +1 -1
  108. package/dist/chunks/chunk-T54CZKNJ.js +6 -0
  109. package/dist/chunks/chunk-TKFFQNAP.js +19 -0
  110. package/dist/chunks/chunk-TMV2ZDOI.js +18 -0
  111. package/dist/chunks/chunk-TRXLIL7V.js +4 -0
  112. package/dist/chunks/{chunk-SUFW24P4.js → chunk-UEEW2R4E.js} +1 -1
  113. package/dist/chunks/chunk-UHXPRU6G.js +10 -0
  114. package/dist/chunks/chunk-UPQVWHZ3.js +4 -0
  115. package/dist/chunks/{chunk-JERCOLY3.js → chunk-V35MFAUQ.js} +4 -6
  116. package/dist/chunks/chunk-V7K3KNDM.js +4 -0
  117. package/dist/chunks/chunk-VHX2GHBF.js +4 -0
  118. package/dist/chunks/chunk-VOAKRJ4R.js +4 -0
  119. package/dist/chunks/{chunk-X2GYYRVM.js → chunk-VW7TLY3P.js} +1 -1
  120. package/dist/chunks/chunk-W34AK4SK.js +65 -0
  121. package/dist/chunks/{chunk-REBNWCKI.js → chunk-WU7RNAZD.js} +1 -1
  122. package/dist/chunks/chunk-WZC4TDDM.js +6 -0
  123. package/dist/chunks/chunk-WZYS2HAK.js +4 -0
  124. package/dist/chunks/chunk-X2TKJ7KR.js +11 -0
  125. package/dist/chunks/{chunk-H2FP6DG4.js → chunk-X5ND4H4P.js} +1 -1
  126. package/dist/chunks/{chunk-4U7XXM4W.js → chunk-Y3AOGNDT.js} +1 -1
  127. package/dist/chunks/chunk-Y6DGVTKM.js +6 -0
  128. package/dist/chunks/{chunk-KENCMLRE.js → chunk-YAEHSSR4.js} +1 -1
  129. package/dist/chunks/chunk-YWPBE5LP.js +4 -0
  130. package/dist/chunks/chunk-ZAVX7G2M.js +15 -0
  131. package/dist/chunks/chunk-ZD2M73XA.js +19 -0
  132. package/dist/chunks/chunk-ZD4O6NPV.js +4 -0
  133. package/dist/chunks/chunk-ZNAMETPQ.js +4 -0
  134. package/dist/chunks/chunk-ZY6N5LVQ.js +4 -0
  135. package/dist/chunks/chunk-ZYQ4TDTT.js +81 -0
  136. package/dist/chunks/cli-VB2N7HEK.js +55 -0
  137. package/dist/chunks/cloudflare-workers-ai-system-one-YKU742EC.js +4 -0
  138. package/dist/chunks/context-CI2FKEQE.js +4 -0
  139. package/dist/chunks/cost-CZRRSIUF.js +5 -0
  140. package/dist/chunks/dist-QCNQN6DY.js +4 -0
  141. package/dist/chunks/easter-egg-3d-XR5S2O3T.js +4 -0
  142. package/dist/chunks/{event-streams-3JSFPOTZ.js → event-streams-AVE4MSS6.js} +1 -1
  143. package/dist/chunks/{execution-repo-ZLJTBWFC.js → execution-repo-5TLV2NM4.js} +1 -1
  144. package/dist/chunks/{executions-6ARGR3IO.js → executions-I3UUIGSL.js} +1 -1
  145. package/dist/chunks/file-Y5G56IUT.js +4 -0
  146. package/dist/chunks/github-copilot-BRU2SRRZ.js +4 -0
  147. package/dist/chunks/google-generative-ai-ZF5QEUZV.js +4 -0
  148. package/dist/chunks/google-vertex-4PJZZI3Y.js +4 -0
  149. package/dist/chunks/init-A6GY656J.js +4 -0
  150. package/dist/chunks/{install-cli-4IZCSDFZ.js → install-cli-FALWKQYO.js} +1 -1
  151. package/dist/chunks/{interaction-ask-G5T3H3CG.js → interaction-ask-O5HGF6CH.js} +1 -1
  152. package/dist/chunks/{interaction-plan-E5V42MUP.js → interaction-plan-JTVDN3BC.js} +1 -1
  153. package/dist/chunks/kimi-coding-ZCIBMDZ6.js +4 -0
  154. package/dist/chunks/{llama-cpp-classify-OTXZWCMW.js → llama-cpp-classify-NRUXAIGQ.js} +3 -3
  155. package/dist/chunks/local-client-stop-RS4AHNF4.js +4 -0
  156. package/dist/chunks/{memory-cli-PYOILNN5.js → memory-cli-DIT4DQF3.js} +1 -1
  157. package/dist/chunks/meta-JQH66YU7.js +4 -0
  158. package/dist/chunks/mistral-conversations-CXHOECUV.js +7 -0
  159. package/dist/chunks/model-resolver-GIBPYRKP.js +4 -0
  160. package/dist/chunks/monitor-Z2HKNY5E.js +4 -0
  161. package/dist/chunks/{node-PTK2HCDV.js → node-DAO3SX7O.js} +1 -1
  162. package/dist/chunks/{openai-codex-2REL6UQU.js → openai-codex-JULCKICT.js} +1 -1
  163. package/dist/chunks/openai-codex-responses-U6DGMGDK.js +12 -0
  164. package/dist/chunks/openai-completions-PP4XLLOM.js +9 -0
  165. package/dist/chunks/{openai-decisions-2N6ZRPZC.js → openai-decisions-JU6QQKEM.js} +1 -1
  166. package/dist/chunks/openai-responses-2SG757TL.js +6 -0
  167. package/dist/chunks/openrouter-images-32M7YZWC.js +4 -0
  168. package/dist/chunks/pi-messages-VSINMXN4.js +10 -0
  169. package/dist/chunks/radius-THYKWV4E.js +4 -0
  170. package/dist/chunks/remote-ops-2WBEFQ3E.js +14 -0
  171. package/dist/chunks/runner-5MKMRTIN.js +4 -0
  172. package/dist/chunks/runtime-DST3H5JP.js +4 -0
  173. package/dist/chunks/schedule-cli-V7Y2BBVY.js +4 -0
  174. package/dist/chunks/slack-R7SEJYMY.js +4 -0
  175. package/dist/chunks/start-ui-http-7K5JOLPU.js +43 -0
  176. package/dist/chunks/subagent-Z5IQ4L54.js +4 -0
  177. package/dist/chunks/{time-KEHDQT6K.js → time-P6PE52WL.js} +1 -1
  178. package/dist/chunks/tool-shims-YCXZWTST.js +4 -0
  179. package/dist/chunks/typesafe-system-one-M2DABJSZ.js +4 -0
  180. package/dist/chunks/ui-board-HQIE4RZG.js +5 -0
  181. package/dist/chunks/ui-decision-YBZDS4YW.js +4 -0
  182. package/dist/chunks/{ui-file-GVH53O3X.js → ui-file-SRD4ILBS.js} +1 -1
  183. package/dist/chunks/ui-view-Z25MTZT7.js +4 -0
  184. package/dist/chunks/virtual-modules-H4DXPJZB.js +4 -0
  185. package/dist/chunks/waitpoint-M6JZBSLT.js +5 -0
  186. package/dist/chunks/workers-SQ2R32TK.js +4 -0
  187. package/dist/client-bundle/client.mjs +273 -93
  188. package/dist/client-bundle/manifest.json +2 -2
  189. package/dist/core/pi-sdk.js +1 -1
  190. package/dist/domain/auth/cc-auth-cli.js +1 -1
  191. package/dist/domain/mcp/bundled-server.js +1 -1
  192. package/dist/domain/mcp/feishu/client.js +4 -0
  193. package/dist/entry/app.js +151 -559
  194. package/dist/entry/browser-cli.js +10 -10
  195. package/dist/entry/cli.js +1 -1
  196. package/dist/entry/cortex-cli.js +1 -1
  197. package/dist/entry/daemon.js +4 -4
  198. package/dist/entry/hook-cli.js +2 -2
  199. package/dist/entry/production-app-bootstrap.js +1 -1
  200. package/dist/entry/production-evidence-export-cli.js +1 -1
  201. package/dist/entry/signal-cli.js +2 -2
  202. package/dist/tui/index.js +41 -41
  203. package/package.json +3 -3
  204. package/vendor/pi/CHANGELOG.md +330 -0
  205. package/vendor/pi/dist/codemode-worker.js +2 -0
  206. package/vendor/pi/dist/core/export-html/ansi-to-html.js +57 -20
  207. package/vendor/pi/dist/core/export-html/template.css +9 -0
  208. package/vendor/pi/dist/core/export-html/template.js +166 -46
  209. package/vendor/pi/dist/core/export-html/tool-renderer.js +5 -3
  210. package/vendor/pi/dist/core/extensions/loader.js +1 -1
  211. package/vendor/pi/dist/extensions/codemode/execute.js +15 -13
  212. package/vendor/pi/dist/modes/interactive/theme/theme.js +36 -23
  213. package/vendor/pi/dist/utils/image-resize-worker.js +1 -1
  214. package/vendor/pi/dist/utils/image-resize.js +1 -1
  215. package/vendor/pi/docs/cli.md +35 -12
  216. package/vendor/pi/docs/custom-provider.md +2 -0
  217. package/vendor/pi/docs/environment-variables.md +2 -0
  218. package/vendor/pi/docs/extensions.md +3192 -225
  219. package/vendor/pi/docs/keybindings.md +2 -2
  220. package/vendor/pi/docs/llama-cpp.md +27 -19
  221. package/vendor/pi/docs/mcp.md +6 -4
  222. package/vendor/pi/docs/message-types.md +1 -1
  223. package/vendor/pi/docs/models-configuration.md +9 -3
  224. package/vendor/pi/docs/models.md +2 -1
  225. package/vendor/pi/docs/nvidia-rtx-llama-cpp.md +5 -5
  226. package/vendor/pi/docs/packages.md +24 -0
  227. package/vendor/pi/docs/prompt-templates.md +1 -1
  228. package/vendor/pi/docs/providers.md +4 -2
  229. package/vendor/pi/docs/quickstart.md +7 -3
  230. package/vendor/pi/docs/rpc-commands.md +1 -1
  231. package/vendor/pi/docs/rpc.md +4 -2
  232. package/vendor/pi/docs/sessions.md +17 -3
  233. package/vendor/pi/docs/settings.md +6 -5
  234. package/vendor/pi/docs/slash-commands.md +3 -2
  235. package/vendor/pi/docs/terminal-setup.md +3 -1
  236. package/vendor/pi/docs/tmux.md +6 -0
  237. package/vendor/pi/docs/tui.md +4 -0
  238. package/vendor/pi/docs/windows.md +27 -0
  239. package/vendor/pi/examples/extensions/README.md +2 -1
  240. package/vendor/pi/examples/extensions/custom-provider-anthropic/index.ts +27 -31
  241. package/vendor/pi/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  242. package/vendor/pi/examples/extensions/custom-provider-anthropic/package.json +1 -1
  243. package/vendor/pi/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  244. package/vendor/pi/examples/extensions/debug-provider.ts +2 -2
  245. package/vendor/pi/examples/extensions/gondolin/index.ts +4 -7
  246. package/vendor/pi/examples/extensions/gondolin/package-lock.json +19 -29
  247. package/vendor/pi/examples/extensions/gondolin/package.json +2 -2
  248. package/vendor/pi/examples/extensions/plan-mode/index.ts +23 -13
  249. package/vendor/pi/examples/extensions/plan-mode/utils.ts +42 -16
  250. package/vendor/pi/examples/extensions/preset.ts +2 -0
  251. package/vendor/pi/examples/extensions/reload-runtime.ts +17 -5
  252. package/vendor/pi/examples/extensions/subagent/README.md +14 -11
  253. package/vendor/pi/examples/extensions/subagent/index.ts +392 -171
  254. package/vendor/pi/examples/extensions/todo.ts +7 -0
  255. package/vendor/pi/examples/extensions/tools.ts +2 -0
  256. package/vendor/pi/examples/extensions/with-deps/package-lock.json +2 -2
  257. package/vendor/pi/examples/extensions/with-deps/package.json +1 -1
  258. package/vendor/pi/examples/tsconfig.json +208 -0
  259. package/vendor/pi/package.json +15 -16
  260. package/vendor/pi/schemas/models.schema.json +66 -37
  261. package/vendor/pi/schemas/settings.schema.json +18 -1
  262. package/vendor/pi-ai/bedrock.js +1 -1
  263. package/vendor/pi-ai/oauth-load.js +1 -1
  264. package/web/dist/assets/{board-math-css-BPXakv_3.js → board-math-css-DKX6FcUS.js} +1 -1
  265. package/web/dist/assets/index-D11wi0uG.js +540 -0
  266. package/web/dist/assets/index-JedYumhY.css +1 -0
  267. package/web/dist/assets/{index-WCm6wwmM.js → index-jl30Gy8P.js} +1 -1
  268. package/web/dist/assets/pdf-worker-DdZgk2mV.js +57 -0
  269. package/web/dist/assets/pdf.worker.min-Bz_KHX45.js +55 -0
  270. package/web/dist/index.html +2 -2
  271. package/web/dist/theme.css +22 -0
  272. package/dist/chunks/anthropic-messages-M3SMXACA.js +0 -8
  273. package/dist/chunks/api-GM53PHIL-GFHEXXE6.js +0 -4
  274. package/dist/chunks/azure-openai-responses-76YWXHSB.js +0 -4
  275. package/dist/chunks/bedrock-converse-stream-5UPX4NTQ.js +0 -58
  276. package/dist/chunks/child-runner-3GHOWGZP.js +0 -4
  277. package/dist/chunks/chunk-2ZNLUY2U.js +0 -128
  278. package/dist/chunks/chunk-3F6WW7HR.js +0 -13
  279. package/dist/chunks/chunk-3OKHUVEM.js +0 -7
  280. package/dist/chunks/chunk-3YHOCPQU.js +0 -10
  281. package/dist/chunks/chunk-4EX2JJWB.js +0 -4
  282. package/dist/chunks/chunk-4LLH5OWM.js +0 -10
  283. package/dist/chunks/chunk-52T37Y47.js +0 -8
  284. package/dist/chunks/chunk-7MU2AKNM.js +0 -4
  285. package/dist/chunks/chunk-AAA3UBIS.js +0 -4
  286. package/dist/chunks/chunk-ASYQHJVQ.js +0 -9
  287. package/dist/chunks/chunk-BKHDWCRT.js +0 -79
  288. package/dist/chunks/chunk-CQLH4UVX.js +0 -4
  289. package/dist/chunks/chunk-CVC66CFV.js +0 -33
  290. package/dist/chunks/chunk-D6UA4BZC.js +0 -19
  291. package/dist/chunks/chunk-DGMNI4AO.js +0 -4
  292. package/dist/chunks/chunk-DHSA5ACV.js +0 -125
  293. package/dist/chunks/chunk-DPQPXBTP.js +0 -68
  294. package/dist/chunks/chunk-DXBSQXJL.js +0 -18
  295. package/dist/chunks/chunk-E7ZMYIY6.js +0 -30
  296. package/dist/chunks/chunk-EQITBTJC.js +0 -10
  297. package/dist/chunks/chunk-EXJA5RIX.js +0 -357
  298. package/dist/chunks/chunk-FF7UELTU.js +0 -4
  299. package/dist/chunks/chunk-FH74NME3.js +0 -115
  300. package/dist/chunks/chunk-FOQ7VLIL.js +0 -17
  301. package/dist/chunks/chunk-FX6MOGLR.js +0 -11
  302. package/dist/chunks/chunk-G2V65UBA.js +0 -4
  303. package/dist/chunks/chunk-HGPBHTVD.js +0 -6
  304. package/dist/chunks/chunk-J5DVLUKY.js +0 -6
  305. package/dist/chunks/chunk-JW2HFMTF.js +0 -4
  306. package/dist/chunks/chunk-KDYEGGMW.js +0 -4
  307. package/dist/chunks/chunk-KIGMAATV.js +0 -23
  308. package/dist/chunks/chunk-KIU5FAPY.js +0 -5
  309. package/dist/chunks/chunk-KIWMQPH7.js +0 -739
  310. package/dist/chunks/chunk-L6VCIGWS.js +0 -11
  311. package/dist/chunks/chunk-LACGULCN.js +0 -10
  312. package/dist/chunks/chunk-LMSQZ6TQ.js +0 -4
  313. package/dist/chunks/chunk-MEPASGPP.js +0 -6
  314. package/dist/chunks/chunk-MFAEUHMV.js +0 -28
  315. package/dist/chunks/chunk-NAA7GF6Q.js +0 -5
  316. package/dist/chunks/chunk-NKDMKRSB.js +0 -68
  317. package/dist/chunks/chunk-NKXV32S6.js +0 -4
  318. package/dist/chunks/chunk-NVX5IPRN.js +0 -4
  319. package/dist/chunks/chunk-O3JW2F7D.js +0 -8
  320. package/dist/chunks/chunk-OE4KH3NJ.js +0 -4
  321. package/dist/chunks/chunk-OISO5JXB.js +0 -4
  322. package/dist/chunks/chunk-OPYXNSMY.js +0 -4
  323. package/dist/chunks/chunk-OSEIQ7SS.js +0 -4
  324. package/dist/chunks/chunk-P52RMIYX.js +0 -6
  325. package/dist/chunks/chunk-PBJ5MPPX.js +0 -60
  326. package/dist/chunks/chunk-PZMGBKUR.js +0 -13
  327. package/dist/chunks/chunk-PZMXHA6X.js +0 -9
  328. package/dist/chunks/chunk-Q7CE3UIE.js +0 -133
  329. package/dist/chunks/chunk-QBKCAIJG.js +0 -4
  330. package/dist/chunks/chunk-QEOFEETJ.js +0 -4
  331. package/dist/chunks/chunk-QUUEQRIT.js +0 -4
  332. package/dist/chunks/chunk-RA6HKFBV.js +0 -4
  333. package/dist/chunks/chunk-REPYBMQS.js +0 -4
  334. package/dist/chunks/chunk-SKHLZ6XY.js +0 -9
  335. package/dist/chunks/chunk-TAWLERZA.js +0 -4
  336. package/dist/chunks/chunk-TWAEABGG.js +0 -52
  337. package/dist/chunks/chunk-TZFLHVOQ.js +0 -7
  338. package/dist/chunks/chunk-UD3NMUHR.js +0 -12
  339. package/dist/chunks/chunk-UNVEZI57.js +0 -4
  340. package/dist/chunks/chunk-VQUPKMDR.js +0 -4
  341. package/dist/chunks/chunk-W25TB3PU.js +0 -4
  342. package/dist/chunks/chunk-W5LGYSPZ.js +0 -4
  343. package/dist/chunks/chunk-WEZWKMYU.js +0 -4
  344. package/dist/chunks/chunk-XAJLZR7C.js +0 -28
  345. package/dist/chunks/chunk-XH6FMP3N.js +0 -71
  346. package/dist/chunks/chunk-XSRZHN63.js +0 -4
  347. package/dist/chunks/chunk-Y3GFB5XM.js +0 -8
  348. package/dist/chunks/chunk-YG7OEPR2.js +0 -6
  349. package/dist/chunks/chunk-YHIWOGVL.js +0 -4
  350. package/dist/chunks/chunk-YKKEI5GI.js +0 -4
  351. package/dist/chunks/chunk-YZSHTWNM.js +0 -92
  352. package/dist/chunks/chunk-Z4H3VDHI.js +0 -4
  353. package/dist/chunks/cli-5DBTRMHU.js +0 -53
  354. package/dist/chunks/client-XOGYH5UR.js +0 -4
  355. package/dist/chunks/cloudflare-workers-ai-system-one-32JCFHI3.js +0 -4
  356. package/dist/chunks/config-DJSQI77S-335IXHSM.js +0 -4
  357. package/dist/chunks/context-VCQH5OB6.js +0 -4
  358. package/dist/chunks/cost-PGGFI7QJ.js +0 -5
  359. package/dist/chunks/dist-PUKMZ7GW.js +0 -4
  360. package/dist/chunks/easter-egg-3d-MO4MOEVF.js +0 -4
  361. package/dist/chunks/es5-VNTQPCKX.js +0 -4
  362. package/dist/chunks/file-7BN7RCAY.js +0 -4
  363. package/dist/chunks/gateway-UCRPMR75.js +0 -36
  364. package/dist/chunks/github-copilot-HAI2DA62.js +0 -4
  365. package/dist/chunks/google-generative-ai-2VXWLHWI.js +0 -4
  366. package/dist/chunks/google-vertex-UA36QP2U.js +0 -4
  367. package/dist/chunks/init-HA7FAQ73.js +0 -4
  368. package/dist/chunks/kimi-coding-HMJRKCPA.js +0 -4
  369. package/dist/chunks/local-client-stop-SQRU7ZZM.js +0 -4
  370. package/dist/chunks/meta-KY3LNFV2.js +0 -4
  371. package/dist/chunks/mistral-conversations-34F66L3O.js +0 -7
  372. package/dist/chunks/model-resolver-N3DTAQ2S.js +0 -4
  373. package/dist/chunks/openai-codex-responses-ZBVHREB3.js +0 -12
  374. package/dist/chunks/openai-completions-VVIB26SH.js +0 -9
  375. package/dist/chunks/openai-responses-735XA2ZX.js +0 -6
  376. package/dist/chunks/openrouter-images-3IKETHAC.js +0 -4
  377. package/dist/chunks/pi-messages-I3E4ZFHA.js +0 -10
  378. package/dist/chunks/radius-HXRZVBDB.js +0 -4
  379. package/dist/chunks/remote-ops-BALZYKH6.js +0 -14
  380. package/dist/chunks/runner-PLVZDGHB.js +0 -4
  381. package/dist/chunks/runtime-6YLTA2ZD.js +0 -4
  382. package/dist/chunks/schedule-cli-OLASBBYJ.js +0 -4
  383. package/dist/chunks/slack-WAGSPZUX.js +0 -4
  384. package/dist/chunks/start-ui-http-QALT7C3P.js +0 -43
  385. package/dist/chunks/subagent-E3UC7ZHC.js +0 -4
  386. package/dist/chunks/tool-shims-Q6P6UXVC.js +0 -4
  387. package/dist/chunks/typesafe-system-one-6ULACYD4.js +0 -4
  388. package/dist/chunks/ui-board-4GYW6KKW.js +0 -5
  389. package/dist/chunks/ui-decision-U2FXSEC2.js +0 -4
  390. package/dist/chunks/ui-view-O7PLANT7.js +0 -4
  391. package/dist/chunks/virtual-modules-IDC5YKZJ.js +0 -4
  392. package/dist/chunks/waitpoint-2FGQBIAC.js +0 -5
  393. package/dist/chunks/workers-XN4PSTH6.js +0 -4
  394. package/vendor/aistatus/gateway-cli.js +0 -21
  395. package/vendor/pi/examples/extensions/sandbox/index.ts +0 -321
  396. package/vendor/pi/examples/extensions/sandbox/package-lock.json +0 -92
  397. package/vendor/pi/examples/extensions/sandbox/package.json +0 -19
  398. package/web/dist/assets/index-BHZpFXhc.js +0 -525
  399. package/web/dist/assets/index-DqWMdMkh.css +0 -1
  400. package/web/dist/assets/pdf-worker-Hp15W1QJ.js +0 -57
  401. package/web/dist/assets/pdf.worker.min-DnhTvCwe.js +0 -55
@@ -1,79 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{g as Ts,h as ws}from"./chunk-TJ4GQRT6.js";import{a as We,b as ye,c as cs,d as ds,e as ps,f as fs,g as ms,h as hs,l as Ss,m as _s,t as bs}from"./chunk-DHSA5ACV.js";import{C as ks,b as gr,d as Fe,e as Gt,h as qr,i as es,j as ts,k as ns,q as rs,r as Ke,s as ls,u as gs,x as ys}from"./chunk-KIU5FAPY.js";import{e as _r,f as wr,h as xr}from"./chunk-4U7XXM4W.js";import{a as Ft,b as Wt}from"./chunk-LMDWRRX4.js";import{d as ze}from"./chunk-NVX5IPRN.js";import{h as Hr,i as Gr,j as Ht}from"./chunk-CQLH4UVX.js";import{a as Cr,b as Pr,c as Ar,d as $e,e as Rr,f as Or,g as Mr,h as Lr,i as Dr,j as jr,k as Ur,l as Nr,m as $r,n as Br,p as Yr,s as Rs,v as Os}from"./chunk-EQITBTJC.js";import{b as xs}from"./chunk-UD3NMUHR.js";import{h as O}from"./chunk-LEUENXI2.js";import{c as kr}from"./chunk-HALUQ7ZF.js";import{e as Xr,k as Qr}from"./chunk-3THJYAEF.js";import{b as br,c as Tr}from"./chunk-D3NXKK2L.js";import{a as Zr}from"./chunk-NKXV32S6.js";import{I as As,a as Kr,g as Ve,j as J,k as vs,l as j,m as M,n as U,o as zt,p as se,q as Je,r as X,s as Xe,t as Es,w as ie,y as Cs,z as Ps}from"./chunk-O3JW2F7D.js";import{X as Is,i as zr,k as Vr,r as Be}from"./chunk-TZFLHVOQ.js";import{a as os,b as as,e as us}from"./chunk-YG7OEPR2.js";import{a as He,b as Ge,c as is}from"./chunk-7MU2AKNM.js";import{b as Ue,e as ss}from"./chunk-LMSQZ6TQ.js";import{a as Su}from"./chunk-JERCOLY3.js";import{a as Kt}from"./chunk-DGMNI4AO.js";import{a as Fr,c as Wr}from"./chunk-5T7IX5KN.js";import{a as Jr}from"./chunk-BGVHA2D4.js";import{d as vr,e as Er,f as Ir}from"./chunk-OE4KH3NJ.js";import{a as ne}from"./chunk-LCKVYFMD.js";import{d as Ne}from"./chunk-3YHOCPQU.js";import{d as h}from"./chunk-MEPASGPP.js";import{J as d}from"./chunk-DPQPXBTP.js";import{a as De}from"./chunk-Q4UGYGU5.js";import{c as Bt,d as pr}from"./chunk-W5LGYSPZ.js";import{d as yr,e as b}from"./chunk-E7ZMYIY6.js";import{e as m}from"./chunk-NAA7GF6Q.js";import{c as Sr}from"./chunk-QWAQHHRS.js";import{f as I,g as fr,h as re,m as mr,n as je,s as hr,x as ge}from"./chunk-J5DVLUKY.js";import{d as yu,e as ku}from"./chunk-WHC7AYZD.js";import{randomUUID as Bg}from"node:crypto";var C;(function(t){t.MidTurnInject="mid-turn-inject",t.Usage="usage",t.BackgroundContinuation="background-continuation",t.Subagents="subagents"})(C||(C={}));var _u=[C.MidTurnInject,C.Subagents,C.BackgroundContinuation],bu=[C.MidTurnInject,C.Usage,C.Subagents],K={claude:new Set(_u),pi:new Set(bu)};import{createHash as Tu}from"crypto";function wu(){return h().streamDeltas}var xu={direct:[Rr],none:[Or]};function vu(t,e){let n=t.mcpConfigPaths?[...t.mcpConfigPaths]:[...xu[e]];t.supplementalMcpConfigPath&&e==="direct"&&n.push(t.supplementalMcpConfigPath);let r=Qe(t),s=t.mcpToolAllowlist??void 0;return Kr(n,s,void 0,r)}function Eu(t){let e=["-p","--input-format","stream-json","--output-format","stream-json","--verbose","--replay-user-messages"];return(t.streamDeltas??wu())&&e.push("--include-partial-messages"),h().showThinking&&e.push("--thinking-display","summarized"),e}function Qe(t){if((t.mcpComposition??"direct")==="none")return[];let n=["cortex-core","cortex-ext"];return t.isUserInitiated&&n.push("cortex-interaction-bridge"),t.teamLead&&n.push("cortex-workers"),t.teamWorker&&n.push("cortex-worker-report"),t.loadSlackMcp&&n.push("cortex-slack"),t.loadFeishuMcp&&n.push("cortex-feishu"),t.loadWebMcp&&n.push("cortex-web"),n}function Iu(t){if((t.mcpComposition??"direct")==="none")return[];let e=t.mcpToolAllowlist??void 0;return(e===void 0?Qe(t).includes("cortex-core"):vr.every(r=>e.includes(r)))?$r():[]}function Cu(t,e){let n=(t.tools||Dr).split(",").map(s=>s.trim()).filter(s=>s&&!Nr.has(s)&&!(e&&Ur.has(s))),r=[...e?jr:[],...Iu(t)];return[...new Set([...n,...r])].join(",")}function Pu(t,e,n,r){t.push("--dangerously-skip-permissions","--permission-mode","bypassPermissions","--mcp-config",...e),n==="none"&&t.push("--strict-mcp-config"),t.push("--tools",r)}function Au(t,e){for(let[n,r]of e)r&&t.push(n,r)}function Ru(t,e){Au(t,[["--system-prompt",e.systemPrompt],["--append-system-prompt",e.appendSystemPrompt],["--model",e.model],["--effort",e.thinking],["--agent",e.claudeAgent]])}function Ou(t,e,n){for(let r of n??[])t.push(e,r)}function Mu(t,e){e.disableSkills&&t.push("--disable-slash-commands"),e.settingSources&&t.push("--setting-sources",e.settingSources.join(","))}function Lu(t,e){let n={hooks:t.disableHooks?{}:Yr(e)};return t.outputStyle&&(n.outputStyle=t.outputStyle),t.omitGitContext&&(n.includeGitInstructions=!1),n}function Du(t,e){e.needsResume?t.push("--resume",e.sessionId):t.push("--session-id",e.sessionId)}function js(t){let e=t.mcpComposition??"direct",r=e==="direct"&&!!t.isUserInitiated,s=vu(t,e),i=Eu(t),o=Cu(t,r);return Pu(i,s,e,o),Ru(i,t),Ou(i,"--plugin-dir",t.pluginDirs),Mu(i,t),i.push("--settings",JSON.stringify(Lu(t,o))),Du(i,t),i}var ju=["CORTEX_PROFILE","CORTEX_PROJECT","CORTEX_SESSION_NAME","CORTEX_BACKEND","CORTEX_MODEL","CORTEX_PROVIDER","CORTEX_THINKING","CORTEX_MODE"];function ke(t,e,n){n&&(t[e]=n)}function Uu(t){t.MCP_TOOL_TIMEOUT=String(183e4),t.CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT=String(183e4),t.CLAUDE_CODE_DISABLE_AUTO_MEMORY="1",t.DISABLE_AUTOUPDATER="1",t.CLAUDE_CODE_DISABLE_OFFICIAL_MARKETPLACE_AUTOINSTALL="1",t.CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL="1",t.CLAUDE_CODE_AUTO_CONNECT_IDE="false",t.CLAUDE_CODE_DISABLE_POLICY_SKILLS="1",t.CLAUDE_CODE_DISABLE_TERMINAL_TITLE="1"}function Nu(t){if(process.platform!=="win32")return;let e=t.CLAUDE_CODE_GIT_BASH_PATH??t.CORTEX_GIT_BASH_PATH;e!==void 0&&(t.CLAUDE_CODE_GIT_BASH_PATH=e)}function $u(t,e){let n=e?t.CLAUDE_CODE_OAUTH_TOKEN:void 0;delete t.CLAUDECODE;for(let r of Object.keys(t)){let s=process.platform==="win32"&&r==="CLAUDE_CODE_GIT_BASH_PATH";r.startsWith("CLAUDE_CODE")&&!s&&delete t[r]}n&&(t.CLAUDE_CODE_OAUTH_TOKEN=n),Nu(t),Uu(t)}function Bu(t,e,n){n||(t.SLACK_CHANNEL=e,t.FEISHU_CHANNEL=e,t.SLACK_BOT_TOKEN=process.env.SLACK_BOT_TOKEN)}function Fu(t,e,n){for(let[r,s]of Object.entries(e??{}))t[r]=s;for(let r of n??[])delete t[r]}var Wu=["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN"];function Ku(t){return`sha256:${Tu("sha256").update(t).digest("hex").slice(0,8)}`}function Ls(t,e,n){return e.unsetEnv?.includes(t)?null:e.routeEnv?.[t]??n}function Ds(t,e){return t===null?"deleted":t===void 0?"inherited":e(t)}function Us(t){let e=Ds(Ls("ANTHROPIC_BASE_URL",t,t.anthropicBaseUrl||void 0),r=>`url:${r}`),n=Wu.map(r=>`${r}=${Ds(Ls(r,t),Ku)}`);return[e,...n].join(" ")}function Hu(t){return{CORTEX_BACKEND:"claude",CORTEX_MODEL:t?.selection?.model,CORTEX_PROVIDER:t?.selection?.provider,CORTEX_THINKING:t?.selection?.thinking,CORTEX_MODE:t?.selection?.mode,CORTEX_PROJECT:t?.project,CORTEX_EXECUTION_ID:t?.executionId}}function Gu(t,e){for(let n of ju)delete t[n];for(let[n,r]of Object.entries(Hu(e)))ke(t,n,r)}var zu=64,Vu=64;function Ju(t){t.CLAUDE_CONFIG_DIR=je;let e=h().maxContextTokens;e!==null&&(t.CLAUDE_CODE_AUTO_COMPACT_WINDOW=String(e))}function Vt(){let t={},e=Gr(Be.peekModels().slice(0,zu).map(r=>({provider:r.provider,id:r.model})));e.length>0&&(t.CORTEX_SUBAGENT_PI_MODELS=Ht(e));let n=Vr.get();if(n.length>0){let r=Hr(null,zr(n)).slice(0,Vu);t.CORTEX_SUBAGENT_CLAUDE_MODELS=Ht(r)}return t}function Xu(t){for(let[e,n]of Object.entries(Vt()))ke(t,e,n)}function Ns(t,e,n,r,s,i,o,a,u){let l=a?{...a}:{...process.env};return $u(l,!a),Bu(l,t,!!a),l.CORTEX_SESSION_ID=o?.trackSessionId??e,ke(l,"CORTEX_CALLBACK_SOURCE",n),ke(l,"CORTEX_SCHEDULE_TASK_ID",r),ke(l,"ANTHROPIC_BASE_URL",s),a||Ju(l),Xu(l),Fu(l,i,u),Gu(l,o),l}import{spawn as Hc}from"child_process";import{createInterface as Gc}from"readline";function my(){return h().bgContinuation}var Qu=9e4,Yu=18e5;function $s(t,e){let n=process.env[t];if(!n)return e;let r=Number(n);return Number.isFinite(r)&&r>0?r*1e3:e}function Bs(){return $s("CORTEX_BG_GRACE_S",Qu)}function Fs(){return $s("CORTEX_BG_WAIT_MAX_S",Yu)}function Se(t){return t?(t.pendingBackgroundTasks??0)+(t.undeliveredBackgroundTasks??0):0}var Zu={set(t,e){let n=setTimeout(t,e);return n.unref?.(),n},clear(t){clearTimeout(t)}};function Jt(t,e){let n=t.total_cost_usd==null&&e.total_cost_usd==null,r=t.num_turns==null&&e.num_turns==null;return{...t,total_cost_usd:n?null:(t.total_cost_usd??0)+(e.total_cost_usd??0),num_turns:r?null:(t.num_turns??0)+(e.num_turns??0),finalOutput:e.finalOutput||t.finalOutput,rateLimited:t.rateLimited||e.rateLimited,rateLimitMessage:e.rateLimitMessage??t.rateLimitMessage,pendingBackgroundTasks:e.pendingBackgroundTasks??0,undeliveredBackgroundTasks:e.undeliveredBackgroundTasks??0}}function qu(t){let e=t.reportedAccounting;return t.total_cost_usd==null&&e?.usageReported!==!0?null:{type:"cost_record",provider:"anthropic",model:e?.model??"unknown",tokens_in:e?.promptTokens??null,tokens_out:e?.outputTokens??null,prompt_tokens:e?.promptTokens??null,cached_tokens:e?.cachedTokens??null,input_tokens:e?.inputTokens??null,output_tokens:e?.outputTokens??null,cache_read_tokens:e?.cacheReadTokens??null,cache_creation_tokens:e?.cacheCreationTokens??null,provider_requests:Number.isSafeInteger(t.num_turns)&&Number(t.num_turns)>0?t.num_turns:null,cost_usd:t.total_cost_usd}}var oe=class{mode;port;timers;graceMs;maxWaitMs;acc=null;outstandingInjections=0;queued=[];started=!1;settled=!1;closed=!1;backgroundTurnOpen=!1;handle=null;waitExpired=!1;handedOff=!1;constructor(e,n){this.mode=e,this.port=n,this.timers=n.timers??Zu,this.graceMs=n.graceMs??Bs(),this.maxWaitMs=n.maxWaitMs??Fs()}sink(){return{...el(n=>this.ingest(n)),onTurnOpen:n=>this.onTurnOpen(n),onResult:n=>this.onResult(n)}}start(e){if(this.started)return;this.started=!0,this.acc=e;let n=this.queued.splice(0);if(this.mode==="none"||this.handedOff||!this.owesWork(e)){this.finish();for(let r of n)this.onResult(r);return}this.port.settleForeground(this.acc),this.enterBackground(),this.arm(Math.max(e.pendingBackgroundTasks??0,this.outstandingInjections),e.undeliveredBackgroundTasks??0);for(let r of n)this.onResult(r)}handOff(){this.handedOff=!0,this.started&&this.finish()}owesWork(e){return Se(e)>0||this.outstandingInjections>0}noteInjectionAccepted(){this.outstandingInjections+=1}onTurnOpen(e){this.settled||!this.started||(this.backgroundTurnOpen=!0,this.outstandingInjections=0,this.pause(),this.enterBackground(),e&&this.port.push({type:"background_wake",summaries:e.summaries,phase:"background"}))}enterBackground(){this.acc&&this.port.push({type:"phase",phase:"background",pendingBackground:this.acc.pendingBackgroundTasks??0,undeliveredBackground:this.acc.undeliveredBackgroundTasks??0})}ingest(e){if(!this.settled){if(e.type==="injection_rejected"||e.type==="injection_delivered"&&e.foldedIntoTurn){this.outstandingInjections>0&&(this.outstandingInjections-=1),this.port.push(e),this.started&&this.outstandingInjections===0&&Se(this.acc)===0&&this.backgroundTurnOpen===!1&&this.finish();return}e.type==="phase"&&e.phase==="background"&&(this.backgroundTurnOpen=!0),this.port.push(e)}}onResult(e){if(!this.started){this.queued.push(e);return}if(this.settled)return;if(e.backgroundInterrupted){this.port.push({type:"background_result",result:e}),this.acc={...this.acc,backgroundInterrupted:!0},this.finish();return}let n=qu(e);if(n&&this.port.push(n),this.port.push({type:"background_result",result:e}),this.acc=Jt(this.acc,e),this.backgroundTurnOpen=!1,this.acc.rateLimited){this.finish();return}let r=e.pendingBackgroundTasks??0,s=e.undeliveredBackgroundTasks??0;r+s>0||this.outstandingInjections>0?this.arm(Math.max(r,this.outstandingInjections),s):this.finish()}arm(e,n){if(this.clearTimer(),!(this.settled||this.waitExpired)){if(e>0){this.handle=this.timers.set(()=>this.onTimeout("max-wait"),this.maxWaitMs);return}n>0&&(this.handle=this.timers.set(()=>this.onTimeout("grace"),this.graceMs))}}pause(){this.settled||this.handle===null||this.clearTimer()}clearTimer(){this.handle!==null&&(this.timers.clear(this.handle),this.handle=null)}onTimeout(e){this.settled||(this.handle=null,this.waitExpired=!0,this.port.push({type:"background_timeout",reason:e}),!this.settled&&e==="grace"&&this.finish())}finish(){this.settled||(this.settled=!0,this.clearTimer(),this.acc&&this.port.settleRun(this.acc),this.close())}close(){this.closed||(this.closed=!0,this.port.push({type:"phase",phase:"done",pendingBackground:0,undeliveredBackground:0}),this.port.close())}};function el(t){return{onAssistantText:(e,n,r)=>{t({type:"assistant_text",text:e,phase:"background",...n!==void 0?{model:n}:{},...r!==void 0?{subagent:r}:{}})},onAssistantThinking:(e,n)=>t({type:"assistant_thinking",text:e,phase:"background",...n?{blockId:n}:{}}),onToolUse:(e,n,r,s)=>{t({type:"tool_use",toolUseId:r??"",name:e,input:n,phase:"background",...s!==void 0?{subagent:s}:{}})},onToolResult:(e,n,r,s,i)=>{t({type:"tool_result",toolUseId:e,ok:!r,content:n,phase:"background",...s!==void 0?{subagent:s}:{},...i?.length?{images:i}:{}})},onContextUsage:e=>t({type:"context_usage",...e,phase:"background"}),onSubagentEnd:(e,n)=>{t({type:"subagent_end",parentToolUseId:e,status:n,phase:"background"})}}}function tl(t,e){let n=t.findIndex(r=>r.text===e);if(n!==-1)return t.splice(n,1)[0]}var ae=class{session;idPrefix;active=null;seq=0;constructor(e,n){this.session=e,this.idPrefix=n}beginRun(e){this.active?.phase?.handOff();let n={queue:e,pending:[],phase:null};return this.active=n,this.session.setInjectionAckSink(this.ackSink(n)),{attachPhase:r=>{n.phase=r}}}steer(e,n){let r=n??this.nextId(),s=this.session.injectUserMessage(e);return s&&this.active?.phase?.noteInjectionAccepted(),s?(this.active?.pending.push({id:r,text:e.text}),{accepted:!0,injectionId:r}):(this.active?.queue.push({type:"injection_rejected",injectionId:r,reason:"refused"}),{accepted:!1,injectionId:r})}pushOutOfBand(e){let n=this.active?.queue;return n?(n.push(e),!0):!1}ackSink(e){let n=r=>{e.phase?e.phase.ingest(r):e.queue.push(r)};return{onDelivered:({text:r,foldedIntoTurn:s,position:i})=>n({type:"injection_delivered",injectionId:this.ackedId(e,r),foldedIntoTurn:s,...i?{position:i}:{}}),onUndelivered:({text:r})=>n({type:"injection_rejected",injectionId:this.ackedId(e,r),reason:"undelivered"})}}ackedId(e,n){return tl(e.pending,n)?.id??this.nextId()}nextId(){return`${this.idPrefix}-${++this.seq}`}};function ue(){let t,e;return{promise:new Promise((r,s)=>{t=r,e=s}),resolve:t,reject:e}}function nl(t){throw new Error(`Unhandled NormalizedEvent: ${JSON.stringify(t)}`)}function Ws(t){return{sessionId:null,total_cost_usd:t.totalCostUsd,num_turns:t.numTurns,rateLimited:!1,rateLimitMessage:null,planFilePath:null,enteredPlanMode:!1,exitedPlanMode:!1,finalOutput:null}}function _e(t,e){switch(t.type){case"session_started":return{type:"engine_started",backendSessionId:t.sessionId,...t.sessionFile!==void 0?{sessionFile:t.sessionFile}:{}};case"assistant_text":return{...t,phase:e};case"assistant_thinking":case"assistant_thinking_delta":case"assistant_delta":return{...t,phase:e};case"tool_use":return{...t,phase:e};case"tool_result":return{...t,phase:e};case"todo_update":return{...t,phase:e};case"ask_user_question":return{type:"dialog_request",dialogId:t.toolUseId,kind:"ask_user",payload:t.questions};case"plan_written":return{...t,phase:e};case"context_compacted":return{...t,phase:e};case"model_fallback":return{...t,phase:e};case"context_usage":return{...t,phase:e};case"rate_limit":return{type:"rate_limit",raw:t.raw};case"cost_record":return{...t};case"turn_progress":return{...t};case"turn_complete":return e==="background"?{type:"background_result",result:Ws(t)}:{type:"foreground_result",result:Ws(t)};case"subagent_activity":return{...t,phase:e};case"subagent_end":return{...t,phase:e};case"error":return{...t};default:return nl(t)}}var le=class{pending=[];waiters=[];closed=!1;push(e){if(this.closed)return;let n=this.waiters.shift();n?n({value:e,done:!1}):this.pending.push(e)}next(){let e=this.pending.shift();return e?Promise.resolve({value:e,done:!1}):this.closed?Promise.resolve({value:void 0,done:!0}):new Promise(n=>this.waiters.push(n))}close(){if(!this.closed){this.closed=!0;for(let e of this.waiters.splice(0))e({value:void 0,done:!0})}}};function ce(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}function Ks(t){let e=t.map(ce);if(e.some(r=>r===null))return null;let n=e.reduce((r,s)=>r+s,0);return Number.isSafeInteger(n)?n:null}function Xt(t){return{promptTokens:Ks([t?.input,t?.cacheCreation,t?.cacheRead]),cachedTokens:Ks([t?.cacheRead])}}function Hs(t){return{onAssistantMessage:(e,n,r,s)=>t({type:"assistant_text",text:e,...n?{blockId:n}:{},...r!=null?{model:r}:{},...s?{subagent:s}:{}}),onAssistantDelta:(e,n)=>t({type:"assistant_delta",text:e,blockId:n}),onAssistantThinking:(e,n)=>t({type:"assistant_thinking",text:e,...n?{blockId:n}:{}}),onAssistantThinkingDelta:(e,n)=>t({type:"assistant_thinking_delta",text:e,blockId:n}),onToolUse:(e,n,r,s)=>{if(t({type:"tool_use",toolUseId:r,name:e,input:n,...s?{subagent:s}:{}}),s)return;let i=gr("claude",e,n);i&&t({type:"todo_update",toolUseId:r,snapshot:i})},onToolResult:(e,n,r,s,i)=>t({type:"tool_result",toolUseId:e,content:n,ok:!r,...s?{subagent:s}:{},...i?.length?{images:i}:{}}),onCompact:e=>t({type:"context_compacted",trigger:e.trigger,preTokens:e.preTokens}),onModelFallback:e=>t({type:"model_fallback",...e}),onContextUsage:e=>t({type:"context_usage",...e}),onProgress:e=>{t({type:"turn_progress",numTurns:e?.num_turns??0})},onSubagentActivity:(e,n,r)=>t({type:"subagent_activity",parentToolUseId:e,subagentType:n,kind:r}),onSubagentEnd:(e,n)=>t({type:"subagent_end",parentToolUseId:e,status:n})}}function Gs(t,e,n){e.planFilePath&&t({type:"plan_written",toolUseId:"",path:e.planFilePath,content:""}),e.rateLimited&&t({type:"rate_limit",raw:{message:e.rateLimitMessage}});let r=e.reportedAccounting;if(e.total_cost_usd!=null||n.lastTokenUsage!==null){let s=n.lastTokenUsage,i=Xt(s);t({type:"cost_record",provider:"anthropic",model:n.lastModelName||n.modelName||"unknown",tokens_in:i.promptTokens,tokens_out:s?.output??0,prompt_tokens:i.promptTokens,cached_tokens:i.cachedTokens,input_tokens:r?.inputTokens??null,output_tokens:r?.outputTokens??null,cache_read_tokens:r?.cacheReadTokens??null,cache_creation_tokens:r?.cacheCreationTokens??null,provider_requests:Number.isSafeInteger(e.num_turns)&&Number(e.num_turns)>0?e.num_turns:null,cost_usd:e.total_cost_usd??null})}t({type:"turn_complete",numTurns:e.num_turns??0,totalCostUsd:e.total_cost_usd??null})}var Ye=class{backend="claude";identity;session;spec;injections;started=!1;constructor(e,n,r){this.session=e,this.spec=n,this.identity=r,this.injections=new ae(e,"claude-run-inj")}get backendSessionId(){return this.session.sessionId}run(e,n){let r=new le,s=this.injections.beginRun(r);this.started||(r.push(_e({type:"session_started",sessionId:this.session.sessionId},"foreground")),this.started=!0);let i=ue(),o=ue(),a=new oe(n.awaitBackground,{push:l=>r.push(l),settleForeground:l=>i.resolve(l),settleRun:l=>{o.resolve(l),i.resolve(l)},close:()=>r.close()});s.attachPhase(a),this.session.setBackgroundTurnSink(a.sink());let u=l=>{n.onNormalizedEvent?.(l),l.type!=="turn_complete"&&r.push(_e(l,"foreground"))};return this.driveRun(e,u,r,a,i),i.promise.catch(l=>o.reject(l)),i.promise.catch(()=>{}),o.promise.catch(()=>{}),{events:{[Symbol.asyncIterator]:()=>({next:()=>r.next()})},result:i.promise,settled:o.promise,cancel:()=>r.close()}}async driveRun(e,n,r,s,i){let o;try{o=await this.session.sendMessage(e.text,{attachments:e.attachments,...Hs(n)}),Gs(n,o,this.session)}catch(a){a?.cancelled||n({type:"error",message:String(a?.message??a),fatal:!0}),r.push({type:"phase",phase:"done",pendingBackground:0,undeliveredBackground:0}),r.close(),i.reject(a);return}r.push({type:"foreground_result",result:o}),s.start(o)}steer(e,n){return this.injections.steer(e,n)}ingestExternal(e){return this.injections.pushOutOfBand(e)}respondToDialog(e,n){return!1}compact(){return this.session.compact()}async close(){this.session.close()}kill(){return this.session.kill()}isAlive(){return this.session.isAlive()}};import*as Zs from"crypto";import{createHash as rl}from"node:crypto";import $ from"node:fs";import Te from"node:path";import{fileURLToPath as sl}from"node:url";import de from"node:fs";import N from"node:path";function zs(t,e){let n=N.resolve(t);for(;;){if(de.existsSync(n)&&de.lstatSync(n).isSymbolicLink())throw new Error(`${e} has a symlink ancestor: ${n}`);let r=N.dirname(n);if(r===n)return;n=r}}function v(t,e){let n=N.resolve(t);if(zs(n,e),de.mkdirSync(n,{recursive:!0,mode:448}),zs(n,e),de.realpathSync(n)!==n)throw new Error(`${e} is not a physical path: ${n}`);de.chmodSync(n,448)}function be(t,e){let n=N.resolve(t),r=N.resolve(e),s=N.relative(n,r);if(s===".."||s.startsWith(`..${N.sep}`)||N.isAbsolute(s))return r;try{return N.join(de.realpathSync(n),s)}catch{return r}}var il=m("claude-mcp-config"),ol=sl(new URL("./remote-mcp-proxy.js",new URL("dist/agent-adapter/claude/mcp-config.js",__cortexPackageRoot).href));function Js(t,e){return t<e?-1:t>e?1:0}function Qt(t){return Object.fromEntries(t.sort(([e],[n])=>Js(e,n)))}function al(t){return{command:t.command,args:[...t.args],env:Qt(Object.entries(t.env)),cwd:t.cwd}}function ul(t){return{type:t.type==="streamable-http"?"http":"sse",url:t.url,headers:Qt(Object.entries(t.headers))}}function ll(t){return t.type==="stdio"?al(t):ul(t)}function cl(t){let e=t.map(n=>[n.name,ll(n)]).sort(([n],[r])=>Js(n,r));return`${JSON.stringify({mcpServers:Object.fromEntries(e)},null,2)}
5
- `}function Ze(t){return rl("sha256").update(t,"utf8").digest("hex")}function dl(t){return(t&63)===0}function Xs(t){let e=$.lstatSync(t);if(!e.isFile()||e.isSymbolicLink())throw new Error(`Claude supplemental MCP file is invalid: ${t}`);if(!dl(e.mode&511))throw new Error(`Claude supplemental MCP file is not private: ${t}`);return $.readFileSync(t,"utf8")}function Yt(t,e){if(Te.basename(t)!==`${e}.json`)throw new Error(`Claude supplemental MCP file identity mismatch: ${t}`);if(Ze(Xs(t))!==e)throw new Error(`Claude supplemental MCP file identity mismatch: ${t}`)}function Vs(t,e){if(Xs(t)!==e)throw new Error(`Claude supplemental MCP file content mismatch: ${t}`);Yt(t,Ze(e))}function pl(t,e){let n=`${t}.tmp.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2,8)}`;$.writeFileSync(n,e,{encoding:"utf8",mode:384}),$.chmodSync(n,384),$.renameSync(n,t),$.chmodSync(t,384)}function fl(t){try{let e=new Date;$.utimesSync(t,e,e)}catch{}}function Qs(t,e,n){v(t,n);let r=Te.join(t,`${Ze(e)}.json`);if($.existsSync(r))return Vs(r,e),fl(r),r;try{pl(r,e)}catch(s){if(!$.existsSync(r))throw s;Vs(r,e)}return r}function ml(t,e){let n=Te.join(e,"claude-mcp-proxies"),r=`${JSON.stringify({type:t.type,url:t.url,headers:Qt(Object.entries(t.headers))})}
6
- `,s=Qs(n,r,"Claude remote MCP runtime");return{name:t.name,type:"stdio",command:process.execPath,args:[ol,s],env:{},cwd:n}}function hl(t,e){return t.flatMap(n=>{if(n.type==="stdio")return[n];try{return[ml(n,e)]}catch(r){return il.warn(`Skipping Claude remote MCP '${n.name}': ${r.message}`),[]}})}function Ys(t,e={}){let n=be(I,e.runtimeDir??Te.join(I,"data","plugin-runtime"));v(n,"Claude MCP runtime");let r=cl(hl(t,n)),s=Ze(r),i=Te.join(n,"claude-mcp");return{path:Qs(i,r,"Claude MCP runtime"),identity:s}}function gl(t){return{tools:t.tools||null,systemPrompt:t.systemPrompt||null,appendSystemPrompt:t.appendSystemPrompt??null,model:t.model||null,claudeAgent:t.claudeAgent||null,pluginDirs:t.pluginDirs||null,outputStyle:t.outputStyle||null,thinking:t.thinking??null}}function yl(t){return{mcpComposition:t.mcpComposition,mcpConfigPaths:t.mcpConfigPaths,mcpToolAllowlist:t.mcpToolAllowlist,supplementalMcpConfigPath:t.supplementalMcpConfigPath??null,disableHooks:t.disableHooks===!0,disableSkills:t.disableSkills===!0,settingSources:t.settingSources,...t.omitGitContext?{omitGitContext:!0}:{},streamDeltas:t.streamDeltas,isUserInitiated:t.isUserInitiated===!0,teamLead:t.teamLead===!0,teamWorker:t.teamWorker===!0}}function kl(t){let{channel:e,options:n}=t;return{...gl(n),...yl(n),needsResume:t.needsResume,sessionId:t.sessionId,loadSlackMcp:e.startsWith("slack:"),loadFeishuMcp:e.startsWith("feishu:"),loadWebMcp:e.startsWith("web:")}}function qs(t){let e=kl(t),{options:n}=t,r=Ns(t.channel,t.sessionId,n.callbackSource||null,n.scheduleTaskId||null,n.anthropicBaseUrl,n.routeEnv,n.context,n.pinnedEnv,n.unsetEnv);return r[Fr]=Wr(Qe(e)),{args:js(e),env:r}}function Sl(t){if(!t||t.length===0)return null;let e=t.map(n=>Ue("claude",n)).filter(n=>typeof n=="string");return e.length?e.join(","):null}function _l(t,e){return!t.mcp.servers||e!=="direct"?null:Ys(t.mcp.servers)}function bl(t){let e=t.backend.kind==="claude"?t.backend:void 0;return{model:t.model.id??null,systemPrompt:t.prompt.system??null,appendSystemPrompt:t.prompt.append??null,outputStyle:e?.outputStyle??null,tools:t.tools.rawClaude??Sl(t.tools.canonical),pluginDirs:t.plugins.dirs??null,isUserInitiated:!!t.flags.isUserInitiated,teamLead:t.flags.teamLead===!0,teamWorker:t.flags.teamWorker===!0,callbackSource:t.context.callbackSource??null,scheduleTaskId:t.context.scheduleTaskId??null,claudeAgent:e?.claudeAgent??null,thinking:t.model.thinking??null}}function Tl(t,e){let n=_l(t,e);return{anthropicBaseUrl:t.route.anthropicBaseUrl,routeEnv:t.env.sets,unsetEnv:t.env.unsets,cwd:re(t.cwd),mcpComposition:e,mcpConfigPaths:t.mcp.configPaths,mcpToolAllowlist:t.mcp.allowlist,supplementalMcpConfigPath:n?.path??null,supplementalMcpConfigIdentity:n?.identity??null,pluginCapabilityFingerprint:t.plugins.fingerprint??null,disableHooks:t.flags.disableHooks,disableSkills:t.flags.disableSkills,settingSources:t.flags.settingSources,...t.flags.clean?{omitGitContext:!0}:{},streamDeltas:t.flags.streamDeltas,captureTranscriptLogs:t.flags.captureTranscripts,processSpawner:t.process.spawner,cliPath:t.process.cliPath,pinnedEnv:t.env.pinned,context:t.env.context}}function Zt(t){let e=Fe(t.mcp.composition);return{...bl(t),...Tl(t,e)}}function qt(t){let e=t.context.channel??t.env.sets?.SLACK_CHANNEL??t.engineKey;return{channel:e,sessionKey:t.engineKey||e,sessionId:t.resume.backendSessionId||Zs.randomUUID(),needsResume:t.resume.resume,options:Zt(t)}}import{closeSync as wl,existsSync as xl,fstatSync as vl,openSync as El,readSync as Il}from"node:fs";import*as ti from"path";function en(t,e){let n=t.replace(/[/.]/g,"-");return ti.join(Ar,n,`${e}.jsonl`)}function ni(t,e,n=xl){return t&&n(e)}var ei=Buffer.from('"cost-state"'),Cl=1<<20;function Pl(t,e){let n;try{n=JSON.parse(t)}catch{return null}let r=n.totalCostUSD;return n.type!=="cost-state"||n.sessionId!==e?null:typeof r=="number"&&Number.isFinite(r)&&r>=0?r:null}function Al(t,e){let n=t.lastIndexOf(ei);for(;n!==-1;){let r=t.lastIndexOf(10,n)+1,s=t.indexOf(10,n),i=Pl(t.toString("utf8",r,s===-1?t.length:s),e);if(i!==null)return i;if(r===0)return null;n=t.lastIndexOf(ei,r-1)}return null}function ri(t,e,n=Cl){let r;try{r=El(t,"r")}catch{return 0}try{let s=vl(r).size,i=Buffer.alloc(0);for(;s>0;){let o=Math.max(0,s-n),a=Buffer.alloc(s-o);Il(r,a,0,a.length,o);let u=i.length?Buffer.concat([a,i]):a,l=o===0?-1:u.indexOf(10);if(o>0&&l===-1){i=u,s=o;continue}let p=Al(u.subarray(l+1),e);if(p!==null)return p;i=u.subarray(0,Math.max(l,0)),s=o}return 0}catch{return 0}finally{wl(r)}}import*as P from"node:fs";import*as ai from"node:path";import{isUtf8 as Nl}from"node:buffer";import{closeSync as Rl,fstatSync as Ol,openSync as Ml,readSync as Ll}from"node:fs";var Dl=512*1024,si=new Map;function Xy(t,e=Date.now()){si.set(t,e)}function jl(t){let e=t.split(`
7
- `);for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.includes('"timestamp"'))try{let s=JSON.parse(r);if(typeof s.timestamp!="string"||s.message?.model==="<synthetic>")continue;let i=Date.parse(s.timestamp);if(Number.isFinite(i))return i}catch{continue}}return null}function Ul(t){let e;try{e=Ml(t,"r")}catch{return null}try{let n=Ol(e),r=Math.max(0,n.size-Dl),s=Buffer.alloc(n.size-r);Ll(e,s,0,s.length,r);let i=s.toString("utf8");return r>0&&(i=i.slice(i.indexOf(`
8
- `)+1)),jl(i)??n.mtimeMs}catch{return null}finally{Rl(e)}}function ii(t,e){let n=Ul(t),r=si.get(e)??null;return n===null?r:r===null?n:Math.max(n,r)}var ui=m("claude-bridge"),li="[Old tool result content cleared]",$l=10,Bl=65*6e4,Fl=1e5,Wl=4e4,oi=Buffer.from('"compact_boundary"'),Kl={readFileSync:t=>P.readFileSync(t),statSync:t=>P.statSync(t),writeFileSync:(t,e,n)=>P.writeFileSync(t,e,{mode:n}),appendFileSync:(t,e)=>P.appendFileSync(t,e),renameSync:(t,e)=>P.renameSync(t,e),unlinkSync:t=>P.unlinkSync(t)};function nn(t){try{let e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function ci(t){if(!t.includes('"compact_boundary"'))return!1;let e=nn(t);return e?.type==="system"&&e.subtype==="compact_boundary"}function di(t){for(let e=t.length-1;e>=0;e--)if(ci(t[e]))return e+1;return 0}function pi(t){let e=t?.message;return e!==null&&typeof e=="object"?e:null}function Hl(t){if(t?.type!=="user"||t.isSidechain===!0)return[];let e=pi(t)?.content;return Array.isArray(e)?e.filter(n=>n!==null&&typeof n=="object"&&n.type==="tool_result"):[]}function Gl(t,e){let n=[];for(let r=e;r<t.length;r++){if(!t[r].includes('"tool_result"'))continue;let s=nn(t[r]);for(let i of Hl(s))n.push({line:r,record:s,block:i})}return n}var zl=JSON.stringify(li).length;function Vl(t){let e=JSON.stringify(t.content??"").length-zl;return e<=0?0:(t.content=li,e)}function Jl(t,e=$l){let n=Gl(t,di(t)),r=new Map,s=0,i=0;for(let a of n.slice(0,Math.max(0,n.length-e))){let u=Vl(a.block);u!==0&&(r.set(a.line,a.record),s++,i+=u)}return{lines:t.map((a,u)=>r.has(u)?JSON.stringify(r.get(u)):a),clearedCount:s,charsRemoved:i}}function tn(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}function Xl(t){if(t?.type!=="assistant"||t.isSidechain===!0)return null;let e=pi(t)?.usage;if(e===null||typeof e!="object")return null;let n=tn(e.input_tokens)+tn(e.cache_read_input_tokens)+tn(e.cache_creation_input_tokens);return n>0?n:null}function Ql(t){let e=di(t);for(let n=t.length-1;n>=e;n--){if(!t[n].includes('"usage"'))continue;let r=Xl(nn(t[n]));if(r!==null)return r}return null}function Yl(t){let e=t.lastIndexOf(oi);for(;e!==-1;){let n=t.lastIndexOf(10,e)+1,r=t.indexOf(10,e);if(ci(t.toString("utf8",n,r===-1?t.length:r)))return n;if(n===0)return 0;e=t.lastIndexOf(oi,n-1)}return 0}function Zl(t,e,n){if(!h().coldResumeClearToolResults)return"disabled";let r=ii(t,e);return r===null||n-r<=Bl?"warm":null}function ql(t,e){try{return e.readFileSync(t)}catch{return null}}function ec(t){let e=t.split(`
9
- `),n=Ql(e);if(n===null||n<Fl)return"small-context";let r=Jl(e);return r.charsRemoved<Wl?"too-little":r}function tc(t,e,n,r){let s=`${t}.${process.pid}.clear.tmp`;try{r.writeFileSync(s,e,r.statSync(t).mode&511),r.appendFileSync(s,n),r.renameSync(s,t)}catch(i){try{r.unlinkSync(s)}catch{}throw i}}function nc(t,e,n,r){try{tc(t,e,n.lines.join(`
10
- `),r)}catch(s){return ui.warn(`Cold-resume tool-result clearing failed for ${ai.basename(t)}, resuming it as is: ${s.message}`),{cleared:!1,reason:"write-failed"}}return{cleared:!0,clearedCount:n.clearedCount,charsRemoved:n.charsRemoved}}function rc(t,e){let n=ql(t,e);if(!n)return{cleared:!1,reason:"unreadable"};let r=Yl(n),s=n.subarray(r);if(!Nl(s))return{cleared:!1,reason:"unreadable"};let i=ec(s.toString("utf8"));return typeof i=="string"?{cleared:!1,reason:i}:nc(t,n.subarray(0,r),i,e)}function fi(t,e,n=Date.now(),r=Kl){let s=Zl(t,e,n),i=s?{cleared:!1,reason:s}:rc(t,r);return i.cleared&&ui.info(`Cleared ${i.clearedCount} old tool results before cold resume: ${e.substring(0,8)} (-${i.charsRemoved} chars)`),i}import{readFileSync as oc}from"fs";var sc={Bash:t=>t.command||"",Read:t=>t.file_path||JSON.stringify(t),Write:t=>t.file_path||JSON.stringify(t),Edit:t=>t.file_path||JSON.stringify(t),Grep:t=>t.pattern||JSON.stringify(t),Glob:t=>t.pattern||JSON.stringify(t),Task:t=>t.description||JSON.stringify(t),mcp__cortex__slack_send_file:t=>{let e=t.file_path||"",n=t.comment||"";return n?`${n} [file: ${e}]`:`[file: ${e}]`}};function mi(t,e){let n=sc[t];return n?n(e):JSON.stringify(e)}import*as hi from"path";function ic(t){if(t.length===0)return"";let e=t.map(n=>`${n.name} (${n.reason})`).join(`
11
- `);return`[${t.length} attachment(s) the user sent could NOT be downloaded and are unavailable to you. Say so rather than answering as if they had not been sent:
12
- ${e}
13
- ]
14
-
15
- `}function rn(t){let e=t.path.replace(/\\/g,"/"),n=t.name?.trim();return n&&n!==hi.basename(e)?`${e} (${n})`:e}function Q(t,e,n=[]){if(e.length===0&&n.length===0)return t;let r=e.filter(a=>Ft.has(a.mimeType)),s=e.filter(a=>Wt.has(a.mimeType)),i=e.filter(a=>!Ft.has(a.mimeType)&&!Wt.has(a.mimeType)),o="";if(r.length>0){let a=r.map(rn).join(`
16
- `);o+=`[User sent ${r.length} image(s). Read these files to view them:
17
- ${a}
18
- ]
19
-
20
- `}if(s.length>0){let a=s.map(rn).join(`
21
- `);o+=`[User sent ${s.length} video(s). Read these files to view them:
22
- ${a}
23
- ]
24
-
25
- `}if(i.length>0){let a=i.map(rn).join(`
26
- `);o+=`[User sent ${i.length} file(s). Read these files:
27
- ${a}
28
- ]
29
-
30
- `}return o+=ic(n),o+(t||(e.length>0?"Please analyze the attached file(s).":""))}function gi(t){if(t?.type!=="system"||t.subtype!=="model_refusal_fallback")return null;let e=t.originalModel??t.original_model,n=t.fallbackModel??t.fallback_model;return typeof e!="string"||e.length===0||typeof n!="string"||n.length===0?null:{type:"model_fallback",originalModel:e,fallbackModel:n}}function sn(){return{messageId:null,model:null,textBlockId:null,thinkingBlockId:null}}function ac(t,e){e.messageId=typeof t.message?.id=="string"?t.message.id:null,e.model=typeof t.message?.model=="string"?t.message.model:null,e.textBlockId=null,e.thinkingBlockId=null}function uc(t,e){if(!e.messageId||typeof t.index!="number")return;let n=`${e.messageId}:${t.index}`;t.content_block?.type==="text"&&(e.textBlockId=n),t.content_block?.type==="thinking"&&(e.thinkingBlockId=n)}function lc(t,e){let n=t.delta?.type;if(n!=="text_delta"&&n!=="thinking_delta")return null;let r=n==="thinking_delta"?t.delta.thinking:t.delta.text;if(typeof r!="string"||r.length===0||!e.messageId||typeof t.index!="number")return null;let s=`${e.messageId}:${t.index}`;return n==="thinking_delta"?(e.thinkingBlockId=s,{kind:"thinking",text:r,blockId:s}):(e.textBlockId=s,{text:r,blockId:s})}function yi(t,e){if(!t||t.type!=="stream_event"||t.parent_tool_use_id)return null;let n=t.event;return!n||typeof n.type!="string"?null:n.type==="message_start"?(ac(n,e),null):n.type==="content_block_start"?(uc(n,e),null):n.type==="content_block_delta"?lc(n,e):null}function ki(t){let e=t.textBlockId;return t.textBlockId=null,e}function Si(t){let e=t.thinkingBlockId;return t.thinkingBlockId=null,e}function cc(t){let e=[];for(let n of t.message?.content||[])n.type==="text"?e.push(`[assistant] ${n.text||""}`):n.type==="tool_use"&&e.push(`[tool_use] ${n.name||"?"}: ${mi(n.name,n.input||{})}`);return e.length?e.join(`
31
- `):null}function dc(t){let e=t.message?.content;if(!Array.isArray(e))return null;let n=[];for(let r of e){if(r.type!=="tool_result")continue;let s=r.content||"",i;Array.isArray(s)?i=s.filter(o=>o.type==="text").map(o=>o.text||"").join(" "):typeof s=="string"?i=s:i=JSON.stringify(s),n.push(`[tool_result]${r.is_error?" [ERROR]":""}: ${i}`)}return n.length?n.join(`
32
- `):null}function pc(t){let e=t.result||"",n=t.total_cost_usd!=null?`$${t.total_cost_usd.toFixed(4)}`:"?",r=t.duration_ms!=null?`${(t.duration_ms/1e3).toFixed(1)}s`:"?";return`[result] turns=${t.num_turns}, cost=${n}, duration=${r}
33
- \u2192 ${e}`}var fc={assistant:cc,user:dc,result:pc};function on(t){let e=t.type||"";if(e==="system"&&t.subtype==="init")return`[init] model=${t.model||"?"}, session=${(t.session_id||"").substring(0,8)}`;if(e==="system"||e==="rate_limit_event")return null;let n=fc[e];return n?n(t):null}function mc(t,e){return!t||!e||t===e?t:t.length<300&&t.length<e.length*.5?e+`
34
-
35
- ---
36
- `+t:t}function hc(t){if(!t?.is_error||typeof t.result!="string")return null;let e=t.result,n=e.toLowerCase();return n.includes("hit your limit")||n.includes("rate limit")||n.includes("rate_limit")||n.includes("too many requests")||n.includes("temporarily limiting requests")?e:null}function an(t,e,n,r,s,i,o,a,u){let l=null,p=null,c=!1,f=null,T=e;if(t){t.total_cost_usd!=null&&(l=t.total_cost_usd),t.num_turns!=null&&(p=t.num_turns);let R=hc(t);if(R&&(c=!0,f=R),typeof t.session_id=="string"&&t.session_id!==e&&(T=t.session_id),t.is_error&&!c){let $t=Array.isArray(t.errors)&&t.errors.length>0?t.errors.join("; "):typeof t.result=="string"&&t.result?t.result:"Claude reported an error during execution";return{resolved:!1,error:new Error($t)}}}let w=mc(a,u),g={sessionId:T,total_cost_usd:l,num_turns:p,rateLimited:c,rateLimitMessage:f,planFilePath:s,enteredPlanMode:i,exitedPlanMode:o,askUserQuestions:[],finalOutput:w||null};return c?{resolved:!0,value:g}:n!==0?{resolved:!1,error:new Error(r||`claude exited with code ${n}`)}:{resolved:!0,value:g}}function gc(t){if(typeof t!="string")return null;let e=t.trim();return e?e.replace(/^\.\//,"").replace(/\\/g,"/").replace(/\/+$/,""):null}function yc(){let t=[];try{let e=JSON.parse(oc(Mr,"utf8")),n=gc(e?.plansDirectory);n&&t.push(n)}catch{}for(let e of Lr)t.includes(e)||t.push(e);return t}var kc=yc();function _i(t){if(typeof t!="string"||!t)return!1;let e=t.replace(/\\/g,"/");return kc.some(n=>e.includes(`${n}/`)||e.endsWith(`/${n}`))}var un=new Map;function bi(t,e){!t||!e||un.set(t,e)}function qe(t){t&&un.delete(t)}function lk(t){return t&&un.get(t)||null}var Sc=new Set(["completed","failed","killed"]),we=class{running=new Set;undelivered=new Set;foreground=new Set;armed=new Map;subagentTasks=new Map;observe(e){if(!e)return;if(e.type==="user"&&e.isReplay){this.observeReplay(e);return}if(e.type!=="system")return;let n=typeof e.task_id=="string"?e.task_id:null;if(n)switch(e.subtype){case"task_started":typeof e.subagent_type=="string"&&typeof e.tool_use_id=="string"&&this.subagentTasks.set(n,e.tool_use_id),e.is_backgrounded===!1?this.foreground.add(n):this.running.add(n);break;case"task_updated":{let r=e.patch??{};r.is_backgrounded===!0&&this.foreground.delete(n)&&this.running.add(n);let s=r.status;s==="killed"?(this.running.delete(n),this.undelivered.delete(n),this.foreground.delete(n)):(s==="completed"||s==="failed")&&this.running.delete(n)&&this.undelivered.add(n);break}case"task_notification":{if(this.foreground.delete(n)||!(this.running.delete(n)||this.undelivered.delete(n))&&e.status==="stopped")break;this.armed.set(n,typeof e.summary=="string"?e.summary.trim():"");break}default:break}}observeReplay(e){if(this.armed.size===0)return;let n=e.message?.content,r=typeof n=="string"?n:Array.isArray(n)?n.filter(s=>s?.type==="text").map(s=>s.text).join(`
37
- `):"";if(r.includes("<task-notification>"))for(let s of r.matchAll(/<task-id>([^<]+)<\/task-id>/g))this.armed.delete(s[1])}get pendingCount(){return this.running.size}get undeliveredCount(){return this.undelivered.size}hasPending(){return this.running.size>0||this.undelivered.size>0}get continuationArmed(){return this.armed.size>0}disarmContinuation(){let e=[...this.armed.values()].filter(Boolean);return this.armed.clear(),e}subagentEndFor(e){if(e?.type!=="system")return null;let n=typeof e.task_id=="string"?e.task_id:null;if(!n)return null;let r=this.subagentTasks.get(n);if(!r)return null;let s=e.subtype==="task_updated"?e.patch?.status:e.subtype==="task_notification"?e.status:null;return typeof s!="string"||!Sc.has(s)?null:(this.subagentTasks.delete(n),{parentToolUseId:r,status:s})}};function Ti(t){return t?.type==="result"&&t?.origin?.kind==="task-notification"}function ln(t,e){return typeof e?.parent_tool_use_id=="string"&&e.parent_tool_use_id.length>0&&(e?.type==="assistant"||e?.type==="user")?"subagent-orphan":e?.type==="assistant"&&t.continuationArmed?"open-continuation":"ignore"}import{createWriteStream as vi,mkdirSync as vc}from"fs";import{Writable as Ec}from"stream";import*as fn from"path";var _c=m("claude-bridge");function bc(t,e,n,r){e.name==="Write"&&_i(e.input?.file_path)&&(t.planFilePath=e.input.file_path,bi(n,e.input.file_path)),e.name==="EnterPlanMode"&&(t.enteredPlanMode=!0),e.name==="ExitPlanMode"&&(t.exitedPlanMode=!0);try{t.onToolUse?.(e.name||"?",e.input||{},typeof e.id=="string"?e.id:"",r)}catch(s){_c.warn("onToolUse threw:",s.message)}}function Tc(t,e,n,r,s){if(!n.text)return;let i=typeof e.message?.model=="string"?e.message.model:null;if(s){t.onAssistantMessage?.(n.text,void 0,i,s);return}t.finalOutput=n.text,n.text.length>(t.longestOutput?.length||0)&&(t.longestOutput=n.text);let o=ki(r)??void 0,a=r.messageId===e.message?.id?r.model:null;t.onAssistantMessage?.(n.text,o,i??a)}function wc(t,e,n,r){if(r)return;let s=Si(n)??void 0;!h().showThinking||typeof e.thinking!="string"||!e.thinking||t.onAssistantThinking?.(e.thinking,s)}function wi(t,e,n,r,s){s?t.subagentTurnCount+=1:t.turnCount+=1;let i={tool_use:o=>bc(t,o,r,s),text:o=>Tc(t,e,o,n,s),thinking:o=>wc(t,o,n,s)};for(let o of e.message?.content||[])i[o.type]?.(o);s||t.onProgress?.({num_turns:t.turnCount,total_cost_usd:null,duration_ms:null})}import xc from"node:path";var cn=class{byPair=new Map;register(e,n){let r=n.map(o=>xc.resolve(o)),s=this.byPair.get(e);if(s){s.refs+=1;for(let o of r)s.paths.includes(o)||s.paths.push(o)}else this.byPair.set(e,{paths:r,refs:1});let i=!1;return()=>{if(i)return;i=!0;let o=this.byPair.get(e);o&&(o.refs-=1,o.refs<=0&&this.byPair.delete(e))}}listPaths(){let e=new Set;for(let n of this.byPair.values())for(let r of n.paths)e.add(r);return[...e]}listPairs(){return[...this.byPair.keys()]}},xi=new cn;var x=m("claude-bridge");function dn(t){let e=t?.parent_tool_use_id;if(!(typeof e!="string"||!e))return{parentToolUseId:e,type:typeof t?.subagent_type=="string"?t.subagent_type:null,description:typeof t?.task_description=="string"?t.task_description:null,model:typeof t?.message?.model=="string"?t.message.model:null}}var pn=1e3;function Ic(t){return t>=1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:t>=1024?`${Math.round(t/1024)} KB`:`${t} B`}function Ei(t){if(typeof t=="string")return t;if(!t||typeof t!="object")return"";if(t.type==="text"&&typeof t.text=="string")return t.text;if(t.type==="image"||t.type==="document"){let n=t.source??{},r=typeof n.media_type=="string"?n.media_type:t.type;return typeof n.data=="string"?`[${r}, ${Ic(Math.floor(n.data.length*3/4))}]`:typeof n.url=="string"?`[${r}, ${n.url}]`:`[${r}]`}let e=JSON.stringify(t)??"";return e.length>pn?`${e.slice(0,pn)}\u2026 [${e.length-pn} more chars]`:e}function Ii(t){return typeof t.content=="string"?t.content:Array.isArray(t.content)?t.content.map(Ei).join(`
38
- `):t.content==null?"":Ei(t.content)}function Cc(t){return t.type==="assistant"?"assistant":t.type==="user"&&!t.isReplay?"tool_result":null}function Pc(t){let e=t?.message?.content;if(typeof e=="string")return e;if(!Array.isArray(e))return null;let n=e.filter(r=>r?.type==="text"&&typeof r.text=="string").map(r=>r.text);return n.length?n.join(""):null}var et=class{host;currentTurn=null;streamDeltaState=sn();contextUsageTracker;bgTracker=new we;backgroundTurnSink=null;pendingInjections=[];injectionAck=null;injectionContinuationArmed=!1;cumulativeCostUsd=0;lastModelName=null;lastTokenUsage=null;constructor(e,n){this.host=e,this.contextUsageTracker=n}notifyBgInterrupted(e=!1){let n=this.backgroundTurnSink;if(!n)return;this.backgroundTurnSink=null;let r=this.pendingInjections.length>0||this.injectionContinuationArmed;if(!e&&!this.bgTracker.hasPending()&&!this.bgTracker.continuationArmed&&!r)return;let s={sessionId:this.host.sessionId,total_cost_usd:null,num_turns:null,rateLimited:!1,rateLimitMessage:null,planFilePath:null,enteredPlanMode:!1,exitedPlanMode:!1,finalOutput:null,pendingBackgroundTasks:0,undeliveredBackgroundTasks:0,backgroundInterrupted:!0};try{n.onResult(s)}catch(i){x.warn("bg-interrupted sink onResult threw:",i.message)}}createTurnStreams(e){if(!this.host.captureTranscriptLogs){let u=()=>new Ec({write(l,p,c){c()}});return{rawStream:u(),txtStream:u(),pairKey:null,releaseCapture:null}}vc($e,{recursive:!0});let n=Sr(),r=fn.join($e,`claude-output-${n}.jsonl`),s=fn.join($e,`claude-output-${n}.txt`),i=vi(r,{flags:"a"}),o=vi(s,{flags:"a"}),a=xi.register(n,[r,s]);return o.write(`=== Cortex session started at ${new Date().toISOString()} ===
39
- === channel=${this.host.channel}, session=${this.host.sessionId} ===
40
-
41
- `),o.write(`[user-input] ${e}
42
-
43
- `),{rawStream:i,txtStream:o,pairKey:n,releaseCapture:a}}registerTurn(e,n,r,s){qe(this.host.sessionId),this.currentTurn={resolve:e,reject:n,resultData:null,planFilePath:null,enteredPlanMode:!1,exitedPlanMode:!1,finalOutput:null,longestOutput:null,turnCount:0,subagentTurnCount:0,capturePairKey:r.pairKey,releaseCapture:r.releaseCapture,onProgress:s.onProgress||null,onAssistantMessage:s.onAssistantMessage||null,onAssistantDelta:s.onAssistantDelta||null,onAssistantThinking:s.onAssistantThinking||null,onAssistantThinkingDelta:s.onAssistantThinkingDelta||null,onToolUse:s.onToolUse||null,onToolResult:s.onToolResult||null,onCompact:s.onCompact||null,onModelFallback:s.onModelFallback||null,onContextUsage:s.onContextUsage||null,onSubagentActivity:s.onSubagentActivity||null,onSubagentEnd:s.onSubagentEnd||null,rawStream:r.rawStream,txtStream:r.txtStream,killed:!1}}deliverContinuation(e){let n=this.backgroundTurnSink;if(n)try{e(n)}catch(r){x.warn("background-turn sink threw:",r.message)}}setBackgroundTurnSink(e){this.backgroundTurnSink=e}setInjectionAckSink(e){this.injectionAck=e}injectUserMessage(e){if(!this.host.canWriteStdin()||!this.currentTurn)return!1;let n=Q(e.text,e.attachments??[]);try{this.host.writeTurnStdin(n)}catch{return!1}return this.pendingInjections.push({prompt:n,text:e.text}),this.host.resetIdleTimer(),this.host.bumpTurnIdleTimer(),x.info(`Injected mid-turn message into ${this.host.sessionId.substring(0,8)} (${n.length} chars)`),!0}handleReplayEcho(e){let n=Pc(e),r=this.pendingInjections[0];if(n===null||!r||r.prompt!==n)return;this.pendingInjections.shift();let s=!!this.currentTurn;s||(this.injectionContinuationArmed=!0),this.ackDelivered(r.text,s,e.uuid)}ackDelivered(e,n,r){let s=this.injectionAck;if(!s)return;let i=typeof r=="string"&&r?{before:r}:void 0;try{s.onDelivered({text:e,foldedIntoTurn:n,...i?{position:i}:{}})}catch(o){x.warn("injection onDelivered threw:",o.message)}}continuationCallbacks(){return{resolve:e=>this.deliverContinuation(n=>n.onResult(e)),reject:e=>x.warn("continuation turn rejected:",e?.message??String(e)),onAssistantMessage:(e,n,r,s)=>this.deliverContinuation(i=>i.onAssistantText(e,r,s)),onAssistantThinking:(e,n)=>this.deliverContinuation(r=>r.onAssistantThinking?.(e,n)),onToolUse:(e,n,r,s)=>this.deliverContinuation(i=>i.onToolUse?.(e,n,r,s)),onToolResult:(e,n,r,s,i)=>this.deliverContinuation(o=>o.onToolResult?.(e,n,r,s,i)),onContextUsage:e=>this.deliverContinuation(n=>n.onContextUsage?.(e)),onModelFallback:null}}openContinuationTurn(e){let n=this.bgTracker.disarmContinuation(),r=e?"[injected-message continuation]":"[background-task continuation]",s=this.createTurnStreams(r),i=e?void 0:{summaries:n};this.deliverContinuation(o=>o.onTurnOpen?.(i)),this.currentTurn={...this.continuationCallbacks(),resultData:null,planFilePath:null,enteredPlanMode:!1,exitedPlanMode:!1,finalOutput:null,longestOutput:null,turnCount:0,subagentTurnCount:0,capturePairKey:s.pairKey,releaseCapture:s.releaseCapture,onProgress:null,onAssistantDelta:null,onCompact:null,onSubagentActivity:null,onSubagentEnd:null,onAssistantThinkingDelta:null,rawStream:s.rawStream,txtStream:s.txtStream,killed:!1,spontaneous:!0}}compactUsage(e){let n=this.lastTokenUsage;return!n&&!e.total_cost_usd?null:{inputTokens:n?.input??0,outputTokens:n?.output??0,cacheReadTokens:n?.cacheRead??0,cacheWriteTokens:n?.cacheCreation??0,costUsd:e.total_cost_usd}}resetCostBaseline(e){this.cumulativeCostUsd=e}turnCost(e){if(e.total_cost_usd==null)return 0;let n=e.total_cost_usd,r=n-this.cumulativeCostUsd;return this.cumulativeCostUsd=n,r>0?r:0}captureTurnAccounting(e){this.lastTokenUsage=e.usage?{input:e.usage.input_tokens??0,output:e.usage.output_tokens??0,cacheCreation:e.usage.cache_creation_input_tokens??0,cacheRead:e.usage.cache_read_input_tokens??0}:null;let n=e.modelUsage?Object.keys(e.modelUsage):[];return this.lastModelName=n[0]??null,this.turnCost(e)}reportedAccounting(e){let n=e.usage,r=n?{input:ce(n.input_tokens),output:ce(n.output_tokens),cacheCreation:ce(n.cache_creation_input_tokens),cacheRead:ce(n.cache_read_input_tokens)}:null;return{usageReported:n!=null,inputTokens:r?.input??null,outputTokens:r?.output??null,cacheReadTokens:r?.cacheRead??null,cacheCreationTokens:r?.cacheCreation??null,...Xt(r),model:e.modelUsage?Object.keys(e.modelUsage)[0]??null:null}}settleResultTurn(e,n,r){if(r.resolved){let i=r.value;i.reportedAccounting=this.reportedAccounting(n),i.pendingBackgroundTasks=this.bgTracker.pendingCount,i.undeliveredBackgroundTasks=this.bgTracker.undeliveredCount+(this.bgTracker.continuationArmed?1:0)}this.currentTurn=null,this.host.clearTurnIdleTimer();let s=on(n);s&&e.txtStream.write(s+`
44
- `),e.txtStream.write(`
45
- === Turn finished at ${new Date().toISOString()} ===
46
- `),e.rawStream.end(),e.txtStream.end(),e.releaseCapture?.(),e.releaseCapture=null,r.resolved?e.resolve(r.value):e.reject(r.error)}handleResultEvent(e,n){e.resultData={...n,total_cost_usd:this.captureTurnAccounting(n)};let r=an(e.resultData,this.host.sessionId,0,"",e.planFilePath,e.enteredPlanMode,e.exitedPlanMode,e.finalOutput,e.longestOutput);this.settleResultTurn(e,n,r)}handleToolResultEvent(e,n){if(typeof e.onToolResult!="function")return;let r=n.message?.content;if(!Array.isArray(r))return;let s=dn(n);for(let i of r){if(!i||i.type!=="tool_result")continue;let o=typeof i.tool_use_id=="string"?i.tool_use_id:"",a=Gt(i.content);try{e.onToolResult(o,Ii(i),i.is_error===!0,s,a.length?a:void 0)}catch(u){x.warn("onToolResult threw:",u.message)}}}handleOrphanSubagentLine(e){let n=dn(e);if(!n)return;let r=e.message?.content;if(!Array.isArray(r))return;let s=typeof e.message?.model=="string"?e.message.model:null;for(let i of r)if(i){if(i.type==="tool_use"){let o=typeof i.id=="string"?i.id:"";this.deliverContinuation(a=>a.onToolUse?.(i.name||"?",i.input||{},o,n))}else if(i.type==="text"&&i.text)this.deliverContinuation(o=>o.onAssistantText(i.text,s,n));else if(i.type==="tool_result"){let o=typeof i.tool_use_id=="string"?i.tool_use_id:"",a=Gt(i.content);this.deliverContinuation(u=>u.onToolResult?.(o,Ii(i),i.is_error===!0,n,a.length?a:void 0))}}}handleAssistantEvent(e,n){wi(e,n,this.streamDeltaState,this.host.sessionId,dn(n))}handleStreamEvent(e){this.emitContextUsage(e);let n=yi(e,this.streamDeltaState);if(!n)return;let r=n.kind==="thinking"?h().showThinking?this.currentTurn?.onAssistantThinkingDelta:null:this.currentTurn?.onAssistantDelta;try{r?.(n.text,n.blockId)}catch(s){x.warn("assistant delta callback threw:",s.message)}}emitContextUsage(e){let n=this.contextUsageTracker.observe(e),r=this.currentTurn?.onContextUsage;if(!(!n||typeof r!="function"))try{r(n)}catch(s){x.warn("onContextUsage threw:",s.message)}}emitSubagentActivity(e){let n=e?.parent_tool_use_id;if(typeof n!="string")return;let r=Cc(e);if(!r)return;let s=typeof e.subagent_type=="string"?e.subagent_type:null,i=this.currentTurn?.onSubagentActivity;if(typeof i=="function")try{i(n,s,r)}catch(o){x.warn("onSubagentActivity threw:",o.message)}}emitModelFallback(e){let n=gi(e),r=this.currentTurn?.onModelFallback;if(!(!n||!r))try{r({originalModel:n.originalModel,fallbackModel:n.fallbackModel})}catch(s){x.warn("onModelFallback threw:",s.message)}}handleLine(e){if(!e)return;this.host.resetIdleTimer(),this.host.bumpTurnIdleTimer();let n,r=!1;try{n=JSON.parse(e),r=!0}catch{}if(r&&n?.type==="stream_event"){this.handleStreamEvent(n);return}this.currentTurn?.rawStream&&this.currentTurn.rawStream.write(e+`
47
- `);try{let s=n;if(!r)throw new Error("not json");if(s.type==="system"&&s.subtype==="compact_boundary"&&this.emitContextUsage(s),s.type==="system"&&s.subtype==="compact_boundary"&&this.currentTurn?.onCompact){let a=s.compact_metadata??{};try{this.currentTurn.onCompact({trigger:typeof a.trigger=="string"?a.trigger:"auto",preTokens:typeof a.pre_tokens=="number"?a.pre_tokens:void 0})}catch(u){x.warn("onCompact threw:",u.message)}}if(this.emitModelFallback(s),s.type==="rate_limit_event"&&s.rate_limit_info){let a=this.host.anthropicBaseUrl?.match(/\/m\/([^/]+)\//)?.[1]||void 0;this.host.reportRateLimit(s.rate_limit_info,{provider:"anthropic",displayName:"Anthropic",mode:a}).catch(u=>x.error("handleRateLimitEvent error:",u))}s.type==="user"&&s.isReplay&&this.handleReplayEcho(s),s.type==="user"&&!s.isReplay&&this.currentTurn&&this.handleToolResultEvent(this.currentTurn,s),this.bgTracker.observe(s);let i=this.bgTracker.subagentEndFor(s);if(i){let a=this.currentTurn?.onSubagentEnd;if(a)try{a(i.parentToolUseId,i.status)}catch(u){x.warn("onSubagentEnd threw:",u.message)}else this.deliverContinuation(u=>u.onSubagentEnd?.(i.parentToolUseId,i.status))}if(!this.currentTurn&&ln(this.bgTracker,s)==="subagent-orphan"&&this.handleOrphanSubagentLine(s),!this.currentTurn&&this.backgroundTurnSink&&s.type==="assistant"&&(this.injectionContinuationArmed||ln(this.bgTracker,s)==="open-continuation")){let a=this.injectionContinuationArmed;this.injectionContinuationArmed=!1,this.openContinuationTurn(a)}if(s.type==="result"&&this.currentTurn){if(Ti(s)&&!this.currentTurn.spontaneous){x.info(`Ignoring notification-turn result on user turn ${this.host.sessionId.substring(0,8)} (num_turns=${s.num_turns??"?"})`),this.currentTurn.txtStream.write(`[notification-turn result ignored \u2014 user turn still open]
48
- `);return}this.emitContextUsage(s),this.handleResultEvent(this.currentTurn,s);return}s.type==="assistant"&&this.currentTurn&&this.handleAssistantEvent(this.currentTurn,s),this.emitSubagentActivity(s);let o=on(s);o&&this.currentTurn?.txtStream&&this.currentTurn.txtStream.write(o+`
49
- `)}catch{this.currentTurn?.txtStream&&this.currentTurn.txtStream.write(`[raw] ${e}
50
- `)}x.info("stream:",e.substring(0,200))}closeTurnLogs(e){try{e.txtStream.write(`
51
- === Turn ended at ${new Date().toISOString()} ===
52
- `),e.rawStream.end(),e.txtStream.end()}catch{}e.releaseCapture?.(),e.releaseCapture=null}abortTurnOnProcessClose(e,n){if(this.currentTurn){let r=this.currentTurn;if(this.currentTurn=null,this.closeTurnLogs(r),this.host.clearTurnIdleTimer(),r.spontaneous)this.notifyBgInterrupted(!0);else if(r.killed)r.reject(new Br);else{let s=an(r.resultData,this.host.sessionId,e||1,n,r.planFilePath,r.enteredPlanMode,r.exitedPlanMode,r.finalOutput,r.longestOutput);s.resolved?r.resolve(s.value):r.reject(s.error)}}}failInFlightTurn(e){if(this.currentTurn){let n=this.currentTurn;this.currentTurn=null,this.closeTurnLogs(n),n.reject(e)}}holdsIdle(){return this.bgTracker.hasPending()||this.pendingInjections.length>0||this.injectionContinuationArmed}markCurrentTurnKilled(){this.currentTurn&&(this.currentTurn.killed=!0)}};function L(t){return t!==null&&typeof t=="object"?t:null}function Y(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}function Ci(t,e){return t[e]===void 0?0:Y(t[e])}function Pi(t){let e=L(t);if(!e)return null;let n=Y(e.input_tokens),r=Ci(e,"cache_creation_input_tokens"),s=Ci(e,"cache_read_input_tokens");return n===null||r===null||s===null?null:Y(n+r+s)}function Ac(t){let e=L(t);if(!e)return null;let n=Pi(e),r=Y(e.output_tokens);return n===null||r===null?null:Y(n+r)}function Rc(t){let n=L(t.usage)?.iterations;return Array.isArray(n)&&n.length>0?n.at(-1):null}function Ai(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:null}function Oc(t){let e=L(t)?.canonicalModel;return typeof e=="string"?e:null}function Mc(t){return t?.replace(/\[1m\]$/,"")??null}function Ri(t,e){return e?t.find(([,n])=>Oc(n)===e)?.[1]??null:null}function Oi(t,e){return e?t.find(([n])=>n===e)?.[1]??null:null}function Lc(t,e){return Ri(t,e)??Oi(t,e)}function Dc(t,e){return Oi(t,e)??Ri(t,Mc(e))}function jc(t,e,n){let r=L(t);if(!r)return null;let s=Object.entries(r);return Lc(s,e)??Dc(s,n)??(s.length===1?s[0][1]:null)}function Uc(t,e,n){let r=L(jc(t.modelUsage,e,n));return Ai(r?.contextWindow)}function Nc(t){return t?.endsWith("[1m]")?1e6:2e5}var tt=class{configuredModel;autoCompactWindow;contextWindow;currentInput=null;currentUsed=null;activeModel=null;resultFallbackAllowed=!0;lastSnapshotKey=null;constructor(e,n){this.configuredModel=e??null,this.autoCompactWindow=Ai(n),this.contextWindow=this.capped(Nc(e))}capped(e){return this.autoCompactWindow===null?e:Math.min(e,this.autoCompactWindow)}observe(e){let n=L(e);return n?n.type==="stream_event"?this.observeStream(L(n.event)):n.type==="system"&&n.subtype==="compact_boundary"?this.observeCompaction():n.type==="result"?this.observeResult(n):null:null}observeStream(e){return e?.type==="message_start"?this.observeMessageStart(L(e.message)):e?.type==="message_delta"?this.observeMessageDelta(L(e.usage)):null}observeMessageStart(e){this.currentInput=null,this.currentUsed=null,this.resultFallbackAllowed=!0,this.activeModel=typeof e?.model=="string"?e.model:null;let n=Pi(e?.usage);return n===null?null:(this.currentInput=n,this.currentUsed=n,this.snapshot(n))}observeMessageDelta(e){let n=Y(e?.output_tokens);return this.currentInput===null||n===null?null:(this.currentUsed=Y(this.currentInput+n),this.currentUsed===null?null:this.snapshot(this.currentUsed))}observeCompaction(){return this.currentInput=null,this.currentUsed=null,this.activeModel=null,this.resultFallbackAllowed=!1,null}observeResult(e){let n=Uc(e,this.activeModel,this.configuredModel);n!==null&&(this.contextWindow=this.capped(n));let r=this.resultFallbackAllowed?Ac(Rc(e))??this.currentUsed:null;return r===null?null:(this.currentUsed=r,this.snapshot(r))}snapshot(e){let n=`${e}/${this.contextWindow}`;return n===this.lastSnapshotKey?null:(this.lastSnapshotKey=n,{usedTokens:e,contextWindow:this.contextWindow,percent:e/this.contextWindow*100,accuracy:"exact"})}};import $c from"node:fs";import mn from"node:path";var Bc=1e5,Fc=1e6;function Wc(t){try{let n=JSON.parse($c.readFileSync(t,"utf8"))?.autoCompactWindow;return typeof n!="number"||!Number.isInteger(n)?null:n>=Bc&&n<=Fc?n:null}catch{return null}}function Kc(t,e=je){let n=[mn.join(t,".claude","settings.local.json"),mn.join(t,".claude","settings.json"),mn.join(e,"settings.json")];for(let r of n){let s=Wc(r);if(s!==null)return s}return null}function Mi(t,e){return(e.pinned?null:h().maxContextTokens)??Kc(t,e.userConfigDir)}var nt=m("claude-bridge");function zc(t,e,n,r){let s=r??"claude";return t?t(s,e,n):{process:Hc(s,e,{...n,stdio:["pipe","pipe","pipe"]})}}function Li(t){return t?[...t]:[]}function Di(t){return t==null?null:[...t]}function Ni(t){let e=t.mcpComposition;return{cwd:re(t.cwd),routeIdentity:Us(t),composition:e,interactionBridge:e==="direct"&&t.isUserInitiated===!0,teamLead:e==="direct"&&t.teamLead===!0,teamWorker:e==="direct"&&t.teamWorker===!0,tools:t.tools??null,pluginCapabilityFingerprint:t.pluginCapabilityFingerprint??null,pluginDirs:Li(t.pluginDirs),mcpConfigPaths:Li(t.mcpConfigPaths),mcpToolAllowlist:Di(t.mcpToolAllowlist),supplementalMcpConfigIdentity:t.supplementalMcpConfigIdentity??null,disableSkills:t.disableSkills===!0,settingSources:Di(t.settingSources)}}function Vc(t){let e=[["cwd",t.cwd],["routeIdentity",t.routeIdentity],["composition",t.composition],["interactionBridge",t.interactionBridge],["tools",t.tools],["pluginCapabilityFingerprint",t.pluginCapabilityFingerprint],["supplementalMcpConfigIdentity",t.supplementalMcpConfigIdentity],["disableSkills",t.disableSkills],["pluginDirs",t.pluginDirs],["mcpConfigPaths",t.mcpConfigPaths],["mcpToolAllowlist",t.mcpToolAllowlist],["settingSources",t.settingSources]];return t.teamLead&&e.push(["teamLead",!0]),t.teamWorker&&e.push(["teamWorker",!0]),JSON.stringify(e)}function ji(t){return Vc(Ni(Zt(t)))}function Jc(t,e,n){return new tt(t,Mi(e,{pinned:!!n.pinnedEnv,userConfigDir:n.pinnedEnv?.CLAUDE_CONFIG_DIR}))}var hn=class{proc=null;rl=null;sessionId;channel;sessionKey;options;modelName;compatibility;supervision;onSelfClose;onEvict;onRateLimit;turns;alive=!1;needsResume;idleTimer=null;turnIdleTimer=null;stderr="";constructor(e,n={}){this.channel=e.channel,this.sessionId=e.sessionId,this.sessionKey=e.sessionKey,this.needsResume=e.needsResume,this.options=e.options,this.modelName=e.options.model||null,this.compatibility=Ni(e.options),this.onSelfClose=n.onSelfClose,this.onEvict=n.onEvict,this.onRateLimit=n.onRateLimit,this.turns=new et(this,Jc(this.modelName,e.options.cwd,e.options)),this.spawnProcess()}get captureTranscriptLogs(){return this.options.captureTranscriptLogs!==!1}get anthropicBaseUrl(){return this.options.anthropicBaseUrl}handleProcessClose(e){nt.info(`Process closed: ${this.sessionId.substring(0,8)} code=${e}`),this.idleTimer&&clearTimeout(this.idleTimer),this.turnIdleTimer&&clearTimeout(this.turnIdleTimer),this.idleTimer=null,this.turnIdleTimer=null,this.alive=!1,qe(this.sessionId),this.turns.abortTurnOnProcessClose(e,this.stderr),this.turns.notifyBgInterrupted(),this.onSelfClose?.(this.sessionKey,this)}validateSupplementalMcpConfig(){let e=this.options.supplementalMcpConfigPath,n=this.compatibility.supplementalMcpConfigIdentity;!e||!n||Yt(e,n)}attachSpawnedProcess(e){this.proc=e.process,this.supervision=e.supervision,this.stderr="",this.rl=Gc({input:this.proc.stdout,crlfDelay:1/0}),this.rl.on("line",n=>this.turns.handleLine(n)),this.proc.stderr.on("data",n=>{this.stderr+=n.toString()}),this.proc.on("close",n=>this.handleProcessClose(n))}armProcessTimers(){this.alive=!0,this.resetIdleTimer()}spawnProcess(){this.validateSupplementalMcpConfig();let{cwd:e,processSpawner:n,cliPath:r}=this.options,s=en(e,this.sessionId);this.needsResume&&fi(s,this.sessionId);let{args:i,env:o}=qs({channel:this.channel,sessionId:this.sessionId,needsResume:this.needsResume,options:this.options}),a=this.needsResume?ri(s,this.sessionId):0;this.turns.resetCostBaseline(a),nt.info(`Spawning persistent process: ${this.sessionId.substring(0,8)} ${this.needsResume?`(resume, restored cost $${a.toFixed(2)})`:"(new)"}`);let u=zc(n,i,{cwd:e,env:o},r);this.attachSpawnedProcess(u),this.armProcessTimers()}writeTurnStdin(e){let n=JSON.stringify({type:"user",message:{role:"user",content:e},session_id:this.sessionId})+`
53
- `;try{this.proc.stdin.write(n)}catch(r){throw this.alive=!1,this.turns.failInFlightTurn(new Error(`Failed to write to claude stdin: ${r.message}`)),this.onEvict?.(this.sessionKey,this),new Error(`Claude process stdin write failed: ${r.message}`)}}startTurnIdleTimer(){this.turnIdleTimer=setTimeout(()=>{nt.info(`Session ${this.sessionId.substring(0,8)} turn idle for 60min, killing`),this.kill()},Pr)}async sendMessage(e,n){this.alive||(this.needsResume=!0,this.spawnProcess()),this.resetIdleTimer();let r=Q(e,n.attachments??[]),s=this.turns.createTurnStreams(e),i=new Promise((a,u)=>{this.turns.registerTurn(a,u,s,n)});this.writeTurnStdin(r),this.startTurnIdleTimer();let o=await i;return this.clearTurnIdleTimer(),this.resetIdleTimer(),o}async compact(){let e=!1,n=null,r=await this.sendMessage("/compact",{onCompact:s=>{e=!0,n=typeof s.preTokens=="number"?s.preTokens:null}});if(r.finalOutput?.trim()==="Error: No messages to compact")return{status:"not-needed",tokensBefore:null,estimatedTokensAfter:null,contextUsage:null,usage:null};if(!e)throw new Error("Claude did not confirm compaction with compact_boundary");return{status:"compacted",tokensBefore:n,estimatedTokensAfter:null,contextUsage:null,usage:this.turns.compactUsage(r)}}bumpTurnIdleTimer(){this.turnIdleTimer&&(clearTimeout(this.turnIdleTimer),this.startTurnIdleTimer())}resetIdleTimer(){if(this.idleTimer&&clearTimeout(this.idleTimer),this.turns.holdsIdle()){this.idleTimer=null;return}this.idleTimer=setTimeout(()=>{nt.info(`Session ${this.sessionId.substring(0,8)} idle for 65min, closing`),this.close()},Cr)}close(){if(this.idleTimer&&clearTimeout(this.idleTimer),this.turnIdleTimer&&clearTimeout(this.turnIdleTimer),!this.proc||!this.alive){this.turns.notifyBgInterrupted();return}this.alive=!1;try{this.proc.stdin.end()}catch{}let e=setTimeout(()=>{if(this.proc&&this.proc.exitCode===null){try{this.proc.kill("SIGTERM")}catch{}setTimeout(()=>{if(this.proc&&this.proc.exitCode===null)try{this.proc.kill("SIGKILL")}catch{}},1e4)}},3e4);this.proc.on("close",()=>clearTimeout(e))}kill(){if(this.idleTimer&&clearTimeout(this.idleTimer),this.turnIdleTimer&&clearTimeout(this.turnIdleTimer),!this.proc||this.proc.exitCode!==null)return!1;if(this.alive=!1,this.turns.markCurrentTurnKilled(),this.supervision)return this.supervision.cancel("cancel"),!0;try{return this.proc.kill("SIGTERM"),!0}catch{return!1}}canWriteStdin(){return this.alive&&!!this.proc?.stdin}clearTurnIdleTimer(){this.turnIdleTimer&&clearTimeout(this.turnIdleTimer),this.turnIdleTimer=null}reportRateLimit(e,n){return this.onRateLimit?this.onRateLimit(e,n):Promise.resolve()}handleLine(e){this.turns.handleLine(e)}get currentTurn(){return this.turns.currentTurn}set currentTurn(e){this.turns.currentTurn=e}get backgroundTurnSink(){return this.turns.backgroundTurnSink}get bgTracker(){return this.turns.bgTracker}get lastModelName(){return this.turns.lastModelName}get lastTokenUsage(){return this.turns.lastTokenUsage}setBackgroundTurnSink(e){this.turns.setBackgroundTurnSink(e)}setInjectionAckSink(e){this.turns.setInjectionAckSink(e)}injectUserMessage(e){return this.turns.injectUserMessage(e)}isAlive(){return this.alive}};function Xc(t,e,n,r=fr){return ni(t,en(r,e),n)}function Ui(t){let e=Xc(t.needsResume,t.sessionId,void 0,t.options.cwd);return{...t,needsResume:e}}var rt=class{backend="claude";capabilities=K.claude;onRateLimit;constructor(e={}){this.onRateLimit=e.onRateLimit}open(e,n={}){let r=new hn(Ui(qt(e)),{onSelfClose:n.onSelfClose,onEvict:n.onEvict,onRateLimit:this.onRateLimit});return new Ye(r,e,ji(e))}specIdentity(e){return ji(e)}claudeResumeTarget(e){let{needsResume:n,sessionId:r}=Ui(qt(e));return{needsResume:n,sessionId:r}}};import{existsSync as Jd,mkdirSync as Xd}from"fs";import{existsSync as Qc,mkdirSync as Yc,renameSync as Zc,unlinkSync as qc,writeFileSync as ed}from"fs";import*as $i from"path";var td={deepseek:{supportsDeveloperRole:!1,maxTokensField:"max_completion_tokens"}};function Bi(t,e,n){let r=n.modelsPath,s={};for(let u of t){if(u.entry){s[u.name]=u.entry;continue}let l=u.basePath??`/${u.name}`,p={baseUrl:`${e}${l}`},c={...td[u.name]};Object.keys(c).length>0&&(p.compat=c),u.modelOverrides&&(p.modelOverrides=u.modelOverrides),s[u.name]=p}let o=JSON.stringify({providers:s},null,2)+`
54
- `;Yc($i.dirname(r),{recursive:!0});let a=`${r}.tmp.${process.pid}.${Date.now()}`;try{ed(a,o,"utf8"),Zc(a,r)}catch(u){try{Qc(a)&&qc(a)}catch{}throw u}}function gn(t,e,n){let r=new Map;for(let s of t)r.has(s)||r.set(s,{name:s});return e&&r.set(e,{name:e,...n!=null?{basePath:n}:{}}),Array.from(r.values())}function Fi(t,e){return t.map(n=>{let r=e[n.name];return r?{...n,entry:r}:n})}import{readdirSync as od}from"fs";import*as Gi from"path";var Wi="[A-Za-z0-9-]+",nd="\\d{4}-\\d{2}-\\d{2}T\\d{2}(?:[-:]\\d{2}){2}(?:-\\d{3})?Z",rd=/^(?<primary>.+)\.turn-(?<turn>\d+)\.bak$/,sd=new RegExp(`^(?<sessionId>${Wi})\\.jsonl$`),id=new RegExp(`^(?<timestamp>${nd})_(?<sessionId>${Wi})\\.jsonl$`);function Ki(t){let e=t.match(rd);if(e?.groups){let s=Number(e.groups.turn),i=Ki(e.groups.primary);return!i||!Number.isSafeInteger(s)||s<0||i.backupTurn!==null?null:{...i,backupTurn:s}}let n=t.match(id);if(n?.groups?.sessionId&&n.groups.timestamp)return{sessionId:n.groups.sessionId,primaryFilename:t,timestampPrefix:n.groups.timestamp,backupTurn:null};let r=t.match(sd);return r?.groups?.sessionId?{sessionId:r.groups.sessionId,primaryFilename:t,timestampPrefix:null,backupTurn:null}:null}function Hi(t,e){let n=null;for(let r of t){let s=Ki(r);if(!(!s||s.backupTurn!==null||s.sessionId!==e)){if(s.timestampPrefix===null)return r;(n===null||s.primaryFilename>n)&&(n=s.primaryFilename)}}return n}function zi(t,e){if(!e)return null;try{let n=Hi(od(t),e);return n?Gi.join(t,n):null}catch{return null}}var ad={"openai-codex":"OpenAI Codex"};function Vi(t){let e=t.provider||"pi",n=t.gatewayPath?.match(/\/m\/([^/]+)\//)?.[1]??"api";return{provider:e,displayName:ad[e]??e,mode:n}}function ud(t,e,n){return{provider:e.provider,displayName:e.displayName,modes:e.mode?[e.mode]:[],windows:t.windows.map(r=>({...r})),observedAt:Math.floor(n/1e3),freshness:"stale",billing:"subscription"}}async function ld(t,e,n){for(let r of t.windows)await n({rateLimitType:r.type,...r.label?{rateLimitLabel:r.label}:{},utilization:r.utilization,resetsAt:r.resetsAt},e)}async function Ji(t,e,n){let r=n.usageStore.update(ud(t,e,(n.now??Date.now)())).then(()=>null,o=>({error:o})),s;try{await ld(t,e,n.submit)}catch(o){s=o}let i=await r;if(s!==void 0)throw s;if(i)throw i.error}import*as qi from"node:path";var Xi=m("pi-adapter"),Qi=3900*1e3,Yi=3600*1e3,Zi=2e3;function yn(t){return Q(t.text,t.attachments??[])}var st=class{pending=[];waiters=[];closed=!1;push(e){if(this.closed)return;let n=this.waiters.shift();n?n({value:e,done:!1}):this.pending.push(e)}next(){let e=this.pending.shift();return e?Promise.resolve({value:e,done:!1}):this.closed?Promise.resolve({value:void 0,done:!0}):new Promise(n=>this.waiters.push(n))}close(){if(!this.closed){this.closed=!0;for(let e of this.waiters.splice(0))e({value:void 0,done:!0})}}},it=class{sink=null;pending=[];sequence=0;get hasPending(){return this.pending.length>0}setSink(e){this.sink=e}clearSink(){this.sink=null}begin(e){let n={id:`pi-inject-${++this.sequence}`,text:e,rejected:!1};return this.pending.push(n),n}reject(e){return this.pending.includes(e)?(e.rejected=!0,this.drainRejected(),!0):!1}consumeNext(e){this.drainRejected();let n=this.pending.shift();n&&this.notifyDelivered(n,e),this.drainRejected()}abandon(){for(let e of this.pending.splice(0))this.notifyUndelivered(e)}drainRejected(){for(;this.pending[0]?.rejected;){let e=this.pending.shift();e&&this.notifyUndelivered(e)}}notifyDelivered(e,n){try{this.sink?.onDelivered({text:e.text,foldedIntoTurn:!0,...n?{position:n}:{}})}catch(r){Xi.warn(`PI injection delivery sink failed: ${r.message}`)}}notifyUndelivered(e){try{this.sink?.onUndelivered?.({text:e.text})}catch(n){Xi.warn(`PI injection undelivered sink failed: ${n.message}`)}}};var H=m("pi-adapter");function Z(t){return t instanceof Error?t:new Error(String(t))}function q(t){return typeof t=="number"&&Number.isFinite(t)?t:null}function kn(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function cd(t){let e=kn(t);return Object.keys(e).length===0?null:{inputTokens:q(e.input)??0,outputTokens:q(e.output)??0,cacheReadTokens:q(e.cacheRead)??0,cacheWriteTokens:q(e.cacheWrite)??0,costUsd:q(kn(e.cost).total)}}function dd(t){return/nothing to compact|no messages to compact/i.test(t)}function pd(t){return kn(t).role==="user"}function eo(t){return{[Symbol.asyncIterator]:()=>({next:()=>t.next()})}}var ot=class{sessionKey;sessionId=null;sessionFile=null;currentSessionId=null;ready;handle=null;turnStream=null;parserState=qr();request;registry;onClose;onProviderQuota;subagent;openBundledMcpServer;getSubagentModelEnv;alive=!0;textBuffer="";textBlockId=null;idleTimer=null;turnIdleTimer=null;pendingTurn=null;steering=new it;loopState="idle";compacting=!1;lastContextSampleAt=0;constructor(e){this.sessionKey=e.request.sessionKey,this.request=e.request,this.registry=e.registry,this.onClose=e.onClose,this.onProviderQuota=e.onProviderQuota,this.subagent=e.subagent,this.openBundledMcpServer=e.openBundledMcpServer,this.getSubagentModelEnv=e.getSubagentModelEnv,this.ready=this.start(e.runtimeFactory),this.ready.catch(()=>{}),this.resetIdleTimer()}async start(e){let n;try{n=await e(this.request,{onEvent:r=>this.handleRawEvent(r),onProviderQuota:r=>this.handleProviderQuota(r)},{subagent:this.subagent,openBundledMcpServer:this.openBundledMcpServer,getSubagentModelEnv:this.getSubagentModelEnv})}catch(r){let s=Z(r);throw this.fail(s),s}if(!this.alive)throw await n.dispose().catch(()=>{}),new Error("PI session closed while starting");this.handle=n,this.announceSession(n.session.sessionId,n.session.sessionFile??null)}fail(e){this.alive&&(this.alive=!1,this.clearTimers(),this.steering.abandon(),this.steering.clearSink(),this.rejectPendingTurn(e),this.turnStream?.push({type:"error",message:e.message,fatal:!0}),this.closeTurnStream(),this.onClose?.(this.sessionKey,this))}announceSession(e,n){this.sessionId=e,this.currentSessionId=e,this.sessionFile=n,this.registry.set(e,n??qi.join(this.request.sessionDir,`${e}.jsonl`)),this.emitNormalizedEvent(n?{type:"session_started",sessionId:e,sessionFile:n}:{type:"session_started",sessionId:e})}flushTextBuffer(){this.textBuffer.length>0&&(this.pendingTurn&&(this.pendingTurn.lastAssistantText=this.textBuffer),this.turnStream?.push(this.textBlockId!==null?{type:"assistant_text",text:this.textBuffer,blockId:this.textBlockId}:{type:"assistant_text",text:this.textBuffer}),this.textBuffer=""),this.textBlockId=null}clearTimers(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null),this.clearTurnIdleTimer(),this.flushTextBuffer()}resetIdleTimer(){this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=setTimeout(()=>{H.info(`Session ${this.sessionKey} idle for 65min, closing`),this.close(),this.onClose?.(this.sessionKey,this)},Qi),this.idleTimer.unref?.()}startTurnIdleTimer(){this.turnIdleTimer=setTimeout(()=>{H.info(`Session ${this.sessionKey} turn idle for 60min, killing`),this.kill(new Error("PI turn idle for 60min")),this.onClose?.(this.sessionKey,this)},Yi),this.turnIdleTimer.unref?.()}bumpTurnIdleTimer(){this.turnIdleTimer&&(clearTimeout(this.turnIdleTimer),this.startTurnIdleTimer())}clearTurnIdleTimer(){this.turnIdleTimer&&(clearTimeout(this.turnIdleTimer),this.turnIdleTimer=null)}async liveHandle(){if(await this.ready,!this.alive||!this.handle)throw new Error("PI session is not alive");return this.handle}async compact(){if(this.compacting)throw new Error("PI compact already in progress");let e=await this.liveHandle();this.compacting=!0;try{let n=await e.session.compact();return{status:"compacted",tokensBefore:q(n.tokensBefore),estimatedTokensAfter:q(n.estimatedTokensAfter),usage:cd(n.usage),contextUsage:this.currentContextUsage()}}catch(n){let r=Z(n);if(dd(r.message))return{status:"not-needed",tokensBefore:null,estimatedTokensAfter:null,contextUsage:null,usage:null};throw r}finally{this.compacting=!1}}currentContextUsage(){let e=this.handle?.session;if(!e)return null;try{return ns(e.getSessionStats(),h().maxContextTokens)}catch(n){return H.warn(`PI session ${this.sessionKey}: session stats unavailable: ${Z(n).message}`),null}}isAlive(){return this.alive}openTurnStream(){this.closeTurnStream();let e=new st;return this.turnStream=e,e}closeTurnStream(){this.turnStream!==null&&(this.turnStream.close(),this.turnStream=null)}closeTurnStreamFor(e){this.turnStream===e?this.closeTurnStream():e.close()}handleRawEvent(e){if(!this.alive||e.type==="cortex_subagent_usage"&&this.turnStream===null)return;this.resetIdleTimer(),this.bumpTurnIdleTimer(),this.observeLoop(e);let n=ts(e,this.handle?.session.model);for(let r of es(n,this.parserState)){let s=this.processPendingTurnEvent(r);s!==null&&this.emitWithContext(s)}this.pendingTurn&&(e.type==="message_update"||e.type==="message_end")&&this.sampleContextUsage(!1)}emitWithContext(e){e.type==="turn_complete"&&this.sampleContextUsage(!0),this.emitNormalizedEvent(e)}sampleContextUsage(e){let n=Date.now();if(!e&&n-this.lastContextSampleAt<Zi)return;this.lastContextSampleAt=n;let r=this.currentContextUsage();r&&this.turnStream?.push({type:"context_usage",...r})}observeLoop(e){if(e.type==="agent_start"?this.loopState="running":e.type==="agent_settled"&&(this.loopState="idle"),e.type!=="message_start"||!pd(e.message))return;let n=this.pendingTurn;n&&!n.openingUserSeen?n.openingUserSeen=!0:n&&this.steering.consumeNext(this.leafPosition())}leafPosition(){let e=this.handle?.session.sessionManager?.getLeafId();return e?{after:e}:void 0}handleProviderQuota(e){e?.windows?.length&&(this.onProviderQuota?.(e),this.turnStream?.push({type:"rate_limit",raw:e}))}processPendingTurnEvent(e){let n=this.pendingTurn;if(!n)return e;if(e.type==="plan_written")n.planFilePath=e.path;else if(e.type!=="ask_user_question"){if(e.type==="turn_complete")return this.handleTurnComplete(e);e.type==="error"&&e.fatal&&(this.flushTextBuffer(),this.clearTurnIdleTimer(),this.steering.abandon(),this.pendingTurn=null,n.reject(new Error(e.message)))}return e}handleTurnComplete(e){let n=this.pendingTurn;return this.flushTextBuffer(),n.numTurns+=e.numTurns,e.totalCostUsd!==null&&(n.totalCostUsd=(n.totalCostUsd??0)+e.totalCostUsd),e.error?(this.steering.abandon(),this.settlePendingTurn(e.error)):this.steering.hasPending?(n.deferredCompletion=!0,null):this.settlePendingTurn()}finishDeferredTurn(){return!this.pendingTurn?.deferredCompletion||this.steering.hasPending?null:this.settlePendingTurn()}settlePendingTurn(e){let n=this.pendingTurn;this.pendingTurn=null,this.clearTurnIdleTimer();let r=e?{type:"turn_complete",numTurns:n.numTurns,totalCostUsd:n.totalCostUsd,error:e}:{type:"turn_complete",numTurns:n.numTurns,totalCostUsd:n.totalCostUsd};return e?n.reject(Object.assign(new Error(e),{reason:"provider_error"})):n.resolve(this.buildAgentResult(n)),r}buildAgentResult(e){return{sessionId:this.sessionId,total_cost_usd:e.totalCostUsd,num_turns:e.numTurns,rateLimited:!1,rateLimitMessage:null,planFilePath:e.planFilePath,enteredPlanMode:!1,exitedPlanMode:e.planFilePath!==null,askUserQuestions:void 0,finalOutput:e.lastAssistantText}}emitNormalizedEvent(e){if(e.type==="context_usage"){this.turnStream?.push(e);return}if(e.type==="assistant_thinking"||e.type==="assistant_thinking_delta"){this.emitThinkingEvent(e);return}if(e.type==="assistant_text"&&e.subagent){this.flushTextBuffer(),this.turnStream?.push(e);return}if(e.type!=="assistant_text"){this.flushTextBuffer(),this.turnStream?.push(e),e.type==="turn_complete"&&this.closeTurnStream();return}this.bufferTextEvent(e)}emitThinkingEvent(e){h().showThinking&&(this.flushTextBuffer(),!(e.type==="assistant_thinking_delta"&&!this.request.streamDeltas)&&this.turnStream?.push(e))}bufferTextEvent(e){let n=e.blockId??null;this.textBuffer.length>0&&n!==this.textBlockId&&this.flushTextBuffer(),this.textBlockId=n,this.request.streamDeltas&&n!==null&&this.turnStream?.push({type:"assistant_delta",text:e.text,blockId:n}),this.textBuffer+=e.text}dispatchPrompt(e,n){this.loopState="starting",this.pendingTurn&&(this.pendingTurn.promptDispatched=!0),e.session.prompt(n).catch(r=>this.promptFailed(Z(r)))}promptFailed(e){if(H.warn(`PI session ${this.sessionKey}: prompt failed: ${e.message}`),this.loopState="idle",!this.pendingTurn)return;this.flushTextBuffer(),this.clearTurnIdleTimer(),this.steering.abandon();let n=this.pendingTurn;this.pendingTurn=null,n.reject(e),this.turnStream?.push({type:"error",message:e.message,fatal:!0}),this.closeTurnStream()}injectUserMessage(e){let n=this.handle;if(!this.alive||!n||!this.pendingTurn?.promptDispatched)return!1;let r=this.steering.begin(e.text),s=yn(e),i=this.loopState==="starting"?n.session.steer(s):n.session.prompt(s,{streamingBehavior:"steer"});return this.loopState==="idle"&&(this.loopState="starting"),i.catch(o=>{let a=`injection refused: ${Z(o).message}`;H.warn(`PI session ${this.sessionKey}: ${a}`),this.turnStream?.push({type:"error",message:a,fatal:!1}),this.rejectInjection(r)}),!0}rejectInjection(e){if(!this.steering.reject(e))return;let n=this.finishDeferredTurn();n!==null&&this.emitWithContext(n)}setInjectionAckSink(e){this.steering.setSink(e)}async sendSwitchSession(e){if(!this.alive)return{ok:!1,cancelled:!1};let n;try{n=await this.liveHandle()}catch{return{ok:!1,cancelled:!1}}try{let r=await n.switchSession(e);return{ok:!r.cancelled,cancelled:r.cancelled}}catch(r){return H.warn(`PI session ${this.sessionKey}: switch to ${e} failed: ${Z(r).message}`),{ok:!1,cancelled:!1}}}async sendTurn(e,n,r){let s=await this.liveHandle(),i=yn(r);if(e!==null&&this.currentSessionId!==e&&n!==null&&(await this.sendSwitchSession(n)).ok&&(this.currentSessionId=e),!this.alive||!this.handle)throw new Error("PI session closed before its prompt was sent");this.dispatchPrompt(s,i)}sendExtensionUiResponse(e,n){return this.alive?this.handle?.respondToUi(e,n)?!0:(H.debug(`PI session ${this.sessionKey}: no dialog waits on ui request ${e}`),!1):!1}beginTurn(e,n){this.beginTurnReject(new Error("PISession.beginTurn: superseded by a newer send()")),this.parserState.turnProgressCount=0,this.pendingTurn={resolve:e,reject:n,planFilePath:null,numTurns:0,totalCostUsd:null,promptDispatched:!1,openingUserSeen:!1,deferredCompletion:!1,lastAssistantText:null},this.startTurnIdleTimer()}beginTurnReject(e){this.rejectPendingTurn(e)}rejectPendingTurn(e){if(this.pendingTurn===null)return;let n=this.pendingTurn;this.pendingTurn=null,this.clearTurnIdleTimer(),this.steering.abandon(),n.reject(e)}async close(){return this.shutdown(new Error("PI session closed before turn_complete"))}async shutdown(e){if(this.clearTimers(),!this.alive)return;this.alive=!1,this.steering.abandon(),this.steering.clearSink(),this.rejectPendingTurn(e),this.closeTurnStream();let n=this.handle;if(this.handle=null,!!n)try{await n.dispose()}catch(r){H.warn(`PI session ${this.sessionKey}: dispose failed: ${Z(r).message}`)}}kill(e=Object.assign(new Error("Cancelled by user"),{cancelled:!0})){if(!this.alive)return!1;let n=this.handle;return n&&n.session.abort().catch(()=>{}),this.shutdown(e),!0}};function fd(t){return t instanceof Error?t:new Error(String(t))}var at=class{backend="pi";identity;session;onEvict;resolveSessionPath;injections;constructor(e,n,r={}){this.session=e,this.identity=Ke(n),this.onEvict=r.onEvict,this.resolveSessionPath=r.resolveSessionPath,this.injections=new ae(e,"pi-run-inj")}get backendSessionId(){return this.session.sessionId}run(e,n){let r=this.session.openTurnStream(),s=new le,i=this.injections.beginRun(s),o=this.sendTurn(e);o.catch(()=>{});let a=ue(),u=ue(),l=new oe(n.awaitBackground,{push:g=>s.push(g),settleForeground:g=>a.resolve(g),settleRun:g=>{u.resolve(g),a.resolve(g)},close:()=>s.close()});i.attachPhase(l),a.promise.catch(g=>u.reject(g)),u.promise.catch(()=>{});let p=!1,c=[],f=g=>{p?g():c.push(g)},T=()=>{p=!0;let g=c;c=[];for(let R of g)R()},w=!1;return o.then(g=>{w=!0,f(()=>{s.push({type:"foreground_result",result:g}),l.start(g)})},g=>{w=!0,f(()=>{s.push({type:"phase",phase:"done",pendingBackground:0,undeliveredBackground:0}),s.close()}),a.reject(g)}),(async()=>{for await(let g of eo(r))n.onNormalizedEvent?.(g),g.type!=="turn_complete"&&s.push(_e(g,"foreground"));T(),await Promise.resolve(),w||(s.push({type:"phase",phase:"done",pendingBackground:0,undeliveredBackground:0}),s.close())})(),a.promise.catch(()=>{}),{events:{[Symbol.asyncIterator]:()=>({next:()=>s.next()})},result:a.promise,settled:u.promise,cancel:()=>{this.session.closeTurnStreamFor(r)}}}sendTurn(e){return new Promise((n,r)=>{this.session.beginTurn(n,r),this.session.sendTurn(this.session.sessionId,this.turnPath(),e).catch(s=>this.session.beginTurnReject(fd(s)))})}turnPath(){let e=this.session.sessionId;return e===null?null:this.resolveSessionPath?.(e)??this.session.sessionFile}steer(e,n){return this.injections.steer(e,n)}respondToDialog(e,n){return this.session.sendExtensionUiResponse(e,n)}ingestExternal(e){return this.injections.pushOutOfBand(e)}compact(){return this.session.compact()}close(){return this.session.close()}kill(){let e=this.session.kill();return e&&this.onEvict?.(this),e}isAlive(){return this.session.isAlive()}async switchSession(e,n){let r=await this.session.sendSwitchSession(n);return r.ok&&(this.session.currentSessionId=e),r}};import*as xn from"node:path";import{randomUUID as to}from"node:crypto";function no(t){return t.cancelled===!0}function Sn(t){if(no(t))return;let e=t.value;return typeof e=="string"?e:void 0}function ro(t,e){let n=new Map;function r(o,a,u,l){if(l?.signal?.aborted)return Promise.resolve(a);let p=to();return new Promise(c=>{let f,T=()=>{w(),c(a)},w=()=>{f&&clearTimeout(f),l?.signal?.removeEventListener("abort",T),n.delete(p)};l?.signal?.addEventListener("abort",T,{once:!0}),l?.timeout&&(f=setTimeout(()=>{w(),c(a)},l.timeout),f.unref?.()),n.set(p,{resolve:g=>{w(),c(u(g))},cleanup:w}),t({type:"extension_ui_request",id:p,...o})})}function s(o,a){t({type:"extension_ui_request",id:to(),method:o,...a})}return{ui:{select:(o,a,u)=>r({method:"select",title:o,options:a,timeout:u?.timeout},void 0,Sn,u),confirm:(o,a,u)=>r({method:"confirm",title:o,message:a,timeout:u?.timeout},!1,l=>!no(l)&&l.confirmed===!0,u),input:(o,a,u)=>r({method:"input",title:o,placeholder:a,timeout:u?.timeout},void 0,Sn,u),editor:(o,a)=>r({method:"editor",title:o,prefill:a},void 0,Sn),notify:(o,a)=>s("notify",{message:o,notifyType:a}),setStatus:(o,a)=>s("setStatus",{statusKey:o,statusText:a}),setWidget:(o,a,u)=>{(a===void 0||Array.isArray(a))&&s("setWidget",{widgetKey:o,widgetLines:a,widgetPlacement:u?.placement})},setTitle:o=>s("setTitle",{title:o}),setEditorText:o=>s("set_editor_text",{text:o}),pasteToEditor:o=>s("set_editor_text",{text:o}),onTerminalInput:()=>()=>{},setWorkingMessage:()=>{},setWorkingVisible:()=>{},setWorkingIndicator:()=>{},setHiddenThinkingLabel:()=>{},setFooter:()=>{},setHeader:()=>{},custom:async()=>{},getEditorText:()=>"",addAutocompleteProvider:()=>{},setEditorComponent:()=>{},getEditorComponent:()=>{},get theme(){return e},getAllThemes:()=>[],getTheme:()=>{},setTheme:()=>({success:!1,error:"Theme switching not supported in Cortex sessions"}),getToolsExpanded:()=>!1,setToolsExpanded:()=>{}},respond(o,a){let u=n.get(o);return u?(u.resolve(a),!0):!1},cancelAll(){for(let o of[...n.values()])o.resolve({cancelled:!0})}}}import{spawn as md}from"node:child_process";import{readFileSync as hd}from"node:fs";import*as ao from"node:path";import{pathToFileURL as gd}from"node:url";var uo=m("hook-bridge"),yd={"agent:pre-tool":"tool_call","agent:post-tool":"tool_result","agent:session-start":"before_agent_start","agent:session-end":"session_shutdown","agent:pre-compact":"session_before_compact","agent:user-prompt":"input","agent:turn-end":"turn_end"},_n={"agent:pre-tool":"PreToolUse","agent:post-tool":"PostToolUse","agent:session-start":"SessionStart","agent:session-end":"SessionEnd","agent:pre-compact":"PreCompact","agent:user-prompt":"UserPromptSubmit","agent:turn-end":"Stop"};function lo(t){return(t.startsWith("mcp__")?null:Ue("claude",t))??t.charAt(0).toUpperCase()+t.slice(1)}function kd(t,e){return(t==="read"||t==="write"||t==="edit")&&typeof e.path=="string"?{...e,file_path:e.path}:{...e}}function bn(t,e){let n=t.sessionManager?.getSessionFile();return n?ao.basename(n,".jsonl"):e.CORTEX_SESSION_ID??"unknown"}function Sd(t){return Array.isArray(t)?t.filter(e=>typeof e=="object"&&e!==null&&e.type==="text").map(e=>e.text).join(""):""}function co(t,e){let n=t.CORTEX_CACHE_SESSION_ID??t.CORTEX_SESSION_ID;return{...t,...n?{CORTEX_CACHE_SESSION_ID:n}:{},CORTEX_SESSION_ID:e}}function _d(t){if(t?.trim())try{return JSON.parse(t.trim())}catch{return}}function bd(t,e){if(t===0)return null;let n=e?.trim()?`: ${e.trim()}`:"";return new Error(`exited with code ${t}${n}`)}function so(t,e,n,r,s){return new Promise((i,o)=>{let a=md(t,e,{env:co(s,String(n.session_id??"unknown")),stdio:["pipe","pipe","pipe"]}),u="",l="",p=!1,c=setTimeout(()=>{p=!0,a.kill("SIGKILL")},r);a.stdout.setEncoding("utf8").on("data",f=>{u+=f}),a.stderr.setEncoding("utf8").on("data",f=>{l+=f}),a.on("error",f=>{clearTimeout(c),o(f)}),a.on("close",f=>{if(clearTimeout(c),p){o(new Error(`timed out after ${r}ms`));return}let T=bd(f,l);T?o(T):i(_d(u))}),a.stdin.on("error",()=>{}),a.stdin.end(JSON.stringify(n))})}var io=new Map,Td=/export\s+(?:async\s+)?function\s+runHook\b|export\s*\{[^}]*\brunHook\b/;function wd(t){try{return Td.test(hd(t,"utf8"))}catch{return!1}}async function xd(t){let e=br(t).path,n=io.get(e);if(n!==void 0)return n;let r=null;if(wd(e))try{let s=await import(gd(e).href);typeof s.runHook=="function"&&(r=s.runHook)}catch(s){uo.warn(`in-process load of ${t} failed; using the spawned form: ${s.message}`)}return io.set(e,r),r}function vd(t,e,n){return t instanceof Promise?Promise.race([t,new Promise((r,s)=>{setTimeout(()=>s(new Error(`${n} timed out after ${e}ms`)),e).unref?.()})]):Promise.resolve(t)}function Tn(t){return typeof t!="object"||t===null||Array.isArray(t)?{}:t}async function xe(t,e,n){let r=(t.run.timeout??30)*1e3;try{if(t.run.script){let s=await xd(t.run.script);if(s){let i=co(n,String(e.session_id??"unknown"));return await vd(s(e,i),r,t.id)}return await so(process.execPath,Tr(t.run.script),e,r,n)}return await so("sh",["-c",t.run.command],e,r,n)}catch(s){uo.error(`${t.id} error:`,s);return}}function wn(t,e){if(typeof t.matcher!="string")return!0;let n=e.startsWith("mcp__")?e:lo(e),r=t.event.startsWith("agent:")?n:e;return new RegExp(t.matcher).test(r)}function Ed(t){return t.event.startsWith("pi:")?t.event.slice(3):t.event.startsWith("agent:")?yd[t.event]:null}function po(t,e,n,r){let s={hook_event_name:t,session_id:bn(n,r),tool_name:lo(e.toolName),tool_input:kd(e.toolName,e.input),tool_use_id:e.toolCallId,cwd:n.cwd};return"content"in e&&Id(s,e),s}function Id(t,e){t.tool_output=Sd(e.content),t.tool_response=e.details??null,t.is_error=e.isError}function fo(t,e,n,r){return{...typeof e=="object"&&e!==null?e:{event:e},hook_event_name:_n[t.event],session_id:bn(n,r),tool_name:"",tool_input:{},tool_use_id:"",cwd:n.cwd}}function Cd(t,e,n,r){return{...typeof e=="object"&&e!==null?e:{event:e},hook_event_name:t,session_id:bn(n,r),cwd:n.cwd}}function Pd(t,e){if(!(!e?.updatedInput||typeof e.updatedInput!="object")){for(let n of Object.keys(t.input))delete t.input[n];Object.assign(t.input,e.updatedInput)}}function Ad(t){let e=t.hookSpecificOutput;if(e?.permissionDecision==="deny")return{block:!0,reason:e.permissionDecisionReason??"Blocked by hook registry"}}async function Rd(t,e,n,r){for(let s of n){if(!wn(s,t.toolName))continue;let i=po(_n[s.event],t,e,r),o=Tn(await xe(s,i,r));Pd(t,o.hookSpecificOutput);let a=Ad(o);if(a)return a}}function Od(t,e){if(!e)return!1;let n=Array.isArray(t.content)?t.content:[];return n.push({type:"text",text:e}),t.content=n,!0}async function Md(t,e,n,r){let s=!1;for(let i of n){if(!wn(i,t.toolName))continue;let o=po(_n[i.event],t,e,r),a=Tn(await xe(i,o,r));s=Od(t,a.hookSpecificOutput?.additionalContext)||s}return s?{content:t.content}:void 0}async function Ld(t,e,n,r){let s=t.systemPrompt??"",i=!1;for(let o of n){let a={...t,systemPrompt:s},l=Tn(await xe(o,fo(o,a,e,r),r)).hookSpecificOutput?.additionalContext;l&&(s+=`
55
-
56
- ${l}`,i=!0)}if(i)return{systemPrompt:s}}async function Dd(t,e,n,r){for(let s of n)await xe(s,fo(s,t,e,r),r)}function jd(t,e,n,r,s){let i=[e];return t==="tool_call"?Rd(n,r,i,s):t==="tool_result"?Md(n,r,i,s):t==="before_agent_start"?Ld(n,r,i,s):Dd(n,r,i,s)}function pe(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function oo(t,e){for(let n of Object.keys(t))delete t[n];Object.assign(t,e)}function Ud(t,e,n){if(!pe(e)||!pe(n))return n;if(t==="before_provider_headers"){pe(e.headers)&&pe(n.headers)&&oo(e.headers,n.headers);return}if(t!=="tool_call"||!pe(e.input)||!pe(n.input))return n;oo(e.input,n.input);let r={...n};return delete r.input,Object.keys(r).length>0?r:void 0}async function Nd(t,e,n,r,s){let i=t==="tool_call"||t==="tool_result",o=n?.toolName;if(i&&(typeof o!="string"||!wn(e,o)))return;let a=await xe(e,Cd(t,n,r,s),s);return Ud(t,n,a)}function $d(t,e,n,r,s){return e.event.startsWith("pi:")?Nd(t,e,n,r,s):jd(t,e,n,r,s)}function mo(t,e){let n=Qr(Xr(),{backend:"pi"});for(let r of n){let s=Ed(r);s&&t.on(s,(i,o)=>$d(s,r,i,o,e))}}function Bd(t,e){let n={};try{n=e?.()??{}}catch{}return{...t,CORTEX_SUBAGENT_CLAUDE_MODELS:n.CORTEX_SUBAGENT_CLAUDE_MODELS??"[]",CORTEX_SUBAGENT_PI_MODELS:n.CORTEX_SUBAGENT_PI_MODELS??"[]"}}function ho(t,e={}){let n=t.reportsProviderQuota?e.onProviderQuota:void 0,r=Bd(t.env,e.getSubagentModelEnv),s=[{name:"cortex-image-first",factory:hs},{name:"cortex-mcp-bridge",factory:i=>fs(i,ps(r,t.pluginMcpServers,e.openBundledMcpServer))},{name:"cortex-tool-shims",factory:i=>bs(i,r,{onSubagentEvent:e.onSubagentEvent,onSubagentUsage:e.onSubagentUsage,onProviderQuota:n,runForeignSubagent:e.subagent?.runForeignSubagent,startBackgroundSubagent:e.subagent?.startBackgroundSubagent,stopBackgroundSubagent:e.subagent?.stopBackgroundSubagent,openBundledMcpServer:e.openBundledMcpServer})}];return t.disableHooks||s.push({name:"cortex-hook-bridge",factory:i=>mo(i,t.env)}),n&&s.push({name:"cortex-quota-probe",factory:ms(n)}),s}var fe=m("pi-runtime"),Fd=new Set(["off","minimal","low","medium","high","xhigh","max"]),go=Symbol.for("@earendil-works/pi-coding-agent:theme");function Wd(t){let e=globalThis;return e[go]||t.initTheme("dark",!1),e[go]}function Kd(t){if(t.thinking){if(Fd.has(t.thinking))return t.thinking;fe.warn(`Ignoring unknown PI thinking level '${t.thinking}' for session ${t.sessionKey}`)}}function Hd(t,e){return e.sessionPath?t.SessionManager.open(e.sessionPath,e.sessionDir):t.SessionManager.create(e.cwd,e.sessionDir)}function Gd(t,e,n){let r=Kd(e);if(!e.model)return{model:void 0,thinking:r};let s=t.resolveCliModel({cliProvider:e.provider??void 0,cliModel:e.model,cliThinking:r,modelRuntime:n});if(s.error)throw new Error(s.error);return s.warning&&fe.warn(`PI model resolution for ${e.sessionKey}: ${s.warning}`),{model:s.model&&e.benchmarkMaxOutputTokens!==void 0?{...s.model,maxTokens:e.benchmarkMaxOutputTokens}:s.model,thinking:r??s.thinkingLevel}}async function zd(t,e,n,r,s){us(h().piCompactReserveTokens,{agentDir:s});let i=ls(t,r,s),o=await t.ModelRuntime.create({authPath:xn.join(s,"auth.json"),modelsPath:xn.join(s,"models.json"),allowModelNetwork:!1});return t.createAgentSessionServices({cwd:r,agentDir:s,settingsManager:i,modelRuntime:o,resourceLoaderOptions:{additionalSkillPaths:e.skillPaths,extensionFactories:n,systemPrompt:e.systemPrompt??void 0,appendSystemPrompt:e.appendSystemPrompt,noContextFiles:e.noContextFiles}})}function Vd(t,e,n){return async({cwd:r,agentDir:s,sessionManager:i,sessionStartEvent:o})=>{let a=await zd(t,e,n,r,s),u=[...a.diagnostics,...a.resourceLoader.getExtensions().errors.map(({path:f,error:T})=>({type:"error",message:`Failed to load extension "${f}": ${T}`}))],{model:l,thinking:p}=Gd(t,e,a.modelRuntime);return{...await t.createAgentSessionFromServices({services:a,sessionManager:i,sessionStartEvent:o,model:l,thinkingLevel:p}),services:a,diagnostics:u}}}async function yo(t,e,n={}){let r=await Jr(),s=ro(c=>e.onEvent(c),Wd(r)),i=ho(t,{subagent:n.subagent,openBundledMcpServer:n.openBundledMcpServer,getSubagentModelEnv:n.getSubagentModelEnv,onProviderQuota:e.onProviderQuota,onSubagentEvent:c=>e.onEvent({type:"cortex_subagent_event",notice:c}),onSubagentUsage:c=>e.onEvent({type:"cortex_subagent_usage",report:c})}),o=Hd(r,t),a=await r.createAgentSessionRuntime(Vd(r,t,i),{cwd:o.getCwd(),agentDir:t.agentDir,sessionManager:o});for(let c of a.diagnostics){let f=`PI session ${t.sessionKey}: ${c.message}`;c.type==="error"?fe.error(f):c.type==="warning"?fe.warn(f):fe.info(f)}a.modelFallbackMessage&&fe.warn(`PI session ${t.sessionKey}: ${a.modelFallbackMessage}`);let u,l=async()=>{let c=a.session;await c.bindExtensions({uiContext:s.ui,mode:"rpc",onError:f=>e.onEvent({type:"extension_error",extensionPath:f.extensionPath,event:f.event,error:f.error})}),u?.(),u=c.subscribe(f=>e.onEvent(f))};a.setRebindSession(l),await l();let p=!1;return{get session(){return a.session},respondToUi:(c,f)=>s.respond(c,f),switchSession:c=>a.switchSession(c),async dispose(){p||(p=!0,u?.(),s.cancelAll(),await a.dispose())}}}var ve=m("pi-adapter"),Qd={getProviders:()=>[],getModels:()=>[],peekModels:()=>[],ensureModels:async()=>[],refresh:()=>{}};function Yd(t){return{provider:We,displayName:"OpenAI Codex",modes:[t],windows:[],observedAt:null,freshness:"never"}}function Zd(t){return{...t,modes:[...t.modes],windows:t.windows.map(e=>({...e})),...t.spend?{spend:{...t.spend}}:{},freshness:"stale"}}function qd(){return{engineKey:"default",resume:{backendSessionId:null,resume:!1},model:{},prompt:{},tools:{},plugins:{},mcp:{},env:{},route:{},flags:{isUserInitiated:!1},context:{},backend:{kind:"pi"},process:{}}}var ut=class{backend="pi";capabilities=K.pi;poolLookup=null;runtimeFactory;providerDiscovery;configuredProviderOverrides=new Map;sessionPathRegistry=new Map;configuredAgentDir;prepareAgentDir;userModelsPath;usageStore;submitRateLimit;subagent;openBundledMcpServer;getSubagentModelEnv;sessionDir;constructor(e=yo,n=Ge,r=Qd,s={}){this.runtimeFactory=e,this.sessionDir=n,this.providerDiscovery=r,this.configuredAgentDir=s.agentDir,this.prepareAgentDir=s.prepareAgentDir,this.userModelsPath=s.userModelsPath,this.usageStore=s.usageStore,this.submitRateLimit=s.submitRateLimit,this.subagent=s.subagent,this.openBundledMcpServer=s.openBundledMcpServer,this.getSubagentModelEnv=s.getSubagentModelEnv}async getUsage(e){if(e.provider!==We||!e.mode)return null;let n=await this.usageStore?.get(We)??null;return[n?Zd(n):Yd(e.mode)]}gatewayOverrides(e,n,r){if(n){let[i]=gn([],n,r);this.configuredProviderOverrides.set(n,i)}let s=new Map(gn(e,null,null).map(i=>[i.name,i]));for(let i of this.configuredProviderOverrides.values())s.set(i.name,i);return Array.from(s.values())}resolveSpawnSessionPath(e,n){if(!e.resume.resume||!e.resume.backendSessionId)return null;let r=this.resolveSessionPath(e.resume.backendSessionId);return r===null&&ve.info(`PI resume target '${e.resume.backendSessionId}' not found (no live session or file in ${n}); starting fresh`),r}prepareGatewayAgentDir(e){try{this.prepareAgentDir?.(e)}catch(n){ve.warn(`Failed to prepare the PI agent dir: ${n.message}`)}}writeGatewayProviders(e,n,r){try{this.writeGatewayProvidersUnchecked(e,n,r)}catch(s){ve.warn(`Failed to write PI models.json: ${s.message}`)}}writeGatewayProvidersUnchecked(e,n,r){let s=Fi(this.gatewayOverrides(this.providerDiscovery.getProviders(),e.model.provider??null,e.route.gatewayPath??null),this.userModelsPath?Zr(this.userModelsPath):{});if(s.length===0){ve.warn("No PI providers to route (empty discovery and no selected provider); the PI session may fail to authenticate");return}Bi(s,r,{modelsPath:is(n)})}syncGatewayConfig(e,n){let r=e.route.gatewayBaseUrl;r&&(this.prepareGatewayAgentDir(n),this.writeGatewayProviders(e,n,r))}get agentDir(){return this.configuredAgentDir??He}ensureProviderRouting(e){let n=qd();n.model.provider=e.provider,n.model.id=e.model,n.route.gatewayPath=e.gatewayPath??void 0,n.route.gatewayBaseUrl=e.gatewayBaseUrl,this.syncGatewayConfig(n,this.agentDir)}buildRequest(e,n){return rs(e,{agentDir:this.agentDir,sessionDir:this.sessionDir,sessionPath:n,cwd:re(e.cwd),streamDeltas:e.flags.streamDeltas??h().streamDeltas})}specIdentity(e){return Ke(this.buildRequest(e,null))}prepareRequest(e){let n=this.agentDir;Xd(this.sessionDir,{recursive:!0});let r=this.resolveSpawnSessionPath(e,this.sessionDir);return this.syncGatewayConfig(e,n),this.buildRequest(e,r)}quotaReporter(e){if(!e.route.gatewayBaseUrl)return;let n=this.usageStore,r=this.submitRateLimit;if(!(!n||!r))return s=>{Ji(s,Vi({provider:e.model.provider,gatewayPath:e.route.gatewayPath}),{usageStore:n,submit:r}).catch(i=>ve.error("reportCodexQuota error:",i))}}open(e,n={}){let r=this.prepareRequest(e),s=new ot({request:r,runtimeFactory:this.runtimeFactory,registry:this.sessionPathRegistry,onClose:n.onSelfClose,onProviderQuota:this.quotaReporter(e),subagent:this.subagent,openBundledMcpServer:this.openBundledMcpServer,getSubagentModelEnv:this.getSubagentModelEnv});return new at(s,r,{onEvict:n.onEvict,resolveSessionPath:i=>this.resolveSessionPath(i)})}setEnginePool(e){this.poolLookup=e}registerSessionPath(e,n){this.sessionPathRegistry.set(e,n)}resolveSessionPath(e){let n=this.sessionPathRegistry.get(e);if(n&&Jd(n))return n;n&&this.sessionPathRegistry.delete(e);let r=zi(this.sessionDir,e);return r&&this.sessionPathRegistry.set(e,r),r}async switchSession(e,n){let r=this.poolLookup?.get(n);if(!r)return{ok:!1,cancelled:!1};let s=this.resolveSessionPath(e);return s===null?{ok:!1,cancelled:!1}:r.switchSession(e,s)}};var D=m("rate-limit-throttle"),ep="rate-limit:clear",tp={five_hour:.9,seven_day:.95,seven_day_overage_included:.95},np=.9,rp=5e3,sp=5e3,lt="outage",ip="model_scoped",vn=null,Ie=null,So=null,_o=null,bo=null,Ee=null,Cn=0,A=new Map,ct=new De;function op(t){return{...t,modes:[...t.modes].sort(),windows:t.windows.map(e=>({...e})).sort((e,n)=>e.resetsAt-n.resetsAt)}}function dt(t=A){return[...t.values()].map(op).sort((e,n)=>e.provider.localeCompare(n.provider))}function pt(){return new Map(dt().map(t=>[t.provider,t]))}function ft(t){A.clear();for(let e of t.values())A.set(e.provider,e)}function En(t=A){return dt(t).flatMap(e=>e.windows)}function ap(t){return[...new Set(t)].sort()}function up(t=A){let e=dt(t);return e.length>0?{providers:e}:null}async function Ce(t=A){await Ie?.save(up(t))}function mt(){try{_o?.()}catch(t){D.error(`onChange hook failed: ${t.message}`)}}function ht(t){try{So?.(t)}catch(e){D.error(`onResume hook failed: ${e.message}`)}}function gt(t,e=b("notice.rateLimit.title"),n){vn&&_r(vn,{text:t,level:"warning",title:e,...n&&n.length>0?{actions:n}:{}})}function lp(t){return[{type:"button",text:b("notice.rateLimit.resumeNow"),actionId:ep,value:t,style:"primary"}]}function cp(t){return new Date(t*1e3).toLocaleString(yr()==="zh"?"zh-CN":"en-GB",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1})}function dp(t){let e=Math.max(0,Math.round(t-Date.now()/1e3)),n=Math.floor(e/3600),r=Math.floor(e%3600/60);return n>0?`${n}h ${r}m`:r>0?`${r}m`:`${e}s`}function To(t,e){return e??tp[t]??np}function ko(t){let e=t?.trim();return e||null}function Pn(t,e,n){return n.type===t&&(t!==ip||n.label===e)}function wo(t,e,n){let r=h().providerRateLimits[t],s=r?.windows?.find(i=>Pn(e,n,i));return s?{enabled:s.enabled,threshold:s.threshold??null}:typeof r?.enabled=="boolean"?{enabled:r.enabled,threshold:r.threshold??null}:{enabled:!0,threshold:null}}function pp(t){if(typeof t=="string"){let n=ko(t)??"unknown";return{provider:n,displayName:n,mode:n}}let e=ko(t?.provider);return e?{provider:e,displayName:t?.displayName?.trim()||e,...t?.mode?{mode:t.mode}:{}}:{provider:"unknown",displayName:"Unknown provider"}}function fp(t){if(!t?.provider||!Array.isArray(t.windows))return null;let e=t.windows.filter(n=>n?.type&&Number.isFinite(n.resetsAt));return e.length===0?null:{provider:t.provider,displayName:t.displayName||t.provider,modes:Array.isArray(t.modes)?ap(t.modes.filter(Boolean)):[],windows:e.map(n=>({type:n.type,...n.label?{label:n.label}:{},utilization:Number.isFinite(n.utilization)?n.utilization:null,resetsAt:n.resetsAt,activatedAt:Number.isFinite(n.activatedAt)?n.activatedAt:Date.now()}))}}function mp(t){return Array.isArray(t.providers)?t.providers.map(fp).filter(e=>e!==null):[]}function xo(t){let e=t.type===lt?0:rp;return t.resetsAt*1e3+e}function In(t,e=Date.now()){return xo(t)>e}function hp(t){for(let e of mp(t)){let n=e.windows.filter(r=>In(r));n.length>0&&A.set(e.provider,{...e,windows:n})}}function gp(){let t=En().map(xo);return t.length>0?Math.min(...t):null}function yp(){Ee&&clearTimeout(Ee),Ee=null,Cn++}function ee(t=0){yp();let e=gp();if(e===null)return;let n=Cn,r=Math.max(t,e-Date.now(),0);D.info(`Next provider reset check in ${(r/1e3/60).toFixed(1)} min`),Ee=setTimeout(()=>{Tp(e,n)},r)}function kp(t,e){let n=[];for(let[r,s]of t){let i=s.windows.filter(o=>!In(o,e)).map(o=>o.type);s.windows=s.windows.filter(o=>In(o,e)),!(s.windows.length>0)&&(t.delete(r),n.push({provider:r,displayName:s.displayName,expiredTypes:i}))}return n}function Sp(t){return t.expiredTypes.includes(lt)?{text:`${ne.ok} ${b("notice.rateLimit.outageCleared",{provider:t.displayName})}`,title:b("notice.rateLimit.outageTitle")}:{text:`${ne.ok} ${b("notice.rateLimit.cleared",{provider:t.displayName})}`}}async function _p(t){try{return await Ce(t),!0}catch(e){return D.error(`Failed to persist throttle expiry: ${e.message}`),ee(sp),!1}}async function bp(t){let e=pt(),n=En(e).length,r=Math.max(Date.now(),t),s=kp(e,r);if(En(e).length===n){ee();return}if(await _p(e)){ft(e);for(let i of s){let o=Sp(i);gt(o.text,o.title)}mt(),s.length>0&&ht(s.map(i=>i.provider)),ee()}}async function Tp(t,e){await ct.run(async()=>{e===Cn&&(Ee=null,await bp(t))})}async function m_(t,e,n,r){vn=t,Ie=e,So=n??null,_o=r??null;let s=await e.load();if(!s){D.info("Initialized");return}hp(s),A.size===0?(await e.save(null),ht([])):(await Ce(),ee()),D.info(`Initialized \u2014 ${A.size} provider throttle(s) restored`)}function wp(t,e){let n=t.windows.find(i=>Pn(e.rateLimitType,e.rateLimitLabel,i));if(!n)return t.windows.push({type:e.rateLimitType,...e.rateLimitLabel?{label:e.rateLimitLabel}:{},utilization:e.utilization,resetsAt:e.resetsAt,activatedAt:Date.now()}),!0;let r=Math.max(n.resetsAt,e.resetsAt),s=r!==n.resetsAt||e.utilization!==n.utilization;return n.resetsAt=r,n.utilization=e.utilization,s}function xp(t,e){if(typeof t.utilization!="number"||!t.rateLimitType)return!1;let n=wo(e.provider,t.rateLimitType,t.rateLimitLabel);return n.enabled&&t.utilization>=To(t.rateLimitType,n.threshold)}async function vp(t){try{return await bo?.(t)??[]}catch(e){return D.warn(`Rate-limit notice actions failed: ${e.message}`),[]}}async function Ep(t,e,n){if(D.info(`Throttle updated: provider=${e.provider}, type=${t.rateLimitType}, utilization=${t.utilization}, mode=${e.mode??"(none)"}`),!n)return;let r=[...lp(e.provider),...await vp(e.provider)];gt(`${ne.warning} ${b("notice.rateLimit.activated",{provider:e.displayName,type:t.rateLimitType,pct:(t.utilization*100).toFixed(0),at:cp(t.resetsAt),remaining:dp(t.resetsAt)})}`,b("notice.rateLimit.title"),r)}async function Ip(t,e){if(!t||!Ie||!t.rateLimitType||!t.resetsAt)return;let n=pp(e);if(!xp(t,n))return;let r=pt(),s=r.get(n.provider),i=!s;s||(s={provider:n.provider,displayName:n.displayName,modes:[],windows:[]},r.set(n.provider,s));let o=!!n.mode&&!s.modes.includes(n.mode);o&&s.modes.push(n.mode);let a=wp(s,{rateLimitType:t.rateLimitType,rateLimitLabel:t.rateLimitLabel,utilization:t.utilization,resetsAt:t.resetsAt});!i&&!o&&!a||(await Ce(r),ft(r),ee(),mt(),await Ep(t,n,i))}async function An(t,e){await ct.run(()=>Ip(t,e))}async function Cp(t){if(!Ie)return{cleared:[]};let e=pt(),n=t?e.has(t)?[t]:[]:[...e.keys()];if(n.length===0)return{cleared:[]};let r=[];for(let s of n){let i=e.get(s),o=i.windows.reduce((a,u)=>Math.max(a,u.resetsAt),0);r.push({provider:s,displayName:i.displayName,types:i.windows.map(a=>a.type),resetsAt:o}),e.delete(s)}await Ce(e),ft(e),ee(),mt(),ht(r.map(s=>s.provider));for(let s of r){let i=s.types.join(", ");D.info(`Throttle manually cleared: provider=${s.provider}, types=${i}`),gt(`${ne.ok} ${b("notice.rateLimit.clearedManually",{provider:s.displayName})}`)}return{cleared:r}}async function h_(t){return ct.run(()=>Cp(t))}function Pp(t,e,n){if(e.type===lt)return!1;let r=n.find(i=>Pn(e.type,e.label,i));if(!r)return!1;let s=wo(t,e.type,e.label);return!s.enabled||r.utilization<To(e.type,s.threshold)}async function Ap(t,e){await Ce(t),ft(t),ee(),mt(),e&&(D.info(`Throttle released by a fresh quota reading: provider=${e.provider}`),gt(`${ne.ok} ${b("notice.rateLimit.cleared",{provider:e.displayName})}`),ht([e.provider]))}async function Rp(t,e){let n=pt(),r=n.get(t);if(!Ie||!r)return!1;let s=r.windows.filter(i=>!Pp(t,i,e));return s.length===r.windows.length?!1:(s.length>0?r.windows=s:n.delete(t),await Ap(n,s.length===0?r:null),!0)}async function g_(t,e){return ct.run(()=>Rp(t,e))}function y_(t){bo=t}function vo(t){return t?A.has(t):A.size>0}function Eo(t,e){let n=A.get(t);return n?n.windows.some(r=>r.type===lt)||n.modes.includes(e):!1}function k_(){return{providers:dt()}}import Op from"node:fs/promises";import yt from"node:path";var Mp=yt.join(mr,"provider-state.json");function Lp(){return{rateLimitThrottle:null,resumeQueue:[],providerUsage:[]}}function Io(t){return JSON.stringify(t,null,2)}async function Co(t){try{let e=JSON.parse(await Op.readFile(t,"utf8"));if(typeof e!="object"||e===null||Array.isArray(e))throw new Error(`${t} must contain a JSON object`);return e}catch(e){if(e.code==="ENOENT")return null;throw e}}function Dp(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function jp(t){let e=t.rateLimitThrottle,n=t.providerUsage;return Object.hasOwn(t,"rateLimitThrottle")&&Object.hasOwn(t,"resumeQueue")&&(e===null||Dp(e))&&Array.isArray(t.resumeQueue)&&(n===void 0||Array.isArray(n))}async function Up(t){let e=await Co(t);if(!e)return!1;if(!jp(e))throw new Error(`${t} must contain rateLimitThrottle and resumeQueue`);return!0}function Np(t){return Object.hasOwn(t,"rateLimitThrottle")||Object.hasOwn(t,"resumeQueue")}function $p(t){return{rateLimitThrottle:t.rateLimitThrottle??null,resumeQueue:t.resumeQueue??[],providerUsage:[]}}function Bp(t){let e={...t};return delete e.rateLimitThrottle,delete e.resumeQueue,e}async function v_(t=I){let e=yt.join(t,"data"),n=yt.join(e,"schedules.json"),r=await Co(n);if(!r||!Np(r))return;let s=yt.join(e,"provider-state.json");await Up(s)||await Bt(s,Io($p(r))),await Bt(n,Io(Bp(r)))}var Rn=class{repo;constructor(e=Mp){this.repo=new kr({filePath:e,defaultValue:Lp})}async setRateLimitThrottle(e){await this.repo.mutate(n=>({next:{...n,rateLimitThrottle:e},result:void 0}))}async getRateLimitThrottle(){return(await this.repo.read()).rateLimitThrottle??null}async setResumeQueue(e){await this.repo.mutate(n=>({next:{...n,resumeQueue:e},result:void 0}))}async getResumeQueue(){return(await this.repo.read()).resumeQueue??[]}async setProviderUsage(e){await this.repo.mutate(n=>({next:{...n,providerUsage:e},result:void 0}))}async getProviderUsage(){return(await this.repo.read()).providerUsage??[]}async getSubscriptionSignOuts(){return{...(await this.repo.read()).subscriptionSignOuts}}async setSubscriptionSignOut(e,n){await this.repo.mutate(r=>{let s={...r.subscriptionSignOuts};return n===null?delete s[e]:s[e]=n,{next:{...r,subscriptionSignOuts:s},result:void 0}})}flush(){return this.repo.flush()}},On=new Rn;function P_(t){return t.credits.find(e=>e.id===t.nextCreditId)??t.credits[0]??null}function B(t){return t.billing?`${t.provider}::${t.billing}`:t.provider}function Fp(t){return{...t,modes:[...t.modes],windows:t.windows.map(e=>({...e})),...t.spend?{spend:{...t.spend}}:{},...t.resetCredits?{resetCredits:Ao(t.resetCredits)}:{}}}function Ao(t){return{...t,credits:t.credits.map(e=>({...e,...e.clears?{clears:[...e.clears]}:{}}))}}function Wp(t,e){return e.resetCredits||!t?.resetCredits?e:{...e,resetCredits:Ao(t.resetCredits)}}function Pe(t){let e=new Map;for(let n of t)e.set(B(n),Fp(n));return[...e.values()].sort((n,r)=>n.provider.localeCompare(r.provider)||B(n).localeCompare(B(r)))}function Po(t,e){return t.observedAt===null?!0:e.observedAt===null?!1:e.observedAt>=t.observedAt}var Kp={load:()=>On.getProviderUsage(),save:t=>On.setProviderUsage(t)},Mn=class{persistence;mutationMutex=new De;constructor(e=Kp){this.persistence=e}async list(){return Pe(await this.persistence.load())}async get(e,n){let r=await this.list();if(n===void 0)return r.find(i=>i.provider===e)??null;let s=B({provider:e,billing:n});return r.find(i=>B(i)===s)??null}async update(e){await this.mutationMutex.run(async()=>{let n=Pe(await this.persistence.load()),r=B(e),s=n.findIndex(i=>B(i)===r);s!==-1&&!Po(n[s],e)||(s===-1?n.push(e):n[s]=Wp(n[s],e),await this.persistence.save(Pe(n)))})}async commit(e){await this.mutationMutex.run(async()=>{let n=new Map(Pe(await this.persistence.load()).map(s=>[B(s),s])),r=e.map(s=>{let i=n.get(B(s));return!i||Po(i,s)?s:{...s,windows:i.windows.map(o=>({...o})),observedAt:i.observedAt,freshness:i.freshness}});await this.persistence.save(Pe(r))})}},Ro=new Mn;var Oo=async t=>{let{runSubagent:e}=await import("./runner-PLVZDGHB.js");return e({task:t.task,role:t.role,backend:t.backend,cwd:t.cwd,workspace:t.workspace??null,ref:t.ref,signal:t.signal,onNotice:t.onNotice,parent:{backend:t.parent.backend,model:t.parent.model??null,provider:t.parent.provider??null,env:t.parent.env,project:t.parent.env.CORTEX_PROJECT||void 0}})};var Hp=new ut(void 0,Ge,Be,{agentDir:He,prepareAgentDir:t=>as({agentDir:t}),userModelsPath:os,usageStore:Ro,submitRateLimit:An,openBundledMcpServer:ze,getSubagentModelEnv:Vt,subagent:{runForeignSubagent:Oo,startBackgroundSubagent:t=>me.start?me.start(t):Promise.reject(new Error("run_in_background is unavailable in this session.")),stopBackgroundSubagent:t=>me.stop?me.stop(t):Promise.resolve(null)}}),me={};function W_(t){me.start=t?.startBackgroundSubagent,me.stop=t?.stopBackgroundSubagent}var Gp=new rt({onRateLimit:An});function Mo(){return Gp}function kt(){return Hp}function Ln(){return{currentDateTime:new Date().toLocaleString("en-US",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})}}function St(t){let e=Ln();return t.replace(/\{\{(\w+)\}\}/g,(n,r)=>r in e?e[r]:n)}function Lo(t,e){return t.replace(/\{\{#if (\w+)\}\}([\s\S]*?)\{\{\/if\}\}/g,(r,s,i)=>e[s]?i:"").replace(/\{\{(\w+)\}\}/g,(r,s)=>e[s]||"")}import*as Do from"path";var zp=Do.join(I,"rules");function jo(t=zp,e=Ts()){return ws(t,e).filter(n=>n.paths.length===0).map(n=>n.body)}import{readFileSync as Vp,statSync as Jp}from"fs";import*as $o from"path";var Uo=$o.join(hr,"user","USER.md"),_t=null,No=0;function Xp(){try{let t=Jp(Uo);return t.mtimeMs===No&&_t!==null||(_t=Vp(Uo,"utf8"),No=t.mtimeMs),_t}catch{return null}}function Bo(){if(h().disableUserContext)return null;let t=Xp();return t?`[User Context]
57
- ${t}
58
- [/User Context]`:null}function Fo(t,e={}){let n=[...e.rules??[]],r=t.appendSystemPrompt?.trim();return r&&n.push(r),e.workspace&&n.push(e.workspace),n.length>0?n.join(`
59
-
60
- ---
61
-
62
- `):void 0}function Wo(t){return t?jo():[]}function tb(t,e,n={}){let r=Lo(t.promptTemplate||"{{input}}",{input:e,...Ln()});return[...n.resumed?[]:Qp(t,n),r].join(`
63
-
64
- `).trim()}function Qp(t,e){return[e.userContext,t.directive?St(t.directive):null,e.project?Yp(e.project):null,e.transcriptDir?Zp(e.transcriptDir):null,e.board?tf(e.board):null,e.team?qp(e.team.roster,e.team.unread):null,e.worker?ef(e.worker):null].filter(n=>!!n)}function nb(t){return t?Bo():null}function Yp(t){return`[Session Project] This session is bound to the project "${t.id}".
65
- Project context directory: ${t.contextDir}
66
- Treat messages in this session as pertaining to this project unless stated otherwise, and record project-related findings and status updates there.`}function Zp(t){return`[Session Transcripts] The full transcript of any Cortex session is at ${t}/<sessionId>.jsonl.`}function qp(t,e){let n=`[Team] You lead these workers (persistent sessions you manage with the worker_* tools):
67
- ${t.length>0?t.join(`
68
- `):"- (no active workers)"}
69
- Rules:
70
- 1. After dispatching work, end your turn. Worker reports and questions wake you as they arrive. Updates a worker marks routine do not wake you; they appear under [Unread routine updates] on your next turn. Never poll or wait.
71
- 2. Continue a worker with worker_send when the topic and code area are the same and its context is still relevant; otherwise write a self-contained handoff and spawn a fresh one.
72
- 3. Answer workers' questions and approve their plans yourself with worker_answer; ask the user with cortex_ask_user only when you are unsure what they would want.
73
- 4. Do not run repeated review loops on a worker's output.`;return e?`${n}
74
-
75
- ${e}`:n}function ef(t){return`[Worker] You are worker "${t.name}" of the lead session "${t.lead}". Each final reply is delivered to the lead and wakes it. If a turn has nothing new for the lead (a stale or duplicate signal, a routine check, work still running with no change), call mark_routine before your final reply: the reply is then recorded for the lead without waking it. Ask for decisions with cortex_ask_user; they are handled by the lead, as are your plan approvals. The user may also open this session and talk to you directly. Keep final replies concise: conclusions, output paths, and open items. You cannot create workers yourself.`}function tf(t){return[`[Board] This session is bound to the board "${t.title}" (${t.id}).`,`Board directory: ${t.dir}`," board.html \u2014 the page body you edit (HTML, body content only); images go in assets/"," decisions.jsonl \u2014 written by the server from send_decision; do not edit","","Read board.html before anything else. Update it at milestones and whenever the status changes. Take every time you write from the clock (current_time), never from memory. Prefer the preset component classes from the board skill."].join(`
76
- `)}import{createHash as Hm}from"node:crypto";import E from"node:fs";import y from"node:path";import am from"node:fs";import _ from"node:path";var nf="https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",Ko="https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",Ho=new Set(["$schema","name","version","description","author","homepage","repository","license","keywords","extensions"]),rf=/^(?!.*(?:--|\.\.))[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/,sf=/^(?:\.\/|\$\{PLUGIN_ROOT\}(?:\/|$)|\$\{PLUGIN_DATA\}(?:\/|$))/,of=new Set(["PLUGIN_ROOT","PLUGIN_DATA"]),af=d.object({name:d.string().optional(),email:d.string().optional(),url:d.string().optional()}).strict(),uf=d.record(d.string(),d.record(d.string(),d.unknown())),Go=d.object({$schema:d.literal(nf),name:d.string().min(1).max(64).regex(rf),version:d.string().optional(),description:d.string().optional(),author:af.optional(),homepage:d.string().optional(),repository:d.string().optional(),license:d.string().optional(),keywords:d.array(d.string()).optional(),extensions:uf.optional()}).strict();function lf(t,e){for(let n of Object.keys(t))of.has(n.toUpperCase())&&e.addIssue({code:d.ZodIssueCode.custom,path:[n],message:`Reserved env key ${n} is not allowed`})}var cf=d.object({type:d.literal("stdio"),command:d.string().min(1),args:d.array(d.string()).optional(),env:d.record(d.string(),d.string()).superRefine(lf).optional(),cwd:d.string().regex(sf).optional()}).strict(),zo=d.record(d.string(),d.string()),df=d.object({type:d.literal("streamable-http"),url:d.string().min(1),headers:zo.optional()}).strict(),pf=d.object({type:d.literal("sse"),url:d.string().min(1),headers:zo.optional()}).strict(),Dn=d.union([cf,df,pf]),Vo=d.object({$schema:d.literal(Ko),mcpServers:d.record(d.string(),d.unknown())}).strict(),ib=d.object({$schema:d.literal(Ko),mcpServers:d.record(d.string(),Dn)}).strict();import ff from"node:fs";import Un from"node:path";import Yo from"node:net";import{validateHeaderName as mf,validateHeaderValue as hf}from"node:http";function k(t,e,n,r){return{code:t,scope:e,path:n,message:r}}function bt(t){return t.reduce((e,n)=>typeof n=="number"?`${e}[${n}]`:e?`${e}.${String(n)}`:String(n),"")}var Jo=Symbol("skillRoot");function Tt(t,e,n){let r={name:t.name,dir:t.dir,description:t.description,origin:n};return Object.defineProperty(r,Jo,{value:e,enumerable:!1}),r}function Ae(t){return t[Jo]??null}var Xo=Symbol("pluginMcpRuntime");function jn(t,e){return Object.defineProperty(t,Xo,{value:e,enumerable:!1}),t}function Qo(t){return t[Xo]??null}function G(t){return cs(t.manifest.name?.trim()||t.id)}function qo(t){return t.issues.map(e=>`${bt(e.path)||"(root)"}: ${e.message}`).join("; ")}function gf(t,e){return Un.join(t,"data","plugin-data",e)}function Nn(t,e,n){let r={PLUGIN_ROOT:e,PLUGIN_DATA:n};return t.replace(/\$\{(PLUGIN_ROOT|PLUGIN_DATA)\}/g,(s,i)=>r[i])}function yf(t,e,n){let r=Nn(t,e,n);return t.startsWith("${PLUGIN_ROOT}")?U(e,r):t.startsWith("${PLUGIN_DATA}")?U(n,r):r}function kf(t,e,n){return(t??[]).map(r=>Nn(r,e,n))}function Sf(t,e,n){let r={};for(let[s,i]of Object.entries(t??{}))r[s]=Nn(i,e,n);return r.PLUGIN_ROOT=e,r.PLUGIN_DATA=n,r}function _f(t){return Un.basename(t)}function bf(t){return t.includes("/")||t.includes("\\")}function Tf(t,e){return e.startsWith("./")?zt(t,e):bf(e)?null:e}function wf(t,e,n){return n?n.startsWith("./")?zt(t,n):yf(n,t,e):t}function xf(t){return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function vf(t){let e=xf(t);return e==="localhost"?!0:Yo.isIP(e)===4?e.startsWith("127."):Yo.isIP(e)!==6?!1:e==="::1"||e.toLowerCase()==="0:0:0:0:0:0:0:1"}function Ef(t){return t.protocol==="https:"||t.protocol==="http:"&&vf(t.hostname)}function If(t){return!!(t.username||t.password||t.hash)}function Cf(t){return Ef(t)&&!If(t)}function Pf(t){try{let e=new URL(t);return Cf(e)?e:null}catch{return null}}function Af(t,e){let n=e.toLowerCase();return t.has(n)?!1:(t.add(n),!0)}function Rf(t,e){try{return mf(t),hf(t,e),!0}catch{return!1}}function Of(t,e,n){return Af(t,e)&&Rf(e,n)}function Mf(t){let e=t??{},n=new Set;for(let[r,s]of Object.entries(e))if(!Of(n,r,s))return null;return Object.keys(e).sort()}function Lf(t,e,n,r){let s=e,i=Tf(t,r.command),o=kf(r.args,t,s),a=Sf(r.env,t,s),u=wf(t,s,r.cwd);return!i||!u?null:jn({name:n,type:"stdio",summary:{command:_f(i),argsCount:o.length,envKeys:Object.keys(a).sort()}},{command:i,args:o,env:a,cwd:u})}function Df(t,e){let n=Pf(e.url),r=Mf(e.headers);return!n||!r?null:jn({name:t,type:e.type,summary:{origin:n.origin,headerKeys:r}},{url:e.url,headers:e.headers??{}})}function jf(t,e,n,r){return r.type==="stdio"?Lf(t,e,n,r):Df(n,r)}function Uf(t){let e=Un.join(t,"mcp.json");if(!j(e))return{};let n=U(t,e);if(!n||!se(n))return{issue:k("mcp_invalid","mcp","mcp.json","mcp.json must be a regular file inside the plugin root")};try{return{text:ff.readFileSync(n,"utf8")}}catch{return{issue:k("mcp_invalid","mcp","mcp.json","mcp.json could not be read")}}}function Zo(t){return t.match(/\/schemas\/([^/]+)\//)?.[1]??""}function Nf(t,e){try{let n=JSON.parse(t),r=Vo.safeParse(n);return r.success?Zo(r.data.$schema)!==Zo(e)?{issue:k("mcp_invalid","mcp","mcp.json","mcp.json schema does not match plugin.json")}:{value:r.data}:{issue:k("mcp_invalid","mcp","mcp.json",qo(r.error))}}catch{return{issue:k("mcp_invalid","mcp","mcp.json","mcp.json is not valid JSON")}}}function $f(t,e,n){let r=[],s=[];for(let[i,o]of Object.entries(n).sort(([a],[u])=>a.localeCompare(u))){let a=Dn.safeParse(o);if(!a.success){s.push(k("mcp_server_invalid","server",`mcpServers.${i}`,qo(a.error)));continue}let u=jf(t,e,i,a.data);if(!u){s.push(k("mcp_server_invalid","server",`mcpServers.${i}`,"server violates URL or containment rules"));continue}r.push(u)}return{servers:r,issues:s}}function $n(t,e,n,r){let s=Uf(e);if(s.issue)return{status:"invalid",servers:[],issues:[s.issue]};if(s.text===void 0)return{status:"missing",servers:[],issues:[]};let i=Nf(s.text,r);if(i.issue||!i.value)return{status:"invalid",servers:[],issues:i.issue?[i.issue]:[]};let o=$f(e,gf(n,t),i.value.mcpServers);return{status:"valid",servers:o.servers,issues:o.issues}}var ta=ku(Su(),1);import ea from"node:fs";import Bf from"node:path";var Ff=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,Wf=/^(?!.*--)[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/,Kf=new Set(["name","description","license","compatibility","metadata","allowed-tools"]);function na(t){return`skills.${t}.SKILL.md`}function xt(t,e){return{code:"skill_invalid",scope:"skill",path:na(t),message:e}}function ra(t,e){return{code:"skill_frontmatter_ignored",scope:"skill",path:na(t),message:e}}function sa(t){let e=Ff.exec(t);if(!e)return null;try{let n=(0,ta.parse)(e[1]);return J(n)?n:null}catch{return null}}function Hf(t,e){return t!==void 0&&!(typeof t=="string"&&t===e)}function ia(t){return typeof t=="string"&&t.trim().length>0}function vt(t,e,n){return[ra(t,`SKILL.md frontmatter ${e} ${n}`)]}function Gf(t,e){let n=Object.keys(e).filter(r=>!Kf.has(r)).sort();return n.length===0?[]:[ra(t,`SKILL.md frontmatter has fields outside the spec, ignored: ${n.join(", ")}`)]}function zf(t,e){let n=[];return e.name===void 0?n.push(...vt(t,"name","is absent; the directory name is used")):typeof e.name=="string"&&(e.name.length>64||!Wf.test(e.name))&&n.push(...vt(t,"name","is not a canonical Agent Skills name")),typeof e.description=="string"&&e.description.length>1024&&n.push(...vt(t,"description","exceeds the 1024-character guidance")),n}function Vf(t){return J(t)?Object.values(t).every(e=>typeof e=="string"):!1}function wt(t,e,n,r,s){n&&t.push(...vt(e,r,s))}function Jf(t,e){let n=[];return wt(n,t,e.license!==void 0&&typeof e.license!="string","license","must be a string when present"),wt(n,t,e.compatibility!==void 0&&(!ia(e.compatibility)||String(e.compatibility).length>500),"compatibility","must be 1-500 characters when present"),wt(n,t,e.metadata!==void 0&&!Vf(e.metadata),"metadata","must be a string-to-string map when present"),wt(n,t,e["allowed-tools"]!==void 0&&!Xf(e["allowed-tools"]),"allowed-tools","should be a comma-separated string"),n}function Xf(t){return typeof t=="string"||Array.isArray(t)&&t.every(e=>typeof e=="string")}function Qf(t,e){return e?Hf(e.name,t)?[xt(t,"SKILL.md frontmatter name must match the skill directory")]:ia(e.description)?[]:[xt(t,"SKILL.md frontmatter description must be non-empty")]:[xt(t,"SKILL.md must start with YAML frontmatter")]}function Yf(t,e){return[...zf(t,e),...Jf(t,e),...Gf(t,e)]}function Bn(t){try{let e=sa(ea.readFileSync(t,"utf8"));return typeof e?.description=="string"?e.description.trim():""}catch{return""}}function oa(t,e){let n;try{n=ea.readFileSync(e,"utf8")}catch{return{issues:[xt(t,"SKILL.md could not be read")]}}let r=sa(n),s=Qf(t,r);return s.length>0||!r?{issues:s}:{skill:{name:t,dir:Bf.join("skills",t),description:String(r.description).trim()},issues:Yf(t,r)}}import{createHash as Zf}from"node:crypto";import S from"node:fs";import F from"node:path";function qf(t){return Zf("sha256").update(t).digest("hex")}function Wn(t,e){let n=S.realpathSync(e);if(!vs(t,n))throw new Error(`Skill path escapes plugin root: ${e}`);return n}function em(t,e){if(!t.isFile())throw new Error(`Skill path is not a file: ${e}`)}function ua(t,e,n){if(t.dev!==e.dev||t.ino!==e.ino)throw new Error(`Skill file changed while being read: ${n}`)}function Et(t){return`${t.size}:${t.mtimeMs}:${t.ctimeMs}:${t.ino}:${t.mode&511}`}var tm=S.constants.O_RDONLY|(S.constants.O_NOFOLLOW??0);function la(t,e){let n=Wn(t,e),r=S.openSync(n,tm);try{let s=S.fstatSync(r);return em(s,n),ua(s,S.lstatSync(e),e),{fd:r,stat:S.fstatSync(r)}}catch(s){throw S.closeSync(r),s}}function Kn(t,e,n,r){let{fd:s,stat:i}=la(t,n);try{e.push({path:r,signature:Et(i),size:i.size,mode:i.mode&511})}finally{S.closeSync(s)}}function Hn(t,e,n,r,s,i){let o=Wn(t,e);if(r.has(o))throw new Error(`Skill tree contains a symlink cycle: ${n||"."}`);let a=new Set(r).add(o);n&&s.push(n);for(let u of S.readdirSync(e).sort())rm(t,F.join(e,u),F.posix.join(n,u),a,s,i)}function nm(t,e,n,r,s,i){let o=Wn(t,e),a=S.statSync(o);if(a.isDirectory())return Hn(t,o,n,r,s,i);if(a.isFile())return Kn(t,i,o,n);throw new Error(`Skill path is not a file or directory: ${n}`)}function rm(t,e,n,r,s,i){let o=S.lstatSync(e);if(o.isSymbolicLink())return nm(t,e,n,r,s,i);if(o.isDirectory())return Hn(t,e,n,r,s,i);if(o.isFile())return Kn(t,i,e,n);throw new Error(`Skill path is not a file or directory: ${n}`)}function ca(t,e){return qf(JSON.stringify({dirs:t,files:e}))}function It(t,e){let n=[],r=[];return Hn(S.realpathSync(t),e,"",new Set,n,r),n.sort(),r.sort((s,i)=>s.path.localeCompare(i.path)),{dirs:n,files:r,sha256:ca(n,r)}}function Fn(t){S.mkdirSync(t,{recursive:!0,mode:448}),S.chmodSync(t,448)}function sm(t,e,n,r,s){let{fd:i,stat:o}=la(t,e);try{if(s&&Et(o)!==r.signature)throw new Error(`Skill file changed after validation: ${e}`);if(o.size!==r.size||(o.mode&511)!==r.mode)throw new Error(`Skill file changed after validation: ${e}`);let a=S.readFileSync(i),u=S.fstatSync(i);if(ua(o,u,e),u.size!==r.size||Et(u)!==Et(o))throw new Error(`Skill file changed while being read: ${e}`);S.writeFileSync(n,a,{mode:r.mode}),S.chmodSync(n,r.mode)}finally{S.closeSync(i)}}function Gn(t,e,n,r,s={}){Fn(r);for(let i of n.dirs)Fn(F.join(r,i));for(let i of n.files)Fn(F.dirname(F.join(r,i.path))),sm(t,F.join(e,i.path),F.join(r,i.path),i,s.requireSourceSignature===!0)}function im(t,e,n,r,s){n&&r.push(n);for(let i of S.readdirSync(e).sort())da(t,F.join(e,i),F.posix.join(n,i),r,s)}function da(t,e,n,r,s){let i=S.lstatSync(e);if(i.isSymbolicLink())throw new Error(`Portable projection target is invalid: ${e}`);if(i.isDirectory())return im(t,e,n,r,s);if(i.isFile())return Kn(t,s,e,n);throw new Error(`Portable projection target is invalid: ${e}`)}function om(t){let e=[],n=[];return da(t,t,"",e,n),e.sort(),n.sort((r,s)=>r.path.localeCompare(s.path)),{dirs:e,files:n,sha256:ca(e,n)}}function aa(t){return JSON.stringify({dirs:t.dirs,files:t.files.map(({path:e,size:n,mode:r})=>({path:e,size:n,mode:r}))})}function zn(t,e){let n=S.lstatSync(t);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`Portable projection target is invalid: ${t}`);let r=om(t);if(aa(r)!==aa(e))throw new Error(`Portable projection skill tree mismatch: ${t}`)}function um(t){return _.join("plugins",t)}function W(t){return{id:t,origin:"local",kind:"unknown",rootDir:um(t),valid:!1,manifest:{source:"none"},skills:[],mcp:{status:"missing",servers:[]},issues:[]}}function Ct(t){if(typeof t!="string")return;let e=t.trim();return e.length>0?e:void 0}function lm(t){return t.issues.map(e=>k("manifest_invalid","manifest",bt(e.path)||"plugin.json",e.message))}function cm(t){let e={},n=[];for(let[r,s]of Object.entries(t)){if(!Ho.has(r)){n.push(k("manifest_unknown_field","manifest",`plugin.json.${r}`,`Ignoring unknown field "${r}"`));continue}if(r==="extensions"&&!J(s)){n.push(k("manifest_extensions_ignored","manifest","plugin.json.extensions","Ignoring non-object extensions field"));continue}e[r]=s}return{sanitized:e,issues:n}}function dm(t){try{let e=JSON.parse(t);if(!J(e))return pa("plugin.json must contain a top-level object");let n=cm(e),r=Go.safeParse(n.sanitized);return r.success?{manifest:pm(r.data),valid:!0,issues:n.issues}:{manifest:{source:"root"},valid:!1,issues:[...n.issues,...lm(r.error)]}}catch{return pa("plugin.json is not valid JSON")}}function pm(t){return{source:"root",name:t.name,schema:t.$schema,version:Ct(t.version),description:Ct(t.description)}}function pa(t){return{manifest:{source:"root"},valid:!1,issues:[k("manifest_invalid","manifest","plugin.json",t)]}}function fm(t){try{let e=JSON.parse(t);return!J(e)||typeof e.name!="string"||e.name.trim()===""?fa("legacy manifest must define a non-empty name"):{manifest:{source:"legacy",name:e.name.trim(),version:Ct(e.version),description:Ct(e.description)},valid:!0,issues:[]}}catch{return fa("legacy manifest is not valid JSON")}}function fa(t){return{manifest:{source:"legacy"},valid:!1,issues:[k("legacy_manifest_invalid","manifest",".claude-plugin/plugin.json",t)]}}function mm(t){return k("manifest_invalid","manifest",t,`${t} must be a regular file inside the plugin root`)}function ha(t,e){let n=_.join(t,e);if(!j(n))return{state:"missing",issues:[]};let r=U(t,n);return!r||!se(r)?{state:"invalid",issues:[mm(e)]}:{state:"present",path:r,issues:[]}}function Vn(t){return k("skill_invalid","skill","skills",t)}function hm(t){let e=_.join(t,"skills");if(!j(e))return{state:"missing",issues:[]};let n=U(t,e);return n?Je(n)?{state:"present",path:n,issues:[]}:{state:"invalid",issues:[Vn("skills must be a directory inside the plugin root")]}:{state:"invalid",issues:[Vn("skills must resolve to a directory inside the plugin root")]}}function gm(t){try{return{names:X(t),issues:[]}}catch{return{names:[],issues:[Vn("skills could not be read")]}}}function Jn(t,e){let n=hm(t);if(n.state!=="present"||!n.path)return{skills:[],issues:n.issues};let r=gm(n.path),s=[],i=[...r.issues];for(let o of r.names){let a=km(t,n.path,o,e);a.skill&&s.push(Tt(a.skill,t,"local")),i.push(...a.issues)}return{skills:s,issues:i}}function ym(t,e,n){let r=oa(e,n);if(!r.skill)return r;try{return It(t,_.dirname(n)),r}catch(s){let i=s instanceof Error?s.message:String(s);return{issues:[...r.issues,k("skill_invalid","skill",`skills.${e}`,`Skill support tree is invalid: ${i}`)]}}}function km(t,e,n,r){let s=_.join(e,n,"SKILL.md"),i=U(t,s);return!i||!se(i)?{issues:[k("skill_outside_plugin_root","skill",`skills.${n}.SKILL.md`,"SKILL.md must remain inside the plugin root")]}:r==="legacy"?{skill:{name:n,dir:_.join("skills",n),description:Bn(i)},issues:[]}:ym(t,n,i)}function Sm(t,e,n,r){let s=W(t),i=dm(r);if(s.kind="portable",s.manifest=i.manifest,s.issues.push(...i.issues),!i.valid||!i.manifest.schema)return s;let o=Jn(e,"portable"),a=$n(t,e,n,i.manifest.schema);return s.valid=!0,s.skills=o.skills,s.mcp={status:a.status,servers:a.servers},s.issues.push(...o.issues,...a.issues),s}function _m(t,e,n){let r=W(t),s=fm(n);if(r.kind="legacy",r.manifest=s.manifest,r.issues.push(...s.issues),!s.valid)return r;let i=Jn(e,"legacy");return r.valid=!0,r.skills=i.skills,r.issues.push(...i.issues),r}function bm(t){let e=W(t);return e.issues.push(k("manifest_missing","manifest",null,"plugin.json and .claude-plugin/plugin.json are both missing")),e}function ga(t,e,n){try{return{text:am.readFileSync(t,"utf8"),issues:[]}}catch{return{issues:[k(e,"manifest",n,`${n} could not be read`)]}}}function ya(t,e){let n=U(t,e);return n&&Je(n)?n:null}function ka(t,e){let n=W(t),s=j(e)?"plugin_root_outside_plugins_dir":"plugin_root_not_directory",i=s==="plugin_root_outside_plugins_dir"?"plugin root must resolve inside PLUGINS_DIR":"plugin root must be a directory";return n.issues.push(k(s,"plugin",t,i)),n}function Tm(t,e,n,r){let s=ga(r,"manifest_invalid","plugin.json");if(s.text!==void 0)return Sm(t,e,n,s.text);let i=W(t);return i.kind="portable",i.manifest={source:"root"},i.issues.push(...s.issues),i}function wm(t,e,n){let r=ga(n,"legacy_manifest_invalid",".claude-plugin/plugin.json");if(r.text!==void 0)return _m(t,e,r.text);let s=W(t);return s.kind="legacy",s.manifest={source:"legacy"},s.issues.push(...r.issues),s}function xm(t,e,n){let r=ha(e,"plugin.json");if(r.state==="invalid"){let s=W(t);return s.kind="portable",s.manifest={source:"root"},s.issues.push(...r.issues),s}return r.state!=="present"||!r.path?null:Tm(t,e,n,r.path)}function vm(t,e){let n=ha(e,_.join(".claude-plugin","plugin.json"));if(n.state==="invalid"){let r=W(t);return r.kind="legacy",r.manifest={source:"legacy"},r.issues.push(...n.issues),r}return n.state!=="present"||!n.path?null:wm(t,e,n.path)}function Em(t,e,n){let r=_.join(e,t),s=ya(e,r);return s?xm(t,s,n)??vm(t,s)??bm(t):ka(t,r)}function Sa(t,e,n){try{return Em(t,e,n)}catch{let r=W(t);return r.issues.push(k("manifest_invalid","manifest","plugin.json","plugin entry could not be loaded")),r}}function ma(t){return t&&Je(t)?M(t):null}function Im(t){let e=t.builtin?X(t.builtin):[],n=t.user?X(t.user):[];return[...new Set([...e,...n])].sort()}function Cm(t,e){return t.name<e.name?-1:t.name>e.name?1:0}function Pm(t,e){let n=new Map(t.skills.map(r=>[r.name,r]));for(let r of e.skills)n.set(r.name,Tt(r,Ae(r),n.has(r.name)?"overridden":"local"));t.skills=[...n.values()].sort(Cm),t.issues.push(...e.issues)}function Am(t,e,n){if(!j(_.join(e,"mcp.json"))||!t.manifest.schema)return;let r=$n(t.id,e,n,t.manifest.schema);t.mcp={status:r.status,servers:r.servers},t.issues=[...t.issues.filter(s=>s.scope!=="mcp"&&s.scope!=="server"),...r.issues]}function Rm(t,e,n){let r=e?_.join(e,t.id):null;if(!r||!j(r))return t;let s=ya(e,r);return s?(t.kind==="portable"&&t.valid&&(Pm(t,Jn(s,"portable")),Am(t,s,n)),t):{...t,issues:[...t.issues,...ka(t.id,r).issues]}}function Om(t,e){let n=Sa(t,e.builtin,e.dataDir),r={...n,origin:"builtin",skills:n.skills.map(s=>Tt(s,Ae(s),"builtin"))};return Rm(r,e.user,e.dataDir)}function Mm(t,e){return e.builtin&&j(_.join(e.builtin,t))?Om(t,e):Sa(t,e.user,e.dataDir)}function Xn(t={}){let e={user:ma(_.resolve(t.pluginsDir??ge)),builtin:ma(t.builtinDir===void 0?Xe():t.builtinDir),dataDir:_.resolve(t.dataDir??I)},n=Im(e).filter(r=>!t.ids||t.ids.has(r)).map(r=>Mm(r,e));return Lm(n),n}function Lm(t){let e=new Map;for(let n of t){if(n.kind!=="portable"||!n.valid)continue;let r=G(n);e.set(r,[...e.get(r)??[],n.id])}for(let n of t){if(n.kind!=="portable"||!n.valid)continue;let r=(e.get(G(n))??[]).filter(s=>s!==n.id);r.length!==0&&n.issues.push(k("manifest_name_duplicate","manifest","plugin.json.name",`Plugin name "${G(n)}" is also used by ${r.map(s=>`'${s}'`).join(", ")}; a session that selects more than one of them loads only the first selected.`))}}function Dm(t){return[...t].sort((e,n)=>e.localeCompare(n))}function jm(t){let e=_.join(t,"skills");return X(e).filter(n=>se(_.join(e,n,"SKILL.md"))).map(n=>({name:n,description:Bn(_.join(e,n,"SKILL.md"))}))}function Um(t){return[...t].sort((e,n)=>e.name.localeCompare(n.name))}function Nm(t,e){let n=new Map;for(let r of t){let s=_.join(e,r.id);n.set(s,r);let i=M(s);i&&n.set(i,r)}return n}function $m(t,e,n){if(n?.kind==="portable"&&!n.valid)return[];let r=n?.id??t,s=n?G(n):_.basename(e),i=n?.kind==="portable"?n.skills:jm(e);return Um(i).map(o=>({plugin:r,namespace:s,name:o.name,description:o.description}))}function _a(t,e,n,r){let s=Nm(t,e),i=[],o=new Set;for(let a of r){let u=_.isAbsolute(a)?_.resolve(a):_.resolve(n,a),l=M(u)??u;o.has(l)||(o.add(l),i.push($m(a,l,s.get(u)??s.get(l))))}return i.filter(a=>a.length>0)}function ba(t){let e=_.resolve(t.pluginsDir??ge),n=_.resolve(t.dataDir??I);return{entries:Xn({pluginsDir:e,dataDir:n,builtinDir:t.builtinDir}),pluginsDir:e,dataDir:n}}function jb(t){let{entries:e,pluginsDir:n,dataDir:r}=ba(t);return _a(e,n,r,t.pluginDirs).flat()}function Ub(t={}){let{entries:e,pluginsDir:n,dataDir:r}=ba(t);return t.pluginDirs?_a(e,n,r,t.pluginDirs).map(s=>({plugin:s[0].plugin,skills:s.map(i=>i.name)})):e.filter(s=>s.valid&&s.skills.length>0).map(s=>({plugin:s.id,skills:Dm(s.skills.map(i=>i.name))}))}import At from"node:fs";import Pt from"node:path";var Yn=m("plugin-runtime"),Bm=10080*60*1e3,Fm=3600*1e3,Ta=/^(plugin|skill)_/,Wm=/^[0-9a-f]{64}\.json(?:\.tmp\..+)?$/,wa=["claude-mcp","claude-mcp-proxies"],xa=new Map;function Zn(t){try{let e=new Date;At.utimesSync(t,e,e)}catch{}}function Qn(t,e){try{return At.readdirSync(t).filter(n=>e.test(n)).map(n=>Pt.join(t,n))}catch{return[]}}function Km(t,e,n){try{let r=At.lstatSync(t);return n(r)&&e-r.mtimeMs>=Bm}catch{return!1}}function va(t,e){return e-(xa.get(t)??0)<Fm?!0:(xa.set(t,e),!1)}function Ea(t,e,n,r){let s=[];for(let i of t)if(!(e.has(i)||!Km(i,n,r)))try{At.rmSync(i,{recursive:!0,force:!0}),s.push(i)}catch(o){Yn.warn(`Could not remove stale plugin runtime entry ${i}: ${o.message}`)}return s}function Ia(t,e,n=Date.now()){if(va(t,n))return[];let r=[...Qn(t,Ta),...Qn(Pt.join(t,"skill-snapshots"),Ta)],s=Ea(r,e,n,i=>i.isDirectory());return s.length>0&&Yn.info(`Removed ${s.length} stale plugin runtime dir(s) under ${t}`),s}function Ca(t,e=Date.now()){if(va(Pt.join(t,wa[0]),e))return[];let n=wa.flatMap(s=>Qn(Pt.join(t,s),Wm)),r=Ea(n,new Set,e,s=>s.isFile());return r.length>0&&Yn.info(`Removed ${r.length} stale Claude MCP config(s) under ${t}`),r}var Rt=m("plugin-runtime");function Oe(t,e){Rt.warn(e),t.push(e)}function Gm(t){return JSON.stringify(t)}function zm(t){return`[${t.map(e=>Re(e)??"null").join(",")}]`}function Vm(t){return`{${Object.keys(t).sort().flatMap(n=>{let r=Re(t[n]);return r===void 0?[]:[`${JSON.stringify(n)}:${r}`]}).join(",")}}`}function Re(t){return t===null||typeof t!="object"?Gm(t):Array.isArray(t)?zm(t):Vm(t)}function Ma(t){let e=Re(t);if(e===void 0)throw new TypeError("Value is not JSON-serializable");return Hm("sha256").update(e,"utf8").digest("hex")}function Pa(t){return t.length>0?t:void 0}function La(t,e){return y.isAbsolute(e)?y.resolve(e):y.resolve(t,e)}function Jm(t){return t!=="none"}function Xm(t,e){let n=new Map;for(let r of e){let s=y.resolve(t,r.id);n.set(r.id,{absolute:s,real:M(s)??s})}return n}function Qm(t,e){let n=new Map,r=new Map;for(let s of t){let i=e.get(s.id);i&&(n.set(i.absolute,s),r.set(i.real,s))}return{byAbsolute:n,byRealpath:r}}function Ym(t,e){return ye([t.id,e],"plugin")}function Zm(t,e,n,r){if(!("command"in n)||!("cwd"in n))throw new Error(`Portable MCP runtime mismatch for '${t.id}/${e.name}'`);let s=n.env.PLUGIN_DATA;if(!s)throw new Error(`Portable MCP PLUGIN_DATA missing for '${t.id}/${e.name}'`);return v(s,"Portable plugin data"),{name:r,type:"stdio",command:n.command,args:[...n.args],env:{...n.env},cwd:n.cwd}}function qm(t,e){let n=Qo(e);if(!n)throw new Error(`Portable MCP runtime missing for '${t.id}/${e.name}'`);let r=Ym(t,e.name);if(e.type==="stdio")return Zm(t,e,n,r);if(!("url"in n))throw new Error(`Portable MCP runtime mismatch for '${t.id}/${e.name}'`);return{name:r,type:e.type,url:n.url,headers:{...n.headers}}}function eh(t,e,n){try{let r=Ae(e);if(!r)throw new Error("its plugin layer is unknown");let s=y.join(r,e.dir),i=M(s)??s,o=It(r,i);return{name:e.name,root:r,target:i,contentSha256:o.sha256,tree:o}}catch(r){return Oe(n,`Skipping portable skill '${t.entry.id}/${e.name}': ${r.message}`),null}}function th(t,e){return t.entry.skills.flatMap(n=>{let r=eh(t,n,e);return r?[r]:[]})}function nh(t,e){return Ma({pluginId:t.entry.id,manifest:Da(t.entry),skills:e.map(n=>({name:n.name,sha256:n.contentSha256}))})}function Da(t){let e=ds(t.manifest.version);return`${JSON.stringify({name:G(t),...e?{version:e}:{},...t.manifest.description?{description:t.manifest.description}:{}},null,2)}
77
- `}function rh(t){return E.readdirSync(t).sort((e,n)=>e.localeCompare(n))}function qn(t){let e=E.lstatSync(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Claude projection target is invalid: ${t}`)}function er(t,e,n){if(Re(rh(t))!==Re(e))throw new Error(`Claude projection ${n} mismatch: ${t}`)}function sh(t,e){let n=y.join(t,".claude-plugin");if(qn(n),er(n,["plugin.json"],"manifest directory"),E.readFileSync(y.join(n,"plugin.json"),"utf8")!==e)throw new Error(`Claude projection manifest mismatch: ${t}`)}function ih(t,e){let n=y.join(t,"skills");qn(n);let r=e.map(s=>s.name).sort((s,i)=>s.localeCompare(i));er(n,r,"skill set");for(let s of e)zn(y.join(n,s.name),s.tree)}function oh(t,e,n){qn(t),er(t,[".claude-plugin","skills"],"root"),sh(t,e),ih(t,n)}function ja(t){v(t,"Claude projection"),v(y.join(t,".claude-plugin"),"Claude projection"),v(y.join(t,"skills"),"Claude projection")}function ah(t,e,n){ja(t),pr(y.join(t,".claude-plugin","plugin.json"),e);for(let r of n)Gn(r.target,r.target,r.tree,y.join(t,"skills",r.name))}function uh(t,e,n){let r=nh(e,n);return y.join(t,ye([e.entry.id,r],"plugin"))}function Ua(t,e){let n=`${process.pid}:${Date.now()}:${Math.random()}`;return y.join(t,ye([y.basename(e),n],"plugin_tmp"))}function lh(t,e,n,r){let s=Ua(y.dirname(r),r);E.mkdirSync(s,{mode:448});try{return ah(s,n,e),E.renameSync(s,r),!0}catch(i){if(E.rmSync(s,{recursive:!0,force:!0}),!E.existsSync(r))throw i;return!1}}function Aa(t,e,n){return oh(t,e,n),ja(t),t}function ch(t,e,n){let r=ye([e.entry.id,n.name,n.contentSha256],"skill");return y.join(t,r,n.name)}function dh(t,e,n){let r=Ua(y.dirname(n),n);try{return Gn(e.root,e.target,e.tree,r,{requireSourceSignature:!0}),E.renameSync(r,n),!0}catch(s){if(E.rmSync(r,{recursive:!0,force:!0}),!E.existsSync(n))throw s;return!1}}function Ra(t,e){return zn(t,e.tree),v(t,"Portable skill snapshot"),t}function ph(t,e,n,r){v(n,"Plugin runtime");let s=y.join(n,r,"skill-snapshots");v(s,`${r} skill snapshots`);let i=ch(s,t,e);if(v(y.dirname(i),`${r} skill snapshot`),E.existsSync(i))return Zn(y.dirname(i)),Ra(i,e);let o=dh(t,e,i);try{return Ra(i,e)}catch(a){throw o&&E.rmSync(i,{recursive:!0,force:!0}),a}}function fh(t,e,n,r,s){try{return{...e,target:ph(t,e,n,r)}}catch(i){return Oe(s,`Skipping portable skill '${t.entry.id}/${e.name}': ${i.message}`),null}}function mh(t,e,n,r,s){return e.flatMap(i=>{let o=fh(t,i,n,r,s);return o?[o]:[]})}function hh(t,e,n,r){v(n,"Plugin runtime");let s=y.join(n,r);v(s,`${r} plugin projection`);let i=Da(t.entry),o=uh(s,t,e);if(E.existsSync(o))return Zn(o),Aa(o,i,e);let a=lh(t,e,i,o);try{return Aa(o,i,e)}catch(u){throw a&&E.rmSync(o,{recursive:!0,force:!0}),u}}function gh(t,e,n,r,s){if(e.length===0)return null;try{return hh(t,e,n,r)}catch(i){return Oe(s,`Skipping portable skills for '${t.entry.id}': ${i.message}`),e.splice(0),null}}function yh(t,e,n){try{return[qm(t,e)]}catch(r){return Oe(n,`Skipping portable MCP '${t.id}/${e.name}': ${r.message}`),[]}}function kh(t,e,n,r,s,i){let o=mh(t,wh(t,th(t,i),s),n,e,i);return{skills:o,projectionDir:e==="claude"?gh(t,o,n,e,i):null,mcpServers:r?t.entry.mcp.servers.flatMap(a=>yh(t.entry,a,i)):[]}}function Sh(t,e,n,r,s,i){if(!(!r&&!s&&!i))return Ma({backend:t,pluginDirs:r??[],pluginSkillDirs:s??[],mcpServers:i??[],selected:e.map(o=>o.kind==="preserved"?{kind:o.kind,path:o.path}:{kind:o.kind,id:o.id,skills:n.get(o.id)?.skills.map(a=>({name:a.name,target:a.target,contentSha256:a.contentSha256}))??[]})})}function _h(t,e){if(!t.valid){let n=t.issues[0]?.message??"manifest is invalid";Oe(e.warnings,`Skipping plugin '${t.id}': its plugin.json is invalid (${n})`);return}e.portableSelections.has(t.id)||(e.portableSelections.set(t.id,{entry:t}),e.items.push({kind:"portable",id:t.id}))}function bh(t,e,n,r,s){if(n?.kind==="portable")return _h(n,r);n?.kind==="legacy"&&r.selectedLegacySkills.push(...n.skills.map(o=>({name:o.name,pluginId:n.id})));let i=e??t;s.has(i)||(s.add(i),r.items.push({kind:"preserved",path:i}))}function Th(t,e,n,r){let s=Qm(t,e),i={items:[],portableSelections:new Map,selectedLegacySkills:[],warnings:[]},o=new Set;for(let a of r){let u=La(n,a),l=M(u),p=s.byAbsolute.get(u)??(l?s.byRealpath.get(l):void 0);bh(u,l,p,i,o)}return i}function wh(t,e,n){let r=[];for(let s of e){let i=n.get(s.name);if(i!==void 0){Rt.warn(`Skipping skill '${s.name}' from plugin '${t.entry.id}': '${i}' is already selected and provides that name.`);continue}n.set(s.name,t.entry.id),r.push(s)}return r}function xh(t,e,n){let r=new Set(n.map(s=>s.name));for(let[s,i]of t)i===e&&!r.has(s)&&t.delete(s)}function vh(t,e){for(let n of t.mcpServers){if(e.has(n.name))throw new Error(`Duplicate portable MCP server name: ${n.name}`);e.add(n.name)}}function Eh(t,e){let n=G(e.entry),r=t.get(n);return r!==void 0?(Rt.warn(`Skipping plugin '${e.entry.id}': its name '${n}' is already used by selected plugin '${r}'.`),!1):(t.set(n,e.entry.id),!0)}function Ih(t,e,n,r){let s=new Map,i=new Map,o=new Map,a=new Set,u=[];for(let[l,p]of t){if(!Eh(i,p))continue;let c=kh(p,e,n,r,o,u);xh(o,l,c.skills),vh(c,a),s.set(l,c)}return{details:s,skillClaims:o,warnings:u}}function Ch(t,e){for(let{name:n,pluginId:r}of e){let s=t.get(n);s!==void 0&&Rt.warn(`Skill '${n}' is provided by both portable plugin '${s}' and legacy plugin '${r}'. Deselect one of them to make the choice explicit.`)}}function Ph(t,e,n){e==="claude"&&t.projectionDir&&n.pluginDirs.push(t.projectionDir),e==="pi"&&n.pluginSkillDirs.push(...t.skills.map(r=>r.target)),n.mcpServers.push(...t.mcpServers)}function Ah(t,e,n,r){if(t.kind==="preserved")return void r.pluginDirs.push(t.path);let s=e.get(t.id);s&&Ph(s,n,r)}function Rh(t,e,n){let r={pluginDirs:[],pluginSkillDirs:[],mcpServers:[]};for(let s of t)Ah(s,e,n,r);return r}function Oh(t,e,n){let r=Rh(e,n,t),s=Pa(r.pluginDirs),i=t==="pi"?Pa(r.pluginSkillDirs):void 0,o=r.mcpServers.length>0?r.mcpServers:void 0;return{pluginDirs:s,pluginSkillDirs:i,mcpServers:o,pluginCapabilityFingerprint:Sh(t,e,n,s,i,o)}}function Mh(t,e,n,r){let s=new Set;for(let o of n){let a=La(e,o);s.add(a);let u=M(a);u&&s.add(u)}let i=new Set;for(let o of new Set([...X(t),...r])){let a=y.resolve(t,o);(s.has(a)||s.has(M(a)??a))&&i.add(o)}return i}function Lh(t){let e=new Set;for(let n of t.values()){n.projectionDir&&e.add(n.projectionDir);for(let r of n.skills)e.add(y.dirname(r.target))}return e}function Na(t){let e=y.resolve(t.dataDir??I),n=y.resolve(t.pluginsDir??ge),r=be(e,e),s=be(e,t.runtimeDir??y.join(e,"data","plugin-runtime")),i=(t.selectedPluginDirs??[]).filter(f=>typeof f=="string"&&f.length>0);if(i.length===0)return{};let o=t.builtinDir===void 0?Xe():t.builtinDir,a=Mh(n,e,i,Es(o)),u=Xn({pluginsDir:n,dataDir:r,builtinDir:o,ids:a}),l=Th(u,Xm(n,u),e,i);if(l.items.length===0)return Oa({},l.warnings);let p=Ih(l.portableSelections,t.backend,s,Jm(t.mcpComposition));Ch(p.skillClaims,l.selectedLegacySkills),Ia(y.join(s,t.backend),Lh(p.details)),Ca(s);let c=Oh(t.backend,l.items,p.details);return Oa(c,[...l.warnings,...p.warnings])}function Oa(t,e){return e.length>0?{...t,warnings:e}:t}var Dh=[{plugin:"cortex-feishu",channelPrefix:"feishu:"}];function jh(t,e){if(!t)return t;if(Array.isArray(t))return t.filter(n=>{if(typeof n!="string")return!1;let r=n.split("/").filter(Boolean).pop()??"",s=Dh.find(o=>o.plugin===r);return s?!!(r==="cortex-feishu"&&e.feishuSkillsInWeb===!0&&e.channel?.startsWith("web:"))||!!e.channel?.startsWith(s.channelPrefix):!0})}function tr(t,e){if(t)return`/m/${t}/${e}`}function Uh(t,e,n){return{selection:{...e},project:t.context.project??null,trackSessionId:t.session.sessionId??t.session.backendSessionId??null,executionId:n??null}}function Nh(t){return Array.isArray(t.spec.tools)?t.spec.tools:void 0}function $h(t){return typeof t.spec.tools=="string"?t.spec.tools:void 0}function Bh(t){return{mcp:{composition:void 0,servers:void 0,allowlist:t.policy.mcpToolAllowlist===void 0?void 0:Ir(t.policy.mcpToolAllowlist),configPaths:t.isolation?.mcpConfigPaths},flags:{disableHooks:t.policy.hooks===void 0?void 0:!t.policy.hooks,disableSkills:t.policy.skills===!1?!0:void 0,settingSources:t.policy.settingSources,streamDeltas:t.policy.streamDeltas,captureTranscripts:t.policy.captureTranscripts,isUserInitiated:!!t.context.isUserInitiated,...t.context.teamLead?{teamLead:!0}:{},...t.context.teamWorker?{teamWorker:!0}:{},...t.policy.clean?{clean:!0}:{}},process:{spawner:t.isolation?.spawner,cliPath:typeof t.isolation?.cliPath=="string"?t.isolation.cliPath:void 0}}}function Fh(t,e,n){let r=jh(t.spec.pluginDirs,{channel:t.context.channel,feishuSkillsInWeb:h().feishuSkillsInWeb}),s=Na({backend:e.backend,selectedPluginDirs:r,mcpComposition:n});return{dirs:s.pluginDirs,skillDirs:s.pluginSkillDirs,servers:s.mcpServers,fingerprint:s.pluginCapabilityFingerprint,...s.warnings?{warnings:s.warnings}:{}}}var $a=["ANTHROPIC_API_KEY","CLAUDE_CODE_OAUTH_TOKEN"];function Wh(t){let e={};for(let n of $a){let r=t[n];typeof r=="string"&&(e[n]=r)}return e}function Kh(t){let e=$a.filter(n=>t[n]===null);return t.ANTHROPIC_BASE_URL||e.push("ANTHROPIC_BASE_URL"),e}function Hh(t){let e=t?Wh(t):{},n=t?Kh(t):[];return{sets:Object.keys(e).length>0?e:void 0,unsets:n.length>0?n:void 0}}function Gh(t,e){let n={claudeAgent:t.spec.backendOptions.claudeAgent??void 0,outputStyle:typeof t.spec.backendOptions.outputStyle=="string"?t.spec.backendOptions.outputStyle:void 0};return e.backend==="claude"?{kind:"claude",...n}:{kind:"pi"}}function Ba(t,e,n={}){let{route:r,executionId:s=null}=n,i=Fe(t.policy.mcpComposition),o=Uh(t,e,s),a=Fo(t.spec,{rules:Wo(t.policy.loadRules!==!1),workspace:t.policy.clean&&t.cwd?ks(t.cwd):null}),u=Fh(t,e,i),l=Bh(t),p=Hh(r),c=e.backend==="pi"&&e.provider||void 0;return{engineKey:t.session.engineKey||t.context.channel||"default",cwd:t.cwd??void 0,resume:{backendSessionId:t.session.backendSessionId??null,resume:!!t.session.backendSessionId},model:{id:e.model,provider:c,thinking:e.thinking||void 0,benchmarkMaxOutputTokens:e.backend==="pi"&&t.benchmark?.evidenceContext?t.benchmarkMaxOutputTokens:void 0},prompt:{system:typeof t.spec.systemPrompt=="string"?t.spec.systemPrompt:void 0,append:a},tools:{canonical:Nh(t),rawClaude:$h(t)},plugins:{dirs:u.dirs,skillDirs:u.skillDirs,fingerprint:u.fingerprint,...u.warnings?{warnings:u.warnings}:{}},mcp:{...l.mcp,composition:i,servers:u.servers},env:{sets:p.sets,unsets:p.unsets,pinned:t.isolation?.pinnedEnv,context:o},route:{anthropicBaseUrl:r?.ANTHROPIC_BASE_URL,gatewayBaseUrl:e.backend==="pi"?Ve:void 0,gatewayPath:c?tr(e.mode,c):void 0},flags:l.flags,context:{channel:t.context.channel,callbackSource:t.context.callbackSource??void 0,scheduleTaskId:t.context.scheduleTaskId??void 0},backend:Gh(t,e),process:l.process}}var nr=class{byKey=new Map;byChannel=new Map;_bus=null;constructor(e){e&&(this._bus=e)}setBus(e){this._bus=e}register(e){let n=e.executionId??e.registryKey;if(!n)throw new Error("RunRegistry.register requires an executionId or registryKey");let r=this.byKey.get(n);r&&this._removeFromIndices(r);let s={channel:e.channel,registryKey:n,executionId:e.executionId,kind:e.kind??null,kill:e.kill,startTime:Date.now(),backend:e.backend,run:e.run,trackSessionId:e.trackSessionId??null,backendSessionId:e.backendSessionId??null,numTurns:e.numTurns??null,subagent:e.subagent??!1};if(this.byKey.set(n,s),s.channel){let i=this.byChannel.get(s.channel);i||(i=new Set,this.byChannel.set(s.channel,i)),i.add(s)}return this._bus&&s.executionId&&this._bus.publish({type:"agent.started",channel:s.channel??n,executionId:s.executionId,backend:s.backend}),n}getById(e){return this.byKey.get(e)??null}setNumTurns(e,n){let r=this.byKey.get(e);r&&(r.numTurns=n)}hasId(e){return this.byKey.has(e)}getBySessionId(e){let n=null;for(let r of this.byKey.values())r.trackSessionId!==e&&r.backendSessionId!==e||(!n||r.startTime>=n.startTime)&&(n=r);return n}getByChannel(e){let n=this.byChannel.get(e);return n?Array.from(n):[]}getOwnByChannel(e){return this.getByChannel(e).filter(n=>!n.subagent)}getRunByChannel(e){let n=null;for(let r of this.getByChannel(e))r.run&&(!n||r.startTime>=n.startTime)&&(n=r);return n?.run??null}hasChannel(e){let n=this.byChannel.get(e);return!!n&&n.size>0}getAll(){return Array.from(this.byKey.values())}killById(e){let n=this.byKey.get(e);if(!n)return!1;let r=n.kill();return this._delete(n),r}killByChannel(e){let n=this.getByChannel(e);for(let r of n)r.kill(),this._delete(r);return n.length}remove(e){let n=this.byKey.get(e);n&&this._delete(n)}complete(e,n=0){let r=this.byKey.get(e);return r?(this._delete(r),this._bus&&r.executionId&&this._bus.publish({type:"agent.completed",executionId:r.executionId,cost:n,durationMs:Date.now()-r.startTime}),!0):!1}fail(e,n){let r=this.byKey.get(e);return r?(this._delete(r),this._bus&&r.executionId&&this._bus.publish({type:"agent.failed",executionId:r.executionId,error:n}),!0):!1}supersede(e,n){let r=this.byKey.get(e);return r?(r.kill(),this._delete(r),this._bus&&r.executionId&&this._bus.publish({type:"agent.superseded",executionId:r.executionId,reason:n}),!0):!1}supersedeByChannel(e,n){let r=this.getByChannel(e);for(let s of r)s.kill(),this._delete(s),this._bus&&s.executionId&&this._bus.publish({type:"agent.superseded",executionId:s.executionId,reason:n});return r.length}_delete(e){this.byKey.delete(e.registryKey),this._removeFromIndices(e)}_removeFromIndices(e){if(e.channel){let n=this.byChannel.get(e.channel);n&&(n.delete(e),n.size===0&&this.byChannel.delete(e.channel))}}},z=new nr;var rr=new Map,Fa=new Map;function fT(t,e,n){let r=zh(e.trial_id,e.root_run_id);if(r&&r!==t)throw new Error(`trial run ${e.trial_id}/${e.root_run_id} already has a session`);rr.set(t,e),n!==void 0&&Fa.set(t,n)}function mT(t){return rr.get(t)??null}function Wa(t){return Fa.get(t)}function zh(t,e){for(let[n,r]of rr)if(r.trial_id===t&&r.root_run_id===e)return n;return null}var za={};yu(za,{cancelExecution:()=>Ga,completeExecution:()=>Ka,failExecution:()=>Ha,getAll:()=>Jh,getExecution:()=>Vh,getRunningExecutions:()=>Xh,markMissingRunningExecutionsStale:()=>qh,startLocalExecution:()=>sr,stopLiveExecution:()=>Zh,teardownExecution:()=>Ot,touchExecution:()=>Qh});function Vh(t){return O.getExecution(t)}function Jh(){return O.getAll()}function Xh(){return O.getRunningExecutions()}function sr(t){return O.startLocalExecution(t)}function Qh(t,e){return O.touchExecution(t,e)}function Ka(t,e){return O.completeExecution(t,e)}function Ha(t,e){return O.failExecution(t,e)}function Ga(t,e){return O.cancelExecution(t,e)}function Yh(t){let e=t?.rateLimitMessage;return e?`Rate limited: ${e}`:"Rate limited"}function Ot({executionId:t,status:e,result:n,spend:r,error:s,durationS:i}){if(!t)return null;let o=r?r.costUsd:n?.total_cost_usd,a={costUsd:o,numTurns:r?r.numTurns:n?.num_turns,durationS:i,finalOutput:n?.finalOutput||null},u;if(e==="completed")u=Ka(t,a),z.complete(t,o??0);else if(e==="cancelled")u=Ga(t,a),z.supersede(t,"cancelled");else{let l=e==="rate-limited"?s?.message||Yh(n):s?.message||null;u=Ha(t,{...a,error:l}),z.fail(t,l??"error")}return u}function Zh(t){if(t.run?.cancel){t.run.cancel("user");return}t.executionId?Ot({executionId:t.executionId,status:"cancelled",durationS:0}):z.killById(t.registryKey)}async function qh(t){return await O.markMissingRunningExecutionsStale(t)}var eg=/rate[ _]limit|usage[ _]limit|overloaded|529|too many requests|quota/i;function he(t){return!!t&&eg.test(t)}var tg=/(?:invalid[_ ]request|forbidden|not found|request body too large|context(?: window|_length).*exceed|insufficient[_ ](?:balance|quota)|billing|quota exhausted)/i,ng=/(?:^(?:error\s*)?(?:408|500|502|503|504)\b|\bhttp(?: status)?\s*[:=]?\s*(?:408|500|502|503|504)\b|\bstatus(?: code)?\s*[:=]?\s*(?:408|500|502|503|504)\b)/i,rg=/(?:fetch failed|econnreset|econnrefused|etimedout|eai_again|enotfound|socket hang up|connection (?:reset|refused|terminated|error)|upstream connection error|temporary failure in name resolution|(?:request|connection|connect|network|socket|tls|upstream).*tim(?:ed? out|eout))/i,sg=/\byou can retry your request\b/i,ig=/\b(?:ENOSPC|EMFILE|ENFILE|EAGAIN)\b/i;function Me(t){let e=t?.message;return!e||ie(e)||tg.test(e)?!1:he(e)||ng.test(e)||rg.test(e)||sg.test(e)||ig.test(e)}var ir=Object.freeze({costUsd:null,numTurns:null});function og(t,e){return t===null?e:e===null?t:t+e}function Mt(t){return typeof t=="number"&&Number.isFinite(t)?t:null}function Va(t){return{costUsd:Mt(t.total_cost_usd),numTurns:Mt(t.num_turns)}}function Ja(t,e){if(e.type==="cost_record")t.costUsd=og(t.costUsd,Mt(e.cost_usd));else if(e.type==="turn_progress"){let n=Mt(e.numTurns);n!==null&&(t.numTurns=Math.max(t.numTurns??0,n))}}var ag={claude:"anthropic"};function Le(t){return t.provider||ag[t.backend]||t.backend}function or(t){return Eo(Le(t),t.mode||"api")}function ar(t,e){return{sessionId:null,total_cost_usd:null,num_turns:null,rateLimited:!0,rateLimitMessage:`Mode ${t} is rate-limited`,rateLimitProvider:e,planFilePath:null,enteredPlanMode:!1,exitedPlanMode:!1,finalOutput:null}}function Xa(t,e){return or(t)&&!e.isUserInitiated}function ur(t){return Le(t)}function Qa(t){return t.backend!=="claude"?null:t.mode==="api"?"api_key":"oauth"}function lr(t){return t.model?Le(t):null}function Ya(t){return t.startsWith("API Error:")?"error":void 0}function ug(t){return t.startsWith("API Error:")?t:b("status.errorBody",{message:t})}var Lt=class{ctx;emit;synthesize;attemptHasErrorNotice=!1;heldError=null;constructor(e,n){this.ctx=e,this.emit=n,this.synthesize=e.channel?.startsWith("web:")===!0}observe(e,n,r,s,i){if(r==="error"&&this.synthesize&&he(e)){this.heldError={text:e,...n?{blockId:n}:{}};return}r==="error"&&(this.attemptHasErrorNotice=!0),this.emit?.(e,n,r,s,i)}flushHeldError(){let e=this.heldError;this.heldError=null,!(!e||!this.emit)&&(this.attemptHasErrorNotice=!0,this.emit(e.text,e.blockId,"error"))}settleSuccess(){this.flushHeldError()}emitTerminal(e,n=ug(e)){this.flushHeldError(),!(!this.synthesize||!this.emit||this.attemptHasErrorNotice)&&(this.attemptHasErrorNotice=!0,this.emit(n,void 0,"error"))}emitAutoResume(e){return!this.ctx.isUserInitiated||!vo(e)?!1:(this.heldError=null,this.synthesize&&this.emit&&!this.attemptHasErrorNotice&&(this.attemptHasErrorNotice=!0,this.emit(b("notify.rateLimitAutoResume"),void 0,"warning",{kind:"cancel-resume"})),!0)}emitTerminalError(e){let n=e;if(n?.cancelled)return;let r=typeof n?.message=="string"&&n.message.length>0?n.message:String(e);this.ctx.trigger!=="edit-retry"&&he(r)&&this.emitAutoResume(n?.rateLimitProvider)||this.emitTerminal(r)}emitTerminalRateLimit(e){if(this.emitAutoResume(e.rateLimitProvider))return;let n=e.rateLimitMessage;typeof n=="string"&&n.startsWith("API Error:")?this.emitTerminal(n):this.emitTerminal(b("status.rateLimitedExhausted"),b("status.rateLimitedExhausted"))}};var lg=m("agent-adapter"),Za=m("pi-adapter");function qa(t){return t instanceof Error?t.message:String(t)}var cr=class{pi;claude;sessions=new Map;constructor(e={}){this.pi=e.pi,this.claude=e.claude,this.pi?.setEnginePool({get:n=>this.piEngine(n)})}acquire(e){return e.backend.kind==="pi"?this.acquirePi(e):this.acquireClaude(e)}reuses(e){let n=this.get(e.engineKey);return n?e.backend.kind==="pi"?!!this.pi&&this.piReusable(this.pi,e,n):!!this.claude&&this.claudeReusable(this.claude,e,n):!1}piReusable(e,n,r){return r.isAlive()&&r.identity===e.specIdentity(n)}claudeReusable(e,n,r){if(!r.isAlive()||r.identity!==e.specIdentity(n))return!1;let s=e.claudeResumeTarget(n);return!s.needsResume||r.backendSessionId===s.sessionId}acquirePi(e){let n=this.pi;if(!n)throw new Error("SessionEngines has no PI engine adapter configured");let r=e.engineKey,s=this.sessions.get(r);if(s&&this.piReusable(n,e,s))return s;s&&(Za.info(`PI session ${r} retired (${s.isAlive()?"spawn config changed":"session gone"}); creating a new session`),s.close().catch(o=>Za.warn(`retiring PI session ${r} failed: ${qa(o)}`)),this.sessions.delete(r));let i;return i=n.open(e,{onSelfClose:o=>{this.sessions.get(o)===i&&this.sessions.delete(o)},onEvict:o=>{this.sessions.get(r)===o&&this.sessions.delete(r)}}),this.sessions.set(r,i),i}acquireClaude(e){let n=this.claude;if(!n)throw new Error("SessionEngines has no Claude engine adapter configured");let r=e.engineKey,s=this.sessions.get(r);if(!s||!this.claudeReusable(n,e,s)){s&&s.close(),this.sessions.delete(r);let i;i=n.open(e,{onSelfClose:o=>{this.sessions.get(o)===i&&this.sessions.delete(o)},onEvict:o=>{this.sessions.delete(o)}}),this.sessions.set(r,i),s=i}return s}piEngine(e){let n=this.sessions.get(e);return n&&n.backend==="pi"?n:void 0}get(e){return this.sessions.get(e)}async close(e){let n=this.sessions.get(e);n&&(this.sessions.delete(e),await n.close().catch(r=>lg.warn(`close ${n.backend} session ${e} failed: ${qa(r)}`)))}kill(e){let n=this.sessions.get(e);if(!n)return!1;let r=n.kill();return r&&this.sessions.delete(e),r}closeByPrefix(e){for(let n of[...this.sessions.keys()])n.startsWith(e)&&this.close(n)}closeAll(){for(let e of[...this.sessions.keys()])this.close(e)}listKeys(){return[...this.sessions.keys()]}registerSessionPath=(e,n)=>{if(!this.pi)throw new Error("SessionEngines has no PI engine adapter configured");this.pi.registerSessionPath(e,n)}},cg=kt(),dg=Mo(),Dt=new cr({pi:cg,claude:dg});var jt=m("run-attempt");function pg(t,e,n){return Object.freeze({session_id:n?.session_id??t.session.sessionId??t.session.backendSessionId??null,execution_id:n?.execution_id??e??null,attempt_id:n?.attempt_id??null,root_attempt_id:n?.root_attempt_id??null,trial_id:n?.trial_id??null,root_run_id:n?.root_run_id??null})}function fg(t,e){return e?t?`${t}:bg-continuation`:"bg-continuation":t||"unknown"}function mg(t,e,n,r){e.request.policy.recordCost!==!1&&xs({...n,project:e.request.context.project||"general",trigger:fg(e.request.context.trigger,r),cost_usd:t.cost_usd,backend:e.attempt.backend,mode:e.attempt.mode||"api",source:"estimate",input_tokens:t.input_tokens,output_tokens:t.output_tokens,prompt_tokens:t.prompt_tokens===void 0?t.tokens_in:t.prompt_tokens,cache_read_tokens:t.cache_read_tokens,cache_creation_tokens:t.cache_creation_tokens,provider_requests:t.provider_requests,provider:t.provider||void 0,model:t.model||void 0}).catch(s=>jt.warn("recordCost failed:",s?.message??s))}function hg(t){if(t.length!==0)return e=>{for(let n of t)try{n.onEvent(e)}catch(r){jt.warn("required sink failed:",r?.message??r)}}}async function gg(t){for(let e of t)try{await e.onClose?.()}catch(n){jt.warn("required sink close failed:",n?.message??n)}}function yg(t){for(let e of t)try{e.onClose?.()}catch(n){jt.warn("required sink close failed:",n?.message??n)}}async function kg(t,e){let n=null,r;try{[n]=await Promise.all([t.settled,e])}catch(s){r=s;try{await e}catch(i){r=i}}if(r!==void 0)throw r;return n}function Sg(){let t,e;return{promise:new Promise((r,s)=>{t=r,e=s}),resolve:t,reject:e}}function _g(t){return t==="hold"}function eu(t){let{request:e,attempt:n,executionId:r,route:s}=t,i=Ba(e,n,{route:s,executionId:r}),o=Os({adapterBackend:n.backend,spec:i,request:e,executionId:r,selection:e.selection}),a=o?Rs({identity:o,spec:i,canonicalInstruction:e.benchmark?.identityDirective??"",message:e.prompt.text}):null,u=pg(e,r,o),l=[...a?[a]:[],...t.requiredSinks??[]],p=hg(l),c=e.policy.background,f=_g(c),T,w;try{T=Dt.acquire(i),w=T.run({text:e.prompt.text,attachments:e.prompt.attachments},{awaitBackground:c,...p?{onNormalizedEvent:p}:{}})}catch(V){throw yg(l),V}let g=!1,R=Sg(),$t=(async()=>{try{for await(let V of w.events)V.type==="cost_record"&&mg(V,t,u,g),t.onEvent(V),V.type==="foreground_result"&&(g=!0,f&&R.resolve(V.result))}finally{await gg(l)}})(),dr=kg(w,$t);return dr.then(R.resolve,R.reject),R.promise.catch(()=>{}),{engine:T,engineRun:w,spec:i,identity:o,backend:n.backend,foreground:R.promise,settled:dr,get backendSessionId(){return T.backendSessionId},kill:()=>T.kill()}}var Ut=m("run"),tu=3;function te(t){return t instanceof Error?t:new Error(String(t))}function bg(t){return Object.assign(new Error(`Run cancelled (${t})`),{cancelled:!0})}var Nt=class{id;request;executionId;result;settled;attemptValue;lastAssistantModel=null;backgroundTranscriptOwnedValue=!1;statusValue="running";phaseValue="foreground";numTurnsValue=null;backendSessionIdValue;foregroundResult=null;continuations=[];liveSpend=null;observers;registry;onTerminal;startedAt;settleDeferred=nu();resultDeferred=nu();notices;noticesActive=!0;pluginWarningsAnnounced=!1;current=null;started=!1;terminal=!1;observersClosed=!1;cancelRequested=!1;constructor(e){this.request=e.request,this.executionId=e.executionId,this.id=e.request.runId,this.attemptValue={index:0,config:e.request.selection},this.notices=new Lt({channel:e.request.context.channel,isUserInitiated:e.request.context.isUserInitiated,trigger:e.request.context.trigger},(n,r,s,i,o)=>this.absorb({type:"assistant_text",text:n,phase:this.phaseValue,...this.lastAssistantModel?{model:this.lastAssistantModel}:{},...r?{blockId:r}:{},...s?{noticeLevel:s}:{},...i?{noticeAction:i}:{},...o?{subagent:o}:{}})),this.backendSessionIdValue=e.request.session.backendSessionId,this.observers=[...e.observers],this.registry=e.registry,this.onTerminal=e.onTerminal,this.startedAt=e.startedAt,this.result=this.resultDeferred.promise,this.settled=this.settleDeferred.promise,this.result.catch(()=>{}),this.settled.catch(()=>{})}get attempt(){return this.attemptValue}get status(){return this.statusValue}get phase(){return this.phaseValue}get numTurns(){return this.numTurnsValue}get backendSessionId(){return this.backendSessionIdValue}get capabilities(){return K[this.attemptValue.config.backend]}get onSessionBackend(){return this.attemptValue.config.backend===this.request.selection.backend}adoptBackendSessionId(e){e&&this.onSessionBackend&&(this.backendSessionIdValue=e)}get backgroundTranscriptOwned(){return this.backgroundTranscriptOwnedValue}claimBackgroundTranscript(){this.backgroundTranscriptOwnedValue=!0}start(){this.started||(this.started=!0,this.runOnce())}async runOnce(){let e=this.request.selection;if(Xa(e,this.request.context)){let r=ar(e.mode,ur(e));this.notices.emitTerminalRateLimit(r),this.settleBlocked(r);return}let n;try{n=this.openAttempt(e)}catch(r){this.onForegroundError(r);return}try{this.settleAttemptResult(n,await n.foreground)}catch(r){this.onAttemptError(n,e,r)}}openAttempt(e){let n={...ir};this.liveSpend=n;let r=eu({request:this.request,attempt:e,executionId:this.executionId,route:this.routeFor(e),onEvent:s=>{Ja(n,s),this.onRunEvent(s)}});return this.current=r,this.registerAttempt(r),this.announcePluginWarnings(r.spec),r}routeFor(e){return As(this.request,e)}settleAttemptResult(e,n){let r=this.attribute(n);r.rateLimited?this.notices.emitTerminalRateLimit(r):this.notices.settleSuccess(),this.publishAuthOutcome(r,null),this.onForegroundResult(r),e.settled.then(s=>this.onAttemptSettled(this.attribute(s)),s=>this.finishForegroundError(te(this.attributeError(s))))}settleBlocked(e){this.onForegroundResult(e),this.finishTerminal("rate-limited",e)}onAttemptError(e,n,r){let s=this.attributeError(r);this.notices.emitTerminalError(s),this.publishAuthOutcome(null,s,n),e.settled.catch(()=>{}),this.onForegroundError(s)}attribute(e){let n=lr(this.attemptValue.config);return!n||e.rateLimitProvider?e:{...e,rateLimitProvider:n}}attributeError(e){let n=te(e),r=lr(this.attemptValue.config);return r&&Me(n)&&(n.rateLimitProvider??=r),n}publishAuthOutcome(e,n,r=this.attemptValue.config){let s={backend:r.backend,provider:ur(r)};if(e){e.rateLimited||Ps(s);return}let i=ie(n?.message??"");i&&Cs({...s,authType:Qa(r),kind:i,channel:this.request.context.channel,sessionId:this.request.session.sessionId??this.backendSessionIdValue??this.request.session.backendSessionId})}steer(e,n){if(this.terminal||!this.capabilities.has(C.MidTurnInject))return Promise.resolve("refused");let r=this.current?.engine;if(!r)return Promise.resolve("refused");let s=!1;try{s=r.steer(e,n).accepted}catch(i){Ut.warn("run steer failed:",te(i).message)}return s?Promise.resolve(this.phaseValue==="background"?"queued":"folded"):Promise.resolve("refused")}respondToDialog(e,n){return this.current?.engine.respondToDialog(e,n)??!1}ingestExternal(e){return this.terminal?!1:this.current?.engine.ingestExternal(e)??!1}cancel(e){if(!this.terminal){this.cancelRequested=!0;try{this.current?.kill()}catch(n){Ut.warn("run kill failed:",te(n).message)}this.finishTerminal("cancelled",null,bg(e))}}subscribe(e){return this.observers.push(e),()=>{let n=this.observers.indexOf(e);n>=0&&this.observers.splice(n,1)}}registerAttempt(e){this.registry.register({channel:this.request.context.channel,executionId:this.executionId,kind:this.request.context.executionKind,kill:()=>e.kill(),backend:e.backend,run:this,trackSessionId:this.request.session.sessionId,backendSessionId:e.backendSessionId??this.request.session.backendSessionId,subagent:this.request.context.trigger==="subagent"}),this.adoptBackendSessionId(e.backendSessionId)}onRunEvent(e){if(!this.terminal){switch(this.refreshBackendSessionId(),e.type){case"assistant_text":e.model&&(this.lastAssistantModel=e.model),this.notices.observe(e.text,e.blockId,Ya(e.text),void 0,e.subagent);return;case"foreground_result":this.noticesActive=!1;return;case"phase":if(e.phase==="done")return;break;case"engine_started":this.announceBackendSessionReset(e.backendSessionId);break;case"context_compacted":this.noticesActive&&h().notifyCompaction&&this.notices.observe(b("notify.contextCompacted"),void 0,"info");break;case"model_fallback":this.noticesActive&&this.notices.observe(b("notify.agentFallback",{from:e.originalModel,to:e.fallbackModel}),void 0,"warning");break;default:break}this.absorb(e)}}announcePluginWarnings(e){let n=e?.plugins?.warnings;if(!n?.length||this.pluginWarningsAnnounced||!this.noticesActive||!this.request.context.channel?.startsWith("web:"))return;this.pluginWarningsAnnounced=!0;let r=n.slice(0,tu).join(`
78
- `),s=n.length-tu;this.notices.observe(b("notify.pluginsUnavailable",{detail:s>0?`${r}
79
- ${b("notify.pluginsUnavailableMore",{n:s})}`:r}),void 0,"warning")}announceBackendSessionReset(e){if(!this.noticesActive||!this.request.context.channel?.startsWith("web:"))return;let n=this.current?.spec;!n?.resume.resume||!n.resume.backendSessionId||e!==n.resume.backendSessionId&&this.notices.observe(b("notify.backendSessionReset"),void 0,"warning")}onAttemptSettled(e){this.terminal||(this.absorbResultCounts(e),this.finishTerminal(e.rateLimited?"rate-limited":"completed",e))}refreshBackendSessionId(){this.backendSessionIdValue||this.adoptBackendSessionId(this.current?.backendSessionId)}absorb(e){if(!this.terminal){switch(e.type){case"engine_started":this.adoptBackendSessionId(e.backendSessionId);break;case"turn_progress":this.setNumTurns(e.numTurns);break;case"background_result":this.absorbContinuation(e.result);break;default:break}this.fanOut(e)}}setNumTurns(e){this.numTurnsValue=e,this.registry.setNumTurns(this.executionId,e)}absorbResultCounts(e){typeof e.num_turns=="number"&&this.setNumTurns(e.num_turns),this.adoptBackendSessionId(e.sessionId)}absorbContinuation(e){if(e.backgroundInterrupted)return;this.continuations.push(e);let n=this.tally();n&&this.absorbResultCounts(n)}tally(){return this.foregroundResult?this.continuations.reduce(Jt,this.foregroundResult):null}onForegroundResult(e){this.terminal||(this.foregroundResult=e,this.absorbResultCounts(this.tally()??e),this.resultDeferred.resolve(e),this.fanOut({type:"foreground_result",result:e}),!this.terminal&&Se(e)>0&&(this.phaseValue="background",this.statusValue="background"))}onForegroundError(e){if(this.terminal)return;let n=te(e);queueMicrotask(()=>this.finishForegroundError(n))}finishForegroundError(e){if(!this.terminal){if(this.cancelRequested||e.cancelled===!0){this.finishTerminal("cancelled",null,e);return}this.fanOut({type:"error",message:e.message,fatal:!0}),this.finishTerminal("failed",null,e)}}finishTerminal(e,n,r){if(this.terminal)return;this.terminal=!0,this.statusValue=e,this.phaseValue="done",this.fanOut({type:"phase",phase:"done",pendingBackground:0,undeliveredBackground:0});let s=(Date.now()-this.startedAt)/1e3,i=n??this.tally();try{this.onTerminal({status:e,result:i,spend:this.runSpend(i),error:r,durationS:s})}catch(o){Ut.warn("run terminal handler failed:",te(o).message)}r?(this.resultDeferred.reject(r),this.settleDeferred.reject(r)):(this.resultDeferred.resolve(i),this.settleDeferred.resolve(i)),this.closeObservers()}runSpend(e){return e?Va(e):this.liveSpend??ir}fanOut(e){for(let n of[...this.observers])try{let r=n.onEvent(e);r&&typeof r.then=="function"&&r.catch(s=>this.onObserverError(s))}catch(r){this.onObserverError(r)}}closeObservers(){if(!this.observersClosed){this.observersClosed=!0;for(let e of[...this.observers])try{let n=e.onClose?.();n&&typeof n.then=="function"&&n.catch(r=>this.onObserverError(r))}catch(n){this.onObserverError(n)}}}onObserverError(e){Ut.warn("run observer failed:",te(e).message)}};function nu(){let t,e;return{promise:new Promise((r,s)=>{t=r,e=s}),resolve:t,reject:e}}var au=new Set(["cache-refresh","manual-compact"]);function Tg(t){return ie(t)?"auth":he(t)?"rate_limit":/tim(?:ed? ?out|eout)/i.test(t)?"timeout":Me(new Error(t))?"network":/exited with code|process exited|spawn|SIGSEGV|SIGABRT|killed|crash/i.test(t)?"adapter_crash":"other"}function wg(t){let{backend:e,mode:n}=t.selection,r=h();return(e==="claude"?r.anthropicSubscriptionModes:r.subscriptionBillingModes).includes(n)?"plan":"api"}function ru(t,e){return t.tools.has(e)||t.tools.set(e,{calls:0,errors:0}),t.tools.get(e)}var xg=new Set(["assistant_text","assistant_delta","assistant_thinking","assistant_thinking_delta","tool_use"]),vg={completed:"completed",failed:"failed",killed:"cancelled"};function su(t,e){if(e.type==="tool_use"){t.toolNames.set(e.toolUseId,e.name),ru(t,e.name).calls+=1;return}let n=t.toolNames.get(e.toolUseId);n&&!e.ok&&(ru(t,n).errors+=1)}function Eg(t,e){t.tokens.input+=e.input_tokens??0,t.tokens.output+=e.output_tokens??0,t.tokens.cacheRead+=e.cache_read_tokens??0,t.tokens.cacheWrite+=e.cache_creation_tokens??0}var Ig={tool_use:su,tool_result:su,cost_record:Eg,context_usage:(t,e)=>{t.contextPct=e.percent??t.contextPct},context_compacted:(t,e)=>{t.compactions[e.trigger==="manual"?"manual":"auto"]+=1},model_fallback:t=>{t.fallbacks+=1},error:(t,e)=>{e.fatal||(t.retries+=1)},subagent_end:(t,e)=>{t.subagents[vg[e.status]??"failed"]+=1}};function Cg(t,e){t.firstOutputAt===null&&xg.has(e.type)&&(t.firstOutputAt=Date.now()),Ig[e.type]?.(t,e)}function Pg(){return{startedAt:Date.now(),firstOutputAt:null,contextPct:null,compactions:{auto:0,manual:0},tokens:{input:0,output:0,cacheRead:0,cacheWrite:0},retries:0,fallbacks:0,toolNames:new Map,tools:new Map,subagents:{completed:0,failed:0,cancelled:0}}}function uu(t){let e=Pg(),n=!1;return{observer:{onEvent:r=>{try{Cg(e,r)}catch{}}},finish:r=>{n||(n=!0,xr(s=>Lg(s,t,e,r)),r.status==="completed"&&!au.has(t.context.trigger)&&(Kt("provider_authed",t.selection.backend),Kt("first_turn_completed")))}}}function iu(t,e){let{backend:n,provider:r,model:s}=e.selection,i=wg(e),o=[n,r??"",s,i].join("|");return t.turns[o]??=wr(n,r??"",s,i),t.turns[o]}function Ag(t,e){if(e.status==="rate-limited"?t.outcomes.rateLimited+=1:t.outcomes[e.status]+=1,e.status==="failed"){let n=Tg(e.error?.message??"");t.failures[n]=(t.failures[n]??0)+1}}function Rg(t,e,n){Ag(t,n),t.retries+=e.retries,t.fallbacks+=e.fallbacks,n.status==="completed"&&e.firstOutputAt!==null&&(t.ttftMs[Ne("ttftMs",e.firstOutputAt-e.startedAt)]+=1),t.durationS[Ne("turnDurationS",n.durationS)]+=1,e.contextPct!==null&&(t.contextPctAtEnd[Ne("contextPct",e.contextPct)]+=1),t.compactions.auto+=e.compactions.auto,t.compactions.manual+=e.compactions.manual;for(let r of["input","output","cacheRead","cacheWrite"])t.tokens[r]+=e.tokens[r]}function lu(t){return t.status==="rate-limited"?"failed":t.status}function Og(t){return t.status==="cancelled"?/\((\w+)\)/.exec(t.error?.message??"")?.[1]??null:null}function ou(t,e){for(let[n,r]of e.tools){let s=t.tools[n]??={calls:0,errors:0};s.calls+=r.calls,s.errors+=r.errors}}function Mg(t,e,n,r){let s=Og(r);s==="user"&&(t.agent.userInterrupts+=1),s==="supersede"&&(t.agent.superseded+=1);for(let o of["completed","failed","cancelled"])t.agent.subagents[o]+=n.subagents[o];e.context.teamWorker&&(t.agent.workers[lu(r)]+=1);let i=e.session.sessionId;i&&(t.agent.sessionTurns[i]=(t.agent.sessionTurns[i]??0)+1)}function Lg(t,e,n,r){let{trigger:s}=e.context;if(s==="subagent")return t.agent.subagents[lu(r)]+=1,ou(t,n);if(au.has(s)){n.compactions.manual>0&&(iu(t,e).compactions.manual+=n.compactions.manual);return}Rg(iu(t,e),n,r),ou(t,n),Mg(t,e,n,r)}function Dg(t){return!t.benchmark?.evidenceContext||!t.session.sessionId?t:{...t,benchmarkMaxOutputTokens:t.benchmarkMaxOutputTokens??Wa(t.session.sessionId)}}function jg(t){return sr({kind:t.context.executionKind,channel:t.context.channel,project:t.context.project,trigger:t.context.trigger,backend:t.selection.backend,billingMode:t.selection.mode||"api",sessionId:t.session.sessionId,ownerSessionId:t.context.ownerSessionId??null,label:t.prompt.text.substring(0,60),scheduleTaskId:t.context.scheduleTaskId||null})}function Ug(t,e){let{status:n,result:r,spend:s,error:i,durationS:o}=e;Ot({executionId:t,status:n,result:r,spend:s,error:i?{message:i.message}:null,durationS:o}),z.remove(t)}function cu(t,e){t=Dg(t);let n=Date.now(),r=jg(t),s=uu(t),i=new Nt({request:t,observers:[...e,s.observer],executionId:r.id,registry:z,startedAt:n,onTerminal:o=>{Ug(r.id,o),s.finish(o)}});return i.start(),i}function yw(){return{systemPrompt:null,directive:null,promptTemplate:null,tools:null,pluginDirs:[],mcp:{composition:"direct",allowlist:null},backendOptions:{}}}function kw(t,e){return{systemPrompt:t.systemPrompt?St(t.systemPrompt):null,directive:t.directive??null,promptTemplate:t.promptTemplate??null,tools:t.tools||null,pluginDirs:t.pluginDirs||[],mcp:{composition:e.mcpComposition,allowlist:t.mcpToolAllowlist??null},backendOptions:{...t.claudeAgent?{claudeAgent:t.claudeAgent}:{},...t.outputStyle?{outputStyle:t.outputStyle}:{}}}}function du(t,e,n={}){let r=ss(t,e);return{systemPrompt:null,appendSystemPrompt:t.systemPrompt,directive:null,promptTemplate:null,tools:r?r.join(","):null,pluginDirs:[],mcp:{composition:"direct",allowlist:n.mcpAllowlist??null},backendOptions:{}}}var Ng=["user","project","local"];function $g(t){return(t??Ng).filter(e=>e!=="project")}function pu(t){return{...t,clean:!0,hooks:!1,loadRules:!1,settingSources:$g(t.settingSources)}}var fu=m("subagent-runner"),Fg=["cortex-core","cortex-ext"];function Wg(t){return Ss(t.task.model?.trim()||t.role.model?.trim())}function Kg(t){return!!K[t]?.has(C.Subagents)}async function Uw(t){if(t.signal?.aborted)throw new Error("Subagent was aborted.");if(!Kg(t.backend))throw new Error(`Backend "${t.backend}" cannot run subagents.`);return t.backend==="pi"?Gg(t):Yg(t)}function Hg(t,e){if(t.role.mode)return t.role.mode;let n=t.parent;return n.backend==="pi"&&n.provider===e&&n.mode?n.mode:e}async function Gg(t){let[{runPiChild:e},{childExtensions:n}]=await Promise.all([import("./child-runner-3GHOWGZP.js"),import("./tool-shims-Q6P6UXVC.js")]),r=_s(t.task,t.role,t.parent.backend==="pi"?t.parent:null),s=kt(),i=r.provider;if(i){let o=Hg(t,i);try{s.ensureProviderRouting({provider:i,gatewayPath:tr(o,i)??null,gatewayBaseUrl:Ve,model:r.model})}catch(a){fu.warn(`Could not route provider ${i} for a pi subagent: ${a.message}`)}}return e({task:t.task,role:t.role,cwd:t.cwd,workspace:t.workspace??null,agentDir:s.agentDir,parentEnv:t.parent.env??process.env,model:r,childExtensions:o=>n(o,ze),signal:t.signal,forward:zg(t)})}function zg(t){let e=t.onNotice;if(!e)return;let{ref:n,task:r}=t,s=!1;return(i,o)=>{let a=ys(n,r,o,i);for(let u of a)try{e(s?u:{...u,prompt:r.prompt}),s=!0}catch{}}}function Vg(){let t=Is("claude");if(!t)throw new Error("A claude subagent needs a Claude default or favorite; favorite a Claude model first.");return t}function mu(t,e){let n=t.parent.backend==="claude",r=null,s=()=>r??=Vg(),i=n&&t.parent.mode!=null?t.parent.mode:s().mode;return{model:e.model??(n?t.parent.model:null)??s().model,backend:"claude",mode:i,provider:null,thinking:e.thinking??null}}function Jg(t,e){return`${t.parent.channel||"default"}#sub:${e}`}function hu(t,e){let n=Xg(t,e);return t.workspace?{...n,cwd:t.workspace,policy:pu(n.policy)}:n}function Xg(t,e){let n=Er(void 0,Fg),r=Bg();return{runId:r,session:{sessionId:null,backendSessionId:null,engineKey:Jg(t,r)},selection:e,cwd:t.cwd,spec:du(t.role,"claude",{mcpAllowlist:n??null}),prompt:{text:`Task: ${t.task.prompt}`,attachments:[]},context:{channel:t.parent.channel??"",project:t.parent.project??"general",trigger:"subagent",ownerSessionId:t.parent.sessionId??null,executionKind:"local",isUserInitiated:!1,scheduleTaskId:null},policy:{background:"none",recordCost:!0,hooks:!1,loadRules:!1,mcpComposition:"direct",mcpToolAllowlist:n,captureTranscripts:!1}}}function Qg(t,e){t.catch(()=>{}).then(()=>Dt.close(e)).catch(n=>fu.warn(`releasing child engine ${e} failed: ${n.message}`))}async function Yg(t){let e=Wg(t),n=mu(t,e);if(!n.model)throw new Error("A claude subagent needs a model: set one on the task or the role.");let r=hu(t,n),s=cu(r,t.onNotice?[gu(t)]:[]);Qg(s.settled,r.session.engineKey);let i=()=>{s.cancel("user")};t.signal?.addEventListener("abort",i,{once:!0});let o;try{o=await s.result}finally{t.signal?.removeEventListener("abort",i)}if(t.signal?.aborted)throw new Error("Subagent was aborted.");return qg(t,o,n.model)}function Zg(t){let e=t.reportedAccounting,n=gs();return n.input=e?.inputTokens??0,n.output=e?.outputTokens??0,n.cacheRead=e?.cacheReadTokens??0,n.cacheWrite=e?.cacheCreationTokens??0,n.cost=t.total_cost_usd??0,n.turns=t.num_turns??0,n}function qg(t,e,n){let r=e.rateLimited||!e.finalOutput&&!!e.rateLimitMessage;return{description:t.task.description,prompt:t.task.prompt,subagentType:t.task.subagent_type,output:e.finalOutput??"",usage:Zg(e),model:e.reportedAccounting?.model??n,backend:"claude",...r?{stopReason:"error",errorMessage:e.rateLimitMessage??"Subagent run failed."}:{}}}function gu(t){let e=t.onNotice,n=t.ref,r={ref:n,type:t.task.subagent_type,description:t.task.description,backend:"claude",...t.task.clean?{clean:!0}:{}},s=null,i=!1,o=a=>{try{e(i?a:{...a,prompt:t.task.prompt}),i=!0}catch{}};return{onEvent(a){if(!("subagent"in a&&a.subagent)){if(a.type==="assistant_text"){a.model&&(s=a.model),a.text&&o({...r,model:s,kind:"assistant_text",text:a.text});return}if(a.type==="tool_use"){o({...r,model:s,kind:"tool_use",toolUseId:`${n}:${a.toolUseId}`,name:a.name,input:a.input});return}a.type==="tool_result"&&o({...r,model:s,kind:"tool_result",toolUseId:`${n}:${a.toolUseId}`,ok:a.ok,content:a.content,...a.images?.length?{images:a.images}:{}})}}}}var Nw={claudeChildConfig:mu,claudeChildRequest:hu,claudeNoticeObserver:gu};export{wu as a,Ns as b,C as c,my as d,Se as e,_e as f,qs as g,qt as h,en as i,ri as j,Xy as k,Ul as l,ii as m,ic as n,Q as o,lk as p,xi as q,Ki as r,Hi as s,ep as t,m_ as u,h_ as v,g_ as w,y_ as x,vo as y,k_ as z,v_ as A,On as B,P_ as C,B as D,Ro as E,St as F,tb as G,nb as H,nf as I,Ko as J,ib as K,Ff as L,Wf as M,Xn as N,jb as O,Ub as P,Dh as Q,jh as R,Hh as S,Ba as T,z as U,fT as V,mT as W,zh as X,Xh as Y,sr as Z,Ka as _,Zh as $,qh as aa,za as ba,he as ca,or as da,cu as ea,yw as fa,kw as ga,pu as ha,Kg as ia,Uw as ja,Nw as ka,W_ as la,kt as ma,Dt as na};
@@ -1,4 +0,0 @@
1
- import { createRequire as __cortexCreateRequire } from 'node:module';
2
- const require = __cortexCreateRequire(import.meta.url);
3
- const __cortexPackageRoot = new URL("../../", import.meta.url);
4
- import{a as d}from"./chunk-OKRK6JPY.js";var h="Model override: pi provider/model[:thinking], claude model ID. Default: role model, then parent model.",A="Backend override. Default: role backend, then parent backend.",$="Delegate isolated, one-shot work; children cannot delegate. Give self-contained prompts. Choose one mode: single, parallel, or chain. Supports both backends. Set clean for work that must not be shaped by Cortex context: the child runs in a fresh workspace with its brief and the files you list in files, copied to inputs/. Its brief must stand alone, name those files as inputs/<name>, and include external paths only when the user explicitly authorizes access, stating the allowed operations. Its result ends with the workspace path, where it leaves its output.",U="Run in a fresh workspace without Cortex context. Implied by files.",D="Files or directories (absolute or ~ paths) copied into the workspace inputs/. Implies clean.",g=["description","prompt","subagent_type"];function _(n,e){if(n!=null){if(n==="claude"||n==="pi")return n;throw new Error(`${e} backend must be "claude" or "pi".`)}}function S(n){for(let e of g)if(typeof n[e]!="string"||n[e].trim()==="")throw new Error(`Agent task requires a non-empty ${e}.`);_(n.backend,"Agent task"),T(n)}function T(n){if(n.clean!==void 0&&typeof n.clean!="boolean")throw new Error("Agent task clean must be a boolean.");let e=n.files;if(e!==void 0&&(!Array.isArray(e)||e.some(o=>typeof o!="string"||o.trim()==="")))throw new Error("Agent task files must be a list of non-empty paths.")}function f(n,e){if(e.length===0)throw new Error(`${n} requires at least one task.`);if(e.length>8)throw new Error(`Agent ${n} task maximum is 8.`);for(let o of e)S(o);return{mode:n,tasks:e}}function G(n){let e=n??{},o=g.some(s=>s in e),t=Array.isArray(e.parallel),r=Array.isArray(e.chain);if(Number(o)+Number(t)+Number(r)!==1)throw new Error("Provide exactly one Agent mode: single fields, parallel, or chain.");if(t)return f("parallel",e.parallel);if(r)return f("chain",e.chain);let i=e;return S(i),{mode:"single",tasks:[i]}}var y=24,u=480;function K(n){return[...C(n.claudeModel,(n.subagentClaudeModels??[]).map(e=>e.id)),...n.subagentPiModels??[]]}var N={model:h,backend:A},x="Role name, such as explore, general-purpose, or plan.",k="Role name for single mode, such as explore, general-purpose, or plan.";function F(n){let e=(n.roles??[]).map(r=>({name:r.name.trim(),summary:r.summary.trim()})).filter(r=>r.name!=="").sort((r,i)=>r.name.localeCompare(i.name)),o=n.models??[],t=e.length>0?` Available here: ${B(e)}.`:"";return{subagentType:e.length>0?`Role name.${t}`:x,subagentTypeSingle:e.length>0?`Role name for single mode.${t}`:k,...N,catalog:R(o)}}function j(n){let e=[];for(let o of n){let t=o.name.trim();t&&e.push({name:t,summary:M(o.description)})}return e}function C(n,e=d){let o=e.length>0?e:d,t=o.map(i=>({backend:"claude",id:i})),r=n?.trim();return r&&!o.includes(r)&&t.push({backend:"claude",id:r}),t}function X(n){let e=[];for(let o of n){let t=o.id.trim();if(!t)continue;let r=o.provider.trim();e.push(r?{backend:"pi",provider:r,id:t}:{backend:"pi",id:t})}return e}function Y(n){return JSON.stringify(n)}function H(n){if(!n)return[];let e;try{e=JSON.parse(n)}catch{return[]}if(!Array.isArray(e))return[];let o=e,t=[];for(let r of o){if(!I(r))continue;let{backend:i,provider:s,id:c}=r;if(i!=="claude"&&i!=="pi"||typeof c!="string"||!c.trim())continue;let l={backend:i,id:c.trim()};typeof s=="string"&&s.trim()&&(l.provider=s.trim()),t.push(l)}return t}function I(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function M(n){let e=n.trim(),o=e.indexOf(". "),t=o>=0?e.slice(0,o):e;return t.endsWith(".")&&(t=t.slice(0,-1)),t.length>80&&(t=`${t.slice(0,80)}\u2026`),t}function w(n){let e=n.id.trim();if(!e)return null;if(n.backend==="claude")return e;let o=n.provider?.trim()??"";return o?`${o}/${e}`:e}function O(n){let e=new Set,o=[];for(let t of n){let r=w(t);if(!r)continue;let i=`${t.backend}:${r}`;e.has(i)||(e.add(i),o.push({backend:t.backend,name:r}))}return o.sort((t,r)=>t.backend===r.backend?t.name.localeCompare(r.name):t.backend==="claude"?-1:1),o}var E=" Known models \u2014 ";function R(n){let e=O(n),o=["claude","pi"].flatMap(t=>{let r=e.filter(i=>i.backend===t).map(i=>i.name);return r.length?[`${t}: ${r.join(", ")}`]:[]});return o.length?`${E}${o.join("; ")}.`:""}function q(n){return n.split(E)[0]}function B(n){let e=n.slice(0,y),o=n.length-e.length,t=o>0?` (+${o} more)`:"",r=e.map(a=>a.summary?`${a.name} \u2014 ${a.summary}`:a.name).join("; ");if(r.length+t.length<=u)return r+t;let i=e.map(a=>a.name).join(", ");if(i.length+t.length<=u)return i+t;let s=[],c=0;for(let a of e){let p=a.name.length+(s.length>0?2:0),m=n.length-(s.length+1),b=m>0?` (+${m} more)`.length:0;if(c+p+b>u)break;s.push(a.name),c+=p}let l=n.length-s.length;return s.join(", ")+(l>0?` (+${l} more)`:"")}export{$ as a,U as b,D as c,G as d,K as e,F as f,j as g,C as h,X as i,Y as j,H as k,R as l,q as m};