@cortex-agent/server 2026.10.28 → 2026.11.17
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.
- package/LICENSE +255 -21
- package/README.md +36 -7
- package/THIRD_PARTY_NOTICES.txt +1109 -278
- package/defaults/hooks/cortex-hook-api.mjs +2 -1
- package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +23 -15
- package/dist/agent-adapter/claude/remote-mcp-proxy.js +1 -1
- package/dist/chunks/{anthropic-messages-M3SMXACA.js → anthropic-messages-M732OMEE.js} +1 -1
- package/dist/chunks/{azure-openai-responses-76YWXHSB.js → azure-openai-responses-RAKTV6JY.js} +1 -1
- package/dist/chunks/bedrock-converse-stream-WNUGNZ27.js +62 -0
- package/dist/chunks/bowser-MLGGLXTZ.js +20 -0
- package/dist/chunks/child-runner-MO5RT6FH.js +4 -0
- package/dist/chunks/chunk-2ATTYCRJ.js +4 -0
- package/dist/chunks/{chunk-PXS5SHOV.js → chunk-2ROGTDM2.js} +1 -1
- package/dist/chunks/chunk-2VVRTJQN.js +4 -0
- package/dist/chunks/{chunk-OZGBWAT2.js → chunk-2YTYYG4K.js} +1 -1
- package/dist/chunks/chunk-3CPIMAYX.js +30 -0
- package/dist/chunks/{chunk-FXDIR3SQ.js → chunk-3CZPBLB3.js} +1 -1
- package/dist/chunks/chunk-3ORG56I5.js +8 -0
- package/dist/chunks/{chunk-LEUENXI2.js → chunk-4YLAGSDM.js} +1 -1
- package/dist/chunks/{chunk-HU6UIDEJ.js → chunk-53TQNK7Z.js} +1 -1
- package/dist/chunks/{chunk-4U7XXM4W.js → chunk-5A6CA5TM.js} +1 -1
- package/dist/chunks/{chunk-PBJ5MPPX.js → chunk-5DF5WJNM.js} +1 -1
- package/dist/chunks/chunk-5PAW3DEU.js +50 -0
- package/dist/chunks/{chunk-DXBSQXJL.js → chunk-7GAYFN52.js} +1 -1
- package/dist/chunks/chunk-7GEBDPTT.js +4 -0
- package/dist/chunks/{chunk-NR6U3WIZ.js → chunk-AFTBQRPN.js} +1 -1
- package/dist/chunks/chunk-AVXDF7AG.js +4 -0
- package/dist/chunks/chunk-BDLKI2NT.js +4 -0
- package/dist/chunks/{chunk-P52RMIYX.js → chunk-BJGYGEZO.js} +1 -1
- package/dist/chunks/chunk-BUZQBTV2.js +10 -0
- package/dist/chunks/chunk-BZDIAI5M.js +125 -0
- package/dist/chunks/{chunk-A34TDMIC.js → chunk-CEGSDGYQ.js} +1 -1
- package/dist/chunks/{chunk-Q7CE3UIE.js → chunk-CK3P345X.js} +69 -69
- package/dist/chunks/{chunk-YAEVYJAR.js → chunk-EE3WT25T.js} +1 -1
- package/dist/chunks/chunk-ETIBCA2S.js +4 -0
- package/dist/chunks/{chunk-REBNWCKI.js → chunk-FP7ML72L.js} +1 -1
- package/dist/chunks/{chunk-H2FP6DG4.js → chunk-H4QZ2P3Z.js} +1 -1
- package/dist/chunks/chunk-IA6IODY3.js +4 -0
- package/dist/chunks/{chunk-D3NXKK2L.js → chunk-IKLTEWA3.js} +1 -1
- package/dist/chunks/chunk-IYVZHGUQ.js +5 -0
- package/dist/chunks/chunk-JJDEQ6N2.js +4 -0
- package/dist/chunks/chunk-JKL3AK5D.js +106 -0
- package/dist/chunks/chunk-KDPY2YA3.js +129 -0
- package/dist/chunks/{chunk-SUFW24P4.js → chunk-KUDK7GPS.js} +1 -1
- package/dist/chunks/chunk-LAWOWPZX.js +363 -0
- package/dist/chunks/chunk-LEAV3FFG.js +4 -0
- package/dist/chunks/chunk-LP72AF56.js +45 -0
- package/dist/chunks/{chunk-KENCMLRE.js → chunk-LP7T32PW.js} +1 -1
- package/dist/chunks/chunk-LQTFDC67.js +4 -0
- package/dist/chunks/{chunk-HALUQ7ZF.js → chunk-MGYYSX7Y.js} +1 -1
- package/dist/chunks/chunk-NNBSSISP.js +4 -0
- package/dist/chunks/chunk-NNTQUHLO.js +877 -0
- package/dist/chunks/{chunk-PFMEUFJ7.js → chunk-NRD57ICT.js} +1 -1
- package/dist/chunks/{chunk-QWAQHHRS.js → chunk-NXZS5PEW.js} +1 -1
- package/dist/chunks/chunk-OFEPDNRB.js +4 -0
- package/dist/chunks/{chunk-6LZK4DDH.js → chunk-P7TVR4GY.js} +1 -1
- package/dist/chunks/chunk-QEL6CMLE.js +4 -0
- package/dist/chunks/chunk-QMSSIDRQ.js +70 -0
- package/dist/chunks/chunk-QUXPMNFQ.js +4 -0
- package/dist/chunks/chunk-R52AVUQB.js +5 -0
- package/dist/chunks/chunk-R6CGBSTC.js +22 -0
- package/dist/chunks/chunk-RA2BUYI3.js +6 -0
- package/dist/chunks/chunk-RDW6FRF5.js +4 -0
- package/dist/chunks/chunk-RF4JLYBX.js +6 -0
- package/dist/chunks/{chunk-YPK2CAIZ.js → chunk-ROVKOIHF.js} +1 -1
- package/dist/chunks/chunk-RYLSRII6.js +7 -0
- package/dist/chunks/{chunk-XNSSUVT6.js → chunk-S3MR37DL.js} +1 -1
- package/dist/chunks/chunk-SAJD4EKE.js +10 -0
- package/dist/chunks/chunk-SFX7V5O2.js +10 -0
- package/dist/chunks/chunk-STCNHXPJ.js +6 -0
- package/dist/chunks/{chunk-FOJQXLL2.js → chunk-SY2HV3V5.js} +1 -1
- package/dist/chunks/chunk-T73GHMFB.js +4 -0
- package/dist/chunks/chunk-TKFFQNAP.js +19 -0
- package/dist/chunks/chunk-TMV2ZDOI.js +18 -0
- package/dist/chunks/chunk-TX46YMGI.js +5 -0
- package/dist/chunks/chunk-U23S37TT.js +6 -0
- package/dist/chunks/chunk-UT6DGZDO.js +4 -0
- package/dist/chunks/{chunk-JERCOLY3.js → chunk-V35MFAUQ.js} +4 -6
- package/dist/chunks/chunk-V6X7Y62J.js +7 -0
- package/dist/chunks/chunk-V7K3KNDM.js +4 -0
- package/dist/chunks/{chunk-NAA7GF6Q.js → chunk-VBN2JSER.js} +1 -1
- package/dist/chunks/chunk-VIMHSW6J.js +4 -0
- package/dist/chunks/chunk-VK5J556O.js +4 -0
- package/dist/chunks/chunk-VPVSKJGX.js +6 -0
- package/dist/chunks/chunk-VTL3Z2OP.js +23 -0
- package/dist/chunks/{chunk-X2GYYRVM.js → chunk-VW7TLY3P.js} +1 -1
- package/dist/chunks/chunk-W34AK4SK.js +65 -0
- package/dist/chunks/chunk-W6AKCEYF.js +8 -0
- package/dist/chunks/chunk-WBSE3EF3.js +27 -0
- package/dist/chunks/chunk-WZYS2HAK.js +4 -0
- package/dist/chunks/{chunk-UNVEZI57.js → chunk-XEBEWR6Y.js} +1 -1
- package/dist/chunks/chunk-XPPZ6Y3X.js +8 -0
- package/dist/chunks/chunk-XYSXL3KX.js +4 -0
- package/dist/chunks/chunk-YAAKL3QS.js +80 -0
- package/dist/chunks/chunk-YB5LUJHS.js +65 -0
- package/dist/chunks/chunk-Z24SBRJK.js +4 -0
- package/dist/chunks/cloudflare-workers-ai-system-one-32JCFHI3.js +1 -1
- package/dist/chunks/context-GQKWKFRM.js +4 -0
- package/dist/chunks/cost-OOO32GLC.js +5 -0
- package/dist/chunks/dist-V5FRMUFH.js +4 -0
- package/dist/chunks/easter-egg-3d-CZH7AYZ7.js +4 -0
- package/dist/chunks/{event-streams-3JSFPOTZ.js → event-streams-AVE4MSS6.js} +1 -1
- package/dist/chunks/execution-repo-XXL4FXC6.js +4 -0
- package/dist/chunks/{executions-6ARGR3IO.js → executions-BN6OLLVM.js} +1 -1
- package/dist/chunks/file-H572PL2Z.js +4 -0
- package/dist/chunks/google-generative-ai-2G4ITOZL.js +4 -0
- package/dist/chunks/google-vertex-PACHCMRZ.js +4 -0
- package/dist/chunks/init-75F4V7SK.js +4 -0
- package/dist/chunks/{install-cli-4IZCSDFZ.js → install-cli-ABBD7DO5.js} +1 -1
- package/dist/chunks/{interaction-ask-G5T3H3CG.js → interaction-ask-EE2UPR3Q.js} +1 -1
- package/dist/chunks/{interaction-plan-E5V42MUP.js → interaction-plan-C446T2GZ.js} +1 -1
- package/dist/chunks/{llama-cpp-classify-OTXZWCMW.js → llama-cpp-classify-IA2F2H7A.js} +1 -1
- package/dist/chunks/local-client-stop-5YOLXGYT.js +4 -0
- package/dist/chunks/memory-cli-5SSF6YJM.js +11 -0
- package/dist/chunks/{mistral-conversations-34F66L3O.js → mistral-conversations-VHP63CDS.js} +1 -1
- package/dist/chunks/{model-resolver-N3DTAQ2S.js → model-resolver-FVJNZ6NA.js} +1 -1
- package/dist/chunks/{node-PTK2HCDV.js → node-DAO3SX7O.js} +1 -1
- package/dist/chunks/{openai-codex-2REL6UQU.js → openai-codex-JULCKICT.js} +1 -1
- package/dist/chunks/{openai-codex-responses-ZBVHREB3.js → openai-codex-responses-EHJ4AZBE.js} +1 -1
- package/dist/chunks/{openai-completions-VVIB26SH.js → openai-completions-CRAGQFCE.js} +1 -1
- package/dist/chunks/{openai-decisions-2N6ZRPZC.js → openai-decisions-P5UX7BWY.js} +1 -1
- package/dist/chunks/{openai-responses-735XA2ZX.js → openai-responses-IZ22NVQ7.js} +1 -1
- package/dist/chunks/{openrouter-images-3IKETHAC.js → openrouter-images-W2JAMSRH.js} +1 -1
- package/dist/chunks/{pi-messages-I3E4ZFHA.js → pi-messages-MJEEQU2R.js} +1 -1
- package/dist/chunks/{radius-HXRZVBDB.js → radius-ZM7ZRMXF.js} +1 -1
- package/dist/chunks/{remote-ops-BALZYKH6.js → remote-ops-O5CR4RGA.js} +1 -1
- package/dist/chunks/runner-S6R3US24.js +4 -0
- package/dist/chunks/schedule-cli-4T4YC5V5.js +4 -0
- package/dist/chunks/slack-2CGM4SMY.js +4 -0
- package/dist/chunks/start-ui-http-3D7QNHGB.js +43 -0
- package/dist/chunks/subagent-OZGUOV3J.js +4 -0
- package/dist/chunks/{time-KEHDQT6K.js → time-P6PE52WL.js} +1 -1
- package/dist/chunks/tool-shims-IA2WELXJ.js +4 -0
- package/dist/chunks/typesafe-system-one-6ULACYD4.js +1 -1
- package/dist/chunks/ui-board-H4INJD6C.js +5 -0
- package/dist/chunks/ui-decision-6HHNROIT.js +4 -0
- package/dist/chunks/{ui-file-GVH53O3X.js → ui-file-6PLXHSTB.js} +1 -1
- package/dist/chunks/ui-view-6MDU4GXY.js +4 -0
- package/dist/chunks/virtual-modules-OFI7QKYH.js +4 -0
- package/dist/chunks/waitpoint-W5M3BE55.js +5 -0
- package/dist/chunks/workers-GTFP75MS.js +4 -0
- package/dist/client-bundle/client.mjs +44 -31
- package/dist/client-bundle/manifest.json +2 -2
- package/dist/core/pi-sdk.js +1 -1
- package/dist/domain/auth/cc-auth-cli.js +1 -1
- package/dist/domain/mcp/bundled-server.js +1 -1
- package/dist/domain/mcp/feishu/client.js +4 -0
- package/dist/entry/app.js +201 -191
- package/dist/entry/browser-cli.js +10 -10
- package/dist/entry/cli.js +1 -1
- package/dist/entry/cortex-cli.js +1 -1
- package/dist/entry/daemon.js +4 -4
- package/dist/entry/hook-cli.js +2 -2
- package/dist/entry/production-app-bootstrap.js +1 -1
- package/dist/entry/production-evidence-export-cli.js +1 -1
- package/dist/entry/signal-cli.js +2 -2
- package/dist/tui/index.js +41 -41
- package/package.json +3 -3
- package/vendor/pi/dist/core/extensions/loader.js +1 -1
- package/vendor/pi/dist/extensions/codemode/execute.js +1 -1
- package/vendor/pi-ai/bedrock.js +1 -1
- package/vendor/pi-ai/oauth-load.js +1 -1
- package/web/dist/assets/{board-math-css-BPXakv_3.js → board-math-css-BgIyUG-C.js} +1 -1
- package/web/dist/assets/index-9lyu2S6W.css +1 -0
- package/web/dist/assets/index-C-hpzey7.js +532 -0
- package/web/dist/assets/{index-WCm6wwmM.js → index-C2eMpcuI.js} +1 -1
- package/web/dist/assets/pdf-worker-DdZgk2mV.js +57 -0
- package/web/dist/assets/pdf.worker.min-Bz_KHX45.js +55 -0
- package/web/dist/index.html +2 -2
- package/web/dist/theme.css +22 -0
- package/dist/chunks/api-GM53PHIL-GFHEXXE6.js +0 -4
- package/dist/chunks/bedrock-converse-stream-5UPX4NTQ.js +0 -58
- package/dist/chunks/child-runner-3GHOWGZP.js +0 -4
- package/dist/chunks/chunk-2ZNLUY2U.js +0 -128
- package/dist/chunks/chunk-3F6WW7HR.js +0 -13
- package/dist/chunks/chunk-3OKHUVEM.js +0 -7
- package/dist/chunks/chunk-3THJYAEF.js +0 -4
- package/dist/chunks/chunk-3YHOCPQU.js +0 -10
- package/dist/chunks/chunk-4LLH5OWM.js +0 -10
- package/dist/chunks/chunk-52T37Y47.js +0 -8
- package/dist/chunks/chunk-7MU2AKNM.js +0 -4
- package/dist/chunks/chunk-AAA3UBIS.js +0 -4
- package/dist/chunks/chunk-ASYQHJVQ.js +0 -9
- package/dist/chunks/chunk-BGVHA2D4.js +0 -4
- package/dist/chunks/chunk-BKHDWCRT.js +0 -79
- package/dist/chunks/chunk-CQLH4UVX.js +0 -4
- package/dist/chunks/chunk-D6UA4BZC.js +0 -19
- package/dist/chunks/chunk-DGMNI4AO.js +0 -4
- package/dist/chunks/chunk-DHSA5ACV.js +0 -125
- package/dist/chunks/chunk-DPQPXBTP.js +0 -68
- package/dist/chunks/chunk-E7ZMYIY6.js +0 -30
- package/dist/chunks/chunk-EQITBTJC.js +0 -10
- package/dist/chunks/chunk-EXJA5RIX.js +0 -357
- package/dist/chunks/chunk-FH74NME3.js +0 -115
- package/dist/chunks/chunk-FOQ7VLIL.js +0 -17
- package/dist/chunks/chunk-J5DVLUKY.js +0 -6
- package/dist/chunks/chunk-JW2HFMTF.js +0 -4
- package/dist/chunks/chunk-KIGMAATV.js +0 -23
- package/dist/chunks/chunk-KIU5FAPY.js +0 -5
- package/dist/chunks/chunk-KIWMQPH7.js +0 -739
- package/dist/chunks/chunk-LMSQZ6TQ.js +0 -4
- package/dist/chunks/chunk-MEPASGPP.js +0 -6
- package/dist/chunks/chunk-MFAEUHMV.js +0 -28
- package/dist/chunks/chunk-NKDMKRSB.js +0 -68
- package/dist/chunks/chunk-NKXV32S6.js +0 -4
- package/dist/chunks/chunk-NVX5IPRN.js +0 -4
- package/dist/chunks/chunk-O3JW2F7D.js +0 -8
- package/dist/chunks/chunk-OISO5JXB.js +0 -4
- package/dist/chunks/chunk-OPYXNSMY.js +0 -4
- package/dist/chunks/chunk-PZMXHA6X.js +0 -9
- package/dist/chunks/chunk-QEOFEETJ.js +0 -4
- package/dist/chunks/chunk-REPYBMQS.js +0 -4
- package/dist/chunks/chunk-TAWLERZA.js +0 -4
- package/dist/chunks/chunk-TWAEABGG.js +0 -52
- package/dist/chunks/chunk-TZFLHVOQ.js +0 -7
- package/dist/chunks/chunk-UD3NMUHR.js +0 -12
- package/dist/chunks/chunk-W25TB3PU.js +0 -4
- package/dist/chunks/chunk-W5LGYSPZ.js +0 -4
- package/dist/chunks/chunk-XAJLZR7C.js +0 -28
- package/dist/chunks/chunk-XH6FMP3N.js +0 -71
- package/dist/chunks/chunk-XSRZHN63.js +0 -4
- package/dist/chunks/chunk-YG7OEPR2.js +0 -6
- package/dist/chunks/chunk-YHIWOGVL.js +0 -4
- package/dist/chunks/chunk-YZSHTWNM.js +0 -92
- package/dist/chunks/chunk-Z4H3VDHI.js +0 -4
- package/dist/chunks/client-XOGYH5UR.js +0 -4
- package/dist/chunks/config-DJSQI77S-335IXHSM.js +0 -4
- package/dist/chunks/context-VCQH5OB6.js +0 -4
- package/dist/chunks/cost-PGGFI7QJ.js +0 -5
- package/dist/chunks/dist-PUKMZ7GW.js +0 -4
- package/dist/chunks/easter-egg-3d-MO4MOEVF.js +0 -4
- package/dist/chunks/es5-VNTQPCKX.js +0 -4
- package/dist/chunks/execution-repo-ZLJTBWFC.js +0 -4
- package/dist/chunks/file-7BN7RCAY.js +0 -4
- package/dist/chunks/gateway-UCRPMR75.js +0 -36
- package/dist/chunks/google-generative-ai-2VXWLHWI.js +0 -4
- package/dist/chunks/google-vertex-UA36QP2U.js +0 -4
- package/dist/chunks/init-HA7FAQ73.js +0 -4
- package/dist/chunks/local-client-stop-SQRU7ZZM.js +0 -4
- package/dist/chunks/memory-cli-PYOILNN5.js +0 -11
- package/dist/chunks/models-L5VF4I5O-XXNJYQMQ.js +0 -4
- package/dist/chunks/runner-PLVZDGHB.js +0 -4
- package/dist/chunks/schedule-cli-OLASBBYJ.js +0 -4
- package/dist/chunks/slack-WAGSPZUX.js +0 -4
- package/dist/chunks/start-ui-http-QALT7C3P.js +0 -43
- package/dist/chunks/subagent-E3UC7ZHC.js +0 -4
- package/dist/chunks/tool-shims-Q6P6UXVC.js +0 -4
- package/dist/chunks/ui-board-4GYW6KKW.js +0 -5
- package/dist/chunks/ui-decision-U2FXSEC2.js +0 -4
- package/dist/chunks/ui-view-O7PLANT7.js +0 -4
- package/dist/chunks/virtual-modules-IDC5YKZJ.js +0 -4
- package/dist/chunks/waitpoint-2FGQBIAC.js +0 -5
- package/dist/chunks/workers-XN4PSTH6.js +0 -4
- package/vendor/aistatus/gateway-cli.js +0 -21
- package/web/dist/assets/index-BHZpFXhc.js +0 -525
- package/web/dist/assets/index-DqWMdMkh.css +0 -1
- package/web/dist/assets/pdf-worker-Hp15W1QJ.js +0 -57
- package/web/dist/assets/pdf.worker.min-DnhTvCwe.js +0 -55
|
@@ -0,0 +1,80 @@
|
|
|
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 Li,b as Mi}from"./chunk-QEL6CMLE.js";import{g as qi,h as es}from"./chunk-TJ4GQRT6.js";import{a as Wr,e as Je,f as Yr,h as Zr}from"./chunk-5A6CA5TM.js";import{a as nn,b as rn}from"./chunk-LMDWRRX4.js";import{a as it,b as xe,c as Fi,d as Wi,e as Ki,f as Hi,g as zi,h as Gi,o as Qi,q as Yi}from"./chunk-BZDIAI5M.js";import{e as Pi,f as Oi}from"./chunk-IA6IODY3.js";import{D as Xi,b as jr,d as rt,e as an,h as Di,i as Ni,j as ji,k as Ui,r as $i,s as st,t as Bi,v as Vi,y as Ji}from"./chunk-IYVZHGUQ.js";import{d as ot}from"./chunk-OFEPDNRB.js";import{h as hi,i as on}from"./chunk-ETIBCA2S.js";import{a as qr,b as ei,c as ti,d as qe,e as ni,f as ri,g as ii,h as si,i as oi,j as ai,k as ui,l as li,m as ci,n as di,p as Ei,s as us,v as ls}from"./chunk-SFX7V5O2.js";import{c as ns}from"./chunk-VTL3Z2OP.js";import{h as L}from"./chunk-4YLAGSDM.js";import{e as xi,k as vi}from"./chunk-RDW6FRF5.js";import{b as Kr,c as Hr}from"./chunk-IKLTEWA3.js";import{a as mi,g as le,i as rs,j as is,n as ss,o as Q,p as os,q as j,r as M,s as U,t as ln,u as ce,v as at,w as Y,x as ut,y as as}from"./chunk-2VVRTJQN.js";import{A as un}from"./chunk-RF4JLYBX.js";import{g as sn}from"./chunk-7GEBDPTT.js";import{a as pi,c as fi}from"./chunk-5T7IX5KN.js";import{a as Zi,f as w,g as ts}from"./chunk-BDLKI2NT.js";import{A as Ii,E as Ci,I as et,J as Ai,L as H,M as tt,N as nt,O as Ri,g as gi,h as yi,i as Ti,j as _i,k as wi}from"./chunk-JJDEQ6N2.js";import{a as $r,c as Br}from"./chunk-MGYYSX7Y.js";import{e as Qr}from"./chunk-RA2BUYI3.js";import{a as Si,c as ki,d as bi}from"./chunk-U23S37TT.js";import{d as Qe,e as Ye,f as Ze}from"./chunk-T73GHMFB.js";import{b as Ge,e as Xr}from"./chunk-NNBSSISP.js";import{a as dl}from"./chunk-V35MFAUQ.js";import{a as Xe}from"./chunk-OKRK6JPY.js";import{d as Gr,e as Vr,f as Jr}from"./chunk-OE4KH3NJ.js";import{a as zr}from"./chunk-VK5J556O.js";import{a as ae}from"./chunk-LCKVYFMD.js";import{d as Ve}from"./chunk-BUZQBTV2.js";import{b as Nr,e as h}from"./chunk-STCNHXPJ.js";import{K as d}from"./chunk-W34AK4SK.js";import{b as ze}from"./chunk-TX46YMGI.js";import{a as We}from"./chunk-Q4UGYGU5.js";import{d as _e,e as Lr}from"./chunk-AVXDF7AG.js";import{d as Ur,e as S}from"./chunk-3CPIMAYX.js";import{e as f}from"./chunk-VBN2JSER.js";import{c as Fr}from"./chunk-NXZS5PEW.js";import{d as A,e as Mr,f as ue,j as Ke,k as He,r as Dr,w as we}from"./chunk-Z24SBRJK.js";import{d as ll,e as cl}from"./chunk-WHC7AYZD.js";import{randomUUID as rS}from"node:crypto";var R;(function(t){t.MidTurnInject="mid-turn-inject",t.Usage="usage",t.BackgroundContinuation="background-continuation",t.Subagents="subagents"})(R||(R={}));var pl=[R.MidTurnInject,R.Subagents,R.BackgroundContinuation],fl=[R.MidTurnInject,R.Usage,R.Subagents],z={claude:new Set(pl),pi:new Set(fl)};import{createHash as ml}from"crypto";function hl(){return h().streamDeltas}var gl={direct:[ni],none:[ri]};function yl(t,e){let n=t.mcpConfigPaths?[...t.mcpConfigPaths]:[...gl[e]];t.supplementalMcpConfigPath&&e==="direct"&&n.push(t.supplementalMcpConfigPath);let r=lt(t),i=t.mcpToolAllowlist??void 0;return mi(n,i,void 0,r)}function Sl(t){let e=["-p","--input-format","stream-json","--output-format","stream-json","--verbose","--replay-user-messages"];return(t.streamDeltas??hl())&&e.push("--include-partial-messages"),h().showThinking&&e.push("--thinking-display","summarized"),e}function lt(t){if((t.mcpComposition??"direct")==="none")return[];let n=["cortex-core","cortex-ext"];return t.isUserInitiated&&n.push("cortex-interaction-bridge"),t.teamLead&&n.push("cortex-workers"),t.teamWorker&&n.push("cortex-worker-report"),t.loadSlackMcp&&n.push("cortex-slack"),t.loadFeishuMcp&&n.push("cortex-feishu"),t.loadWebMcp&&n.push("cortex-web"),n}function kl(t){if((t.mcpComposition??"direct")==="none")return[];let e=t.mcpToolAllowlist??void 0;return(e===void 0?lt(t).includes("cortex-core"):Gr.every(r=>e.includes(r)))?ci():[]}function bl(t,e){let n=(t.tools||oi).split(",").map(i=>i.trim()).filter(i=>i&&!li.has(i)&&!(e&&ui.has(i))),r=[...e?ai:[],...kl(t)];return[...new Set([...n,...r])].join(",")}function Tl(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 _l(t,e){for(let[n,r]of e)r&&t.push(n,r)}function wl(t,e){_l(t,[["--system-prompt",e.systemPrompt],["--append-system-prompt",e.appendSystemPrompt],["--model",e.model],["--effort",e.thinking],["--agent",e.claudeAgent]])}function xl(t,e,n){for(let r of n??[])t.push(e,r)}function vl(t,e){e.disableSkills&&t.push("--disable-slash-commands"),e.settingSources&&t.push("--setting-sources",e.settingSources.join(","))}function El(t,e){let n={hooks:t.disableHooks?{}:Ei(e)};return t.outputStyle&&(n.outputStyle=t.outputStyle),t.omitGitContext&&(n.includeGitInstructions=!1),n}function Il(t,e){e.needsResume?t.push("--resume",e.sessionId):t.push("--session-id",e.sessionId)}function fs(t){let e=t.mcpComposition??"direct",r=e==="direct"&&!!t.isUserInitiated,i=yl(t,e),s=Sl(t),o=bl(t,r);return Tl(s,i,e,o),wl(s,t),xl(s,"--plugin-dir",t.pluginDirs),vl(s,t),s.push("--settings",JSON.stringify(El(t,o))),Il(s,t),s}var Cl=["CORTEX_PROFILE","CORTEX_MODE","CORTEX_PROJECT","CORTEX_SESSION_NAME","CORTEX_BACKEND","CORTEX_MODEL","CORTEX_PROVIDER","CORTEX_THINKING","CORTEX_CONNECTION"];function ve(t,e,n){n&&(t[e]=n)}function Al(t){t.MCP_TOOL_TIMEOUT=String(183e4),t.CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT=String(183e4),t.CLAUDE_CODE_DISABLE_AUTO_MEMORY="1",t.DISABLE_AUTOUPDATER="1",t.CLAUDE_CODE_DISABLE_OFFICIAL_MARKETPLACE_AUTOINSTALL="1",t.CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL="1",t.CLAUDE_CODE_AUTO_CONNECT_IDE="false",t.CLAUDE_CODE_DISABLE_POLICY_SKILLS="1",t.CLAUDE_CODE_DISABLE_TERMINAL_TITLE="1"}function Rl(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 Pl(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),Rl(t),Al(t)}function Ol(t,e,n){n||(t.SLACK_CHANNEL=e,t.FEISHU_CHANNEL=e,t.SLACK_BOT_TOKEN=process.env.SLACK_BOT_TOKEN)}function Ll(t,e,n){for(let[r,i]of Object.entries(e??{}))t[r]=i;for(let r of n??[])delete t[r]}var Ml=["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN"];function Dl(t){return`sha256:${ml("sha256").update(t).digest("hex").slice(0,8)}`}function ds(t,e,n){return e.unsetEnv?.includes(t)?null:e.routeEnv?.[t]??n}function ps(t,e){return t===null?"deleted":t===void 0?"inherited":e(t)}function ms(t){let e=ps(ds("ANTHROPIC_BASE_URL",t,t.anthropicBaseUrl||void 0),i=>`url:${i}`),n=Ml.map(i=>`${i}=${ps(ds(i,t),Dl)}`),r=[...t.connection?[`connection:${t.connection}`]:[],...t.configDir?[`config:${t.configDir}`]:[]];return[e,...n,...r].join(" ")}function Nl(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}}function jl(t,e){for(let n of Cl)delete t[n];for(let[n,r]of Object.entries(Nl(e)))ve(t,n,r)}var Ul=64,$l=64;function Bl(t,e){t.CLAUDE_CONFIG_DIR=e??He;let n=h().maxContextTokens;n!==null&&(t.CLAUDE_CODE_AUTO_COMPACT_WINDOW=String(n))}function Fl(){let t=yi.get();return{pi:wi.peekModels().map(e=>({provider:e.provider,id:e.model})),claude:t.length>0?gi(t):null}}var hs=Fl;function gs(t){hs=t}function Wl(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}function cn(){let t={},e=hs(),n=hi(e.pi.slice(0,Ul));if(n.length>0&&(t.CORTEX_SUBAGENT_PI_MODELS=on(n)),e.claude&&!Wl(e.claude,Xe)){let r=e.claude.slice(0,$l).map(i=>({backend:"claude",id:i}));t.CORTEX_SUBAGENT_CLAUDE_MODELS=on(r)}return t}function Kl(t){for(let[e,n]of Object.entries(cn()))ve(t,e,n)}function ys(t,e,n,r,i,s,o,a,u,l){let c=a?{...a}:{...process.env};return Pl(c,!a),Ol(c,t,!!a),c.CORTEX_SESSION_ID=o?.trackSessionId??e,ve(c,"CORTEX_CALLBACK_SOURCE",n),ve(c,"CORTEX_SCHEDULE_TASK_ID",r),ve(c,"ANTHROPIC_BASE_URL",i),a||Bl(c,l),Kl(c),Ll(c,s,u),jl(c,o),c}import{spawn as zd}from"child_process";import{createInterface as Gd}from"readline";function LS(){return h().bgContinuation}var Hl=9e4,zl=18e5;function Ss(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 ks(){return Ss("CORTEX_BG_GRACE_S",Hl)}function bs(){return Ss("CORTEX_BG_WAIT_MAX_S",zl)}function Ee(t){return t?(t.pendingBackgroundTasks??0)+(t.undeliveredBackgroundTasks??0):0}var Gl={set(t,e){let n=setTimeout(t,e);return n.unref?.(),n},clear(t){clearTimeout(t)}};function dn(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 Vl(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 de=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??Gl,this.graceMs=n.graceMs??ks(),this.maxWaitMs=n.maxWaitMs??bs()}sink(){return{...Jl(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 Ee(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&&Ee(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=Vl(e);if(n&&this.port.push(n),this.port.push({type:"background_result",result:e}),this.acc=dn(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 Jl(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"})}}}function Xl(t,e){let n=t.findIndex(r=>r.text===e);if(n!==-1)return t.splice(n,1)[0]}var pe=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 Xl(e.pending,n)?.id??this.nextId()}nextId(){return`${this.idPrefix}-${++this.seq}`}};function fe(){let t,e;return{promise:new Promise((r,i)=>{t=r,e=i}),resolve:t,reject:e}}function Ql(t){throw new Error(`Unhandled NormalizedEvent: ${JSON.stringify(t)}`)}function Ts(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 Ie(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:Ts(t)}:{type:"foreground_result",result:Ts(t)};case"subagent_activity":return{...t,phase:e};case"subagent_end":return{...t,phase:e};case"error":return{...t};default:return Ql(t)}}var me=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 he(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}function _s(t){let e=t.map(he);if(e.some(r=>r===null))return null;let n=e.reduce((r,i)=>r+i,0);return Number.isSafeInteger(n)?n:null}function pn(t){return{promptTokens:_s([t?.input,t?.cacheCreation,t?.cacheRead]),cachedTokens:_s([t?.cacheRead])}}function ws(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=jr("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 xs(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=pn(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 ct=class{backend="claude";identity;session;spec;injections;started=!1;constructor(e,n,r){this.session=e,this.spec=n,this.identity=r,this.injections=new pe(e,"claude-run-inj")}get backendSessionId(){return this.session.sessionId}run(e,n){let r=new me,i=this.injections.beginRun(r);this.started||(r.push(Ie({type:"session_started",sessionId:this.session.sessionId},"foreground")),this.started=!0);let s=fe(),o=fe(),a=new de(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(a),this.session.setBackgroundTurnSink(a.sink());let u=l=>{n.onNormalizedEvent?.(l),l.type!=="turn_complete"&&r.push(Ie(l,"foreground"))};return this.driveRun(e,u,r,a,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()}}async driveRun(e,n,r,i,s){let o;try{o=await this.session.sendMessage(e.text,{attachments:e.attachments,...ws(n)}),xs(n,o,this.session)}catch(a){a?.cancelled||n({type:"error",message:String(a?.message??a),fatal:!0}),r.push({type:"phase",phase:"done",pendingBackground:0,undeliveredBackground:0}),r.close(),s.reject(a);return}r.push({type:"foreground_result",result:o}),i.start(o)}steer(e,n){return this.injections.steer(e,n)}ingestExternal(e){return this.injections.pushOutOfBand(e)}respondToDialog(e,n){return!1}compact(){return this.session.compact()}async close(){this.session.close()}kill(){return this.session.kill()}isAlive(){return this.session.isAlive()}};import*as Ps from"crypto";import{createHash as Yl}from"node:crypto";import B from"node:fs";import Ae from"node:path";import{fileURLToPath as Zl}from"node:url";import ge from"node:fs";import $ from"node:path";function vs(t,e){let n=$.resolve(t);for(;;){if(ge.existsSync(n)&&ge.lstatSync(n).isSymbolicLink())throw new Error(`${e} has a symlink ancestor: ${n}`);let r=$.dirname(n);if(r===n)return;n=r}}function E(t,e){let n=$.resolve(t);if(vs(n,e),ge.mkdirSync(n,{recursive:!0,mode:448}),vs(n,e),ge.realpathSync(n)!==n)throw new Error(`${e} is not a physical path: ${n}`);ge.chmodSync(n,448)}function Ce(t,e){let n=$.resolve(t),r=$.resolve(e),i=$.relative(n,r);if(i===".."||i.startsWith(`..${$.sep}`)||$.isAbsolute(i))return r;try{return $.join(ge.realpathSync(n),i)}catch{return r}}var ql=f("claude-mcp-config"),ec=Zl(new URL("./remote-mcp-proxy.js",new URL("dist/agent-adapter/claude/mcp-config.js",__cortexPackageRoot).href));function Is(t,e){return t<e?-1:t>e?1:0}function fn(t){return Object.fromEntries(t.sort(([e],[n])=>Is(e,n)))}function tc(t){return{command:t.command,args:[...t.args],env:fn(Object.entries(t.env)),cwd:t.cwd}}function nc(t){return{type:t.type==="streamable-http"?"http":"sse",url:t.url,headers:fn(Object.entries(t.headers))}}function rc(t){return t.type==="stdio"?tc(t):nc(t)}function ic(t){let e=t.map(n=>[n.name,rc(n)]).sort(([n],[r])=>Is(n,r));return`${JSON.stringify({mcpServers:Object.fromEntries(e)},null,2)}
|
|
5
|
+
`}function dt(t){return Yl("sha256").update(t,"utf8").digest("hex")}function sc(t){return(t&63)===0}function Cs(t){let e=B.lstatSync(t);if(!e.isFile()||e.isSymbolicLink())throw new Error(`Claude supplemental MCP file is invalid: ${t}`);if(!sc(e.mode&511))throw new Error(`Claude supplemental MCP file is not private: ${t}`);return B.readFileSync(t,"utf8")}function mn(t,e){if(Ae.basename(t)!==`${e}.json`)throw new Error(`Claude supplemental MCP file identity mismatch: ${t}`);if(dt(Cs(t))!==e)throw new Error(`Claude supplemental MCP file identity mismatch: ${t}`)}function Es(t,e){if(Cs(t)!==e)throw new Error(`Claude supplemental MCP file content mismatch: ${t}`);mn(t,dt(e))}function oc(t,e){let n=`${t}.tmp.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2,8)}`;B.writeFileSync(n,e,{encoding:"utf8",mode:384}),B.chmodSync(n,384),B.renameSync(n,t),B.chmodSync(t,384)}function ac(t){try{let e=new Date;B.utimesSync(t,e,e)}catch{}}function As(t,e,n){E(t,n);let r=Ae.join(t,`${dt(e)}.json`);if(B.existsSync(r))return Es(r,e),ac(r),r;try{oc(r,e)}catch(i){if(!B.existsSync(r))throw i;Es(r,e)}return r}function uc(t,e){let n=Ae.join(e,"claude-mcp-proxies"),r=`${JSON.stringify({type:t.type,url:t.url,headers:fn(Object.entries(t.headers))})}
|
|
6
|
+
`,i=As(n,r,"Claude remote MCP runtime");return{name:t.name,type:"stdio",command:process.execPath,args:[ec,i],env:{},cwd:n}}function lc(t,e){return t.flatMap(n=>{if(n.type==="stdio")return[n];try{return[uc(n,e)]}catch(r){return ql.warn(`Skipping Claude remote MCP '${n.name}': ${r.message}`),[]}})}function Rs(t,e={}){let n=Ce(A,e.runtimeDir??Ae.join(A,"data","plugin-runtime"));E(n,"Claude MCP runtime");let r=ic(lc(t,n)),i=dt(r),s=Ae.join(n,"claude-mcp");return{path:As(s,r,"Claude MCP runtime"),identity:i}}function cc(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 dc(t){return{mcpComposition:t.mcpComposition,mcpConfigPaths:t.mcpConfigPaths,mcpToolAllowlist:t.mcpToolAllowlist,supplementalMcpConfigPath:t.supplementalMcpConfigPath??null,disableHooks:t.disableHooks===!0,disableSkills:t.disableSkills===!0,settingSources:t.settingSources,...t.omitGitContext?{omitGitContext:!0}:{},streamDeltas:t.streamDeltas,isUserInitiated:t.isUserInitiated===!0,teamLead:t.teamLead===!0,teamWorker:t.teamWorker===!0}}function pc(t){let{channel:e,options:n}=t;return{...cc(n),...dc(n),needsResume:t.needsResume,sessionId:t.sessionId,loadSlackMcp:e.startsWith("slack:"),loadFeishuMcp:e.startsWith("feishu:"),loadWebMcp:e.startsWith("web:")}}function Os(t){let e=pc(t),{options:n}=t,r=ys(t.channel,t.sessionId,n.callbackSource||null,n.scheduleTaskId||null,n.anthropicBaseUrl,n.routeEnv,n.context,n.pinnedEnv,n.unsetEnv,n.configDir);return r[pi]=fi(lt(e)),{args:fs(e),env:r}}function fc(t){if(!t||t.length===0)return null;let e=t.map(n=>Ge("claude",n)).filter(n=>typeof n=="string");return e.length?e.join(","):null}function mc(t,e){return!t.mcp.servers||e!=="direct"?null:Rs(t.mcp.servers)}function hc(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??fc(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 gc(t,e){let n=mc(t,e);return{anthropicBaseUrl:t.route.anthropicBaseUrl,connection:t.route.connection,configDir:t.route.claudeConfigDir,routeEnv:t.env.sets,unsetEnv:t.env.unsets,cwd:ue(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 hn(t){let e=rt(t.mcp.composition);return{...hc(t),...gc(t,e)}}function gn(t){let e=t.context.channel??t.env.sets?.SLACK_CHANNEL??t.engineKey;return{channel:e,sessionKey:t.engineKey||e,sessionId:t.resume.backendSessionId||Ps.randomUUID(),needsResume:t.resume.resume,options:hn(t)}}import{closeSync as yc,existsSync as Sc,fstatSync as kc,openSync as bc,readSync as Tc}from"node:fs";import*as Ms from"path";function yn(t,e){let n=t.replace(/[/.]/g,"-");return Ms.join(ti,n,`${e}.jsonl`)}function Ds(t,e,n=Sc){return t&&n(e)}var Ls=Buffer.from('"cost-state"'),_c=1<<20;function wc(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 xc(t,e){let n=t.lastIndexOf(Ls);for(;n!==-1;){let r=t.lastIndexOf(10,n)+1,i=t.indexOf(10,n),s=wc(t.toString("utf8",r,i===-1?t.length:i),e);if(s!==null)return s;if(r===0)return null;n=t.lastIndexOf(Ls,r-1)}return null}function Ns(t,e,n=_c){let r;try{r=bc(t,"r")}catch{return 0}try{let i=kc(r).size,s=Buffer.alloc(0);for(;i>0;){let o=Math.max(0,i-n),a=Buffer.alloc(i-o);Tc(r,a,0,a.length,o);let u=s.length?Buffer.concat([a,s]):a,l=o===0?-1:u.indexOf(10);if(o>0&&l===-1){s=u,i=o;continue}let c=xc(u.subarray(l+1),e);if(c!==null)return c;s=u.subarray(0,Math.max(l,0)),i=o}return 0}catch{return 0}finally{yc(r)}}import*as P from"node:fs";import*as Bs from"node:path";import{isUtf8 as Oc}from"node:buffer";import{closeSync as vc,fstatSync as Ec,openSync as Ic,readSync as Cc}from"node:fs";var Ac=512*1024,js=new Map;function mk(t,e=Date.now()){js.set(t,e)}function Rc(t){let e=t.split(`
|
|
7
|
+
`);for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.includes('"timestamp"'))try{let 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 Pc(t){let e;try{e=Ic(t,"r")}catch{return null}try{let n=Ec(e),r=Math.max(0,n.size-Ac),i=Buffer.alloc(n.size-r);Cc(e,i,0,i.length,r);let s=i.toString("utf8");return r>0&&(s=s.slice(s.indexOf(`
|
|
8
|
+
`)+1)),Rc(s)??n.mtimeMs}catch{return null}finally{vc(e)}}function Us(t,e){let n=Pc(t),r=js.get(e)??null;return n===null?r:r===null?n:Math.max(n,r)}var Fs=f("claude-bridge"),Ws="[Old tool result content cleared]",Lc=10,Mc=65*6e4,Dc=1e5,Nc=4e4,$s=Buffer.from('"compact_boundary"'),jc={readFileSync:t=>P.readFileSync(t),statSync:t=>P.statSync(t),writeFileSync:(t,e,n)=>P.writeFileSync(t,e,{mode:n}),appendFileSync:(t,e)=>P.appendFileSync(t,e),renameSync:(t,e)=>P.renameSync(t,e),unlinkSync:t=>P.unlinkSync(t)};function kn(t){try{let e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function Ks(t){if(!t.includes('"compact_boundary"'))return!1;let e=kn(t);return e?.type==="system"&&e.subtype==="compact_boundary"}function Hs(t){for(let e=t.length-1;e>=0;e--)if(Ks(t[e]))return e+1;return 0}function zs(t){let e=t?.message;return e!==null&&typeof e=="object"?e:null}function Uc(t){if(t?.type!=="user"||t.isSidechain===!0)return[];let e=zs(t)?.content;return Array.isArray(e)?e.filter(n=>n!==null&&typeof n=="object"&&n.type==="tool_result"):[]}function $c(t,e){let n=[];for(let r=e;r<t.length;r++){if(!t[r].includes('"tool_result"'))continue;let i=kn(t[r]);for(let s of Uc(i))n.push({line:r,record:i,block:s})}return n}var Bc=JSON.stringify(Ws).length;function Fc(t){let e=JSON.stringify(t.content??"").length-Bc;return e<=0?0:(t.content=Ws,e)}function Wc(t,e=Lc){let n=$c(t,Hs(t)),r=new Map,i=0,s=0;for(let a of n.slice(0,Math.max(0,n.length-e))){let u=Fc(a.block);u!==0&&(r.set(a.line,a.record),i++,s+=u)}return{lines:t.map((a,u)=>r.has(u)?JSON.stringify(r.get(u)):a),clearedCount:i,charsRemoved:s}}function Sn(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}function Kc(t){if(t?.type!=="assistant"||t.isSidechain===!0)return null;let e=zs(t)?.usage;if(e===null||typeof e!="object")return null;let n=Sn(e.input_tokens)+Sn(e.cache_read_input_tokens)+Sn(e.cache_creation_input_tokens);return n>0?n:null}function Hc(t){let e=Hs(t);for(let n=t.length-1;n>=e;n--){if(!t[n].includes('"usage"'))continue;let r=Kc(kn(t[n]));if(r!==null)return r}return null}function zc(t){let e=t.lastIndexOf($s);for(;e!==-1;){let n=t.lastIndexOf(10,e)+1,r=t.indexOf(10,e);if(Ks(t.toString("utf8",n,r===-1?t.length:r)))return n;if(n===0)return 0;e=t.lastIndexOf($s,n-1)}return 0}function Gc(t,e,n){if(!h().coldResumeClearToolResults)return"disabled";let r=Us(t,e);return r===null||n-r<=Mc?"warm":null}function Vc(t,e){try{return e.readFileSync(t)}catch{return null}}function Jc(t){let e=t.split(`
|
|
9
|
+
`),n=Hc(e);if(n===null||n<Dc)return"small-context";let r=Wc(e);return r.charsRemoved<Nc?"too-little":r}function Xc(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 Qc(t,e,n,r){try{Xc(t,e,n.lines.join(`
|
|
10
|
+
`),r)}catch(i){return Fs.warn(`Cold-resume tool-result clearing failed for ${Bs.basename(t)}, resuming it as is: ${i.message}`),{cleared:!1,reason:"write-failed"}}return{cleared:!0,clearedCount:n.clearedCount,charsRemoved:n.charsRemoved}}function Yc(t,e){let n=Vc(t,e);if(!n)return{cleared:!1,reason:"unreadable"};let r=zc(n),i=n.subarray(r);if(!Oc(i))return{cleared:!1,reason:"unreadable"};let s=Jc(i.toString("utf8"));return typeof s=="string"?{cleared:!1,reason:s}:Qc(t,n.subarray(0,r),s,e)}function Gs(t,e,n=Date.now(),r=jc){let i=Gc(t,e,n),s=i?{cleared:!1,reason:i}:Yc(t,r);return s.cleared&&Fs.info(`Cleared ${s.clearedCount} old tool results before cold resume: ${e.substring(0,8)} (-${s.charsRemoved} chars)`),s}import{readFileSync as ed}from"fs";var Zc={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 Vs(t,e){let n=Zc[t];return n?n(e):JSON.stringify(e)}import*as Js from"path";function qc(t){if(t.length===0)return"";let e=t.map(n=>`${n.name} (${n.reason})`).join(`
|
|
11
|
+
`);return`[${t.length} attachment(s) the user sent could NOT be downloaded and are unavailable to you. Say so rather than answering as if they had not been sent:
|
|
12
|
+
${e}
|
|
13
|
+
]
|
|
14
|
+
|
|
15
|
+
`}function bn(t){let e=t.path.replace(/\\/g,"/"),n=t.name?.trim();return n&&n!==Js.basename(e)?`${e} (${n})`:e}function Z(t,e,n=[]){if(e.length===0&&n.length===0)return t;let r=e.filter(a=>nn.has(a.mimeType)),i=e.filter(a=>rn.has(a.mimeType)),s=e.filter(a=>!nn.has(a.mimeType)&&!rn.has(a.mimeType)),o="";if(r.length>0){let a=r.map(bn).join(`
|
|
16
|
+
`);o+=`[User sent ${r.length} image(s). Read these files to view them:
|
|
17
|
+
${a}
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
`}if(i.length>0){let a=i.map(bn).join(`
|
|
21
|
+
`);o+=`[User sent ${i.length} video(s). Read these files to view them:
|
|
22
|
+
${a}
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
`}if(s.length>0){let a=s.map(bn).join(`
|
|
26
|
+
`);o+=`[User sent ${s.length} file(s). Read these files:
|
|
27
|
+
${a}
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
`}return o+=qc(n),o+(t||(e.length>0?"Please analyze the attached file(s).":""))}function Xs(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 Qs(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 Tn(){return{messageId:null,model:null,textBlockId:null,thinkingBlockId:null}}function td(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 nd(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 rd(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 Ys(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"?(td(n,e),null):n.type==="content_block_start"?(nd(n,e),null):n.type==="content_block_delta"?rd(n,e):null}function Zs(t){let e=t.textBlockId;return t.textBlockId=null,e}function qs(t){let e=t.thinkingBlockId;return t.thinkingBlockId=null,e}function id(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||"?"}: ${Vs(n.name,n.input||{})}`);return e.length?e.join(`
|
|
31
|
+
`):null}function sd(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(`
|
|
32
|
+
`):null}function od(t){let e=t.result||"",n=t.total_cost_usd!=null?`$${t.total_cost_usd.toFixed(4)}`:"?",r=t.duration_ms!=null?`${(t.duration_ms/1e3).toFixed(1)}s`:"?";return`[result] turns=${t.num_turns}, cost=${n}, duration=${r}
|
|
33
|
+
\u2192 ${e}`}var ad={assistant:id,user:sd,result:od};function _n(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=ad[e];return n?n(t):null}function ud(t,e){return!t||!e||t===e?t:t.length<300&&t.length<e.length*.5?e+`
|
|
34
|
+
|
|
35
|
+
---
|
|
36
|
+
`+t:t}function ld(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 pt(t,e,n,r,i,s,o,a,u){let l=null,c=null,p=!1,m=null,_=e;if(t){t.total_cost_usd!=null&&(l=t.total_cost_usd),t.num_turns!=null&&(c=t.num_turns);let O=ld(t);if(O&&(p=!0,m=O),typeof t.session_id=="string"&&t.session_id!==e&&(_=t.session_id),t.is_error&&!p){let tn=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(tn)}}}let x=ud(a,u),g={sessionId:_,total_cost_usd:l,num_turns:c,rateLimited:p,rateLimitMessage:m,planFilePath:i,enteredPlanMode:s,exitedPlanMode:o,askUserQuestions:[],finalOutput:x||null};return p?{resolved:!0,value:g}:n!==0?{resolved:!1,error:new Error(r||`claude exited with code ${n}`)}:{resolved:!0,value:g}}function cd(t){if(typeof t!="string")return null;let e=t.trim();return e?e.replace(/^\.\//,"").replace(/\\/g,"/").replace(/\/+$/,""):null}function dd(){let t=[];try{let e=JSON.parse(ed(ii,"utf8")),n=cd(e?.plansDirectory);n&&t.push(n)}catch{}for(let e of si)t.includes(e)||t.push(e);return t}var pd=dd();function eo(t){if(typeof t!="string"||!t)return!1;let e=t.replace(/\\/g,"/");return pd.some(n=>e.includes(`${n}/`)||e.endsWith(`/${n}`))}var wn=new Map;function to(t,e){!t||!e||wn.set(t,e)}function ft(t){t&&wn.delete(t)}function Ck(t){return t&&wn.get(t)||null}var fd=new Set(["completed","failed","killed"]),Re=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(`
|
|
37
|
+
`):"";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"||!fd.has(i)?null:(this.subagentTasks.delete(n),{parentToolUseId:r,status:i})}};function no(t){return t?.type==="result"&&t?.origin?.kind==="task-notification"}function xn(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 lo,mkdirSync as vd}from"fs";import{Writable as Ed}from"stream";import*as An from"path";var md=f("claude-bridge");function hd(t,e,n,r){e.name==="Write"&&eo(e.input?.file_path)&&(t.planFilePath=e.input.file_path,to(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){md.warn("onToolUse threw:",i.message)}}function gd(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=Zs(r)??void 0,a=r.messageId===e.message?.id?r.model:null;t.onAssistantMessage?.(n.text,o,s??a)}function yd(t,e,n,r){if(r)return;let i=qs(n)??void 0;!h().showThinking||typeof e.thinking!="string"||!e.thinking||t.onAssistantThinking?.(e.thinking,i)}function ro(t,e,n,r,i){i?t.subagentTurnCount+=1:t.turnCount+=1;let s={tool_use:o=>hd(t,o,r,i),text:o=>gd(t,e,o,n,i),thinking:o=>yd(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})}import Sd from"node:path";var vn=class{byPair=new Map;register(e,n){let r=n.map(o=>Sd.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()]}},io=new vn;var kd=f("claude-bridge");function En(t,e){try{e()}catch(n){kd.warn(`${t} threw:`,n.message)}}function bd(t,e){if(e.subtype!=="compact_boundary"||!t.onCompact)return;let n=e.compact_metadata??{};En("onCompact",()=>t.onCompact({trigger:typeof n.trigger=="string"?n.trigger:"auto",preTokens:typeof n.pre_tokens=="number"?n.pre_tokens:void 0}))}function Td(t,e){let n=Xs(e);!n||!t.onModelFallback||En("onModelFallback",()=>t.onModelFallback({originalModel:n.originalModel,fallbackModel:n.fallbackModel}))}function _d(t,e){let n=Qs(e);!n||!t.onApiRetry||En("onApiRetry",()=>t.onApiRetry({attempt:n.attempt,error:n.error}))}var wd=[bd,Td,_d];function so(t,e){if(!(!t||e?.type!=="system"))for(let n of wd)n(t,e)}function xd(t){return t>=1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:t>=1024?`${Math.round(t/1024)} KB`:`${t} B`}function oo(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}, ${xd(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 In(t){return typeof t.content=="string"?t.content:Array.isArray(t.content)?t.content.map(oo).join(`
|
|
38
|
+
`):t.content==null?"":oo(t.content)}function ao(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 uo(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 I=f("claude-bridge");function Cn(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 Id(t){return t.type==="assistant"?"assistant":t.type==="user"&&!t.isReplay?"tool_result":null}function Cd(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 Ad(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}
|
|
39
|
+
${i}`,n===e)return r;if(n.length>=e.length)return 0}return 0}function Rd(t){try{return JSON.parse(t)}catch{return}}var mt=class{host;currentTurn=null;streamDeltaState=Tn();contextUsageTracker;bgTracker=new Re;backgroundTurnSink=null;pendingInjections=[];injectionAck=null;injectionContinuationArmed=!1;cumulativeCostUsd=0;lastModelName=null;lastTokenUsage=null;constructor(e,n){this.host=e,this.contextUsageTracker=n}notifyBgInterrupted(e=!1){let n=this.backgroundTurnSink;if(!n)return;this.backgroundTurnSink=null;let r=this.pendingInjections.length>0||this.injectionContinuationArmed;if(!e&&!this.bgTracker.hasPending()&&!this.bgTracker.continuationArmed&&!r)return;let 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){I.warn("bg-interrupted sink onResult threw:",s.message)}}createTurnStreams(e){if(!this.host.captureTranscriptLogs){let u=()=>new Ed({write(l,c,p){p()}});return{rawStream:u(),txtStream:u(),pairKey:null,releaseCapture:null}}vd(qe,{recursive:!0});let n=Fr(),r=An.join(qe,`claude-output-${n}.jsonl`),i=An.join(qe,`claude-output-${n}.txt`),s=lo(r,{flags:"a"}),o=lo(i,{flags:"a"}),a=io.register(n,[r,i]);return o.write(`=== Cortex session started at ${new Date().toISOString()} ===
|
|
40
|
+
=== channel=${this.host.channel}, session=${this.host.sessionId} ===
|
|
41
|
+
|
|
42
|
+
`),o.write(`[user-input] ${e}
|
|
43
|
+
|
|
44
|
+
`),{rawStream:s,txtStream:o,pairKey:n,releaseCapture:a}}registerTurn(e,n,r,i){ft(this.host.sessionId),this.displaceOpenTurn(),this.currentTurn={resolve:e,reject:n,...ao(r),...uo(i)}}displaceOpenTurn(){let e=this.currentTurn;if(!e||e.spontaneous)return;I.info(`New turn on ${this.host.sessionId.substring(0,8)} while a user turn is open; settling the open one`),e.txtStream.write(`[displaced by a new turn \u2014 the loop result goes to that turn]
|
|
45
|
+
`);let n=pt(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){I.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=Z(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(),I.info(`Injected mid-turn message into ${this.host.sessionId.substring(0,8)} (${n.length} chars)`),!0}handleReplayEcho(e){let n=Cd(e);if(n===null)return;let r=Ad(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){let r=e.origin?.kind==="task-notification"||n.startsWith("<task-notification>");this.currentTurn&&!r&&(this.currentTurn.promptConsumed=!0)}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){I.warn("injection onDelivered threw:",o.message)}}continuationCallbacks(){return{resolve:e=>this.deliverContinuation(n=>n.onResult(e)),reject:e=>I.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:he(n.input_tokens),output:he(n.output_tokens),cacheCreation:he(n.cache_creation_input_tokens),cacheRead:he(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,...pn(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.currentTurn=null,this.host.clearTurnIdleTimer();let i=_n(n);i&&e.txtStream.write(i+`
|
|
46
|
+
`),e.txtStream.write(`
|
|
47
|
+
=== Turn finished at ${new Date().toISOString()} ===
|
|
48
|
+
`),e.rawStream.end(),e.txtStream.end(),e.releaseCapture?.(),e.releaseCapture=null,r.resolved?e.resolve(r.value):e.reject(r.error)}handleResultEvent(e,n){e.resultData={...n,total_cost_usd:this.captureTurnAccounting(n)};let r=pt(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=Cn(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:"",a=an(s.content);try{e.onToolResult(o,In(s),s.is_error===!0,i,a.length?a:void 0)}catch(u){I.warn("onToolResult threw:",u.message)}}}handleOrphanSubagentLine(e){let n=Cn(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(a=>a.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:"",a=an(s.content);this.deliverContinuation(u=>u.onToolResult?.(o,In(s),s.is_error===!0,n,a.length?a:void 0))}}}handleAssistantEvent(e,n){ro(e,n,this.streamDeltaState,this.host.sessionId,Cn(n))}handleStreamEvent(e){this.emitContextUsage(e);let n=Ys(e,this.streamDeltaState);if(!n)return;let r=n.kind==="thinking"?h().showThinking?this.currentTurn?.onAssistantThinkingDelta:null:this.currentTurn?.onAssistantDelta;try{r?.(n.text,n.blockId)}catch(i){I.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){I.warn("onContextUsage threw:",i.message)}}emitSubagentActivity(e){let n=e?.parent_tool_use_id;if(typeof n!="string")return;let r=Id(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){I.warn("onSubagentActivity threw:",o.message)}}handleLine(e){if(!e)return;this.host.resetIdleTimer(),this.host.bumpTurnIdleTimer();let n=Rd(e);if(n?.type==="stream_event"){this.handleStreamEvent(n);return}this.currentTurn?.rawStream?.write(e+`
|
|
49
|
+
`),this.handleCompleteLine(e,n)&&I.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}
|
|
50
|
+
`),!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=_n(e);return n&&this.currentTurn?.txtStream?.write(n+`
|
|
51
|
+
`),!0}observeLine(e){e.type==="system"&&e.subtype==="compact_boundary"&&this.emitContextUsage(e),so(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=>I.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){I.warn("onSubagentEnd threw:",i.message)}}routeTurnlessLine(e){if(!this.currentTurn&&(xn(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||xn(this.bgTracker,e)==="open-continuation")}handleTurnResult(e,n){if(no(n)&&!e.spontaneous&&!e.promptConsumed){I.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]
|
|
52
|
+
`);return}this.emitContextUsage(n),this.handleResultEvent(e,n)}closeTurnLogs(e){try{e.txtStream.write(`
|
|
53
|
+
=== Turn ended at ${new Date().toISOString()} ===
|
|
54
|
+
`),e.rawStream.end(),e.txtStream.end()}catch{}e.releaseCapture?.(),e.releaseCapture=null}abortTurnOnProcessClose(e,n){if(this.currentTurn){let r=this.currentTurn;if(this.currentTurn=null,this.closeTurnLogs(r),this.host.clearTurnIdleTimer(),r.spontaneous)this.notifyBgInterrupted(!0);else if(r.killed)r.reject(r.killError??new di);else{let i=pt(r.resultData,this.host.sessionId,e||1,n,r.planFilePath,r.enteredPlanMode,r.exitedPlanMode,r.finalOutput,r.longestOutput);i.resolved?r.resolve(i.value):r.reject(i.error)}}}failInFlightTurn(e){if(this.currentTurn){let n=this.currentTurn;this.currentTurn=null,this.closeTurnLogs(n),n.reject(e)}}holdsIdle(){return this.bgTracker.hasPending()||this.pendingInjections.length>0||this.injectionContinuationArmed}markCurrentTurnKilled(e){this.currentTurn&&(this.currentTurn.killed=!0,this.currentTurn.killError=e)}};function D(t){return t!==null&&typeof t=="object"?t:null}function q(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}function co(t,e){return t[e]===void 0?0:q(t[e])}function po(t){let e=D(t);if(!e)return null;let n=q(e.input_tokens),r=co(e,"cache_creation_input_tokens"),i=co(e,"cache_read_input_tokens");return n===null||r===null||i===null?null:q(n+r+i)}function Pd(t){let e=D(t);if(!e)return null;let n=po(e),r=q(e.output_tokens);return n===null||r===null?null:q(n+r)}function Od(t){let n=D(t.usage)?.iterations;return Array.isArray(n)&&n.length>0?n.at(-1):null}function fo(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:null}function Ld(t){let e=D(t)?.canonicalModel;return typeof e=="string"?e:null}function Md(t){return t?.replace(/\[1m\]$/,"")??null}function mo(t,e){return e?t.find(([,n])=>Ld(n)===e)?.[1]??null:null}function ho(t,e){return e?t.find(([n])=>n===e)?.[1]??null:null}function Dd(t,e){return mo(t,e)??ho(t,e)}function Nd(t,e){return ho(t,e)??mo(t,Md(e))}function jd(t,e,n){let r=D(t);if(!r)return null;let i=Object.entries(r);return Dd(i,e)??Nd(i,n)??(i.length===1?i[0][1]:null)}function Ud(t,e,n){let r=D(jd(t.modelUsage,e,n));return fo(r?.contextWindow)}function $d(t){return t?.endsWith("[1m]")?1e6:2e5}var ht=class{configuredModel;autoCompactWindow;contextWindow;currentInput=null;currentUsed=null;activeModel=null;resultFallbackAllowed=!0;lastSnapshotKey=null;constructor(e,n){this.configuredModel=e??null,this.autoCompactWindow=fo(n),this.contextWindow=this.capped($d(e))}capped(e){return this.autoCompactWindow===null?e:Math.min(e,this.autoCompactWindow)}observe(e){let n=D(e);return n?n.type==="stream_event"?this.observeStream(D(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(D(e.message)):e?.type==="message_delta"?this.observeMessageDelta(D(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=po(e?.usage);return n===null?null:(this.currentInput=n,this.currentUsed=n,this.snapshot(n))}observeMessageDelta(e){let n=q(e?.output_tokens);return this.currentInput===null||n===null?null:(this.currentUsed=q(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=Ud(e,this.activeModel,this.configuredModel);n!==null&&(this.contextWindow=this.capped(n));let r=this.resultFallbackAllowed?Pd(Od(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 Bd from"node:fs";import Rn from"node:path";var Fd=1e5,Wd=1e6;function Kd(t){try{let n=JSON.parse(Bd.readFileSync(t,"utf8"))?.autoCompactWindow;return typeof n!="number"||!Number.isInteger(n)?null:n>=Fd&&n<=Wd?n:null}catch{return null}}function Hd(t,e=He){let n=[Rn.join(t,".claude","settings.local.json"),Rn.join(t,".claude","settings.json"),Rn.join(e,"settings.json")];for(let r of n){let i=Kd(r);if(i!==null)return i}return null}function go(t,e){return(e.pinned?null:h().maxContextTokens)??Hd(t,e.userConfigDir)}var yo=0;function So(){return yo}function cb(){yo+=1}var gt=f("claude-bridge");function Vd(t,e,n,r){let i=r??"claude";return t?t(i,e,n):{process:zd(i,e,{...n,stdio:["pipe","pipe","pipe"]})}}function ko(t){return t?[...t]:[]}function bo(t){return t==null?null:[...t]}function wo(t){let e=t.mcpComposition;return{cwd:ue(t.cwd),routeIdentity:ms(t),composition:e,interactionBridge:e==="direct"&&t.isUserInitiated===!0,teamLead:e==="direct"&&t.teamLead===!0,teamWorker:e==="direct"&&t.teamWorker===!0,tools:t.tools??null,pluginCapabilityFingerprint:t.pluginCapabilityFingerprint??null,pluginDirs:ko(t.pluginDirs),mcpConfigPaths:ko(t.mcpConfigPaths),mcpToolAllowlist:bo(t.mcpToolAllowlist),supplementalMcpConfigIdentity:t.supplementalMcpConfigIdentity??null,disableSkills:t.disableSkills===!0,settingSources:bo(t.settingSources)}}function Jd(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 To(t){let e=Jd(wo(hn(t))),n=So();return n===0?e:`${e}#cli${n}`}function Xd(t,e,n){return new ht(t,go(e,{pinned:!!n.pinnedEnv,userConfigDir:n.pinnedEnv?n.pinnedEnv.CLAUDE_CONFIG_DIR:n.configDir}))}var Pn=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=wo(e.options),this.onSelfClose=n.onSelfClose,this.onEvict=n.onEvict,this.onRateLimit=n.onRateLimit,this.turns=new mt(this,Xd(this.modelName,e.options.cwd,e.options)),this.spawnProcess()}get captureTranscriptLogs(){return this.options.captureTranscriptLogs!==!1}get connection(){return this.options.connection}handleProcessClose(e){gt.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,ft(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||mn(e,n)}attachSpawnedProcess(e){this.proc=e.process,this.supervision=e.supervision,this.stderr="",this.rl=Gd({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=yn(e,this.sessionId);this.needsResume&&Gs(i,this.sessionId);let{args:s,env:o}=Os({channel:this.channel,sessionId:this.sessionId,needsResume:this.needsResume,options:this.options}),a=this.needsResume?Ns(i,this.sessionId):0;this.turns.resetCostBaseline(a),gt.info(`Spawning persistent process: ${this.sessionId.substring(0,8)} ${this.needsResume?`(resume, restored cost $${a.toFixed(2)})`:"(new)"}`);let u=Vd(n,s,{cwd:e,env:o},r);this.attachSpawnedProcess(u),this.armProcessTimers()}writeTurnStdin(e){let n=JSON.stringify({type:"user",message:{role:"user",content:e},session_id:this.sessionId})+`
|
|
55
|
+
`;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(()=>{gt.info(`Session ${this.sessionId.substring(0,8)} turn idle for 60min, killing`),this.kill(new Error("Claude turn idle for 60min"))},ei)}async sendMessage(e,n){this.alive||(this.needsResume=!0,this.spawnProcess()),this.resetIdleTimer();let r=Z(e,n.attachments??[]),i=this.turns.createTurnStreams(e),s=new Promise((a,u)=>{this.turns.registerTurn(a,u,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(()=>{gt.info(`Session ${this.sessionId.substring(0,8)} idle for 65min, closing`),this.close()},qr)}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 Qd(t,e,n,r=Mr){return Ds(t,yn(r,e),n)}function _o(t){let e=Qd(t.needsResume,t.sessionId,void 0,t.options.cwd);return{...t,needsResume:e}}var yt=class{backend="claude";capabilities=z.claude;onRateLimit;constructor(e={}){this.onRateLimit=e.onRateLimit}open(e,n={}){let r=new Pn(_o(gn(e)),{onSelfClose:n.onSelfClose,onEvict:n.onEvict,onRateLimit:this.onRateLimit});return new ct(r,e,To(e))}specIdentity(e){return To(e)}claudeResumeTarget(e){let{needsResume:n,sessionId:r}=_o(gn(e));return{needsResume:n,sessionId:r}}};import{existsSync as Kp,mkdirSync as Hp}from"fs";import{readdirSync as tp}from"fs";import*as Io from"path";var xo="[A-Za-z0-9-]+",Yd="\\d{4}-\\d{2}-\\d{2}T\\d{2}(?:[-:]\\d{2}){2}(?:-\\d{3})?Z",Zd=/^(?<primary>.+)\.turn-(?<turn>\d+)\.bak$/,qd=new RegExp(`^(?<sessionId>${xo})\\.jsonl$`),ep=new RegExp(`^(?<timestamp>${Yd})_(?<sessionId>${xo})\\.jsonl$`);function vo(t){let e=t.match(Zd);if(e?.groups){let i=Number(e.groups.turn),s=vo(e.groups.primary);return!s||!Number.isSafeInteger(i)||i<0||s.backupTurn!==null?null:{...s,backupTurn:i}}let n=t.match(ep);if(n?.groups?.sessionId&&n.groups.timestamp)return{sessionId:n.groups.sessionId,primaryFilename:t,timestampPrefix:n.groups.timestamp,backupTurn:null};let r=t.match(qd);return r?.groups?.sessionId?{sessionId:r.groups.sessionId,primaryFilename:t,timestampPrefix:null,backupTurn:null}:null}function Eo(t,e){let n=null;for(let r of t){let i=vo(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 Co(t,e){if(!e)return null;try{let n=Eo(tp(t),e);return n?Io.join(t,n):null}catch{return null}}var np={"openai-codex":"OpenAI Codex"};function Ao(t){let e=t.provider||"pi",n=t.connection||e;return{provider:e,displayName:np[e]??e,mode:n}}function rp(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}:{}}}async function ip(t,e,n){for(let r of t.windows)await n({rateLimitType:r.type,...r.label?{rateLimitLabel:r.label}:{},utilization:r.utilization,resetsAt:r.resetsAt},e)}async function Ro(t,e,n){let r=n.usageStore.update(rp(t,e,(n.now??Date.now)())).then(()=>null,o=>({error:o})),i;try{await ip(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 Do from"node:path";var Po=f("pi-adapter"),Oo=3900*1e3,Lo=3600*1e3,Mo=2e3;function On(t){return Z(t.text,t.attachments??[])}var St=class{pending=[];waiters=[];closed=!1;push(e){if(this.closed)return;let n=this.waiters.shift();n?n({value:e,done:!1}):this.pending.push(e)}next(){let e=this.pending.shift();return e?Promise.resolve({value:e,done:!1}):this.closed?Promise.resolve({value:void 0,done:!0}):new Promise(n=>this.waiters.push(n))}close(){if(!this.closed){this.closed=!0;for(let e of this.waiters.splice(0))e({value:void 0,done:!0})}}},kt=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){Po.warn(`PI injection delivery sink failed: ${r.message}`)}}notifyUndelivered(e){try{this.sink?.onUndelivered?.({text:e.text})}catch(n){Po.warn(`PI injection undelivered sink failed: ${n.message}`)}}};var G=f("pi-adapter");function ee(t){return t instanceof Error?t:new Error(String(t))}function te(t){return typeof t=="number"&&Number.isFinite(t)?t:null}function Ln(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function sp(t){let e=Ln(t);return Object.keys(e).length===0?null:{inputTokens:te(e.input)??0,outputTokens:te(e.output)??0,cacheReadTokens:te(e.cacheRead)??0,cacheWriteTokens:te(e.cacheWrite)??0,costUsd:te(Ln(e.cost).total)}}function op(t){return/nothing to compact|no messages to compact/i.test(t)}function ap(t){return Ln(t).role==="user"}function No(t){return{[Symbol.asyncIterator]:()=>({next:()=>t.next()})}}var bt=class{sessionKey;sessionId=null;sessionFile=null;currentSessionId=null;ready;handle=null;turnStream=null;parserState=Di();request;registry;onClose;onProviderQuota;subagent;openBundledMcpServer;getSubagentModelEnv;alive=!0;textBuffer="";textBlockId=null;idleTimer=null;turnIdleTimer=null;pendingTurn=null;steering=new kt;loopState="idle";compacting=!1;lastContextSampleAt=0;constructor(e){this.sessionKey=e.request.sessionKey,this.request=e.request,this.registry=e.registry,this.onClose=e.onClose,this.onProviderQuota=e.onProviderQuota,this.subagent=e.subagent,this.openBundledMcpServer=e.openBundledMcpServer,this.getSubagentModelEnv=e.getSubagentModelEnv,this.ready=this.start(e.runtimeFactory),this.ready.catch(()=>{}),this.resetIdleTimer()}async start(e){let n;try{n=await e(this.request,{onEvent:r=>this.handleRawEvent(r),onProviderQuota:r=>this.handleProviderQuota(r)},{subagent:this.subagent,openBundledMcpServer:this.openBundledMcpServer,getSubagentModelEnv:this.getSubagentModelEnv})}catch(r){let i=ee(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??Do.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(()=>{G.info(`Session ${this.sessionKey} idle for 65min, closing`),this.close(),this.onClose?.(this.sessionKey,this)},Oo),this.idleTimer.unref?.()}startTurnIdleTimer(){this.turnIdleTimer=setTimeout(()=>{G.info(`Session ${this.sessionKey} turn idle for 60min, killing`),this.kill(new Error("PI turn idle for 60min")),this.onClose?.(this.sessionKey,this)},Lo),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:te(n.tokensBefore),estimatedTokensAfter:te(n.estimatedTokensAfter),usage:sp(n.usage),contextUsage:this.currentContextUsage()}}catch(n){let r=ee(n);if(op(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 Ui(e.getSessionStats(),h().maxContextTokens)}catch(n){return G.warn(`PI session ${this.sessionKey}: session stats unavailable: ${ee(n).message}`),null}}isAlive(){return this.alive}openTurnStream(){this.closeTurnStream();let e=new St;return this.turnStream=e,e}closeTurnStream(){this.turnStream!==null&&(this.turnStream.close(),this.turnStream=null)}closeTurnStreamFor(e){this.turnStream===e?this.closeTurnStream():e.close()}handleRawEvent(e){if(!this.alive||e.type==="cortex_subagent_usage"&&this.turnStream===null)return;this.resetIdleTimer(),this.bumpTurnIdleTimer(),this.observeLoop(e);let n=ji(e,this.handle?.session.model);for(let r of Ni(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<Mo)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"||!ap(e.message))return;let n=this.pendingTurn;n&&!n.openingUserSeen?n.openingUserSeen=!0:n&&this.steering.consumeNext(this.leafPosition())}leafPosition(){let e=this.handle?.session.sessionManager?.getLeafId();return e?{after:e}:void 0}handleProviderQuota(e){e?.windows?.length&&(this.onProviderQuota?.(e),this.turnStream?.push({type:"rate_limit",raw:e}))}processPendingTurnEvent(e){let n=this.pendingTurn;if(!n)return e;if(e.type==="plan_written")n.planFilePath=e.path;else if(e.type!=="ask_user_question"){if(e.type==="turn_complete")return this.handleTurnComplete(e);e.type==="error"&&e.fatal&&(this.flushTextBuffer(),this.clearTurnIdleTimer(),this.steering.abandon(),this.pendingTurn=null,n.reject(new Error(e.message)))}return e}handleTurnComplete(e){let n=this.pendingTurn;return this.flushTextBuffer(),n.numTurns+=e.numTurns,e.totalCostUsd!==null&&(n.totalCostUsd=(n.totalCostUsd??0)+e.totalCostUsd),e.error?(this.steering.abandon(),this.settlePendingTurn(e.error)):this.steering.hasPending?(n.deferredCompletion=!0,null):this.settlePendingTurn()}finishDeferredTurn(){return!this.pendingTurn?.deferredCompletion||this.steering.hasPending?null:this.settlePendingTurn()}settlePendingTurn(e){let n=this.pendingTurn;this.pendingTurn=null,this.clearTurnIdleTimer();let r=e?{type:"turn_complete",numTurns:n.numTurns,totalCostUsd:n.totalCostUsd,error:e}:{type:"turn_complete",numTurns:n.numTurns,totalCostUsd:n.totalCostUsd};return e?n.reject(Object.assign(new Error(e),{reason:"provider_error"})):n.resolve(this.buildAgentResult(n)),r}buildAgentResult(e){return{sessionId:this.sessionId,total_cost_usd:e.totalCostUsd,num_turns:e.numTurns,rateLimited:!1,rateLimitMessage:null,planFilePath:e.planFilePath,enteredPlanMode:!1,exitedPlanMode:e.planFilePath!==null,askUserQuestions:void 0,finalOutput:e.lastAssistantText}}emitNormalizedEvent(e){if(e.type==="context_usage"){this.turnStream?.push(e);return}if(e.type==="assistant_thinking"||e.type==="assistant_thinking_delta"){this.emitThinkingEvent(e);return}if(e.type==="assistant_text"&&e.subagent){this.flushTextBuffer(),this.turnStream?.push(e);return}if(e.type!=="assistant_text"){this.flushTextBuffer(),this.turnStream?.push(e),e.type==="turn_complete"&&this.closeTurnStream();return}this.bufferTextEvent(e)}emitThinkingEvent(e){h().showThinking&&(this.flushTextBuffer(),!(e.type==="assistant_thinking_delta"&&!this.request.streamDeltas)&&this.turnStream?.push(e))}bufferTextEvent(e){let n=e.blockId??null;this.textBuffer.length>0&&n!==this.textBlockId&&this.flushTextBuffer(),this.textBlockId=n,this.request.streamDeltas&&n!==null&&this.turnStream?.push({type:"assistant_delta",text:e.text,blockId:n}),this.textBuffer+=e.text}dispatchPrompt(e,n){this.loopState="starting",this.pendingTurn&&(this.pendingTurn.promptDispatched=!0),e.session.prompt(n).catch(r=>this.promptFailed(ee(r)))}promptFailed(e){if(G.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=On(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 a=`injection refused: ${ee(o).message}`;G.warn(`PI session ${this.sessionKey}: ${a}`),this.turnStream?.push({type:"error",message:a,fatal:!1}),this.rejectInjection(r)}),!0}rejectInjection(e){if(!this.steering.reject(e))return;let n=this.finishDeferredTurn();n!==null&&this.emitWithContext(n)}setInjectionAckSink(e){this.steering.setSink(e)}async sendSwitchSession(e){if(!this.alive)return{ok:!1,cancelled:!1};let n;try{n=await this.liveHandle()}catch{return{ok:!1,cancelled:!1}}try{let r=await n.switchSession(e);return{ok:!r.cancelled,cancelled:r.cancelled}}catch(r){return G.warn(`PI session ${this.sessionKey}: switch to ${e} failed: ${ee(r).message}`),{ok:!1,cancelled:!1}}}async sendTurn(e,n,r){let i=await this.liveHandle(),s=On(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:(G.debug(`PI session ${this.sessionKey}: no dialog waits on ui request ${e}`),!1):!1}beginTurn(e,n){this.beginTurnReject(new Error("PISession.beginTurn: superseded by a newer send()")),this.parserState.turnProgressCount=0,this.pendingTurn={resolve:e,reject:n,planFilePath:null,numTurns:0,totalCostUsd:null,promptDispatched:!1,openingUserSeen:!1,deferredCompletion:!1,lastAssistantText:null},this.startTurnIdleTimer()}beginTurnReject(e){this.rejectPendingTurn(e)}rejectPendingTurn(e){if(this.pendingTurn===null)return;let n=this.pendingTurn;this.pendingTurn=null,this.clearTurnIdleTimer(),this.steering.abandon(),n.reject(e)}async close(){return this.shutdown(new Error("PI session closed before turn_complete"))}async shutdown(e){if(this.clearTimers(),!this.alive)return;this.alive=!1,this.steering.abandon(),this.steering.clearSink(),this.rejectPendingTurn(e),this.closeTurnStream();let n=this.handle;if(this.handle=null,!!n)try{await n.dispose()}catch(r){G.warn(`PI session ${this.sessionKey}: dispose failed: ${ee(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 up(t){return t instanceof Error?t:new Error(String(t))}var Tt=class{backend="pi";identity;session;onEvict;resolveSessionPath;injections;constructor(e,n,r={}){this.session=e,this.identity=st(n),this.onEvict=r.onEvict,this.resolveSessionPath=r.resolveSessionPath,this.injections=new pe(e,"pi-run-inj")}get backendSessionId(){return this.session.sessionId}run(e,n){let r=this.session.openTurnStream(),i=new me,s=this.injections.beginRun(i),o=this.sendTurn(e);o.catch(()=>{});let a=fe(),u=fe(),l=new de(n.awaitBackground,{push:g=>i.push(g),settleForeground:g=>a.resolve(g),settleRun:g=>{u.resolve(g),a.resolve(g)},close:()=>i.close()});s.attachPhase(l),a.promise.catch(g=>u.reject(g)),u.promise.catch(()=>{});let c=!1,p=[],m=g=>{c?g():p.push(g)},_=()=>{c=!0;let g=p;p=[];for(let O of g)O()},x=!1;return o.then(g=>{x=!0,m(()=>{i.push({type:"foreground_result",result:g}),l.start(g)})},g=>{x=!0,m(()=>{i.push({type:"phase",phase:"done",pendingBackground:0,undeliveredBackground:0}),i.close()}),a.reject(g)}),(async()=>{for await(let g of No(r))n.onNormalizedEvent?.(g),g.type!=="turn_complete"&&i.push(Ie(g,"foreground"));_(),await Promise.resolve(),x||(i.push({type:"phase",phase:"done",pendingBackground:0,undeliveredBackground:0}),i.close())})(),a.promise.catch(()=>{}),{events:{[Symbol.asyncIterator]:()=>({next:()=>i.next()})},result:a.promise,settled:u.promise,cancel:()=>{this.session.closeTurnStreamFor(r)}}}sendTurn(e){return new Promise((n,r)=>{this.session.beginTurn(n,r),this.session.sendTurn(this.session.sessionId,this.turnPath(),e).catch(i=>this.session.beginTurnReject(up(i)))})}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 Zo from"node:path";import{randomUUID as jo}from"node:crypto";function Uo(t){return t.cancelled===!0}function Mn(t){if(Uo(t))return;let e=t.value;return typeof e=="string"?e:void 0}function $o(t,e){let n=new Map;function r(o,a,u,l){if(l?.signal?.aborted)return Promise.resolve(a);let c=jo();return new Promise(p=>{let m,_=()=>{x(),p(a)},x=()=>{m&&clearTimeout(m),l?.signal?.removeEventListener("abort",_),n.delete(c)};l?.signal?.addEventListener("abort",_,{once:!0}),l?.timeout&&(m=setTimeout(()=>{x(),p(a)},l.timeout),m.unref?.()),n.set(c,{resolve:g=>{x(),p(u(g))},cleanup:x}),t({type:"extension_ui_request",id:c,...o})})}function i(o,a){t({type:"extension_ui_request",id:jo(),method:o,...a})}return{ui:{select:(o,a,u)=>r({method:"select",title:o,options:a,timeout:u?.timeout},void 0,Mn,u),confirm:(o,a,u)=>r({method:"confirm",title:o,message:a,timeout:u?.timeout},!1,l=>!Uo(l)&&l.confirmed===!0,u),input:(o,a,u)=>r({method:"input",title:o,placeholder:a,timeout:u?.timeout},void 0,Mn,u),editor:(o,a)=>r({method:"editor",title:o,prefill:a},void 0,Mn),notify:(o,a)=>i("notify",{message:o,notifyType:a}),setStatus:(o,a)=>i("setStatus",{statusKey:o,statusText:a}),setWidget:(o,a,u)=>{(a===void 0||Array.isArray(a))&&i("setWidget",{widgetKey:o,widgetLines:a,widgetPlacement:u?.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,a){let u=n.get(o);return u?(u.resolve(a),!0):!1},cancelAll(){for(let o of[...n.values()])o.resolve({cancelled:!0})}}}import{spawn as lp}from"node:child_process";import{readFileSync as cp}from"node:fs";import*as Ko from"node:path";import{pathToFileURL as dp}from"node:url";var Ho=f("hook-bridge"),pp={"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"},Dn={"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 zo(t){return(t.startsWith("mcp__")?null:Ge("claude",t))??t.charAt(0).toUpperCase()+t.slice(1)}function fp(t,e){return(t==="read"||t==="write"||t==="edit")&&typeof e.path=="string"?{...e,file_path:e.path}:{...e}}function Nn(t,e){let n=t.sessionManager?.getSessionFile();return n?Ko.basename(n,".jsonl"):e.CORTEX_SESSION_ID??"unknown"}function mp(t){return Array.isArray(t)?t.filter(e=>typeof e=="object"&&e!==null&&e.type==="text").map(e=>e.text).join(""):""}function Go(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 hp(t){if(t?.trim())try{return JSON.parse(t.trim())}catch{return}}function gp(t,e){if(t===0)return null;let n=e?.trim()?`: ${e.trim()}`:"";return new Error(`exited with code ${t}${n}`)}function Bo(t,e,n,r,i){return new Promise((s,o)=>{let a=lp(t,e,{env:Go(i,String(n.session_id??"unknown")),stdio:["pipe","pipe","pipe"]}),u="",l="",c=!1,p=setTimeout(()=>{c=!0,a.kill("SIGKILL")},r);a.stdout.setEncoding("utf8").on("data",m=>{u+=m}),a.stderr.setEncoding("utf8").on("data",m=>{l+=m}),a.on("error",m=>{clearTimeout(p),o(m)}),a.on("close",m=>{if(clearTimeout(p),c){o(new Error(`timed out after ${r}ms`));return}let _=gp(m,l);_?o(_):s(hp(u))}),a.stdin.on("error",()=>{}),a.stdin.end(JSON.stringify(n))})}var Fo=new Map,yp=/export\s+(?:async\s+)?function\s+runHook\b|export\s*\{[^}]*\brunHook\b/;function Sp(t){try{return yp.test(cp(t,"utf8"))}catch{return!1}}async function kp(t){let e=Kr(t).path,n=Fo.get(e);if(n!==void 0)return n;let r=null;if(Sp(e))try{let i=await import(dp(e).href);typeof i.runHook=="function"&&(r=i.runHook)}catch(i){Ho.warn(`in-process load of ${t} failed; using the spawned form: ${i.message}`)}return Fo.set(e,r),r}function bp(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 jn(t){return typeof t!="object"||t===null||Array.isArray(t)?{}:t}async function Pe(t,e,n){let r=(t.run.timeout??30)*1e3;try{if(t.run.script){let i=await kp(t.run.script);if(i){let s=Go(n,String(e.session_id??"unknown"));return await bp(i(e,s),r,t.id)}return await Bo(process.execPath,Hr(t.run.script),e,r,n)}return await Bo("sh",["-c",t.run.command],e,r,n)}catch(i){Ho.error(`${t.id} error:`,i);return}}function Un(t,e){if(typeof t.matcher!="string")return!0;let n=e.startsWith("mcp__")?e:zo(e),r=t.event.startsWith("agent:")?n:e;return new RegExp(t.matcher).test(r)}function Tp(t){return t.event.startsWith("pi:")?t.event.slice(3):t.event.startsWith("agent:")?pp[t.event]:null}function Vo(t,e,n,r){let i={hook_event_name:t,session_id:Nn(n,r),tool_name:zo(e.toolName),tool_input:fp(e.toolName,e.input),tool_use_id:e.toolCallId,cwd:n.cwd};return"content"in e&&_p(i,e),i}function _p(t,e){t.tool_output=mp(e.content),t.tool_response=e.details??null,t.is_error=e.isError}function Jo(t,e,n,r){return{...typeof e=="object"&&e!==null?e:{event:e},hook_event_name:Dn[t.event],session_id:Nn(n,r),tool_name:"",tool_input:{},tool_use_id:"",cwd:n.cwd}}function wp(t,e,n,r){return{...typeof e=="object"&&e!==null?e:{event:e},hook_event_name:t,session_id:Nn(n,r),cwd:n.cwd}}function xp(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 vp(t){let e=t.hookSpecificOutput;if(e?.permissionDecision==="deny")return{block:!0,reason:e.permissionDecisionReason??"Blocked by hook registry"}}async function Ep(t,e,n,r){for(let i of n){if(!Un(i,t.toolName))continue;let s=Vo(Dn[i.event],t,e,r),o=jn(await Pe(i,s,r));xp(t,o.hookSpecificOutput);let a=vp(o);if(a)return a}}function Ip(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 Cp(t,e,n,r){let i=!1;for(let s of n){if(!Un(s,t.toolName))continue;let o=Vo(Dn[s.event],t,e,r),a=jn(await Pe(s,o,r));i=Ip(t,a.hookSpecificOutput?.additionalContext)||i}return i?{content:t.content}:void 0}async function Ap(t,e,n,r){let i=t.systemPrompt??"",s=!1;for(let o of n){let a={...t,systemPrompt:i},l=jn(await Pe(o,Jo(o,a,e,r),r)).hookSpecificOutput?.additionalContext;l&&(i+=`
|
|
56
|
+
|
|
57
|
+
${l}`,s=!0)}if(s)return{systemPrompt:i}}async function Rp(t,e,n,r){for(let i of n)await Pe(i,Jo(i,t,e,r),r)}function Pp(t,e,n,r,i){let s=[e];return t==="tool_call"?Ep(n,r,s,i):t==="tool_result"?Cp(n,r,s,i):t==="before_agent_start"?Ap(n,r,s,i):Rp(n,r,s,i)}function ye(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Wo(t,e){for(let n of Object.keys(t))delete t[n];Object.assign(t,e)}function Op(t,e,n){if(!ye(e)||!ye(n))return n;if(t==="before_provider_headers"){ye(e.headers)&&ye(n.headers)&&Wo(e.headers,n.headers);return}if(t!=="tool_call"||!ye(e.input)||!ye(n.input))return n;Wo(e.input,n.input);let r={...n};return delete r.input,Object.keys(r).length>0?r:void 0}async function Lp(t,e,n,r,i){let s=t==="tool_call"||t==="tool_result",o=n?.toolName;if(s&&(typeof o!="string"||!Un(e,o)))return;let a=await Pe(e,wp(t,n,r,i),i);return Op(t,n,a)}function Mp(t,e,n,r,i){return e.event.startsWith("pi:")?Lp(t,e,n,r,i):Pp(t,e,n,r,i)}function Xo(t,e){let n=vi(xi(),{backend:"pi"});for(let r of n){let i=Tp(r);i&&t.on(i,(s,o)=>Mp(i,r,s,o,e))}}function Dp(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 Qo(t,e={}){let n=t.reportsProviderQuota?e.onProviderQuota:void 0,r=Dp(t.env,e.getSubagentModelEnv),i=[{name:"cortex-image-first",factory:Gi},{name:"cortex-mcp-bridge",factory:s=>Hi(s,Ki(r,t.pluginMcpServers,e.openBundledMcpServer))},{name:"cortex-tool-shims",factory:s=>Yi(s,r,{onSubagentEvent:e.onSubagentEvent,onSubagentUsage:e.onSubagentUsage,onProviderQuota:n,runForeignSubagent:e.subagent?.runForeignSubagent,startBackgroundSubagent:e.subagent?.startBackgroundSubagent,stopBackgroundSubagent:e.subagent?.stopBackgroundSubagent,checkDelegatedModel:e.subagent?.checkDelegatedModel,openBundledMcpServer:e.openBundledMcpServer})},{name:"cortex-described-bash",factory:s=>Qi(s)}];return t.disableHooks||i.push({name:"cortex-hook-bridge",factory:s=>Xo(s,t.env)}),n&&i.push({name:"cortex-quota-probe",factory:zi(n)}),i}var Se=f("pi-runtime"),Np=new Set(["off","minimal","low","medium","high","xhigh","max"]),Yo=Symbol.for("@earendil-works/pi-coding-agent:theme");function jp(t){let e=globalThis;return e[Yo]||t.initTheme("dark",!1),e[Yo]}function Up(t){if(t.thinking){if(Np.has(t.thinking))return t.thinking;Se.warn(`Ignoring unknown PI thinking level '${t.thinking}' for session ${t.sessionKey}`)}}function $p(t,e){return e.sessionPath?t.SessionManager.open(e.sessionPath,e.sessionDir):t.SessionManager.create(e.cwd,e.sessionDir)}function Bp(t,e,n){let r=Up(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&&Se.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 Fp(t,e,n,r,i){Qr(h().piCompactReserveTokens,{agentDir:i});let s=Bi(t,r,i),o=await t.ModelRuntime.create({authPath:Ze(i),modelsPath:Zo.join(i,"models.json"),allowModelNetwork:!1});return await bi(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 Wp(t,e,n){return async({cwd:r,agentDir:i,sessionManager:s,sessionStartEvent:o})=>{let a=await Fp(t,e,n,r,i),u=[...a.diagnostics,...a.resourceLoader.getExtensions().errors.map(({path:m,error:_})=>({type:"error",message:`Failed to load extension "${m}": ${_}`}))],{model:l,thinking:c}=Bp(t,e,a.modelRuntime);return{...await t.createAgentSessionFromServices({services:a,sessionManager:s,sessionStartEvent:o,model:l,thinkingLevel:c}),services:a,diagnostics:u}}}async function qo(t,e,n={}){let r=await zr(),i=$o(p=>e.onEvent(p),jp(r)),s=Qo(t,{subagent:n.subagent,openBundledMcpServer:n.openBundledMcpServer,getSubagentModelEnv:n.getSubagentModelEnv,onProviderQuota:e.onProviderQuota,onSubagentEvent:p=>e.onEvent({type:"cortex_subagent_event",notice:p}),onSubagentUsage:p=>e.onEvent({type:"cortex_subagent_usage",report:p})}),o=$p(r,t),a=await r.createAgentSessionRuntime(Wp(r,t,s),{cwd:o.getCwd(),agentDir:t.agentDir,sessionManager:o});for(let p of a.diagnostics){let m=`PI session ${t.sessionKey}: ${p.message}`;p.type==="error"?Se.error(m):p.type==="warning"?Se.warn(m):Se.info(m)}a.modelFallbackMessage&&Se.warn(`PI session ${t.sessionKey}: ${a.modelFallbackMessage}`);let u,l=async()=>{let p=a.session;await p.bindExtensions({uiContext:i.ui,mode:"rpc",onError:m=>e.onEvent({type:"extension_error",extensionPath:m.extensionPath,event:m.event,error:m.error})}),u?.(),u=p.subscribe(m=>e.onEvent(m))};a.setRebindSession(l),await l();let c=!1;return{get session(){return a.session},respondToUi:(p,m)=>i.respond(p,m),switchSession:p=>a.switchSession(p),async dispose(){c||(c=!0,u?.(),i.cancelAll(),await a.dispose())}}}var $n=f("pi-adapter");function zp(t){return{provider:it,displayName:"OpenAI Codex",modes:[t],windows:[],observedAt:null,freshness:"never"}}function Gp(t){return{...t,modes:[...t.modes],windows:t.windows.map(e=>({...e})),...t.spend?{spend:{...t.spend}}:{},freshness:"stale"}}var _t=class{backend="pi";capabilities=z.pi;poolLookup=null;runtimeFactory;sessionPathRegistry=new Map;configuredAgentDir;catalog;usageStore;submitRateLimit;subagent;openBundledMcpServer;getSubagentModelEnv;sessionDir;constructor(e=qo,n=Ye,r={}){this.runtimeFactory=e,this.sessionDir=n,this.configuredAgentDir=r.agentDir,this.catalog=r.catalog,this.usageStore=r.usageStore,this.submitRateLimit=r.submitRateLimit,this.subagent=r.subagent,this.openBundledMcpServer=r.openBundledMcpServer,this.getSubagentModelEnv=r.getSubagentModelEnv}async getUsage(e){if(e.provider!==it||!e.mode)return null;let n=await this.usageStore?.get(it,"subscription")??null;return[n?Gp(n):zp(e.mode)]}resolveSpawnSessionPath(e,n){if(!e.resume.resume||!e.resume.backendSessionId)return null;let r=this.resolveSessionPath(e.resume.backendSessionId);return r===null&&$n.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{ki(this.catalog(e),{agentDir:e,oauthProviders:Si(Ze(e))})}catch(n){$n.warn(`Failed to write PI models.json: ${n.message}`)}}syncAgentDir(e){this.writeCatalog(e)}get agentDir(){return this.configuredAgentDir??Qe}agentDirFor(e){return e.route.piAgentDir??this.agentDir}ensureCatalog(e=this.agentDir){this.syncAgentDir(e)}scanModels(e=this.agentDir){return this.ensureCatalog(e),Ti(e)}buildRequest(e,n){return $i(e,{agentDir:this.agentDirFor(e),homeAgentDir:this.agentDir,sessionDir:this.sessionDir,sessionPath:n,cwd:ue(e.cwd),streamDeltas:e.flags.streamDeltas??h().streamDeltas})}specIdentity(e){return st(this.buildRequest(e,null))}prepareRequest(e){let n=this.agentDirFor(e);Hp(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=>{Ro(i,Ao({provider:e.model.provider,connection:e.route.connection}),{usageStore:n,submit:r}).catch(s=>$n.error("reportCodexQuota error:",s))}}open(e,n={}){let r=this.prepareRequest(e),i=new bt({request:r,runtimeFactory:this.runtimeFactory,registry:this.sessionPathRegistry,onClose:n.onSelfClose,onProviderQuota:this.quotaReporter(e),subagent:this.subagent,openBundledMcpServer:this.openBundledMcpServer,getSubagentModelEnv:this.getSubagentModelEnv});return new Tt(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&&Kp(n))return n;n&&this.sessionPathRegistry.delete(e);let r=Co(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)}};function ne(t,e){return e?`${t}::${e}`:t}function wt(t){let e=t.indexOf("::");return e<0?{provider:t,route:null}:{provider:t.slice(0,e),route:t.slice(e+2)}}function BT(t,e){if(e.has(t))return!0;let{provider:n,route:r}=wt(t);return r?e.has(n):[...e].some(i=>wt(i).provider===n)}var N=f("rate-limit-throttle"),Vp="rate-limit:clear",Jp={five_hour:.9,seven_day:.95,seven_day_overage_included:.95},Xp=.9,Qp=5e3,Yp=5e3,ke="outage",Zp="model_scoped",Bn=null,Le=null,ta=null,na=null,ra=null,Oe=null,Kn=0,v=new Map,xt=new We;function qp(t){return{...t,modes:[...t.modes].sort(),windows:t.windows.map(e=>({...e})).sort((e,n)=>e.resetsAt-n.resetsAt)}}function re(t){return ne(t.provider,t.route)}function vt(t){return!t.route||t.route===ze||t.route===t.provider?t.displayName:`${t.displayName} (${t.route})`}function Et(t=v){return[...t.values()].map(qp).sort((e,n)=>re(e).localeCompare(re(n)))}function It(){return new Map(Et().map(t=>[re(t),t]))}function Ct(t){v.clear();for(let e of t.values())v.set(re(e),e)}function Fn(t=v){return Et(t).flatMap(e=>e.windows)}function ef(t){return[...new Set(t)].sort()}function tf(t=v){let e=Et(t);return e.length>0?{providers:e}:null}async function Me(t=v){await Le?.save(tf(t))}function At(){try{na?.()}catch(t){N.error(`onChange hook failed: ${t.message}`)}}function Rt(t){try{ta?.(t)}catch(e){N.error(`onResume hook failed: ${e.message}`)}}function Pt(t,e=S("notice.rateLimit.title"),n){Bn&&Je(Bn,{text:t,level:"warning",title:e,...n&&n.length>0?{actions:n}:{}})}function nf(t){return[{type:"button",text:S("notice.rateLimit.resumeNow"),actionId:Vp,value:t,style:"primary"}]}function rf(t){return new Date(t*1e3).toLocaleString(Ur()==="zh"?"zh-CN":"en-GB",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1})}function sf(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 ia(t,e){return e??Jp[t]??Xp}function ea(t){let e=t?.trim();return e||null}function Hn(t,e,n){return n.type===t&&(t!==Zp||n.label===e)}function sa(t,e,n,r){let i=h().providerRateLimits[t],s=a=>Hn(n,r,a),o=i?.accounts?.[Nr(t,e)]?.windows.find(s)??i?.windows?.find(s);return o?{enabled:o.enabled,threshold:o.threshold??null}:typeof i?.enabled=="boolean"?{enabled:i.enabled,threshold:i.threshold??null}:{enabled:!0,threshold:null}}function of(t){if(typeof t=="string"){let n=ea(t)??"unknown";return{provider:n,displayName:n,mode:n}}let e=ea(t?.provider);return e?{provider:e,displayName:t?.displayName?.trim()||e,...t?.mode?{mode:t.mode}:{}}:{provider:"unknown",displayName:"Unknown provider"}}function af(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)?ef(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 uf(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===ke),n=t.windows.filter(i=>i?.type!==ke),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 lf(t){return Array.isArray(t.providers)?t.providers.flatMap(uf).map(af).filter(e=>e!==null):[]}function oa(t){let e=t.type===ke?0:Qp;return t.resetsAt*1e3+e}function Wn(t,e=Date.now()){return oa(t)>e}function cf(t){for(let e of lf(t)){let n=e.windows.filter(r=>Wn(r));n.length>0&&v.set(re(e),{...e,windows:n})}}function df(){let t=Fn().map(oa);return t.length>0?Math.min(...t):null}function pf(){Oe&&clearTimeout(Oe),Oe=null,Kn++}function ie(t=0){pf();let e=df();if(e===null)return;let n=Kn,r=Math.max(t,e-Date.now(),0);N.info(`Next provider reset check in ${(r/1e3/60).toFixed(1)} min`),Oe=setTimeout(()=>{yf(e,n)},r)}function ff(t,e){let n=[];for(let[r,i]of t){let s=i.windows.filter(o=>!Wn(o,e)).map(o=>o.type);i.windows=i.windows.filter(o=>Wn(o,e)),!(i.windows.length>0)&&(t.delete(r),n.push({provider:r,displayName:vt(i),expiredTypes:s}))}return n}function mf(t){return t.expiredTypes.includes(ke)?{text:`${ae.ok} ${S("notice.rateLimit.outageCleared",{provider:t.displayName})}`,title:S("notice.rateLimit.outageTitle")}:{text:`${ae.ok} ${S("notice.rateLimit.cleared",{provider:t.displayName})}`}}async function hf(t){try{return await Me(t),!0}catch(e){return N.error(`Failed to persist throttle expiry: ${e.message}`),ie(Yp),!1}}async function gf(t){let e=It(),n=Fn(e).length,r=Math.max(Date.now(),t),i=ff(e,r);if(Fn(e).length===n){ie();return}if(await hf(e)){Ct(e);for(let s of i){let o=mf(s);Pt(o.text,o.title)}At(),i.length>0&&Rt(i.map(s=>s.provider)),ie()}}async function yf(t,e){await xt.run(async()=>{e===Kn&&(Oe=null,await gf(t))})}async function QT(t,e,n,r){Bn=t,Le=e,ta=n??null,na=r??null;let i=await e.load();if(!i){N.info("Initialized");return}cf(i),v.size===0?(await e.save(null),Rt([])):(await Me(),ie()),N.info(`Initialized \u2014 ${v.size} provider throttle(s) restored`)}function Sf(t,e){let n=t.windows.find(s=>Hn(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 kf(t,e){if(typeof t.utilization!="number"||!t.rateLimitType)return!1;let n=sa(e.provider,e.mode,t.rateLimitType,t.rateLimitLabel);return n.enabled&&t.utilization>=ia(t.rateLimitType,n.threshold)}async function bf(t,e,n){try{return await ra?.(t,e,n)??[]}catch(r){return N.warn(`Rate-limit notice actions failed: ${r.message}`),[]}}async function Tf(t,e,n,r){if(N.info(`Throttle updated: provider=${e.provider}, type=${t.rateLimitType}, utilization=${t.utilization}, mode=${e.mode??"(none)"}`),!r)return;let i=[...nf(re(n)),...await bf(e.provider,n.route,t.rateLimitType)];Pt(`${ae.warning} ${S("notice.rateLimit.activated",{provider:vt(n),type:t.rateLimitType,pct:(t.utilization*100).toFixed(0),at:rf(t.resetsAt),remaining:sf(t.resetsAt)})}`,S("notice.rateLimit.title"),i)}function _f(t){return t.status==="rejected"&&typeof t.utilization!="number"?{...t,utilization:1}:t}async function wf(t,e){if(!t||!Le||!t.rateLimitType||!t.resetsAt)return;let n=_f(t),r=of(e);if(!kf(n,r))return;let i=It(),s=ne(r.provider,r.mode),o=i.get(s),a=!o;o||(o={provider:r.provider,...r.mode?{route:r.mode}:{},displayName:r.displayName,modes:[],windows:[]},i.set(s,o));let u=!!r.mode&&!o.modes.includes(r.mode);u&&o.modes.push(r.mode);let l=Sf(o,{rateLimitType:n.rateLimitType,rateLimitLabel:n.rateLimitLabel,utilization:n.utilization,resetsAt:n.resetsAt});!a&&!u&&!l||(await Me(i),Ct(i),ie(),At(),await Tf(n,r,o,a))}async function zn(t,e){await xt.run(()=>wf(t,e))}function xf(t,e){return e?t.has(e)?[e]:wt(e).route?[]:[...t.entries()].filter(([,n])=>n.provider===e).map(([n])=>n):[...t.keys()]}function vf(t){return{provider:t.provider,...t.route?{route:t.route}:{},displayName:vt(t),types:t.windows.map(e=>e.type),resetsAt:t.windows.reduce((e,n)=>Math.max(e,n.resetsAt),0)}}async function Ef(t){if(!Le)return{cleared:[]};let e=It(),n=xf(e,t);if(n.length===0)return{cleared:[]};let r=n.map(i=>vf(e.get(i)));for(let i of n)e.delete(i);await Me(e),Ct(e),ie(),At(),Rt(n);for(let i of r){let s=i.types.join(", ");N.info(`Throttle manually cleared: provider=${i.provider}, route=${i.route??"(all)"}, types=${s}`),Pt(`${ae.ok} ${S("notice.rateLimit.clearedManually",{provider:i.displayName})}`)}return{cleared:r}}async function YT(t){return xt.run(()=>Ef(t))}function If(t,e,n){if(e.type===ke)return!1;let r=n.find(s=>Hn(e.type,e.label,s));if(!r)return!1;let i=sa(t.provider,t.route,e.type,e.label);return!i.enabled||r.utilization<ia(e.type,i.threshold)}async function Cf(t,e){await Me(t),Ct(t),ie(),At(),e&&(N.info(`Throttle released by a fresh quota reading: provider=${e.provider}, route=${e.route??"(none)"}`),Pt(`${ae.ok} ${S("notice.rateLimit.cleared",{provider:vt(e)})}`),Rt([re(e)]))}function Af(t,e,n){return n?t.has(ne(e,n))?[ne(e,n)]:[]:[...t.entries()].filter(([,r])=>r.provider===e).map(([r])=>r)}async function Rf(t,e,n){if(!Le)return!1;let r=It(),i=!1;for(let s of Af(r,t,n)){let o=r.get(s),a=o.windows.filter(u=>!If(o,u,e));a.length!==o.windows.length&&(a.length>0?o.windows=a:r.delete(s),await Cf(r,a.length===0?o:null),i=!0)}return i}async function ZT(t,e,n){return xt.run(()=>Rf(t,e,n))}function qT(t){ra=t}function Pf(t){return[...v.values()].filter(e=>e.provider===t)}function aa(t,e){return t?e?v.has(ne(t,e))||v.has(t):Pf(t).length>0:v.size>0}function ua(t,e){return v.has(ne(t,e))?!0:!!v.get(t)?.windows.some(n=>n.type===ke)}function e_(){return{providers:Et()}}import Of from"node:fs/promises";import Ot from"node:path";var Lf=Ot.join(Ke,"provider-state.json");function Mf(){return{rateLimitThrottle:null,resumeQueue:[],providerUsage:[]}}function la(t){return JSON.stringify(t,null,2)}async function ca(t){try{let e=JSON.parse(await Of.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 Df(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Nf(t){let e=t.rateLimitThrottle,n=t.providerUsage;return Object.hasOwn(t,"rateLimitThrottle")&&Object.hasOwn(t,"resumeQueue")&&(e===null||Df(e))&&Array.isArray(t.resumeQueue)&&(n===void 0||Array.isArray(n))}async function jf(t){let e=await ca(t);if(!e)return!1;if(!Nf(e))throw new Error(`${t} must contain rateLimitThrottle and resumeQueue`);return!0}function Uf(t){return Object.hasOwn(t,"rateLimitThrottle")||Object.hasOwn(t,"resumeQueue")}function $f(t){return{rateLimitThrottle:t.rateLimitThrottle??null,resumeQueue:t.resumeQueue??[],providerUsage:[]}}function Bf(t){let e={...t};return delete e.rateLimitThrottle,delete e.resumeQueue,e}async function a_(t=A){let e=Ot.join(t,"data"),n=Ot.join(e,"schedules.json"),r=await ca(n);if(!r||!Uf(r))return;let i=Ot.join(e,"provider-state.json");await jf(i)||await _e(i,la($f(r))),await _e(n,la(Bf(r)))}var Gn=class{repo;constructor(e=Lf){this.repo=new Br({filePath:e,defaultValue:Mf})}async setRateLimitThrottle(e){await this.repo.mutate(n=>({next:{...n,rateLimitThrottle:e},result:void 0}))}async getRateLimitThrottle(){return(await this.repo.read()).rateLimitThrottle??null}async setResumeQueue(e){await this.repo.mutate(n=>({next:{...n,resumeQueue:e},result:void 0}))}async getResumeQueue(){return(await this.repo.read()).resumeQueue??[]}async setProviderUsage(e){await this.repo.mutate(n=>({next:{...n,providerUsage:e},result:void 0}))}async getProviderUsage(){return(await this.repo.read()).providerUsage??[]}async getSubscriptionSignOuts(){return{...(await this.repo.read()).subscriptionSignOuts}}async setSubscriptionSignOut(e,n){await this.repo.mutate(r=>{let i={...r.subscriptionSignOuts};return n===null?delete i[e]:i[e]=n,{next:{...r,subscriptionSignOuts:i},result:void 0}})}flush(){return this.repo.flush()}},Vn=new Gn;import pa from"node:fs/promises";import fa from"node:path";var Lt=f("usage-window-history"),ma=1,Ff=2160*60*60*1e3,Wf=300*1e3,Kf=3e4,Hf=/^(five_hour|seven_day.*|codex_.+)$/;function zf(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&&Hf.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 Gf(t){return t.flatMap(zf)}function Vf(t,e){return t.provider===e.provider&&t.route===e.route&&t.windowType===e.windowType&&Math.abs(t.resetsAt-e.resetsAt)<=Wf}function Jf(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 Xf(t,e){let n=t.find(s=>Vf(s,e));if(!n)return t.push(Jf(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 da(t,e){return t.filter(n=>n.resetsAt>=e-Ff)}async function Qf(t){try{let e=JSON.parse(await pa.readFile(t,"utf8"));return e.version===ma&&Array.isArray(e.records)?e.records:[]}catch(e){return e.code!=="ENOENT"&&Lt.warn(`usage window history unreadable, starting over: ${String(e)}`),[]}}var Jn=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=Gf(e)}catch(r){Lt.warn(`usage window observation skipped: ${String(r)}`);return}n.length!==0&&(this.chain=this.chain.then(async()=>this.apply(n)).catch(r=>Lt.warn(`usage window history update failed: ${String(r)}`)))}async list(){return await this.chain,da(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??=Qf(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)Xf(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??Kf),this.timer.unref?.())}async persist(){if(!(!this.dirty||!this.records)){this.dirty=!1,this.records=da(this.records,this.now());try{await pa.mkdir(fa.dirname(this.opts.filePath),{recursive:!0}),await _e(this.opts.filePath,JSON.stringify({version:ma,records:this.records}))}catch(e){Lt.warn(`usage window history write failed: ${String(e)}`)}}}},Yf=fa.join(Ke,"usage-windows.json"),Xn=new Jn({filePath:Yf});$r(Xn);function k_(t){return t.credits.find(e=>e.id===t.nextCreditId)??t.credits[0]??null}function F(t){if(!t.billing)return t.provider;let e=`${t.provider}::${t.billing}`;return t.route?`${e}::${t.route}`:e}function Zf(t){return{...t,modes:[...t.modes],windows:t.windows.map(e=>({...e})),...t.spend?{spend:{...t.spend}}:{},...t.resetCredits?{resetCredits:ga(t.resetCredits)}:{}}}function ga(t){return{...t,credits:t.credits.map(e=>({...e,...e.clears?{clears:[...e.clears]}:{}}))}}function qf(t,e){return e.resetCredits||!t?.resetCredits?e:{...e,resetCredits:ga(t.resetCredits)}}function De(t){let e=new Map;for(let n of t)e.set(F(n),Zf(n));return[...e.values()].sort((n,r)=>n.provider.localeCompare(r.provider)||F(n).localeCompare(F(r)))}function ha(t,e){return t.observedAt===null?!0:e.observedAt===null?!1:e.observedAt>=t.observedAt}var ya={load:()=>Vn.getProviderUsage(),save:t=>Vn.setProviderUsage(t)},Qn=class{persistence;observer;mutationMutex=new We;constructor(e=ya,n){this.persistence=e,this.observer=n}async list(){return De(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=F({provider:e,billing:n,route:r});return i.find(o=>F(o)===s)??null}async update(e){this.observer?.observe([e]),await this.mutationMutex.run(async()=>{let n=De(await this.persistence.load()),r=F(e),i=n.findIndex(s=>F(s)===r);i!==-1&&!ha(n[i],e)||(i===-1?n.push(e):n[i]=qf(n[i],e),await this.persistence.save(De(n)))})}async commit(e){this.observer?.observe(e),await this.mutationMutex.run(async()=>{let n=new Map(De(await this.persistence.load()).map(i=>[F(i),i])),r=e.map(i=>{let s=n.get(F(i));return!s||ha(s,i)?i:{...i,windows:s.windows.map(o=>({...o})),observedAt:s.observedAt,freshness:s.freshness}});await this.persistence.save(De(r))})}},Sa=new Qn(ya,Xn);var ka=async t=>{let{runSubagent:e}=await import("./runner-S6R3US24.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 em=f("run-adapters"),Yn=new _t(void 0,Ye,{agentDir:Qe,catalog:t=>Zi({accountProvider:Ai(t)?.provider}),usageStore:Sa,submitRateLimit:zn,openBundledMcpServer:ot,getSubagentModelEnv:cn,subagent:{checkDelegatedModel:Mi,runForeignSubagent:ka,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)}});async function tm(){let t=H.piAccounts(),[e,...n]=await Promise.all([Yn.scanModels(),...t.map(r=>Yn.scanModels(Ci(r.id)).catch(i=>(em.warn(`PI model scan of account '${r.id}' failed: ${i.message}`),[])))]);return[e,...n].flat()}_i(tm);gs(()=>{let t=tt.peek(),e=Li(),n=nt(t,{backend:"claude",provider:null})?.models??Xe;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 U_(t){be.start=t?.startBackgroundSubagent,be.stop=t?.stopBackgroundSubagent}var nm=new yt({onRateLimit:zn});function ba(){return nm}function Mt(){return Yn}var Zn=class{byKey=new Map;byChannel=new Map;_bus=null;constructor(e){e&&(this._bus=e)}setBus(e){this._bus=e}register(e){let n=e.executionId??e.registryKey;if(!n)throw new Error("RunRegistry.register requires an executionId or registryKey");let r=this.byKey.get(n);r&&this._removeFromIndices(r);let i={channel:e.channel,registryKey:n,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};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}),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}_delete(e){this.byKey.delete(e.registryKey),this._removeFromIndices(e)}_removeFromIndices(e){if(e.channel){let n=this.byChannel.get(e.channel);n&&(n.delete(e),n.size===0&&this.byChannel.delete(e.channel))}}},V=new Zn;var qn=new Map,Ta=new Map;function F_(t,e,n){let r=rm(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`);qn.set(t,e),n!==void 0&&Ta.set(t,n)}function W_(t){return qn.get(t)??null}function _a(t){return Ta.get(t)}function rm(t,e){for(let[n,r]of qn)if(r.trial_id===t&&r.root_run_id===e)return n;return null}var Ea={};ll(Ea,{cancelExecution:()=>va,completeExecution:()=>wa,failExecution:()=>xa,getAll:()=>sm,getExecution:()=>im,getRunningExecutions:()=>om,markMissingRunningExecutionsStale:()=>cm,startLocalExecution:()=>er,stopLiveExecution:()=>lm,teardownExecution:()=>Dt,touchExecution:()=>am});function im(t){return L.getExecution(t)}function sm(){return L.getAll()}function om(){return L.getRunningExecutions()}function er(t){return L.startLocalExecution(t)}function am(t,e){return L.touchExecution(t,e)}function wa(t,e){return L.completeExecution(t,e)}function xa(t,e){return L.failExecution(t,e)}function va(t,e){return L.cancelExecution(t,e)}function um(t){let e=t?.rateLimitMessage;return e?`Rate limited: ${e}`:"Rate limited"}function Dt({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,a={costUsd:o,numTurns:r?r.numTurns:n?.num_turns,durationS:s,finalOutput:n?.finalOutput||null},u;if(e==="completed")u=wa(t,a),V.complete(t,o??0);else if(e==="cancelled")u=va(t,a),V.supersede(t,"cancelled");else{let l=e==="rate-limited"?i?.message||um(n):i?.message||null;u=xa(t,{...a,error:l}),V.fail(t,l??"error")}return u}function lm(t){if(t.run?.cancel){t.run.cancel("user");return}t.executionId?Dt({executionId:t.executionId,status:"cancelled",durationS:0}):V.killById(t.registryKey)}async function cm(t){return await L.markMissingRunningExecutionsStale(t)}var dm=/rate[ _]limit|usage[ _]limit|hit your (?:[\w-]+ )?limit|overloaded|529|too many requests|quota/i;function Te(t){return!!t&&dm.test(t)}var pm=/(?:invalid[_ ]request|forbidden|not found|request body too large|context(?: window|_length).*exceed|insufficient[_ ](?:balance|quota)|billing|quota exhausted)/i,fm=/(?:^(?: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,mm=/(?: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,hm=/\byou can retry your request\b/i,gm=/\b(?:ENOSPC|EMFILE|ENFILE|EAGAIN)\b/i;function Ne(t){let e=t?.message;return!e||le(e)||pm.test(e)?!1:Te(e)||fm.test(e)||mm.test(e)||hm.test(e)||gm.test(e)}var tr=Object.freeze({costUsd:null,numTurns:null});function ym(t,e){return t===null?e:e===null?t:t+e}function Nt(t){return typeof t=="number"&&Number.isFinite(t)?t:null}function Ia(t){return{costUsd:Nt(t.total_cost_usd),numTurns:Nt(t.num_turns)}}function Ca(t,e){if(e.type==="cost_record")t.costUsd=ym(t.costUsd,Nt(e.cost_usd));else if(e.type==="turn_progress"){let n=Nt(e.numTurns);n!==null&&(t.numTurns=Math.max(t.numTurns??0,n))}}var Sm=/\bClaude Code v?(\d+\.\d+\.\d+)\b.*?\bversion v?(\d+\.\d+\.\d+)\S* or newer is required/i,km=/\brun\s+['"`]?claude update\b/i;function Ra(t){let e=Sm.exec(t);return e?{installed:e[1],required:e[2]}:km.test(t)?{}:null}function nr(t){let e=Ra(t);if(e)return e.required?{kind:"update-claude-code",required:e.required}:{kind:"update-claude-code"}}var Aa=new Set;function Pa(t,e){if(e?.startsWith("web:"))return;let n=Ra(t),r=Wr.adapter;if(!n||!r)return;let i=n.required??"";if(Aa.has(i))return;Aa.add(i);let s=n.required?S("notify.claudeUpdateRequired.body",{installed:n.installed??"?",required:n.required}):S("notify.claudeUpdateRequired.bodyGeneric");Je(r,{title:S("notify.claudeUpdateRequired.title"),text:s,level:"warning"})}var bm={claude:"anthropic"};function se(t){return t.provider||bm[t.backend]||t.backend}function je(t){let e=w({...t,provider:t.provider??null});return ua(se(t),e)}function rr(t,e){return{sessionId:null,total_cost_usd:null,num_turns:null,rateLimited:!0,rateLimitMessage:`Connection ${t} is rate-limited`,rateLimitProvider:e,rateLimitRoute:t,planFilePath:null,enteredPlanMode:!1,exitedPlanMode:!1,finalOutput:null}}function Oa(t,e){return je(t)&&!e.isUserInitiated}function ir(t){return se(t)}function La(t){return t.backend!=="claude"?null:w(t)===ze||jt(t)?"oauth":"api_key"}function jt(t){let e=w(t);return Ii({backend:t.backend,id:e})?e:null}function sr(t){return t.model?se(t):null}function Tm(t){let e=tt.peek();if(t.backend==="claude")return Ri(e,t.model).filter(i=>H.findClaude(i)?.kind!=="key");let n=t.provider??"";return(nt(e,{backend:"pi",provider:n})?.connections??[n]).map(i=>i===n?null:i)}function ar(t){return{enabled:t.enabled??(()=>h().accountFailover),logins:t.logins??Tm,billingOf:t.billingOf??(e=>H.billingOf(e)),isRateLimited:t.isRateLimited??je}}function _m(t,e){return{...t,connection:e}}function ur(t,e={}){let n=ar(e);if(!n.enabled())return null;let r=n.logins(t).map(u=>_m(t,u)),i=w(t);if(!r.some(u=>w(u)===i))return null;let s=n.billingOf(t),o=u=>w(u)!==i&&n.billingOf(u)===s&&!n.isRateLimited(u),a=r.find(o);return a?{selection:a,from:i,to:w(a)}:null}function Ma(t,e={}){let n=ar(e);return!n.enabled()||!n.isRateLimited(t)?null:ur(t,n)}function Da(t,e,n={}){return e.route!==w(t)||e.provider!==se(t)?null:ur(t,n)}function pw(t,e={}){let n=ar(e);return n.enabled()?!n.isRateLimited(t)||ur(t,n)!==null:!1}function lr(t){if(t.backend==="pi"&&!t.connection)return t.provider??"pi";let e=w(t);return H.list().find(r=>r.backend===t.backend&&r.id===e)?.label??e}var or=new Map;function Na(t,e){if(!e)return or.delete(t),!1;let n=`${e.from}\0${e.to}`;return or.get(t)===n?!1:(or.set(t,n),!0)}function ja(t){return t.startsWith("API Error:")?"error":void 0}function wm(t){return t.startsWith("API Error:")?t:S("status.errorBody",{message:t})}var Ut=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&&Te(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?nr(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=wm(e)){this.flushHeldError(),!(!this.synthesize||!this.emit||this.attemptHasErrorNotice)&&(this.attemptHasErrorNotice=!0,this.emit(n,void 0,"error",nr(e)))}emitAutoResume(e,n){if(!this.ctx.isUserInitiated||!aa(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"&&Te(r)&&this.emitAutoResume(n?.rateLimitProvider,n?.rateLimitRoute)||this.emitTerminal(r)}emitTerminalRateLimit(e){if(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"))}};var xm=f("agent-adapter"),Ua=f("pi-adapter");function $a(t){return t instanceof Error?t.message:String(t)}var cr=class{pi;claude;sessions=new Map;constructor(e={}){this.pi=e.pi,this.claude=e.claude,this.pi?.setEnginePool({get:n=>this.piEngine(n)})}acquire(e){return e.backend.kind==="pi"?this.acquirePi(e):this.acquireClaude(e)}reuses(e){let n=this.get(e.engineKey);return n?e.backend.kind==="pi"?!!this.pi&&this.piReusable(this.pi,e,n):!!this.claude&&this.claudeReusable(this.claude,e,n):!1}piReusable(e,n,r){return r.isAlive()&&r.identity===e.specIdentity(n)}claudeReusable(e,n,r){if(!r.isAlive()||r.identity!==e.specIdentity(n))return!1;let 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&&(Ua.info(`PI session ${r} retired (${i.isAlive()?"spawn config changed":"session gone"}); creating a new session`),i.close().catch(o=>Ua.warn(`retiring PI session ${r} failed: ${$a(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=>xm.warn(`close ${n.backend} session ${e} failed: ${$a(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)}},vm=Mt(),Em=ba(),$t=new cr({pi:vm,claude:Em});function dr(){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 Bt(t){let e=dr();return t.replace(/\{\{(\w+)\}\}/g,(n,r)=>r in e?e[r]:n)}function Ba(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 Fa from"path";var Im=Fa.join(A,"rules");function Wa(t=Im,e=qi()){return es(t,e).filter(n=>n.paths.length===0).map(n=>n.body)}import{readFileSync as Cm,statSync as Am}from"fs";import*as za from"path";var Ka=za.join(Dr,"user","USER.md"),Ft=null,Ha=0;function Rm(){try{let t=Am(Ka);return t.mtimeMs===Ha&&Ft!==null||(Ft=Cm(Ka,"utf8"),Ha=t.mtimeMs),Ft}catch{return null}}function Ga(){if(h().disableUserContext)return null;let t=Rm();return t?`[User Context]
|
|
58
|
+
${t}
|
|
59
|
+
[/User Context]`:null}function Va(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(`
|
|
60
|
+
|
|
61
|
+
---
|
|
62
|
+
|
|
63
|
+
`):void 0}function Ja(t){return t?Wa():[]}function Lw(t,e,n={}){let r=Ba(t.promptTemplate||"{{input}}",{input:e,...dr()});return[...n.resumed?[]:Pm(t,n),r].join(`
|
|
64
|
+
|
|
65
|
+
`).trim()}function Pm(t,e){return[e.userContext,t.directive?Bt(t.directive):null,e.project?Om(e.project):null,e.transcriptDir?Lm(e.transcriptDir):null,e.board?Nm(e.board):null,e.team?Mm(e.team.roster,e.team.unread):null,e.worker?Dm(e.worker):null].filter(n=>!!n)}function Mw(t){return t?Ga():null}function Om(t){return`[Session Project] This session is bound to the project "${t.id}".
|
|
66
|
+
Project context directory: ${t.contextDir}
|
|
67
|
+
Treat messages in this session as pertaining to this project unless stated otherwise, and record project-related findings and status updates there.`}function Lm(t){return`[Session Transcripts] The full transcript of any Cortex session is at ${t}/<sessionId>.jsonl.`}function Mm(t,e){let n=`[Team] You lead these workers (persistent sessions you manage with the worker_* tools):
|
|
68
|
+
${t.length>0?t.join(`
|
|
69
|
+
`):"- (no active workers)"}
|
|
70
|
+
Rules:
|
|
71
|
+
1. After dispatching work, end your turn. Worker reports and questions wake you as they arrive. Updates a worker marks routine do not wake you; they appear under [Unread routine updates] on your next turn. Never poll or wait.
|
|
72
|
+
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.
|
|
73
|
+
3. Answer workers' questions and approve their plans yourself with worker_answer; ask the user with cortex_ask_user only when you are unsure what they would want.
|
|
74
|
+
4. Do not run repeated review loops on a worker's output.`;return e?`${n}
|
|
75
|
+
|
|
76
|
+
${e}`:n}function Dm(t){return`[Worker] You are worker "${t.name}" of the lead session "${t.lead}". Each final reply is delivered to the lead and wakes it. If a turn has nothing new for the lead (a stale or duplicate signal, a routine check, work still running with no change), call mark_routine before your final reply: the reply is then recorded for the lead without waking it. Ask for decisions with cortex_ask_user; they are handled by the lead, as are your plan approvals. The user may also open this session and talk to you directly. Keep final replies concise: conclusions, output paths, and open items. You cannot create workers yourself.`}function Nm(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(`
|
|
77
|
+
`)}import{createHash as xg}from"node:crypto";import C from"node:fs";import y from"node:path";import Fh from"node:fs";import T from"node:path";var jm="https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",Xa="https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",Qa=new Set(["$schema","name","version","description","author","homepage","repository","license","keywords","extensions"]),Um=/^(?!.*(?:--|\.\.))[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/,$m=/^(?:\.\/|\$\{PLUGIN_ROOT\}(?:\/|$)|\$\{PLUGIN_DATA\}(?:\/|$))/,Bm=new Set(["PLUGIN_ROOT","PLUGIN_DATA"]),Fm=d.object({name:d.string().optional(),email:d.string().optional(),url:d.string().optional()}).strict(),Wm=d.record(d.string(),d.record(d.string(),d.unknown())),Ya=d.object({$schema:d.literal(jm),name:d.string().min(1).max(64).regex(Um),version:d.string().optional(),description:d.string().optional(),author:Fm.optional(),homepage:d.string().optional(),repository:d.string().optional(),license:d.string().optional(),keywords:d.array(d.string()).optional(),extensions:Wm.optional()}).strict();function Km(t,e){for(let n of Object.keys(t))Bm.has(n.toUpperCase())&&e.addIssue({code:d.ZodIssueCode.custom,path:[n],message:`Reserved env key ${n} is not allowed`})}var Hm=d.object({type:d.literal("stdio"),command:d.string().min(1),args:d.array(d.string()).optional(),env:d.record(d.string(),d.string()).superRefine(Km).optional(),cwd:d.string().regex($m).optional()}).strict(),Za=d.record(d.string(),d.string()),zm=d.object({type:d.literal("streamable-http"),url:d.string().min(1),headers:Za.optional()}).strict(),Gm=d.object({type:d.literal("sse"),url:d.string().min(1),headers:Za.optional()}).strict(),pr=d.union([Hm,zm,Gm]),qa=d.object({$schema:d.literal(Xa),mcpServers:d.record(d.string(),d.unknown())}).strict(),jw=d.object({$schema:d.literal(Xa),mcpServers:d.record(d.string(),pr)}).strict();import Vm from"node:fs";import mr from"node:path";import ru from"node:net";import{validateHeaderName as Jm,validateHeaderValue as Xm}from"node:http";function k(t,e,n,r){return{code:t,scope:e,path:n,message:r}}function Wt(t){return t.reduce((e,n)=>typeof n=="number"?`${e}[${n}]`:e?`${e}.${String(n)}`:String(n),"")}var eu=Symbol("skillRoot");function Kt(t,e,n){let r={name:t.name,dir:t.dir,description:t.description,origin:n};return Object.defineProperty(r,eu,{value:e,enumerable:!1}),r}function Ue(t){return t[eu]??null}var tu=Symbol("pluginMcpRuntime");function fr(t,e){return Object.defineProperty(t,tu,{value:e,enumerable:!1}),t}function nu(t){return t[tu]??null}function J(t){return Fi(t.manifest.name?.trim()||t.id)}function su(t){return t.issues.map(e=>`${Wt(e.path)||"(root)"}: ${e.message}`).join("; ")}function Qm(t,e){return mr.join(t,"data","plugin-data",e)}function hr(t,e,n){let r={PLUGIN_ROOT:e,PLUGIN_DATA:n};return t.replace(/\$\{(PLUGIN_ROOT|PLUGIN_DATA)\}/g,(i,s)=>r[s])}function Ym(t,e,n){let r=hr(t,e,n);return t.startsWith("${PLUGIN_ROOT}")?U(e,r):t.startsWith("${PLUGIN_DATA}")?U(n,r):r}function Zm(t,e,n){return(t??[]).map(r=>hr(r,e,n))}function qm(t,e,n){let r={};for(let[i,s]of Object.entries(t??{}))r[i]=hr(s,e,n);return r.PLUGIN_ROOT=e,r.PLUGIN_DATA=n,r}function eh(t){return mr.basename(t)}function th(t){return t.includes("/")||t.includes("\\")}function nh(t,e){return e.startsWith("./")?ln(t,e):th(e)?null:e}function rh(t,e,n){return n?n.startsWith("./")?ln(t,n):Ym(n,t,e):t}function ih(t){return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function sh(t){let e=ih(t);return e==="localhost"?!0:ru.isIP(e)===4?e.startsWith("127."):ru.isIP(e)!==6?!1:e==="::1"||e.toLowerCase()==="0:0:0:0:0:0:0:1"}function oh(t){return t.protocol==="https:"||t.protocol==="http:"&&sh(t.hostname)}function ah(t){return!!(t.username||t.password||t.hash)}function uh(t){return oh(t)&&!ah(t)}function lh(t){try{let e=new URL(t);return uh(e)?e:null}catch{return null}}function ch(t,e){let n=e.toLowerCase();return t.has(n)?!1:(t.add(n),!0)}function dh(t,e){try{return Jm(t),Xm(t,e),!0}catch{return!1}}function ph(t,e,n){return ch(t,e)&&dh(e,n)}function fh(t){let e=t??{},n=new Set;for(let[r,i]of Object.entries(e))if(!ph(n,r,i))return null;return Object.keys(e).sort()}function mh(t,e,n,r){let i=e,s=nh(t,r.command),o=Zm(r.args,t,i),a=qm(r.env,t,i),u=rh(t,i,r.cwd);return!s||!u?null:fr({name:n,type:"stdio",summary:{command:eh(s),argsCount:o.length,envKeys:Object.keys(a).sort()}},{command:s,args:o,env:a,cwd:u})}function hh(t,e){let n=lh(e.url),r=fh(e.headers);return!n||!r?null:fr({name:t,type:e.type,summary:{origin:n.origin,headerKeys:r}},{url:e.url,headers:e.headers??{}})}function gh(t,e,n,r){return r.type==="stdio"?mh(t,e,n,r):hh(n,r)}function yh(t){let e=mr.join(t,"mcp.json");if(!j(e))return{};let n=U(t,e);if(!n||!ce(n))return{issue:k("mcp_invalid","mcp","mcp.json","mcp.json must be a regular file inside the plugin root")};try{return{text:Vm.readFileSync(n,"utf8")}}catch{return{issue:k("mcp_invalid","mcp","mcp.json","mcp.json could not be read")}}}function iu(t){return t.match(/\/schemas\/([^/]+)\//)?.[1]??""}function Sh(t,e){try{let n=JSON.parse(t),r=qa.safeParse(n);return r.success?iu(r.data.$schema)!==iu(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",su(r.error))}}catch{return{issue:k("mcp_invalid","mcp","mcp.json","mcp.json is not valid JSON")}}}function kh(t,e,n){let r=[],i=[];for(let[s,o]of Object.entries(n).sort(([a],[u])=>a.localeCompare(u))){let a=pr.safeParse(o);if(!a.success){i.push(k("mcp_server_invalid","server",`mcpServers.${s}`,su(a.error)));continue}let u=gh(t,e,s,a.data);if(!u){i.push(k("mcp_server_invalid","server",`mcpServers.${s}`,"server violates URL or containment rules"));continue}r.push(u)}return{servers:r,issues:i}}function gr(t,e,n,r){let i=yh(e);if(i.issue)return{status:"invalid",servers:[],issues:[i.issue]};if(i.text===void 0)return{status:"missing",servers:[],issues:[]};let s=Sh(i.text,r);if(s.issue||!s.value)return{status:"invalid",servers:[],issues:s.issue?[s.issue]:[]};let o=kh(e,Qm(n,t),s.value.mcpServers);return{status:"valid",servers:o.servers,issues:o.issues}}var au=cl(dl(),1);import ou from"node:fs";import bh from"node:path";var Th=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,_h=/^(?!.*--)[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/,wh=new Set(["name","description","license","compatibility","metadata","allowed-tools"]);function uu(t){return`skills.${t}.SKILL.md`}function zt(t,e){return{code:"skill_invalid",scope:"skill",path:uu(t),message:e}}function lu(t,e){return{code:"skill_frontmatter_ignored",scope:"skill",path:uu(t),message:e}}function cu(t){let e=Th.exec(t);if(!e)return null;try{let n=(0,au.parse)(e[1]);return Q(n)?n:null}catch{return null}}function xh(t,e){return t!==void 0&&!(typeof t=="string"&&t===e)}function du(t){return typeof t=="string"&&t.trim().length>0}function Gt(t,e,n){return[lu(t,`SKILL.md frontmatter ${e} ${n}`)]}function vh(t,e){let n=Object.keys(e).filter(r=>!wh.has(r)).sort();return n.length===0?[]:[lu(t,`SKILL.md frontmatter has fields outside the spec, ignored: ${n.join(", ")}`)]}function Eh(t,e){let n=[];return e.name===void 0?n.push(...Gt(t,"name","is absent; the directory name is used")):typeof e.name=="string"&&(e.name.length>64||!_h.test(e.name))&&n.push(...Gt(t,"name","is not a canonical Agent Skills name")),typeof e.description=="string"&&e.description.length>1024&&n.push(...Gt(t,"description","exceeds the 1024-character guidance")),n}function Ih(t){return Q(t)?Object.values(t).every(e=>typeof e=="string"):!1}function Ht(t,e,n,r,i){n&&t.push(...Gt(e,r,i))}function Ch(t,e){let n=[];return Ht(n,t,e.license!==void 0&&typeof e.license!="string","license","must be a string when present"),Ht(n,t,e.compatibility!==void 0&&(!du(e.compatibility)||String(e.compatibility).length>500),"compatibility","must be 1-500 characters when present"),Ht(n,t,e.metadata!==void 0&&!Ih(e.metadata),"metadata","must be a string-to-string map when present"),Ht(n,t,e["allowed-tools"]!==void 0&&!Ah(e["allowed-tools"]),"allowed-tools","should be a comma-separated string"),n}function Ah(t){return typeof t=="string"||Array.isArray(t)&&t.every(e=>typeof e=="string")}function Rh(t,e){return e?xh(e.name,t)?[zt(t,"SKILL.md frontmatter name must match the skill directory")]:du(e.description)?[]:[zt(t,"SKILL.md frontmatter description must be non-empty")]:[zt(t,"SKILL.md must start with YAML frontmatter")]}function Ph(t,e){return[...Eh(t,e),...Ch(t,e),...vh(t,e)]}function yr(t){try{let e=cu(ou.readFileSync(t,"utf8"));return typeof e?.description=="string"?e.description.trim():""}catch{return""}}function pu(t,e){let n;try{n=ou.readFileSync(e,"utf8")}catch{return{issues:[zt(t,"SKILL.md could not be read")]}}let r=cu(n),i=Rh(t,r);return i.length>0||!r?{issues:i}:{skill:{name:t,dir:bh.join("skills",t),description:String(r.description).trim()},issues:Ph(t,r)}}import{createHash as Oh}from"node:crypto";import b from"node:fs";import W from"node:path";function Lh(t){return Oh("sha256").update(t).digest("hex")}function kr(t,e){let n=b.realpathSync(e);if(!os(t,n))throw new Error(`Skill path escapes plugin root: ${e}`);return n}function Mh(t,e){if(!t.isFile())throw new Error(`Skill path is not a file: ${e}`)}function mu(t,e,n){if(t.dev!==e.dev||t.ino!==e.ino)throw new Error(`Skill file changed while being read: ${n}`)}function Vt(t){return`${t.size}:${t.mtimeMs}:${t.ctimeMs}:${t.ino}:${t.mode&511}`}var Dh=b.constants.O_RDONLY|(b.constants.O_NOFOLLOW??0);function hu(t,e){let n=kr(t,e),r=b.openSync(n,Dh);try{let i=b.fstatSync(r);return Mh(i,n),mu(i,b.lstatSync(e),e),{fd:r,stat:b.fstatSync(r)}}catch(i){throw b.closeSync(r),i}}function br(t,e,n,r){let{fd:i,stat:s}=hu(t,n);try{e.push({path:r,signature:Vt(s),size:s.size,mode:s.mode&511})}finally{b.closeSync(i)}}function Tr(t,e,n,r,i,s){let o=kr(t,e);if(r.has(o))throw new Error(`Skill tree contains a symlink cycle: ${n||"."}`);let a=new Set(r).add(o);n&&i.push(n);for(let u of b.readdirSync(e).sort())jh(t,W.join(e,u),W.posix.join(n,u),a,i,s)}function Nh(t,e,n,r,i,s){let o=kr(t,e),a=b.statSync(o);if(a.isDirectory())return Tr(t,o,n,r,i,s);if(a.isFile())return br(t,s,o,n);throw new Error(`Skill path is not a file or directory: ${n}`)}function jh(t,e,n,r,i,s){let o=b.lstatSync(e);if(o.isSymbolicLink())return Nh(t,e,n,r,i,s);if(o.isDirectory())return Tr(t,e,n,r,i,s);if(o.isFile())return br(t,s,e,n);throw new Error(`Skill path is not a file or directory: ${n}`)}function gu(t,e){return Lh(JSON.stringify({dirs:t,files:e}))}function Jt(t,e){let n=[],r=[];return Tr(b.realpathSync(t),e,"",new Set,n,r),n.sort(),r.sort((i,s)=>i.path.localeCompare(s.path)),{dirs:n,files:r,sha256:gu(n,r)}}function Sr(t){b.mkdirSync(t,{recursive:!0,mode:448}),b.chmodSync(t,448)}function Uh(t,e,n,r,i){let{fd:s,stat:o}=hu(t,e);try{if(i&&Vt(o)!==r.signature)throw new Error(`Skill file changed after validation: ${e}`);if(o.size!==r.size||(o.mode&511)!==r.mode)throw new Error(`Skill file changed after validation: ${e}`);let a=b.readFileSync(s),u=b.fstatSync(s);if(mu(o,u,e),u.size!==r.size||Vt(u)!==Vt(o))throw new Error(`Skill file changed while being read: ${e}`);b.writeFileSync(n,a,{mode:r.mode}),b.chmodSync(n,r.mode)}finally{b.closeSync(s)}}function _r(t,e,n,r,i={}){Sr(r);for(let s of n.dirs)Sr(W.join(r,s));for(let s of n.files)Sr(W.dirname(W.join(r,s.path))),Uh(t,W.join(e,s.path),W.join(r,s.path),s,i.requireSourceSignature===!0)}function $h(t,e,n,r,i){n&&r.push(n);for(let s of b.readdirSync(e).sort())yu(t,W.join(e,s),W.posix.join(n,s),r,i)}function yu(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 $h(t,e,n,r,i);if(s.isFile())return br(t,i,e,n);throw new Error(`Portable projection target is invalid: ${e}`)}function Bh(t){let e=[],n=[];return yu(t,t,"",e,n),e.sort(),n.sort((r,i)=>r.path.localeCompare(i.path)),{dirs:e,files:n,sha256:gu(e,n)}}function fu(t){return JSON.stringify({dirs:t.dirs,files:t.files.map(({path:e,size:n,mode:r})=>({path:e,size:n,mode:r}))})}function wr(t,e){let n=b.lstatSync(t);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`Portable projection target is invalid: ${t}`);let r=Bh(t);if(fu(r)!==fu(e))throw new Error(`Portable projection skill tree mismatch: ${t}`)}function Wh(t){return T.join("plugins",t)}function K(t){return{id:t,origin:"local",kind:"unknown",rootDir:Wh(t),valid:!1,manifest:{source:"none"},skills:[],mcp:{status:"missing",servers:[]},issues:[]}}function Xt(t){if(typeof t!="string")return;let e=t.trim();return e.length>0?e:void 0}function Kh(t){return t.issues.map(e=>k("manifest_invalid","manifest",Wt(e.path)||"plugin.json",e.message))}function Hh(t){let e={},n=[];for(let[r,i]of Object.entries(t)){if(!Qa.has(r)){n.push(k("manifest_unknown_field","manifest",`plugin.json.${r}`,`Ignoring unknown field "${r}"`));continue}if(r==="extensions"&&!Q(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 zh(t){try{let e=JSON.parse(t);if(!Q(e))return Su("plugin.json must contain a top-level object");let n=Hh(e),r=Ya.safeParse(n.sanitized);return r.success?{manifest:Gh(r.data),valid:!0,issues:n.issues}:{manifest:{source:"root"},valid:!1,issues:[...n.issues,...Kh(r.error)]}}catch{return Su("plugin.json is not valid JSON")}}function Gh(t){return{source:"root",name:t.name,schema:t.$schema,version:Xt(t.version),description:Xt(t.description)}}function Su(t){return{manifest:{source:"root"},valid:!1,issues:[k("manifest_invalid","manifest","plugin.json",t)]}}function Vh(t){try{let e=JSON.parse(t);return!Q(e)||typeof e.name!="string"||e.name.trim()===""?ku("legacy manifest must define a non-empty name"):{manifest:{source:"legacy",name:e.name.trim(),version:Xt(e.version),description:Xt(e.description)},valid:!0,issues:[]}}catch{return ku("legacy manifest is not valid JSON")}}function ku(t){return{manifest:{source:"legacy"},valid:!1,issues:[k("legacy_manifest_invalid","manifest",".claude-plugin/plugin.json",t)]}}function Jh(t){return k("manifest_invalid","manifest",t,`${t} must be a regular file inside the plugin root`)}function Tu(t,e){let n=T.join(t,e);if(!j(n))return{state:"missing",issues:[]};let r=U(t,n);return!r||!ce(r)?{state:"invalid",issues:[Jh(e)]}:{state:"present",path:r,issues:[]}}function xr(t){return k("skill_invalid","skill","skills",t)}function Xh(t){let e=T.join(t,"skills");if(!j(e))return{state:"missing",issues:[]};let n=U(t,e);return n?at(n)?{state:"present",path:n,issues:[]}:{state:"invalid",issues:[xr("skills must be a directory inside the plugin root")]}:{state:"invalid",issues:[xr("skills must resolve to a directory inside the plugin root")]}}function Qh(t){try{return{names:Y(t),issues:[]}}catch{return{names:[],issues:[xr("skills could not be read")]}}}function vr(t,e){let n=Xh(t);if(n.state!=="present"||!n.path)return{skills:[],issues:n.issues};let r=Qh(n.path),i=[],s=[...r.issues];for(let o of r.names){let a=Zh(t,n.path,o,e);a.skill&&i.push(Kt(a.skill,t,"local")),s.push(...a.issues)}return{skills:i,issues:s}}function Yh(t,e,n){let r=pu(e,n);if(!r.skill)return r;try{return Jt(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 Zh(t,e,n,r){let i=T.join(e,n,"SKILL.md"),s=U(t,i);return!s||!ce(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:yr(s)},issues:[]}:Yh(t,n,s)}function qh(t,e,n,r){let i=K(t),s=zh(r);if(i.kind="portable",i.manifest=s.manifest,i.issues.push(...s.issues),!s.valid||!s.manifest.schema)return i;let o=vr(e,"portable"),a=gr(t,e,n,s.manifest.schema);return i.valid=!0,i.skills=o.skills,i.mcp={status:a.status,servers:a.servers},i.issues.push(...o.issues,...a.issues),i}function eg(t,e,n){let r=K(t),i=Vh(n);if(r.kind="legacy",r.manifest=i.manifest,r.issues.push(...i.issues),!i.valid)return r;let s=vr(e,"legacy");return r.valid=!0,r.skills=s.skills,r.issues.push(...s.issues),r}function tg(t){let e=K(t);return e.issues.push(k("manifest_missing","manifest",null,"plugin.json and .claude-plugin/plugin.json are both missing")),e}function _u(t,e,n){try{return{text:Fh.readFileSync(t,"utf8"),issues:[]}}catch{return{issues:[k(e,"manifest",n,`${n} could not be read`)]}}}function wu(t,e){let n=U(t,e);return n&&at(n)?n:null}function xu(t,e){let n=K(t),i=j(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 ng(t,e,n,r){let i=_u(r,"manifest_invalid","plugin.json");if(i.text!==void 0)return qh(t,e,n,i.text);let s=K(t);return s.kind="portable",s.manifest={source:"root"},s.issues.push(...i.issues),s}function rg(t,e,n){let r=_u(n,"legacy_manifest_invalid",".claude-plugin/plugin.json");if(r.text!==void 0)return eg(t,e,r.text);let i=K(t);return i.kind="legacy",i.manifest={source:"legacy"},i.issues.push(...r.issues),i}function ig(t,e,n){let r=Tu(e,"plugin.json");if(r.state==="invalid"){let i=K(t);return i.kind="portable",i.manifest={source:"root"},i.issues.push(...r.issues),i}return r.state!=="present"||!r.path?null:ng(t,e,n,r.path)}function sg(t,e){let n=Tu(e,T.join(".claude-plugin","plugin.json"));if(n.state==="invalid"){let r=K(t);return r.kind="legacy",r.manifest={source:"legacy"},r.issues.push(...n.issues),r}return n.state!=="present"||!n.path?null:rg(t,e,n.path)}function og(t,e,n){let r=T.join(e,t),i=wu(e,r);return i?ig(t,i,n)??sg(t,i)??tg(t):xu(t,r)}function vu(t,e,n){try{return og(t,e,n)}catch{let r=K(t);return r.issues.push(k("manifest_invalid","manifest","plugin.json","plugin entry could not be loaded")),r}}function bu(t){return t&&at(t)?M(t):null}function ag(t){let e=t.builtin?Y(t.builtin):[],n=t.user?Y(t.user):[];return[...new Set([...e,...n])].sort()}function ug(t,e){return t.name<e.name?-1:t.name>e.name?1:0}function lg(t,e){let n=new Map(t.skills.map(r=>[r.name,r]));for(let r of e.skills)n.set(r.name,Kt(r,Ue(r),n.has(r.name)?"overridden":"local"));t.skills=[...n.values()].sort(ug),t.issues.push(...e.issues)}function cg(t,e,n){if(!j(T.join(e,"mcp.json"))||!t.manifest.schema)return;let r=gr(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 dg(t,e,n){let r=e?T.join(e,t.id):null;if(!r||!j(r))return t;let i=wu(e,r);return i?(t.kind==="portable"&&t.valid&&(lg(t,vr(i,"portable")),cg(t,i,n)),t):{...t,issues:[...t.issues,...xu(t.id,r).issues]}}function pg(t,e){let n=vu(t,e.builtin,e.dataDir),r={...n,origin:"builtin",skills:n.skills.map(i=>Kt(i,Ue(i),"builtin"))};return dg(r,e.user,e.dataDir)}function fg(t,e){return e.builtin&&j(T.join(e.builtin,t))?pg(t,e):vu(t,e.user,e.dataDir)}function Er(t={}){let e={user:bu(T.resolve(t.pluginsDir??we)),builtin:bu(t.builtinDir===void 0?ut():t.builtinDir),dataDir:T.resolve(t.dataDir??A)},n=ag(e).filter(r=>!t.ids||t.ids.has(r)).map(r=>fg(r,e));return mg(n),n}function mg(t){let e=new Map;for(let n of t){if(n.kind!=="portable"||!n.valid)continue;let r=J(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(J(n))??[]).filter(i=>i!==n.id);r.length!==0&&n.issues.push(k("manifest_name_duplicate","manifest","plugin.json.name",`Plugin name "${J(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 hg(t){return[...t].sort((e,n)=>e.localeCompare(n))}function gg(t){let e=T.join(t,"skills");return Y(e).filter(n=>ce(T.join(e,n,"SKILL.md"))).map(n=>({name:n,description:yr(T.join(e,n,"SKILL.md"))}))}function yg(t){return[...t].sort((e,n)=>e.name.localeCompare(n.name))}function Sg(t,e){let n=new Map;for(let r of t){let i=T.join(e,r.id);n.set(i,r);let s=M(i);s&&n.set(s,r)}return n}function kg(t,e,n){if(n?.kind==="portable"&&!n.valid)return[];let r=n?.id??t,i=n?J(n):T.basename(e),s=n?.kind==="portable"?n.skills:gg(e);return yg(s).map(o=>({plugin:r,namespace:i,name:o.name,description:o.description}))}function Eu(t,e,n,r){let i=Sg(t,e),s=[],o=new Set;for(let a of r){let u=T.isAbsolute(a)?T.resolve(a):T.resolve(n,a),l=M(u)??u;o.has(l)||(o.add(l),s.push(kg(a,l,i.get(u)??i.get(l))))}return s.filter(a=>a.length>0)}function Iu(t){let e=T.resolve(t.pluginsDir??we),n=T.resolve(t.dataDir??A);return{entries:Er({pluginsDir:e,dataDir:n,builtinDir:t.builtinDir}),pluginsDir:e,dataDir:n}}function mx(t){let{entries:e,pluginsDir:n,dataDir:r}=Iu(t);return Eu(e,n,r,t.pluginDirs).flat()}function hx(t={}){let{entries:e,pluginsDir:n,dataDir:r}=Iu(t);return t.pluginDirs?Eu(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:hg(i.skills.map(s=>s.name))}))}import Yt from"node:fs";import Qt from"node:path";var Cr=f("plugin-runtime"),bg=10080*60*1e3,Tg=3600*1e3,Cu=/^(plugin|skill)_/,_g=/^[0-9a-f]{64}\.json(?:\.tmp\..+)?$/,Au=["claude-mcp","claude-mcp-proxies"],Ru=new Map;function Ar(t){try{let e=new Date;Yt.utimesSync(t,e,e)}catch{}}function Ir(t,e){try{return Yt.readdirSync(t).filter(n=>e.test(n)).map(n=>Qt.join(t,n))}catch{return[]}}function wg(t,e,n){try{let r=Yt.lstatSync(t);return n(r)&&e-r.mtimeMs>=bg}catch{return!1}}function Pu(t,e){return e-(Ru.get(t)??0)<Tg?!0:(Ru.set(t,e),!1)}function Ou(t,e,n,r){let i=[];for(let s of t)if(!(e.has(s)||!wg(s,n,r)))try{Yt.rmSync(s,{recursive:!0,force:!0}),i.push(s)}catch(o){Cr.warn(`Could not remove stale plugin runtime entry ${s}: ${o.message}`)}return i}function Lu(t,e,n=Date.now()){if(Pu(t,n))return[];let r=[...Ir(t,Cu),...Ir(Qt.join(t,"skill-snapshots"),Cu)],i=Ou(r,e,n,s=>s.isDirectory());return i.length>0&&Cr.info(`Removed ${i.length} stale plugin runtime dir(s) under ${t}`),i}function Mu(t,e=Date.now()){if(Pu(Qt.join(t,Au[0]),e))return[];let n=Au.flatMap(i=>Ir(Qt.join(t,i),_g)),r=Ou(n,new Set,e,i=>i.isFile());return r.length>0&&Cr.info(`Removed ${r.length} stale Claude MCP config(s) under ${t}`),r}var Zt=f("plugin-runtime");function Be(t,e){Zt.warn(e),t.push(e)}function vg(t){return JSON.stringify(t)}function Eg(t){return`[${t.map(e=>$e(e)??"null").join(",")}]`}function Ig(t){return`{${Object.keys(t).sort().flatMap(n=>{let r=$e(t[n]);return r===void 0?[]:[`${JSON.stringify(n)}:${r}`]}).join(",")}}`}function $e(t){return t===null||typeof t!="object"?vg(t):Array.isArray(t)?Eg(t):Ig(t)}function $u(t){let e=$e(t);if(e===void 0)throw new TypeError("Value is not JSON-serializable");return xg("sha256").update(e,"utf8").digest("hex")}function Du(t){return t.length>0?t:void 0}function Bu(t,e){return y.isAbsolute(e)?y.resolve(e):y.resolve(t,e)}function Cg(t){return t!=="none"}function Ag(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:M(i)??i})}return n}function Rg(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 Pg(t,e){return xe([t.id,e],"plugin")}function Og(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 E(i,"Portable plugin data"),{name:r,type:"stdio",command:n.command,args:[...n.args],env:{...n.env},cwd:n.cwd}}function Lg(t,e){let n=nu(e);if(!n)throw new Error(`Portable MCP runtime missing for '${t.id}/${e.name}'`);let r=Pg(t,e.name);if(e.type==="stdio")return Og(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 Mg(t,e,n){try{let r=Ue(e);if(!r)throw new Error("its plugin layer is unknown");let i=y.join(r,e.dir),s=M(i)??i,o=Jt(r,s);return{name:e.name,root:r,target:s,contentSha256:o.sha256,tree:o}}catch(r){return Be(n,`Skipping portable skill '${t.entry.id}/${e.name}': ${r.message}`),null}}function Dg(t,e){return t.entry.skills.flatMap(n=>{let r=Mg(t,n,e);return r?[r]:[]})}function Ng(t,e){return $u({pluginId:t.entry.id,manifest:Fu(t.entry),skills:e.map(n=>({name:n.name,sha256:n.contentSha256}))})}function Fu(t){let e=Wi(t.manifest.version);return`${JSON.stringify({name:J(t),...e?{version:e}:{},...t.manifest.description?{description:t.manifest.description}:{}},null,2)}
|
|
78
|
+
`}function jg(t){return C.readdirSync(t).sort((e,n)=>e.localeCompare(n))}function Rr(t){let e=C.lstatSync(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Claude projection target is invalid: ${t}`)}function Pr(t,e,n){if($e(jg(t))!==$e(e))throw new Error(`Claude projection ${n} mismatch: ${t}`)}function Ug(t,e){let n=y.join(t,".claude-plugin");if(Rr(n),Pr(n,["plugin.json"],"manifest directory"),C.readFileSync(y.join(n,"plugin.json"),"utf8")!==e)throw new Error(`Claude projection manifest mismatch: ${t}`)}function $g(t,e){let n=y.join(t,"skills");Rr(n);let r=e.map(i=>i.name).sort((i,s)=>i.localeCompare(s));Pr(n,r,"skill set");for(let i of e)wr(y.join(n,i.name),i.tree)}function Bg(t,e,n){Rr(t),Pr(t,[".claude-plugin","skills"],"root"),Ug(t,e),$g(t,n)}function Wu(t){E(t,"Claude projection"),E(y.join(t,".claude-plugin"),"Claude projection"),E(y.join(t,"skills"),"Claude projection")}function Fg(t,e,n){Wu(t),Lr(y.join(t,".claude-plugin","plugin.json"),e);for(let r of n)_r(r.target,r.target,r.tree,y.join(t,"skills",r.name))}function Wg(t,e,n){let r=Ng(e,n);return y.join(t,xe([e.entry.id,r],"plugin"))}function Ku(t,e){let n=`${process.pid}:${Date.now()}:${Math.random()}`;return y.join(t,xe([y.basename(e),n],"plugin_tmp"))}function Kg(t,e,n,r){let i=Ku(y.dirname(r),r);C.mkdirSync(i,{mode:448});try{return Fg(i,n,e),C.renameSync(i,r),!0}catch(s){if(C.rmSync(i,{recursive:!0,force:!0}),!C.existsSync(r))throw s;return!1}}function Nu(t,e,n){return Bg(t,e,n),Wu(t),t}function Hg(t,e,n){let r=xe([e.entry.id,n.name,n.contentSha256],"skill");return y.join(t,r,n.name)}function zg(t,e,n){let r=Ku(y.dirname(n),n);try{return _r(e.root,e.target,e.tree,r,{requireSourceSignature:!0}),C.renameSync(r,n),!0}catch(i){if(C.rmSync(r,{recursive:!0,force:!0}),!C.existsSync(n))throw i;return!1}}function ju(t,e){return wr(t,e.tree),E(t,"Portable skill snapshot"),t}function Gg(t,e,n,r){E(n,"Plugin runtime");let i=y.join(n,r,"skill-snapshots");E(i,`${r} skill snapshots`);let s=Hg(i,t,e);if(E(y.dirname(s),`${r} skill snapshot`),C.existsSync(s))return Ar(y.dirname(s)),ju(s,e);let o=zg(t,e,s);try{return ju(s,e)}catch(a){throw o&&C.rmSync(s,{recursive:!0,force:!0}),a}}function Vg(t,e,n,r,i){try{return{...e,target:Gg(t,e,n,r)}}catch(s){return Be(i,`Skipping portable skill '${t.entry.id}/${e.name}': ${s.message}`),null}}function Jg(t,e,n,r,i){return e.flatMap(s=>{let o=Vg(t,s,n,r,i);return o?[o]:[]})}function Xg(t,e,n,r){E(n,"Plugin runtime");let i=y.join(n,r);E(i,`${r} plugin projection`);let s=Fu(t.entry),o=Wg(i,t,e);if(C.existsSync(o))return Ar(o),Nu(o,s,e);let a=Kg(t,e,s,o);try{return Nu(o,s,e)}catch(u){throw a&&C.rmSync(o,{recursive:!0,force:!0}),u}}function Qg(t,e,n,r,i){if(e.length===0)return null;try{return Xg(t,e,n,r)}catch(s){return Be(i,`Skipping portable skills for '${t.entry.id}': ${s.message}`),e.splice(0),null}}function Yg(t,e,n){try{return[Lg(t,e)]}catch(r){return Be(n,`Skipping portable MCP '${t.id}/${e.name}': ${r.message}`),[]}}function Zg(t,e,n,r,i,s){let o=Jg(t,ry(t,Dg(t,s),i),n,e,s);return{skills:o,projectionDir:e==="claude"?Qg(t,o,n,e,s):null,mcpServers:r?t.entry.mcp.servers.flatMap(a=>Yg(t.entry,a,s)):[]}}function qg(t,e,n,r,i,s){if(!(!r&&!i&&!s))return $u({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(a=>({name:a.name,target:a.target,contentSha256:a.contentSha256}))??[]})})}function ey(t,e){if(!t.valid){let n=t.issues[0]?.message??"manifest is invalid";Be(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 ty(t,e,n,r,i){if(n?.kind==="portable")return ey(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 ny(t,e,n,r){let i=Rg(t,e),s={items:[],portableSelections:new Map,selectedLegacySkills:[],warnings:[]},o=new Set;for(let a of r){let u=Bu(n,a),l=M(u),c=i.byAbsolute.get(u)??(l?i.byRealpath.get(l):void 0);ty(u,l,c,s,o)}return s}function ry(t,e,n){let r=[];for(let i of e){let s=n.get(i.name);if(s!==void 0){Zt.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 iy(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 sy(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 oy(t,e){let n=J(e.entry),r=t.get(n);return r!==void 0?(Zt.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 ay(t,e,n,r){let i=new Map,s=new Map,o=new Map,a=new Set,u=[];for(let[l,c]of t){if(!oy(s,c))continue;let p=Zg(c,e,n,r,o,u);iy(o,l,p.skills),sy(p,a),i.set(l,p)}return{details:i,skillClaims:o,warnings:u}}function uy(t,e){for(let{name:n,pluginId:r}of e){let i=t.get(n);i!==void 0&&Zt.warn(`Skill '${n}' is provided by both portable plugin '${i}' and legacy plugin '${r}'. Deselect one of them to make the choice explicit.`)}}function ly(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 cy(t,e,n,r){if(t.kind==="preserved")return void r.pluginDirs.push(t.path);let i=e.get(t.id);i&&ly(i,n,r)}function dy(t,e,n){let r={pluginDirs:[],pluginSkillDirs:[],mcpServers:[]};for(let i of t)cy(i,e,n,r);return r}function py(t,e,n){let r=dy(e,n,t),i=Du(r.pluginDirs),s=t==="pi"?Du(r.pluginSkillDirs):void 0,o=r.mcpServers.length>0?r.mcpServers:void 0;return{pluginDirs:i,pluginSkillDirs:s,mcpServers:o,pluginCapabilityFingerprint:qg(t,e,n,i,s,o)}}function fy(t,e,n,r){let i=new Set;for(let o of n){let a=Bu(e,o);i.add(a);let u=M(a);u&&i.add(u)}let s=new Set;for(let o of new Set([...Y(t),...r])){let a=y.resolve(t,o);(i.has(a)||i.has(M(a)??a))&&s.add(o)}return s}function my(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 Hu(t){let e=y.resolve(t.dataDir??A),n=y.resolve(t.pluginsDir??we),r=Ce(e,e),i=Ce(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?ut():t.builtinDir,a=fy(n,e,s,as(o)),u=Er({pluginsDir:n,dataDir:r,builtinDir:o,ids:a}),l=ny(u,Ag(n,u),e,s);if(l.items.length===0)return Uu({},l.warnings);let c=ay(l.portableSelections,t.backend,i,Cg(t.mcpComposition));uy(c.skillClaims,l.selectedLegacySkills),Lu(y.join(i,t.backend),my(c.details)),Mu(i);let p=py(t.backend,l.items,c.details);return Uu(p,[...l.warnings,...c.warnings])}function Uu(t,e){return e.length>0?{...t,warnings:e}:t}var hy=[{plugin:"cortex-feishu",channelPrefix:"feishu:"}];function gy(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=hy.find(o=>o.plugin===r);return i?!!(r==="cortex-feishu"&&e.feishuSkillsInWeb===!0&&e.channel?.startsWith("web:"))||!!e.channel?.startsWith(i.channelPrefix):!0})}function yy(t,e,n){return{selection:{...e},project:t.context.project??null,trackSessionId:t.session.sessionId??t.session.backendSessionId??null,executionId:n??null}}function Sy(t){return Array.isArray(t.spec.tools)?t.spec.tools:void 0}function ky(t){return typeof t.spec.tools=="string"?t.spec.tools:void 0}function by(t){return{mcp:{composition:void 0,servers:void 0,allowlist:t.policy.mcpToolAllowlist===void 0?void 0:Jr(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 Ty(t,e,n){let r=gy(t.spec.pluginDirs,{channel:t.context.channel,feishuSkillsInWeb:h().feishuSkillsInWeb}),i=Hu({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 _y=["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","ANTHROPIC_BASE_URL"];function wy(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 xy(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 vy(t,e){let n=et(t);return n?{connection:n.connection,piAgentDir:n.agentDir}:{anthropicBaseUrl:e?.baseUrl,connection:e?.connection,...e?.configDir?{claudeConfigDir:e.configDir}:{}}}function zu(t,e,n={}){let{route:r,executionId:i=null}=n,s=rt(t.policy.mcpComposition),o=yy(t,e,i),a=Va(t.spec,{rules:Ja(t.policy.loadRules!==!1),workspace:t.policy.clean&&t.cwd?Xi(t.cwd):null}),u=Ty(t,e,s),l=by(t),c=e.backend==="pi"?{unsets:[..._y]}:wy(r),p=e.backend==="pi"&&e.provider||void 0;return{engineKey:t.session.engineKey||t.context.channel||"default",cwd:t.cwd??void 0,resume:{backendSessionId:t.session.backendSessionId??null,resume:!!t.session.backendSessionId},model:{id:e.model,provider:p,thinking:e.thinking||void 0,benchmarkMaxOutputTokens:e.backend==="pi"&&t.benchmark?.evidenceContext?t.benchmarkMaxOutputTokens:void 0},prompt:{system:typeof t.spec.systemPrompt=="string"?t.spec.systemPrompt:void 0,append:a},tools:{canonical:Sy(t),rawClaude:ky(t)},plugins:{dirs:u.dirs,skillDirs:u.skillDirs,fingerprint:u.fingerprint,...u.warnings?{warnings:u.warnings}:{}},mcp:{...l.mcp,composition:s,servers:u.servers},env:{sets:c.sets,unsets:c.unsets,pinned:t.isolation?.pinnedEnv,context:o},route:vy(e,r),flags:l.flags,context:{channel:t.context.channel,callbackSource:t.context.callbackSource??void 0,scheduleTaskId:t.context.scheduleTaskId??void 0},backend:xy(t,e),process:l.process}}var qt=f("run-attempt");function Ey(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 Iy(t,e){return e?t?`${t}:bg-continuation`:"bg-continuation":t||"unknown"}function Cy(t,e,n,r){e.request.policy.recordCost!==!1&&ns({...n,project:e.request.context.project||"general",trigger:Iy(e.request.context.trigger,r),cost_usd:t.cost_usd,backend:e.attempt.backend,connection:t.connection??ts(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=>qt.warn("recordCost failed:",i?.message??i))}function Ay(t){if(t.length!==0)return e=>{for(let n of t)try{n.onEvent(e)}catch(r){qt.warn("required sink failed:",r?.message??r)}}}async function Ry(t){for(let e of t)try{await e.onClose?.()}catch(n){qt.warn("required sink close failed:",n?.message??n)}}function Py(t){for(let e of t)try{e.onClose?.()}catch(n){qt.warn("required sink close failed:",n?.message??n)}}async function Oy(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 Ly(){let t,e;return{promise:new Promise((r,i)=>{t=r,e=i}),resolve:t,reject:e}}function My(t){return t==="hold"}function Gu(t){let{request:e,attempt:n,executionId:r,route:i}=t,s=zu(e,n,{route:i,executionId:r}),o=ls({adapterBackend:n.backend,spec:s,request:e,executionId:r,selection:e.selection}),a=o?us({identity:o,spec:s,canonicalInstruction:e.benchmark?.identityDirective??"",message:e.prompt.text}):null,u=Ey(e,r,o),l=[...a?[a]:[],...t.requiredSinks??[]],c=Ay(l),p=e.policy.background,m=My(p),_,x;try{_=$t.acquire(s),x=_.run({text:e.prompt.text,attachments:e.prompt.attachments},{awaitBackground:p,...c?{onNormalizedEvent:c}:{}})}catch(X){throw Py(l),X}let g=!1,O=Ly(),tn=(async()=>{try{for await(let X of x.events)X.type==="cost_record"&&Cy(X,t,u,g),t.onEvent(X),X.type==="foreground_result"&&(g=!0,m&&O.resolve(X.result))}finally{await Ry(l)}})(),Or=Oy(x,tn);return Or.then(O.resolve,O.reject),O.promise.catch(()=>{}),{engine:_,engineRun:x,spec:s,identity:o,backend:n.backend,foreground:O.promise,settled:Or,get backendSessionId(){return _.backendSessionId},kill:()=>_.kill()}}var Fe=f("run"),Vu=3;function oe(t){return t instanceof Error?t:new Error(String(t))}function Dy(t){return Object.assign(new Error(`Run cancelled (${t})`),{cancelled:!0})}var en=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=Ju();resultDeferred=Ju();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 Ut({channel:e.request.context.channel,isUserInitiated:e.request.context.isUserInitiated,trigger:e.request.context.trigger,failoverResume:(n,r)=>Da(e.request.selection,{provider:n,route:r})!==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 z[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(Oa(e,this.request.context)){let r=rr(w(e),ir(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;if(!h().accountFailover)return e;let n=Ma(e);return this.noteFailover(n),n?(this.attemptValue={index:0,config:n.selection},n.selection):e}noteFailover(e){let n=this.request.context.channel??"";!Na(n,e)||!e||(Fe.info(`Account failover on ${n||"(no channel)"}: ${e.from} \u2192 ${e.to}`),n.startsWith("web:")&&this.notices.observe(S("notify.accountFailover",{from:lr(this.request.selection),to:lr(e.selection)}),void 0,"info"))}openAttempt(e){let n={...tr};this.liveSpend=n;let r=Gu({request:this.request,attempt:e,executionId:this.executionId,route:this.routeFor(e),onEvent:i=>{Ca(n,i),this.onRunEvent(i)}});return this.current=r,this.registerAttempt(r,jt(e)),this.announcePluginWarnings(r.spec),r}routeFor(e){return ss(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(oe(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),Pa(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:w(this.attemptValue.config)}}attributeError(e){let n=oe(e),r=sr(this.attemptValue.config);if(r&&Ne(n)){let i=n;i.rateLimitProvider||(i.rateLimitProvider=r,i.rateLimitRoute=w(this.attemptValue.config))}return n}publishAuthOutcome(e,n,r=this.attemptValue.config){let i={backend:r.backend,provider:ir(r),connection:jt(r)};if(e){e.rateLimited||is(i);return}let s=le(n?.message??"");s&&rs({...i,authType:La(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(R.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){Fe.warn("run steer failed:",oe(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){Fe.warn("run kill failed:",oe(n).message)}this.finishTerminal("cancelled",null,Dy(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"}),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,ja(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&&h().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,Vu).join(`
|
|
79
|
+
`),i=n.length-Vu;this.notices.observe(S("notify.pluginsUnavailable",{detail:i>0?`${r}
|
|
80
|
+
${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(dn,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&&Ee(e)>0&&(this.phaseValue="background",this.statusValue="background"))}onForegroundError(e){if(this.terminal)return;let n=oe(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){Fe.warn("run terminal handler failed:",oe(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?Ia(e):this.liveSpend??tr}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){Fe.warn("run observer failed:",oe(e).message)}};function Ju(){let t,e;return{promise:new Promise((r,i)=>{t=r,e=i}),resolve:t,reject:e}}var qu=new Set(["cache-refresh","manual-compact"]),Ny=/tim(?:ed? ?out|eout)|\bturn idle for\b/i,jy=/exited with code|process exited|spawn|SIGSEGV|SIGABRT|killed|crash/i,Uy=[["auth",t=>!!le(t)],["rate_limit",Te],["timeout",t=>Ny.test(t)],["network",t=>Ne(new Error(t))],["adapter_crash",t=>jy.test(t)]];function $y(t){return Uy.find(([,e])=>e(t))?.[0]??"other"}function By(t){return H.billingOf(t.selection)==="subscription"?"plan":"api"}function Xu(t,e){return t.tools.has(e)||t.tools.set(e,{calls:0,errors:0}),t.tools.get(e)}var Fy=new Set(["assistant_text","assistant_delta","assistant_thinking","assistant_thinking_delta","tool_use"]),Wy={completed:"completed",failed:"failed",killed:"cancelled"};function Qu(t,e){if(e.type==="tool_use"){t.toolNames.set(e.toolUseId,e.name),Xu(t,e.name).calls+=1;return}let n=t.toolNames.get(e.toolUseId);n&&!e.ok&&(Xu(t,n).errors+=1)}function Ky(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 Hy={tool_use:Qu,tool_result:Qu,cost_record:Ky,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[Wy[e.status]??"failed"]+=1}};function zy(t,e){t.firstOutputAt===null&&Fy.has(e.type)&&(t.firstOutputAt=Date.now()),Hy[e.type]?.(t,e)}function Gy(){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 el(t){let e=Gy(),n=!1;return{observer:{onEvent:r=>{try{zy(e,r)}catch{}}},finish:r=>{n||(n=!0,Zr(i=>Yy(i,t,e,r)),r.status==="completed"&&!qu.has(t.context.trigger)&&(sn("provider_authed",t.selection.backend),sn("first_turn_completed")))}}}function Yu(t,e){let{backend:n,provider:r,model:i}=e.selection,s=By(e),o=[n,r??"",i,s].join("|");return t.turns[o]??=Yr(n,r??"",i,s),t.turns[o]}function Vy(t,e){if(e.status==="rate-limited"?t.outcomes.rateLimited+=1:t.outcomes[e.status]+=1,e.status==="failed"){let n=$y(e.error?.message??"");t.failures[n]=(t.failures[n]??0)+1}}function Jy(t,e,n){Vy(t,n),t.retries+=e.retries,t.fallbacks+=e.fallbacks,n.status==="completed"&&e.firstOutputAt!==null&&(t.ttftMs[Ve("ttftMs",e.firstOutputAt-e.startedAt)]+=1),t.durationS[Ve("turnDurationS",n.durationS)]+=1,e.contextPct!==null&&(t.contextPctAtEnd[Ve("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 tl(t){return t.status==="rate-limited"?"failed":t.status}function Xy(t){return t.status==="cancelled"?/\((\w+)\)/.exec(t.error?.message??"")?.[1]??null:null}function Zu(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 Qy(t,e,n,r){let i=Xy(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[tl(r)]+=1);let s=e.session.sessionId;s&&(t.agent.sessionTurns[s]=(t.agent.sessionTurns[s]??0)+1)}function Yy(t,e,n,r){let{trigger:i}=e.context;if(i==="subagent")return t.agent.subagents[tl(r)]+=1,Zu(t,n);if(qu.has(i)){n.compactions.manual>0&&(Yu(t,e).compactions.manual+=n.compactions.manual);return}Jy(Yu(t,e),n,r),Zu(t,n),Qy(t,e,n,r)}function Zy(t){return!t.benchmark?.evidenceContext||!t.session.sessionId?t:{...t,benchmarkMaxOutputTokens:t.benchmarkMaxOutputTokens??_a(t.session.sessionId)}}function qy(t){return er({kind:t.context.executionKind,channel:t.context.channel,project:t.context.project,trigger:t.context.trigger,backend:t.selection.backend,billingMode:w(t.selection),sessionId:t.session.sessionId,ownerSessionId:t.context.ownerSessionId??null,label:t.prompt.text.substring(0,60),scheduleTaskId:t.context.scheduleTaskId||null})}function eS(t,e){let{status:n,result:r,spend:i,error:s,durationS:o}=e;Dt({executionId:t,status:n,result:r,spend:i,error:s?{message:s.message}:null,durationS:o}),V.remove(t)}function nl(t,e){t=Zy(t);let n=Date.now(),r=qy(t),i=el(t),s=new en({request:t,observers:[...e,i.observer],executionId:r.id,registry:V,startedAt:n,onTerminal:o=>{eS(r.id,o),i.finish(o)}});return s.start(),s}function Pv(){return{systemPrompt:null,directive:null,promptTemplate:null,tools:null,pluginDirs:[],mcp:{composition:"direct",allowlist:null},backendOptions:{}}}function Ov(t,e){return{systemPrompt:t.systemPrompt?Bt(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 rl(t,e,n={}){let r=Xr(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 tS=["user","project","local"];function nS(t){return(t??tS).filter(e=>e!=="project")}function il(t){return{...t,clean:!0,hooks:!1,loadRules:!1,settingSources:nS(t.settingSources)}}var sl=f("subagent-runner"),iS=["cortex-core","cortex-ext"];function sS(t){return Pi(t.task.model?.trim()||t.role.model?.trim())}function oS(t){return!!z[t]?.has(R.Subagents)}async function Qv(t){if(t.signal?.aborted)throw new Error("Subagent was aborted.");if(!oS(t.backend))throw new Error(`Backend "${t.backend}" cannot run subagents.`);return t.backend==="pi"?aS(t):hS(t)}async function aS(t){let[{runPiChild:e},{childExtensions:n}]=await Promise.all([import("./child-runner-MO5RT6FH.js"),import("./tool-shims-IA2WELXJ.js")]),r=lS(t),i=Mt(),s=uS(t.parent,r)??i.agentDir;try{i.ensureCatalog(s)}catch(o){sl.warn(`Could not write the PI catalog for a pi subagent: ${o.message}`)}return e({task:t.task,role:t.role,cwd:t.cwd,workspace:t.workspace??null,agentDir:s,parentEnv:t.parent.env??process.env,model:r,childExtensions:o=>n(o,ot),signal:t.signal,forward:cS(t)})}function uS(t,e){if(t.backend!=="pi"||!t.connection)return;let n=e.provider??t.provider??null;if(n===t.provider)return et({backend:"pi",provider:n,connection:t.connection})?.agentDir}function lS(t){let e=t.parent.backend==="pi"?t.parent:null,n=Oi(t.task,t.role,e);if(n.model)return n;let r=un({},{backend:"pi"});if(r.ok===!1)return{};let{provider:i,model:s}=r.selection;return{model:s,...i?{provider:i}:{}}}function cS(t){let e=t.onNotice;if(!e)return;let{ref:n,task:r}=t,i=!1;return(s,o)=>{let a=Ji(n,r,o,s);for(let u of a)try{e(i?u:{...u,prompt:r.prompt}),i=!0}catch{}}}function dS(t){return t.backend!=="claude"||!t.model?null:{backend:"claude",provider:null,model:t.model,thinking:null,connection:t.connection??null}}function ol(t,e){let n=dS(t.parent),r=un({request:n},{...n?{}:{backend:"claude"},...e.model?{model:e.model}:{},thinking:e.thinking??null});if(r.ok===!1)throw new Error(`A claude subagent cannot run (${r.reason}); favorite a Claude model or fix its thinking level.`);return r.effective}function pS(t,e){return`${t.parent.channel||"default"}#sub:${e}`}function al(t,e){let n=fS(t,e);return t.workspace?{...n,cwd:t.workspace,policy:il(n.policy)}:n}function fS(t,e){let n=Vr(void 0,iS),r=rS();return{runId:r,session:{sessionId:null,backendSessionId:null,engineKey:pS(t,r)},selection:e,cwd:t.cwd,spec:rl(t.role,"claude",{mcpAllowlist:n??null}),prompt:{text:`Task: ${t.task.prompt}`,attachments:[]},context:{channel:t.parent.channel??"",project:t.parent.project??"general",trigger:"subagent",ownerSessionId:t.parent.sessionId??null,executionKind:"local",isUserInitiated:!1,scheduleTaskId:null},policy:{background:"none",recordCost:!0,hooks:!1,loadRules:!1,mcpComposition:"direct",mcpToolAllowlist:n,captureTranscripts:!1}}}function mS(t,e){t.catch(()=>{}).then(()=>$t.close(e)).catch(n=>sl.warn(`releasing child engine ${e} failed: ${n.message}`))}async function hS(t){let e=sS(t),n=ol(t,e);if(!n.model)throw new Error("A claude subagent needs a model: set one on the task or the role.");let r=al(t,n),i=nl(r,t.onNotice?[ul(t)]:[]);mS(i.settled,r.session.engineKey);let s=()=>{i.cancel("user")};t.signal?.addEventListener("abort",s,{once:!0});let o;try{o=await i.result}finally{t.signal?.removeEventListener("abort",s)}if(t.signal?.aborted)throw new Error("Subagent was aborted.");return yS(t,o,n.model)}function gS(t){let e=t.reportedAccounting,n=Vi();return n.input=e?.inputTokens??0,n.output=e?.outputTokens??0,n.cacheRead=e?.cacheReadTokens??0,n.cacheWrite=e?.cacheCreationTokens??0,n.cost=t.total_cost_usd??0,n.turns=t.num_turns??0,n}function yS(t,e,n){let r=e.rateLimited||!e.finalOutput&&!!e.rateLimitMessage;return{description:t.task.description,prompt:t.task.prompt,subagentType:t.task.subagent_type,output:e.finalOutput??"",usage:gS(e),model:e.reportedAccounting?.model??n,backend:"claude",...r?{stopReason:"error",errorMessage:e.rateLimitMessage??"Subagent run failed."}:{}}}function ul(t){let e=t.onNotice,n=t.ref,r={ref:n,type:t.task.subagent_type,description:t.task.description,backend:"claude",...t.task.clean?{clean:!0}:{}},i=null,s=!1,o=a=>{try{e(s?a:{...a,prompt:t.task.prompt}),s=!0}catch{}};return{onEvent(a){if(!("subagent"in a&&a.subagent)){if(a.type==="assistant_text"){a.model&&(i=a.model),a.text&&o({...r,model:i,kind:"assistant_text",text:a.text});return}if(a.type==="tool_use"){o({...r,model:i,kind:"tool_use",toolUseId:`${n}:${a.toolUseId}`,name:a.name,input:a.input});return}a.type==="tool_result"&&o({...r,model:i,kind:"tool_result",toolUseId:`${n}:${a.toolUseId}`,ok:a.ok,content:a.content,...a.images?.length?{images:a.images}:{}})}}}}var Yv={claudeChildConfig:ol,claudeChildRequest:al,claudeNoticeObserver:ul};export{hl as a,ys as b,R as c,LS as d,Ee as e,Ie as f,Os as g,gn as h,yn as i,Ns as j,mk as k,Pc as l,Us as m,qc as n,Z as o,Ck as p,io as q,cb as r,vo as s,Eo as t,ne as u,wt as v,BT as w,Vp as x,QT as y,YT as z,ZT as A,qT as B,aa as C,e_ as D,a_ as E,Vn as F,Xn as G,k_ as H,F as I,Sa as J,V as K,F_ as L,W_ as M,rm as N,om as O,er as P,wa as Q,lm as R,cm as S,Ea as T,Te as U,je as V,Ma as W,Da as X,pw as Y,Bt as Z,Lw as _,Mw as $,jm as aa,Xa as ba,jw as ca,Th as da,_h as ea,Er as fa,mx as ga,hx as ha,hy as ia,gy as ja,wy as ka,zu as la,nl as ma,Pv as na,Ov as oa,il as pa,oS as qa,Qv as ra,Yv as sa,U_ as ta,Mt as ua,$t as va};
|