@cortex-agent/server 2026.11.17 → 2026.12.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (338) hide show
  1. package/README.md +5 -5
  2. package/THIRD_PARTY_NOTICES.txt +860 -294
  3. package/defaults/hooks/quota-stop.mjs +37 -0
  4. package/defaults/prompts/clean-workspace.md +5 -0
  5. package/dist/agent-adapter/claude/remote-mcp-proxy.js +1 -1
  6. package/dist/chunks/agent-runner-LVZVKBZX.js +4 -0
  7. package/dist/chunks/anthropic-messages-TT6454AA.js +8 -0
  8. package/dist/chunks/azure-openai-responses-52LR2XZD.js +4 -0
  9. package/dist/chunks/bedrock-converse-stream-EOZGYUNY.js +60 -0
  10. package/dist/chunks/child-runner-SMG2VOU5.js +4 -0
  11. package/dist/chunks/chunk-24DH4IR5.js +4 -0
  12. package/dist/chunks/chunk-25XKBRDT.js +70 -0
  13. package/dist/chunks/{chunk-VTL3Z2OP.js → chunk-2ABET62E.js} +1 -1
  14. package/dist/chunks/chunk-2BVUA256.js +4 -0
  15. package/dist/chunks/{chunk-4YLAGSDM.js → chunk-2WFL62UO.js} +1 -1
  16. package/dist/chunks/{chunk-LQTFDC67.js → chunk-335SSANX.js} +1 -1
  17. package/dist/chunks/chunk-377OPTXX.js +17 -0
  18. package/dist/chunks/chunk-3EZNVLBF.js +129 -0
  19. package/dist/chunks/{chunk-V6X7Y62J.js → chunk-3O6ZG5HA.js} +1 -1
  20. package/dist/chunks/{chunk-6AKUD3CF.js → chunk-3XLHL5YT.js} +1 -1
  21. package/dist/chunks/{chunk-2ATTYCRJ.js → chunk-4HRI75GU.js} +1 -1
  22. package/dist/chunks/chunk-4JBYLRPM.js +57 -0
  23. package/dist/chunks/chunk-4KKV7VKE.js +4 -0
  24. package/dist/chunks/chunk-4KQHDDC5.js +4 -0
  25. package/dist/chunks/chunk-4SWD4JMP.js +33 -0
  26. package/dist/chunks/chunk-52VCLZS5.js +4 -0
  27. package/dist/chunks/chunk-54P7TSY3.js +10 -0
  28. package/dist/chunks/chunk-5DVSAXOI.js +7 -0
  29. package/dist/chunks/chunk-5F3A62YS.js +4 -0
  30. package/dist/chunks/{chunk-S3MR37DL.js → chunk-5FHETFZM.js} +1 -1
  31. package/dist/chunks/{chunk-CEGSDGYQ.js → chunk-5LBLRAHS.js} +1 -1
  32. package/dist/chunks/chunk-5UYVNA3W.js +4 -0
  33. package/dist/chunks/chunk-6G3OYMCV.js +21 -0
  34. package/dist/chunks/chunk-7GGPYU5E.js +30 -0
  35. package/dist/chunks/chunk-7TYSMLUV.js +4 -0
  36. package/dist/chunks/chunk-7W7VYUTK.js +5 -0
  37. package/dist/chunks/chunk-AXYAZTTN.js +6 -0
  38. package/dist/chunks/chunk-B3NB243Z.js +4 -0
  39. package/dist/chunks/{chunk-XPPZ6Y3X.js → chunk-BKYP6AGM.js} +1 -1
  40. package/dist/chunks/{chunk-QUXPMNFQ.js → chunk-BVEDNESB.js} +1 -1
  41. package/dist/chunks/chunk-BWDJS6A4.js +12 -0
  42. package/dist/chunks/chunk-C6YVF7EI.js +4 -0
  43. package/dist/chunks/chunk-CEJIYYVE.js +15 -0
  44. package/dist/chunks/{chunk-5PAW3DEU.js → chunk-CI2RHH74.js} +4 -4
  45. package/dist/chunks/{chunk-OFEPDNRB.js → chunk-CMSOOLJB.js} +1 -1
  46. package/dist/chunks/chunk-CSVTYYLP.js +4 -0
  47. package/dist/chunks/chunk-DE5EGVKG.js +6 -0
  48. package/dist/chunks/{chunk-E6BYRULL.js → chunk-DK3RPZOQ.js} +1 -1
  49. package/dist/chunks/{chunk-ROVKOIHF.js → chunk-DK4UCK7L.js} +1 -1
  50. package/dist/chunks/chunk-DYLBVUAU.js +4 -0
  51. package/dist/chunks/{chunk-WBSE3EF3.js → chunk-FDC2GRBK.js} +1 -1
  52. package/dist/chunks/chunk-FE7HH5JS.js +18 -0
  53. package/dist/chunks/chunk-FYD57YRO.js +436 -0
  54. package/dist/chunks/chunk-G264APQN.js +5 -0
  55. package/dist/chunks/chunk-G4JYZFEO.js +11 -0
  56. package/dist/chunks/chunk-GFFM56U2.js +4 -0
  57. package/dist/chunks/chunk-GOS3P7KS.js +132 -0
  58. package/dist/chunks/{chunk-2VVRTJQN.js → chunk-HVN37UXD.js} +1 -1
  59. package/dist/chunks/{chunk-53TQNK7Z.js → chunk-IGZWZP7Z.js} +1 -1
  60. package/dist/chunks/{chunk-AFTBQRPN.js → chunk-IJ7XFQMI.js} +1 -1
  61. package/dist/chunks/{chunk-U23S37TT.js → chunk-IMMGYDAB.js} +1 -1
  62. package/dist/chunks/chunk-IOWBF7UK.js +10 -0
  63. package/dist/chunks/{chunk-MGYYSX7Y.js → chunk-ITGCWQFK.js} +1 -1
  64. package/dist/chunks/{chunk-QEL6CMLE.js → chunk-IVZ7QUEG.js} +1 -1
  65. package/dist/chunks/{chunk-EE3WT25T.js → chunk-IWY2HIFK.js} +1 -1
  66. package/dist/chunks/{chunk-KGJZAYQD.js → chunk-J7OBATRN.js} +1 -1
  67. package/dist/chunks/{chunk-NXZS5PEW.js → chunk-JGUEIW2W.js} +1 -1
  68. package/dist/chunks/chunk-JZ7U7RUK.js +351 -0
  69. package/dist/chunks/{chunk-VIMHSW6J.js → chunk-KJUQCCB5.js} +1 -1
  70. package/dist/chunks/{chunk-BUZQBTV2.js → chunk-KST6OY76.js} +1 -1
  71. package/dist/chunks/{chunk-KDPY2YA3.js → chunk-KZSAFVSY.js} +2 -2
  72. package/dist/chunks/chunk-LD2ZSH3M.js +903 -0
  73. package/dist/chunks/{chunk-RYLSRII6.js → chunk-LE6QPXN6.js} +1 -1
  74. package/dist/chunks/{chunk-TX46YMGI.js → chunk-LIIZI3HY.js} +1 -1
  75. package/dist/chunks/{chunk-3CZPBLB3.js → chunk-MJQ2D2OP.js} +1 -1
  76. package/dist/chunks/{chunk-P7TVR4GY.js → chunk-NHHR4DCF.js} +1 -1
  77. package/dist/chunks/chunk-NW4GW47L.js +4 -0
  78. package/dist/chunks/chunk-OALEJ6FG.js +60 -0
  79. package/dist/chunks/chunk-OIV4DIMB.js +4 -0
  80. package/dist/chunks/{chunk-T73GHMFB.js → chunk-OJ37ZWBG.js} +1 -1
  81. package/dist/chunks/{chunk-7GEBDPTT.js → chunk-OZXMPBUX.js} +1 -1
  82. package/dist/chunks/chunk-PG7452XE.js +4 -0
  83. package/dist/chunks/chunk-PJCUB7YJ.js +4 -0
  84. package/dist/chunks/{chunk-RA2BUYI3.js → chunk-PTS3J4DQ.js} +1 -1
  85. package/dist/chunks/{chunk-2ROGTDM2.js → chunk-PVVEEBUU.js} +1 -1
  86. package/dist/chunks/{chunk-W6AKCEYF.js → chunk-Q7BZLPBU.js} +1 -1
  87. package/dist/chunks/{chunk-SY2HV3V5.js → chunk-QC66ZXPP.js} +1 -1
  88. package/dist/chunks/chunk-QXFWIL4C.js +4 -0
  89. package/dist/chunks/{chunk-NRD57ICT.js → chunk-R2CCD4OF.js} +1 -1
  90. package/dist/chunks/{chunk-R52AVUQB.js → chunk-RG5GP4RB.js} +1 -1
  91. package/dist/chunks/{chunk-IKLTEWA3.js → chunk-RW2F2QNP.js} +1 -1
  92. package/dist/chunks/{chunk-XEBEWR6Y.js → chunk-RWPO3NZ3.js} +1 -1
  93. package/dist/chunks/chunk-SDUS2H3E.js +4 -0
  94. package/dist/chunks/chunk-SIHGKM4E.js +4 -0
  95. package/dist/chunks/{chunk-NNBSSISP.js → chunk-SKHFU5DI.js} +1 -1
  96. package/dist/chunks/{chunk-STUHNKQS.js → chunk-SM45TH22.js} +1 -1
  97. package/dist/chunks/chunk-T54CZKNJ.js +6 -0
  98. package/dist/chunks/chunk-TRXLIL7V.js +4 -0
  99. package/dist/chunks/{chunk-KUDK7GPS.js → chunk-UEEW2R4E.js} +1 -1
  100. package/dist/chunks/chunk-UHXPRU6G.js +10 -0
  101. package/dist/chunks/chunk-UPQVWHZ3.js +4 -0
  102. package/dist/chunks/{chunk-BDLKI2NT.js → chunk-VHX2GHBF.js} +1 -1
  103. package/dist/chunks/chunk-VOAKRJ4R.js +4 -0
  104. package/dist/chunks/{chunk-FP7ML72L.js → chunk-WU7RNAZD.js} +1 -1
  105. package/dist/chunks/chunk-WZC4TDDM.js +6 -0
  106. package/dist/chunks/chunk-X2TKJ7KR.js +11 -0
  107. package/dist/chunks/{chunk-H4QZ2P3Z.js → chunk-X5ND4H4P.js} +1 -1
  108. package/dist/chunks/{chunk-5A6CA5TM.js → chunk-Y3AOGNDT.js} +1 -1
  109. package/dist/chunks/chunk-Y6DGVTKM.js +6 -0
  110. package/dist/chunks/{chunk-LP7T32PW.js → chunk-YAEHSSR4.js} +1 -1
  111. package/dist/chunks/chunk-YWPBE5LP.js +4 -0
  112. package/dist/chunks/chunk-ZAVX7G2M.js +15 -0
  113. package/dist/chunks/chunk-ZD2M73XA.js +19 -0
  114. package/dist/chunks/chunk-ZD4O6NPV.js +4 -0
  115. package/dist/chunks/chunk-ZNAMETPQ.js +4 -0
  116. package/dist/chunks/chunk-ZY6N5LVQ.js +4 -0
  117. package/dist/chunks/chunk-ZYQ4TDTT.js +81 -0
  118. package/dist/chunks/cli-VB2N7HEK.js +55 -0
  119. package/dist/chunks/cloudflare-workers-ai-system-one-YKU742EC.js +4 -0
  120. package/dist/chunks/context-CI2FKEQE.js +4 -0
  121. package/dist/chunks/cost-CZRRSIUF.js +5 -0
  122. package/dist/chunks/dist-QCNQN6DY.js +4 -0
  123. package/dist/chunks/{easter-egg-3d-CZH7AYZ7.js → easter-egg-3d-XR5S2O3T.js} +1 -1
  124. package/dist/chunks/execution-repo-5TLV2NM4.js +4 -0
  125. package/dist/chunks/{executions-BN6OLLVM.js → executions-I3UUIGSL.js} +1 -1
  126. package/dist/chunks/file-Y5G56IUT.js +4 -0
  127. package/dist/chunks/github-copilot-BRU2SRRZ.js +4 -0
  128. package/dist/chunks/google-generative-ai-ZF5QEUZV.js +4 -0
  129. package/dist/chunks/google-vertex-4PJZZI3Y.js +4 -0
  130. package/dist/chunks/init-A6GY656J.js +4 -0
  131. package/dist/chunks/{install-cli-ABBD7DO5.js → install-cli-FALWKQYO.js} +1 -1
  132. package/dist/chunks/{interaction-ask-EE2UPR3Q.js → interaction-ask-O5HGF6CH.js} +1 -1
  133. package/dist/chunks/{interaction-plan-C446T2GZ.js → interaction-plan-JTVDN3BC.js} +1 -1
  134. package/dist/chunks/kimi-coding-ZCIBMDZ6.js +4 -0
  135. package/dist/chunks/{llama-cpp-classify-IA2F2H7A.js → llama-cpp-classify-NRUXAIGQ.js} +3 -3
  136. package/dist/chunks/local-client-stop-RS4AHNF4.js +4 -0
  137. package/dist/chunks/memory-cli-DIT4DQF3.js +11 -0
  138. package/dist/chunks/meta-JQH66YU7.js +4 -0
  139. package/dist/chunks/mistral-conversations-CXHOECUV.js +7 -0
  140. package/dist/chunks/model-resolver-GIBPYRKP.js +4 -0
  141. package/dist/chunks/monitor-Z2HKNY5E.js +4 -0
  142. package/dist/chunks/openai-codex-responses-U6DGMGDK.js +12 -0
  143. package/dist/chunks/openai-completions-PP4XLLOM.js +9 -0
  144. package/dist/chunks/{openai-decisions-P5UX7BWY.js → openai-decisions-JU6QQKEM.js} +1 -1
  145. package/dist/chunks/openai-responses-2SG757TL.js +6 -0
  146. package/dist/chunks/openrouter-images-32M7YZWC.js +4 -0
  147. package/dist/chunks/pi-messages-VSINMXN4.js +10 -0
  148. package/dist/chunks/radius-THYKWV4E.js +4 -0
  149. package/dist/chunks/remote-ops-2WBEFQ3E.js +14 -0
  150. package/dist/chunks/runner-5MKMRTIN.js +4 -0
  151. package/dist/chunks/runtime-DST3H5JP.js +4 -0
  152. package/dist/chunks/schedule-cli-V7Y2BBVY.js +4 -0
  153. package/dist/chunks/slack-R7SEJYMY.js +4 -0
  154. package/dist/chunks/start-ui-http-7K5JOLPU.js +43 -0
  155. package/dist/chunks/subagent-Z5IQ4L54.js +4 -0
  156. package/dist/chunks/tool-shims-YCXZWTST.js +4 -0
  157. package/dist/chunks/typesafe-system-one-M2DABJSZ.js +4 -0
  158. package/dist/chunks/ui-board-HQIE4RZG.js +5 -0
  159. package/dist/chunks/ui-decision-YBZDS4YW.js +4 -0
  160. package/dist/chunks/{ui-file-6PLXHSTB.js → ui-file-SRD4ILBS.js} +1 -1
  161. package/dist/chunks/ui-view-Z25MTZT7.js +4 -0
  162. package/dist/chunks/virtual-modules-H4DXPJZB.js +4 -0
  163. package/dist/chunks/{waitpoint-W5M3BE55.js → waitpoint-M6JZBSLT.js} +1 -1
  164. package/dist/chunks/workers-SQ2R32TK.js +4 -0
  165. package/dist/client-bundle/client.mjs +229 -62
  166. package/dist/client-bundle/manifest.json +2 -2
  167. package/dist/core/pi-sdk.js +1 -1
  168. package/dist/domain/auth/cc-auth-cli.js +1 -1
  169. package/dist/domain/mcp/bundled-server.js +1 -1
  170. package/dist/domain/mcp/feishu/client.js +1 -1
  171. package/dist/entry/app.js +138 -556
  172. package/dist/entry/browser-cli.js +1 -1
  173. package/dist/entry/cli.js +1 -1
  174. package/dist/entry/cortex-cli.js +1 -1
  175. package/dist/entry/daemon.js +3 -3
  176. package/dist/entry/hook-cli.js +1 -1
  177. package/dist/entry/production-app-bootstrap.js +1 -1
  178. package/dist/entry/production-evidence-export-cli.js +1 -1
  179. package/dist/entry/signal-cli.js +1 -1
  180. package/dist/tui/index.js +1 -1
  181. package/package.json +1 -1
  182. package/vendor/pi/CHANGELOG.md +330 -0
  183. package/vendor/pi/dist/codemode-worker.js +2 -0
  184. package/vendor/pi/dist/core/export-html/ansi-to-html.js +57 -20
  185. package/vendor/pi/dist/core/export-html/template.css +9 -0
  186. package/vendor/pi/dist/core/export-html/template.js +166 -46
  187. package/vendor/pi/dist/core/export-html/tool-renderer.js +5 -3
  188. package/vendor/pi/dist/core/extensions/loader.js +1 -1
  189. package/vendor/pi/dist/extensions/codemode/execute.js +15 -13
  190. package/vendor/pi/dist/modes/interactive/theme/theme.js +36 -23
  191. package/vendor/pi/dist/utils/image-resize-worker.js +1 -1
  192. package/vendor/pi/dist/utils/image-resize.js +1 -1
  193. package/vendor/pi/docs/cli.md +35 -12
  194. package/vendor/pi/docs/custom-provider.md +2 -0
  195. package/vendor/pi/docs/environment-variables.md +2 -0
  196. package/vendor/pi/docs/extensions.md +3192 -225
  197. package/vendor/pi/docs/keybindings.md +2 -2
  198. package/vendor/pi/docs/llama-cpp.md +27 -19
  199. package/vendor/pi/docs/mcp.md +6 -4
  200. package/vendor/pi/docs/message-types.md +1 -1
  201. package/vendor/pi/docs/models-configuration.md +9 -3
  202. package/vendor/pi/docs/models.md +2 -1
  203. package/vendor/pi/docs/nvidia-rtx-llama-cpp.md +5 -5
  204. package/vendor/pi/docs/packages.md +24 -0
  205. package/vendor/pi/docs/prompt-templates.md +1 -1
  206. package/vendor/pi/docs/providers.md +4 -2
  207. package/vendor/pi/docs/quickstart.md +7 -3
  208. package/vendor/pi/docs/rpc-commands.md +1 -1
  209. package/vendor/pi/docs/rpc.md +4 -2
  210. package/vendor/pi/docs/sessions.md +17 -3
  211. package/vendor/pi/docs/settings.md +6 -5
  212. package/vendor/pi/docs/slash-commands.md +3 -2
  213. package/vendor/pi/docs/terminal-setup.md +3 -1
  214. package/vendor/pi/docs/tmux.md +6 -0
  215. package/vendor/pi/docs/tui.md +4 -0
  216. package/vendor/pi/docs/windows.md +27 -0
  217. package/vendor/pi/examples/extensions/README.md +2 -1
  218. package/vendor/pi/examples/extensions/custom-provider-anthropic/index.ts +27 -31
  219. package/vendor/pi/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  220. package/vendor/pi/examples/extensions/custom-provider-anthropic/package.json +1 -1
  221. package/vendor/pi/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  222. package/vendor/pi/examples/extensions/debug-provider.ts +2 -2
  223. package/vendor/pi/examples/extensions/gondolin/index.ts +4 -7
  224. package/vendor/pi/examples/extensions/gondolin/package-lock.json +19 -29
  225. package/vendor/pi/examples/extensions/gondolin/package.json +2 -2
  226. package/vendor/pi/examples/extensions/plan-mode/index.ts +23 -13
  227. package/vendor/pi/examples/extensions/plan-mode/utils.ts +42 -16
  228. package/vendor/pi/examples/extensions/preset.ts +2 -0
  229. package/vendor/pi/examples/extensions/reload-runtime.ts +17 -5
  230. package/vendor/pi/examples/extensions/subagent/README.md +14 -11
  231. package/vendor/pi/examples/extensions/subagent/index.ts +392 -171
  232. package/vendor/pi/examples/extensions/todo.ts +7 -0
  233. package/vendor/pi/examples/extensions/tools.ts +2 -0
  234. package/vendor/pi/examples/extensions/with-deps/package-lock.json +2 -2
  235. package/vendor/pi/examples/extensions/with-deps/package.json +1 -1
  236. package/vendor/pi/examples/tsconfig.json +208 -0
  237. package/vendor/pi/package.json +15 -16
  238. package/vendor/pi/schemas/models.schema.json +66 -37
  239. package/vendor/pi/schemas/settings.schema.json +18 -1
  240. package/vendor/pi-ai/bedrock.js +1 -1
  241. package/vendor/pi-ai/oauth-load.js +1 -1
  242. package/web/dist/assets/{board-math-css-BgIyUG-C.js → board-math-css-DKX6FcUS.js} +1 -1
  243. package/web/dist/assets/index-D11wi0uG.js +540 -0
  244. package/web/dist/assets/index-JedYumhY.css +1 -0
  245. package/web/dist/assets/{index-C2eMpcuI.js → index-jl30Gy8P.js} +1 -1
  246. package/web/dist/index.html +2 -2
  247. package/dist/chunks/anthropic-messages-M732OMEE.js +0 -8
  248. package/dist/chunks/azure-openai-responses-RAKTV6JY.js +0 -4
  249. package/dist/chunks/bedrock-converse-stream-WNUGNZ27.js +0 -62
  250. package/dist/chunks/child-runner-MO5RT6FH.js +0 -4
  251. package/dist/chunks/chunk-3CPIMAYX.js +0 -30
  252. package/dist/chunks/chunk-3ORG56I5.js +0 -8
  253. package/dist/chunks/chunk-4EX2JJWB.js +0 -4
  254. package/dist/chunks/chunk-5DF5WJNM.js +0 -60
  255. package/dist/chunks/chunk-7GAYFN52.js +0 -18
  256. package/dist/chunks/chunk-AVXDF7AG.js +0 -4
  257. package/dist/chunks/chunk-BJGYGEZO.js +0 -6
  258. package/dist/chunks/chunk-BZDIAI5M.js +0 -125
  259. package/dist/chunks/chunk-CK3P345X.js +0 -133
  260. package/dist/chunks/chunk-CVC66CFV.js +0 -33
  261. package/dist/chunks/chunk-ETIBCA2S.js +0 -4
  262. package/dist/chunks/chunk-FF7UELTU.js +0 -4
  263. package/dist/chunks/chunk-FX6MOGLR.js +0 -11
  264. package/dist/chunks/chunk-G2V65UBA.js +0 -4
  265. package/dist/chunks/chunk-HGPBHTVD.js +0 -6
  266. package/dist/chunks/chunk-IYVZHGUQ.js +0 -5
  267. package/dist/chunks/chunk-JJDEQ6N2.js +0 -4
  268. package/dist/chunks/chunk-KDYEGGMW.js +0 -4
  269. package/dist/chunks/chunk-L6VCIGWS.js +0 -11
  270. package/dist/chunks/chunk-LACGULCN.js +0 -10
  271. package/dist/chunks/chunk-LAWOWPZX.js +0 -363
  272. package/dist/chunks/chunk-NNTQUHLO.js +0 -877
  273. package/dist/chunks/chunk-OE4KH3NJ.js +0 -4
  274. package/dist/chunks/chunk-OSEIQ7SS.js +0 -4
  275. package/dist/chunks/chunk-PZMGBKUR.js +0 -13
  276. package/dist/chunks/chunk-QBKCAIJG.js +0 -4
  277. package/dist/chunks/chunk-QMSSIDRQ.js +0 -70
  278. package/dist/chunks/chunk-QUUEQRIT.js +0 -4
  279. package/dist/chunks/chunk-RA6HKFBV.js +0 -4
  280. package/dist/chunks/chunk-RDW6FRF5.js +0 -4
  281. package/dist/chunks/chunk-RF4JLYBX.js +0 -6
  282. package/dist/chunks/chunk-SFX7V5O2.js +0 -10
  283. package/dist/chunks/chunk-SKHLZ6XY.js +0 -9
  284. package/dist/chunks/chunk-STCNHXPJ.js +0 -6
  285. package/dist/chunks/chunk-UT6DGZDO.js +0 -4
  286. package/dist/chunks/chunk-VBN2JSER.js +0 -5
  287. package/dist/chunks/chunk-VK5J556O.js +0 -4
  288. package/dist/chunks/chunk-VPVSKJGX.js +0 -6
  289. package/dist/chunks/chunk-VQUPKMDR.js +0 -4
  290. package/dist/chunks/chunk-WEZWKMYU.js +0 -4
  291. package/dist/chunks/chunk-XYSXL3KX.js +0 -4
  292. package/dist/chunks/chunk-Y3GFB5XM.js +0 -8
  293. package/dist/chunks/chunk-YAAKL3QS.js +0 -80
  294. package/dist/chunks/chunk-YB5LUJHS.js +0 -65
  295. package/dist/chunks/chunk-YKKEI5GI.js +0 -4
  296. package/dist/chunks/chunk-Z24SBRJK.js +0 -4
  297. package/dist/chunks/cli-5DBTRMHU.js +0 -53
  298. package/dist/chunks/cloudflare-workers-ai-system-one-32JCFHI3.js +0 -4
  299. package/dist/chunks/context-GQKWKFRM.js +0 -4
  300. package/dist/chunks/cost-OOO32GLC.js +0 -5
  301. package/dist/chunks/dist-V5FRMUFH.js +0 -4
  302. package/dist/chunks/execution-repo-XXL4FXC6.js +0 -4
  303. package/dist/chunks/file-H572PL2Z.js +0 -4
  304. package/dist/chunks/github-copilot-HAI2DA62.js +0 -4
  305. package/dist/chunks/google-generative-ai-2G4ITOZL.js +0 -4
  306. package/dist/chunks/google-vertex-PACHCMRZ.js +0 -4
  307. package/dist/chunks/init-75F4V7SK.js +0 -4
  308. package/dist/chunks/kimi-coding-HMJRKCPA.js +0 -4
  309. package/dist/chunks/local-client-stop-5YOLXGYT.js +0 -4
  310. package/dist/chunks/memory-cli-5SSF6YJM.js +0 -11
  311. package/dist/chunks/meta-KY3LNFV2.js +0 -4
  312. package/dist/chunks/mistral-conversations-VHP63CDS.js +0 -7
  313. package/dist/chunks/model-resolver-FVJNZ6NA.js +0 -4
  314. package/dist/chunks/openai-codex-responses-EHJ4AZBE.js +0 -12
  315. package/dist/chunks/openai-completions-CRAGQFCE.js +0 -9
  316. package/dist/chunks/openai-responses-IZ22NVQ7.js +0 -6
  317. package/dist/chunks/openrouter-images-W2JAMSRH.js +0 -4
  318. package/dist/chunks/pi-messages-MJEEQU2R.js +0 -10
  319. package/dist/chunks/radius-ZM7ZRMXF.js +0 -4
  320. package/dist/chunks/remote-ops-O5CR4RGA.js +0 -14
  321. package/dist/chunks/runner-S6R3US24.js +0 -4
  322. package/dist/chunks/runtime-6YLTA2ZD.js +0 -4
  323. package/dist/chunks/schedule-cli-4T4YC5V5.js +0 -4
  324. package/dist/chunks/slack-2CGM4SMY.js +0 -4
  325. package/dist/chunks/start-ui-http-3D7QNHGB.js +0 -43
  326. package/dist/chunks/subagent-OZGUOV3J.js +0 -4
  327. package/dist/chunks/tool-shims-IA2WELXJ.js +0 -4
  328. package/dist/chunks/typesafe-system-one-6ULACYD4.js +0 -4
  329. package/dist/chunks/ui-board-H4INJD6C.js +0 -5
  330. package/dist/chunks/ui-decision-6HHNROIT.js +0 -4
  331. package/dist/chunks/ui-view-6MDU4GXY.js +0 -4
  332. package/dist/chunks/virtual-modules-OFI7QKYH.js +0 -4
  333. package/dist/chunks/workers-GTFP75MS.js +0 -4
  334. package/vendor/pi/examples/extensions/sandbox/index.ts +0 -321
  335. package/vendor/pi/examples/extensions/sandbox/package-lock.json +0 -92
  336. package/vendor/pi/examples/extensions/sandbox/package.json +0 -19
  337. package/web/dist/assets/index-9lyu2S6W.css +0 -1
  338. package/web/dist/assets/index-C-hpzey7.js +0 -532
@@ -0,0 +1,81 @@
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 As,b as Cs}from"./chunk-IVZ7QUEG.js";import{g as Vs,h as Js}from"./chunk-TJ4GQRT6.js";import{a as ji,e as wt,f as qi,h as Hi}from"./chunk-Y3AOGNDT.js";import{a as Fn,b as Wn}from"./chunk-LMDWRRX4.js";import{a as Mt,b as ze,c as Ns,d as js,e as Us,f as $s,g as Bs,h as Fs,i as Ws,m as Ks,n as qs,p as Hs}from"./chunk-3EZNVLBF.js";import{A as zs,b as Mi,d as Ot,e as Qn,h as Rs,i as Ps,j as Os,k as Ms,r as Ls,s as Lt,t as Ds}from"./chunk-UHXPRU6G.js";import{d as Ys}from"./chunk-CMSOOLJB.js";import{k as cs,l as qn}from"./chunk-4KQHDDC5.js";import{a as Kn,f as os}from"./chunk-QXFWIL4C.js";import{a as Qi,b as Gi,c as Vi,d as Ct,e as Ji,f as Xi,g as Yi,h as Zi,i as es,j as ts,k as ns,l as rs,m as is,n as ss,p as Ts,q as Hn,r as _s,u as so,x as oo}from"./chunk-IOWBF7UK.js";import{c as Xs}from"./chunk-2ABET62E.js";import{h as U}from"./chunk-2WFL62UO.js";import{e as bs,k as ks}from"./chunk-PG7452XE.js";import{c as Ui,d as $i}from"./chunk-RW2F2QNP.js";import{a as ls,g as _e,i as eo,j as to,n as no,o as ae,p as ro,q as H,r as $,s as Q,t as Gn,u as ve,v as Dt,w as le,x as Nt,y as io}from"./chunk-HVN37UXD.js";import{m as Zs}from"./chunk-Y6DGVTKM.js";import{g as zn}from"./chunk-OZXMPBUX.js";import{a as us,c as as}from"./chunk-5T7IX5KN.js";import{a as Qs,c as _,d as Gs}from"./chunk-VHX2GHBF.js";import{A as vs,E as ws,I as xs,J as Es,L as re,M as Rt,N as Pt,O as Is,g as ds,h as ps,i as gs,j as ys,k as Ss}from"./chunk-C6YVF7EI.js";import{a as _t,c as Di}from"./chunk-ITGCWQFK.js";import{e as Ki}from"./chunk-PTS3J4DQ.js";import{a as fs,c as ms,d as hs}from"./chunk-IMMGYDAB.js";import{d as Et,e as It,f as At}from"./chunk-OJ37ZWBG.js";import{b as Tt,e as zi}from"./chunk-SKHFU5DI.js";import{a as Kc}from"./chunk-V35MFAUQ.js";import{a as xt}from"./chunk-OKRK6JPY.js";import{d as Fi,f as Wi}from"./chunk-52VCLZS5.js";import{a as Bi}from"./chunk-B3NB243Z.js";import{a as be}from"./chunk-LCKVYFMD.js";import{d as vt}from"./chunk-KST6OY76.js";import{c as Oi,f as g}from"./chunk-AXYAZTTN.js";import{K as f}from"./chunk-W34AK4SK.js";import{b as Te}from"./chunk-LIIZI3HY.js";import{a as j}from"./chunk-Q4UGYGU5.js";import{d as q,e as Ai}from"./chunk-TRXLIL7V.js";import{d as Li,e as S}from"./chunk-7GGPYU5E.js";import{e as p}from"./chunk-7W7VYUTK.js";import{c as Ni}from"./chunk-JGUEIW2W.js";import{e as M,f as Ci,g as ne,k as ke,l as Ri,m as kt,t as Pi,y as We}from"./chunk-T54CZKNJ.js";import{d as Wc,e as zc}from"./chunk-WHC7AYZD.js";var B;(function(t){t.MidTurnInject="mid-turn-inject",t.Usage="usage",t.BackgroundContinuation="background-continuation",t.Subagents="subagents"})(B||(B={}));var qc=[B.MidTurnInject,B.Subagents,B.BackgroundContinuation],Hc=[B.MidTurnInject,B.Usage,B.Subagents],we={claude:new Set(qc),pi:new Set(Hc)};import Qc from"node:path";var Vn=class{byPair=new Map;register(e,n){let r=n.map(o=>Qc.resolve(o)),i=this.byPair.get(e);if(i){i.refs+=1;for(let o of r)i.paths.includes(o)||i.paths.push(o)}else this.byPair.set(e,{paths:r,refs:1});let s=!1;return()=>{if(s)return;s=!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()]}},uo=new Vn;import Gc from"node:fs/promises";import jt from"node:path";var Vc=jt.join(ke,"provider-state.json");function Jc(){return{rateLimitThrottle:null,resumeQueue:[],providerUsage:[]}}function ao(t){return JSON.stringify(t,null,2)}async function lo(t){try{let e=JSON.parse(await Gc.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 Xc(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Yc(t){let e=t.rateLimitThrottle,n=t.providerUsage;return Object.hasOwn(t,"rateLimitThrottle")&&Object.hasOwn(t,"resumeQueue")&&(e===null||Xc(e))&&Array.isArray(t.resumeQueue)&&(n===void 0||Array.isArray(n))}async function Zc(t){let e=await lo(t);if(!e)return!1;if(!Yc(e))throw new Error(`${t} must contain rateLimitThrottle and resumeQueue`);return!0}function ed(t){return Object.hasOwn(t,"rateLimitThrottle")||Object.hasOwn(t,"resumeQueue")}function td(t){return{rateLimitThrottle:t.rateLimitThrottle??null,resumeQueue:t.resumeQueue??[],providerUsage:[]}}function nd(t){let e={...t};return delete e.rateLimitThrottle,delete e.resumeQueue,e}async function qk(t=M){let e=jt.join(t,"data"),n=jt.join(e,"schedules.json"),r=await lo(n);if(!r||!ed(r))return;let i=jt.join(e,"provider-state.json");await Zc(i)||await q(i,ao(td(r))),await q(n,ao(nd(r)))}var Jn=class{repo;constructor(e=Vc){this.repo=new Di({filePath:e,defaultValue:Jc})}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 getHardQuotaBlocks(){return(await this.repo.read()).hardQuotaBlocks??[]}async setHardQuotaBlocks(e){await this.repo.mutate(n=>({next:{...n,hardQuotaBlocks:e},result:void 0}))}async getQuotaWindowEvidence(){return(await this.repo.read()).quotaWindowEvidence??[]}async setQuotaWindowEvidence(e){await this.repo.mutate(n=>({next:{...n,quotaWindowEvidence:e},result:void 0}))}async getQuotaOverrides(){return(await this.repo.read()).quotaOverrides??[]}async setQuotaOverrides(e){await this.repo.mutate(n=>({next:{...n,quotaOverrides:e},result:void 0}))}async getSubscriptionSignOuts(){return{...(await this.repo.read()).subscriptionSignOuts}}async setSubscriptionSignOut(e,n){await this.repo.mutate(r=>{let i={...r.subscriptionSignOuts};return n===null?delete i[e]:i[e]=n,{next:{...r,subscriptionSignOuts:i},result:void 0}})}flush(){return this.repo.flush()}},G=new Jn;var Ke=p("quota-overrides"),qe=new j,O=null;function Ut(t,e,n){return t.provider===e&&t.route===n}function He(t){return t.overrides.filter(e=>e.until*1e3>t.now())}function rd(t){try{t.onChange?.()}catch(e){Ke.warn(`Override change callback failed: ${String(e)}`)}}function $t(t){if(t.timer&&clearTimeout(t.timer),t.timer=null,O!==t||t.overrides.length===0)return;let e=Math.min(...t.overrides.map(r=>r.until*1e3)),n=Math.min(Math.max(e-t.now(),0),2147483647);t.timer=setTimeout(()=>{qe.run(()=>id(t))},n),t.timer.unref?.()}async function Bt(t,e){await t.persistence.save(structuredClone(e)),O===t&&(t.overrides=e,$t(t),rd(t))}async function id(t){if(O!==t)return;let e=He(t);e.length!==t.overrides.length?(Ke.info(`Quota override expired: ${t.overrides.length-e.length}`),await Bt(t,e).catch(n=>{Ke.warn(`Override expiry not saved: ${String(n)}`),$t(t)})):$t(t)}async function Vk(t){sd();let e={persistence:t.persistence,onChange:t.onChange,now:t.now??Date.now,overrides:[],timer:null};O=e,await qe.run(async()=>{let n=await e.persistence.load();if(O!==e)return;e.overrides=n;let r=He(e);r.length!==n.length?await Bt(e,r):$t(e)})}async function Jk(t,e,n){let r=O;if(!r||n*1e3<=r.now())return null;let i={provider:t,route:e,until:Math.floor(n),createdAt:r.now()};return await qe.run(()=>Bt(r,[...He(r).filter(s=>!Ut(s,t,e)),i])),Ke.info(`Quota override granted: ${t}::${e} until ${i.until}`),i}async function Xk(t,e){let n=O;return!n||!n.overrides.some(r=>Ut(r,t,e))?!1:(await qe.run(()=>Bt(n,n.overrides.filter(r=>!Ut(r,t,e)))),Ke.info(`Quota override revoked: ${t}::${e}`),!0)}function xe(t,e){let n=O;return!n||!e?null:He(n).find(r=>Ut(r,t,e))??null}function Yk(){return O?structuredClone(He(O)):[]}async function Zk(){await qe.run(()=>{})}function sd(){O?.timer&&clearTimeout(O.timer),O=null}var od={five_hour:.9,seven_day:.95,seven_day_overage_included:.95};function Xn(t,e){return e??od[t]??.9}function ce(t,e,n){return n.type===t&&(t!=="model_scoped"||n.label===e)}function V(t,e,n,r){let i=g().providerRateLimits[t],s=a=>ce(n,r,a),o=i?.accounts?.[Oi(t,e)]?.windows.find(s),u=o??i?.windows?.find(s);return u?{enabled:u.enabled,threshold:u.threshold??null,stopThreshold:u.stopThreshold??null,source:o?"account":"provider"}:typeof i?.enabled=="boolean"?{enabled:i.enabled,threshold:i.threshold??null,stopThreshold:null,source:"provider"}:{enabled:!0,threshold:null,stopThreshold:null,source:"default"}}function co(t){return t.enabled?t.stopThreshold:null}function Qe(t,e){if(!e.enabled)return null;let n=Xn(t,e.threshold);return e.stopThreshold===null?n:Math.min(n,e.stopThreshold)}function po(t){return t.type==="seven_day"||t.type==="seven_day_overage_included"||t.type==="model_scoped"}function Yn(t,e){if(t.type!=="model_scoped"||!t.label)return!0;let n=r=>r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"");return`-${n(e)}-`.includes(`-${n(t.label)}-`)}var Ve=new Set(["five_hour","seven_day","seven_day_overage_included","model_scoped","codex_primary","codex_secondary"]);function w(t){return typeof t!="number"||!Number.isFinite(t)||t<=0?null:t<1e12?t*1e3:t}function F(t){return t==="anthropic"?Te:t}function Ge(t){return JSON.stringify([t.provider,t.route,t.type,t.type==="model_scoped"?t.label??null:null])}function fo(t,e){let n=w(t.observedAt);return t.billing==="api"||!n?[]:t.windows.filter(ud).map(r=>({...r,utilization:r.utilization,provider:t.provider,route:t.route||F(t.provider),observedAt:n,source:e}))}function ud(t){return Ve.has(t.type)&&typeof t.utilization=="number"&&Number.isFinite(t.utilization)&&t.utilization>=0}function ad(t,e,n){if(!t)return!0;if(e.observedAt<t.observedAt)return!1;let r=w(t.resetsAt);return r!==null&&r<=n?!0:e.resetsAt===t.resetsAt&&e.utilization>=t.utilization}function mo(t,e,n,r){let i=new Map(e.map(s=>[Ge(s),s]));return t.flatMap(s=>s.freshness==="live"?fo(s,"live"):!n||s.freshness!=="stale"?[]:fo(s,"legacy-stale").filter(o=>ad(i.get(Ge(o)),o,r)))}function ld(t,e){return e.observedAt>t.observedAt?e:e.observedAt<t.observedAt?t:e.utilization>t.utilization?{...t,utilization:e.utilization}:t}function Je(t,e){let n=new Map(t.map(r=>[Ge(r),r]));for(let r of e){let i=n.get(Ge(r));n.set(Ge(r),i?ld(i,r):r)}return structuredClone([...n.values()])}function ho(t,e){return[...t,...e]}var cd=p("quota-evidence");function dd(t,e,n,r){if(!n)return"policy-disabled";let i=w(t.resetsAt);return i!==null&&i<=r?"reset-elapsed":t.utilization>=e?"above-threshold":"below-threshold"}function pd(t,e,n,r){return t==="pending"?"awaiting-durable-evidence":e&&e.policy!==n?"soft-policy-change":{"policy-disabled":"soft-policy-disabled","reset-elapsed":"known-reset","above-threshold":"last-known-exceeds-threshold","below-threshold":"last-known-below-threshold"}[r]}function fd(t,e,n,r){let i=V(t.provider,t.route,t.type,t.label),s=Xn(t.type,i.threshold),o=e.find(u=>u.provider===t.provider&&(u.route||F(u.provider))===t.route);return{phase:r,provider:t.provider,route:t.route,type:t.type,label:t.label,source:t.source,freshness:o?.freshness??"missing",observedAt:t.observedAt,utilization:t.utilization,resetsAt:t.resetsAt,threshold:s,enabled:i.enabled,status:dd(t,s,i.enabled,n),reason:""}}var Ft=class{emit;seen=new Map;constructor(e=n=>cd.info("Window evidence",n)){this.emit=e}record(e,n,r,i="durable"){for(let s of e)this.recordOne(fd(s,n,r,i))}recordOne(e){let n=JSON.stringify([e.phase,e.provider,e.route,e.type,e.type==="model_scoped"?e.label:null]),{observedAt:r,reason:i,...s}=e,o=JSON.stringify(s),u=this.seen.get(n);if(u?.fingerprint===o)return;let a=JSON.stringify([e.enabled,e.threshold]);e.reason=pd(e.phase,u,a,e.status),this.seen.set(n,{fingerprint:o,policy:a}),this.emit(e)}};var So=p("quota-admission"),Xe=new j,I=null;function er(t,e){return JSON.stringify([t,e])}function Zn(t){return w(t.observedAt)??0}function go(t){return er(t.provider,t.route||F(t.provider))}function bo(t,e){if(t.freshness!=="live"||Zn(t)<=e.observedAt)return!1;let r=t.windows.find(i=>ce(e.type,e.label,i))?.utilization;return typeof r=="number"&&Number.isFinite(r)&&r>=0&&r<1}function Ye(t){if(I===t){t.audit.record(t.evidence,[...t.usage.values()],t.now());try{t.onChange?.()}catch(e){So.warn(`Quota change callback failed: ${String(e)}`)}}}function ko(t){So.warn(`Quota state update failed: ${String(t)}`)}function To(t){t.timer&&clearTimeout(t.timer),t.timer=null}function md(t){return[...zt(t).flatMap(n=>n.windows),...t.evidence,...t.pendingEvidence].flatMap(n=>{let r=w(n.resetsAt);return r!==null&&r>t.now()?[r]:[]})}function J(t,e=!1){if(To(t),I!==t)return;let n=md(t);if(!e&&n.length===0)return;let r=e?5e3:Math.min(...n)-t.now();t.timer=setTimeout(()=>{Xe.run(()=>nr(t)).catch(i=>{ko(i),J(t,!0)})},Math.min(Math.max(r,0),2147483647)),t.timer.unref?.()}async function _o(t,e){let n=[...t.observed];try{await t.persistence.save(structuredClone(e))}catch(r){throw J(t,!0),r}if(I===t){t.blocks=e;for(let r of n)t.observed.delete(r);J(t),Ye(t)}}function tr(t,e){return zt(t).map(n=>{let r=t.usage.get(er(n.provider,n.route)),i=n.windows.filter(s=>{let o=w(s.resetsAt);return o!==null&&o<=t.now()?!1:!(e&&r&&bo(r,s))});return{...n,windows:i}}).filter(n=>n.windows.length>0)}function Wt(t){return t.reduce((e,n)=>e+n.windows.length,0)}async function nr(t,e=!1){if(I!==t)return;let n=tr(t,e);t.observed.size||Wt(n)!==Wt(t.blocks)?await _o(t,n):(J(t),e||Ye(t)),await wo(t)}function hd(t){return{persistence:t.persistence??{load:()=>G.getHardQuotaBlocks(),save:e=>G.setHardQuotaBlocks(e),loadEvidence:()=>G.getQuotaWindowEvidence(),saveEvidence:e=>G.setQuotaWindowEvidence(e)},now:t.now??Date.now,onChange:t.onChange,audit:new Ft,blocks:[],observed:new Set,usage:new Map,evidence:[],pendingEvidence:new Set,timer:null}}async function yT(t={}){_d();let e=hd(t);I=e,await Xe.run(async()=>{let n=await e.persistence.load(),r=await e.persistence.loadEvidence?.()??[],i=await(t.loadUsage??(()=>G.getProviderUsage()))();if(I!==e)return;e.blocks=structuredClone(n),e.evidence=structuredClone(r),xo(e,i),vo(e,i,!0);let s=tr(e,!0);Wt(s)!==Wt(n)&&await _o(e,s),await wo(e),I===e&&(e.audit.record(e.evidence,i,e.now()),J(e))})}function vo(t,e,n=!1){let r=Je(t.evidence,[...t.pendingEvidence]);for(let i of mo(e,r,n,t.now())){let s=Je(r,[i]);JSON.stringify(s)!==JSON.stringify(r)&&(t.pendingEvidence.add(i),t.audit.record([i],[...t.usage.values()],t.now(),"pending"),r=s)}}async function wo(t){let e=[...t.pendingEvidence];if(!e.length)return;let n=Je(t.evidence,e);try{await t.persistence.saveEvidence?.(structuredClone(n))}catch(r){throw J(t,!0),r}if(I===t){t.evidence=n;for(let r of e)t.pendingEvidence.delete(r);J(t),Ye(t)}}function xo(t,e){for(let n of e){if(n.billing==="api")continue;let r=t.usage.get(go(n));r&&Zn(n)<Zn(r)||t.usage.set(go(n),structuredClone(n))}}function Eo(t){let e=I;e&&(xo(e,t),vo(e,t),J(e),Ye(e),Xe.run(()=>nr(e,!0)).catch(ko))}function gd(t,e,n){let r=typeof e=="string"?{provider:e}:e,i=w(t.observedAt??r.observedAt)??n,s=w(t.resetsAt);return{provider:r.provider.trim(),route:r.mode||F(r.provider),windows:[{type:t.rateLimitType,...t.rateLimitLabel?{label:t.rateLimitLabel}:{},resetsAt:s===null?null:s/1e3,observedAt:i}]}}function Io(t,e){let n=t.windows.findIndex(r=>ce(e.type,e.label,r));return n<0?(t.windows.push(e),!0):t.windows[n].observedAt>e.observedAt?!1:(t.windows[n]=e,!0)}function zt(t){let e=structuredClone(t.blocks);for(let n of t.observed){let r=e.find(i=>i.provider===n.provider&&i.route===n.route);r?Io(r,structuredClone(n.windows[0])):e.push(structuredClone(n))}return e}function yd(t,e){let n=e.windows[0],r=w(n.resetsAt);if(r!==null&&r<=t.now())return!0;let i=t.usage.get(er(e.provider,e.route));return!!i&&bo(i,n)}function Sd(t,e){if(yd(t,e))return null;let n=e.windows[0],r=zt(t),i=r.find(s=>s.provider===e.provider&&s.route===e.route);return i?Io(i,n)?r:null:[...r,e]}async function Ao(t,e){let n=I;if(!n||!e||t?.status!=="rejected"||!Ve.has(t.rateLimitType??""))return;let r=gd(t,e,n.now());!r.provider||!Sd(n,r)||(n.observed.add(r),J(n),Ye(n),await Xe.run(()=>nr(n,!0)))}function bd(t,e,n){if(!Yn(e,n))return!1;let r=w(e.resetsAt);if(r!==null&&r<=t.now())return!1;let i=Qe(e.type,V(e.provider,e.route,e.type,e.label));return i!==null&&e.utilization>=i}function Kt(t,e){let n=I,r=t.backend==="claude"?"anthropic":t.provider;return!n||!r?null:(n.audit.record(n.evidence,[...n.usage.values()],n.now()),kd(n,t,r,e))}function kd(t,e,n,r){let i=_(e),s=Td(t,n,i,e.model);return s||(r==="cache-refresh"?yo(t,n,i,e.model,!0):r==="automatic"?yo(t,n,i,e.model):null)}function Td(t,e,n,r){let s=zt(t).find(o=>o.provider===e&&o.route===n)?.windows.filter(o=>Yn(o,r))??[];return s.length?Co("hard",e,n,s):null}function yo(t,e,n,r,i=!1){if(xe(e,n))return null;let s=ho(t.evidence,t.pendingEvidence).filter(u=>u.provider===e&&u.route===n&&(!i||po(u))&&bd(t,u,r)),o=[...new Map(s.map(u=>[JSON.stringify([u.type,u.type==="model_scoped"?u.label:null]),u])).values()];return o.length?Co("soft",e,n,o):null}function Co(t,e,n,r){return{kind:t,provider:e,route:n,windows:r.map(({type:i,label:s,resetsAt:o})=>({type:i,...s?{label:s}:{},resetsAt:o}))}}function Ro(){let t=I;return t?{evidence:Je(t.evidence,[...t.pendingEvidence]),hardBlocks:tr(t,!1)}:{evidence:[],hardBlocks:[]}}async function ST(){await Xe.run(()=>{})}function _d(){I&&To(I),I=null}function W(t,e){return e?`${t}::${e}`:t}function Ee(t){let e=t.indexOf("::");return e<0?{provider:t,route:null}:{provider:t.slice(0,e),route:t.slice(e+2)}}function kT(t,e){if(e.has(t))return!0;let{provider:n,route:r}=Ee(t);return r?e.has(n):[...e].some(i=>Ee(i).provider===n)}var z=p("rate-limit-throttle"),vd="rate-limit:clear",wd=5e3,xd=5e3,Ie="outage",rr=null,et=null,Oo=null,Mo=null,Lo=null,Ze=null,or=0,A=new Map,qt=new j;function Ed(t){return{...t,modes:[...t.modes].sort(),windows:t.windows.map(e=>({...e})).sort((e,n)=>e.resetsAt-n.resetsAt)}}function de(t){return W(t.provider,t.route)}function Ht(t){return!t.route||t.route===Te||t.route===t.provider?t.displayName:`${t.displayName} (${t.route})`}function Qt(t=A){return[...t.values()].map(Ed).sort((e,n)=>de(e).localeCompare(de(n)))}function Gt(){return new Map(Qt().map(t=>[de(t),t]))}function Vt(t){A.clear();for(let e of t.values())A.set(de(e),e)}function ir(t=A){return Qt(t).flatMap(e=>e.windows)}function Id(t){return[...new Set(t)].sort()}function Ad(t=A){let e=Qt(t);return e.length>0?{providers:e}:null}async function tt(t=A){await et?.save(Ad(t))}function Jt(){try{Mo?.()}catch(t){z.error(`onChange hook failed: ${t.message}`)}}function Xt(t){try{Oo?.(t)}catch(e){z.error(`onResume hook failed: ${e.message}`)}}function Yt(t,e=S("notice.rateLimit.title"),n){rr&&wt(rr,{text:t,level:"warning",title:e,...n&&n.length>0?{actions:n}:{}})}function Cd(t){return[{type:"button",text:S("notice.rateLimit.resumeNow"),actionId:vd,value:t,style:"primary"}]}function Rd(t){return new Date(t*1e3).toLocaleString(Li()==="zh"?"zh-CN":"en-GB",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1})}function Pd(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 Po(t){let e=t?.trim();return e||null}function Od(t){if(typeof t=="string"){let n=Po(t)??"unknown";return{provider:n,displayName:n,mode:n}}let e=Po(t?.provider);return e?{provider:e,displayName:t?.displayName?.trim()||e,...t?.mode?{mode:t.mode}:{}}:{provider:"unknown",displayName:"Unknown provider"}}function Md(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,...typeof t.route=="string"&&t.route?{route:t.route}:{},displayName:t.displayName||t.provider,modes:Array.isArray(t.modes)?Id(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 Ld(t){if(t?.route||!Array.isArray(t?.modes)||t.modes.length===0||!Array.isArray(t.windows))return[t];let e=t.windows.filter(i=>i?.type===Ie),n=t.windows.filter(i=>i?.type!==Ie),r=n.length===0?[]:t.modes.filter(Boolean).map(i=>({...t,route:i,modes:[i],windows:n.map(s=>({...s}))}));return e.length>0?[{...t,modes:[],windows:e},...r]:r}function Dd(t){return Array.isArray(t.providers)?t.providers.flatMap(Ld).map(Md).filter(e=>e!==null):[]}function Do(t){let e=t.type===Ie?0:wd;return t.resetsAt*1e3+e}function sr(t,e=Date.now()){return Do(t)>e}function Nd(t){for(let e of Dd(t)){let n=e.windows.filter(r=>sr(r));n.length>0&&A.set(de(e),{...e,windows:n})}}function jd(){let t=ir().map(Do);return t.length>0?Math.min(...t):null}function Ud(){Ze&&clearTimeout(Ze),Ze=null,or++}function pe(t=0){Ud();let e=jd();if(e===null)return;let n=or,r=Math.max(t,e-Date.now(),0);z.info(`Next provider reset check in ${(r/1e3/60).toFixed(1)} min`),Ze=setTimeout(()=>{zd(e,n)},r)}function $d(t,e){let n=[];for(let[r,i]of t){let s=i.windows.filter(o=>!sr(o,e)).map(o=>o.type);i.windows=i.windows.filter(o=>sr(o,e)),!(i.windows.length>0)&&(t.delete(r),n.push({provider:r,displayName:Ht(i),expiredTypes:s}))}return n}function Bd(t){return t.expiredTypes.includes(Ie)?{text:`${be.ok} ${S("notice.rateLimit.outageCleared",{provider:t.displayName})}`,title:S("notice.rateLimit.outageTitle")}:{text:`${be.ok} ${S("notice.rateLimit.cleared",{provider:t.displayName})}`}}async function Fd(t){try{return await tt(t),!0}catch(e){return z.error(`Failed to persist throttle expiry: ${e.message}`),pe(xd),!1}}async function Wd(t){let e=Gt(),n=ir(e).length,r=Math.max(Date.now(),t),i=$d(e,r);if(ir(e).length===n){pe();return}if(await Fd(e)){Vt(e);for(let s of i){let o=Bd(s);Yt(o.text,o.title)}Jt(),i.length>0&&Xt(i.map(s=>s.provider)),pe()}}async function zd(t,e){await qt.run(async()=>{e===or&&(Ze=null,await Wd(t))})}async function OT(t,e,n,r){rr=t,et=e,Oo=n??null,Mo=r??null;let i=await e.load();if(!i){z.info("Initialized");return}Nd(i),A.size===0?(await e.save(null),Xt([])):(await tt(),pe()),z.info(`Initialized \u2014 ${A.size} provider throttle(s) restored`)}function Kd(t,e){let n=t.windows.find(s=>ce(e.rateLimitType,e.rateLimitLabel,s));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),i=r!==n.resetsAt||e.utilization!==n.utilization;return n.resetsAt=r,n.utilization=e.utilization,i}function qd(t,e){if(typeof t.utilization!="number"||!t.rateLimitType||t.status!=="rejected"&&xe(e.provider,e.mode))return!1;let n=Qe(t.rateLimitType,V(e.provider,e.mode,t.rateLimitType,t.rateLimitLabel));return n!==null&&t.utilization>=n}async function Hd(t,e,n){try{return await Lo?.(t,e,n)??[]}catch(r){return z.warn(`Rate-limit notice actions failed: ${r.message}`),[]}}async function Qd(t,e,n,r){if(z.info(`Throttle updated: provider=${e.provider}, type=${t.rateLimitType}, utilization=${t.utilization}, mode=${e.mode??"(none)"}`),!r)return;let i=[...Cd(de(n)),...await Hd(e.provider,n.route,t.rateLimitType)];Yt(`${be.warning} ${S("notice.rateLimit.activated",{provider:Ht(n),type:t.rateLimitType,pct:(t.utilization*100).toFixed(0),at:Rd(t.resetsAt),remaining:Pd(t.resetsAt)})}`,S("notice.rateLimit.title"),i)}function Gd(t){return t.status==="rejected"&&typeof t.utilization!="number"?{...t,utilization:1}:t}async function Vd(t,e){if(!t||!et||!t.rateLimitType||!t.resetsAt)return;let n=Gd(t),r=Od(e);if(!qd(n,r))return;let i=Gt(),s=W(r.provider,r.mode),o=i.get(s),u=!o;o||(o={provider:r.provider,...r.mode?{route:r.mode}:{},displayName:r.displayName,modes:[],windows:[]},i.set(s,o));let a=!!r.mode&&!o.modes.includes(r.mode);a&&o.modes.push(r.mode);let l=Kd(o,{rateLimitType:n.rateLimitType,rateLimitLabel:n.rateLimitLabel,utilization:n.utilization,resetsAt:n.resetsAt});!u&&!a&&!l||(await tt(i),Vt(i),pe(),Jt(),await Qd(n,r,o,u))}async function nt(t,e){await Ao(t,e),await qt.run(()=>Vd(t,e))}function Jd(t,e){return e?t.has(e)?[e]:Ee(e).route?[]:[...t.entries()].filter(([,n])=>n.provider===e).map(([n])=>n):[...t.keys()]}function Xd(t){return{provider:t.provider,...t.route?{route:t.route}:{},displayName:Ht(t),types:t.windows.map(e=>e.type),resetsAt:t.windows.reduce((e,n)=>Math.max(e,n.resetsAt),0)}}async function Yd(t){if(!et)return{cleared:[]};let e=Gt(),n=Jd(e,t);if(n.length===0)return{cleared:[]};let r=n.map(i=>Xd(e.get(i)));for(let i of n)e.delete(i);await tt(e),Vt(e),pe(),Jt(),Xt(n);for(let i of r){let s=i.types.join(", ");z.info(`Throttle manually cleared: provider=${i.provider}, route=${i.route??"(all)"}, types=${s}`),Yt(`${be.ok} ${S("notice.rateLimit.clearedManually",{provider:i.displayName})}`)}return{cleared:r}}async function MT(t){return qt.run(()=>Yd(t))}function Zd(t,e,n){if(e.type===Ie)return!1;let r=n.find(s=>ce(e.type,e.label,s));if(!r)return!1;let i=Qe(e.type,V(t.provider,t.route,e.type,e.label));return i===null||r.utilization<i}async function ep(t,e){await tt(t),Vt(t),pe(),Jt(),e&&(z.info(`Throttle released by a fresh quota reading: provider=${e.provider}, route=${e.route??"(none)"}`),Yt(`${be.ok} ${S("notice.rateLimit.cleared",{provider:Ht(e)})}`),Xt([de(e)]))}function tp(t,e,n){return n?t.has(W(e,n))?[W(e,n)]:[]:[...t.entries()].filter(([,r])=>r.provider===e).map(([r])=>r)}async function np(t,e,n){if(!et)return!1;let r=Gt(),i=!1;for(let s of tp(r,t,n)){let o=r.get(s),u=o.windows.filter(a=>!Zd(o,a,e));u.length!==o.windows.length&&(u.length>0?o.windows=u:r.delete(s),await ep(r,u.length===0?o:null),i=!0)}return i}async function LT(t,e,n){return qt.run(()=>np(t,e,n))}function DT(t){Lo=t}function rp(t){return[...A.values()].filter(e=>e.provider===t)}function Ae(t,e){return t?e?A.has(W(t,e))||A.has(t):rp(t).length>0:A.size>0}function No(t,e){return A.has(W(t,e))?!0:!!A.get(t)?.windows.some(n=>n.type===Ie)}function NT(){return{providers:Qt()}}function ip(t,e){return{channel:e.channel,registryKey:t,executionId:e.executionId,kind:e.kind??null,kill:e.kill,startTime:Date.now(),backend:e.backend,account:e.account??null,run:e.run,trackSessionId:e.trackSessionId??null,backendSessionId:e.backendSessionId??null,numTurns:e.numTurns??null,subagent:e.subagent??!1,...e.quotaPurpose?{quotaPurpose:e.quotaPurpose}:{},...e.ownerSessionId?{ownerSessionId:e.ownerSessionId}:{}}}var ur=class{byKey=new Map;byChannel=new Map;_bus=null;listeners=new Set;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 i=ip(n,e);if(this.byKey.set(n,i),i.channel){let s=this.byChannel.get(i.channel);s||(s=new Set,this.byChannel.set(i.channel,s)),s.add(i)}return this._bus&&i.executionId&&this._bus.publish({type:"agent.started",channel:i.channel??n,executionId:i.executionId,backend:i.backend}),this.notify(),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 i of r)i.kill(),this._delete(i),this._bus&&i.executionId&&this._bus.publish({type:"agent.superseded",executionId:i.executionId,reason:n});return r.length}promoteHuman(e){let n=!1;for(let r of this.byKey.values())r.subagent||r.trackSessionId!==e||r.quotaPurpose==="human"||(r.quotaPurpose="human",n=!0);n&&this.notify()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(){for(let e of[...this.listeners])try{e()}catch{}}_delete(e){this.byKey.delete(e.registryKey),this._removeFromIndices(e),this.notify()}_removeFromIndices(e){if(e.channel){let n=this.byChannel.get(e.channel);n&&(n.delete(e),n.size===0&&this.byChannel.delete(e.channel))}}},D=new ur;import{rm as Uo}from"node:fs/promises";var sp="anthropic",op={anthropic:"five_hour","openai-codex":"codex_primary"},up={anthropic:"Anthropic","openai-codex":"OpenAI Codex"},ap={five_hour:"five-hour",codex_primary:"primary"},lp=6e4;function ar(t){return op[t]??null}var Zt=p("quota-stop"),cp=new j,C=null,dp={activateThrottle:(t,e)=>nt({status:"allowed_warning",rateLimitType:e.window,utilization:e.utilization,resetsAt:e.resetsAt},{provider:e.provider,displayName:up[e.provider]??e.provider,mode:t}),throttleActive:(t,e)=>Ae(t,e)};async function JT(t=dp){kp();let e={deps:t,file:t.file??Ri,now:t.now??Date.now,readings:new Map,stops:{},written:null,timer:null,unsubscribe:()=>{}};C=e,await Uo(e.file,{force:!0}),e.unsubscribe=D.subscribe(()=>{cr()})}function $o(t){let e=C;if(!e)return Promise.resolve();let n=W(t.provider,t.route),r=e.readings.get(n);return(!r||t.observedAt>=r.observedAt)&&e.readings.set(n,t),cr()}function lr(t,e){let n=C,r=ar(e.provider);if(!n||!r||!e.mode)return;let i=t.unifiedWindows?.[r]??(t.rateLimitType===r?t:void 0),s=Fo(e.provider,e.mode,i,n.now());s&&$o(s)}function Bo(t){for(let e of t){let n=ar(e.provider),r=w(e.observedAt);if(!n||!pp(e)||r===null)continue;let i=e.windows.find(o=>o.type===n),s=Fo(e.provider,e.route||F(e.provider),i,r);s&&$o(s)}}function pp(t){return t.billing!=="api"&&t.freshness==="live"}function Fo(t,e,n,r){let i=w(n?.resetsAt),s=n?.utilization;return i===null||typeof s!="number"||!Number.isFinite(s)?null:{provider:t,route:e,utilization:s,resetsAt:Math.floor(i/1e3),observedAt:r}}function cr(){let t=C;return t?cp.run(()=>fp(t)).catch(e=>Zt.warn(`Quota stop update failed: ${String(e)}`)):Promise.resolve()}async function fp(t){if(C!==t)return;let e={};for(let[n,r,i]of mp(t))await gp(t,n,r.route,i)&&(e[n]=i);C===t&&(t.stops=e,await yp(t),Sp(t))}function mp(t){let e=t.now();return[...t.readings].flatMap(([n,r])=>{let i=hp(r);return i&&i.resetsAt*1e3>e&&!xe(r.provider,r.route)?[[n,r,i]]:[]})}function hp(t){let e=ar(t.provider);if(!e)return null;let n=co(V(t.provider,t.route,e));return n===null||t.utilization<n?null:{provider:t.provider,window:e,utilization:t.utilization,threshold:n,resetsAt:t.resetsAt}}async function gp(t,e,n,r){if(t.stops[e]?.resetsAt===r.resetsAt&&t.deps.throttleActive(r.provider,n))return!0;try{await t.deps.activateThrottle(n,r)}catch(s){return Zt.warn(`Quota stop for ${e} not armed: ${String(s)}`),!1}let i=t.deps.throttleActive(r.provider,n);return i&&Zt.info(`Quota stop: ${e} ${r.window} window at ${r.utilization}, until ${r.resetsAt}`),i}async function yp(t){let e=Object.fromEntries(zo(t).filter(r=>r.provider===sp).map(r=>[r.route,r.entry])),n=Object.keys(e).length===0?null:JSON.stringify({routes:e,exempt:Wo(t)});n!==t.written&&(n===null?await Uo(t.file,{force:!0}):await q(t.file,n),n===null&&Zt.info("Quota stop cleared"),t.written=n)}function Wo(t){let e=t.deps.exemptKeys?.()??bp(D.getAll());return[...new Set(e)].sort()}function Sp(t){t.timer&&clearTimeout(t.timer),t.timer=null;let e=Object.values(t.stops).map(r=>r.resetsAt*1e3);if(e.length===0)return;let n=Math.min(Math.max(Math.min(...e)-t.now(),0),2147483647);t.timer=setTimeout(()=>{cr()},n),t.timer.unref?.()}function bp(t){let e=new Set(t.filter(i=>!i.subagent&&i.quotaPurpose==="human").map(i=>i.trackSessionId).filter(i=>!!i)),r=t.filter(i=>i.subagent?!!i.ownerSessionId&&e.has(i.ownerSessionId):i.quotaPurpose==="human").flatMap(i=>[i.trackSessionId,i.backendSessionId]);return[...new Set(r.filter(i=>!!i))].sort()}function zo(t){return Object.entries(t.stops).map(([e,n])=>({...Ee(e),entry:n})).filter(e=>!!e.route)}function XT(){let t=C;return t?zo(t).filter(e=>e.entry.resetsAt*1e3>t.now()):[]}function Ko(t,e){let n=C,r=n&&e?n.stops[W(t,e)]:void 0;return n&&r&&r.resetsAt*1e3>n.now()?r:null}function qo(t,e){let n=Ko(t,e);return n?Qo(e,n):null}function Ho(t,e,n){let r=C,i=Ko(t,e);if(!r||!i||i.resetsAt*1e3-lp<=r.now())return null;let s=new Set(Wo(r));return n.some(o=>!!o&&s.has(o))?null:Qo(e,i)}function Qo(t,e){return`Quota stop: the ${t} ${ap[e.window]??e.window} window is at ${jo(e.utilization)} (stop threshold ${jo(e.threshold)}); this turn resumes after the window resets.`}function jo(t){return`${Math.round(t*100)}%`}function kp(){C&&(C.timer&&clearTimeout(C.timer),C.unsubscribe(),C=null)}var Xo={};Wc(Xo,{cancelExecution:()=>Jo,completeExecution:()=>Go,failExecution:()=>Vo,getAll:()=>_p,getExecution:()=>Tp,getRunningExecutions:()=>vp,markMissingRunningExecutionsStale:()=>Ip,startLocalExecution:()=>dr,stopLiveExecution:()=>Ep,teardownExecution:()=>en,touchExecution:()=>wp});function Tp(t){return U.getExecution(t)}function _p(){return U.getAll()}function vp(){return U.getRunningExecutions()}function dr(t){return U.startLocalExecution(t)}function wp(t,e){return U.touchExecution(t,e)}function Go(t,e){return U.completeExecution(t,e)}function Vo(t,e){return U.failExecution(t,e)}function Jo(t,e){return U.cancelExecution(t,e)}function xp(t){let e=t?.rateLimitMessage;return e?`Rate limited: ${e}`:"Rate limited"}function en({executionId:t,status:e,result:n,spend:r,error:i,durationS:s}){if(!t)return null;let o=r?r.costUsd:n?.total_cost_usd,u={costUsd:o,numTurns:r?r.numTurns:n?.num_turns,durationS:s,finalOutput:n?.finalOutput||null},a;if(e==="completed")a=Go(t,u),D.complete(t,o??0);else if(e==="cancelled")a=Jo(t,u),D.supersede(t,"cancelled");else{let l=e==="rate-limited"?i?.message||xp(n):i?.message||null;a=Vo(t,{...u,error:l}),D.fail(t,l??"error")}return a}function Ep(t){if(t.run?.cancel){t.run.cancel("user");return}t.executionId?en({executionId:t.executionId,status:"cancelled",durationS:0}):D.killById(t.registryKey)}async function Ip(t){return await U.markMissingRunningExecutionsStale(t)}var pr=new Map,Yo=new Map;function t_(t,e,n){let r=Ap(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`);pr.set(t,e),n!==void 0&&Yo.set(t,n)}function n_(t){return pr.get(t)??null}function Zo(t){return Yo.get(t)}function Ap(t,e){for(let[n,r]of pr)if(r.trial_id===t&&r.root_run_id===e)return n;return null}function s_(){return g().bgContinuation}var Cp=9e4,Rp=18e5;function eu(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 tu(){return eu("CORTEX_BG_GRACE_S",Cp)}function nu(){return eu("CORTEX_BG_WAIT_MAX_S",Rp)}function rt(t){return t?(t.pendingBackgroundTasks??0)+(t.undeliveredBackgroundTasks??0):0}var Pp={set(t,e){let n=setTimeout(t,e);return n.unref?.(),n},clear(t){clearTimeout(t)}};function fr(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 Op(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 Ce=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??Pp,this.graceMs=n.graceMs??tu(),this.maxWaitMs=n.maxWaitMs??nu()}sink(){return{...Mp(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 rt(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&&rt(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=Op(e);if(n&&this.port.push(n),this.port.push({type:"background_result",result:e}),this.acc=fr(this.acc,e),this.backgroundTurnOpen=!1,this.acc.rateLimited){this.finish();return}let r=e.pendingBackgroundTasks??0,i=e.undeliveredBackgroundTasks??0;r+i>0||this.outstandingInjections>0?this.arm(Math.max(r,this.outstandingInjections),i):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 Mp(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,i)=>{t({type:"tool_use",toolUseId:r??"",name:e,input:n,phase:"background",...i!==void 0?{subagent:i}:{}})},onToolResult:(e,n,r,i,s)=>{t({type:"tool_result",toolUseId:e,ok:!r,content:n,phase:"background",...i!==void 0?{subagent:i}:{},...s?.length?{images:s}:{}})},onContextUsage:e=>t({type:"context_usage",...e,phase:"background"}),onSubagentEnd:(e,n)=>{t({type:"subagent_end",parentToolUseId:e,status:n,phase:"background"})}}}var Lp=/rate[ _]limit|usage[ _]limit|hit your (?:[\w-]+ )?limit|overloaded|529|too many requests|quota/i;function Re(t){return!!t&&Lp.test(t)}var Dp=/(?:invalid[_ ]request|forbidden|not found|request body too large|context(?: window|_length).*exceed|insufficient[_ ](?:balance|quota)|billing|quota exhausted)/i,Np=/(?:^(?: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,jp=/(?: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,Up=/\byou can retry your request\b/i,$p=/\b(?:ENOSPC|EMFILE|ENFILE|EAGAIN)\b/i;function it(t){let e=t?.message;return!e||_e(e)||Dp.test(e)?!1:Re(e)||Np.test(e)||jp.test(e)||Up.test(e)||$p.test(e)}var mr=Object.freeze({costUsd:null,numTurns:null});function Bp(t,e){return t===null?e:e===null?t:t+e}function tn(t){return typeof t=="number"&&Number.isFinite(t)?t:null}function ru(t){return{costUsd:tn(t.total_cost_usd),numTurns:tn(t.num_turns)}}function iu(t,e){if(e.type==="cost_record")t.costUsd=Bp(t.costUsd,tn(e.cost_usd));else if(e.type==="turn_progress"){let n=tn(e.numTurns);n!==null&&(t.numTurns=Math.max(t.numTurns??0,n))}}var Fp=/\bClaude Code v?(\d+\.\d+\.\d+)\b.*?\bversion v?(\d+\.\d+\.\d+)\S* or newer is required/i,Wp=/\brun\s+['"`]?claude update\b/i;function ou(t){let e=Fp.exec(t);return e?{installed:e[1],required:e[2]}:Wp.test(t)?{}:null}function hr(t){let e=ou(t);if(e)return e.required?{kind:"update-claude-code",required:e.required}:{kind:"update-claude-code"}}var su=new Set;function uu(t,e){if(e?.startsWith("web:"))return;let n=ou(t),r=ji.adapter;if(!n||!r)return;let i=n.required??"";if(su.has(i))return;su.add(i);let s=n.required?S("notify.claudeUpdateRequired.body",{installed:n.installed??"?",required:n.required}):S("notify.claudeUpdateRequired.bodyGeneric");wt(r,{title:S("notify.claudeUpdateRequired.title"),text:s,level:"warning"})}var zp={claude:"anthropic"};function fe(t){return t.provider||zp[t.backend]||t.backend}function st(t){let e=_({...t,provider:t.provider??null});return No(fe(t),e)}function gr(t,e){return{sessionId:null,total_cost_usd:null,num_turns:null,inputNotDispatched:!0,rateLimited:!0,rateLimitMessage:`Connection ${t} is rate-limited`,rateLimitProvider:e,rateLimitRoute:t,planFilePath:null,enteredPlanMode:!1,exitedPlanMode:!1,finalOutput:null}}var Kp=new Set(["scheduled","monitor","external-signal","team-lead","worker-result","worker-question","agent-result","resume","deferred"]);function ot(t){return t.quotaPurpose?t.quotaPurpose:t.isUserInitiated===!1||t.executionKind==="scheduled"||Kp.has(t.trigger??"")?"automatic":"human"}function au(t,e){let n=ot(e);return Kt(t,n)?!0:!(n==="human"&&(e.isUserInitiated||e.quotaPurpose==="human"))&&st(t)}function yr(t){return fe(t)}function lu(t){return t.backend!=="claude"?null:_(t)===Te||nn(t)?"oauth":"api_key"}function nn(t){let e=_(t);return vs({backend:t.backend,id:e})?e:null}function Sr(t){return t.model?fe(t):null}function qp(t){let e=Rt.peek();if(t.backend==="claude")return Is(e,t.model).filter(i=>re.findClaude(i)?.kind!=="key");let n=t.provider??"";return(Pt(e,{backend:"pi",provider:n})?.connections??[n]).map(i=>i===n?null:i)}function kr(t){return{enabled:t.enabled??(()=>g().accountFailover),logins:t.logins??qp,billingOf:t.billingOf??(e=>re.billingOf(e)),isRateLimited:t.isRateLimited??st,quotaPurpose:t.quotaPurpose??"human",quotaPaused:t.quotaPaused??((e,n)=>Kt(e,n)!==null)}}function Hp(t,e){return{...t,connection:e}}function Tr(t,e){return e.quotaPaused(t,e.quotaPurpose)||e.isRateLimited(t)}function _r(t,e={}){let n=kr(e);if(!n.enabled())return null;let r=n.logins(t).map(a=>Hp(t,a)),i=_(t);if(!r.some(a=>_(a)===i))return null;let s=n.billingOf(t),o=a=>_(a)!==i&&n.billingOf(a)===s&&!Tr(a,n),u=r.find(o);return u?{selection:u,from:i,to:_(u)}:null}function cu(t,e={}){let n=kr(e);return!n.enabled()||!Tr(t,n)?null:_r(t,n)}function du(t,e,n={}){return e.route!==_(t)||e.provider!==fe(t)?null:_r(t,n)}function P_(t,e={}){let n=kr(e);return n.enabled()?!Tr(t,n)||_r(t,n)!==null:!1}function vr(t){if(t.backend==="pi"&&!t.connection)return t.provider??"pi";let e=_(t);return re.list().find(r=>r.backend===t.backend&&r.id===e)?.label??e}var br=new Map;function pu(t,e){if(!e)return br.delete(t),!1;let n=`${e.from}\0${e.to}`;return br.get(t)===n?!1:(br.set(t,n),!0)}function fu(t){return t.startsWith("API Error:")?"error":void 0}function Qp(t){return t.startsWith("API Error:")?t:S("status.errorBody",{message:t})}var rn=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,i,s){if(r==="error"&&this.synthesize&&Re(e)){this.heldError={text:e,...n?{blockId:n}:{}};return}r==="error"&&(this.attemptHasErrorNotice=!0),this.emit?.(e,n,r,i??this.errorAction(e,r),s)}errorAction(e,n){return n==="error"&&this.synthesize?hr(e):void 0}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=Qp(e)){this.flushHeldError(),!(!this.synthesize||!this.emit||this.attemptHasErrorNotice)&&(this.attemptHasErrorNotice=!0,this.emit(n,void 0,"error",hr(e)))}emitAutoResume(e,n){if(!this.ctx.isUserInitiated||!Ae(e,n))return!1;if(this.heldError=null,this.synthesize&&this.emit&&!this.attemptHasErrorNotice){this.attemptHasErrorNotice=!0;let r=this.ctx.failoverResume?.(e,n)?S("notify.rateLimitFailover"):S("notify.rateLimitAutoResume");this.emit(r,void 0,"warning",{kind:"cancel-resume"})}return!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"&&Re(r)&&this.emitAutoResume(n?.rateLimitProvider,n?.rateLimitRoute)||this.emitTerminal(r)}emitTerminalRateLimit(e){if(e.inputNotDispatched||this.emitAutoResume(e.rateLimitProvider,e.rateLimitRoute))return;let n=e.rateLimitMessage;typeof n=="string"&&n.startsWith("API Error:")?this.emitTerminal(n):this.emitTerminal(S("status.rateLimitedExhausted"),S("status.rateLimitedExhausted"))}};import{createHash as Gp}from"crypto";function Vp(){return g().streamDeltas}var Jp={direct:[Ji],none:[Xi]};function Xp(t,e){let n=t.mcpConfigPaths?[...t.mcpConfigPaths]:[...Jp[e]];t.supplementalMcpConfigPath&&e==="direct"&&n.push(t.supplementalMcpConfigPath);let r=sn(t),i=t.mcpToolAllowlist??void 0;return ls(n,i,void 0,r)}function Yp(t){let e=["-p","--input-format","stream-json","--output-format","stream-json","--verbose","--replay-user-messages"];return(t.streamDeltas??Vp())&&e.push("--include-partial-messages"),g().showThinking&&e.push("--thinking-display","summarized"),e}function sn(t){if((t.mcpComposition??"direct")==="none")return[];let n=["cortex-core","cortex-ext"];return t.isUserInitiated&&!t.teamWorker&&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 Zp(t){if((t.mcpComposition??"direct")==="none")return[];let e=t.mcpToolAllowlist??void 0;return(e===void 0?sn(t).includes("cortex-core"):Fi.every(r=>e.includes(r)))?is():[]}function ef(t,e){let n=(t.tools||es).split(",").map(i=>i.trim()).filter(i=>i&&!rs.has(i)&&!(e&&ns.has(i))),r=[...e?ts:[],...Zp(t)];return[...new Set([...n,...r])].join(",")}function tf(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 nf(t,e){for(let[n,r]of e)r&&t.push(n,r)}function rf(t,e){nf(t,[["--system-prompt",e.systemPrompt],["--append-system-prompt",e.appendSystemPrompt],["--model",e.model],["--effort",e.thinking],["--agent",e.claudeAgent]])}function sf(t,e,n){for(let r of n??[])t.push(e,r)}function of(t,e){e.disableSkills&&t.push("--disable-slash-commands"),e.settingSources&&t.push("--setting-sources",e.settingSources.join(","))}function uf(t,e){let n=t.disableHooks?{}:Ts(e),r={hooks:t.quotaStop?_s(n):n};return t.outputStyle&&(r.outputStyle=t.outputStyle),t.omitGitContext&&(r.includeGitInstructions=!1),r}function af(t,e){e.needsResume?t.push("--resume",e.sessionId):t.push("--session-id",e.sessionId)}function yu(t){let e=t.mcpComposition??"direct",r=e==="direct"&&!!t.isUserInitiated,i=Xp(t,e),s=Yp(t),o=ef(t,r);return tf(s,i,e,o),rf(s,t),sf(s,"--plugin-dir",t.pluginDirs),of(s,t),s.push("--settings",JSON.stringify(uf(t,o))),af(s,t),s}var lf=["CORTEX_PROFILE","CORTEX_MODE","CORTEX_PROJECT","CORTEX_SESSION_NAME","CORTEX_BACKEND","CORTEX_MODEL","CORTEX_PROVIDER","CORTEX_THINKING","CORTEX_CONNECTION",Kn];function ut(t,e,n){n&&(t[e]=n)}function cf(t){t.MCP_TOOL_TIMEOUT=String(192e4),t.CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT=String(192e4),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 df(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 pf(t,e){let n=e?t.CLAUDE_CODE_OAUTH_TOKEN:void 0;delete t.CLAUDECODE;for(let r of Object.keys(t)){let i=process.platform==="win32"&&r==="CLAUDE_CODE_GIT_BASH_PATH";r.startsWith("CLAUDE_CODE")&&!i&&delete t[r]}n&&(t.CLAUDE_CODE_OAUTH_TOKEN=n),df(t),cf(t)}function ff(t,e,n){n||(t.SLACK_CHANNEL=e,t.FEISHU_CHANNEL=e,t.SLACK_BOT_TOKEN=process.env.SLACK_BOT_TOKEN)}function mf(t,e,n){for(let[r,i]of Object.entries(e??{}))t[r]=i;for(let r of n??[])delete t[r]}var hf=["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN"];function gf(t){return`sha256:${Gp("sha256").update(t).digest("hex").slice(0,8)}`}function hu(t,e,n){return e.unsetEnv?.includes(t)?null:e.routeEnv?.[t]??n}function gu(t,e){return t===null?"deleted":t===void 0?"inherited":e(t)}function on(t){let e=gu(hu("ANTHROPIC_BASE_URL",t,t.anthropicBaseUrl||void 0),i=>`url:${i}`),n=hf.map(i=>`${i}=${gu(hu(i,t),gf)}`),r=[...t.connection?[`connection:${t.connection}`]:[],...t.configDir?[`config:${t.configDir}`]:[]];return[e,...n,...r].join(" ")}function yf(t){return{CORTEX_BACKEND:"claude",CORTEX_MODEL:t?.selection?.model,CORTEX_PROVIDER:t?.selection?.provider,CORTEX_THINKING:t?.selection?.thinking,CORTEX_CONNECTION:t?.selection?.connection,CORTEX_PROJECT:t?.project,CORTEX_EXECUTION_ID:t?.executionId,[Kn]:t?.clean?"1":void 0}}function Sf(t,e){for(let n of lf)delete t[n];for(let[n,r]of Object.entries(yf(e)))ut(t,n,r)}var bf=64,kf=64;function Tf(t,e){t.CLAUDE_CONFIG_DIR=e??kt;let n=g().maxContextTokens;n!==null&&(t.CLAUDE_CODE_AUTO_COMPACT_WINDOW=String(n))}function _f(){let t=ps.get();return{pi:Ss.peekModels().map(e=>({provider:e.provider,id:e.model})),claude:t.length>0?ds(t):null}}var Su=_f;function bu(t){Su=t}function vf(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}function wr(){let t={},e=Su(),n=cs(e.pi.slice(0,bf));if(n.length>0&&(t.CORTEX_SUBAGENT_PI_MODELS=qn(n)),e.claude&&!vf(e.claude,xt)){let r=e.claude.slice(0,kf).map(i=>({backend:"claude",id:i}));t.CORTEX_SUBAGENT_CLAUDE_MODELS=qn(r)}return t}function wf(t){for(let[e,n]of Object.entries(wr()))ut(t,e,n)}function ku(t,e,n,r,i,s,o,u,a,l){let c=u?{...u}:{...process.env};return pf(c,!u),ff(c,t,!!u),c.CORTEX_SESSION_ID=o?.trackSessionId??e,ut(c,"CORTEX_CALLBACK_SOURCE",n),ut(c,"CORTEX_SCHEDULE_TASK_ID",r),ut(c,"ANTHROPIC_BASE_URL",i),u||Tf(c,l),wf(c),mf(c,s,a),Sf(c,o),c}import{spawn as Ah}from"child_process";import{createInterface as Ch}from"readline";import{createHash as Pf}from"node:crypto";import{closeSync as Of,fstatSync as Mf,openSync as Lf,readSync as Df}from"node:fs";import{readFileSync as xf}from"node:fs";import Ef from"node:path";var If=p("cache-identity-store"),Tu=Ef.join(ke,"cache-identities.json"),Af=1560*6e4;function _u(t,e){let n=t;return!!n&&typeof n.savedAt=="number"&&e-n.savedAt<=Af}function vu(t=Tu,e=Date.now()){let n=new Map,r;try{r=JSON.parse(xf(t,"utf8"))}catch{return n}for(let[i,s]of Object.entries(r.sessions??{}))_u(s,e)&&n.set(i,s);return n}var at=null,un=!1;async function Cf(t,e){for(;un;){un=!1;let n=Date.now(),r=Object.fromEntries([...e()].filter(([,i])=>_u(i,n)));await q(t,JSON.stringify({version:1,sessions:r}))}}function xr(t,e=Tu){un=!0,!at&&(at=Cf(e,t).catch(n=>If.warn(`cache identities not saved: ${n.message}`)).finally(()=>{at=null,un&&xr(t,e)}))}async function Rf(){for(;at;)await at}_t({flush:Rf});var Nf=512*1024,Pe=new Map,ie=new Map,Er=new Map,wu=!1;function Oe(){if(!wu){wu=!0;for(let[t,e]of vu())e.identity&&!ie.has(t)&&(ie.set(t,e.identity),Er.set(t,e.savedAt)),e.refresh&&!Pe.has(t)&&Pe.set(t,e.refresh)}}function jf(){let t=new Map;for(let[e,n]of ie)t.set(e,{identity:n,savedAt:Er.get(e)??Date.now()});for(let[e,n]of Pe){let r=t.get(e);t.set(e,{...r,refresh:n,savedAt:Math.max(r?.savedAt??0,n.at)})}return t}function an(){xr(jf)}function Ir(t){let e=on({connection:t.route.connection,configDir:t.route.claudeConfigDir,anthropicBaseUrl:t.route.anthropicBaseUrl,routeEnv:t.env.sets,unsetEnv:t.env.unsets}),{isUserInitiated:n,teamLead:r,teamWorker:i,disableSkills:s,settingSources:o,clean:u}=t.flags;return Pf("sha256").update(JSON.stringify([ne(t.cwd),e,t.model,t.prompt,t.tools,t.plugins,t.mcp,t.backend,{isUserInitiated:n,teamLead:r,teamWorker:i,disableSkills:s,settingSources:o,clean:u}])).digest("hex")}function Uf(t,e){return t!==null&&t.replace(/\[1m\]$/,"")===e.replace(/\[1m\]$/,"")}function xu(t,e,n,r=Ir(e)){Oe();let i=e.env.context?.selection;if(!i||i.backend!=="claude"||!Uf(n,e.model.id??"")){ie.delete(t)&&an();return}let s={...i,connection:e.route.connection??i.connection,model:e.model.id};ie.set(t,{selection:s,prefix:r}),Er.set(t,Date.now()),an()}function cv(t){Oe();let e=ie.get(t);return e?{selection:{...e.selection},prefix:e.prefix}:null}function dv(t,e){Oe(),ie.get(t)?.prefix===e&&(ie.delete(t),an())}function pv(t,e=Date.now(),n,r){Oe(),Pe.set(t,{at:e,prefix:n,...r}),an()}function fv(t){Oe();let e=Pe.get(t);return e?{...e}:null}function $f(t){let e=t.split(`
5
+ `);for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.includes('"timestamp"'))try{let i=JSON.parse(r);if(typeof i.timestamp!="string"||i.message?.model==="<synthetic>")continue;let s=Date.parse(i.timestamp);if(Number.isFinite(s))return s}catch{continue}}return null}function Eu(t){let e;try{e=Lf(t,"r")}catch{return null}try{let n=Mf(e),r=Math.max(0,n.size-Nf),i=Buffer.alloc(n.size-r);Df(e,i,0,i.length,r);let s=i.toString("utf8");return{text:r>0?s.slice(s.indexOf(`
6
+ `)+1):s,mtimeMs:n.mtimeMs}}catch{return null}finally{Of(e)}}function Bf(t){let e=Eu(t);return e?$f(e.text)??e.mtimeMs:null}function Ff(t){let e;try{e=JSON.parse(t)}catch{return null}let n=e.message?.usage,r=typeof e.timestamp=="string"?Date.parse(e.timestamp):Number.NaN;return e.type!=="assistant"||!n||e.message?.model==="<synthetic>"||!Number.isFinite(r)?null:{at:r,readTokens:n.cache_read_input_tokens??0,writeTokens:n.cache_creation_input_tokens??0,inputTokens:n.input_tokens??0}}function mv(t){let e=Eu(t)?.text.split(`
7
+ `)??[];for(let n=e.length-1;n>=0;n--){if(!e[n].includes('"usage"'))continue;let r=Ff(e[n]);if(r)return r}return null}function Iu(t,e,n){Oe();let r=Bf(t),i=Pe.get(e),s=i&&(n===void 0||n===i.prefix)?i.at:null;return r===null?s:s===null?r:Math.max(r,s)}function Wf(t,e){let n=t.findIndex(r=>r.text===e);if(n!==-1)return t.splice(n,1)[0]}var Me=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(),i=this.session.injectUserMessage(e);return i&&this.active?.phase?.noteInjectionAccepted(),i?(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:i,position:s})=>n({type:"injection_delivered",injectionId:this.ackedId(e,r),foldedIntoTurn:i,...s?{position:s}:{}}),onUndelivered:({text:r})=>n({type:"injection_rejected",injectionId:this.ackedId(e,r),reason:"undelivered"})}}ackedId(e,n){return Wf(e.pending,n)?.id??this.nextId()}nextId(){return`${this.idPrefix}-${++this.seq}`}};function Le(){let t,e;return{promise:new Promise((r,i)=>{t=r,e=i}),resolve:t,reject:e}}function zf(t){throw new Error(`Unhandled NormalizedEvent: ${JSON.stringify(t)}`)}function Au(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 lt(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":case"api_retry":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:Au(t)}:{type:"foreground_result",result:Au(t)};case"subagent_activity":return{...t,phase:e};case"subagent_end":return{...t,phase:e};case"error":return{...t};default:return zf(t)}}var De=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 Ne(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}function Cu(t){let e=t.map(Ne);if(e.some(r=>r===null))return null;let n=e.reduce((r,i)=>r+i,0);return Number.isSafeInteger(n)?n:null}function Ar(t){return{promptTokens:Cu([t?.input,t?.cacheCreation,t?.cacheRead]),cachedTokens:Cu([t?.cacheRead])}}function Ru(t){return{onAssistantMessage:(e,n,r,i)=>t({type:"assistant_text",text:e,...n?{blockId:n}:{},...r!=null?{model:r}:{},...i?{subagent:i}:{}}),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,i)=>{if(t({type:"tool_use",toolUseId:r,name:e,input:n,...i?{subagent:i}:{}}),i)return;let s=Mi("claude",e,n);s&&t({type:"todo_update",toolUseId:r,snapshot:s})},onToolResult:(e,n,r,i,s)=>t({type:"tool_result",toolUseId:e,content:n,ok:!r,...i?{subagent:i}:{},...s?.length?{images:s}:{}}),onCompact:e=>t({type:"context_compacted",trigger:e.trigger,preTokens:e.preTokens}),onModelFallback:e=>t({type:"model_fallback",...e}),onApiRetry:e=>t({type:"api_retry",...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 Pu(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 i=n.lastTokenUsage,s=Ar(i);t({type:"cost_record",provider:"anthropic",model:n.lastModelName||n.modelName||"unknown",tokens_in:s.promptTokens,tokens_out:i?.output??0,prompt_tokens:s.promptTokens,cached_tokens:s.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 ln=class{quotaStopMessage;backend="claude";identity;session;spec;cachePrefix;cacheModel=null;injections;started=!1;constructor(e,n,r,i){this.quotaStopMessage=i,this.session=e,this.spec=n,this.cachePrefix=Ir(n),this.identity=r,this.injections=new Me(e,"claude-run-inj")}get backendSessionId(){return this.session.sessionId}run(e,n){let r=new De;this.cacheModel=null;let i=this.beginRun(r),s=Le(),o=Le(),u=new Ce(n.awaitBackground,{push:l=>r.push(l),settleForeground:l=>s.resolve(l),settleRun:l=>{o.resolve(l),s.resolve(l)},close:()=>r.close()});i.attachPhase(u),this.attachBackgroundSink(u);let a=l=>this.pushTurnEvent(l,n,r);return this.driveRun(e,a,r,u,s),s.promise.catch(l=>o.reject(l)),s.promise.catch(()=>{}),o.promise.catch(()=>{}),{events:{[Symbol.asyncIterator]:()=>({next:()=>r.next()})},result:s.promise,settled:o.promise,cancel:()=>r.close()}}beginRun(e){let n=this.injections.beginRun(e);return this.started||(e.push(lt({type:"session_started",sessionId:this.session.sessionId},"foreground")),this.started=!0),n}attachBackgroundSink(e){let n=e.sink();this.session.setBackgroundTurnSink({...n,onAssistantText:(r,i,s)=>{i&&!s&&(this.cacheModel=i),n.onAssistantText(r,i,s)},onResult:r=>{this.noteCache(r),n.onResult(this.quotaStopped(r))}})}pushTurnEvent(e,n,r){e.type==="assistant_text"&&e.model&&!e.subagent&&(this.cacheModel=e.model),n.onNormalizedEvent?.(e),e.type!=="turn_complete"&&r.push(lt(e,"foreground"))}async driveRun(e,n,r,i,s){let o;try{o=this.quotaStopped(await this.session.sendMessage(e.text,{attachments:e.attachments,...Ru(n),onInputConsumed:u=>r.push(u)})),this.noteCache(o),Pu(n,o,this.session)}catch(u){this.failRun(u,n,r,s);return}r.push({type:"foreground_result",result:o}),i.start(o)}failRun(e,n,r,i){e?.cancelled||n({type:"error",message:String(e?.message??e),fatal:!0}),r.push({type:"phase",phase:"done",pendingBackground:0,undeliveredBackground:0}),r.close(),i.reject(e)}quotaStopped(e){if(!e.hookStopped||e.rateLimited)return e;let n=this.quotaStopMessage?.(this.spec.route.connection);return n?{...e,rateLimited:!0,rateLimitMessage:n}:e}noteCache(e){let n=e.reportedAccounting;!n?.usageReported||(n.cacheReadTokens??0)+(n.cacheCreationTokens??0)<=0||xu(this.session.sessionId,this.spec,this.cacheModel??n.model,this.cachePrefix)}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 Uu from"crypto";import{createHash as Kf}from"node:crypto";import Y from"node:fs";import dt from"node:path";import{fileURLToPath as qf}from"node:url";import je from"node:fs";import X from"node:path";function Ou(t,e){let n=X.resolve(t);for(;;){if(je.existsSync(n)&&je.lstatSync(n).isSymbolicLink())throw new Error(`${e} has a symlink ancestor: ${n}`);let r=X.dirname(n);if(r===n)return;n=r}}function R(t,e){let n=X.resolve(t);if(Ou(n,e),je.mkdirSync(n,{recursive:!0,mode:448}),Ou(n,e),je.realpathSync(n)!==n)throw new Error(`${e} is not a physical path: ${n}`);je.chmodSync(n,448)}function ct(t,e){let n=X.resolve(t),r=X.resolve(e),i=X.relative(n,r);if(i===".."||i.startsWith(`..${X.sep}`)||X.isAbsolute(i))return r;try{return X.join(je.realpathSync(n),i)}catch{return r}}var Hf=p("claude-mcp-config"),Qf=qf(new URL("./remote-mcp-proxy.js",new URL("dist/agent-adapter/claude/mcp-config.js",__cortexPackageRoot).href));function Lu(t,e){return t<e?-1:t>e?1:0}function Cr(t){return Object.fromEntries(t.sort(([e],[n])=>Lu(e,n)))}function Gf(t){return{command:t.command,args:[...t.args],env:Cr(Object.entries(t.env)),cwd:t.cwd}}function Vf(t){return{type:t.type==="streamable-http"?"http":"sse",url:t.url,headers:Cr(Object.entries(t.headers))}}function Jf(t){return t.type==="stdio"?Gf(t):Vf(t)}function Xf(t){let e=t.map(n=>[n.name,Jf(n)]).sort(([n],[r])=>Lu(n,r));return`${JSON.stringify({mcpServers:Object.fromEntries(e)},null,2)}
8
+ `}function cn(t){return Kf("sha256").update(t,"utf8").digest("hex")}function Yf(t){return(t&63)===0}function Du(t){let e=Y.lstatSync(t);if(!e.isFile()||e.isSymbolicLink())throw new Error(`Claude supplemental MCP file is invalid: ${t}`);if(!Yf(e.mode&511))throw new Error(`Claude supplemental MCP file is not private: ${t}`);return Y.readFileSync(t,"utf8")}function Rr(t,e){if(dt.basename(t)!==`${e}.json`)throw new Error(`Claude supplemental MCP file identity mismatch: ${t}`);if(cn(Du(t))!==e)throw new Error(`Claude supplemental MCP file identity mismatch: ${t}`)}function Mu(t,e){if(Du(t)!==e)throw new Error(`Claude supplemental MCP file content mismatch: ${t}`);Rr(t,cn(e))}function Zf(t,e){let n=`${t}.tmp.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2,8)}`;Y.writeFileSync(n,e,{encoding:"utf8",mode:384}),Y.chmodSync(n,384),Y.renameSync(n,t),Y.chmodSync(t,384)}function em(t){try{let e=new Date;Y.utimesSync(t,e,e)}catch{}}function Nu(t,e,n){R(t,n);let r=dt.join(t,`${cn(e)}.json`);if(Y.existsSync(r))return Mu(r,e),em(r),r;try{Zf(r,e)}catch(i){if(!Y.existsSync(r))throw i;Mu(r,e)}return r}function tm(t,e){let n=dt.join(e,"claude-mcp-proxies"),r=`${JSON.stringify({type:t.type,url:t.url,headers:Cr(Object.entries(t.headers))})}
9
+ `,i=Nu(n,r,"Claude remote MCP runtime");return{name:t.name,type:"stdio",command:process.execPath,args:[Qf,i],env:{},cwd:n}}function nm(t,e){return t.flatMap(n=>{if(n.type==="stdio")return[n];try{return[tm(n,e)]}catch(r){return Hf.warn(`Skipping Claude remote MCP '${n.name}': ${r.message}`),[]}})}function ju(t,e={}){let n=ct(M,e.runtimeDir??dt.join(M,"data","plugin-runtime"));R(n,"Claude MCP runtime");let r=Xf(nm(t,n)),i=cn(r),s=dt.join(n,"claude-mcp");return{path:Nu(s,r,"Claude MCP runtime"),identity:i}}function rm(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 im(t){return{mcpComposition:t.mcpComposition,mcpConfigPaths:t.mcpConfigPaths,mcpToolAllowlist:t.mcpToolAllowlist,supplementalMcpConfigPath:t.supplementalMcpConfigPath??null,disableHooks:t.disableHooks===!0,quotaStop:!t.pinnedEnv,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 sm(t){let{channel:e,options:n}=t;return{...rm(n),...im(n),needsResume:t.needsResume,sessionId:t.sessionId,loadSlackMcp:e.startsWith("slack:"),loadFeishuMcp:e.startsWith("feishu:"),loadWebMcp:e.startsWith("web:")}}function $u(t){let e=sm(t),{options:n}=t,r=ku(t.channel,t.sessionId,n.callbackSource||null,n.scheduleTaskId||null,n.anthropicBaseUrl,n.routeEnv,n.context,n.pinnedEnv,n.unsetEnv,n.configDir);return r[us]=as(sn(e)),n.pinnedEnv||om(r,n.connection),{args:yu(e),env:r}}function om(t,e){e?t[Hn]=e:delete t[Hn]}function um(t){if(!t||t.length===0)return null;let e=t.map(n=>Tt("claude",n)).filter(n=>typeof n=="string");return e.length?e.join(","):null}function am(t,e){return!t.mcp.servers||e!=="direct"?null:ju(t.mcp.servers)}function lm(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??um(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 cm(t,e){let n=am(t,e);return{anthropicBaseUrl:t.route.anthropicBaseUrl,connection:t.route.connection,configDir:t.route.claudeConfigDir,routeEnv:t.env.sets,unsetEnv:t.env.unsets,cwd:ne(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 Pr(t){let e=Ot(t.mcp.composition);return{...lm(t),...cm(t,e)}}function Or(t){let e=t.context.channel??t.env.sets?.SLACK_CHANNEL??t.engineKey;return{channel:e,sessionKey:t.engineKey||e,sessionId:t.resume.backendSessionId||Uu.randomUUID(),needsResume:t.resume.resume,options:Pr(t)}}import{closeSync as dm,existsSync as pm,fstatSync as fm,openSync as mm,readSync as hm}from"node:fs";import*as Fu from"path";function Mr(t,e){let n=t.replace(/[/.]/g,"-");return Fu.join(Vi,n,`${e}.jsonl`)}function Wu(t,e,n=pm){return t&&n(e)}var Bu=Buffer.from('"cost-state"'),gm=1<<20;function ym(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 Sm(t,e){let n=t.lastIndexOf(Bu);for(;n!==-1;){let r=t.lastIndexOf(10,n)+1,i=t.indexOf(10,n),s=ym(t.toString("utf8",r,i===-1?t.length:i),e);if(s!==null)return s;if(r===0)return null;n=t.lastIndexOf(Bu,r-1)}return null}function zu(t,e,n=gm){let r;try{r=mm(t,"r")}catch{return 0}try{let i=fm(r).size,s=Buffer.alloc(0);for(;i>0;){let o=Math.max(0,i-n),u=Buffer.alloc(i-o);hm(r,u,0,u.length,o);let a=s.length?Buffer.concat([u,s]):u,l=o===0?-1:a.indexOf(10);if(o>0&&l===-1){s=a,i=o;continue}let c=Sm(a.subarray(l+1),e);if(c!==null)return c;s=a.subarray(0,Math.max(l,0)),i=o}return 0}catch{return 0}finally{dm(r)}}import*as L from"node:fs";import*as qu from"node:path";import{isUtf8 as bm}from"node:buffer";var Hu=p("claude-bridge"),Qu="[Old tool result content cleared]",km=10,Tm=65*6e4,_m=1e5,vm=4e4,Ku=Buffer.from('"compact_boundary"'),wm={readFileSync:t=>L.readFileSync(t),statSync:t=>L.statSync(t),writeFileSync:(t,e,n)=>L.writeFileSync(t,e,{mode:n}),appendFileSync:(t,e)=>L.appendFileSync(t,e),renameSync:(t,e)=>L.renameSync(t,e),unlinkSync:t=>L.unlinkSync(t)};function Dr(t){try{let e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function Gu(t){if(!t.includes('"compact_boundary"'))return!1;let e=Dr(t);return e?.type==="system"&&e.subtype==="compact_boundary"}function Vu(t){for(let e=t.length-1;e>=0;e--)if(Gu(t[e]))return e+1;return 0}function Ju(t){let e=t?.message;return e!==null&&typeof e=="object"?e:null}function xm(t){if(t?.type!=="user"||t.isSidechain===!0)return[];let e=Ju(t)?.content;return Array.isArray(e)?e.filter(n=>n!==null&&typeof n=="object"&&n.type==="tool_result"):[]}function Em(t,e){let n=[];for(let r=e;r<t.length;r++){if(!t[r].includes('"tool_result"'))continue;let i=Dr(t[r]);for(let s of xm(i))n.push({line:r,record:i,block:s})}return n}var Im=JSON.stringify(Qu).length;function Am(t){let e=JSON.stringify(t.content??"").length-Im;return e<=0?0:(t.content=Qu,e)}function Cm(t,e=km){let n=Em(t,Vu(t)),r=new Map,i=0,s=0;for(let u of n.slice(0,Math.max(0,n.length-e))){let a=Am(u.block);a!==0&&(r.set(u.line,u.record),i++,s+=a)}return{lines:t.map((u,a)=>r.has(a)?JSON.stringify(r.get(a)):u),clearedCount:i,charsRemoved:s}}function Lr(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}function Rm(t){if(t?.type!=="assistant"||t.isSidechain===!0)return null;let e=Ju(t)?.usage;if(e===null||typeof e!="object")return null;let n=Lr(e.input_tokens)+Lr(e.cache_read_input_tokens)+Lr(e.cache_creation_input_tokens);return n>0?n:null}function Pm(t){let e=Vu(t);for(let n=t.length-1;n>=e;n--){if(!t[n].includes('"usage"'))continue;let r=Rm(Dr(t[n]));if(r!==null)return r}return null}function Om(t){let e=t.lastIndexOf(Ku);for(;e!==-1;){let n=t.lastIndexOf(10,e)+1,r=t.indexOf(10,e);if(Gu(t.toString("utf8",n,r===-1?t.length:r)))return n;if(n===0)return 0;e=t.lastIndexOf(Ku,n-1)}return 0}function Mm(t,e,n){if(!g().coldResumeClearToolResults)return"disabled";let r=Iu(t,e);return r===null||n-r<=Tm?"warm":null}function Lm(t,e){try{return e.readFileSync(t)}catch{return null}}function Dm(t){let e=t.split(`
10
+ `),n=Pm(e);if(n===null||n<_m)return"small-context";let r=Cm(e);return r.charsRemoved<vm?"too-little":r}function Nm(t,e,n,r){let i=`${t}.${process.pid}.clear.tmp`;try{r.writeFileSync(i,e,r.statSync(t).mode&511),r.appendFileSync(i,n),r.renameSync(i,t)}catch(s){try{r.unlinkSync(i)}catch{}throw s}}function jm(t,e,n,r){try{Nm(t,e,n.lines.join(`
11
+ `),r)}catch(i){return Hu.warn(`Cold-resume tool-result clearing failed for ${qu.basename(t)}, resuming it as is: ${i.message}`),{cleared:!1,reason:"write-failed"}}return{cleared:!0,clearedCount:n.clearedCount,charsRemoved:n.charsRemoved}}function Um(t,e){let n=Lm(t,e);if(!n)return{cleared:!1,reason:"unreadable"};let r=Om(n),i=n.subarray(r);if(!bm(i))return{cleared:!1,reason:"unreadable"};let s=Dm(i.toString("utf8"));return typeof s=="string"?{cleared:!1,reason:s}:jm(t,n.subarray(0,r),s,e)}function Xu(t,e,n=Date.now(),r=wm){let i=Mm(t,e,n),s=i?{cleared:!1,reason:i}:Um(t,r);return s.cleared&&Hu.info(`Cleared ${s.clearedCount} old tool results before cold resume: ${e.substring(0,8)} (-${s.charsRemoved} chars)`),s}import{readFileSync as Fm}from"fs";var $m={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 Yu(t,e){let n=$m[t];return n?n(e):JSON.stringify(e)}import*as Zu from"path";function Bm(t){if(t.length===0)return"";let e=t.map(n=>`${n.name} (${n.reason})`).join(`
12
+ `);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:
13
+ ${e}
14
+ ]
15
+
16
+ `}function Nr(t){let e=t.path.replace(/\\/g,"/"),n=t.name?.trim();return n&&n!==Zu.basename(e)?`${e} (${n})`:e}function me(t,e,n=[]){if(e.length===0&&n.length===0)return t;let r=e.filter(u=>Fn.has(u.mimeType)),i=e.filter(u=>Wn.has(u.mimeType)),s=e.filter(u=>!Fn.has(u.mimeType)&&!Wn.has(u.mimeType)),o="";if(r.length>0){let u=r.map(Nr).join(`
17
+ `);o+=`[User sent ${r.length} image(s). Read these files to view them:
18
+ ${u}
19
+ ]
20
+
21
+ `}if(i.length>0){let u=i.map(Nr).join(`
22
+ `);o+=`[User sent ${i.length} video(s). Read these files to view them:
23
+ ${u}
24
+ ]
25
+
26
+ `}if(s.length>0){let u=s.map(Nr).join(`
27
+ `);o+=`[User sent ${s.length} file(s). Read these files:
28
+ ${u}
29
+ ]
30
+
31
+ `}return o+=Bm(n),o+(t||(e.length>0?"Please analyze the attached file(s).":""))}function ea(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 ta(t){return t?.type!=="system"||t.subtype!=="api_retry"||typeof t.attempt!="number"?null:{type:"api_retry",attempt:t.attempt,error:typeof t.error=="string"?t.error:null}}function jr(){return{messageId:null,model:null,textBlockId:null,thinkingBlockId:null}}function Wm(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 zm(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 Km(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 i=`${e.messageId}:${t.index}`;return n==="thinking_delta"?(e.thinkingBlockId=i,{kind:"thinking",text:r,blockId:i}):(e.textBlockId=i,{text:r,blockId:i})}function na(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"?(Wm(n,e),null):n.type==="content_block_start"?(zm(n,e),null):n.type==="content_block_delta"?Km(n,e):null}function ra(t){let e=t.textBlockId;return t.textBlockId=null,e}function ia(t){let e=t.thinkingBlockId;return t.thinkingBlockId=null,e}function qm(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||"?"}: ${Yu(n.name,n.input||{})}`);return e.length?e.join(`
32
+ `):null}function Hm(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 i=r.content||"",s;Array.isArray(i)?s=i.filter(o=>o.type==="text").map(o=>o.text||"").join(" "):typeof i=="string"?s=i:s=JSON.stringify(i),n.push(`[tool_result]${r.is_error?" [ERROR]":""}: ${s}`)}return n.length?n.join(`
33
+ `):null}function Qm(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}
34
+ \u2192 ${e}`}var Gm={assistant:qm,user:Hm,result:Qm};function Ur(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=Gm[e];return n?n(t):null}function Vm(t,e){return!t||!e||t===e?t:t.length<300&&t.length<e.length*.5?e+`
35
+
36
+ ---
37
+ `+t:t}function Jm(t){if(!t?.is_error||typeof t.result!="string")return null;let e=t.result,n=e.toLowerCase();return/hit your (?:[\w-]+ )?limit/.test(n)||n.includes("rate limit")||n.includes("rate_limit")||n.includes("too many requests")||n.includes("temporarily limiting requests")?e:null}function dn(t,e,n,r,i,s,o,u,a){let l=null,c=null,d=!1,m=null,v=e;if(t){t.total_cost_usd!=null&&(l=t.total_cost_usd),t.num_turns!=null&&(c=t.num_turns);let N=Jm(t);if(N&&(d=!0,m=N),typeof t.session_id=="string"&&t.session_id!==e&&(v=t.session_id),t.is_error&&!d){let Bn=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(Bn)}}}let E=Vm(u,a),h={sessionId:v,total_cost_usd:l,num_turns:c,rateLimited:d,rateLimitMessage:m,planFilePath:i,enteredPlanMode:s,exitedPlanMode:o,askUserQuestions:[],finalOutput:E||null,...t?.terminal_reason==="hook_stopped"?{hookStopped:!0}:{}};return d?{resolved:!0,value:h}:n!==0?{resolved:!1,error:new Error(r||`claude exited with code ${n}`)}:{resolved:!0,value:h}}function Xm(t){if(typeof t!="string")return null;let e=t.trim();return e?e.replace(/^\.\//,"").replace(/\\/g,"/").replace(/\/+$/,""):null}function Ym(){let t=[];try{let e=JSON.parse(Fm(Yi,"utf8")),n=Xm(e?.plansDirectory);n&&t.push(n)}catch{}for(let e of Zi)t.includes(e)||t.push(e);return t}var Zm=Ym();function sa(t){if(typeof t!="string"||!t)return!1;let e=t.replace(/\\/g,"/");return Zm.some(n=>e.includes(`${n}/`)||e.endsWith(`/${n}`))}var $r=new Map;function oa(t,e){!t||!e||$r.set(t,e)}function pn(t){t&&$r.delete(t)}function ow(t){return t&&$r.get(t)||null}var eh=new Set(["completed","failed","killed"]),pt=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 i=r.status;i==="killed"?(this.running.delete(n),this.undelivered.delete(n),this.foreground.delete(n)):(i==="completed"||i==="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(i=>i?.type==="text").map(i=>i.text).join(`
38
+ `):"";if(r.includes("<task-notification>"))for(let i of r.matchAll(/<task-id>([^<]+)<\/task-id>/g))this.armed.delete(i[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 i=e.subtype==="task_updated"?e.patch?.status:e.subtype==="task_notification"?e.status:null;return typeof i!="string"||!eh.has(i)?null:(this.subagentTasks.delete(n),{parentToolUseId:r,status:i})}};function ua(t){return t?.type==="result"&&t?.origin?.kind==="task-notification"}function Br(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 dh,mkdirSync as ph}from"fs";import{Writable as fh}from"stream";import*as ft from"path";var th=p("claude-bridge");function nh(t,e,n,r){e.name==="Write"&&sa(e.input?.file_path)&&(t.planFilePath=e.input.file_path,oa(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(i){th.warn("onToolUse threw:",i.message)}}function rh(t,e,n,r,i){if(!n.text)return;let s=typeof e.message?.model=="string"?e.message.model:null;if(i){t.onAssistantMessage?.(n.text,void 0,s,i);return}t.finalOutput=n.text,n.text.length>(t.longestOutput?.length||0)&&(t.longestOutput=n.text);let o=ra(r)??void 0,u=r.messageId===e.message?.id?r.model:null;t.onAssistantMessage?.(n.text,o,s??u)}function ih(t,e,n,r){if(r)return;let i=ia(n)??void 0;!g().showThinking||typeof e.thinking!="string"||!e.thinking||t.onAssistantThinking?.(e.thinking,i)}function aa(t,e,n,r,i){i?t.subagentTurnCount+=1:t.turnCount+=1;let s={tool_use:o=>nh(t,o,r,i),text:o=>rh(t,e,o,n,i),thinking:o=>ih(t,o,n,i)};for(let o of e.message?.content||[])s[o.type]?.(o);i||t.onProgress?.({num_turns:t.turnCount,total_cost_usd:null,duration_ms:null})}var sh=p("claude-bridge");function Fr(t,e){try{e()}catch(n){sh.warn(`${t} threw:`,n.message)}}function oh(t,e){if(e.subtype!=="compact_boundary"||!t.onCompact)return;let n=e.compact_metadata??{};Fr("onCompact",()=>t.onCompact({trigger:typeof n.trigger=="string"?n.trigger:"auto",preTokens:typeof n.pre_tokens=="number"?n.pre_tokens:void 0}))}function uh(t,e){let n=ea(e);!n||!t.onModelFallback||Fr("onModelFallback",()=>t.onModelFallback({originalModel:n.originalModel,fallbackModel:n.fallbackModel}))}function ah(t,e){let n=ta(e);!n||!t.onApiRetry||Fr("onApiRetry",()=>t.onApiRetry({attempt:n.attempt,error:n.error}))}var lh=[oh,uh,ah];function la(t,e){if(!(!t||e?.type!=="system"))for(let n of lh)n(t,e)}function ch(t){return t>=1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:t>=1024?`${Math.round(t/1024)} KB`:`${t} B`}function ca(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}, ${ch(Math.floor(n.data.length*3/4))}]`:typeof n.url=="string"?`[${r}, ${n.url}]`:`[${r}]`}let e=JSON.stringify(t)??"";return e.length>1e3?`${e.slice(0,1e3)}\u2026 [${e.length-1e3} more chars]`:e}function Wr(t){return typeof t.content=="string"?t.content:Array.isArray(t.content)?t.content.map(ca).join(`
39
+ `):t.content==null?"":ca(t.content)}function fn(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}}function da(t){return t.type==="assistant"?"assistant":t.type==="user"&&!t.isReplay?"tool_result":null}function pa(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}function fa(t,e){let n=null;for(let r=1;r<=t.length;r++){let i=t[r-1].prompt;if(n=n===null?i:`${n}
40
+ ${i}`,n===e)return r;if(n.length>=e.length)return 0}return 0}function ma(t){try{return JSON.parse(t)}catch{return}}function ha(t){return{resultData:null,planFilePath:null,enteredPlanMode:!1,exitedPlanMode:!1,finalOutput:null,longestOutput:null,turnCount:0,subagentTurnCount:0,capturePairKey:t.pairKey,releaseCapture:t.releaseCapture,rawStream:t.rawStream,txtStream:t.txtStream,killed:!1}}function ga(t){return{onProgress:t.onProgress||null,onAssistantMessage:t.onAssistantMessage||null,onAssistantDelta:t.onAssistantDelta||null,onAssistantThinking:t.onAssistantThinking||null,onAssistantThinkingDelta:t.onAssistantThinkingDelta||null,onToolUse:t.onToolUse||null,onToolResult:t.onToolResult||null,onCompact:t.onCompact||null,onModelFallback:t.onModelFallback||null,onApiRetry:t.onApiRetry||null,onContextUsage:t.onContextUsage||null,onSubagentActivity:t.onSubagentActivity||null,onSubagentEnd:t.onSubagentEnd||null}}var x=p("claude-bridge");function ya(t){let e=dh(t,{flags:"a"});return e.on("error",n=>x.warn(`Transcript log ${ft.basename(t)} stopped: ${n.message}`)),e}var mn=class{host;currentTurn=null;streamDeltaState=jr();contextUsageTracker;bgTracker=new pt;backgroundTurnSink=null;pendingInjections=[];injectionAck=null;injectionContinuationArmed=!1;queuedTurn=null;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 i={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(i)}catch(s){x.warn("bg-interrupted sink onResult threw:",s.message)}}createTurnStreams(e){if(!this.host.captureTranscriptLogs){let a=()=>new fh({write(l,c,d){d()}});return{rawStream:a(),txtStream:a(),pairKey:null,releaseCapture:null}}ph(Ct,{recursive:!0});let n=Ni(),r=ft.join(Ct,`claude-output-${n}.jsonl`),i=ft.join(Ct,`claude-output-${n}.txt`),s=ya(r),o=ya(i),u=uo.register(n,[r,i]);return o.write(`=== Cortex session started at ${new Date().toISOString()} ===
41
+ === channel=${this.host.channel}, session=${this.host.sessionId} ===
42
+
43
+ `),o.write(`[user-input] ${e}
44
+
45
+ `),{rawStream:s,txtStream:o,pairKey:n,releaseCapture:u}}registerTurn(e,n,r,i){pn(this.host.sessionId);let s={resolve:e,reject:n,...ha(r),...ga(i),onInputConsumed:i.onInputConsumed};if(this.currentTurn?.spontaneous){this.queueBehindContinuation(s);return}this.displaceOpenTurn(),this.currentTurn=s}queueBehindContinuation(e){let n=this.queuedTurn;n&&this.settleDisplaced(n),x.info(`New turn on ${this.host.sessionId.substring(0,8)} during a continuation; it opens when that ends`),this.queuedTurn=e}displaceOpenTurn(){let e=this.currentTurn;!e||e.spontaneous||(x.info(`New turn on ${this.host.sessionId.substring(0,8)} while a user turn is open; settling the open one`),this.settleDisplaced(e))}foldContinuation(){let e=this.currentTurn;!this.queuedTurn||!e||(x.info(`Continuation on ${this.host.sessionId.substring(0,8)} folded into the new turn`),this.settleDisplaced(e))}settleDisplaced(e){e.txtStream.write(`[displaced by a new turn \u2014 the loop result goes to that turn]
46
+ `);let n=dn(null,this.host.sessionId,0,"",e.planFilePath,e.enteredPlanMode,e.exitedPlanMode,e.finalOutput,e.longestOutput);this.settleResultTurn(e,{},n)}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=me(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=pa(e);if(n===null)return;let r=fa(this.pendingInjections,n);if(r===0){this.notePromptEcho(e,n);return}let i=this.pendingInjections.splice(0,r),s=!!this.currentTurn;s||(this.injectionContinuationArmed=!0);for(let o of i)this.ackDelivered(o.text,s,e.uuid)}notePromptEcho(e,n){if(e.origin?.kind==="task-notification"||n.startsWith("<task-notification>"))return;this.foldContinuation();let i=this.currentTurn;!i||i.promptConsumed||(i.promptConsumed=!0,i.spontaneous||i.onInputConsumed?.({type:"input_consumed",backendSessionId:this.host.sessionId,...typeof e.uuid=="string"&&e.uuid?{position:{before:e.uuid}}:{}}))}ackDelivered(e,n,r){let i=this.injectionAck;if(!i)return;let s=typeof r=="string"&&r?{before:r}:void 0;try{i.onDelivered({text:e,foldedIntoTurn:n,...s?{position:s}:{}})}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,i)=>this.deliverContinuation(s=>s.onAssistantText(e,r,i)),onAssistantThinking:(e,n)=>this.deliverContinuation(r=>r.onAssistantThinking?.(e,n)),onToolUse:(e,n,r,i)=>this.deliverContinuation(s=>s.onToolUse?.(e,n,r,i)),onToolResult:(e,n,r,i,s)=>this.deliverContinuation(o=>o.onToolResult?.(e,n,r,i,s)),onContextUsage:e=>this.deliverContinuation(n=>n.onContextUsage?.(e)),onModelFallback:null,onApiRetry:null}}openContinuationTurn(e){let n=this.bgTracker.disarmContinuation(),r=e?"[injected-message continuation]":"[background-task continuation]",i=this.createTurnStreams(r),s=e?void 0:{summaries:n};this.deliverContinuation(o=>o.onTurnOpen?.(s)),this.currentTurn={...this.continuationCallbacks(),resultData:null,planFilePath:null,enteredPlanMode:!1,exitedPlanMode:!1,finalOutput:null,longestOutput:null,turnCount:0,subagentTurnCount:0,capturePairKey:i.pairKey,releaseCapture:i.releaseCapture,onProgress:null,onAssistantDelta:null,onCompact:null,onSubagentActivity:null,onSubagentEnd:null,onAssistantThinkingDelta:null,rawStream:i.rawStream,txtStream:i.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:Ne(n.input_tokens),output:Ne(n.output_tokens),cacheCreation:Ne(n.cache_creation_input_tokens),cacheRead:Ne(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,...Ar(r),model:e.modelUsage?Object.keys(e.modelUsage)[0]??null:null}}settleResultTurn(e,n,r){if(r.resolved){let s=r.value;s.reportedAccounting=this.reportedAccounting(n),s.pendingBackgroundTasks=this.bgTracker.pendingCount,s.undeliveredBackgroundTasks=this.bgTracker.undeliveredCount+(this.bgTracker.continuationArmed?1:0)}this.releaseTurnSlot(e);let i=Ur(n);i&&e.txtStream.write(i+`
47
+ `),e.txtStream.write(`
48
+ === Turn finished at ${new Date().toISOString()} ===
49
+ `),e.rawStream.end(),e.txtStream.end(),e.releaseCapture?.(),e.releaseCapture=null,r.resolved?e.resolve(r.value):e.reject(r.error)}releaseTurnSlot(e){let n=e===this.currentTurn?this.queuedTurn:null;e===this.currentTurn&&(this.currentTurn=n),this.queuedTurn=null,n||this.host.clearTurnIdleTimer()}handleResultEvent(e,n){e.resultData={...n,total_cost_usd:this.captureTurnAccounting(n)};let r=dn(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 i=fn(n);for(let s of r){if(!s||s.type!=="tool_result")continue;let o=typeof s.tool_use_id=="string"?s.tool_use_id:"",u=Qn(s.content);try{e.onToolResult(o,Wr(s),s.is_error===!0,i,u.length?u:void 0)}catch(a){x.warn("onToolResult threw:",a.message)}}}handleOrphanSubagentLine(e){let n=fn(e);if(!n)return;let r=e.message?.content;if(!Array.isArray(r))return;let i=typeof e.message?.model=="string"?e.message.model:null;for(let s of r)if(s){if(s.type==="tool_use"){let o=typeof s.id=="string"?s.id:"";this.deliverContinuation(u=>u.onToolUse?.(s.name||"?",s.input||{},o,n))}else if(s.type==="text"&&s.text)this.deliverContinuation(o=>o.onAssistantText(s.text,i,n));else if(s.type==="tool_result"){let o=typeof s.tool_use_id=="string"?s.tool_use_id:"",u=Qn(s.content);this.deliverContinuation(a=>a.onToolResult?.(o,Wr(s),s.is_error===!0,n,u.length?u:void 0))}}}handleAssistantEvent(e,n){aa(e,n,this.streamDeltaState,this.host.sessionId,fn(n))}handleStreamEvent(e){this.emitContextUsage(e);let n=na(e,this.streamDeltaState);if(!n)return;let r=n.kind==="thinking"?g().showThinking?this.currentTurn?.onAssistantThinkingDelta:null:this.currentTurn?.onAssistantDelta;try{r?.(n.text,n.blockId)}catch(i){x.warn("assistant delta callback threw:",i.message)}}emitContextUsage(e){let n=this.contextUsageTracker.observe(e),r=this.currentTurn?.onContextUsage;if(!(!n||typeof r!="function"))try{r(n)}catch(i){x.warn("onContextUsage threw:",i.message)}}emitSubagentActivity(e){let n=e?.parent_tool_use_id;if(typeof n!="string")return;let r=da(e);if(!r)return;let i=typeof e.subagent_type=="string"?e.subagent_type:null,s=this.currentTurn?.onSubagentActivity;if(typeof s=="function")try{s(n,i,r)}catch(o){x.warn("onSubagentActivity threw:",o.message)}}handleLine(e){if(!e)return;this.host.resetIdleTimer(),this.host.bumpTurnIdleTimer();let n=ma(e);if(n?.type==="stream_event"){this.handleStreamEvent(n);return}this.currentTurn?.rawStream?.write(e+`
50
+ `),this.handleCompleteLine(e,n)&&x.info("stream:",e.substring(0,200))}handleCompleteLine(e,n){try{if(n===void 0)throw new Error("not json");return this.handleEvent(n)}catch{return this.currentTurn?.txtStream?.write(`[raw] ${e}
51
+ `),!0}}handleEvent(e){if(this.observeLine(e),this.routeTurnlessLine(e),e.type==="result"&&this.currentTurn)return this.handleTurnResult(this.currentTurn,e),!1;e.type==="assistant"&&this.currentTurn&&this.handleAssistantEvent(this.currentTurn,e),this.emitSubagentActivity(e);let n=Ur(e);return n&&this.currentTurn?.txtStream?.write(n+`
52
+ `),!0}observeLine(e){e.type==="system"&&e.subtype==="compact_boundary"&&this.emitContextUsage(e),la(this.currentTurn,e),e.type==="rate_limit_event"&&e.rate_limit_info&&this.host.reportRateLimit(e.rate_limit_info,{provider:"anthropic",displayName:"Anthropic",mode:this.host.connection}).catch(n=>x.error("handleRateLimitEvent error:",n)),this.observeUserLine(e),this.bgTracker.observe(e),this.forwardSubagentEnd(e)}observeUserLine(e){e.type==="user"&&(e.isReplay?this.handleReplayEcho(e):this.currentTurn&&this.handleToolResultEvent(this.currentTurn,e))}forwardSubagentEnd(e){let n=this.bgTracker.subagentEndFor(e);if(!n)return;let r=this.currentTurn?.onSubagentEnd;if(!r){this.deliverContinuation(i=>i.onSubagentEnd?.(n.parentToolUseId,n.status));return}try{r(n.parentToolUseId,n.status)}catch(i){x.warn("onSubagentEnd threw:",i.message)}}routeTurnlessLine(e){if(!this.currentTurn&&(Br(this.bgTracker,e)==="subagent-orphan"&&this.handleOrphanSubagentLine(e),this.startsContinuation(e))){let n=this.injectionContinuationArmed;this.injectionContinuationArmed=!1,this.openContinuationTurn(n)}}startsContinuation(e){return!!this.backgroundTurnSink&&e.type==="assistant"&&(this.injectionContinuationArmed||Br(this.bgTracker,e)==="open-continuation")}handleTurnResult(e,n){if(ua(n)&&!e.spontaneous&&!e.promptConsumed){x.info(`Ignoring notification-turn result on user turn ${this.host.sessionId.substring(0,8)} (num_turns=${n.num_turns??"?"})`),e.txtStream.write(`[notification-turn result ignored \u2014 user turn still open]
53
+ `);return}this.emitContextUsage(n),this.handleResultEvent(e,n)}closeTurnLogs(e){try{e.txtStream.write(`
54
+ === Turn ended at ${new Date().toISOString()} ===
55
+ `),e.rawStream.end(),e.txtStream.end()}catch{}e.releaseCapture?.(),e.releaseCapture=null}abortTurnOnProcessClose(e,n){let r=[this.currentTurn,this.queuedTurn];this.currentTurn=null,this.queuedTurn=null;for(let i of r)i&&this.abortTurn(i,e,n)}abortTurn(e,n,r){if(this.closeTurnLogs(e),this.host.clearTurnIdleTimer(),e.spontaneous)this.notifyBgInterrupted(!0);else if(e.killed)e.reject(e.killError??new ss);else{let i=dn(e.resultData,this.host.sessionId,n||1,r,e.planFilePath,e.enteredPlanMode,e.exitedPlanMode,e.finalOutput,e.longestOutput);i.resolved?e.resolve(i.value):e.reject(i.error)}}failInFlightTurn(e){let n=this.queuedTurn??this.currentTurn;n&&(this.queuedTurn=null,n===this.currentTurn&&(this.currentTurn=null),this.closeTurnLogs(n),n.reject(e))}holdsIdle(){return this.bgTracker.hasPending()||this.pendingInjections.length>0||this.injectionContinuationArmed}markCurrentTurnKilled(e){let n=this.queuedTurn??this.currentTurn;n&&(n.killed=!0,n.killError=e)}};function K(t){return t!==null&&typeof t=="object"?t:null}function he(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}function Sa(t,e){return t[e]===void 0?0:he(t[e])}function ba(t){let e=K(t);if(!e)return null;let n=he(e.input_tokens),r=Sa(e,"cache_creation_input_tokens"),i=Sa(e,"cache_read_input_tokens");return n===null||r===null||i===null?null:he(n+r+i)}function mh(t){let e=K(t);if(!e)return null;let n=ba(e),r=he(e.output_tokens);return n===null||r===null?null:he(n+r)}function hh(t){let n=K(t.usage)?.iterations;return Array.isArray(n)&&n.length>0?n.at(-1):null}function ka(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:null}function gh(t){let e=K(t)?.canonicalModel;return typeof e=="string"?e:null}function yh(t){return t?.replace(/\[1m\]$/,"")??null}function Ta(t,e){return e?t.find(([,n])=>gh(n)===e)?.[1]??null:null}function _a(t,e){return e?t.find(([n])=>n===e)?.[1]??null:null}function Sh(t,e){return Ta(t,e)??_a(t,e)}function bh(t,e){return _a(t,e)??Ta(t,yh(e))}function kh(t,e,n){let r=K(t);if(!r)return null;let i=Object.entries(r);return Sh(i,e)??bh(i,n)??(i.length===1?i[0][1]:null)}function Th(t,e,n){let r=K(kh(t.modelUsage,e,n));return ka(r?.contextWindow)}function _h(t){return t?.endsWith("[1m]")?1e6:2e5}var hn=class{configuredModel;autoCompactWindow;contextWindow;currentInput=null;currentUsed=null;activeModel=null;resultFallbackAllowed=!0;lastSnapshotKey=null;constructor(e,n){this.configuredModel=e??null,this.autoCompactWindow=ka(n),this.contextWindow=this.capped(_h(e))}capped(e){return this.autoCompactWindow===null?e:Math.min(e,this.autoCompactWindow)}observe(e){let n=K(e);return n?n.type==="stream_event"?this.observeStream(K(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(K(e.message)):e?.type==="message_delta"?this.observeMessageDelta(K(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=ba(e?.usage);return n===null?null:(this.currentInput=n,this.currentUsed=n,this.snapshot(n))}observeMessageDelta(e){let n=he(e?.output_tokens);return this.currentInput===null||n===null?null:(this.currentUsed=he(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=Th(e,this.activeModel,this.configuredModel);n!==null&&(this.contextWindow=this.capped(n));let r=this.resultFallbackAllowed?mh(hh(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 vh from"node:fs";import zr from"node:path";var wh=1e5,xh=1e6;function Eh(t){try{let n=JSON.parse(vh.readFileSync(t,"utf8"))?.autoCompactWindow;return typeof n!="number"||!Number.isInteger(n)?null:n>=wh&&n<=xh?n:null}catch{return null}}function Ih(t,e=kt){let n=[zr.join(t,".claude","settings.local.json"),zr.join(t,".claude","settings.json"),zr.join(e,"settings.json")];for(let r of n){let i=Eh(r);if(i!==null)return i}return null}function va(t,e){return(e.pinned?null:g().maxContextTokens)??Ih(t,e.userConfigDir)}var wa=0;function xa(){return wa}function Ww(){wa+=1}var gn=p("claude-bridge");function Rh(t,e,n,r){let i=r??"claude";return t?t(i,e,n):{process:Ah(i,e,{...n,stdio:["pipe","pipe","pipe"]})}}function Ea(t){return t?[...t]:[]}function Ia(t){return t==null?null:[...t]}function Ra(t){let e=t.mcpComposition;return{cwd:ne(t.cwd),routeIdentity:on(t),composition:e,interactionBridge:e==="direct"&&t.isUserInitiated===!0&&t.teamWorker!==!0,teamLead:e==="direct"&&t.teamLead===!0,teamWorker:e==="direct"&&t.teamWorker===!0,tools:t.tools??null,pluginCapabilityFingerprint:t.pluginCapabilityFingerprint??null,pluginDirs:Ea(t.pluginDirs),mcpConfigPaths:Ea(t.mcpConfigPaths),mcpToolAllowlist:Ia(t.mcpToolAllowlist),supplementalMcpConfigIdentity:t.supplementalMcpConfigIdentity??null,disableSkills:t.disableSkills===!0,settingSources:Ia(t.settingSources)}}function Ph(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 Aa(t){let e=Ph(Ra(Pr(t))),n=xa();return n===0?e:`${e}#cli${n}`}function Oh(t,e,n){return new hn(t,va(e,{pinned:!!n.pinnedEnv,userConfigDir:n.pinnedEnv?n.pinnedEnv.CLAUDE_CONFIG_DIR:n.configDir}))}var Kr=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=Ra(e.options),this.onSelfClose=n.onSelfClose,this.onEvict=n.onEvict,this.onRateLimit=n.onRateLimit,this.turns=new mn(this,Oh(this.modelName,e.options.cwd,e.options)),this.spawnProcess()}get captureTranscriptLogs(){return this.options.captureTranscriptLogs!==!1}get connection(){return this.options.connection}handleProcessClose(e){gn.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,pn(this.sessionId),this.turns.abortTurnOnProcessClose(e,this.stderr),this.turns.notifyBgInterrupted(!0),this.onSelfClose?.(this.sessionKey,this)}validateSupplementalMcpConfig(){let e=this.options.supplementalMcpConfigPath,n=this.compatibility.supplementalMcpConfigIdentity;!e||!n||Rr(e,n)}attachSpawnedProcess(e){this.proc=e.process,this.supervision=e.supervision,this.stderr="",this.rl=Ch({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,i=Mr(e,this.sessionId);this.needsResume&&Xu(i,this.sessionId);let{args:s,env:o}=$u({channel:this.channel,sessionId:this.sessionId,needsResume:this.needsResume,options:this.options}),u=this.needsResume?zu(i,this.sessionId):0;this.turns.resetCostBaseline(u),gn.info(`Spawning persistent process: ${this.sessionId.substring(0,8)} ${this.needsResume?`(resume, restored cost $${u.toFixed(2)})`:"(new)"}`);let a=Rh(n,s,{cwd:e,env:o},r);this.attachSpawnedProcess(a),this.armProcessTimers()}writeTurnStdin(e){let n=JSON.stringify({type:"user",message:{role:"user",content:e},session_id:this.sessionId})+`
56
+ `;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(()=>{gn.info(`Session ${this.sessionId.substring(0,8)} turn idle for 60min, killing`),this.kill(new Error("Claude turn idle for 60min"))},Gi)}async sendMessage(e,n){this.alive||(this.needsResume=!0,this.spawnProcess()),this.resetIdleTimer();let r=me(e,n.attachments??[]),i=this.turns.createTurnStreams(e),s=new Promise((u,a)=>{this.turns.registerTurn(u,a,i,n)});this.writeTurnStdin(r),this.startTurnIdleTimer();let o=await s;return this.turns.currentTurn||this.clearTurnIdleTimer(),this.resetIdleTimer(),o}async compact(){let e=!1,n=null,r=await this.sendMessage("/compact",{onCompact:i=>{e=!0,n=typeof i.preTokens=="number"?i.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(()=>{gn.info(`Session ${this.sessionId.substring(0,8)} idle for 65min, closing`),this.close()},Qi)}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(e){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(e),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 Mh(t,e,n,r=Ci){return Wu(t,Mr(r,e),n)}function Ca(t,e=!1){let n=Mh(t.needsResume,t.sessionId,void 0,t.options.cwd);if(e&&!n)throw Object.assign(new Error(`Pinned backend resume target is unavailable: ${t.sessionId}`),{code:"PINNED_BACKEND_UNAVAILABLE"});return{...t,needsResume:n}}var yn=class{backend="claude";capabilities=we.claude;onRateLimit;quotaStopMessage;constructor(e={}){this.onRateLimit=e.onRateLimit,this.quotaStopMessage=e.quotaStopMessage}open(e,n={}){let r=new Kr(Ca(Or(e),e.resume.requireExisting),{onSelfClose:n.onSelfClose,onEvict:n.onEvict,onRateLimit:this.onRateLimit});return new ln(r,e,Aa(e),this.quotaStopMessage)}specIdentity(e){return Aa(e)}claudeResumeTarget(e){let{needsResume:n,sessionId:r}=Ca(Or(e),e.resume.requireExisting);return{needsResume:n,sessionId:r}}};import{existsSync as Ag,mkdirSync as Cg}from"fs";import{readdirSync as Uh}from"fs";import*as La from"path";var Pa="[A-Za-z0-9-]+",Lh="\\d{4}-\\d{2}-\\d{2}T\\d{2}(?:[-:]\\d{2}){2}(?:-\\d{3})?Z",Dh=/^(?<primary>.+)\.turn-(?<turn>\d+)\.bak$/,Nh=new RegExp(`^(?<sessionId>${Pa})\\.jsonl$`),jh=new RegExp(`^(?<timestamp>${Lh})_(?<sessionId>${Pa})\\.jsonl$`);function Oa(t){let e=t.match(Dh);if(e?.groups){let i=Number(e.groups.turn),s=Oa(e.groups.primary);return!s||!Number.isSafeInteger(i)||i<0||s.backupTurn!==null?null:{...s,backupTurn:i}}let n=t.match(jh);if(n?.groups?.sessionId&&n.groups.timestamp)return{sessionId:n.groups.sessionId,primaryFilename:t,timestampPrefix:n.groups.timestamp,backupTurn:null};let r=t.match(Nh);return r?.groups?.sessionId?{sessionId:r.groups.sessionId,primaryFilename:t,timestampPrefix:null,backupTurn:null}:null}function Ma(t,e){let n=null;for(let r of t){let i=Oa(r);if(!(!i||i.backupTurn!==null||i.sessionId!==e)){if(i.timestampPrefix===null)return r;(n===null||i.primaryFilename>n)&&(n=i.primaryFilename)}}return n}function Da(t,e){if(!e)return null;try{let n=Ma(Uh(t),e);return n?La.join(t,n):null}catch{return null}}var $h={"openai-codex":"OpenAI Codex"};function qr(t){let e=t.provider||"pi",n=t.connection||e;return{provider:e,displayName:$h[e]??e,mode:n}}function Bh(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",...e.mode&&e.mode!==e.provider?{route:e.mode}:{}}}function Fh(t,e){return t.status===429&&e.utilization>=1}async function Wh(t,e,n){for(let r of t.windows)await n({...Fh(t,r)?{status:"rejected"}:{},rateLimitType:r.type,...r.label?{rateLimitLabel:r.label}:{},utilization:r.utilization,resetsAt:r.resetsAt},e)}async function Na(t,e,n){let r=n.usageStore.update(Bh(t,e,(n.now??Date.now)())).then(()=>null,o=>({error:o})),i;try{await Wh(t,e,n.submit)}catch(o){i=o}let s=await r;if(i!==void 0)throw i;if(s)throw s.error}import*as Fa from"node:path";var Sn=class{lastType=null;running=new Map;observe(e){this.lastType=e.type;let n=typeof e.toolCallId=="string"?e.toolCallId:null;n!==null&&(e.type==="tool_execution_start"?this.running.set(n,String(e.toolName??"unknown")):e.type==="tool_execution_end"&&this.running.delete(n))}reset(){this.lastType=null,this.running.clear()}runningTools(){return[...this.running.values()]}describe(){let e=this.lastType===null?"no events":`last event ${this.lastType}`,n=this.running.size,r=n===0?"no tool running":`${n} tool${n===1?"":"s"} running`;return`${e}, ${r}`}};var ja=p("pi-adapter"),Ua=3900*1e3,$a=3600*1e3,Ba=2e3;function Hr(t){return me(t.text,t.attachments??[])}var bn=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})}}},kn=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){ja.warn(`PI injection delivery sink failed: ${r.message}`)}}notifyUndelivered(e){try{this.sink?.onUndelivered?.({text:e.text})}catch(n){ja.warn(`PI injection undelivered sink failed: ${n.message}`)}}};var se=p("pi-adapter"),zh=/usage[ _]limit|usage_not_included/i;function ge(t){return t instanceof Error?t:new Error(String(t))}function ye(t){return typeof t=="number"&&Number.isFinite(t)?t:null}function Qr(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Kh(t){let e=Qr(t);return Object.keys(e).length===0?null:{inputTokens:ye(e.input)??0,outputTokens:ye(e.output)??0,cacheReadTokens:ye(e.cacheRead)??0,cacheWriteTokens:ye(e.cacheWrite)??0,costUsd:ye(Qr(e.cost).total)}}function qh(t){return/nothing to compact|no messages to compact/i.test(t)}function Hh(t){return Qr(t).role==="user"}function Wa(t){return{[Symbol.asyncIterator]:()=>({next:()=>t.next()})}}var Tn=class{sessionKey;sessionId=null;sessionFile=null;currentSessionId=null;ready;handle=null;turnStream=null;parserState=Rs();request;registry;onClose;onProviderQuota;quotaStop;quotaLimited;subagent;openBundledMcpServer;getSubagentModelEnv;alive=!0;textBuffer="";textBlockId=null;idleTimer=null;turnIdleTimer=null;turnActivity=new Sn;pendingTurn=null;steering=new kn;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.quotaStop=e.quotaStop,this.quotaLimited=e.quotaLimited,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),...this.quotaStop?{quotaStop:()=>this.quotaStopReason(),onQuotaStop:r=>this.noteQuotaStop(r)}:{}},{subagent:this.subagent,openBundledMcpServer:this.openBundledMcpServer,getSubagentModelEnv:this.getSubagentModelEnv})}catch(r){let i=ge(r);throw this.fail(i),i}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??Fa.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(()=>{se.info(`Session ${this.sessionKey} idle for 65min, closing`),this.close(),this.onClose?.(this.sessionKey,this)},Ua),this.idleTimer.unref?.()}startTurnIdleTimer(){this.turnIdleTimer=setTimeout(()=>{let e=this.turnActivity.describe();se.info(`Session ${this.sessionKey} turn idle for 60min (${e}; tools: ${this.turnActivity.runningTools().join(", ")||"none"}), killing`),this.kill(new Error(`PI turn idle for 60min (${e})`)),this.onClose?.(this.sessionKey,this)},$a),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:ye(n.tokensBefore),estimatedTokensAfter:ye(n.estimatedTokensAfter),usage:Kh(n.usage),contextUsage:this.currentContextUsage()}}catch(n){let r=ge(n);if(qh(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 Ms(e.getSessionStats(),g().maxContextTokens)}catch(n){return se.warn(`PI session ${this.sessionKey}: session stats unavailable: ${ge(n).message}`),null}}isAlive(){return this.alive}openTurnStream(){this.closeTurnStream();let e=new bn;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.turnActivity.observe(e),this.observeLoop(e);let n=Os(e,this.handle?.session.model);for(let r of Ps(n,this.parserState)){let i=this.processPendingTurnEvent(r);i!==null&&this.emitWithContext(i)}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<Ba)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"||!Hh(e.message))return;let n=this.pendingTurn;n?.promptDispatched&&(n.openingUserSeen?this.steering.consumeNext(this.leafPosition()):this.noteOpeningInput(n))}noteOpeningInput(e){e.openingUserSeen=!0;let n=this.leafPosition();e.onInputConsumed?.({type:"input_consumed",...this.currentSessionId?{backendSessionId:this.currentSessionId}:{},...n?{position:n}:{}})}leafPosition(){let e=this.handle?.session.sessionManager?.getLeafId();return e?{after:e}:void 0}quotaStopReason(){return!this.pendingTurn||!this.quotaStop?null:this.quotaStop([this.request.env.CORTEX_SESSION_ID,this.currentSessionId??this.sessionId])}noteQuotaStop(e){this.pendingTurn&&(this.pendingTurn.quotaStop=e)}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&&!this.quotaRefused(e)?n.reject(Object.assign(new Error(e),{reason:"provider_error"})):n.resolve(this.buildAgentResult(n,e)),r}quotaRefused(e){return zh.test(e)&&this.quotaLimited?.()===!0}buildAgentResult(e,n){let r=n??e.quotaStop;return{sessionId:this.sessionId,total_cost_usd:e.totalCostUsd,num_turns:e.numTurns,rateLimited:r!==null,rateLimitMessage:r,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){g().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(ge(r)))}promptFailed(e){if(se.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),i=Hr(e),s=this.loopState==="starting"?n.session.steer(i):n.session.prompt(i,{streamingBehavior:"steer"});return this.loopState==="idle"&&(this.loopState="starting"),s.catch(o=>{let u=`injection refused: ${ge(o).message}`;se.warn(`PI session ${this.sessionKey}: ${u}`),this.turnStream?.push({type:"error",message:u,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 se.warn(`PI session ${this.sessionKey}: switch to ${e} failed: ${ge(r).message}`),{ok:!1,cancelled:!1}}}async sendTurn(e,n,r){let i=await this.liveHandle(),s=Hr(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(i,s)}sendExtensionUiResponse(e,n){return this.alive?this.handle?.respondToUi(e,n)?!0:(se.debug(`PI session ${this.sessionKey}: no dialog waits on ui request ${e}`),!1):!1}beginTurn(e,n,r){this.beginTurnReject(new Error("PISession.beginTurn: superseded by a newer send()")),this.parserState.turnProgressCount=0,this.turnActivity.reset(),this.pendingTurn={resolve:e,reject:n,planFilePath:null,numTurns:0,totalCostUsd:null,promptDispatched:!1,openingUserSeen:!1,onInputConsumed:r,deferredCompletion:!1,lastAssistantText:null,quotaStop: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){se.warn(`PI session ${this.sessionKey}: dispose failed: ${ge(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 Qh(t){return t instanceof Error?t:new Error(String(t))}var _n=class{backend="pi";identity;session;onEvict;resolveSessionPath;injections;constructor(e,n,r={}){this.session=e,this.identity=Lt(n),this.onEvict=r.onEvict,this.resolveSessionPath=r.resolveSessionPath,this.injections=new Me(e,"pi-run-inj")}get backendSessionId(){return this.session.sessionId}run(e,n){let r=this.session.openTurnStream(),i=new De,s=this.injections.beginRun(i),o=this.sendTurn(e,h=>i.push(h));o.catch(()=>{});let u=Le(),a=Le(),l=new Ce(n.awaitBackground,{push:h=>i.push(h),settleForeground:h=>u.resolve(h),settleRun:h=>{a.resolve(h),u.resolve(h)},close:()=>i.close()});s.attachPhase(l),u.promise.catch(h=>a.reject(h)),a.promise.catch(()=>{});let c=!1,d=[],m=h=>{c?h():d.push(h)},v=()=>{c=!0;let h=d;d=[];for(let N of h)N()},E=!1;return o.then(h=>{E=!0,m(()=>{i.push({type:"foreground_result",result:h}),l.start(h)})},h=>{E=!0,m(()=>{i.push({type:"phase",phase:"done",pendingBackground:0,undeliveredBackground:0}),i.close()}),u.reject(h)}),(async()=>{for await(let h of Wa(r))n.onNormalizedEvent?.(h),h.type!=="turn_complete"&&i.push(lt(h,"foreground"));v(),await Promise.resolve(),E||(i.push({type:"phase",phase:"done",pendingBackground:0,undeliveredBackground:0}),i.close())})(),u.promise.catch(()=>{}),{events:{[Symbol.asyncIterator]:()=>({next:()=>i.next()})},result:u.promise,settled:a.promise,cancel:()=>{this.session.closeTurnStreamFor(r)}}}sendTurn(e,n){return new Promise((r,i)=>{this.session.beginTurn(r,i,n),this.session.sendTurn(this.session.sessionId,this.turnPath(),e).catch(s=>this.session.beginTurnReject(Qh(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 il from"node:path";import{randomUUID as za}from"node:crypto";function Ka(t){return t.cancelled===!0}function Gr(t){if(Ka(t))return;let e=t.value;return typeof e=="string"?e:void 0}function qa(t,e){let n=new Map;function r(o,u,a,l){if(l?.signal?.aborted)return Promise.resolve(u);let c=za();return new Promise(d=>{let m,v=()=>{E(),d(u)},E=()=>{m&&clearTimeout(m),l?.signal?.removeEventListener("abort",v),n.delete(c)};l?.signal?.addEventListener("abort",v,{once:!0}),l?.timeout&&(m=setTimeout(()=>{E(),d(u)},l.timeout),m.unref?.()),n.set(c,{resolve:h=>{E(),d(a(h))},cleanup:E}),t({type:"extension_ui_request",id:c,...o})})}function i(o,u){t({type:"extension_ui_request",id:za(),method:o,...u})}return{ui:{select:(o,u,a)=>r({method:"select",title:o,options:u,timeout:a?.timeout},void 0,Gr,a),confirm:(o,u,a)=>r({method:"confirm",title:o,message:u,timeout:a?.timeout},!1,l=>!Ka(l)&&l.confirmed===!0,a),input:(o,u,a)=>r({method:"input",title:o,placeholder:u,timeout:a?.timeout},void 0,Gr,a),editor:(o,u)=>r({method:"editor",title:o,prefill:u},void 0,Gr),notify:(o,u)=>i("notify",{message:o,notifyType:u}),setStatus:(o,u)=>i("setStatus",{statusKey:o,statusText:u}),setWidget:(o,u,a)=>{(u===void 0||Array.isArray(u))&&i("setWidget",{widgetKey:o,widgetLines:u,widgetPlacement:a?.placement})},setTitle:o=>i("setTitle",{title:o}),setEditorText:o=>i("set_editor_text",{text:o}),pasteToEditor:o=>i("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,u){let a=n.get(o);return a?(a.resolve(u),!0):!1},cancelAll(){for(let o of[...n.values()])o.resolve({cancelled:!0})}}}import{spawn as Gh}from"node:child_process";import{readFileSync as Vh}from"node:fs";import*as Va from"node:path";import{pathToFileURL as Jh}from"node:url";var Ja=p("hook-bridge"),Xh={"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"},Vr={"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 Xa(t){return(t.startsWith("mcp__")?null:Tt("claude",t))??t.charAt(0).toUpperCase()+t.slice(1)}function Yh(t,e){return(t==="read"||t==="write"||t==="edit")&&typeof e.path=="string"?{...e,file_path:e.path}:{...e}}function Jr(t,e){let n=t.sessionManager?.getSessionFile();return n?Va.basename(n,".jsonl"):e.CORTEX_SESSION_ID??"unknown"}function Zh(t){return Array.isArray(t)?t.filter(e=>typeof e=="object"&&e!==null&&e.type==="text").map(e=>e.text).join(""):""}function Ya(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 eg(t){if(t?.trim())try{return JSON.parse(t.trim())}catch{return}}function tg(t,e){if(t===0)return null;let n=e?.trim()?`: ${e.trim()}`:"";return new Error(`exited with code ${t}${n}`)}function Ha(t,e,n,r,i){return new Promise((s,o)=>{let u=Gh(t,e,{env:Ya(i,String(n.session_id??"unknown")),stdio:["pipe","pipe","pipe"]}),a="",l="",c=!1,d=setTimeout(()=>{c=!0,u.kill("SIGKILL")},r);u.stdout.setEncoding("utf8").on("data",m=>{a+=m}),u.stderr.setEncoding("utf8").on("data",m=>{l+=m}),u.on("error",m=>{clearTimeout(d),o(m)}),u.on("close",m=>{if(clearTimeout(d),c){o(new Error(`timed out after ${r}ms`));return}let v=tg(m,l);v?o(v):s(eg(a))}),u.stdin.on("error",()=>{}),u.stdin.end(JSON.stringify(n))})}var Qa=new Map,ng=/export\s+(?:async\s+)?function\s+runHook\b|export\s*\{[^}]*\brunHook\b/;function rg(t){try{return ng.test(Vh(t,"utf8"))}catch{return!1}}async function ig(t){let e=Ui(t).path,n=Qa.get(e);if(n!==void 0)return n;let r=null;if(rg(e))try{let i=await import(Jh(e).href);typeof i.runHook=="function"&&(r=i.runHook)}catch(i){Ja.warn(`in-process load of ${t} failed; using the spawned form: ${i.message}`)}return Qa.set(e,r),r}function sg(t,e,n){return t instanceof Promise?Promise.race([t,new Promise((r,i)=>{setTimeout(()=>i(new Error(`${n} timed out after ${e}ms`)),e).unref?.()})]):Promise.resolve(t)}function Xr(t){return typeof t!="object"||t===null||Array.isArray(t)?{}:t}async function mt(t,e,n){let r=(t.run.timeout??30)*1e3;try{if(t.run.script){let i=await ig(t.run.script);if(i){let s=Ya(n,String(e.session_id??"unknown"));return await sg(i(e,s),r,t.id)}return await Ha(process.execPath,$i(t.run.script),e,r,n)}return await Ha("sh",["-c",t.run.command],e,r,n)}catch(i){Ja.error(`${t.id} error:`,i);return}}function Yr(t,e){if(typeof t.matcher!="string")return!0;let n=e.startsWith("mcp__")?e:Xa(e),r=t.event.startsWith("agent:")?n:e;return new RegExp(t.matcher).test(r)}function og(t){return t.event.startsWith("pi:")?t.event.slice(3):t.event.startsWith("agent:")?Xh[t.event]:null}function Za(t,e,n,r){let i={hook_event_name:t,session_id:Jr(n,r),tool_name:Xa(e.toolName),tool_input:Yh(e.toolName,e.input),tool_use_id:e.toolCallId,cwd:n.cwd};return"content"in e&&ug(i,e),i}function ug(t,e){t.tool_output=Zh(e.content),t.tool_response=e.details??null,t.is_error=e.isError}function el(t,e,n,r){return{...typeof e=="object"&&e!==null?e:{event:e},hook_event_name:Vr[t.event],session_id:Jr(n,r),tool_name:"",tool_input:{},tool_use_id:"",cwd:n.cwd}}function ag(t,e,n,r){return{...typeof e=="object"&&e!==null?e:{event:e},hook_event_name:t,session_id:Jr(n,r),cwd:n.cwd}}function lg(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 cg(t){let e=t.hookSpecificOutput;if(e?.permissionDecision==="deny")return{block:!0,reason:e.permissionDecisionReason??"Blocked by hook registry"}}async function dg(t,e,n,r){for(let i of n){if(!Yr(i,t.toolName))continue;let s=Za(Vr[i.event],t,e,r),o=Xr(await mt(i,s,r));lg(t,o.hookSpecificOutput);let u=cg(o);if(u)return u}}function pg(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 fg(t,e,n,r){let i=!1;for(let s of n){if(!Yr(s,t.toolName))continue;let o=Za(Vr[s.event],t,e,r),u=Xr(await mt(s,o,r));i=pg(t,u.hookSpecificOutput?.additionalContext)||i}return i?{content:t.content}:void 0}async function mg(t,e,n,r){let i=t.systemPrompt??"",s=!1;for(let o of n){let u={...t,systemPrompt:i},l=Xr(await mt(o,el(o,u,e,r),r)).hookSpecificOutput?.additionalContext;l&&(i+=`
57
+
58
+ ${l}`,s=!0)}if(s)return{systemPrompt:i}}async function hg(t,e,n,r){for(let i of n)await mt(i,el(i,t,e,r),r)}function gg(t,e,n,r,i){let s=[e];return t==="tool_call"?dg(n,r,s,i):t==="tool_result"?fg(n,r,s,i):t==="before_agent_start"?mg(n,r,s,i):hg(n,r,s,i)}function Ue(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ga(t,e){for(let n of Object.keys(t))delete t[n];Object.assign(t,e)}function yg(t,e,n){if(!Ue(e)||!Ue(n))return n;if(t==="before_provider_headers"){Ue(e.headers)&&Ue(n.headers)&&Ga(e.headers,n.headers);return}if(t!=="tool_call"||!Ue(e.input)||!Ue(n.input))return n;Ga(e.input,n.input);let r={...n};return delete r.input,Object.keys(r).length>0?r:void 0}async function Sg(t,e,n,r,i){let s=t==="tool_call"||t==="tool_result",o=n?.toolName;if(s&&(typeof o!="string"||!Yr(e,o)))return;let u=await mt(e,ag(t,n,r,i),i);return yg(t,n,u)}function bg(t,e,n,r,i){return e.event.startsWith("pi:")?Sg(t,e,n,r,i):gg(t,e,n,r,i)}function tl(t,e){let n=ks(bs(),{backend:"pi"});for(let r of n){let i=og(r);i&&t.on(i,(s,o)=>bg(i,r,s,o,e))}}function kg(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 nl(t,e={}){let n=t.reportsProviderQuota?e.onProviderQuota:void 0,r=kg(t.env,e.getSubagentModelEnv),i=[{name:"cortex-image-first",factory:Ws},{name:"cortex-mcp-bridge",factory:s=>$s(s,Us(r,t.pluginMcpServers,e.openBundledMcpServer))},{name:"cortex-tool-shims",factory:s=>Hs(s,r,{onSubagentEvent:e.onSubagentEvent,onSubagentUsage:e.onSubagentUsage,onProviderQuota:n,quotaStop:e.quotaStop,runForeignSubagent:e.subagent?.runForeignSubagent,startBackgroundSubagent:e.subagent?.startBackgroundSubagent,stopBackgroundSubagent:e.subagent?.stopBackgroundSubagent,checkDelegatedModel:e.subagent?.checkDelegatedModel,sessionAllowedPaths:e.subagent?.sessionAllowedPaths,openBundledMcpServer:e.openBundledMcpServer})},{name:"cortex-described-bash",factory:s=>qs(s,Ks(t.env))}];return t.disableHooks||i.push({name:"cortex-hook-bridge",factory:s=>tl(s,t.env)}),n&&i.push({name:"cortex-quota-probe",factory:Bs(n)}),e.quotaStop&&i.push({name:"cortex-quota-stop",factory:Fs(e.quotaStop,e.onQuotaStop)}),i}var $e=p("pi-runtime"),Tg=new Set(["off","minimal","low","medium","high","xhigh","max"]),rl=Symbol.for("@earendil-works/pi-coding-agent:theme");function _g(t){let e=globalThis;return e[rl]||t.initTheme("dark",!1),e[rl]}function vg(t){if(t.thinking){if(Tg.has(t.thinking))return t.thinking;$e.warn(`Ignoring unknown PI thinking level '${t.thinking}' for session ${t.sessionKey}`)}}function wg(t,e){return e.sessionPath?t.SessionManager.open(e.sessionPath,e.sessionDir):t.SessionManager.create(e.cwd,e.sessionDir)}function xg(t,e,n){let r=vg(e);if(!e.model)return{model:void 0,thinking:r};let i=t.resolveCliModel({cliProvider:e.provider??void 0,cliModel:e.model,cliThinking:r,modelRuntime:n});if(i.error)throw new Error(i.error);return i.warning&&$e.warn(`PI model resolution for ${e.sessionKey}: ${i.warning}`),{model:i.model&&e.benchmarkMaxOutputTokens!==void 0?{...i.model,maxTokens:e.benchmarkMaxOutputTokens}:i.model,thinking:r??i.thinkingLevel}}async function Eg(t,e,n,r,i){Ki(g().piCompactReserveTokens,{agentDir:i});let s=Ds(t,r,i),o=await t.ModelRuntime.create({authPath:At(i),modelsPath:il.join(i,"models.json"),allowModelNetwork:!1});return await hs(o,i),t.createAgentSessionServices({cwd:r,agentDir:i,settingsManager:s,modelRuntime:o,resourceLoaderOptions:{additionalSkillPaths:e.skillPaths,extensionFactories:n,systemPrompt:e.systemPrompt??void 0,appendSystemPrompt:e.appendSystemPrompt,noContextFiles:e.noContextFiles}})}function Ig(t,e,n){return async({cwd:r,agentDir:i,sessionManager:s,sessionStartEvent:o})=>{let u=await Eg(t,e,n,r,i),a=[...u.diagnostics,...u.resourceLoader.getExtensions().errors.map(({path:m,error:v})=>({type:"error",message:`Failed to load extension "${m}": ${v}`}))],{model:l,thinking:c}=xg(t,e,u.modelRuntime);return{...await t.createAgentSessionFromServices({services:u,sessionManager:s,sessionStartEvent:o,model:l,thinkingLevel:c}),services:u,diagnostics:a}}}async function sl(t,e,n={}){let r=await Bi(),i=qa(d=>e.onEvent(d),_g(r)),s=nl(t,{subagent:n.subagent,openBundledMcpServer:n.openBundledMcpServer,getSubagentModelEnv:n.getSubagentModelEnv,onProviderQuota:e.onProviderQuota,quotaStop:e.quotaStop?()=>e.quotaStop():void 0,onQuotaStop:d=>e.onQuotaStop?.(d),onSubagentEvent:d=>e.onEvent({type:"cortex_subagent_event",notice:d}),onSubagentUsage:d=>e.onEvent({type:"cortex_subagent_usage",report:d})}),o=wg(r,t),u=await r.createAgentSessionRuntime(Ig(r,t,s),{cwd:o.getCwd(),agentDir:t.agentDir,sessionManager:o});for(let d of u.diagnostics){let m=`PI session ${t.sessionKey}: ${d.message}`;d.type==="error"?$e.error(m):d.type==="warning"?$e.warn(m):$e.info(m)}u.modelFallbackMessage&&$e.warn(`PI session ${t.sessionKey}: ${u.modelFallbackMessage}`);let a,l=async()=>{let d=u.session;await d.bindExtensions({uiContext:i.ui,mode:"rpc",onError:m=>e.onEvent({type:"extension_error",extensionPath:m.extensionPath,event:m.event,error:m.error})}),a?.(),a=d.subscribe(m=>e.onEvent(m))};u.setRebindSession(l),await l();let c=!1;return{get session(){return u.session},respondToUi:(d,m)=>i.respond(d,m),switchSession:d=>u.switchSession(d),async dispose(){c||(c=!0,a?.(),i.cancelAll(),await u.dispose())}}}var Zr=p("pi-adapter");function Rg(t){return{provider:Mt,displayName:"OpenAI Codex",modes:[t],windows:[],observedAt:null,freshness:"never"}}function Pg(t){return{...t,modes:[...t.modes],windows:t.windows.map(e=>({...e})),...t.spend?{spend:{...t.spend}}:{},freshness:"stale"}}var vn=class{backend="pi";capabilities=we.pi;poolLookup=null;runtimeFactory;sessionPathRegistry=new Map;configuredAgentDir;catalog;usageStore;submitRateLimit;quotaStop;quotaLimited;subagent;openBundledMcpServer;getSubagentModelEnv;sessionDir;constructor(e=sl,n=It,r={}){this.runtimeFactory=e,this.sessionDir=n,this.configuredAgentDir=r.agentDir,this.catalog=r.catalog,this.usageStore=r.usageStore,this.submitRateLimit=r.submitRateLimit,this.quotaStop=r.quotaStop,this.quotaLimited=r.quotaLimited,this.subagent=r.subagent,this.openBundledMcpServer=r.openBundledMcpServer,this.getSubagentModelEnv=r.getSubagentModelEnv}async getUsage(e){if(e.provider!==Mt||!e.mode)return null;let n=await this.usageStore?.get(Mt,"subscription")??null;return[n?Pg(n):Rg(e.mode)]}resolveSpawnSessionPath(e,n){if(!e.resume.resume||!e.resume.backendSessionId)return null;let r=this.resolveSessionPath(e.resume.backendSessionId);if(r===null&&e.resume.requireExisting)throw Object.assign(new Error(`Pinned backend resume target is unavailable: ${e.resume.backendSessionId}`),{code:"PINNED_BACKEND_UNAVAILABLE"});return r===null&&Zr.info(`PI resume target '${e.resume.backendSessionId}' not found (no live session or file in ${n}); starting fresh`),r}writeCatalog(e){if(this.catalog)try{ms(this.catalog(e),{agentDir:e,oauthProviders:fs(At(e))})}catch(n){Zr.warn(`Failed to write PI models.json: ${n.message}`)}}syncAgentDir(e){this.writeCatalog(e)}get agentDir(){return this.configuredAgentDir??Et}agentDirFor(e){return e.route.piAgentDir??this.agentDir}ensureCatalog(e=this.agentDir){this.syncAgentDir(e)}scanModels(e=this.agentDir){return this.ensureCatalog(e),gs(e)}buildRequest(e,n){return Ls(e,{agentDir:this.agentDirFor(e),homeAgentDir:this.agentDir,sessionDir:this.sessionDir,sessionPath:n,cwd:ne(e.cwd),streamDeltas:e.flags.streamDeltas??g().streamDeltas})}specIdentity(e){return Lt(this.buildRequest(e,null))}prepareRequest(e){let n=this.agentDirFor(e);Cg(this.sessionDir,{recursive:!0});let r=this.resolveSpawnSessionPath(e,this.sessionDir);return this.syncAgentDir(n),this.buildRequest(e,r)}quotaReporter(e){let n=this.usageStore,r=this.submitRateLimit;if(!(!n||!r))return i=>{Na(i,qr({provider:e.model.provider,connection:e.route.connection}),{usageStore:n,submit:r}).catch(s=>Zr.error("reportCodexQuota error:",s))}}quotaAccount(e){let n=qr({provider:e.model.provider,connection:e.route.connection});return{provider:n.provider,route:n.mode??n.provider}}quotaStopCheck(e){let n=this.quotaStop;if(!n)return;let{provider:r,route:i}=this.quotaAccount(e);return s=>n(r,i,s)}quotaLimitedCheck(e){let n=this.quotaLimited;if(!n)return;let{provider:r,route:i}=this.quotaAccount(e);return()=>n(r,i)}open(e,n={}){let r=this.prepareRequest(e),i=new Tn({request:r,runtimeFactory:this.runtimeFactory,registry:this.sessionPathRegistry,onClose:n.onSelfClose,onProviderQuota:this.quotaReporter(e),quotaStop:this.quotaStopCheck(e),quotaLimited:this.quotaLimitedCheck(e),subagent:this.subagent,openBundledMcpServer:this.openBundledMcpServer,getSubagentModelEnv:this.getSubagentModelEnv});return new _n(i,r,{onEvict:n.onEvict,resolveSessionPath:s=>this.resolveSessionPath(s)})}setEnginePool(e){this.poolLookup=e}registerSessionPath(e,n){this.sessionPathRegistry.set(e,n)}resolveSessionPath(e){let n=this.sessionPathRegistry.get(e);if(n&&Ag(n))return n;n&&this.sessionPathRegistry.delete(e);let r=Da(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 i=this.resolveSessionPath(e);return i===null?{ok:!1,cancelled:!1}:r.switchSession(e,i)}};var Og=7200*1e3,Mg=3600*1e3,Lg=600*1e3,Dg=240,wn=10080*60*1e3,ol={seven_day:wn,seven_day_overage_included:wn,model_scoped:wn,codex_secondary:wn},Ng=1440*60*1e3,ei=new Map;function ul(t,e,n,r){return JSON.stringify([t,e,n,n==="model_scoped"?r??null:null])}function al(t){if(!Ve.has(t.type)||!Number.isFinite(t.utilization))return;let e=ul(t.provider,t.route,t.type,t.label),n=w(t.resetsAt),r=ei.get(e),i=r&&(n===null||r.resetsAt===n)?r:{resetsAt:n,points:[]},s=i.points.at(-1);if(s&&t.observedAt<=s.at)return;i.points.push({at:t.observedAt,utilization:t.utilization});let o=t.observedAt-Og;i.points=i.points.filter(u=>u.at>=o).slice(-Dg),ei.set(e,i)}function ll(t){for(let e of t){let n=w(e.observedAt);if(!(e.billing==="api"||e.freshness!=="live"||n===null))for(let r of e.windows)typeof r.utilization=="number"&&al({provider:e.provider,route:e.route||F(e.provider),type:r.type,...r.label?{label:r.label}:{},utilization:r.utilization,resetsAt:r.resetsAt,observedAt:n})}}function cl(t,e,n){if(!(!t||!e.mode))for(let[r,i]of Object.entries(t))typeof i?.utilization=="number"&&al({provider:e.provider,route:e.mode,type:r,utilization:i.utilization,resetsAt:i.resetsAt,observedAt:n})}function jg(t,e){let n=t.filter(a=>a.at>=e-Mg);if(n.length<2||n.at(-1).at-n[0].at<Lg)return null;let r=n.reduce((a,l)=>a+l.at,0)/n.length,i=n.reduce((a,l)=>a+l.utilization,0)/n.length,s=n.reduce((a,l)=>a+(l.at-r)*(l.utilization-i),0),o=n.reduce((a,l)=>a+(l.at-r)**2,0),u=o>0?s/o:0;return u>0?u:null}function Ug(t,e,n){if(e===null)return null;let r=n.at-(e-t);return r<Ng||r>t?null:n.utilization>0?n.utilization/r:null}function vE(t,e,n,r,i,s=Date.now()){let o=ei.get(ul(t,e,n,r)),u=o?.points.at(-1);if(!o||!u)return null;let a=Object.hasOwn(ol,n)?ol[n]:null,l=a===null?"hour":"period",c=a===null?jg(o.points,s):Ug(a,o.resetsAt,u);if(c===null)return null;let d=c*36e5;if(u.utilization>=i)return{at:null,ratePerHour:d,basis:l};let m=u.at+(i-u.utilization)/c;return{at:o.resetsAt===null||m<o.resetsAt?Math.round(m/1e3):null,ratePerHour:d,basis:l}}import pl from"node:fs/promises";import fl from"node:path";var xn=p("usage-window-history"),ml=1,$g=2160*60*60*1e3,Bg=300*1e3,Fg=3e4,Wg=/^(five_hour|seven_day.*|codex_.+)$/;function zg(t){if(t.billing!=="subscription"||t.observedAt===null)return[];let e=t.observedAt*1e3;return t.windows.filter(n=>n.utilization!==null&&n.resetsAt!==null&&Wg.test(n.type)).map(n=>({provider:t.provider,route:t.route??null,windowType:n.type,...n.label?{label:n.label}:{},utilization:n.utilization,resetsAt:n.resetsAt*1e3,observedAt:e}))}function Kg(t){return t.flatMap(zg)}function qg(t,e){return t.provider===e.provider&&t.route===e.route&&t.windowType===e.windowType&&Math.abs(t.resetsAt-e.resetsAt)<=Bg}function Hg(t){return{provider:t.provider,route:t.route,windowType:t.windowType,...t.label?{label:t.label}:{},resetsAt:t.resetsAt,peakUtilization:t.utilization,firstObservedAt:t.observedAt,lastObservedAt:t.observedAt,horizonMs:Math.max(0,t.resetsAt-t.observedAt)}}function Qg(t,e){let n=t.find(s=>qg(s,e));if(!n)return t.push(Hg(e)),!0;let r={...n};e.observedAt>=n.lastObservedAt&&(r.lastObservedAt=e.observedAt,r.resetsAt=e.resetsAt),r.firstObservedAt=Math.min(n.firstObservedAt,e.observedAt),r.peakUtilization=Math.max(n.peakUtilization,e.utilization),r.horizonMs=Math.max(n.horizonMs,e.resetsAt-e.observedAt);let i=Object.keys(r).some(s=>r[s]!==n[s]);return Object.assign(n,r),i}function dl(t,e){return t.filter(n=>n.resetsAt>=e-$g)}async function Gg(t){try{let e=JSON.parse(await pl.readFile(t,"utf8"));return e.version===ml&&Array.isArray(e.records)?e.records:[]}catch(e){return e.code!=="ENOENT"&&xn.warn(`usage window history unreadable, starting over: ${String(e)}`),[]}}var ti=class{opts;records=null;loading=null;chain=Promise.resolve();timer=null;dirty=!1;now;constructor(e){this.opts=e,this.now=e.now??Date.now}observe(e){let n;try{n=Kg(e)}catch(r){xn.warn(`usage window observation skipped: ${String(r)}`);return}n.length!==0&&(this.chain=this.chain.then(async()=>this.apply(n)).catch(r=>xn.warn(`usage window history update failed: ${String(r)}`)))}async list(){return await this.chain,dl(await this.load(),this.now()).map(e=>({...e}))}async flush(){await this.chain,this.timer&&clearTimeout(this.timer),this.timer=null,await this.persist()}async load(){return this.loading??=Gg(this.opts.filePath).then(e=>{this.records=e}),await this.loading,this.records}async apply(e){let n=await this.load(),r=!1;for(let i of e)Qg(n,i)&&(r=!0);r&&(this.dirty=!0,this.schedule())}schedule(){this.timer||(this.timer=setTimeout(()=>{this.timer=null,this.chain=this.chain.then(()=>this.persist())},this.opts.writeDelayMs??Fg),this.timer.unref?.())}async persist(){if(!(!this.dirty||!this.records)){this.dirty=!1,this.records=dl(this.records,this.now());try{await pl.mkdir(fl.dirname(this.opts.filePath),{recursive:!0}),await q(this.opts.filePath,JSON.stringify({version:ml,records:this.records}))}catch(e){xn.warn(`usage window history write failed: ${String(e)}`)}}}},Vg=fl.join(ke,"usage-windows.json"),ni=new ti({filePath:Vg});_t(ni);function UE(t,e){return t?.cooldownUntil!==void 0&&t.cooldownUntil>e}function $E(t){return t.credits.find(e=>e.id===t.nextCreditId)??t.credits[0]??null}function Z(t){if(!t.billing)return t.provider;let e=`${t.provider}::${t.billing}`;return t.route?`${e}::${t.route}`:e}function Jg(t){return{...t,modes:[...t.modes],windows:t.windows.map(e=>({...e})),...t.spend?{spend:{...t.spend}}:{},...t.resetCredits?{resetCredits:gl(t.resetCredits)}:{}}}function gl(t){return{...t,credits:t.credits.map(e=>({...e,...e.clears?{clears:[...e.clears]}:{}}))}}function Xg(t,e){return e.resetCredits||!t?.resetCredits?e:{...e,resetCredits:gl(t.resetCredits)}}function ht(t){let e=new Map;for(let n of t)e.set(Z(n),Jg(n));return[...e.values()].sort((n,r)=>n.provider.localeCompare(r.provider)||Z(n).localeCompare(Z(r)))}function hl(t,e){return t.observedAt===null?!0:e.observedAt===null?!1:e.observedAt>=t.observedAt}var yl={load:()=>G.getProviderUsage(),save:t=>G.setProviderUsage(t)},ri=class{persistence;observer;persistedObserver;mutationMutex=new j;constructor(e=yl,n,r){this.persistence=e,this.observer=n,this.persistedObserver=r}async list(){return ht(await this.persistence.load())}async get(e,n,r){let i=await this.list();if(n===void 0)return i.find(o=>o.provider===e)??null;let s=Z({provider:e,billing:n,route:r});return i.find(o=>Z(o)===s)??null}async update(e){this.observer?.observe([e]),await this.mutationMutex.run(async()=>{let n=ht(await this.persistence.load()),r=Z(e),i=n.findIndex(o=>Z(o)===r);if(i!==-1&&!hl(n[i],e))return;i===-1?n.push(e):n[i]=Xg(n[i],e);let s=ht(n);await this.persistence.save(s),this.persistedObserver?.observe(s)})}async commit(e){this.observer?.observe(e),await this.mutationMutex.run(async()=>{let n=new Map(ht(await this.persistence.load()).map(s=>[Z(s),s])),r=e.map(s=>{let o=n.get(Z(s));return!o||hl(o,s)?s:{...s,windows:o.windows.map(u=>({...u})),observedAt:o.observedAt,freshness:o.freshness}}),i=ht(r);await this.persistence.save(i),this.persistedObserver?.observe(i)})}},Sl=new ri(yl,ni,{observe:t=>{Eo(t),Bo(t),ll(t)}});var bl=async t=>{let{runSubagent:e}=await import("./runner-5MKMRTIN.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 Yg=p("run-adapters");function Zg(t,e){return Ae(t,e)?!0:Ro().hardBlocks.some(n=>n.provider===t&&n.route===e)}var ii=new vn(void 0,It,{agentDir:Et,catalog:t=>Qs({accountProvider:Es(t)?.provider}),usageStore:Sl,submitRateLimit:(t,e)=>(lr(t,e),nt(t,e)),quotaStop:Ho,quotaLimited:Zg,openBundledMcpServer:Ys,getSubagentModelEnv:wr,subagent:{checkDelegatedModel:Cs,runForeignSubagent:bl,startBackgroundSubagent:t=>Be.start?Be.start(t):Promise.reject(new Error("run_in_background is unavailable in this session.")),stopBackgroundSubagent:t=>Be.stop?Be.stop(t):Promise.resolve(null),sessionAllowedPaths:async t=>(await Zs.getById(t))?.allowedPaths??[]}});async function ey(){let t=re.piAccounts(),[e,...n]=await Promise.all([ii.scanModels(),...t.map(r=>ii.scanModels(ws(r.id)).catch(i=>(Yg.warn(`PI model scan of account '${r.id}' failed: ${i.message}`),[])))]);return[e,...n].flat()}ys(ey);bu(()=>{let t=Rt.peek(),e=As(),n=Pt(t,{backend:"claude",provider:null})?.models??xt;return{pi:t.routes.filter(r=>r.backend==="pi").flatMap(r=>r.models.map(i=>({provider:r.provider,id:i}))).filter(r=>e({backend:"pi",provider:r.provider,model:r.id})),claude:n.filter(r=>e({backend:"claude",model:r}))}});var Be={};function aI(t){Be.start=t?.startBackgroundSubagent,Be.stop=t?.stopBackgroundSubagent}var ty=new yn({onRateLimit:(t,e)=>(lr(t,e),cl(t.unifiedWindows,e,Date.now()),nt(t,e)),quotaStopMessage:t=>qo("anthropic",t)});function kl(){return ty}function Tl(){return ii}var ny=p("agent-adapter"),_l=p("pi-adapter");function vl(t){return t instanceof Error?t.message:String(t)}var si=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 i=e.claudeResumeTarget(n);return!i.needsResume||r.backendSessionId===i.sessionId}acquirePi(e){let n=this.pi;if(!n)throw new Error("SessionEngines has no PI engine adapter configured");let r=e.engineKey,i=this.sessions.get(r);if(i&&this.piReusable(n,e,i))return i;i&&(_l.info(`PI session ${r} retired (${i.isAlive()?"spawn config changed":"session gone"}); creating a new session`),i.close().catch(o=>_l.warn(`retiring PI session ${r} failed: ${vl(o)}`)),this.sessions.delete(r));let s;return s=n.open(e,{onSelfClose:o=>{this.sessions.get(o)===s&&this.sessions.delete(o)},onEvict:o=>{this.sessions.get(r)===o&&this.sessions.delete(r)}}),this.sessions.set(r,s),s}acquireClaude(e){let n=this.claude;if(!n)throw new Error("SessionEngines has no Claude engine adapter configured");let r=e.engineKey,i=this.sessions.get(r);if(!i||!this.claudeReusable(n,e,i)){i&&i.close(),this.sessions.delete(r);let s;s=n.open(e,{onSelfClose:o=>{this.sessions.get(o)===s&&this.sessions.delete(o)},onEvict:o=>{this.sessions.delete(o)}}),this.sessions.set(r,s),i=s}return i}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=>ny.warn(`close ${n.backend} session ${e} failed: ${vl(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)}},ry=Tl(),iy=kl(),wl=new si({pi:ry,claude:iy});function oi(){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 En(t){let e=oi();return t.replace(/\{\{(\w+)\}\}/g,(n,r)=>r in e?e[r]:n)}function xl(t,e){return t.replace(/\{\{#if (\w+)\}\}([\s\S]*?)\{\{\/if\}\}/g,(r,i,s)=>e[i]?s:"").replace(/\{\{(\w+)\}\}/g,(r,i)=>e[i]||"")}import*as El from"path";var sy=El.join(M,"rules");function Il(t=sy,e=Vs()){return Js(t,e).filter(n=>n.paths.length===0).map(n=>n.body)}import{readFileSync as oy,statSync as uy}from"fs";import*as Rl from"path";var Al=Rl.join(Pi,"user","USER.md"),In=null,Cl=0;function ay(){try{let t=uy(Al);return t.mtimeMs===Cl&&In!==null||(In=oy(Al,"utf8"),Cl=t.mtimeMs),In}catch{return null}}function Pl(){if(g().disableUserContext)return null;let t=ay();return t?`[User Context]
59
+ ${t}
60
+ [/User Context]`:null}function Ol(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(`
61
+
62
+ ---
63
+
64
+ `):void 0}function Ml(t){return t?Il():[]}function xI(t,e,n={}){let r=xl(t.promptTemplate||"{{input}}",{input:e,...oi()});return[...n.resumed?[]:ly(t,n),r].join(`
65
+
66
+ `).trim()}function ly(t,e){return[e.userContext,t.directive?En(t.directive):null,e.project?cy(e.project):null,e.transcriptDir?dy(e.transcriptDir):null,e.board?my(e.board):null,e.team?py(e.team.roster,e.team.unread):null,e.worker?fy(e.worker):null,e.authorizedPaths?zs(e.authorizedPaths):null].filter(n=>!!n)}function EI(t){return t?Pl():null}function cy(t){return`[Session Project] This session is bound to the project "${t.id}".
67
+ Project context directory: ${t.contextDir}
68
+ Treat messages in this session as pertaining to this project unless stated otherwise, and record project-related findings and status updates there.`}function dy(t){return`[Session Transcripts] The full transcript of any Cortex session is at ${t}/<sessionId>.jsonl.`}function py(t,e){let n=`[Team] You lead these workers (persistent sessions you manage with the worker_* tools):
69
+ ${t.length>0?t.join(`
70
+ `):"- (no active workers)"}
71
+ Rules:
72
+ 1. After dispatching work, end your turn. Worker reports wake you as they arrive; a worker's other replies do not, and appear under [Unread routine updates] on your next turn. Never poll or wait.
73
+ 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.
74
+ 3. Workers bring questions and plans needing approval in their reports: answer or approve them yourself with worker_send; ask the user with cortex_ask_user only when you are unsure what they would want.
75
+ 4. Do not run repeated review loops on a worker's output.`;return e?`${n}
76
+
77
+ ${e}`:n}var II="report-to-lead";function fy(t){return`[Worker] You are worker "${t.name}" of the lead session "${t.lead}". Reach the lead with report_to_lead: the report is delivered at once and wakes the lead, and you may call it mid-turn and keep working. Your final reply stays in your own chat; the lead sees it only as an unread routine update, or as a report when the turn ends with nothing running and no waitpoint or monitor left to wake you. Report results, milestones, failures, blockers, questions and plans needing approval; skip acknowledgements and "still running". You have no ask-user or plan-approval tool: put the question or plan in a report and end your turn; the lead answers with a message. The user may also open this session and talk to you directly; report anything from that the lead needs to know. Keep reports concise: conclusions, output paths, open items. You cannot create workers yourself.`}function my(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(`
78
+ `)}import{createHash as ib}from"node:crypto";import P from"node:fs";import y from"node:path";import TS from"node:fs";import T from"node:path";var hy="https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",Ll="https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",Dl=new Set(["$schema","name","version","description","author","homepage","repository","license","keywords","extensions"]),gy=/^(?!.*(?:--|\.\.))[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/,yy=/^(?:\.\/|\$\{PLUGIN_ROOT\}(?:\/|$)|\$\{PLUGIN_DATA\}(?:\/|$))/,Sy=new Set(["PLUGIN_ROOT","PLUGIN_DATA"]),by=f.object({name:f.string().optional(),email:f.string().optional(),url:f.string().optional()}).strict(),ky=f.record(f.string(),f.record(f.string(),f.unknown())),Nl=f.object({$schema:f.literal(hy),name:f.string().min(1).max(64).regex(gy),version:f.string().optional(),description:f.string().optional(),author:by.optional(),homepage:f.string().optional(),repository:f.string().optional(),license:f.string().optional(),keywords:f.array(f.string()).optional(),extensions:ky.optional()}).strict();function Ty(t,e){for(let n of Object.keys(t))Sy.has(n.toUpperCase())&&e.addIssue({code:f.ZodIssueCode.custom,path:[n],message:`Reserved env key ${n} is not allowed`})}var _y=f.object({type:f.literal("stdio"),command:f.string().min(1),args:f.array(f.string()).optional(),env:f.record(f.string(),f.string()).superRefine(Ty).optional(),cwd:f.string().regex(yy).optional()}).strict(),jl=f.record(f.string(),f.string()),vy=f.object({type:f.literal("streamable-http"),url:f.string().min(1),headers:jl.optional()}).strict(),wy=f.object({type:f.literal("sse"),url:f.string().min(1),headers:jl.optional()}).strict(),ui=f.union([_y,vy,wy]),Ul=f.object({$schema:f.literal(Ll),mcpServers:f.record(f.string(),f.unknown())}).strict(),RI=f.object({$schema:f.literal(Ll),mcpServers:f.record(f.string(),ui)}).strict();import xy from"node:fs";import li from"node:path";import Wl from"node:net";import{validateHeaderName as Ey,validateHeaderValue as Iy}from"node:http";function k(t,e,n,r){return{code:t,scope:e,path:n,message:r}}function An(t){return t.reduce((e,n)=>typeof n=="number"?`${e}[${n}]`:e?`${e}.${String(n)}`:String(n),"")}var $l=Symbol("skillRoot");function Cn(t,e,n){let r={name:t.name,dir:t.dir,description:t.description,origin:n};return Object.defineProperty(r,$l,{value:e,enumerable:!1}),r}function gt(t){return t[$l]??null}var Bl=Symbol("pluginMcpRuntime");function ai(t,e){return Object.defineProperty(t,Bl,{value:e,enumerable:!1}),t}function Fl(t){return t[Bl]??null}function oe(t){return Ns(t.manifest.name?.trim()||t.id)}function Kl(t){return t.issues.map(e=>`${An(e.path)||"(root)"}: ${e.message}`).join("; ")}function Ay(t,e){return li.join(t,"data","plugin-data",e)}function ci(t,e,n){let r={PLUGIN_ROOT:e,PLUGIN_DATA:n};return t.replace(/\$\{(PLUGIN_ROOT|PLUGIN_DATA)\}/g,(i,s)=>r[s])}function Cy(t,e,n){let r=ci(t,e,n);return t.startsWith("${PLUGIN_ROOT}")?Q(e,r):t.startsWith("${PLUGIN_DATA}")?Q(n,r):r}function Ry(t,e,n){return(t??[]).map(r=>ci(r,e,n))}function Py(t,e,n){let r={};for(let[i,s]of Object.entries(t??{}))r[i]=ci(s,e,n);return r.PLUGIN_ROOT=e,r.PLUGIN_DATA=n,r}function Oy(t){return li.basename(t)}function My(t){return t.includes("/")||t.includes("\\")}function Ly(t,e){return e.startsWith("./")?Gn(t,e):My(e)?null:e}function Dy(t,e,n){return n?n.startsWith("./")?Gn(t,n):Cy(n,t,e):t}function Ny(t){return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function jy(t){let e=Ny(t);return e==="localhost"?!0:Wl.isIP(e)===4?e.startsWith("127."):Wl.isIP(e)!==6?!1:e==="::1"||e.toLowerCase()==="0:0:0:0:0:0:0:1"}function Uy(t){return t.protocol==="https:"||t.protocol==="http:"&&jy(t.hostname)}function $y(t){return!!(t.username||t.password||t.hash)}function By(t){return Uy(t)&&!$y(t)}function Fy(t){try{let e=new URL(t);return By(e)?e:null}catch{return null}}function Wy(t,e){let n=e.toLowerCase();return t.has(n)?!1:(t.add(n),!0)}function zy(t,e){try{return Ey(t),Iy(t,e),!0}catch{return!1}}function Ky(t,e,n){return Wy(t,e)&&zy(e,n)}function qy(t){let e=t??{},n=new Set;for(let[r,i]of Object.entries(e))if(!Ky(n,r,i))return null;return Object.keys(e).sort()}function Hy(t,e,n,r){let i=e,s=Ly(t,r.command),o=Ry(r.args,t,i),u=Py(r.env,t,i),a=Dy(t,i,r.cwd);return!s||!a?null:ai({name:n,type:"stdio",summary:{command:Oy(s),argsCount:o.length,envKeys:Object.keys(u).sort()}},{command:s,args:o,env:u,cwd:a})}function Qy(t,e){let n=Fy(e.url),r=qy(e.headers);return!n||!r?null:ai({name:t,type:e.type,summary:{origin:n.origin,headerKeys:r}},{url:e.url,headers:e.headers??{}})}function Gy(t,e,n,r){return r.type==="stdio"?Hy(t,e,n,r):Qy(n,r)}function Vy(t){let e=li.join(t,"mcp.json");if(!H(e))return{};let n=Q(t,e);if(!n||!ve(n))return{issue:k("mcp_invalid","mcp","mcp.json","mcp.json must be a regular file inside the plugin root")};try{return{text:xy.readFileSync(n,"utf8")}}catch{return{issue:k("mcp_invalid","mcp","mcp.json","mcp.json could not be read")}}}function zl(t){return t.match(/\/schemas\/([^/]+)\//)?.[1]??""}function Jy(t,e){try{let n=JSON.parse(t),r=Ul.safeParse(n);return r.success?zl(r.data.$schema)!==zl(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",Kl(r.error))}}catch{return{issue:k("mcp_invalid","mcp","mcp.json","mcp.json is not valid JSON")}}}function Xy(t,e,n){let r=[],i=[];for(let[s,o]of Object.entries(n).sort(([u],[a])=>u.localeCompare(a))){let u=ui.safeParse(o);if(!u.success){i.push(k("mcp_server_invalid","server",`mcpServers.${s}`,Kl(u.error)));continue}let a=Gy(t,e,s,u.data);if(!a){i.push(k("mcp_server_invalid","server",`mcpServers.${s}`,"server violates URL or containment rules"));continue}r.push(a)}return{servers:r,issues:i}}function di(t,e,n,r){let i=Vy(e);if(i.issue)return{status:"invalid",servers:[],issues:[i.issue]};if(i.text===void 0)return{status:"missing",servers:[],issues:[]};let s=Jy(i.text,r);if(s.issue||!s.value)return{status:"invalid",servers:[],issues:s.issue?[s.issue]:[]};let o=Xy(e,Ay(n,t),s.value.mcpServers);return{status:"valid",servers:o.servers,issues:o.issues}}var Hl=zc(Kc(),1);import ql from"node:fs";import Yy from"node:path";var Zy=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,eS=/^(?!.*--)[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/,tS=new Set(["name","description","license","compatibility","metadata","allowed-tools"]);function Ql(t){return`skills.${t}.SKILL.md`}function Pn(t,e){return{code:"skill_invalid",scope:"skill",path:Ql(t),message:e}}function Gl(t,e){return{code:"skill_frontmatter_ignored",scope:"skill",path:Ql(t),message:e}}function Vl(t){let e=Zy.exec(t);if(!e)return null;try{let n=(0,Hl.parse)(e[1]);return ae(n)?n:null}catch{return null}}function nS(t,e){return t!==void 0&&!(typeof t=="string"&&t===e)}function Jl(t){return typeof t=="string"&&t.trim().length>0}function On(t,e,n){return[Gl(t,`SKILL.md frontmatter ${e} ${n}`)]}function rS(t,e){let n=Object.keys(e).filter(r=>!tS.has(r)).sort();return n.length===0?[]:[Gl(t,`SKILL.md frontmatter has fields outside the spec, ignored: ${n.join(", ")}`)]}function iS(t,e){let n=[];return e.name===void 0?n.push(...On(t,"name","is absent; the directory name is used")):typeof e.name=="string"&&(e.name.length>64||!eS.test(e.name))&&n.push(...On(t,"name","is not a canonical Agent Skills name")),typeof e.description=="string"&&e.description.length>1024&&n.push(...On(t,"description","exceeds the 1024-character guidance")),n}function sS(t){return ae(t)?Object.values(t).every(e=>typeof e=="string"):!1}function Rn(t,e,n,r,i){n&&t.push(...On(e,r,i))}function oS(t,e){let n=[];return Rn(n,t,e.license!==void 0&&typeof e.license!="string","license","must be a string when present"),Rn(n,t,e.compatibility!==void 0&&(!Jl(e.compatibility)||String(e.compatibility).length>500),"compatibility","must be 1-500 characters when present"),Rn(n,t,e.metadata!==void 0&&!sS(e.metadata),"metadata","must be a string-to-string map when present"),Rn(n,t,e["allowed-tools"]!==void 0&&!uS(e["allowed-tools"]),"allowed-tools","should be a comma-separated string"),n}function uS(t){return typeof t=="string"||Array.isArray(t)&&t.every(e=>typeof e=="string")}function aS(t,e){return e?nS(e.name,t)?[Pn(t,"SKILL.md frontmatter name must match the skill directory")]:Jl(e.description)?[]:[Pn(t,"SKILL.md frontmatter description must be non-empty")]:[Pn(t,"SKILL.md must start with YAML frontmatter")]}function lS(t,e){return[...iS(t,e),...oS(t,e),...rS(t,e)]}function pi(t){try{let e=Vl(ql.readFileSync(t,"utf8"));return typeof e?.description=="string"?e.description.trim():""}catch{return""}}function Xl(t,e){let n;try{n=ql.readFileSync(e,"utf8")}catch{return{issues:[Pn(t,"SKILL.md could not be read")]}}let r=Vl(n),i=aS(t,r);return i.length>0||!r?{issues:i}:{skill:{name:t,dir:Yy.join("skills",t),description:String(r.description).trim()},issues:lS(t,r)}}import{createHash as cS}from"node:crypto";import b from"node:fs";import ee from"node:path";function ec(t){return cS("sha256").update(t).digest("hex")}function mi(t,e){let n=b.realpathSync(e);if(!ro(t,n))throw new Error(`Skill path escapes plugin root: ${e}`);return n}function dS(t,e){if(!t.isFile())throw new Error(`Skill path is not a file: ${e}`)}function tc(t,e,n){if(t.dev!==e.dev||t.ino!==e.ino)throw new Error(`Skill file changed while being read: ${n}`)}function Fe(t){return`${t.size}:${t.mtimeMs}:${t.ctimeMs}:${t.ino}:${t.mode&511}`}var pS=b.constants.O_RDONLY|(b.constants.O_NOFOLLOW??0);function hi(t,e){let n=mi(t,e),r=b.openSync(n,pS);try{let i=b.fstatSync(r);return dS(i,n),tc(i,b.lstatSync(e),e),{fd:r,stat:b.fstatSync(r),resolved:n}}catch(i){throw b.closeSync(r),i}}var Yl=new Map;function fS(t,e,n){let r=Fe(n),i=Yl.get(e);if(i?.signature===r)return i.digest;let s=ec(b.readFileSync(t));if(Fe(b.fstatSync(t))!==r)throw new Error(`Skill file changed while being read: ${e}`);return Yl.set(e,{signature:r,digest:s}),s}function nc(t,e,n,r){let{fd:i,stat:s,resolved:o}=hi(t,n);try{e.push({path:r,signature:Fe(s),size:s.size,mode:s.mode&511,digest:fS(i,o,s)})}finally{b.closeSync(i)}}function mS(t,e,n,r){let{fd:i,stat:s}=hi(t,n);b.closeSync(i),e.push({path:r,size:s.size,mode:s.mode&511})}function gi(t,e,n,r,i,s){let o=mi(t,e);if(r.has(o))throw new Error(`Skill tree contains a symlink cycle: ${n||"."}`);let u=new Set(r).add(o);n&&i.push(n);for(let a of b.readdirSync(e).sort())gS(t,ee.join(e,a),ee.posix.join(n,a),u,i,s)}function hS(t,e,n,r,i,s){let o=mi(t,e),u=b.statSync(o);if(u.isDirectory())return gi(t,o,n,r,i,s);if(u.isFile())return nc(t,s,o,n);throw new Error(`Skill path is not a file or directory: ${n}`)}function gS(t,e,n,r,i,s){let o=b.lstatSync(e);if(o.isSymbolicLink())return hS(t,e,n,r,i,s);if(o.isDirectory())return gi(t,e,n,r,i,s);if(o.isFile())return nc(t,s,e,n);throw new Error(`Skill path is not a file or directory: ${n}`)}function yS(t,e){let n=e.map(({path:r,size:i,mode:s,digest:o})=>({path:r,size:i,mode:s,digest:o}));return ec(JSON.stringify({dirs:t,files:n}))}function Mn(t,e){let n=[],r=[];return gi(b.realpathSync(t),e,"",new Set,n,r),n.sort(),r.sort((i,s)=>i.path.localeCompare(s.path)),{dirs:n,files:r,sha256:yS(n,r)}}function fi(t){b.mkdirSync(t,{recursive:!0,mode:448}),b.chmodSync(t,448)}function SS(t,e,n,r,i){let{fd:s,stat:o}=hi(t,e);try{if(i&&Fe(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 u=b.readFileSync(s),a=b.fstatSync(s);if(tc(o,a,e),a.size!==r.size||Fe(a)!==Fe(o))throw new Error(`Skill file changed while being read: ${e}`);b.writeFileSync(n,u,{mode:r.mode}),b.chmodSync(n,r.mode)}finally{b.closeSync(s)}}function yi(t,e,n,r,i={}){fi(r);for(let s of n.dirs)fi(ee.join(r,s));for(let s of n.files)fi(ee.dirname(ee.join(r,s.path))),SS(t,ee.join(e,s.path),ee.join(r,s.path),s,i.requireSourceSignature===!0)}function bS(t,e,n,r,i){n&&r.push(n);for(let s of b.readdirSync(e).sort())rc(t,ee.join(e,s),ee.posix.join(n,s),r,i)}function rc(t,e,n,r,i){let s=b.lstatSync(e);if(s.isSymbolicLink())throw new Error(`Portable projection target is invalid: ${e}`);if(s.isDirectory())return bS(t,e,n,r,i);if(s.isFile())return mS(t,i,e,n);throw new Error(`Portable projection target is invalid: ${e}`)}function kS(t){let e=[],n=[];return rc(t,t,"",e,n),e.sort(),n.sort((r,i)=>r.path.localeCompare(i.path)),{dirs:e,files:n}}function Zl(t){return JSON.stringify({dirs:t.dirs,files:t.files.map(({path:e,size:n,mode:r})=>({path:e,size:n,mode:r}))})}function Si(t,e){let n=b.lstatSync(t);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`Portable projection target is invalid: ${t}`);let r=kS(t);if(Zl(r)!==Zl(e))throw new Error(`Portable projection skill tree mismatch: ${t}`)}function _S(t){return T.join("plugins",t)}function te(t){return{id:t,origin:"local",kind:"unknown",rootDir:_S(t),valid:!1,manifest:{source:"none"},skills:[],mcp:{status:"missing",servers:[]},issues:[]}}function Ln(t){if(typeof t!="string")return;let e=t.trim();return e.length>0?e:void 0}function vS(t){return t.issues.map(e=>k("manifest_invalid","manifest",An(e.path)||"plugin.json",e.message))}function wS(t){let e={},n=[];for(let[r,i]of Object.entries(t)){if(!Dl.has(r)){n.push(k("manifest_unknown_field","manifest",`plugin.json.${r}`,`Ignoring unknown field "${r}"`));continue}if(r==="extensions"&&!ae(i)){n.push(k("manifest_extensions_ignored","manifest","plugin.json.extensions","Ignoring non-object extensions field"));continue}e[r]=i}return{sanitized:e,issues:n}}function xS(t){try{let e=JSON.parse(t);if(!ae(e))return ic("plugin.json must contain a top-level object");let n=wS(e),r=Nl.safeParse(n.sanitized);return r.success?{manifest:ES(r.data),valid:!0,issues:n.issues}:{manifest:{source:"root"},valid:!1,issues:[...n.issues,...vS(r.error)]}}catch{return ic("plugin.json is not valid JSON")}}function ES(t){return{source:"root",name:t.name,schema:t.$schema,version:Ln(t.version),description:Ln(t.description)}}function ic(t){return{manifest:{source:"root"},valid:!1,issues:[k("manifest_invalid","manifest","plugin.json",t)]}}function IS(t){try{let e=JSON.parse(t);return!ae(e)||typeof e.name!="string"||e.name.trim()===""?sc("legacy manifest must define a non-empty name"):{manifest:{source:"legacy",name:e.name.trim(),version:Ln(e.version),description:Ln(e.description)},valid:!0,issues:[]}}catch{return sc("legacy manifest is not valid JSON")}}function sc(t){return{manifest:{source:"legacy"},valid:!1,issues:[k("legacy_manifest_invalid","manifest",".claude-plugin/plugin.json",t)]}}function AS(t){return k("manifest_invalid","manifest",t,`${t} must be a regular file inside the plugin root`)}function uc(t,e){let n=T.join(t,e);if(!H(n))return{state:"missing",issues:[]};let r=Q(t,n);return!r||!ve(r)?{state:"invalid",issues:[AS(e)]}:{state:"present",path:r,issues:[]}}function bi(t){return k("skill_invalid","skill","skills",t)}function CS(t){let e=T.join(t,"skills");if(!H(e))return{state:"missing",issues:[]};let n=Q(t,e);return n?Dt(n)?{state:"present",path:n,issues:[]}:{state:"invalid",issues:[bi("skills must be a directory inside the plugin root")]}:{state:"invalid",issues:[bi("skills must resolve to a directory inside the plugin root")]}}function RS(t){try{return{names:le(t),issues:[]}}catch{return{names:[],issues:[bi("skills could not be read")]}}}function ki(t,e){let n=CS(t);if(n.state!=="present"||!n.path)return{skills:[],issues:n.issues};let r=RS(n.path),i=[],s=[...r.issues];for(let o of r.names){let u=OS(t,n.path,o,e);u.skill&&i.push(Cn(u.skill,t,"local")),s.push(...u.issues)}return{skills:i,issues:s}}function PS(t,e,n){let r=Xl(e,n);if(!r.skill)return r;try{return Mn(t,T.dirname(n)),r}catch(i){let s=i instanceof Error?i.message:String(i);return{issues:[...r.issues,k("skill_invalid","skill",`skills.${e}`,`Skill support tree is invalid: ${s}`)]}}}function OS(t,e,n,r){let i=T.join(e,n,"SKILL.md"),s=Q(t,i);return!s||!ve(s)?{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:T.join("skills",n),description:pi(s)},issues:[]}:PS(t,n,s)}function MS(t,e,n,r){let i=te(t),s=xS(r);if(i.kind="portable",i.manifest=s.manifest,i.issues.push(...s.issues),!s.valid||!s.manifest.schema)return i;let o=ki(e,"portable"),u=di(t,e,n,s.manifest.schema);return i.valid=!0,i.skills=o.skills,i.mcp={status:u.status,servers:u.servers},i.issues.push(...o.issues,...u.issues),i}function LS(t,e,n){let r=te(t),i=IS(n);if(r.kind="legacy",r.manifest=i.manifest,r.issues.push(...i.issues),!i.valid)return r;let s=ki(e,"legacy");return r.valid=!0,r.skills=s.skills,r.issues.push(...s.issues),r}function DS(t){let e=te(t);return e.issues.push(k("manifest_missing","manifest",null,"plugin.json and .claude-plugin/plugin.json are both missing")),e}function ac(t,e,n){try{return{text:TS.readFileSync(t,"utf8"),issues:[]}}catch{return{issues:[k(e,"manifest",n,`${n} could not be read`)]}}}function lc(t,e){let n=Q(t,e);return n&&Dt(n)?n:null}function cc(t,e){let n=te(t),i=H(e)?"plugin_root_outside_plugins_dir":"plugin_root_not_directory",s=i==="plugin_root_outside_plugins_dir"?"plugin root must resolve inside PLUGINS_DIR":"plugin root must be a directory";return n.issues.push(k(i,"plugin",t,s)),n}function NS(t,e,n,r){let i=ac(r,"manifest_invalid","plugin.json");if(i.text!==void 0)return MS(t,e,n,i.text);let s=te(t);return s.kind="portable",s.manifest={source:"root"},s.issues.push(...i.issues),s}function jS(t,e,n){let r=ac(n,"legacy_manifest_invalid",".claude-plugin/plugin.json");if(r.text!==void 0)return LS(t,e,r.text);let i=te(t);return i.kind="legacy",i.manifest={source:"legacy"},i.issues.push(...r.issues),i}function US(t,e,n){let r=uc(e,"plugin.json");if(r.state==="invalid"){let i=te(t);return i.kind="portable",i.manifest={source:"root"},i.issues.push(...r.issues),i}return r.state!=="present"||!r.path?null:NS(t,e,n,r.path)}function $S(t,e){let n=uc(e,T.join(".claude-plugin","plugin.json"));if(n.state==="invalid"){let r=te(t);return r.kind="legacy",r.manifest={source:"legacy"},r.issues.push(...n.issues),r}return n.state!=="present"||!n.path?null:jS(t,e,n.path)}function BS(t,e,n){let r=T.join(e,t),i=lc(e,r);return i?US(t,i,n)??$S(t,i)??DS(t):cc(t,r)}function dc(t,e,n){try{return BS(t,e,n)}catch{let r=te(t);return r.issues.push(k("manifest_invalid","manifest","plugin.json","plugin entry could not be loaded")),r}}function oc(t){return t&&Dt(t)?$(t):null}function FS(t){let e=t.builtin?le(t.builtin):[],n=t.user?le(t.user):[];return[...new Set([...e,...n])].sort()}function WS(t,e){return t.name<e.name?-1:t.name>e.name?1:0}function zS(t,e){let n=new Map(t.skills.map(r=>[r.name,r]));for(let r of e.skills)n.set(r.name,Cn(r,gt(r),n.has(r.name)?"overridden":"local"));t.skills=[...n.values()].sort(WS),t.issues.push(...e.issues)}function KS(t,e,n){if(!H(T.join(e,"mcp.json"))||!t.manifest.schema)return;let r=di(t.id,e,n,t.manifest.schema);t.mcp={status:r.status,servers:r.servers},t.issues=[...t.issues.filter(i=>i.scope!=="mcp"&&i.scope!=="server"),...r.issues]}function qS(t,e,n){let r=e?T.join(e,t.id):null;if(!r||!H(r))return t;let i=lc(e,r);return i?(t.kind==="portable"&&t.valid&&(zS(t,ki(i,"portable")),KS(t,i,n)),t):{...t,issues:[...t.issues,...cc(t.id,r).issues]}}function HS(t,e){let n=dc(t,e.builtin,e.dataDir),r={...n,origin:"builtin",skills:n.skills.map(i=>Cn(i,gt(i),"builtin"))};return qS(r,e.user,e.dataDir)}function QS(t,e){return e.builtin&&H(T.join(e.builtin,t))?HS(t,e):dc(t,e.user,e.dataDir)}function Ti(t={}){let e={user:oc(T.resolve(t.pluginsDir??We)),builtin:oc(t.builtinDir===void 0?Nt():t.builtinDir),dataDir:T.resolve(t.dataDir??M)},n=FS(e).filter(r=>!t.ids||t.ids.has(r)).map(r=>QS(r,e));return GS(n),n}function GS(t){let e=new Map;for(let n of t){if(n.kind!=="portable"||!n.valid)continue;let r=oe(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(oe(n))??[]).filter(i=>i!==n.id);r.length!==0&&n.issues.push(k("manifest_name_duplicate","manifest","plugin.json.name",`Plugin name "${oe(n)}" is also used by ${r.map(i=>`'${i}'`).join(", ")}; a session that selects more than one of them loads only the first selected.`))}}function VS(t){return[...t].sort((e,n)=>e.localeCompare(n))}function JS(t){let e=T.join(t,"skills");return le(e).filter(n=>ve(T.join(e,n,"SKILL.md"))).map(n=>({name:n,description:pi(T.join(e,n,"SKILL.md"))}))}function XS(t){return[...t].sort((e,n)=>e.name.localeCompare(n.name))}function YS(t,e){let n=new Map;for(let r of t){let i=T.join(e,r.id);n.set(i,r);let s=$(i);s&&n.set(s,r)}return n}function ZS(t,e,n){if(n?.kind==="portable"&&!n.valid)return[];let r=n?.id??t,i=n?oe(n):T.basename(e),s=n?.kind==="portable"?n.skills:JS(e);return XS(s).map(o=>({plugin:r,namespace:i,name:o.name,description:o.description}))}function pc(t,e,n,r){let i=YS(t,e),s=[],o=new Set;for(let u of r){let a=T.isAbsolute(u)?T.resolve(u):T.resolve(n,u),l=$(a)??a;o.has(l)||(o.add(l),s.push(ZS(u,l,i.get(a)??i.get(l))))}return s.filter(u=>u.length>0)}function fc(t){let e=T.resolve(t.pluginsDir??We),n=T.resolve(t.dataDir??M);return{entries:Ti({pluginsDir:e,dataDir:n,builtinDir:t.builtinDir}),pluginsDir:e,dataDir:n}}function uA(t){let{entries:e,pluginsDir:n,dataDir:r}=fc(t);return pc(e,n,r,t.pluginDirs).flat()}function aA(t={}){let{entries:e,pluginsDir:n,dataDir:r}=fc(t);return t.pluginDirs?pc(e,n,r,t.pluginDirs).map(i=>({plugin:i[0].plugin,skills:i.map(s=>s.name)})):e.filter(i=>i.valid&&i.skills.length>0).map(i=>({plugin:i.id,skills:VS(i.skills.map(s=>s.name))}))}import Nn from"node:fs";import Dn from"node:path";var vi=p("plugin-runtime"),eb=10080*60*1e3,tb=3600*1e3,mc=/^(plugin|skill)_/,nb=/^[0-9a-f]{64}\.json(?:\.tmp\..+)?$/,hc=["claude-mcp","claude-mcp-proxies"],gc=new Map;function wi(t){try{let e=new Date;Nn.utimesSync(t,e,e)}catch{}}function _i(t,e){try{return Nn.readdirSync(t).filter(n=>e.test(n)).map(n=>Dn.join(t,n))}catch{return[]}}function rb(t,e,n){try{let r=Nn.lstatSync(t);return n(r)&&e-r.mtimeMs>=eb}catch{return!1}}function yc(t,e){return e-(gc.get(t)??0)<tb?!0:(gc.set(t,e),!1)}function Sc(t,e,n,r){let i=[];for(let s of t)if(!(e.has(s)||!rb(s,n,r)))try{Nn.rmSync(s,{recursive:!0,force:!0}),i.push(s)}catch(o){vi.warn(`Could not remove stale plugin runtime entry ${s}: ${o.message}`)}return i}function bc(t,e,n=Date.now()){if(yc(t,n))return[];let r=[..._i(t,mc),..._i(Dn.join(t,"skill-snapshots"),mc)],i=Sc(r,e,n,s=>s.isDirectory());return i.length>0&&vi.info(`Removed ${i.length} stale plugin runtime dir(s) under ${t}`),i}function kc(t,e=Date.now()){if(yc(Dn.join(t,hc[0]),e))return[];let n=hc.flatMap(i=>_i(Dn.join(t,i),nb)),r=Sc(n,new Set,e,i=>i.isFile());return r.length>0&&vi.info(`Removed ${r.length} stale Claude MCP config(s) under ${t}`),r}var jn=p("plugin-runtime");function St(t,e){jn.warn(e),t.push(e)}function sb(t){return JSON.stringify(t)}function ob(t){return`[${t.map(e=>yt(e)??"null").join(",")}]`}function ub(t){return`{${Object.keys(t).sort().flatMap(n=>{let r=yt(t[n]);return r===void 0?[]:[`${JSON.stringify(n)}:${r}`]}).join(",")}}`}function yt(t){return t===null||typeof t!="object"?sb(t):Array.isArray(t)?ob(t):ub(t)}function xc(t){let e=yt(t);if(e===void 0)throw new TypeError("Value is not JSON-serializable");return ib("sha256").update(e,"utf8").digest("hex")}function Tc(t){return t.length>0?t:void 0}function Ec(t,e){return y.isAbsolute(e)?y.resolve(e):y.resolve(t,e)}function ab(t){return t!=="none"}function lb(t,e){let n=new Map;for(let r of e){let i=y.resolve(t,r.id);n.set(r.id,{absolute:i,real:$(i)??i})}return n}function cb(t,e){let n=new Map,r=new Map;for(let i of t){let s=e.get(i.id);s&&(n.set(s.absolute,i),r.set(s.real,i))}return{byAbsolute:n,byRealpath:r}}function db(t,e){return ze([t.id,e],"plugin")}function pb(t,e,n,r){if(!("command"in n)||!("cwd"in n))throw new Error(`Portable MCP runtime mismatch for '${t.id}/${e.name}'`);let i=n.env.PLUGIN_DATA;if(!i)throw new Error(`Portable MCP PLUGIN_DATA missing for '${t.id}/${e.name}'`);return R(i,"Portable plugin data"),{name:r,type:"stdio",command:n.command,args:[...n.args],env:{...n.env},cwd:n.cwd}}function fb(t,e){let n=Fl(e);if(!n)throw new Error(`Portable MCP runtime missing for '${t.id}/${e.name}'`);let r=db(t,e.name);if(e.type==="stdio")return pb(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 mb(t,e,n){try{let r=gt(e);if(!r)throw new Error("its plugin layer is unknown");let i=y.join(r,e.dir),s=$(i)??i,o=Mn(r,s);return{name:e.name,root:r,target:s,contentSha256:o.sha256,tree:o}}catch(r){return St(n,`Skipping portable skill '${t.entry.id}/${e.name}': ${r.message}`),null}}function hb(t,e){return t.entry.skills.flatMap(n=>{let r=mb(t,n,e);return r?[r]:[]})}function gb(t,e){return xc({pluginId:t.entry.id,manifest:Ic(t.entry),skills:e.map(n=>({name:n.name,sha256:n.contentSha256}))})}function Ic(t){let e=js(t.manifest.version);return`${JSON.stringify({name:oe(t),...e?{version:e}:{},...t.manifest.description?{description:t.manifest.description}:{}},null,2)}
79
+ `}function yb(t){return P.readdirSync(t).sort((e,n)=>e.localeCompare(n))}function xi(t){let e=P.lstatSync(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Claude projection target is invalid: ${t}`)}function Ei(t,e,n){if(yt(yb(t))!==yt(e))throw new Error(`Claude projection ${n} mismatch: ${t}`)}function Sb(t,e){let n=y.join(t,".claude-plugin");if(xi(n),Ei(n,["plugin.json"],"manifest directory"),P.readFileSync(y.join(n,"plugin.json"),"utf8")!==e)throw new Error(`Claude projection manifest mismatch: ${t}`)}function bb(t,e){let n=y.join(t,"skills");xi(n);let r=e.map(i=>i.name).sort((i,s)=>i.localeCompare(s));Ei(n,r,"skill set");for(let i of e)Si(y.join(n,i.name),i.tree)}function kb(t,e,n){xi(t),Ei(t,[".claude-plugin","skills"],"root"),Sb(t,e),bb(t,n)}function Ac(t){R(t,"Claude projection"),R(y.join(t,".claude-plugin"),"Claude projection"),R(y.join(t,"skills"),"Claude projection")}function Tb(t,e,n){Ac(t),Ai(y.join(t,".claude-plugin","plugin.json"),e);for(let r of n)yi(r.target,r.target,r.tree,y.join(t,"skills",r.name))}function _b(t,e,n){let r=gb(e,n);return y.join(t,ze([e.entry.id,r],"plugin"))}function Cc(t,e){let n=`${process.pid}:${Date.now()}:${Math.random()}`;return y.join(t,ze([y.basename(e),n],"plugin_tmp"))}function vb(t,e,n,r){let i=Cc(y.dirname(r),r);P.mkdirSync(i,{mode:448});try{return Tb(i,n,e),P.renameSync(i,r),!0}catch(s){if(P.rmSync(i,{recursive:!0,force:!0}),!P.existsSync(r))throw s;return!1}}function _c(t,e,n){return kb(t,e,n),Ac(t),t}function wb(t,e,n){let r=ze([e.entry.id,n.name,n.contentSha256],"skill");return y.join(t,r,n.name)}function xb(t,e,n){let r=Cc(y.dirname(n),n);try{return yi(e.root,e.target,e.tree,r,{requireSourceSignature:!0}),P.renameSync(r,n),!0}catch(i){if(P.rmSync(r,{recursive:!0,force:!0}),!P.existsSync(n))throw i;return!1}}function vc(t,e){return Si(t,e.tree),R(t,"Portable skill snapshot"),t}function Eb(t,e,n,r){R(n,"Plugin runtime");let i=y.join(n,r,"skill-snapshots");R(i,`${r} skill snapshots`);let s=wb(i,t,e);if(R(y.dirname(s),`${r} skill snapshot`),P.existsSync(s))return wi(y.dirname(s)),vc(s,e);let o=xb(t,e,s);try{return vc(s,e)}catch(u){throw o&&P.rmSync(s,{recursive:!0,force:!0}),u}}function Ib(t,e,n,r,i){try{return{...e,target:Eb(t,e,n,r)}}catch(s){return St(i,`Skipping portable skill '${t.entry.id}/${e.name}': ${s.message}`),null}}function Ab(t,e,n,r,i){return e.flatMap(s=>{let o=Ib(t,s,n,r,i);return o?[o]:[]})}function Cb(t,e,n,r){R(n,"Plugin runtime");let i=y.join(n,r);R(i,`${r} plugin projection`);let s=Ic(t.entry),o=_b(i,t,e);if(P.existsSync(o))return wi(o),_c(o,s,e);let u=vb(t,e,s,o);try{return _c(o,s,e)}catch(a){throw u&&P.rmSync(o,{recursive:!0,force:!0}),a}}function Rb(t,e,n,r,i){if(e.length===0)return null;try{return Cb(t,e,n,r)}catch(s){return St(i,`Skipping portable skills for '${t.entry.id}': ${s.message}`),e.splice(0),null}}function Pb(t,e,n){try{return[fb(t,e)]}catch(r){return St(n,`Skipping portable MCP '${t.id}/${e.name}': ${r.message}`),[]}}function Ob(t,e,n,r,i,s){let o=Ab(t,jb(t,hb(t,s),i),n,e,s);return{skills:o,projectionDir:e==="claude"?Rb(t,o,n,e,s):null,mcpServers:r?t.entry.mcp.servers.flatMap(u=>Pb(t.entry,u,s)):[]}}function Mb(t,e,n,r,i,s){if(!(!r&&!i&&!s))return xc({backend:t,pluginDirs:r??[],pluginSkillDirs:i??[],mcpServers:s??[],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(u=>({name:u.name,target:u.target,contentSha256:u.contentSha256}))??[]})})}function Lb(t,e){if(!t.valid){let n=t.issues[0]?.message??"manifest is invalid";St(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 Db(t,e,n,r,i){if(n?.kind==="portable")return Lb(n,r);n?.kind==="legacy"&&r.selectedLegacySkills.push(...n.skills.map(o=>({name:o.name,pluginId:n.id})));let s=e??t;i.has(s)||(i.add(s),r.items.push({kind:"preserved",path:s}))}function Nb(t,e,n,r){let i=cb(t,e),s={items:[],portableSelections:new Map,selectedLegacySkills:[],warnings:[]},o=new Set;for(let u of r){let a=Ec(n,u),l=$(a),c=i.byAbsolute.get(a)??(l?i.byRealpath.get(l):void 0);Db(a,l,c,s,o)}return s}function jb(t,e,n){let r=[];for(let i of e){let s=n.get(i.name);if(s!==void 0){jn.warn(`Skipping skill '${i.name}' from plugin '${t.entry.id}': '${s}' is already selected and provides that name.`);continue}n.set(i.name,t.entry.id),r.push(i)}return r}function Ub(t,e,n){let r=new Set(n.map(i=>i.name));for(let[i,s]of t)s===e&&!r.has(i)&&t.delete(i)}function $b(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 Bb(t,e){let n=oe(e.entry),r=t.get(n);return r!==void 0?(jn.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 Fb(t,e,n,r){let i=new Map,s=new Map,o=new Map,u=new Set,a=[];for(let[l,c]of t){if(!Bb(s,c))continue;let d=Ob(c,e,n,r,o,a);Ub(o,l,d.skills),$b(d,u),i.set(l,d)}return{details:i,skillClaims:o,warnings:a}}function Wb(t,e){for(let{name:n,pluginId:r}of e){let i=t.get(n);i!==void 0&&jn.warn(`Skill '${n}' is provided by both portable plugin '${i}' and legacy plugin '${r}'. Deselect one of them to make the choice explicit.`)}}function zb(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 Kb(t,e,n,r){if(t.kind==="preserved")return void r.pluginDirs.push(t.path);let i=e.get(t.id);i&&zb(i,n,r)}function qb(t,e,n){let r={pluginDirs:[],pluginSkillDirs:[],mcpServers:[]};for(let i of t)Kb(i,e,n,r);return r}function Hb(t,e,n){let r=qb(e,n,t),i=Tc(r.pluginDirs),s=t==="pi"?Tc(r.pluginSkillDirs):void 0,o=r.mcpServers.length>0?r.mcpServers:void 0;return{pluginDirs:i,pluginSkillDirs:s,mcpServers:o,pluginCapabilityFingerprint:Mb(t,e,n,i,s,o)}}function Qb(t,e,n,r){let i=new Set;for(let o of n){let u=Ec(e,o);i.add(u);let a=$(u);a&&i.add(a)}let s=new Set;for(let o of new Set([...le(t),...r])){let u=y.resolve(t,o);(i.has(u)||i.has($(u)??u))&&s.add(o)}return s}function Gb(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 Rc(t){let e=y.resolve(t.dataDir??M),n=y.resolve(t.pluginsDir??We),r=ct(e,e),i=ct(e,t.runtimeDir??y.join(e,"data","plugin-runtime")),s=(t.selectedPluginDirs??[]).filter(m=>typeof m=="string"&&m.length>0);if(s.length===0)return{};let o=t.builtinDir===void 0?Nt():t.builtinDir,u=Qb(n,e,s,io(o)),a=Ti({pluginsDir:n,dataDir:r,builtinDir:o,ids:u}),l=Nb(a,lb(n,a),e,s);if(l.items.length===0)return wc({},l.warnings);let c=Fb(l.portableSelections,t.backend,i,ab(t.mcpComposition));Wb(c.skillClaims,l.selectedLegacySkills),bc(y.join(i,t.backend),Gb(c.details)),kc(i);let d=Hb(t.backend,l.items,c.details);return wc(d,[...l.warnings,...c.warnings])}function wc(t,e){return e.length>0?{...t,warnings:e}:t}var Vb=[{plugin:"cortex-feishu",channelPrefix:"feishu:"}];function Jb(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()??"",i=Vb.find(o=>o.plugin===r);return i?!!(r==="cortex-feishu"&&e.feishuSkillsInWeb===!0&&e.channel?.startsWith("web:"))||!!e.channel?.startsWith(i.channelPrefix):!0})}function Xb(t,e,n){return{selection:{...e},project:t.context.project??null,trackSessionId:t.session.sessionId??t.session.backendSessionId??null,executionId:n??null,...t.policy.clean?{clean:!0}:{}}}function Yb(t){return Array.isArray(t.spec.tools)?t.spec.tools:void 0}function Zb(t){return typeof t.spec.tools=="string"?t.spec.tools:void 0}function ek(t){return{mcp:{composition:void 0,servers:void 0,allowlist:t.policy.mcpToolAllowlist===void 0?void 0:Wi(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 tk(t,e,n){let r=Jb(t.spec.pluginDirs,{channel:t.context.channel,feishuSkillsInWeb:g().feishuSkillsInWeb}),i=Rc({backend:e.backend,selectedPluginDirs:r,mcpComposition:n});return{dirs:i.pluginDirs,skillDirs:i.pluginSkillDirs,servers:i.mcpServers,fingerprint:i.pluginCapabilityFingerprint,...i.warnings?{warnings:i.warnings}:{}}}var nk=["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","ANTHROPIC_BASE_URL"];function rk(t){if(!t)return{};let e={...t.sets},n=[...t.unsets];return t.baseUrl||n.push("ANTHROPIC_BASE_URL"),{sets:Object.keys(e).length>0?e:void 0,unsets:n.length>0?n:void 0}}function ik(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 sk(t,e){let n=xs(t);return n?{connection:n.connection,piAgentDir:n.agentDir}:{anthropicBaseUrl:e?.baseUrl,connection:e?.connection,...e?.configDir?{claudeConfigDir:e.configDir}:{}}}function Pc(t,e,n={}){let{route:r,executionId:i=null}=n,s=Ot(t.policy.mcpComposition),o=Xb(t,e,i),u=Ol(t.spec,{rules:Ml(t.policy.loadRules!==!1),workspace:t.policy.clean&&t.cwd?os(t.cwd):null}),a=tk(t,e,s),l=ek(t),c=e.backend==="pi"?{unsets:[...nk]}:rk(r),d=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,...t.session.requireExisting?{requireExisting:!0}:{}},model:{id:e.model,provider:d,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:u},tools:{canonical:Yb(t),rawClaude:Zb(t)},plugins:{dirs:a.dirs,skillDirs:a.skillDirs,fingerprint:a.fingerprint,...a.warnings?{warnings:a.warnings}:{}},mcp:{...l.mcp,composition:s,servers:a.servers},env:{sets:c.sets,unsets:c.unsets,pinned:t.isolation?.pinnedEnv,context:o},route:sk(e,r),flags:l.flags,context:{channel:t.context.channel,callbackSource:t.context.callbackSource??void 0,scheduleTaskId:t.context.scheduleTaskId??void 0},backend:ik(t,e),process:l.process}}var Un=p("run-attempt");function ok(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 uk(t,e){return e?t?`${t}:bg-continuation`:"bg-continuation":t||"unknown"}function ak(t,e,n,r){e.request.policy.recordCost!==!1&&Xs({...n,project:e.request.context.project||"general",trigger:uk(e.request.context.trigger,r),cost_usd:t.cost_usd,backend:e.attempt.backend,connection:t.connection??Gs(e.attempt,e.route),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(i=>Un.warn("recordCost failed:",i?.message??i))}function lk(t){if(t.length!==0)return e=>{for(let n of t)try{n.onEvent(e)}catch(r){Un.warn("required sink failed:",r?.message??r)}}}async function ck(t){for(let e of t)try{await e.onClose?.()}catch(n){Un.warn("required sink close failed:",n?.message??n)}}function dk(t){for(let e of t)try{e.onClose?.()}catch(n){Un.warn("required sink close failed:",n?.message??n)}}async function pk(t,e){let n=null,r;try{[n]=await Promise.all([t.settled,e])}catch(i){r=i;try{await e}catch(s){r=s}}if(r!==void 0)throw r;return n}function fk(){let t,e;return{promise:new Promise((r,i)=>{t=r,e=i}),resolve:t,reject:e}}function mk(t){return t==="hold"}function Oc(t){let{request:e,attempt:n,executionId:r,route:i}=t,s=Pc(e,n,{route:i,executionId:r}),o=oo({adapterBackend:n.backend,spec:s,request:e,executionId:r,selection:e.selection}),u=o?so({identity:o,spec:s,canonicalInstruction:e.benchmark?.identityDirective??"",message:e.prompt.text}):null,a=ok(e,r,o),l=[...u?[u]:[],...t.requiredSinks??[]],c=lk(l),d=e.policy.background,m=mk(d),v,E;try{v=wl.acquire(s),E=v.run({text:e.prompt.text,attachments:e.prompt.attachments},{awaitBackground:d,...c?{onNormalizedEvent:c}:{}})}catch(ue){throw dk(l),ue}let h=!1,N=fk(),Bn=(async()=>{try{for await(let ue of E.events)ue.type==="cost_record"&&ak(ue,t,a,h),t.onEvent(ue),ue.type==="foreground_result"&&(h=!0,m&&N.resolve(ue.result))}finally{await ck(l)}})(),Ii=pk(E,Bn);return Ii.then(N.resolve,N.reject),N.promise.catch(()=>{}),{engine:v,engineRun:E,spec:s,identity:o,backend:n.backend,foreground:N.promise,settled:Ii,get backendSessionId(){return v.backendSessionId},kill:()=>v.kill()}}var bt=p("run"),Mc=3;function Se(t){return t instanceof Error?t:new Error(String(t))}function hk(t){return Object.assign(new Error(`Run cancelled (${t})`),{cancelled:!0})}var $n=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=Lc();resultDeferred=Lc();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 rn({channel:e.request.context.channel,isUserInitiated:e.request.context.isUserInitiated,trigger:e.request.context.trigger,failoverResume:(n,r)=>du(e.request.selection,{provider:n,route:r},{quotaPurpose:ot(e.request.context)})!==null},(n,r,i,s,o)=>this.absorb({type:"assistant_text",text:n,phase:this.phaseValue,...this.lastAssistantModel?{model:this.lastAssistantModel}:{},...r?{blockId:r}:{},...i?{noticeLevel:i}:{},...s?{noticeAction:s}:{},...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 we[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.startingSelection();if(au(e,this.request.context)){let r=gr(_(e),yr(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)}}startingSelection(){let e=this.request.selection,n=e.backend==="claude"?{...e,connection:_(e)}:e;if(this.attemptValue={index:0,config:n},!g().accountFailover)return n;let r=cu(n,{quotaPurpose:ot(this.request.context)});return this.noteFailover(r),r?(this.attemptValue={index:0,config:r.selection},r.selection):n}noteFailover(e){let n=this.request.context.channel??"";!pu(n,e)||!e||(bt.info(`Account failover on ${n||"(no channel)"}: ${e.from} \u2192 ${e.to}`),n.startsWith("web:")&&this.notices.observe(S("notify.accountFailover",{from:vr(this.request.selection),to:vr(e.selection)}),void 0,"info"))}openAttempt(e){let n={...mr};this.liveSpend=n;let r=Oc({request:this.request,attempt:e,executionId:this.executionId,route:this.routeFor(e),onEvent:i=>{iu(n,i),this.onRunEvent(i)}});return this.current=r,this.registerAttempt(r,nn(e)),this.announcePluginWarnings(r.spec),r}routeFor(e){return no(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(i=>this.onAttemptSettled(this.attribute(i)),i=>this.finishForegroundError(Se(this.attributeError(i))))}settleBlocked(e){this.onForegroundResult(e),this.finishTerminal("rate-limited",e)}onAttemptError(e,n,r){let i=this.attributeError(r);this.notices.emitTerminalError(i),this.publishAuthOutcome(null,i,n),uu(i.message,this.request.context.channel),e.settled.catch(()=>{}),this.onForegroundError(i)}attribute(e){let n=Sr(this.attemptValue.config);return!n||e.rateLimitProvider?e:{...e,rateLimitProvider:n,rateLimitRoute:_(this.attemptValue.config)}}attributeError(e){let n=Se(e),r=Sr(this.attemptValue.config);if(r&&it(n)){let i=n;i.rateLimitProvider||(i.rateLimitProvider=r,i.rateLimitRoute=_(this.attemptValue.config))}return n}publishAuthOutcome(e,n,r=this.attemptValue.config){let i={backend:r.backend,provider:yr(r),connection:nn(r)};if(e){e.rateLimited||to(i);return}let s=_e(n?.message??"");s&&eo({...i,authType:lu(r),kind:s,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(B.MidTurnInject))return Promise.resolve("refused");let r=this.current?.engine;if(!r)return Promise.resolve("refused");let i=!1;try{i=r.steer(e,n).accepted}catch(s){bt.warn("run steer failed:",Se(s).message)}return i?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){bt.warn("run kill failed:",Se(n).message)}this.finishTerminal("cancelled",null,hk(e))}}subscribe(e){return this.observers.push(e),()=>{let n=this.observers.indexOf(e);n>=0&&this.observers.splice(n,1)}}registerAttempt(e,n){this.registry.register({channel:this.request.context.channel,executionId:this.executionId,kind:this.request.context.executionKind,kill:()=>e.kill(),backend:e.backend,account:n,run:this,trackSessionId:this.request.session.sessionId,backendSessionId:e.backendSessionId??this.request.session.backendSessionId,subagent:this.request.context.trigger==="subagent",quotaPurpose:ot(this.request.context),ownerSessionId:this.request.context.ownerSessionId??null}),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,fu(e.text),void 0,e.subagent);return;case"foreground_result":this.noticesActive=!1;return;case"phase":if(e.phase==="done")return;e.phase==="background"&&(this.phaseValue="background");break;case"engine_started":this.announceBackendSessionReset(e.backendSessionId);break;case"context_compacted":this.noticesActive&&g().notifyCompaction&&this.notices.observe(S("notify.contextCompacted"),void 0,"info");break;case"model_fallback":this.noticesActive&&this.notices.observe(S("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,Mc).join(`
80
+ `),i=n.length-Mc;this.notices.observe(S("notify.pluginsUnavailable",{detail:i>0?`${r}
81
+ ${S("notify.pluginsUnavailableMore",{n:i})}`: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(S("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(fr,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&&rt(e)>0&&(this.phaseValue="background",this.statusValue="background"))}onForegroundError(e){if(this.terminal)return;let n=Se(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 i=(Date.now()-this.startedAt)/1e3,s=n??this.tally();try{this.onTerminal({status:e,result:s,spend:this.runSpend(s),error:r,durationS:i})}catch(o){bt.warn("run terminal handler failed:",Se(o).message)}r?(this.resultDeferred.reject(r),this.settleDeferred.reject(r)):(this.resultDeferred.resolve(s),this.settleDeferred.resolve(s)),this.closeObservers()}runSpend(e){return e?ru(e):this.liveSpend??mr}fanOut(e){for(let n of[...this.observers])try{let r=n.onEvent(e);r&&typeof r.then=="function"&&r.catch(i=>this.onObserverError(i))}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){bt.warn("run observer failed:",Se(e).message)}};function Lc(){let t,e;return{promise:new Promise((r,i)=>{t=r,e=i}),resolve:t,reject:e}}var $c=new Set(["cache-refresh","manual-compact"]),gk=/tim(?:ed? ?out|eout)|\bturn idle for\b/i,yk=/exited with code|process exited|spawn|SIGSEGV|SIGABRT|killed|crash/i,Sk=[["auth",t=>!!_e(t)],["rate_limit",Re],["timeout",t=>gk.test(t)],["network",t=>it(new Error(t))],["adapter_crash",t=>yk.test(t)]];function bk(t){return Sk.find(([,e])=>e(t))?.[0]??"other"}function kk(t){return re.billingOf(t.selection)==="subscription"?"plan":"api"}function Dc(t,e){return t.tools.has(e)||t.tools.set(e,{calls:0,errors:0}),t.tools.get(e)}var Tk=new Set(["assistant_text","assistant_delta","assistant_thinking","assistant_thinking_delta","tool_use"]),_k={completed:"completed",failed:"failed",killed:"cancelled"};function Nc(t,e){if(e.type==="tool_use"){t.toolNames.set(e.toolUseId,e.name),Dc(t,e.name).calls+=1;return}let n=t.toolNames.get(e.toolUseId);n&&!e.ok&&(Dc(t,n).errors+=1)}function vk(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 wk={tool_use:Nc,tool_result:Nc,cost_record:vk,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},api_retry:t=>{t.retries+=1},subagent_end:(t,e)=>{t.subagents[_k[e.status]??"failed"]+=1}};function xk(t,e){t.firstOutputAt===null&&Tk.has(e.type)&&(t.firstOutputAt=Date.now()),wk[e.type]?.(t,e)}function Ek(){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 Bc(t){let e=Ek(),n=!1;return{observer:{onEvent:r=>{try{xk(e,r)}catch{}}},finish:r=>{n||(n=!0,Hi(i=>Pk(i,t,e,r)),r.status==="completed"&&!$c.has(t.context.trigger)&&(zn("provider_authed",t.selection.backend),zn("first_turn_completed")))}}}function jc(t,e){let{backend:n,provider:r,model:i}=e.selection,s=kk(e),o=[n,r??"",i,s].join("|");return t.turns[o]??=qi(n,r??"",i,s),t.turns[o]}function Ik(t,e){if(e.status==="rate-limited"?t.outcomes.rateLimited+=1:t.outcomes[e.status]+=1,e.status==="failed"){let n=bk(e.error?.message??"");t.failures[n]=(t.failures[n]??0)+1}}function Ak(t,e,n){Ik(t,n),t.retries+=e.retries,t.fallbacks+=e.fallbacks,n.status==="completed"&&e.firstOutputAt!==null&&(t.ttftMs[vt("ttftMs",e.firstOutputAt-e.startedAt)]+=1),t.durationS[vt("turnDurationS",n.durationS)]+=1,e.contextPct!==null&&(t.contextPctAtEnd[vt("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 Fc(t){return t.status==="rate-limited"?"failed":t.status}function Ck(t){return t.status==="cancelled"?/\((\w+)\)/.exec(t.error?.message??"")?.[1]??null:null}function Uc(t,e){for(let[n,r]of e.tools){let i=t.tools[n]??={calls:0,errors:0};i.calls+=r.calls,i.errors+=r.errors}}function Rk(t,e,n,r){let i=Ck(r);i==="user"&&(t.agent.userInterrupts+=1),i==="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[Fc(r)]+=1);let s=e.session.sessionId;s&&(t.agent.sessionTurns[s]=(t.agent.sessionTurns[s]??0)+1)}function Pk(t,e,n,r){let{trigger:i}=e.context;if(i==="subagent")return t.agent.subagents[Fc(r)]+=1,Uc(t,n);if($c.has(i)){n.compactions.manual>0&&(jc(t,e).compactions.manual+=n.compactions.manual);return}Ak(jc(t,e),n,r),Uc(t,n),Rk(t,e,n,r)}function Ok(t){return!t.benchmark?.evidenceContext||!t.session.sessionId?t:{...t,benchmarkMaxOutputTokens:t.benchmarkMaxOutputTokens??Zo(t.session.sessionId)}}function Mk(t){return dr({kind:t.context.executionKind,channel:t.context.channel,project:t.context.project,trigger:t.context.trigger,backend:t.selection.backend,billingMode:_(t.selection),sessionId:t.session.sessionId,ownerSessionId:t.context.ownerSessionId??null,label:t.prompt.text.substring(0,60),scheduleTaskId:t.context.scheduleTaskId||null})}function Lk(t,e){let{status:n,result:r,spend:i,error:s,durationS:o}=e;en({executionId:t,status:n,result:r,spend:i,error:s?{message:s.message}:null,durationS:o}),D.remove(t)}function TC(t,e){t=Ok(t);let n=Date.now(),r=Mk(t),i=Bc(t),s=new $n({request:t,observers:[...e,i.observer],executionId:r.id,registry:D,startedAt:n,onTerminal:o=>{Lk(r.id,o),i.finish(o)}});return s.start(),s}function xC(){return{systemPrompt:null,directive:null,promptTemplate:null,tools:null,pluginDirs:[],mcp:{composition:"direct",allowlist:null},backendOptions:{}}}function EC(t,e){return{systemPrompt:t.systemPrompt?En(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 IC(t,e,n={}){let r=zi(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 Dk=["user","project","local"];function Nk(t){return(t??Dk).filter(e=>e!=="project")}function CC(t){return{...t,clean:!0,hooks:!1,loadRules:!1,settingSources:Nk(t.settingSources)}}export{Vp as a,ku as b,B as c,we as d,Ir as e,Uf as f,cv as g,dv as h,pv as i,fv as j,Bf as k,mv as l,Iu as m,s_ as n,rt as o,lt as p,$u as q,Or as r,Mr as s,zu as t,Bm as u,me as v,ow as w,uo as x,Ww as y,Oa as z,Ma as A,W as B,Ee as C,kT as D,ce as E,V as F,co as G,Qe as H,po as I,Yn as J,w as K,F as L,qk as M,G as N,Vk as O,Jk as P,Xk as Q,Yk as R,Zk as S,yT as T,Ao as U,Kt as V,Ro as W,ST as X,vd as Y,OT as Z,nt as _,MT as $,LT as aa,DT as ba,Ae as ca,NT as da,D as ea,JT as fa,cr as ga,XT as ha,vE as ia,ni as ja,UE as ka,$E as la,Z as ma,Sl as na,t_ as oa,n_ as pa,Ap as qa,vp as ra,dr as sa,Go as ta,Ep as ua,Ip as va,Xo as wa,Re as xa,fe as ya,cu as za,du as Aa,P_ as Ba,En as Ca,xI as Da,EI as Ea,II as Fa,hy as Ga,Ll as Ha,RI as Ia,Zy as Ja,eS as Ka,Ti as La,uA as Ma,aA as Na,Vb as Oa,Jb as Pa,rk as Qa,Pc as Ra,TC as Sa,xC as Ta,EC as Ua,IC as Va,CC as Wa,aI as Xa,Tl as Ya,wl as Za};