@readmagic/workmate 0.0.23 → 0.0.24
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/dist/chunks/{AddWorkspaceDirectory-OgcBcK5A.js → AddWorkspaceDirectory-Ch8IcWXO.js} +1 -1
- package/dist/chunks/AgentsMdExternalIncludesDialog-Cyia0s4g.js +1 -0
- package/dist/chunks/{AgentsMdExternalIncludesDialog-CNEifEyV.js → AgentsMdExternalIncludesDialog-LjI_H_Au.js} +1 -1
- package/dist/chunks/{App-B-3tPQ3k.js → App-BOqh_1tN.js} +1 -1
- package/dist/chunks/{BackgroundTasksDialog-COuhHcey.js → BackgroundTasksDialog-CSEuuoq9.js} +1 -1
- package/dist/chunks/{BypassPermissionsModeDialog-bJek4siJ.js → BypassPermissionsModeDialog-CwfCwUr9.js} +1 -1
- package/dist/chunks/CustomSelect-wmZ9jz0W.js +1 -0
- package/dist/chunks/{DiffDialog-B3X9FMpO.js → DiffDialog-BpXIEWiE.js} +1 -1
- package/dist/chunks/Doctor-CMpr7tdf.js +1 -0
- package/dist/chunks/{Doctor-6PXyjIi6.js → Doctor-DqW6j3_B.js} +1 -1
- package/dist/chunks/{ExitFlow-DgAZp_8U.js → ExitFlow-DacaBTlk.js} +1 -1
- package/dist/chunks/{Grove-CHatOzcE.js → Grove-CNqYPWI6.js} +1 -1
- package/dist/chunks/{InvalidConfigDialog-DXL92MN9.js → InvalidConfigDialog-0TMJItCC.js} +1 -1
- package/dist/chunks/{InvalidSettingsDialog-Dtmpzeps.js → InvalidSettingsDialog-iwh8H52b.js} +1 -1
- package/dist/chunks/{KeybindingProviderSetup-DA37QUFs.js → KeybindingProviderSetup-D49HHTXD.js} +1 -1
- package/dist/chunks/{MCPConnectionManager-thZd-xA_.js → MCPConnectionManager-Cie77ZAK.js} +1 -1
- package/dist/chunks/{MCPToolListView-CpY-YJg4.js → MCPToolListView-B4ehtkXd.js} +1 -1
- package/dist/chunks/{McpParsingWarnings-JvChf3xr.js → McpParsingWarnings-Bff66RtJ.js} +1 -1
- package/dist/chunks/{MessageSelector-C0_iw7SI.js → MessageSelector-Dpd6Iywp.js} +1 -1
- package/dist/chunks/{Messages-K4DDsDP9.js → Messages-DN7M3oS_.js} +1 -1
- package/dist/chunks/{Onboarding-C1UdzM-1.js → Onboarding-CQmE3rUf.js} +1 -1
- package/dist/chunks/{PromptInputFooterSuggestions-AyLog8p7.js → PromptInputFooterSuggestions-HI6HH3TP.js} +1 -1
- package/dist/chunks/{PromptInputHelpMenu-oyic20ip.js → PromptInputHelpMenu-3QNUC2Cg.js} +1 -1
- package/dist/chunks/{ProviderSetup-XcBHjUnd.js → ProviderSetup-BCSPsvfv.js} +1 -1
- package/dist/chunks/{QueryEngine-DYxBjJ4i.js → QueryEngine-DdLWvJv6.js} +1 -1
- package/dist/chunks/{REPL-CQBJRrT0.js → REPL-BqO9KcK_.js} +5 -5
- package/dist/chunks/REPL-CmZmypfF.js +1 -0
- package/dist/chunks/{ResumeConversation-Dl8H9Gfy.js → ResumeConversation-DBqX7gva.js} +1 -1
- package/dist/chunks/SearchExtraToolsTool-BsSoILFj.js +1 -0
- package/dist/chunks/{SelectMulti-Bc6l11_K.js → SelectMulti-BQRHed-d.js} +1 -1
- package/dist/chunks/{Settings-TGp3fPrS.js → Settings-B-7yBewS.js} +3 -3
- package/dist/chunks/{Spinner-zYPFVFHN.js → Spinner-ByQXTvAA.js} +1 -1
- package/dist/chunks/{TextInput-CD9iau2k.js → TextInput-B8ruWRf2.js} +1 -1
- package/dist/chunks/{ThemePicker-0F0hZYPX.js → ThemePicker-BQErFFW1.js} +1 -1
- package/dist/chunks/{TrustDialog-C76YiMKz.js → TrustDialog-BIhz6AZE.js} +1 -1
- package/dist/chunks/{_baseEach-4ff-vRlp.js → _baseEach-CsIRoaTH.js} +1 -1
- package/dist/chunks/{add-dir-JMsRLGfx.js → add-dir-CrUDs19x.js} +1 -1
- package/dist/chunks/{agentDisplay-BReJUBWg.js → agentDisplay-M4pfwbMC.js} +1 -1
- package/dist/chunks/{agents-9qQ8I6zW.js → agents-CGaCQeLw.js} +1 -1
- package/dist/chunks/{agents-B3x8yJ_r.js → agents-DddX7lLX.js} +1 -1
- package/dist/chunks/{allErrors-DfWylHSw.js → allErrors-BF73lon8.js} +1 -1
- package/dist/chunks/{backgroundHousekeeping-CVNIhQg8.js → backgroundHousekeeping-Bq3LMsVR.js} +2 -2
- package/dist/chunks/backgroundHousekeeping-Cl3Ox7Qh.js +1 -0
- package/dist/chunks/{branch-C4TsMEkx.js → branch-Yg_taNlT.js} +1 -1
- package/dist/chunks/{btw-Dn1eYFAz.js → btw-udbprVvu.js} +1 -1
- package/dist/chunks/caches-ChjIEcdd.js +1 -0
- package/dist/chunks/{caches-DArHxBgL.js → caches-DLJ6urv-.js} +1 -1
- package/dist/chunks/{clear-Bdhb6b39.js → clear-B8ZtFPOK.js} +1 -1
- package/dist/chunks/commands-CVCpJo7M.js +1 -0
- package/dist/chunks/{compact-Bu9BUpxV.js → compact-izk6RKHQ.js} +1 -1
- package/dist/chunks/config-CFqpXMFX.js +1 -0
- package/dist/chunks/{context-CY_yfdYa.js → context-BbVm4SWK.js} +1 -1
- package/dist/chunks/{context-noninteractive-Dd4xIoP1.js → context-noninteractive-C7wrRZnM.js} +1 -1
- package/dist/chunks/context-noninteractive-x0HAzWhc.js +1 -0
- package/dist/chunks/conversation-DouVzO0K.js +1 -0
- package/dist/chunks/{conversation-DUu9qBnq.js → conversation-DrVkifKy.js} +1 -1
- package/dist/chunks/{conversationRecovery-2ft8sCPE.js → conversationRecovery-DliPBo_z.js} +1 -1
- package/dist/chunks/{crossProjectResume-6boHMUBx.js → crossProjectResume-DxMy05_P.js} +1 -1
- package/dist/chunks/{datadog-BPuGcxxC.js → datadog-Cu3s7P48.js} +1 -1
- package/dist/chunks/{diff-BOAElpfQ.js → diff-DdpHThJ7.js} +1 -1
- package/dist/chunks/doctor-D_kV_D_l.js +1 -0
- package/dist/chunks/{entry-TNOoyy7_.js → entry-Bxseqbi_.js} +1 -1
- package/dist/chunks/{esm-eTAUP-La.js → esm-BXTZz3av.js} +1 -1
- package/dist/chunks/{exit-DXApFJIP.js → exit-C_R_FgzR.js} +1 -1
- package/dist/chunks/{extraUsage-CmQaLPV1.js → extraUsage-xMuDiNKh.js} +1 -1
- package/dist/chunks/extractMemories-D4Dl1itt.js +1 -0
- package/dist/chunks/{fast-eGx2IxD7.js → fast-DH-C5IZs.js} +1 -1
- package/dist/chunks/fast-bopOPrtf.js +1 -0
- package/dist/chunks/fetchModelList-DC4VQpqa.js +1 -0
- package/dist/chunks/{fetchModelList-CxLsVNsu.js → fetchModelList-FE8tzTDc.js} +1 -1
- package/dist/chunks/{fileSuggestions-DHxdwq28.js → fileSuggestions-C-9unnoJ.js} +1 -1
- package/dist/chunks/{firstPartyEventLogger-M6UMli2c.js → firstPartyEventLogger-QmjjQmgt.js} +2 -2
- package/dist/chunks/firstPartyEventLogger-lFeqhtfh.js +1 -0
- package/dist/chunks/{gemini-D_ORb_L6.js → gemini-C_ApXgwc.js} +1 -1
- package/dist/chunks/{generateSessionName-BQoDduyA.js → generateSessionName-CQ03xlYI.js} +1 -1
- package/dist/chunks/{goal-D7c2mSds.js → goal-CdL29Y8C.js} +1 -1
- package/dist/chunks/{grok-B2-ZbUiR.js → grok-C6WAslUT.js} +1 -1
- package/dist/chunks/{help-CZJdRviD.js → help-DxanITNN.js} +1 -1
- package/dist/chunks/{history-CQiUERTL.js → history-BMycjPTT.js} +1 -1
- package/dist/chunks/hooks-D9ApLkBp.js +1 -0
- package/dist/chunks/{hooks-DIvN6gdv.js → hooks-DR3IYPJ3.js} +1 -1
- package/dist/chunks/{install-T_CV1Slu.js → install-0D9u2dZw.js} +1 -1
- package/dist/chunks/{instrumentation-BjqUZ383.js → instrumentation-BFiGwntt.js} +3 -3
- package/dist/chunks/{job-R6c4-3c8.js → job-YhJQWgE0.js} +1 -1
- package/dist/chunks/{keybindings-CLRaiL_Z.js → keybindings-DZrF9iNd.js} +1 -1
- package/dist/chunks/{launchLocalMemory-DrbKrwXc.js → launchLocalMemory-DhJ56KDc.js} +1 -1
- package/dist/chunks/{launchOnboarding-tqsMD8ni.js → launchOnboarding-DmMoZwv5.js} +1 -1
- package/dist/chunks/{loadAgentsDir-DlPbtIsS.js → loadAgentsDir-B0Anodo0.js} +23 -23
- package/dist/chunks/loadAgentsDir-BbUR6pqH.js +1 -0
- package/dist/chunks/{loadPluginHooks-C_msxVIc.js → loadPluginHooks-BSwCtQ6T.js} +1 -1
- package/dist/chunks/{localSearch-CK-sFzPm.js → localSearch-BxLYi6w_.js} +1 -1
- package/dist/chunks/localSearch-zfn7jgrh.js +1 -0
- package/dist/chunks/{logoUtils-x2pHV-Nl.js → logoUtils-CRxTutvr.js} +1 -1
- package/dist/chunks/{magicDocs-BEF8D3if.js → magicDocs-Bkz7ZcmL.js} +1 -1
- package/dist/chunks/{main-kOVUGxOS.js → main-9ksgUUY_.js} +5 -5
- package/dist/chunks/{mcp-D0wAJrRT.js → mcp-ChF12reQ.js} +1 -1
- package/dist/chunks/{mcp-mgOlm1cY.js → mcp-DoEl5uah.js} +1 -1
- package/dist/chunks/{mcp-BNd29r6p.js → mcp-hp9qqjAy.js} +2 -2
- package/dist/chunks/{memory-DDLk9_LJ.js → memory-Qv-wGNQ5.js} +1 -1
- package/dist/chunks/{mode-CcNsWgK3.js → mode-bFXPCR2P.js} +1 -1
- package/dist/chunks/{model-DzCP4K-9.js → model-6lkW4o2c.js} +1 -1
- package/dist/chunks/{model-BwBG0V1u.js → model-BvQFFOf8.js} +1 -1
- package/dist/chunks/{modelOptions-DRaG3bo0.js → modelOptions-BBvF3wHK.js} +1 -1
- package/dist/chunks/{nativeInstaller-C3pVPqrZ.js → nativeInstaller-CdjmE9Zy.js} +1 -1
- package/dist/chunks/{notifications-4wP1Tx9Y.js → notifications-Bc6k-Ozy.js} +1 -1
- package/dist/chunks/{onChangeAppState-BlaoFbYF.js → onChangeAppState-DLjZ1x95.js} +1 -1
- package/dist/chunks/{openai-CDN71NdX.js → openai-D46QvESE.js} +1 -1
- package/dist/chunks/{overlayContext-BT2Lq8ei.js → overlayContext-8--_fbvY.js} +1 -1
- package/dist/chunks/{partition-CIl_ORUT.js → partition-DznN4XZH.js} +1 -1
- package/dist/chunks/{permissions-zSNOZSwr.js → permissions-DmGFViHI.js} +1 -1
- package/dist/chunks/{pidLock-BTqO-h7Y.js → pidLock-Cm4sW35f.js} +2 -2
- package/dist/chunks/{plan-Bs6em6lk.js → plan-CzGBz_87.js} +1 -1
- package/dist/chunks/{plugin-DDDxjBa0.js → plugin-CluR79xX.js} +1 -1
- package/dist/chunks/{pluginAutoupdate-8qugAFhb.js → pluginAutoupdate-ennb9k8_.js} +1 -1
- package/dist/chunks/{pluginBlocklist-q01ackCf.js → pluginBlocklist-9OrNEh--.js} +1 -1
- package/dist/chunks/{pluginCliCommands-DXZfCZsv.js → pluginCliCommands-CJv5uhOG.js} +1 -1
- package/dist/chunks/{pluginFlagging-BG2MHCQJ.js → pluginFlagging-js_-WmYj.js} +1 -1
- package/dist/chunks/{pluginOperations-hXYLrzM2.js → pluginOperations-CcUSHAIa.js} +1 -1
- package/dist/chunks/pluginStartupCheck-CRBUO9gP.js +1 -0
- package/dist/chunks/{pluginStartupCheck-DTMa6TgL.js → pluginStartupCheck-SRXOyqr7.js} +1 -1
- package/dist/chunks/{plugins-COoGBYk6.js → plugins-IwwaCDba.js} +1 -1
- package/dist/chunks/{print-BASybEtO.js → print-CgszM1ea.js} +2 -2
- package/dist/chunks/{processBashCommand-DDi_Pymt.js → processBashCommand-D098WsqY.js} +1 -1
- package/dist/chunks/{processSlashCommand-Cq9kaoSF.js → processSlashCommand-DOQFjJ88.js} +1 -1
- package/dist/chunks/prompt-BKPmDAuL.js +1 -0
- package/dist/chunks/{prompt-mM79EGnT.js → prompt-CJ1l3XXk.js} +1 -1
- package/dist/chunks/prompt-CgOklk7z.js +1 -0
- package/dist/chunks/{promptEditor-DLGN_eLu.js → promptEditor-DoGHJN_W.js} +1 -1
- package/dist/chunks/{reconciler-CeXqh95g.js → reconciler-ykkSPR-i.js} +1 -1
- package/dist/chunks/{refresh-Ce2yk28a.js → refresh-Dn_I1R4v.js} +1 -1
- package/dist/chunks/{reject-Bld5E-bn.js → reject-DtcCfuZV.js} +1 -1
- package/dist/chunks/{reload-plugins-C42xSB5l.js → reload-plugins-CQZFQLWP.js} +1 -1
- package/dist/chunks/{rename-CtBghpxZ.js → rename-DyEfsZiq.js} +1 -1
- package/dist/chunks/{resume-BWkaTDqd.js → resume-BcXEDUqZ.js} +1 -1
- package/dist/chunks/{runtimeObserver-1wQO8HSZ.js → runtimeObserver-DEuR8z0f.js} +1 -1
- package/dist/chunks/{runtimeObserver-XQrOux41.js → runtimeObserver-PJ1o8GRA.js} +2 -2
- package/dist/chunks/sandbox-adapter-DfB9kgQD.js +1 -0
- package/dist/chunks/{sandbox-toggle-Dir9Polo.js → sandbox-toggle-D9GDUsTl.js} +1 -1
- package/dist/chunks/searchExtraTools-D4gMMQv0.js +1 -0
- package/dist/chunks/{select-Bxf5-5sI.js → select-DIxfl_VN.js} +1 -1
- package/dist/chunks/sessionFileAccessHooks-lbgHnVvi.js +1 -0
- package/dist/chunks/{sessionObserver-DS4G6mb9.js → sessionObserver-BtKjvteq.js} +1 -1
- package/dist/chunks/sessionObserver-D6qzEdGJ.js +1 -0
- package/dist/chunks/sessionStorage-C_7gow_z.js +1 -0
- package/dist/chunks/{sessionTracing-BoDDYLxW.js → sessionTracing-CtbeAD0s.js} +1 -1
- package/dist/chunks/{setup-BRypY6iT.js → setup-qecdf-ES.js} +2 -2
- package/dist/chunks/{shadowedRuleDetection-BRxZjobz.js → shadowedRuleDetection-Bg_aIc5Z.js} +1 -1
- package/dist/chunks/{sideQuestion-DLJxyrlp.js → sideQuestion-D49GsfH7.js} +1 -1
- package/dist/chunks/sinks-C-lP7uyO.js +1 -0
- package/dist/chunks/{sinks-Cz2HfgMU.js → sinks-De-B1lPQ.js} +1 -1
- package/dist/chunks/{skillChangeDetector-xviGstqm.js → skillChangeDetector-DkOJoNhT.js} +1 -1
- package/dist/chunks/{skillGapStore-CKN_d3pO.js → skillGapStore-CcFoHNLl.js} +2 -2
- package/dist/chunks/{skillLifecycle-BMY2JGGG.js → skillLifecycle-Bnz_4wE5.js} +2 -2
- package/dist/chunks/{skillSearchPanel-D9trHULQ.js → skillSearchPanel-C_5yUhqn.js} +2 -2
- package/dist/chunks/{skills-CX_AvwLG.js → skills-BE5scC-g.js} +1 -1
- package/dist/chunks/status-Dw09WZLd.js +1 -0
- package/dist/chunks/{statusNoticeHelpers-vFVgIYuw.js → statusNoticeHelpers-BRQpUIlH.js} +1 -1
- package/dist/chunks/switcher-CgZVah7U.js +1 -0
- package/dist/chunks/{switcher-CAajZeNL.js → switcher-DZwUo5Ed.js} +1 -1
- package/dist/chunks/{tasks-BWNQr2d3.js → tasks-DdcUQEeD.js} +1 -1
- package/dist/chunks/{templateJobs-gUET39Ho.js → templateJobs-C8qsPrLj.js} +1 -1
- package/dist/chunks/{theme-B7fKI6E5.js → theme-f1h2QI8J.js} +1 -1
- package/dist/chunks/{tipRegistry-DamZr34w.js → tipRegistry-B71o4qWr.js} +1 -1
- package/dist/chunks/{toolEventObserver-BL06sDI4.js → toolEventObserver-7QP38x4t.js} +1 -1
- package/dist/chunks/{toolPool-CX5wDBi1.js → toolPool-V-7Yv0GA.js} +1 -1
- package/dist/chunks/{use-select-navigation-BiUJdWai.js → use-select-navigation-hWL5VHnL.js} +1 -1
- package/dist/chunks/{useExitOnCtrlCDWithKeybindings-C9BYG8Bo.js → useExitOnCtrlCDWithKeybindings-BKwzUpgb.js} +1 -1
- package/dist/chunks/useMainLoopModel-DxvV70Ru.js +1 -0
- package/dist/chunks/{useManagePlugins-BqfIVa6E.js → useManagePlugins-BXLXazrR.js} +1 -1
- package/dist/chunks/useMergedTools-CCgnBJzO.js +1 -0
- package/dist/chunks/{useSearchInput-B25K1RnK.js → useSearchInput-CzopttqC.js} +1 -1
- package/dist/chunks/{useSettingsErrors-DYQ44kX4.js → useSettingsErrors-SFPWfxsA.js} +1 -1
- package/dist/chunks/{util-CtlC2dsN.js → util-Cbb3S6SX.js} +1 -1
- package/dist/chunks/{validatePlugin-D6tFo87L.js → validatePlugin-BMSoeb_b.js} +1 -1
- package/dist/chunks/worktree-Vm-SNY5x.js +1 -0
- package/dist/cli.js +1 -1
- package/package.json +1 -1
- package/dist/chunks/AgentsMdExternalIncludesDialog-CDNd5-7E.js +0 -1
- package/dist/chunks/CustomSelect-DoeEXOIP.js +0 -1
- package/dist/chunks/Doctor-DNgkgYhB.js +0 -1
- package/dist/chunks/REPL-CrVuMQY2.js +0 -1
- package/dist/chunks/SearchExtraToolsTool-lv7VE50N.js +0 -1
- package/dist/chunks/backgroundHousekeeping-BGxHB_OX.js +0 -1
- package/dist/chunks/caches-BGzKwpnc.js +0 -1
- package/dist/chunks/commands-QepeBbFn.js +0 -1
- package/dist/chunks/config-D58C3_Lu.js +0 -1
- package/dist/chunks/context-noninteractive-BDDi3NLF.js +0 -1
- package/dist/chunks/conversation-B0wxBwzv.js +0 -1
- package/dist/chunks/doctor-CkLzqAMd.js +0 -1
- package/dist/chunks/extractMemories-xP63mv6R.js +0 -1
- package/dist/chunks/fast-C5nQH8rm.js +0 -1
- package/dist/chunks/fetchModelList-D24lRIgR.js +0 -1
- package/dist/chunks/firstPartyEventLogger-BVAogAX8.js +0 -1
- package/dist/chunks/hooks-BNuUlMzL.js +0 -1
- package/dist/chunks/loadAgentsDir-CcmY8zCj.js +0 -1
- package/dist/chunks/localSearch-DrUj0B-d.js +0 -1
- package/dist/chunks/pluginStartupCheck-HS1ZceZa.js +0 -1
- package/dist/chunks/prompt-CHobfCB1.js +0 -1
- package/dist/chunks/prompt-CMm6RHHc.js +0 -1
- package/dist/chunks/sandbox-adapter-8GO6eJxw.js +0 -1
- package/dist/chunks/searchExtraTools-BhDq8DTJ.js +0 -1
- package/dist/chunks/sessionFileAccessHooks-CozocHQE.js +0 -1
- package/dist/chunks/sessionObserver-DGEQM4cO.js +0 -1
- package/dist/chunks/sessionStorage-BcAscOGE.js +0 -1
- package/dist/chunks/sinks-CGdKmq_8.js +0 -1
- package/dist/chunks/status-Daaak6Bo.js +0 -1
- package/dist/chunks/switcher-BpgmH4AI.js +0 -1
- package/dist/chunks/useMainLoopModel-DwjSVzzO.js +0 -1
- package/dist/chunks/useMergedTools-Bw8FchX8.js +0 -1
- package/dist/chunks/worktree-B8apCnVe.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as e,i as t,n,o as r,r as i,t as a}from"./rolldown-runtime-DaDcL9Zw.js";import{a as o,n as s,o as c,t as l}from"./isObject-C6qM3WEW.js";import{n as u,t as d}from"./memoize-BK3gG5ob.js";import{c as f,f as p,i as m,l as h,o as g,r as _,s as v,u as y}from"./envUtils-DfkgIdYf.js";import{n as b,t as x}from"./defineProperty-C-QyHrDq.js";import{a as S,c as C,i as w,n as T,o as E,r as D,s as O,t as k}from"./classPrivateFieldSet2-D4U5K-I3.js";import{n as A,t as ee}from"./classPrivateMethodInitSpec-BXQD0Vh4.js";import{i as te,n as ne,r as re,t as ie}from"./figures-5ThXQEtq.js";import{c as ae,f as j,i as oe,l as se,m as ce,r as M,t as N,u as le}from"./zod-CuNujUwx.js";import{t as ue}from"./semver-DQo45qGo.js";import{$ as de,Ct as fe,J as pe,Q as me,St as he,X as ge,Y as _e,_t as ve,at as ye,bt as be,ct as xe,et as Se,ft as Ce,gt as we,ht as Te,lt as Ee,mt as De,nt as Oe,ot as ke,rt as Ae,st as je,tt as Me,ut as Ne,vt as Pe,xt as Fe,yt as Ie}from"./esm-eTAUP-La.js";import{n as Le,t as Re}from"./axios-DaWTGg7G.js";import{$r as ze,Bt as Be,Ct as Ve,D as He,Fr as Ue,Ft as We,Gr as Ge,Gt as Ke,H as qe,Hr as Je,I as P,Kr as Ye,Lr as eee,Lt as Xe,Mr as Ze,P as F,Pr as tee,Pt as nee,Qr as ree,Rn as Qe,T as $e,Tt as et,Vr as iee,Wt as aee,Xn as oee,Yt as see,Zt as cee,ai as tt,bn as lee,cr as uee,d as dee,di as nt,fi as rt,fr as fee,gr as pee,gt as mee,hr as hee,j as gee,l as _ee,ln as it,mi as vee,mr as yee,mt as bee,nt as xee,or as See,ot as at,pi as Cee,pr as wee,qr as ot,rn as Tee,sn as st,sr as Eee,t as ct,vn as Dee,xr as Oee,y as kee,yr as Aee,zr as jee}from"./src-DL3w8VPk.js";import{i as lt,r as Mee}from"./isSymbol-BO6cdPI7.js";import{t as ut}from"./jsx-runtime-Bb4Xn-E0.js";import{$ as dt,A as ft,E as Nee,F as pt,G as I,H as mt,I as Pee,J as ht,K as gt,L as _t,N as vt,O as Fee,P as L,Q as yt,S as bt,V as R,W as z,X as xt,Y as St,Z as B,_ as Ct,a as wt,at as Iee,b as Tt,et as Lee,f as Et,g as Dt,j as Ree,l as Ot,lt as zee,n as Bee,o as kt,r as At,rt as Vee,s as V,st as Hee,t as jt,u as Mt,ut as Uee,x as Nt,y as Pt,z as Ft}from"./types-Dx7P7JLQ.js";import{$ as Wee,An as Gee,At as Kee,Bn as qee,Br as It,Bt as Jee,C as Yee,Cr as Lt,Ct as Rt,Dn as zt,Dr as Xee,Dt as Bt,E as Vt,En as Ht,Er as Zee,F as Ut,Ft as Qee,G as Wt,H as Gt,Hr as Kt,I as qt,It as Jt,J as Yt,Jn as Xt,Kn as $ee,Kr as ete,L as tte,Lt as Zt,Mt as nte,N as Qt,O as rte,On as ite,Or as $t,Ot as ate,P as ote,Pt as ste,Q as en,Qn as cte,Qt as lte,R as tn,Rt as nn,S as ute,Sr as rn,St as an,T as dte,Tn as on,Tr as fte,Tt as pte,Ur as mte,V as hte,Vr as sn,Vt as gte,Wn as _te,Wt as cn,X as ln,Xr as vte,Xt as yte,Yn as bte,Z as un,Zr as xte,_ as Ste,_i as Cte,_n as wte,_r as Tte,_t as Ete,a as Dte,ai as Ote,at as dn,b as kte,bt as Ate,c as jte,ci as Mte,ct as fn,d as Nte,dt as Pte,en as Fte,er as pn,et as Ite,f as Lte,fi as Rte,ft as zte,g as Bte,gi as Vte,gn as Hte,gr as Ute,gt as Wte,h as mn,hi as Gte,ht as Kte,i as qte,ii as Jte,ir as Yte,it as hn,jn as Xte,jt as gn,kn as Zte,kr as _n,kt as Qte,li as vn,mi as $te,mn as yn,mt as bn,n as xn,nt as Sn,o as ene,on as Cn,or as wn,p as tne,pi as nne,pt as Tn,q as En,qn as Dn,qr as rne,r as ine,rn as ane,rt as On,s as kn,sr as An,st as jn,tn as Mn,tr as Nn,tt as one,u as Pn,ut as Fn,vr as sne,vt as In,w as cne,wr as Ln,wt as lne,xt as Rn,yr as une,yt as zn,z as dne,zt as fne}from"./state-B4jiUise.js";import{i as Bn,n as Vn,r as pne,t as H}from"./cwd-Pa83R95t.js";import{$ as Hn,A as Un,C as U,D as mne,E as Wn,F as Gn,G as hne,H as Kn,I as qn,J as Jn,K as Yn,L as gne,M as W,N as Xn,O as Zn,P as _ne,R as Qn,S as $n,T as er,V as tr,X as vne,Y as nr,Z as yne,_ as rr,c as G,d as ir,et as ar,f as or,g as sr,i as K,j as cr,k as lr,m as ur,p as dr,q as fr,s as pr,t as bne,tt as xne,u as q,v as Sne,x as mr,y as Cne,z as hr}from"./debug-Bglx1aTu.js";import{$n as gr,$r as wne,$t as Tne,A as _r,An as Ene,Ar as vr,At as yr,B as br,Bn as xr,Br as Dne,C as One,Cn as Sr,Cr,Dn as kne,Dr as wr,Dt as Tr,E as Ane,Er,Et as Dr,F as Or,G as kr,Gr as jne,H as Mne,Hn as Ar,Hr as Nne,Ht as jr,I as Mr,In as Nr,Ir as Pr,J as Pne,Jr as Fne,Jt as Ine,K as Fr,Kr as Lne,Kt as Rne,L as zne,Lr as Ir,Lt as Bne,M as Vne,Mn as Hne,Mr as Lr,N as Rr,Nn as Une,On as zr,Or as Br,Ot as Wne,P as Vr,Pn as Hr,Pt as Gne,Q as Kne,Qn as qne,Qr as Jne,Qt as Ur,R as Wr,Rn as Gr,Rr as Yne,S as Xne,Sn as Kr,Sr as Zne,St as qr,T as Qne,Tn as $ne,Tt as ere,U as tre,Un as nre,Ur as Jr,V as Yr,Vn as Xr,Vr as rre,Vt as Zr,W as ire,Wn as Qr,Wr as are,Wt as $r,X as ore,Xn as sre,Xr as ei,Xt as ti,Y as cre,Yn as lre,Yr as ni,Yt as ure,Z as ri,Zn as dre,Zr as fre,Zt as ii,_ as pre,_i as mre,_n as ai,_t as oi,a as hre,ar as si,at as ci,b as li,bn as gre,br as _re,c as ui,ci as vre,cr as yre,ct as di,d as fi,di as bre,dr as pi,dt as mi,ei as xre,en as Sre,er as hi,f as Cre,fi as gi,fn as wre,fr as Tre,ft as Ere,gi as Dre,gn as Ore,gr as kre,gt as _i,h as vi,hi as Are,hn as jre,hr as Mre,in as Nre,ir as yi,it as bi,jt as xi,k as Pre,kn as Si,kr as Ci,kt as Fre,l as Ire,li as Lre,ln as wi,lr as Ti,lt as Ei,m as Rre,mi as zre,mn as Di,mr as Bre,mt as Oi,ni as Vre,nn as ki,nr as Ai,nt as Hre,o as ji,oi as Ure,on as Wre,ot as Mi,p as Gre,pi as Ni,pn as Kre,pr as Pi,pt as qre,q as Fi,qr as Jre,qt as Ii,ri as Li,rn as Yre,rr as Xre,rt as Ri,s as zi,si as Zre,sn as Qre,sr as $re,st as Bi,t as Vi,ti as eie,tn as tie,tr as Hi,ui as Ui,un as Wi,ur as Gi,ut as Ki,vn as nie,vr as qi,vt as Ji,w as rie,wn as Yi,wr as Xi,xn as Zi,xr as iie,xt as aie,yn as oie,yr as sie,yt as Qi,z as $i,zn as cie,zt as ea}from"./settings-B2jvL8Dp.js";import{A as ta,D as lie,E as na,F as uie,M as die,N as fie,O as ra,P as pie,T as ia,_ as aa,b as oa,c as sa,f as ca,g as la,j as mie,k as ua,l as da,n as fa,o as pa,p as ma,s as ha,u as hie,w as gie,x as ga}from"./config-C-Y2qtB2.js";import{a as _a,c as _ie,i as va,n as ya,o as ba,r as xa,s as Sa,t as Ca}from"./execFileNoThrow-BTachNBI.js";import{B as wa,D as Ta,E as Ea,F as Da,G as Oa,H as ka,I as Aa,K as ja,L as Ma,M as Na,N as Pa,O as Fa,R as Ia,S as La,U as Ra,V as za,W as Ba,b as vie,c as Va,g as yie,j as Ha,l as Ua,m as bie,n as Wa,o as Ga,q as Ka,s as J,x as xie,y as Sie,z as qa}from"./log-D2TIwHBV.js";import{_ as Ja,a as Ya,g as Cie,h as wie,i as Xa,l as Za,m as Qa,n as Tie,o as $a,r as eo,t as to,u as no,v as ro}from"./stringUtils-C718f5ey.js";import{i as io,o as ao}from"./platform-BacQ6ACS.js";import{n as oo,r as Y}from"./analytics-DJobLaWP.js";import{C as Eie,_ as so,a as co,c as lo,f as uo,h as fo,i as Die,l as po,m as mo,n as Oie,o as kie,s as ho,u as go,y as _o}from"./startupProfiler-CJdr3SxP.js";import{$ as Aie,At as jie,B as Mie,Bt as Nie,C as Pie,Et as vo,G as yo,Gt as bo,H as xo,Ht as So,It as Fie,K as Co,Kt as Iie,M as wo,Mt as To,N as Lie,Nt as Rie,O as Eo,Ot as Do,Qt as Oo,Rt as zie,S as Bie,T as ko,Tt as Ao,U as jo,Ut as Vie,V as Hie,Vt as Uie,W as Mo,Wt as No,Xt as Po,Yt as Fo,Zt as Io,_ as Lo,_t as Ro,a as zo,bt as Bo,c as Vo,ct as Ho,d as Uo,dt as Wie,ft as Gie,g as Wo,gt as Kie,ht as Go,i as qie,it as Jie,jt as Ko,k as qo,l as Jo,lt as Yie,nt as Yo,o as Xo,ot as Zo,p as Qo,pt as Xie,qt as Zie,r as Qie,rt as $ie,s as $o,st as es,t as ts,tt as ns,u as eae,ut as tae,vt as nae,w as rs,x as rae,xt as iae,y as is}from"./model-BwBG0V1u.js";import{$ as as,$t as aae,A as oae,At as sae,B as cae,Bt as os,Ct as lae,Dt as uae,Et as ss,Ft as dae,G as fae,Gt as cs,H as pae,Ht as ls,I as mae,It as hae,J as gae,Jt as _ae,K as vae,Kt as us,Lt as yae,Mt as bae,N as xae,Nt as ds,O as Sae,Ot as fs,P as Cae,Pt as wae,Q as Tae,Qt as Eae,R as Dae,Rt as ps,S as Oae,St as ms,T as kae,Tt as hs,U as Aae,Ut as gs,Vt as _s,W as jae,Wt as vs,X as Mae,Xt as Nae,Y as Pae,Yt as ys,Z as Fae,Zt as Iae,_ as Lae,_n as Rae,_t as bs,a as xs,an as zae,at as Ss,b as Bae,bn as Cs,bt as Vae,c as ws,cn as Hae,d as Uae,dn as Wae,dt as Gae,en as Kae,et as qae,f as Ts,ft as Jae,g as Es,gn as Ds,gt as Yae,h as Xae,hn as Os,ht as ks,i as As,in as js,jt as Zae,k as Qae,kt as Ms,l as $ae,lt as eoe,m as toe,mn as Ns,mt as Ps,n as noe,nn as roe,nt as Fs,o as ioe,on as Is,p as aoe,pn as Ls,pt as Rs,q as ooe,qt as zs,r as Bs,rn as Vs,rt as soe,s as coe,sn as loe,st as Hs,t as uoe,tn as Us,tt as Ws,u as doe,un as Gs,ut as foe,vn as Ks,vt as poe,w as moe,wt as qs,xt as Js,yn as Ys,yt as Xs,z as hoe,zt as Zs}from"./prompt-mM79EGnT.js";import{a as goe,c as Qs,i as $s,l as _oe,m as voe,o as yoe,p as boe,s as xoe}from"./proxy-CDBfZjO7.js";import{i as Soe,r as Coe}from"./projectOnboardingState-B5YATuc6.js";import{a as woe,i as Toe,n as Eoe,o as Doe,t as Ooe}from"./break-cache-BMXqFTeS.js";import{a as koe,i as Aoe,l as ec,n as joe,o as tc,r as Moe,s as Noe,t as Poe}from"./localSearch-CK-sFzPm.js";import{a as nc,c as rc,n as Foe,s as ic}from"./ripgrep-Dl3y5r4m.js";import{n as Ioe,r as Loe}from"./client-4iqhC8xq.js";import{r as Roe,t as zoe}from"./store-Z8rTjDHe.js";import{n as Boe,t as Voe}from"./client-CpTCeWba.js";import{i as Hoe,n as Uoe,r as ac}from"./loader-CICGtLp2.js";import{n as Woe,r as Goe,t as Koe}from"./switcher-CAajZeNL.js";import{a as oc,i as sc,n as qoe}from"./genericProcessUtils-DwQFuna9.js";import{r as Joe,t as Yoe}from"./sanitization-DV-94a9Z.js";import{d as Xoe,f as Zoe,h as cc,m as lc,n as Qoe,s as $oe}from"./firstPartyEventLogger-M6UMli2c.js";import{a as ese,o as tse,r as uc,s as nse,t as rse}from"./parser-Cg6hSCmn.js";import{C as dc,S as ise,T as fc,a as ase,b as ose,c as pc,f as sse,g as cse,h as lse,i as use,m as dse,n as fse,o as pse,p as mse,s as mc,t as hse,u as gse,v as _se,w as hc,x as vse,y as yse}from"./sessionTracing-BoDDYLxW.js";import{n as bse,r as xse,t as gc}from"./poorMode-B0QGV6Ci.js";import{n as Sse,t as Cse}from"./worktreeModeEnabled-BFOYTTTr.js";import{n as wse,t as Tse}from"./featureCheck-D6FjD-nt.js";import{n as Ese,t as Dse}from"./datadog-BPuGcxxC.js";import*as Ose from"os";import{homedir as _c,platform as kse,release as Ase,tmpdir as vc,type as jse,userInfo as Mse,version as Nse}from"os";import*as yc from"path";import{basename as bc,delimiter as Pse,dirname as xc,extname as Sc,isAbsolute as Cc,join as X,normalize as wc,parse as Tc,posix as Ec,relative as Dc,resolve as Oc,sep as kc,win32 as Ac}from"path";import jc from"node:process";import*as Mc from"node:path";import Nc,{basename as Fse,dirname as Ise,isAbsolute as Lse,join as Pc,relative as Fc,resolve as Ic,sep as Rse}from"node:path";import*as Lc from"fs";import{accessSync as zse,chmodSync as Bse,closeSync as Vse,constants as Rc,createReadStream as Hse,existsSync as Use,fstat as Wse,fstatSync as Gse,mkdirSync as Kse,openSync as qse,readFileSync as zc,readSync as Jse,readdirSync as Yse,rm as Xse,rmSync as Zse,statSync as Qse,unlinkSync as $se,writeFileSync as ece,writeSync as Bc}from"fs";import{execSync as tce,spawn as nce,spawnSync as rce}from"node:child_process";import*as Vc from"node:fs";import{closeSync as ice,existsSync as Hc,mkdirSync as ace,openSync as oce,readFileSync as sce,readSync as cce,readdirSync as Uc,renameSync as lce,rmSync as uce,stat as dce,statSync as fce,unlinkSync as pce,unwatchFile as mce,watch as hce,watchFile as gce,writeFileSync as _ce}from"node:fs";import{EOL as Wc,homedir as vce,tmpdir as Gc,type as yce}from"node:os";import{createHash as bce,randomBytes as xce,randomUUID as Sce}from"node:crypto";import{createHash as Kc,randomBytes as qc,randomUUID as Jc}from"crypto";import{access as Cce,appendFile as Yc,chmod as Xc,copyFile as Zc,link as Qc,lstat as wce,mkdir as $c,open as el,readFile as tl,readdir as nl,readlink as Tce,realpath as rl,rename as il,rm as al,rmdir as Ece,stat as ol,symlink as sl,truncate as Dce,unlink as cl,utimes as Oce,writeFile as ll}from"fs/promises";import"util";import{execFile as kce,execFileSync as ul,spawn as dl,spawnSync as fl}from"child_process";import{fileURLToPath as Ace,pathToFileURL as pl}from"url";import jce,{createConnection as Mce,isIP as Nce}from"net";import{EventEmitter as Pce}from"node:events";import{setMaxListeners as Fce}from"events";import{PassThrough as Ice,Readable as Lce}from"node:stream";import{lstat as ml,mkdir as Rce,open as zce,readFile as hl,readdir as gl,realpath as _l,rename as Bce,rm as Vce,stat as vl,writeFile as Hce}from"node:fs/promises";import{request as Uce}from"node:https";import{Agent as Wce,createServer as Gce,request as yl}from"node:http";import{URL as bl,fileURLToPath as Kce}from"node:url";import{BlockList as qce,connect as xl,isIP as Sl}from"node:net";import{connect as Jce}from"node:tls";import{text as Yce}from"node:stream/consumers";import{join as Cl}from"path/posix";import{lookup as Xce}from"dns";async function Zce(e,t,{concurrency:n=1/0,stopOnError:r=!0,signal:i}={}){return new Promise((a,o)=>{if(e[Symbol.iterator]===void 0&&e[Symbol.asyncIterator]===void 0)throw TypeError(`Expected \`input\` to be either an \`Iterable\` or \`AsyncIterable\`, got (${typeof e})`);if(typeof t!=`function`)throw TypeError(`Mapper function is required`);if(!(Number.isSafeInteger(n)&&n>=1||n===1/0))throw TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${n}\` (${typeof n})`);let s=[],c=[],l=new Map,u=!1,d=!1,f=!1,p=0,m=0,h=e[Symbol.iterator]===void 0?e[Symbol.asyncIterator]():e[Symbol.iterator](),g=()=>{y(i.reason)},_=()=>{i?.removeEventListener(`abort`,g)},v=e=>{a(e),_()},y=e=>{u=!0,d=!0,o(e),_()};i&&(i.aborted&&y(i.reason),i.addEventListener(`abort`,g,{once:!0}));let b=async()=>{if(d)return;let e=await h.next(),n=m;if(m++,e.done){if(f=!0,p===0&&!d){if(!r&&c.length>0){y(AggregateError(c));return}if(d=!0,l.size===0){v(s);return}let e=[];for(let[t,n]of s.entries())l.get(t)!==wl&&e.push(n);v(e)}return}p++,(async()=>{try{let r=await e.value;if(d)return;let i=await t(r,n);i===wl&&l.set(n,i),s[n]=i,p--,await b()}catch(e){if(r)y(e);else{c.push(e),p--;try{await b()}catch(e){y(e)}}}})()};(async()=>{for(let e=0;e<n;e++){try{await b()}catch(e){y(e);break}if(f||u)break}})()})}var wl,Qce=n((()=>{wl=Symbol(`skip`)}));function $ce(e){let t=e.slice(e.lastIndexOf(`.`)).toLowerCase();return ele.has(t)}var ele,tle=n((()=>{ele=new Set(`.png,.jpg,.jpeg,.gif,.bmp,.ico,.webp,.tiff,.tif,.mp4,.mov,.avi,.mkv,.webm,.wmv,.flv,.m4v,.mpeg,.mpg,.mp3,.wav,.ogg,.flac,.aac,.m4a,.wma,.aiff,.opus,.zip,.tar,.gz,.bz2,.7z,.rar,.xz,.z,.tgz,.iso,.exe,.dll,.so,.dylib,.bin,.o,.a,.obj,.lib,.app,.msi,.deb,.rpm,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.odt,.ods,.odp,.ttf,.otf,.woff,.woff2,.eot,.pyc,.pyo,.class,.jar,.war,.ear,.node,.wasm,.rlib,.sqlite,.sqlite3,.db,.mdb,.idx,.psd,.ai,.eps,.sketch,.fig,.xd,.blend,.3ds,.max,.swf,.fla,.lockb,.dat,.data`.split(`,`))}));function nle(e,t){for(var n=-1,r=e==null?0:e.length;++n<r&&t(e[n],n,e)!==!1;);return e}var rle=n((()=>{}));function ile(e,t){return e&&gi(t,_n(t),e)}var ale=n((()=>{Ni(),$t()}));function ole(e,t){return e&&gi(t,bre(t),e)}var sle=n((()=>{Ni(),Ui()}));function cle(e,t){return gi(e,vte(e),t)}var lle=n((()=>{Ni(),xte()}));function ule(e,t){return gi(e,pie(e),t)}var dle=n((()=>{Ni(),uie()}));function fle(e){var t=e.length,n=new e.constructor(t);return t&&typeof e[0]==`string`&&ple.call(e,`index`)&&(n.index=e.index,n.input=e.input),n}var ple,mle=n((()=>{ple=Object.prototype.hasOwnProperty}));function hle(e,t){var n=t?Vre(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.byteLength)}var gle=n((()=>{Li()}));function _le(e){var t=new e.constructor(e.source,vle.exec(e));return t.lastIndex=e.lastIndex,t}var vle,yle=n((()=>{vle=/\w*$/}));function ble(e){return El?Object(El.call(e)):{}}var Tl,El,xle=n((()=>{c(),Tl=o?o.prototype:void 0,El=Tl?Tl.valueOf:void 0}));function Sle(e,t,n){var r=e.constructor;switch(t){case jle:return Vre(e);case Cle:case wle:return new r(+e);case Mle:return hle(e,n);case Nle:case Ple:case Fle:case Ile:case Lle:case Rle:case zle:case Ble:case Vle:return xre(e,n);case Tle:return new r;case Ele:case kle:return new r(e);case Dle:return _le(e);case Ole:return new r;case Ale:return ble(e)}}var Cle,wle,Tle,Ele,Dle,Ole,kle,Ale,jle,Mle,Nle,Ple,Fle,Ile,Lle,Rle,zle,Ble,Vle,Hle=n((()=>{Li(),gle(),yle(),xle(),eie(),Cle=`[object Boolean]`,wle=`[object Date]`,Tle=`[object Map]`,Ele=`[object Number]`,Dle=`[object RegExp]`,Ole=`[object Set]`,kle=`[object String]`,Ale=`[object Symbol]`,jle=`[object ArrayBuffer]`,Mle=`[object DataView]`,Nle=`[object Float32Array]`,Ple=`[object Float64Array]`,Fle=`[object Int8Array]`,Ile=`[object Int16Array]`,Lle=`[object Int32Array]`,Rle=`[object Uint8Array]`,zle=`[object Uint8ClampedArray]`,Ble=`[object Uint16Array]`,Vle=`[object Uint32Array]`}));function Ule(e){return lt(e)&&rn(e)==Wle}var Wle,Gle=n((()=>{Lt(),Mee(),Wle=`[object Map]`})),Dl,Kle,qle=n((()=>{Gle(),mte(),It(),Dl=sn&&sn.isMap,Kle=Dl?Kt(Dl):Ule}));function Jle(e){return lt(e)&&rn(e)==Yle}var Yle,Xle=n((()=>{Lt(),Mee(),Yle=`[object Set]`})),Ol,Zle,Qle=n((()=>{Xle(),mte(),It(),Ol=sn&&sn.isSet,Zle=Ol?Kt(Ol):Jle}));function kl(e,t,n,r,i,a){var o,c=t&$le,l=t&eue,u=t&tue;if(n&&(o=i?n(e,r,i,a):n(e)),o!==void 0)return o;if(!s(e))return e;var d=Ote(e);if(d){if(o=fle(e),!c)return Ure(e,o)}else{var f=rn(e),p=f==jl||f==oue;if(rne(e))return vre(e,c);if(f==Ml||f==Al||p&&!i){if(o=l||p?{}:Jne(e),!c)return l?ule(e,ole(o,e)):cle(e,ile(o,e))}else{if(!Nl[f])return i?e:{};o=Sle(e,f,c)}}a||(a=new Vte);var m=a.get(e);if(m)return m;a.set(e,o),Zle(e)?e.forEach(function(r){o.add(kl(r,t,n,r,e,a))}):Kle(e)&&e.forEach(function(r,i){o.set(i,kl(r,t,n,i,e,a))});var h=d?void 0:(u?l?die:Zee:l?bre:_n)(e);return nle(h||e,function(r,i){h&&(i=r,r=e[i]),zre(o,i,kl(r,t,n,i,e,a))}),o}var $le,eue,tue,Al,nue,rue,iue,aue,jl,oue,sue,cue,Ml,lue,uue,due,fue,pue,mue,hue,gue,_ue,vue,yue,bue,xue,Sue,Cue,wue,Nl,Pl=n((()=>{Cte(),rle(),Are(),ale(),sle(),Lre(),Zre(),lle(),dle(),Xee(),fie(),Lt(),mle(),Hle(),wne(),Jte(),ete(),qle(),l(),Qle(),$t(),Ui(),$le=1,eue=2,tue=4,Al=`[object Arguments]`,nue=`[object Array]`,rue=`[object Boolean]`,iue=`[object Date]`,aue=`[object Error]`,jl=`[object Function]`,oue=`[object GeneratorFunction]`,sue=`[object Map]`,cue=`[object Number]`,Ml=`[object Object]`,lue=`[object RegExp]`,uue=`[object Set]`,due=`[object String]`,fue=`[object Symbol]`,pue=`[object WeakMap]`,mue=`[object ArrayBuffer]`,hue=`[object DataView]`,gue=`[object Float32Array]`,_ue=`[object Float64Array]`,vue=`[object Int8Array]`,yue=`[object Int16Array]`,bue=`[object Int32Array]`,xue=`[object Uint8Array]`,Sue=`[object Uint8ClampedArray]`,Cue=`[object Uint16Array]`,wue=`[object Uint32Array]`,Nl={},Nl[Al]=Nl[nue]=Nl[mue]=Nl[hue]=Nl[rue]=Nl[iue]=Nl[gue]=Nl[_ue]=Nl[vue]=Nl[yue]=Nl[bue]=Nl[sue]=Nl[cue]=Nl[Ml]=Nl[lue]=Nl[uue]=Nl[due]=Nl[fue]=Nl[xue]=Nl[Sue]=Nl[Cue]=Nl[wue]=!0,Nl[aue]=Nl[jl]=Nl[pue]=!1}));function Tue(e){return kl(e,Fl|Il)}var Fl,Il,Eue=n((()=>{Pl(),Fl=1,Il=4}));function Ll(e){return e.sort((e,t)=>{let n=t.modified.getTime()-e.modified.getTime();return n===0?t.created.getTime()-e.created.getTime():n})}var Due=n((()=>{})),Rl=a((e=>{var t=Symbol.for(`yaml.alias`),n=Symbol.for(`yaml.document`),r=Symbol.for(`yaml.map`),i=Symbol.for(`yaml.pair`),a=Symbol.for(`yaml.scalar`),o=Symbol.for(`yaml.seq`),s=Symbol.for(`yaml.node.type`),c=e=>!!e&&typeof e==`object`&&e[s]===t,l=e=>!!e&&typeof e==`object`&&e[s]===n,u=e=>!!e&&typeof e==`object`&&e[s]===r,d=e=>!!e&&typeof e==`object`&&e[s]===i,f=e=>!!e&&typeof e==`object`&&e[s]===a,p=e=>!!e&&typeof e==`object`&&e[s]===o;function m(e){if(e&&typeof e==`object`)switch(e[s]){case r:case o:return!0}return!1}function h(e){if(e&&typeof e==`object`)switch(e[s]){case t:case r:case a:case o:return!0}return!1}e.ALIAS=t,e.DOC=n,e.MAP=r,e.NODE_TYPE=s,e.PAIR=i,e.SCALAR=a,e.SEQ=o,e.hasAnchor=e=>(f(e)||m(e))&&!!e.anchor,e.isAlias=c,e.isCollection=m,e.isDocument=l,e.isMap=u,e.isNode=h,e.isPair=d,e.isScalar=f,e.isSeq=p})),zl=a((e=>{var t=Rl(),n=Symbol(`break visit`),r=Symbol(`skip children`),i=Symbol(`remove node`);function a(e,n){let r=l(n);t.isDocument(e)?o(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):o(null,e,r,Object.freeze([]))}a.BREAK=n,a.SKIP=r,a.REMOVE=i;function o(e,r,a,s){let c=u(e,r,a,s);if(t.isNode(c)||t.isPair(c))return d(e,s,c),o(e,c,a,s);if(typeof c!=`symbol`){if(t.isCollection(r)){s=Object.freeze(s.concat(r));for(let e=0;e<r.items.length;++e){let t=o(e,r.items[e],a,s);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){s=Object.freeze(s.concat(r));let e=o(`key`,r.key,a,s);if(e===n)return n;e===i&&(r.key=null);let t=o(`value`,r.value,a,s);if(t===n)return n;t===i&&(r.value=null)}}return c}async function s(e,n){let r=l(n);t.isDocument(e)?await c(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):await c(null,e,r,Object.freeze([]))}s.BREAK=n,s.SKIP=r,s.REMOVE=i;async function c(e,r,a,o){let s=await u(e,r,a,o);if(t.isNode(s)||t.isPair(s))return d(e,o,s),c(e,s,a,o);if(typeof s!=`symbol`){if(t.isCollection(r)){o=Object.freeze(o.concat(r));for(let e=0;e<r.items.length;++e){let t=await c(e,r.items[e],a,o);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){o=Object.freeze(o.concat(r));let e=await c(`key`,r.key,a,o);if(e===n)return n;e===i&&(r.key=null);let t=await c(`value`,r.value,a,o);if(t===n)return n;t===i&&(r.value=null)}}return s}function l(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function u(e,n,r,i){if(typeof r==`function`)return r(e,n,i);if(t.isMap(n))return r.Map?.(e,n,i);if(t.isSeq(n))return r.Seq?.(e,n,i);if(t.isPair(n))return r.Pair?.(e,n,i);if(t.isScalar(n))return r.Scalar?.(e,n,i);if(t.isAlias(n))return r.Alias?.(e,n,i)}function d(e,n,r){let i=n[n.length-1];if(t.isCollection(i))i.items[e]=r;else if(t.isPair(i))e===`key`?i.key=r:i.value=r;else if(t.isDocument(i))i.contents=r;else{let e=t.isAlias(i)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}e.visit=a,e.visitAsync=s})),Bl=a((e=>{var t=Rl(),n=zl(),r={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},i=e=>e.replace(/[!,[\]{}]/g,e=>r[e]),a=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,n){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case`%TAG`:{if(r.length!==2&&(n(0,`%TAG directive should contain exactly two parts`),r.length<2))return!1;let[e,t]=r;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,r.length!==1)return n(0,`%YAML directive should contain exactly one part`),!1;let[e]=r;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return n(6,`Unsupported YAML version ${e}`,t),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+i(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],i=Object.entries(this.tags),a;if(e&&i.length>0&&t.isNode(e.contents)){let r={};n.visit(e.contents,(e,n)=>{t.isNode(n)&&n.tag&&(r[n.tag]=!0)}),a=Object.keys(r)}else a=[];for(let[t,n]of i)t===`!!`&&n===`tag:yaml.org,2002:`||(!e||a.some(e=>e.startsWith(n)))&&r.push(`%TAG ${t} ${n}`);return r.join(`
|
|
1
|
+
import{a as e,i as t,n,o as r,r as i,t as a}from"./rolldown-runtime-DaDcL9Zw.js";import{a as o,n as s,o as c,t as l}from"./isObject-C6qM3WEW.js";import{n as u,t as d}from"./memoize-BK3gG5ob.js";import{c as f,f as p,i as m,l as h,o as g,r as _,s as v,u as y}from"./envUtils-DfkgIdYf.js";import{n as b,t as x}from"./defineProperty-C-QyHrDq.js";import{a as S,c as C,i as w,n as T,o as E,r as D,s as O,t as k}from"./classPrivateFieldSet2-D4U5K-I3.js";import{n as A,t as ee}from"./classPrivateMethodInitSpec-BXQD0Vh4.js";import{i as te,n as ne,r as re,t as ie}from"./figures-5ThXQEtq.js";import{c as ae,f as j,i as oe,l as se,m as ce,r as M,t as N,u as le}from"./zod-CuNujUwx.js";import{t as ue}from"./semver-DQo45qGo.js";import{$ as de,Ct as fe,J as pe,Q as me,St as he,X as ge,Y as _e,_t as ve,at as ye,bt as be,ct as xe,et as Se,ft as Ce,gt as we,ht as Te,lt as Ee,mt as De,nt as Oe,ot as ke,rt as Ae,st as je,tt as Me,ut as Ne,vt as Pe,xt as Fe,yt as Ie}from"./esm-BXTZz3av.js";import{n as Le,t as Re}from"./axios-DaWTGg7G.js";import{$r as ze,Bt as Be,Ct as Ve,D as He,Fr as Ue,Ft as We,Gr as Ge,Gt as Ke,H as qe,Hr as Je,I as P,Kr as Ye,Lr as eee,Lt as Xe,Mr as Ze,P as F,Pr as tee,Pt as nee,Qr as ree,Rn as Qe,T as $e,Tt as et,Vr as iee,Wt as aee,Xn as oee,Yt as see,Zt as cee,ai as tt,bn as lee,cr as uee,d as dee,di as nt,fi as rt,fr as fee,gr as pee,gt as mee,hr as hee,j as gee,l as _ee,ln as it,mi as vee,mr as yee,mt as bee,nt as xee,or as See,ot as at,pi as Cee,pr as wee,qr as ot,rn as Tee,sn as st,sr as Eee,t as ct,vn as Dee,xr as Oee,y as kee,yr as Aee,zr as jee}from"./src-DL3w8VPk.js";import{i as lt,r as Mee}from"./isSymbol-BO6cdPI7.js";import{t as ut}from"./jsx-runtime-Bb4Xn-E0.js";import{$ as dt,A as ft,E as Nee,F as pt,G as I,H as mt,I as Pee,J as ht,K as gt,L as _t,N as vt,O as Fee,P as L,Q as yt,S as bt,V as R,W as z,X as xt,Y as St,Z as B,_ as Ct,a as wt,at as Iee,b as Tt,et as Lee,f as Et,g as Dt,j as Ree,l as Ot,lt as zee,n as Bee,o as kt,r as At,rt as Vee,s as V,st as Hee,t as jt,u as Mt,ut as Uee,x as Nt,y as Pt,z as Ft}from"./types-Dx7P7JLQ.js";import{$ as Wee,An as Gee,At as Kee,Bn as qee,Br as It,Bt as Jee,C as Yee,Cr as Lt,Ct as Rt,Dn as zt,Dr as Xee,Dt as Bt,E as Vt,En as Ht,Er as Zee,F as Ut,Ft as Qee,G as Wt,H as Gt,Hr as Kt,I as qt,It as Jt,J as Yt,Jn as Xt,Kn as $ee,Kr as ete,L as tte,Lt as Zt,Mt as nte,N as Qt,O as rte,On as ite,Or as $t,Ot as ate,P as ote,Pt as ste,Q as en,Qn as cte,Qt as lte,R as tn,Rt as nn,S as ute,Sr as rn,St as an,T as dte,Tn as on,Tr as fte,Tt as pte,Ur as mte,V as hte,Vr as sn,Vt as gte,Wn as _te,Wt as cn,X as ln,Xr as vte,Xt as yte,Yn as bte,Z as un,Zr as xte,_ as Ste,_i as Cte,_n as wte,_r as Tte,_t as Ete,a as Dte,ai as Ote,at as dn,b as kte,bt as Ate,c as jte,ci as Mte,ct as fn,d as Nte,dt as Pte,en as Fte,er as pn,et as Ite,f as Lte,fi as Rte,ft as zte,g as Bte,gi as Vte,gn as Hte,gr as Ute,gt as Wte,h as mn,hi as Gte,ht as Kte,i as qte,ii as Jte,ir as Yte,it as hn,jn as Xte,jt as gn,kn as Zte,kr as _n,kt as Qte,li as vn,mi as $te,mn as yn,mt as bn,n as xn,nt as Sn,o as ene,on as Cn,or as wn,p as tne,pi as nne,pt as Tn,q as En,qn as Dn,qr as rne,r as ine,rn as ane,rt as On,s as kn,sr as An,st as jn,tn as Mn,tr as Nn,tt as one,u as Pn,ut as Fn,vr as sne,vt as In,w as cne,wr as Ln,wt as lne,xt as Rn,yr as une,yt as zn,z as dne,zt as fne}from"./state-B4jiUise.js";import{i as Bn,n as Vn,r as pne,t as H}from"./cwd-Pa83R95t.js";import{$ as Hn,A as Un,C as U,D as mne,E as Wn,F as Gn,G as hne,H as Kn,I as qn,J as Jn,K as Yn,L as gne,M as W,N as Xn,O as Zn,P as _ne,R as Qn,S as $n,T as er,V as tr,X as vne,Y as nr,Z as yne,_ as rr,c as G,d as ir,et as ar,f as or,g as sr,i as K,j as cr,k as lr,m as ur,p as dr,q as fr,s as pr,t as bne,tt as xne,u as q,v as Sne,x as mr,y as Cne,z as hr}from"./debug-Bglx1aTu.js";import{$n as gr,$r as wne,$t as Tne,A as _r,An as Ene,Ar as vr,At as yr,B as br,Bn as xr,Br as Dne,C as One,Cn as Sr,Cr,Dn as kne,Dr as wr,Dt as Tr,E as Ane,Er,Et as Dr,F as Or,G as kr,Gr as jne,H as Mne,Hn as Ar,Hr as Nne,Ht as jr,I as Mr,In as Nr,Ir as Pr,J as Pne,Jr as Fne,Jt as Ine,K as Fr,Kr as Lne,Kt as Rne,L as zne,Lr as Ir,Lt as Bne,M as Vne,Mn as Hne,Mr as Lr,N as Rr,Nn as Une,On as zr,Or as Br,Ot as Wne,P as Vr,Pn as Hr,Pt as Gne,Q as Kne,Qn as qne,Qr as Jne,Qt as Ur,R as Wr,Rn as Gr,Rr as Yne,S as Xne,Sn as Kr,Sr as Zne,St as qr,T as Qne,Tn as $ne,Tt as ere,U as tre,Un as nre,Ur as Jr,V as Yr,Vn as Xr,Vr as rre,Vt as Zr,W as ire,Wn as Qr,Wr as are,Wt as $r,X as ore,Xn as sre,Xr as ei,Xt as ti,Y as cre,Yn as lre,Yr as ni,Yt as ure,Z as ri,Zn as dre,Zr as fre,Zt as ii,_ as pre,_i as mre,_n as ai,_t as oi,a as hre,ar as si,at as ci,b as li,bn as gre,br as _re,c as ui,ci as vre,cr as yre,ct as di,d as fi,di as bre,dr as pi,dt as mi,ei as xre,en as Sre,er as hi,f as Cre,fi as gi,fn as wre,fr as Tre,ft as Ere,gi as Dre,gn as Ore,gr as kre,gt as _i,h as vi,hi as Are,hn as jre,hr as Mre,in as Nre,ir as yi,it as bi,jt as xi,k as Pre,kn as Si,kr as Ci,kt as Fre,l as Ire,li as Lre,ln as wi,lr as Ti,lt as Ei,m as Rre,mi as zre,mn as Di,mr as Bre,mt as Oi,ni as Vre,nn as ki,nr as Ai,nt as Hre,o as ji,oi as Ure,on as Wre,ot as Mi,p as Gre,pi as Ni,pn as Kre,pr as Pi,pt as qre,q as Fi,qr as Jre,qt as Ii,ri as Li,rn as Yre,rr as Xre,rt as Ri,s as zi,si as Zre,sn as Qre,sr as $re,st as Bi,t as Vi,ti as eie,tn as tie,tr as Hi,ui as Ui,un as Wi,ur as Gi,ut as Ki,vn as nie,vr as qi,vt as Ji,w as rie,wn as Yi,wr as Xi,xn as Zi,xr as iie,xt as aie,yn as oie,yr as sie,yt as Qi,z as $i,zn as cie,zt as ea}from"./settings-B2jvL8Dp.js";import{A as ta,D as lie,E as na,F as uie,M as die,N as fie,O as ra,P as pie,T as ia,_ as aa,b as oa,c as sa,f as ca,g as la,j as mie,k as ua,l as da,n as fa,o as pa,p as ma,s as ha,u as hie,w as gie,x as ga}from"./config-C-Y2qtB2.js";import{a as _a,c as _ie,i as va,n as ya,o as ba,r as xa,s as Sa,t as Ca}from"./execFileNoThrow-BTachNBI.js";import{B as wa,D as Ta,E as Ea,F as Da,G as Oa,H as ka,I as Aa,K as ja,L as Ma,M as Na,N as Pa,O as Fa,R as Ia,S as La,U as Ra,V as za,W as Ba,b as vie,c as Va,g as yie,j as Ha,l as Ua,m as bie,n as Wa,o as Ga,q as Ka,s as J,x as xie,y as Sie,z as qa}from"./log-D2TIwHBV.js";import{_ as Ja,a as Ya,g as Cie,h as wie,i as Xa,l as Za,m as Qa,n as Tie,o as $a,r as eo,t as to,u as no,v as ro}from"./stringUtils-C718f5ey.js";import{i as io,o as ao}from"./platform-BacQ6ACS.js";import{n as oo,r as Y}from"./analytics-DJobLaWP.js";import{C as Eie,_ as so,a as co,c as lo,f as uo,h as fo,i as Die,l as po,m as mo,n as Oie,o as kie,s as ho,u as go,y as _o}from"./startupProfiler-CJdr3SxP.js";import{$ as Aie,At as jie,B as Mie,Bt as Nie,C as Pie,Et as vo,G as yo,Gt as bo,H as xo,Ht as So,It as Fie,K as Co,Kt as Iie,M as wo,Mt as To,N as Lie,Nt as Rie,O as Eo,Ot as Do,Qt as Oo,Rt as zie,S as Bie,T as ko,Tt as Ao,U as jo,Ut as Vie,V as Hie,Vt as Uie,W as Mo,Wt as No,Xt as Po,Yt as Fo,Zt as Io,_ as Lo,_t as Ro,a as zo,bt as Bo,c as Vo,ct as Ho,d as Uo,dt as Wie,ft as Gie,g as Wo,gt as Kie,ht as Go,i as qie,it as Jie,jt as Ko,k as qo,l as Jo,lt as Yie,nt as Yo,o as Xo,ot as Zo,p as Qo,pt as Xie,qt as Zie,r as Qie,rt as $ie,s as $o,st as es,t as ts,tt as ns,u as eae,ut as tae,vt as nae,w as rs,x as rae,xt as iae,y as is}from"./model-BvQFFOf8.js";import{$ as as,$t as aae,A as oae,At as sae,B as cae,Bt as os,Ct as lae,Dt as uae,Et as ss,Ft as dae,G as fae,Gt as cs,H as pae,Ht as ls,I as mae,It as hae,J as gae,Jt as _ae,K as vae,Kt as us,Lt as yae,Mt as bae,N as xae,Nt as ds,O as Sae,Ot as fs,P as Cae,Pt as wae,Q as Tae,Qt as Eae,R as Dae,Rt as ps,S as Oae,St as ms,T as kae,Tt as hs,U as Aae,Ut as gs,Vt as _s,W as jae,Wt as vs,X as Mae,Xt as Nae,Y as Pae,Yt as ys,Z as Fae,Zt as Iae,_ as Lae,_n as Rae,_t as bs,a as xs,an as zae,at as Ss,b as Bae,bn as Cs,bt as Vae,c as ws,cn as Hae,d as Uae,dn as Wae,dt as Gae,en as Kae,et as qae,f as Ts,ft as Jae,g as Es,gn as Ds,gt as Yae,h as Xae,hn as Os,ht as ks,i as As,in as js,jt as Zae,k as Qae,kt as Ms,l as $ae,lt as eoe,m as toe,mn as Ns,mt as Ps,n as noe,nn as roe,nt as Fs,o as ioe,on as Is,p as aoe,pn as Ls,pt as Rs,q as ooe,qt as zs,r as Bs,rn as Vs,rt as soe,s as coe,sn as loe,st as Hs,t as uoe,tn as Us,tt as Ws,u as doe,un as Gs,ut as foe,vn as Ks,vt as poe,w as moe,wt as qs,xt as Js,yn as Ys,yt as Xs,z as hoe,zt as Zs}from"./prompt-CJ1l3XXk.js";import{a as goe,c as Qs,i as $s,l as _oe,m as voe,o as yoe,p as boe,s as xoe}from"./proxy-CDBfZjO7.js";import{i as Soe,r as Coe}from"./projectOnboardingState-B5YATuc6.js";import{a as woe,i as Toe,n as Eoe,o as Doe,t as Ooe}from"./break-cache-BMXqFTeS.js";import{a as koe,i as Aoe,l as ec,n as joe,o as tc,r as Moe,s as Noe,t as Poe}from"./localSearch-BxLYi6w_.js";import{a as nc,c as rc,n as Foe,s as ic}from"./ripgrep-Dl3y5r4m.js";import{n as Ioe,r as Loe}from"./client-4iqhC8xq.js";import{r as Roe,t as zoe}from"./store-Z8rTjDHe.js";import{n as Boe,t as Voe}from"./client-CpTCeWba.js";import{i as Hoe,n as Uoe,r as ac}from"./loader-CICGtLp2.js";import{n as Woe,r as Goe,t as Koe}from"./switcher-DZwUo5Ed.js";import{a as oc,i as sc,n as qoe}from"./genericProcessUtils-DwQFuna9.js";import{r as Joe,t as Yoe}from"./sanitization-DV-94a9Z.js";import{d as Xoe,f as Zoe,h as cc,m as lc,n as Qoe,s as $oe}from"./firstPartyEventLogger-QmjjQmgt.js";import{a as ese,o as tse,r as uc,s as nse,t as rse}from"./parser-Cg6hSCmn.js";import{C as dc,S as ise,T as fc,a as ase,b as ose,c as pc,f as sse,g as cse,h as lse,i as use,m as dse,n as fse,o as pse,p as mse,s as mc,t as hse,u as gse,v as _se,w as hc,x as vse,y as yse}from"./sessionTracing-CtbeAD0s.js";import{n as bse,r as xse,t as gc}from"./poorMode-B0QGV6Ci.js";import{n as Sse,t as Cse}from"./worktreeModeEnabled-BFOYTTTr.js";import{n as wse,t as Tse}from"./featureCheck-D6FjD-nt.js";import{n as Ese,t as Dse}from"./datadog-Cu3s7P48.js";import*as Ose from"os";import{homedir as _c,platform as kse,release as Ase,tmpdir as vc,type as jse,userInfo as Mse,version as Nse}from"os";import*as yc from"path";import{basename as bc,delimiter as Pse,dirname as xc,extname as Sc,isAbsolute as Cc,join as X,normalize as wc,parse as Tc,posix as Ec,relative as Dc,resolve as Oc,sep as kc,win32 as Ac}from"path";import jc from"node:process";import*as Mc from"node:path";import Nc,{basename as Fse,dirname as Ise,isAbsolute as Lse,join as Pc,relative as Fc,resolve as Ic,sep as Rse}from"node:path";import*as Lc from"fs";import{accessSync as zse,chmodSync as Bse,closeSync as Vse,constants as Rc,createReadStream as Hse,existsSync as Use,fstat as Wse,fstatSync as Gse,mkdirSync as Kse,openSync as qse,readFileSync as zc,readSync as Jse,readdirSync as Yse,rm as Xse,rmSync as Zse,statSync as Qse,unlinkSync as $se,writeFileSync as ece,writeSync as Bc}from"fs";import{execSync as tce,spawn as nce,spawnSync as rce}from"node:child_process";import*as Vc from"node:fs";import{closeSync as ice,existsSync as Hc,mkdirSync as ace,openSync as oce,readFileSync as sce,readSync as cce,readdirSync as Uc,renameSync as lce,rmSync as uce,stat as dce,statSync as fce,unlinkSync as pce,unwatchFile as mce,watch as hce,watchFile as gce,writeFileSync as _ce}from"node:fs";import{EOL as Wc,homedir as vce,tmpdir as Gc,type as yce}from"node:os";import{createHash as bce,randomBytes as xce,randomUUID as Sce}from"node:crypto";import{createHash as Kc,randomBytes as qc,randomUUID as Jc}from"crypto";import{access as Cce,appendFile as Yc,chmod as Xc,copyFile as Zc,link as Qc,lstat as wce,mkdir as $c,open as el,readFile as tl,readdir as nl,readlink as Tce,realpath as rl,rename as il,rm as al,rmdir as Ece,stat as ol,symlink as sl,truncate as Dce,unlink as cl,utimes as Oce,writeFile as ll}from"fs/promises";import"util";import{execFile as kce,execFileSync as ul,spawn as dl,spawnSync as fl}from"child_process";import{fileURLToPath as Ace,pathToFileURL as pl}from"url";import jce,{createConnection as Mce,isIP as Nce}from"net";import{EventEmitter as Pce}from"node:events";import{setMaxListeners as Fce}from"events";import{PassThrough as Ice,Readable as Lce}from"node:stream";import{lstat as ml,mkdir as Rce,open as zce,readFile as hl,readdir as gl,realpath as _l,rename as Bce,rm as Vce,stat as vl,writeFile as Hce}from"node:fs/promises";import{request as Uce}from"node:https";import{Agent as Wce,createServer as Gce,request as yl}from"node:http";import{URL as bl,fileURLToPath as Kce}from"node:url";import{BlockList as qce,connect as xl,isIP as Sl}from"node:net";import{connect as Jce}from"node:tls";import{text as Yce}from"node:stream/consumers";import{join as Cl}from"path/posix";import{lookup as Xce}from"dns";async function Zce(e,t,{concurrency:n=1/0,stopOnError:r=!0,signal:i}={}){return new Promise((a,o)=>{if(e[Symbol.iterator]===void 0&&e[Symbol.asyncIterator]===void 0)throw TypeError(`Expected \`input\` to be either an \`Iterable\` or \`AsyncIterable\`, got (${typeof e})`);if(typeof t!=`function`)throw TypeError(`Mapper function is required`);if(!(Number.isSafeInteger(n)&&n>=1||n===1/0))throw TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${n}\` (${typeof n})`);let s=[],c=[],l=new Map,u=!1,d=!1,f=!1,p=0,m=0,h=e[Symbol.iterator]===void 0?e[Symbol.asyncIterator]():e[Symbol.iterator](),g=()=>{y(i.reason)},_=()=>{i?.removeEventListener(`abort`,g)},v=e=>{a(e),_()},y=e=>{u=!0,d=!0,o(e),_()};i&&(i.aborted&&y(i.reason),i.addEventListener(`abort`,g,{once:!0}));let b=async()=>{if(d)return;let e=await h.next(),n=m;if(m++,e.done){if(f=!0,p===0&&!d){if(!r&&c.length>0){y(AggregateError(c));return}if(d=!0,l.size===0){v(s);return}let e=[];for(let[t,n]of s.entries())l.get(t)!==wl&&e.push(n);v(e)}return}p++,(async()=>{try{let r=await e.value;if(d)return;let i=await t(r,n);i===wl&&l.set(n,i),s[n]=i,p--,await b()}catch(e){if(r)y(e);else{c.push(e),p--;try{await b()}catch(e){y(e)}}}})()};(async()=>{for(let e=0;e<n;e++){try{await b()}catch(e){y(e);break}if(f||u)break}})()})}var wl,Qce=n((()=>{wl=Symbol(`skip`)}));function $ce(e){let t=e.slice(e.lastIndexOf(`.`)).toLowerCase();return ele.has(t)}var ele,tle=n((()=>{ele=new Set(`.png,.jpg,.jpeg,.gif,.bmp,.ico,.webp,.tiff,.tif,.mp4,.mov,.avi,.mkv,.webm,.wmv,.flv,.m4v,.mpeg,.mpg,.mp3,.wav,.ogg,.flac,.aac,.m4a,.wma,.aiff,.opus,.zip,.tar,.gz,.bz2,.7z,.rar,.xz,.z,.tgz,.iso,.exe,.dll,.so,.dylib,.bin,.o,.a,.obj,.lib,.app,.msi,.deb,.rpm,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.odt,.ods,.odp,.ttf,.otf,.woff,.woff2,.eot,.pyc,.pyo,.class,.jar,.war,.ear,.node,.wasm,.rlib,.sqlite,.sqlite3,.db,.mdb,.idx,.psd,.ai,.eps,.sketch,.fig,.xd,.blend,.3ds,.max,.swf,.fla,.lockb,.dat,.data`.split(`,`))}));function nle(e,t){for(var n=-1,r=e==null?0:e.length;++n<r&&t(e[n],n,e)!==!1;);return e}var rle=n((()=>{}));function ile(e,t){return e&&gi(t,_n(t),e)}var ale=n((()=>{Ni(),$t()}));function ole(e,t){return e&&gi(t,bre(t),e)}var sle=n((()=>{Ni(),Ui()}));function cle(e,t){return gi(e,vte(e),t)}var lle=n((()=>{Ni(),xte()}));function ule(e,t){return gi(e,pie(e),t)}var dle=n((()=>{Ni(),uie()}));function fle(e){var t=e.length,n=new e.constructor(t);return t&&typeof e[0]==`string`&&ple.call(e,`index`)&&(n.index=e.index,n.input=e.input),n}var ple,mle=n((()=>{ple=Object.prototype.hasOwnProperty}));function hle(e,t){var n=t?Vre(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.byteLength)}var gle=n((()=>{Li()}));function _le(e){var t=new e.constructor(e.source,vle.exec(e));return t.lastIndex=e.lastIndex,t}var vle,yle=n((()=>{vle=/\w*$/}));function ble(e){return El?Object(El.call(e)):{}}var Tl,El,xle=n((()=>{c(),Tl=o?o.prototype:void 0,El=Tl?Tl.valueOf:void 0}));function Sle(e,t,n){var r=e.constructor;switch(t){case jle:return Vre(e);case Cle:case wle:return new r(+e);case Mle:return hle(e,n);case Nle:case Ple:case Fle:case Ile:case Lle:case Rle:case zle:case Ble:case Vle:return xre(e,n);case Tle:return new r;case Ele:case kle:return new r(e);case Dle:return _le(e);case Ole:return new r;case Ale:return ble(e)}}var Cle,wle,Tle,Ele,Dle,Ole,kle,Ale,jle,Mle,Nle,Ple,Fle,Ile,Lle,Rle,zle,Ble,Vle,Hle=n((()=>{Li(),gle(),yle(),xle(),eie(),Cle=`[object Boolean]`,wle=`[object Date]`,Tle=`[object Map]`,Ele=`[object Number]`,Dle=`[object RegExp]`,Ole=`[object Set]`,kle=`[object String]`,Ale=`[object Symbol]`,jle=`[object ArrayBuffer]`,Mle=`[object DataView]`,Nle=`[object Float32Array]`,Ple=`[object Float64Array]`,Fle=`[object Int8Array]`,Ile=`[object Int16Array]`,Lle=`[object Int32Array]`,Rle=`[object Uint8Array]`,zle=`[object Uint8ClampedArray]`,Ble=`[object Uint16Array]`,Vle=`[object Uint32Array]`}));function Ule(e){return lt(e)&&rn(e)==Wle}var Wle,Gle=n((()=>{Lt(),Mee(),Wle=`[object Map]`})),Dl,Kle,qle=n((()=>{Gle(),mte(),It(),Dl=sn&&sn.isMap,Kle=Dl?Kt(Dl):Ule}));function Jle(e){return lt(e)&&rn(e)==Yle}var Yle,Xle=n((()=>{Lt(),Mee(),Yle=`[object Set]`})),Ol,Zle,Qle=n((()=>{Xle(),mte(),It(),Ol=sn&&sn.isSet,Zle=Ol?Kt(Ol):Jle}));function kl(e,t,n,r,i,a){var o,c=t&$le,l=t&eue,u=t&tue;if(n&&(o=i?n(e,r,i,a):n(e)),o!==void 0)return o;if(!s(e))return e;var d=Ote(e);if(d){if(o=fle(e),!c)return Ure(e,o)}else{var f=rn(e),p=f==jl||f==oue;if(rne(e))return vre(e,c);if(f==Ml||f==Al||p&&!i){if(o=l||p?{}:Jne(e),!c)return l?ule(e,ole(o,e)):cle(e,ile(o,e))}else{if(!Nl[f])return i?e:{};o=Sle(e,f,c)}}a||(a=new Vte);var m=a.get(e);if(m)return m;a.set(e,o),Zle(e)?e.forEach(function(r){o.add(kl(r,t,n,r,e,a))}):Kle(e)&&e.forEach(function(r,i){o.set(i,kl(r,t,n,i,e,a))});var h=d?void 0:(u?l?die:Zee:l?bre:_n)(e);return nle(h||e,function(r,i){h&&(i=r,r=e[i]),zre(o,i,kl(r,t,n,i,e,a))}),o}var $le,eue,tue,Al,nue,rue,iue,aue,jl,oue,sue,cue,Ml,lue,uue,due,fue,pue,mue,hue,gue,_ue,vue,yue,bue,xue,Sue,Cue,wue,Nl,Pl=n((()=>{Cte(),rle(),Are(),ale(),sle(),Lre(),Zre(),lle(),dle(),Xee(),fie(),Lt(),mle(),Hle(),wne(),Jte(),ete(),qle(),l(),Qle(),$t(),Ui(),$le=1,eue=2,tue=4,Al=`[object Arguments]`,nue=`[object Array]`,rue=`[object Boolean]`,iue=`[object Date]`,aue=`[object Error]`,jl=`[object Function]`,oue=`[object GeneratorFunction]`,sue=`[object Map]`,cue=`[object Number]`,Ml=`[object Object]`,lue=`[object RegExp]`,uue=`[object Set]`,due=`[object String]`,fue=`[object Symbol]`,pue=`[object WeakMap]`,mue=`[object ArrayBuffer]`,hue=`[object DataView]`,gue=`[object Float32Array]`,_ue=`[object Float64Array]`,vue=`[object Int8Array]`,yue=`[object Int16Array]`,bue=`[object Int32Array]`,xue=`[object Uint8Array]`,Sue=`[object Uint8ClampedArray]`,Cue=`[object Uint16Array]`,wue=`[object Uint32Array]`,Nl={},Nl[Al]=Nl[nue]=Nl[mue]=Nl[hue]=Nl[rue]=Nl[iue]=Nl[gue]=Nl[_ue]=Nl[vue]=Nl[yue]=Nl[bue]=Nl[sue]=Nl[cue]=Nl[Ml]=Nl[lue]=Nl[uue]=Nl[due]=Nl[fue]=Nl[xue]=Nl[Sue]=Nl[Cue]=Nl[wue]=!0,Nl[aue]=Nl[jl]=Nl[pue]=!1}));function Tue(e){return kl(e,Fl|Il)}var Fl,Il,Eue=n((()=>{Pl(),Fl=1,Il=4}));function Ll(e){return e.sort((e,t)=>{let n=t.modified.getTime()-e.modified.getTime();return n===0?t.created.getTime()-e.created.getTime():n})}var Due=n((()=>{})),Rl=a((e=>{var t=Symbol.for(`yaml.alias`),n=Symbol.for(`yaml.document`),r=Symbol.for(`yaml.map`),i=Symbol.for(`yaml.pair`),a=Symbol.for(`yaml.scalar`),o=Symbol.for(`yaml.seq`),s=Symbol.for(`yaml.node.type`),c=e=>!!e&&typeof e==`object`&&e[s]===t,l=e=>!!e&&typeof e==`object`&&e[s]===n,u=e=>!!e&&typeof e==`object`&&e[s]===r,d=e=>!!e&&typeof e==`object`&&e[s]===i,f=e=>!!e&&typeof e==`object`&&e[s]===a,p=e=>!!e&&typeof e==`object`&&e[s]===o;function m(e){if(e&&typeof e==`object`)switch(e[s]){case r:case o:return!0}return!1}function h(e){if(e&&typeof e==`object`)switch(e[s]){case t:case r:case a:case o:return!0}return!1}e.ALIAS=t,e.DOC=n,e.MAP=r,e.NODE_TYPE=s,e.PAIR=i,e.SCALAR=a,e.SEQ=o,e.hasAnchor=e=>(f(e)||m(e))&&!!e.anchor,e.isAlias=c,e.isCollection=m,e.isDocument=l,e.isMap=u,e.isNode=h,e.isPair=d,e.isScalar=f,e.isSeq=p})),zl=a((e=>{var t=Rl(),n=Symbol(`break visit`),r=Symbol(`skip children`),i=Symbol(`remove node`);function a(e,n){let r=l(n);t.isDocument(e)?o(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):o(null,e,r,Object.freeze([]))}a.BREAK=n,a.SKIP=r,a.REMOVE=i;function o(e,r,a,s){let c=u(e,r,a,s);if(t.isNode(c)||t.isPair(c))return d(e,s,c),o(e,c,a,s);if(typeof c!=`symbol`){if(t.isCollection(r)){s=Object.freeze(s.concat(r));for(let e=0;e<r.items.length;++e){let t=o(e,r.items[e],a,s);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){s=Object.freeze(s.concat(r));let e=o(`key`,r.key,a,s);if(e===n)return n;e===i&&(r.key=null);let t=o(`value`,r.value,a,s);if(t===n)return n;t===i&&(r.value=null)}}return c}async function s(e,n){let r=l(n);t.isDocument(e)?await c(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):await c(null,e,r,Object.freeze([]))}s.BREAK=n,s.SKIP=r,s.REMOVE=i;async function c(e,r,a,o){let s=await u(e,r,a,o);if(t.isNode(s)||t.isPair(s))return d(e,o,s),c(e,s,a,o);if(typeof s!=`symbol`){if(t.isCollection(r)){o=Object.freeze(o.concat(r));for(let e=0;e<r.items.length;++e){let t=await c(e,r.items[e],a,o);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){o=Object.freeze(o.concat(r));let e=await c(`key`,r.key,a,o);if(e===n)return n;e===i&&(r.key=null);let t=await c(`value`,r.value,a,o);if(t===n)return n;t===i&&(r.value=null)}}return s}function l(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function u(e,n,r,i){if(typeof r==`function`)return r(e,n,i);if(t.isMap(n))return r.Map?.(e,n,i);if(t.isSeq(n))return r.Seq?.(e,n,i);if(t.isPair(n))return r.Pair?.(e,n,i);if(t.isScalar(n))return r.Scalar?.(e,n,i);if(t.isAlias(n))return r.Alias?.(e,n,i)}function d(e,n,r){let i=n[n.length-1];if(t.isCollection(i))i.items[e]=r;else if(t.isPair(i))e===`key`?i.key=r:i.value=r;else if(t.isDocument(i))i.contents=r;else{let e=t.isAlias(i)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}e.visit=a,e.visitAsync=s})),Bl=a((e=>{var t=Rl(),n=zl(),r={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},i=e=>e.replace(/[!,[\]{}]/g,e=>r[e]),a=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,n){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case`%TAG`:{if(r.length!==2&&(n(0,`%TAG directive should contain exactly two parts`),r.length<2))return!1;let[e,t]=r;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,r.length!==1)return n(0,`%YAML directive should contain exactly one part`),!1;let[e]=r;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return n(6,`Unsupported YAML version ${e}`,t),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+i(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],i=Object.entries(this.tags),a;if(e&&i.length>0&&t.isNode(e.contents)){let r={};n.visit(e.contents,(e,n)=>{t.isNode(n)&&n.tag&&(r[n.tag]=!0)}),a=Object.keys(r)}else a=[];for(let[t,n]of i)t===`!!`&&n===`tag:yaml.org,2002:`||(!e||a.some(e=>e.startsWith(n)))&&r.push(`%TAG ${t} ${n}`);return r.join(`
|
|
2
2
|
`)}};a.defaultYaml={explicit:!1,version:`1.2`},a.defaultTags={"!!":`tag:yaml.org,2002:`},e.Directives=a})),Vl=a((e=>{var t=Rl(),n=zl();function r(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function i(e){let t=new Set;return n.visit(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function a(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function o(e,n){let r=[],o=new Map,s=null;return{onAnchor:t=>{r.push(t),s??(s=i(e));let o=a(n,s);return s.add(o),o},setAnchors:()=>{for(let e of r){let n=o.get(e);if(typeof n==`object`&&n.anchor&&(t.isScalar(n.node)||t.isCollection(n.node)))n.node.anchor=n.anchor;else{let t=Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:o}}e.anchorIsValid=r,e.anchorNames=i,e.createNodeAnchors=o,e.findNewAnchor=a})),Hl=a((e=>{function t(e,n,r,i){if(i&&typeof i==`object`)if(Array.isArray(i))for(let n=0,r=i.length;n<r;++n){let r=i[n],a=t(e,i,String(n),r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let r=i.get(n),a=t(e,i,n,r);a===void 0?i.delete(n):a!==r&&i.set(n,a)}else if(i instanceof Set)for(let n of Array.from(i)){let r=t(e,i,n,n);r===void 0?i.delete(n):r!==n&&(i.delete(n),i.add(r))}else for(let[n,r]of Object.entries(i)){let a=t(e,i,n,r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}return e.call(n,r,i)}e.applyReviver=t})),Ul=a((e=>{var t=Rl();function n(e,r,i){if(Array.isArray(e))return e.map((e,t)=>n(e,String(t),i));if(e&&typeof e.toJSON==`function`){if(!i||!t.hasAnchor(e))return e.toJSON(r,i);let n={aliasCount:0,count:1,res:void 0};i.anchors.set(e,n),i.onCreate=e=>{n.res=e,delete i.onCreate};let a=e.toJSON(r,i);return i.onCreate&&i.onCreate(a),a}return typeof e==`bigint`&&!i?.keep?Number(e):e}e.toJS=n})),Wl=a((e=>{var t=Hl(),n=Rl(),r=Ul();e.NodeBase=class{constructor(e){Object.defineProperty(this,n.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:i,maxAliasCount:a,onAnchor:o,reviver:s}={}){if(!n.isDocument(e))throw TypeError(`A document argument is required`);let c={anchors:new Map,doc:e,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof a==`number`?a:100},l=r.toJS(this,``,c);if(typeof o==`function`)for(let{count:e,res:t}of c.anchors.values())o(t,e);return typeof s==`function`?t.applyReviver(s,{"":l},``,l):l}}})),Gl=a((e=>{var t=Vl(),n=zl(),r=Rl(),i=Wl(),a=Ul(),o=class extends i.NodeBase{constructor(e){super(r.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){if(t?.maxAliasCount===0)throw ReferenceError(`Alias resolution is disabled`);let i;t?.aliasResolveCache?i=t.aliasResolveCache:(i=[],n.visit(e,{Node:(e,t)=>{(r.isAlias(t)||r.hasAnchor(t))&&i.push(t)}}),t&&(t.aliasResolveCache=i));let a;for(let e of i){if(e===this)break;e.anchor===this.source&&(a=e)}return a}toJSON(e,t){if(!t)return{source:this.source};let{anchors:n,doc:r,maxAliasCount:i}=t,o=this.resolve(r,t);if(!o){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}let c=n.get(o);if(c||(a.toJS(o,null,t),c=n.get(o)),c?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(i>=0&&(c.count+=1,c.aliasCount===0&&(c.aliasCount=s(r,o,n)),c.count*c.aliasCount>i))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`);return c.res}toString(e,n,r){let i=`*${this.source}`;if(e){if(t.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${i} `}return i}};function s(e,t,n){if(r.isAlias(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}else if(r.isCollection(t)){let r=0;for(let i of t.items){let t=s(e,i,n);t>r&&(r=t)}return r}else if(r.isPair(t)){let r=s(e,t.key,n),i=s(e,t.value,n);return Math.max(r,i)}return 1}e.Alias=o})),Kl=a((e=>{var t=Rl(),n=Wl(),r=Ul(),i=e=>!e||typeof e!=`function`&&typeof e!=`object`,a=class extends n.NodeBase{constructor(e){super(t.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:r.toJS(this.value,e,t)}toString(){return String(this.value)}};a.BLOCK_FOLDED=`BLOCK_FOLDED`,a.BLOCK_LITERAL=`BLOCK_LITERAL`,a.PLAIN=`PLAIN`,a.QUOTE_DOUBLE=`QUOTE_DOUBLE`,a.QUOTE_SINGLE=`QUOTE_SINGLE`,e.Scalar=a,e.isScalarValue=i})),ql=a((e=>{var t=Gl(),n=Rl(),r=Kl(),i=`tag:yaml.org,2002:`;function a(e,t,n){if(t){let e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function o(e,o,s){if(n.isDocument(e)&&(e=e.contents),n.isNode(e))return e;if(n.isPair(e)){let t=s.schema[n.MAP].createNode?.(s.schema,null,s);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:c,onAnchor:l,onTagObj:u,schema:d,sourceObjects:f}=s,p;if(c&&e&&typeof e==`object`){if(p=f.get(e),p)return p.anchor??(p.anchor=l(e)),new t.Alias(p.anchor);p={anchor:null,node:null},f.set(e,p)}o?.startsWith(`!!`)&&(o=i+o.slice(2));let m=a(e,o,d.tags);if(!m){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new r.Scalar(e);return p&&(p.node=t),t}m=e instanceof Map?d[n.MAP]:Symbol.iterator in Object(e)?d[n.SEQ]:d[n.MAP]}u&&(u(m),delete s.onTagObj);let h=m?.createNode?m.createNode(s.schema,e,s):typeof m?.nodeClass?.from==`function`?m.nodeClass.from(s.schema,e,s):new r.Scalar(e);return o?h.tag=o:m.default||(h.tag=m.tag),p&&(p.node=h),h}e.createNode=o})),Jl=a((e=>{var t=ql(),n=Rl(),r=Wl();function i(e,n,r){let i=r;for(let e=n.length-1;e>=0;--e){let t=n[e];if(typeof t==`number`&&Number.isInteger(t)&&t>=0){let e=[];e[t]=i,i=e}else i=new Map([[t,i]])}return t.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}var a=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done;e.Collection=class extends r.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>n.isNode(t)||n.isPair(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(a(e))this.add(t);else{let[r,...a]=e,o=this.get(r,!0);if(n.isCollection(o))o.addIn(a,t);else if(o===void 0&&this.schema)this.set(r,i(this.schema,a,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}deleteIn(e){let[t,...r]=e;if(r.length===0)return this.delete(t);let i=this.get(t,!0);if(n.isCollection(i))return i.deleteIn(r);throw Error(`Expected YAML collection at ${t}. Remaining path: ${r}`)}getIn(e,t){let[r,...i]=e,a=this.get(r,!0);return i.length===0?!t&&n.isScalar(a)?a.value:a:n.isCollection(a)?a.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!n.isPair(t))return!1;let r=t.value;return r==null||e&&n.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[t,...r]=e;if(r.length===0)return this.has(t);let i=this.get(t,!0);return n.isCollection(i)?i.hasIn(r):!1}setIn(e,t){let[r,...a]=e;if(a.length===0)this.set(r,t);else{let e=this.get(r,!0);if(n.isCollection(e))e.setIn(a,t);else if(e===void 0&&this.schema)this.set(r,i(this.schema,a,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}},e.collectionFromPath=i,e.isEmptyPath=a})),Yl=a((e=>{var t=e=>e.replace(/^(?!$)(?: $)?/gm,`#`);function n(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}e.indentComment=n,e.lineComment=(e,t,r)=>e.endsWith(`
|
|
3
3
|
`)?n(r,t):r.includes(`
|
|
4
4
|
`)?`
|
|
@@ -114,12 +114,12 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
|
|
|
114
114
|
`)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
|
|
115
115
|
`,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=l(c(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=l(c(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}}})),Yue=a((e=>{var t=Ou(),n=yu(),r=bu(),i=Ql(),a=Rl(),o=ju(),s=Mu();function c(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new o.LineCounter||null,prettyErrors:t}}function l(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=Array.from(l.compose(o.parse(e)));if(a&&i)for(let t of u)t.errors.forEach(r.prettifyError(e,i)),t.warnings.forEach(r.prettifyError(e,i));return u.length>0?u:Object.assign([],{empty:!0},l.streamInfo())}function u(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=null;for(let t of l.compose(o.parse(e),!0,e.length))if(!u)u=t;else if(u.options.logLevel!==`silent`){u.errors.push(new r.YAMLParseError(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return a&&i&&(u.errors.forEach(r.prettifyError(e,i)),u.warnings.forEach(r.prettifyError(e,i))),u}function d(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let a=u(e,n);if(!a)return null;if(a.warnings.forEach(e=>i.warn(a.options.logLevel,e)),a.errors.length>0){if(a.options.logLevel!==`silent`)throw a.errors[0];a.errors=[]}return a.toJS(Object.assign({reviver:r},n))}function f(e,t,r){let i=null;if(typeof t==`function`||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r==`string`&&(r=r.length),typeof r==`number`){let e=Math.round(r);r=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=r??t??{};if(!e)return}return a.isDocument(e)&&!i?e.toString(r):new n.Document(e,i,r).toString(r)}e.parse=d,e.parseAllDocuments=l,e.parseDocument=u,e.stringify=f})),Nu=a((e=>{var t=Ou(),n=yu(),r=vu(),i=bu(),a=Gl(),o=Rl(),s=tu(),c=Kl(),l=ru(),u=au(),d=ku(),f=Au(),p=ju(),m=Mu(),h=Yue(),g=zl();e.Composer=t.Composer,e.Document=n.Document,e.Schema=r.Schema,e.YAMLError=i.YAMLError,e.YAMLParseError=i.YAMLParseError,e.YAMLWarning=i.YAMLWarning,e.Alias=a.Alias,e.isAlias=o.isAlias,e.isCollection=o.isCollection,e.isDocument=o.isDocument,e.isMap=o.isMap,e.isNode=o.isNode,e.isPair=o.isPair,e.isScalar=o.isScalar,e.isSeq=o.isSeq,e.Pair=s.Pair,e.Scalar=c.Scalar,e.YAMLMap=l.YAMLMap,e.YAMLSeq=u.YAMLSeq,e.CST=d,e.Lexer=f.Lexer,e.LineCounter=p.LineCounter,e.Parser=m.Parser,e.parse=h.parse,e.parseAllDocuments=h.parseAllDocuments,e.parseDocument=h.parseDocument,e.stringify=h.stringify,e.visit=g.visit,e.visitAsync=g.visitAsync}));function Pu(e){return typeof Bun<`u`?Bun.YAML.parse(e):Nu().parse(e)}var Fu=n((()=>{}));function Xue(e){let t=e.split(`
|
|
116
116
|
`),n=[];for(let e of t){let t=e.match(/^([a-zA-Z_-]+):\s+(.+)$/);if(t){let[,r,i]=t;if(!r||!i){n.push(e);continue}if(i.startsWith(`"`)&&i.endsWith(`"`)||i.startsWith(`'`)&&i.endsWith(`'`)){n.push(e);continue}if(Uu.test(i)){let e=i.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`);n.push(`${r}: "${e}"`);continue}}n.push(e)}return n.join(`
|
|
117
|
-
`)}function Iu(e,t){let n=e.match(Wu);if(!n)return{frontmatter:{},content:e};let r=n[1]||``,i=e.slice(n[0].length),a={};try{let e=Pu(r);e&&typeof e==`object`&&!Array.isArray(e)&&(a=e)}catch{try{let e=Pu(Xue(r));e&&typeof e==`object`&&!Array.isArray(e)&&(a=e)}catch(e){G(`Failed to parse YAML frontmatter${t?` in ${t}`:``}: ${e instanceof Error?e.message:e}`,{level:`warn`})}}return{frontmatter:a,content:i}}function Lu(e){if(Array.isArray(e))return e.flatMap(Lu);if(typeof e!=`string`)return[];let t=[],n=``,r=0;for(let i=0;i<e.length;i++){let a=e[i];if(a===`{`)r++,n+=a;else if(a===`}`)r--,n+=a;else if(a===`,`&&r===0){let e=n.trim();e&&t.push(e),n=``}else n+=a}let i=n.trim();return i&&t.push(i),t.filter(e=>e.length>0).flatMap(e=>Ru(e))}function Ru(e){let t=e.match(/^([^{]*)\{([^}]+)\}(.*)$/);if(!t)return[e];let n=t[1]||``,r=t[2]||``,i=t[3]||``,a=r.split(`,`).map(e=>e.trim()),o=[];for(let e of a){let t=Ru(n+e+i);o.push(...t)}return o}function zu(e){if(e==null)return;let t=typeof e==`number`?e:parseInt(String(e),10);if(Number.isInteger(t)&&t>0)return t}function Bu(e,t,n){return e==null?null:typeof e==`string`?e.trim()||null:typeof e==`number`||typeof e==`boolean`?String(e):(G(`Description invalid for ${n?`${n}:${t}`:t??`unknown`} - omitting`,{level:`warn`}),null)}function Vu(e){return e===!0||e===`true`}function Hu(e,t){if(e==null)return;let n=String(e).trim().toLowerCase();if(n!==``){if(Gu.includes(n))return n;G(`Frontmatter 'shell: ${e}' in ${t} is not recognized. Valid values: ${Gu.join(`, `)}. Falling back to bash.`,{level:`warn`})}}var Uu,Wu,Gu,Ku=n((()=>{K(),Fu(),Uu=/[{}[\]*&#!|>%@`]|: /,Wu=/^---\s*\n([\s\S]*?)---\s*\n?/,Gu=[`bash`,`powershell`]}));function qu(e){return Fo()===`vertex`?Yu:e?.isNonInteractive?e.hasAppendSystemPrompt?Xu:Zu:Yu}function Zue(){return!f(process.env.CLAUDE_CODE_ATTRIBUTION_HEADER)}function Ju(){if(!Zue())return``;let e=process.env.CLAUDE_CODE_ENTRYPOINT??`unknown`,t=Iie(),n=`x-anthropic-billing-header: cc_version=0.0.
|
|
117
|
+
`)}function Iu(e,t){let n=e.match(Wu);if(!n)return{frontmatter:{},content:e};let r=n[1]||``,i=e.slice(n[0].length),a={};try{let e=Pu(r);e&&typeof e==`object`&&!Array.isArray(e)&&(a=e)}catch{try{let e=Pu(Xue(r));e&&typeof e==`object`&&!Array.isArray(e)&&(a=e)}catch(e){G(`Failed to parse YAML frontmatter${t?` in ${t}`:``}: ${e instanceof Error?e.message:e}`,{level:`warn`})}}return{frontmatter:a,content:i}}function Lu(e){if(Array.isArray(e))return e.flatMap(Lu);if(typeof e!=`string`)return[];let t=[],n=``,r=0;for(let i=0;i<e.length;i++){let a=e[i];if(a===`{`)r++,n+=a;else if(a===`}`)r--,n+=a;else if(a===`,`&&r===0){let e=n.trim();e&&t.push(e),n=``}else n+=a}let i=n.trim();return i&&t.push(i),t.filter(e=>e.length>0).flatMap(e=>Ru(e))}function Ru(e){let t=e.match(/^([^{]*)\{([^}]+)\}(.*)$/);if(!t)return[e];let n=t[1]||``,r=t[2]||``,i=t[3]||``,a=r.split(`,`).map(e=>e.trim()),o=[];for(let e of a){let t=Ru(n+e+i);o.push(...t)}return o}function zu(e){if(e==null)return;let t=typeof e==`number`?e:parseInt(String(e),10);if(Number.isInteger(t)&&t>0)return t}function Bu(e,t,n){return e==null?null:typeof e==`string`?e.trim()||null:typeof e==`number`||typeof e==`boolean`?String(e):(G(`Description invalid for ${n?`${n}:${t}`:t??`unknown`} - omitting`,{level:`warn`}),null)}function Vu(e){return e===!0||e===`true`}function Hu(e,t){if(e==null)return;let n=String(e).trim().toLowerCase();if(n!==``){if(Gu.includes(n))return n;G(`Frontmatter 'shell: ${e}' in ${t} is not recognized. Valid values: ${Gu.join(`, `)}. Falling back to bash.`,{level:`warn`})}}var Uu,Wu,Gu,Ku=n((()=>{K(),Fu(),Uu=/[{}[\]*&#!|>%@`]|: /,Wu=/^---\s*\n([\s\S]*?)---\s*\n?/,Gu=[`bash`,`powershell`]}));function qu(e){return Fo()===`vertex`?Yu:e?.isNonInteractive?e.hasAppendSystemPrompt?Xu:Zu:Yu}function Zue(){return!f(process.env.CLAUDE_CODE_ATTRIBUTION_HEADER)}function Ju(){if(!Zue())return``;let e=process.env.CLAUDE_CODE_ENTRYPOINT??`unknown`,t=Iie(),n=`x-anthropic-billing-header: cc_version=0.0.24; cc_entrypoint=${e};${t?` cc_workload=${t};`:``}`;return G(`attribution header ${n}`),n}var Yu,Xu,Zu,Qu,$u,ed=n((()=>{K(),g(),Io(),Zie(),Yu=`You are Work Mate, a CLI for Work Mate.`,Xu=`You are Work Mate, a CLI for Work Mate, running within the Work Mate Agent SDK.`,Zu=`You are a Work Mate agent, built on the Work Mate Agent SDK.`,Qu=[Yu,Xu,Zu],$u=new Set(Qu)})),td,Que=n((()=>{td=e=>!1})),$ue=a(((e,n)=>{var r=t(`child_process`),i=r.spawn,a=r.exec;n.exports=function(e,t,n){if(typeof t==`function`&&n===void 0&&(n=t,t=void 0),e=parseInt(e),Number.isNaN(e)){if(n)return n(Error(`pid must be a number`));throw Error(`pid must be a number`)}var r={},s={};switch(r[e]=[],s[e]=1,process.platform){case`win32`:a(`taskkill /pid `+e+` /T /F`,n);break;case`darwin`:c(e,r,s,function(e){return i(`pgrep`,[`-P`,e])},function(){o(r,t,n)});break;default:c(e,r,s,function(e){return i(`ps`,[`-o`,`pid`,`--no-headers`,`--ppid`,e])},function(){o(r,t,n)});break}};function o(e,t,n){var r={};try{Object.keys(e).forEach(function(n){e[n].forEach(function(e){r[e]||(s(e,t),r[e]=1)}),r[n]||(s(n,t),r[n]=1)})}catch(e){if(n)return n(e);throw e}if(n)return n()}function s(e,t){try{process.kill(parseInt(e,10),t)}catch(e){if(e.code!==`ESRCH`)throw e}}function c(e,t,n,r,i){var a=r(e),o=``;a.stdout.on(`data`,function(e){var e=e.toString(`ascii`);o+=e}),a.on(`close`,function(a){if(delete n[e],a!=0){Object.keys(n).length==0&&i();return}o.match(/\d+/g).forEach(function(a){a=parseInt(a,10),t[e].push(a),t[a]=[],n[a]=1,c(a,t,n,r,i)})})}}));function ede(e){if(typeof e==`string`)return nd.find(t=>t===e)}var nd,rd,id,ad,od,sd,cd,ld=n((()=>{nd=[`user`,`feedback`,`project`,`reference`],rd=[`## Types of memory`,``,`<types>`,`<type>`,` <name>user</name>`,` <description>The user's role, goals, preferences, responsibilities, and knowledge. Use these to tailor your behavior to the user.</description>`,`</type>`,`<type>`,` <name>feedback</name>`,` <description>Guidance from the user about how to approach work — what to avoid and what to keep doing. Record from failure AND success. Include *why* so you can judge edge cases later. Structure content as: rule/fact, then **Why:** and **How to apply:** lines.</description>`,`</type>`,`<type>`,` <name>project</name>`,` <description>Information about ongoing work, goals, initiatives, bugs, or incidents not derivable from code or git history. Convert relative dates to absolute dates when saving (e.g., "Thursday" → "2026-03-05").</description>`,`</type>`,`<type>`,` <name>reference</name>`,` <description>Pointers to external systems where information can be found (e.g., Linear projects, Slack channels, Grafana dashboards).</description>`,`</type>`,`</types>`,``],id=[`## What NOT to save in memory`,``,`- Code patterns, conventions, architecture, file paths, or project structure — these can be derived by reading the current project state.`,"- Git history, recent changes, or who-changed-what — `git log` / `git blame` are authoritative.",`- Debugging solutions or fix recipes — the fix is in the code; the commit message has the context.`,`- Anything already documented in AGENTS.md files.`,`- Ephemeral task details: in-progress work, temporary state, current conversation context.`,``,`These exclusions apply even when the user explicitly asks you to save. If they ask you to save a PR list or activity summary, ask what was *surprising* or *non-obvious* about it — that is the part worth keeping.`],ad=`- Memory records can become stale over time. Use memory as context for what was true at a given point in time. Before answering the user or building assumptions based solely on information in memory records, verify that the memory is still correct and up-to-date by reading the current state of the files or resources. If a recalled memory conflicts with current information, trust what you observe now — and update or remove the stale memory rather than acting on it.`,od=[`## When to access memories`,`- When memories seem relevant, or the user references prior-conversation work.`,`- You MUST access memory when the user explicitly asks you to check, recall, or remember.`,`- If the user says to *ignore* or *not use* memory: proceed as if MEMORY.md were empty. Do not apply remembered facts, cite, compare against, or mention memory content.`,ad],sd=[`## Before recommending from memory`,``,`A memory that names a specific function, file, or flag is a claim that it existed *when the memory was written*. It may have been renamed, removed, or never merged. Before recommending it:`,``,`- If the memory names a file path: check the file exists.`,`- If the memory names a function or flag: grep for it.`,`- If the user is about to act on your recommendation (not just asking about history), verify first.`,``,`"The memory says X exists" is not the same as "X exists now."`,``,"A memory that summarizes repo state (activity logs, architecture snapshots) is frozen in time. If the user asks about *recent* or *current* state, prefer `git log` or reading the code over recalling the snapshot."],cd=["```markdown",`---`,`name: {{memory name}}`,`description: {{one-line description — used to decide relevance in future conversations, so be specific}}`,`type: {{${nd.join(`, `)}}}`,`---`,``,`{{memory content — for feedback/project types, structure as: rule/fact, then **Why:** and **How to apply:** lines}}`,"```"]}));function ud(e){let t=e.trim(),n=t.split(`
|
|
118
118
|
`),r=n.length,i=t.length,a=r>200,o=i>gd;if(!a&&!o)return{content:t,lineCount:r,byteCount:i,wasLineTruncated:a,wasByteTruncated:o};let s=a?n.slice(0,200).join(`
|
|
119
119
|
`):t;if(s.length>25e3){let e=s.lastIndexOf(`
|
|
120
120
|
`,gd);s=s.slice(0,e>0?e:gd)}let c=o&&!a?`${go(i)} (limit: ${go(gd)}) — index entries are too long`:a&&!o?`${r} lines (limit: 200)`:`${r} lines and ${go(i)}`;return{content:s+`\n\n> WARNING: ${hd} is ${c}. Only part of it was loaded. Keep index entries to one line under ~200 chars; move detail into topic files.`,lineCount:r,byteCount:i,wasLineTruncated:a,wasByteTruncated:o}}async function dd(e){let t=q();try{await t.mkdir(e)}catch(t){G(`ensureMemoryDirExists failed for ${e}: ${(t instanceof Error&&`code`in t&&typeof t.code==`string`?t.code:void 0)??String(t)}`,{level:`debug`})}}function fd(e,t){q().readdir(e).then(e=>{let n=0,r=0;for(let t of e)t.isFile()?n++:t.isDirectory()&&r++;Y(`tengu_memdir_loaded`,{...t,total_file_count:n,total_subdir_count:r})},()=>{Y(`tengu_memdir_loaded`,t)})}function pd(e,t,n,r=!1){let i=r?[`## How to save memories`,``,"Write each memory to its own file (e.g., `user_role.md`, `feedback_testing.md`) using this frontmatter format:",``,...cd,``,`- Keep the name, description, and type fields in memory files up-to-date with the content`,`- Organize memory semantically by topic, not chronologically`,`- Update or remove memories that turn out to be wrong or outdated`,`- Do not write duplicate memories. First check if there is an existing memory you can update before writing a new one.`]:[`## How to save memories`,``,`Saving a memory is a two-step process:`,``,"**Step 1** — write the memory to its own file (e.g., `user_role.md`, `feedback_testing.md`) using this frontmatter format:",``,...cd,``,`**Step 2** — add a pointer to that file in \`${hd}\`. \`${hd}\` is an index, not a memory — each entry should be one line, under ~150 characters: \`- [Title](file.md) — one-line hook\`. It has no frontmatter. Never write memory content directly into \`${hd}\`.`,``,`- \`${hd}\` is always loaded into your conversation context — lines after 200 will be truncated, so keep the index concise`,`- Keep the name, description, and type fields in memory files up-to-date with the content`,`- Organize memory semantically by topic, not chronologically`,`- Update or remove memories that turn out to be wrong or outdated`,`- Do not write duplicate memories. First check if there is an existing memory you can update before writing a new one.`];return[`# ${e}`,``,`You have a persistent, file-based memory system at \`${t}\`. ${vd}`,``,`You should build up this memory system over time so that future conversations can have a complete picture of who the user is, how they'd like to collaborate with you, what behaviors to avoid or repeat, and the context behind the work the user gives you.`,``,`If the user explicitly asks you to remember something, save it immediately as whichever type fits best. If they ask you to forget something, find and remove the relevant entry.`,``,...rd,...id,``,...i,``,...od,``,...sd,``,`## Memory and other forms of persistence`,`Memory is one of several persistence mechanisms available to you as you assist the user in a given conversation. The distinction is often that memory can be recalled in future conversations and should not be used for persisting information that is only useful within the scope of the current conversation.`,`- When to use or update a plan instead of memory: If you are about to start a non-trivial implementation task and would like to reach alignment with the user on your approach you should use a Plan rather than saving this information to memory. Similarly, if you already have a plan within the conversation and you have changed your approach persist that change by updating the plan rather than saving a memory.`,`- When to use or update tasks instead of memory: When you need to break your work in current conversation into discrete steps or keep track of your progress use tasks instead of saving to memory. Tasks are great for persisting information about the work that needs to be done in the current conversation, but memory should be reserved for information that will be useful in future conversations.`,``,...n??[],``]}function tde(e){let{displayName:t,memoryDir:n,extraGuidelines:r}=e,i=q(),a=n+hd,o=``;try{o=i.readFileSync(a,{encoding:`utf-8`})}catch{}let s=pd(t,n,r);if(o.trim()){let e=ud(o),r=t===_d?`auto`:`agent`;fd(n,{content_length:e.byteCount,line_count:e.lineCount,was_truncated:e.wasLineTruncated,was_byte_truncated:e.wasByteTruncated,memory_type:r}),s.push(`## ${hd}`,``,e.content)}else s.push(`## ${hd}`,``,`Your ${hd} is currently empty. When you save new memories, they will appear here.`);return s.join(`
|
|
121
121
|
`)}async function md(){let e=ta(),t=process.env.CLAUDE_COWORK_MEMORY_EXTRA_GUIDELINES,n=t&&t.trim().length>0?[t]:void 0;if(e){let e=ia();return await dd(e),fd(e,{memory_type:`auto`}),pd(`auto memory`,e,n,!1).join(`
|
|
122
|
-
`)}return Y(`tengu_memdir_disabled`,{disabled_by_env_var:h(process.env.CLAUDE_CODE_DISABLE_AUTO_MEMORY),disabled_by_setting:!h(process.env.CLAUDE_CODE_DISABLE_AUTO_MEMORY)&&Vi().autoMemoryEnabled===!1}),null}var hd,gd,_d,vd,yd=n((()=>{or(),ra(),oo(),K(),g(),so(),vi(),ld(),hd=`MEMORY.md`,gd=25e3,_d=`auto memory`,vd=`This directory already exists — write to it directly with the Write tool (do not run mkdir or check for its existence).`}));function nde(e){return e.replace(/:/g,`-`)}function bd(e){return process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR?X(process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR,`projects`,qi(wr(en())??en()),`agent-memory-local`,e)+kc:X(H(),`.workmate`,`agent-memory-local`,e)+kc}function xd(e,t){let n=nde(e);switch(t){case`project`:return X(H(),`.workmate`,`agent-memory`,n)+kc;case`local`:return bd(n);case`user`:return X(na(),`agent-memory`,n)+kc}}function Sd(e){let t=wc(e),n=na();if(t.startsWith(X(n,`agent-memory`)+kc)||t.startsWith(X(H(),`.workmate`,`agent-memory`)+kc))return!0;if(process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR){if(t.includes(`${kc}agent-memory-local${kc}`)&&t.startsWith(X(process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR,`projects`)+kc))return!0}else if(t.startsWith(X(H(),`.workmate`,`agent-memory-local`)+kc))return!0;return!1}function rde(e){switch(e){case`user`:return`User (${X(na(),`agent-memory`)}/)`;case`project`:return`Project (.workmate/agent-memory/)`;case`local`:return`Local (${bd(`...`)})`;default:return`None`}}function Cd(e,t){let n;switch(t){case`user`:n=`- Since this memory is user-scope, keep learnings general since they apply across all projects`;break;case`project`:n=`- Since this memory is project-scope and shared with your team via version control, tailor your memories to this project`;break;case`local`:n=`- Since this memory is local-scope (not checked into version control), tailor your memories to this project and machine`;break}let r=xd(e,t);dd(r);let i=process.env.CLAUDE_COWORK_MEMORY_EXTRA_GUIDELINES;return tde({displayName:`Persistent Agent Memory`,memoryDir:r,extraGuidelines:i&&i.trim().length>0?[n,i]:[n]})}var wd=n((()=>{Jt(),yd(),ra(),Vn(),Ir(),Ai()}));function Td(){let e=process.env.CLAUDE_CODE_ENVIRONMENT_KIND;return e===`byoc`||e===`anthropic_cloud`?e:null}var Ed=n((()=>{K()}));function ide(e){return qc(4).readUInt32BE(0)%e}function Dd(e){return e[ide(e.length)]}function ade(){return`${Dd(Od)}-${Dd(Ad)}-${Dd(kd)}`}var Od,kd,Ad,ode=n((()=>{Od=`abundant.ancient.bright.calm.cheerful.clever.cozy.curious.dapper.dazzling.deep.delightful.eager.elegant.enchanted.fancy.fluffy.gentle.gleaming.golden.graceful.happy.hidden.humble.jolly.joyful.keen.kind.lively.lovely.lucky.luminous.magical.majestic.mellow.merry.mighty.misty.noble.peaceful.playful.polished.precious.proud.quiet.quirky.radiant.rosy.serene.shiny.silly.sleepy.smooth.snazzy.snug.snuggly.soft.sparkling.spicy.splendid.sprightly.starry.steady.sunny.swift.tender.tidy.toasty.tranquil.twinkly.valiant.vast.velvet.vivid.warm.whimsical.wild.wise.witty.wondrous.zany.zesty.zippy.breezy.bubbly.buzzing.cheeky.cosmic.cozy.crispy.crystalline.cuddly.drifting.dreamy.effervescent.ethereal.fizzy.flickering.floating.floofy.fluttering.foamy.frolicking.fuzzy.giggly.glimmering.glistening.glittery.glowing.goofy.groovy.harmonic.hazy.humming.iridescent.jaunty.jazzy.jiggly.melodic.moonlit.mossy.nifty.peppy.prancy.purrfect.purring.quizzical.rippling.rustling.shimmering.shimmying.snappy.snoopy.squishy.swirling.ticklish.tingly.twinkling.velvety.wiggly.wobbly.woolly.zazzy.abstract.adaptive.agile.async.atomic.binary.cached.compiled.composed.compressed.concurrent.cryptic.curried.declarative.delegated.distributed.dynamic.eager.elegant.encapsulated.enumerated.eventual.expressive.federated.functional.generic.greedy.hashed.idempotent.immutable.imperative.indexed.inherited.iterative.lazy.lexical.linear.linked.logical.memoized.modular.mutable.nested.optimized.parallel.parsed.partitioned.piped.polymorphic.pure.reactive.recursive.refactored.reflective.replicated.resilient.robust.scalable.sequential.serialized.sharded.sorted.staged.stateful.stateless.streamed.structured.synchronous.synthetic.temporal.transient.typed.unified.validated.vectorized.virtual`.split(`.`),kd=`aurora.avalanche.blossom.breeze.brook.bubble.canyon.cascade.cloud.clover.comet.coral.cosmos.creek.crescent.crystal.dawn.dewdrop.dusk.eclipse.ember.feather.fern.firefly.flame.flurry.fog.forest.frost.galaxy.garden.glacier.glade.grove.harbor.horizon.island.lagoon.lake.leaf.lightning.meadow.meteor.mist.moon.moonbeam.mountain.nebula.nova.ocean.orbit.pebble.petal.pine.planet.pond.puddle.quasar.rain.rainbow.reef.ripple.river.shore.sky.snowflake.spark.spring.star.stardust.starlight.storm.stream.summit.sun.sunbeam.sunrise.sunset.thunder.tide.twilight.valley.volcano.waterfall.wave.willow.wind.alpaca.axolotl.badger.bear.beaver.bee.bird.bumblebee.bunny.cat.chipmunk.crab.crane.deer.dolphin.dove.dragon.dragonfly.duckling.eagle.elephant.falcon.finch.flamingo.fox.frog.giraffe.goose.hamster.hare.hedgehog.hippo.hummingbird.jellyfish.kitten.koala.ladybug.lark.lemur.llama.lobster.lynx.manatee.meerkat.moth.narwhal.newt.octopus.otter.owl.panda.parrot.peacock.pelican.penguin.phoenix.piglet.platypus.pony.porcupine.puffin.puppy.quail.quokka.rabbit.raccoon.raven.robin.salamander.seahorse.seal.sloth.snail.sparrow.sphinx.squid.squirrel.starfish.swan.tiger.toucan.turtle.unicorn.walrus.whale.wolf.wombat.wren.yeti.zebra.acorn.anchor.balloon.beacon.biscuit.blanket.bonbon.book.boot.cake.candle.candy.castle.charm.clock.cocoa.cookie.crayon.crown.cupcake.donut.dream.fairy.fiddle.flask.flute.fountain.gadget.gem.gizmo.globe.goblet.hammock.harp.haven.hearth.honey.journal.kazoo.kettle.key.kite.lantern.lemon.lighthouse.locket.lollipop.mango.map.marble.marshmallow.melody.mitten.mochi.muffin.music.nest.noodle.oasis.origami.pancake.parasol.peach.pearl.pebble.pie.pillow.pinwheel.pixel.pizza.plum.popcorn.pretzel.prism.pudding.pumpkin.puzzle.quiche.quill.quilt.riddle.rocket.rose.scone.scroll.shell.sketch.snowglobe.sonnet.sparkle.spindle.sprout.sundae.swing.taco.teacup.teapot.thimble.toast.token.tome.tower.treasure.treehouse.trinket.truffle.tulip.umbrella.waffle.wand.whisper.whistle.widget.wreath.zephyr.abelson.adleman.aho.allen.babbage.bachman.backus.barto.bengio.bentley.blum.boole.brooks.catmull.cerf.cherny.church.clarke.cocke.codd.conway.cook.corbato.cray.curry.dahl.diffie.dijkstra.dongarra.eich.emerson.engelbart.feigenbaum.floyd.gosling.graham.gray.hamming.hanrahan.hartmanis.hejlsberg.hellman.hennessy.hickey.hinton.hoare.hollerith.hopcroft.hopper.iverson.kahan.kahn.karp.kay.kernighan.knuth.kurzweil.lamport.lampson.lecun.lerdorf.liskov.lovelace.matsumoto.mccarthy.metcalfe.micali.milner.minsky.moler.moore.naur.neumann.newell.nygaard.papert.parnas.pascal.patterson.pearl.perlis.pike.pnueli.rabin.reddy.ritchie.rivest.rossum.russell.scott.sedgewick.shamir.shannon.sifakis.simon.stallman.stearns.steele.stonebraker.stroustrup.sutherland.sutton.tarjan.thacker.thompson.torvalds.turing.ullman.valiant.wadler.wall.wigderson.wilkes.wilkinson.wirth.wozniak.yao`.split(`.`),Ad=`baking.beaming.booping.bouncing.brewing.bubbling.chasing.churning.coalescing.conjuring.cooking.crafting.crunching.cuddling.dancing.dazzling.discovering.doodling.dreaming.drifting.enchanting.exploring.finding.floating.fluttering.foraging.forging.frolicking.gathering.giggling.gliding.greeting.growing.hatching.herding.honking.hopping.hugging.humming.imagining.inventing.jingling.juggling.jumping.kindling.knitting.launching.leaping.mapping.marinating.meandering.mixing.moseying.munching.napping.nibbling.noodling.orbiting.painting.percolating.petting.plotting.pondering.popping.prancing.purring.puzzling.questing.riding.roaming.rolling.sauteeing.scribbling.seeking.shimmying.singing.skipping.sleeping.snacking.sniffing.snuggling.soaring.sparking.spinning.splashing.sprouting.squishing.stargazing.stirring.strolling.swimming.swinging.tickling.tinkering.toasting.tumbling.twirling.waddling.wandering.watching.weaving.whistling.wibbling.wiggling.wishing.wobbling.wondering.yawning.zooming`.split(`.`)}));function jd(e){let t=e??jn(),n=ln().get(t);if(!n){let e=Rd();for(let t=0;t<Ld;t++){n=ade();let t=X(e,`${n}.md`);if(!q().existsSync(t))break}ite(t,n)}return n}function Md(e,t){ite(e,t)}function sde(){ln().clear()}function Nd(e){let t=jd(jn());return e?X(Rd(),`${t}-agent-${e}.md`):X(Rd(),`${t}.md`)}function Pd(e){let t=Nd(e);try{return q().readFileSync(t,{encoding:`utf-8`})}catch(e){return Qn(e)||J(e),null}}function Fd(e){return e.messages.find(e=>e.slug)?.slug}async function cde(e,t){let n=Fd(e);if(!n)return!1;Md(t??jn(),n);let r=X(Rd(),`${n}.md`);try{return await q().readFile(r,{encoding:`utf-8`}),!0}catch(t){if(!Qn(t))return J(t),!1;if(Td()===null)return!1;G(`Plan file missing during resume: ${r}. Attempting recovery.`);let n=dde(e.messages,`plan`),i=null;if(n&&n.content.length>0?(i=n.content,G(`Plan recovered from file snapshot, ${i.length} chars`,{level:`info`})):(i=ude(e),i&&G(`Plan recovered from message history, ${i.length} chars`,{level:`info`})),i)try{return await ll(r,i,{encoding:`utf-8`}),!0}catch(e){return J(e),!1}return G(`Plan file recovery failed: no file snapshot or plan content found in message history`),!1}}async function lde(e,t){let n=Fd(e);if(!n)return!1;let r=Rd(),i=X(r,`${n}.md`),a=X(r,`${jd(t)}.md`);try{return await Zc(i,a),!0}catch(e){return Qn(e)||J(e),!1}}function ude(e){for(let t=e.messages.length-1;t>=0;t--){let n=e.messages[t];if(n){if(n.type===`assistant`){let{content:e}=n.message;if(Array.isArray(e)){for(let t of e)if(t.type===`tool_use`&&t.name===`ExitPlanMode`){let e=t.input?.plan;if(typeof e==`string`&&e.length>0)return e}}}if(n.type===`user`){let e=n;if(typeof e.planContent==`string`&&e.planContent.length>0)return e.planContent}if(n.type===`attachment`){let e=n;if(e.attachment?.type===`plan_file_reference`){let t=e.attachment.planContent;if(typeof t==`string`&&t.length>0)return t}}}}return null}function dde(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];if(r?.type===`system`&&`subtype`in r&&r.subtype===`file_snapshot`&&`snapshotFiles`in r)return r.snapshotFiles.find(e=>e.key===t)}}async function Id(){if(Td()!==null)try{let e=[],t=Pd();if(t&&e.push({key:`plan`,path:Nd(),content:t}),e.length===0)return;let n={type:`system`,subtype:`file_snapshot`,content:`File snapshot`,level:`info`,isMeta:!0,timestamp:new Date().toISOString(),uuid:Jc(),snapshotFiles:e},{recordTranscript:r}=await import(`./sessionStorage-BcAscOGE.js`);await r([n])}catch(e){J(e)}}var Ld,Rd,zd=n((()=>{d(),Jt(),zs(),Vn(),K(),g(),qn(),Ed(),or(),Ga(),vi(),ode(),Ld=10,Rd=u(function(){let e=Vi().plansDirectory,t;if(e){let n=H(),r=Oc(n,e);!r.startsWith(n+kc)&&r!==n?(J(Error(`plansDirectory must be within project root: ${e}`)),t=X(m(),`plans`)):t=r}else t=X(m(),`plans`);try{q().mkdirSync(t)}catch(e){J(e)}return t})})),Bd,fde=n((()=>{Bd={type:`local-jsx`,name:`add-dir`,description:`添加新的工作目录`,argumentHint:`<path>`,load:()=>import(`./add-dir-JMsRLGfx.js`)}})),Vd,pde=n((()=>{Vd={type:`local-jsx`,name:`btw`,description:`快速问一个旁路问题,不打断主对话`,immediate:!0,argumentHint:`<question>`,load:()=>import(`./btw-Dn1eYFAz.js`)}})),Hd,mde=n((()=>{Hd={type:`local`,name:`clear`,description:`清空对话历史并释放上下文`,aliases:[`reset`,`new`],supportsNonInteractive:!1,load:()=>import(`./clear-Bdhb6b39.js`)}})),Ud,hde=n((()=>{g(),Ud={type:`local`,name:`compact`,description:`清空对话历史但保留摘要在上下文中。可选:/compact [摘要生成的指示]`,isEnabled:()=>!h(process.env.DISABLE_COMPACT),supportsNonInteractive:!0,argumentHint:`<optional custom summarization instructions>`,load:()=>import(`./compact-Bu9BUpxV.js`)}})),Wd,gde=n((()=>{Wd={aliases:[`settings`],type:`local-jsx`,name:`config`,description:`打开配置面板`,load:()=>import(`./config-D58C3_Lu.js`)}})),Gd,Kd,_de=n((()=>{Jt(),Gd={name:`context`,description:`以彩色网格可视化当前上下文占用`,isEnabled:()=>!qt(),type:`local-jsx`,load:()=>import(`./context-CY_yfdYa.js`)},Kd={type:`local`,name:`context`,supportsNonInteractive:!0,description:`显示当前上下文占用`,get isHidden(){return!qt()},isEnabled(){return qt()},load:()=>import(`./context-noninteractive-BDDi3NLF.js`)}})),qd,vde=n((()=>{qd={type:`local-jsx`,name:`diff`,description:`查看未提交的改动以及每一轮的 diff`,load:()=>import(`./diff-BOAElpfQ.js`)}})),Jd,yde=n((()=>{g(),Jd={name:`doctor`,description:`诊断并校验 Work Mate 的安装与设置`,isEnabled:()=>!h(process.env.DISABLE_DOCTOR_COMMAND),type:`local-jsx`,load:()=>import(`./doctor-CkLzqAMd.js`)}})),Yd,bde=n((()=>{Yd={type:`local-jsx`,name:`memory`,description:`编辑 Work Mate 记忆文件`,load:()=>import(`./memory-DDLk9_LJ.js`)}})),Xd,xde=n((()=>{Xd={type:`local-jsx`,name:`mode`,description:`切换交互模式(default、gentle、sharp、workhorse、token-saver、super-ai)`,isEnabled:()=>!0,argumentHint:`<mode-slug>`,load:()=>import(`./mode-CcNsWgK3.js`)}})),Zd,Sde=n((()=>{Zd={type:`local-jsx`,name:`help`,description:`显示帮助与可用命令`,load:()=>import(`./help-CZJdRviD.js`)}}));function Cde(e,t){let n=Fc(e,t);return n===``||!n.startsWith(`..`)&&!Lse(n)}function wde(e,t){let n=Ic(e),r=Ic(t);if(!Cde(n,r))return[n];let i=[],a=r;for(;i.push(a),a!==n;){let e=Ise(a);if(e===a)break;a=e}return i.reverse()}async function Qd(e,t){try{let n=(await q().readFile(e,{encoding:`utf-8`})).trim();return n?{path:e,relativePath:Xre(Fc(t,e))||Fse(e),content:n}:null}catch{return null}}function Tde(e){return e.length===0?null:e.map(e=>`## ${e.relativePath}\n${e.content}`).join(`
|
|
122
|
+
`)}return Y(`tengu_memdir_disabled`,{disabled_by_env_var:h(process.env.CLAUDE_CODE_DISABLE_AUTO_MEMORY),disabled_by_setting:!h(process.env.CLAUDE_CODE_DISABLE_AUTO_MEMORY)&&Vi().autoMemoryEnabled===!1}),null}var hd,gd,_d,vd,yd=n((()=>{or(),ra(),oo(),K(),g(),so(),vi(),ld(),hd=`MEMORY.md`,gd=25e3,_d=`auto memory`,vd=`This directory already exists — write to it directly with the Write tool (do not run mkdir or check for its existence).`}));function nde(e){return e.replace(/:/g,`-`)}function bd(e){return process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR?X(process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR,`projects`,qi(wr(en())??en()),`agent-memory-local`,e)+kc:X(H(),`.workmate`,`agent-memory-local`,e)+kc}function xd(e,t){let n=nde(e);switch(t){case`project`:return X(H(),`.workmate`,`agent-memory`,n)+kc;case`local`:return bd(n);case`user`:return X(na(),`agent-memory`,n)+kc}}function Sd(e){let t=wc(e),n=na();if(t.startsWith(X(n,`agent-memory`)+kc)||t.startsWith(X(H(),`.workmate`,`agent-memory`)+kc))return!0;if(process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR){if(t.includes(`${kc}agent-memory-local${kc}`)&&t.startsWith(X(process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR,`projects`)+kc))return!0}else if(t.startsWith(X(H(),`.workmate`,`agent-memory-local`)+kc))return!0;return!1}function rde(e){switch(e){case`user`:return`User (${X(na(),`agent-memory`)}/)`;case`project`:return`Project (.workmate/agent-memory/)`;case`local`:return`Local (${bd(`...`)})`;default:return`None`}}function Cd(e,t){let n;switch(t){case`user`:n=`- Since this memory is user-scope, keep learnings general since they apply across all projects`;break;case`project`:n=`- Since this memory is project-scope and shared with your team via version control, tailor your memories to this project`;break;case`local`:n=`- Since this memory is local-scope (not checked into version control), tailor your memories to this project and machine`;break}let r=xd(e,t);dd(r);let i=process.env.CLAUDE_COWORK_MEMORY_EXTRA_GUIDELINES;return tde({displayName:`Persistent Agent Memory`,memoryDir:r,extraGuidelines:i&&i.trim().length>0?[n,i]:[n]})}var wd=n((()=>{Jt(),yd(),ra(),Vn(),Ir(),Ai()}));function Td(){let e=process.env.CLAUDE_CODE_ENVIRONMENT_KIND;return e===`byoc`||e===`anthropic_cloud`?e:null}var Ed=n((()=>{K()}));function ide(e){return qc(4).readUInt32BE(0)%e}function Dd(e){return e[ide(e.length)]}function ade(){return`${Dd(Od)}-${Dd(Ad)}-${Dd(kd)}`}var Od,kd,Ad,ode=n((()=>{Od=`abundant.ancient.bright.calm.cheerful.clever.cozy.curious.dapper.dazzling.deep.delightful.eager.elegant.enchanted.fancy.fluffy.gentle.gleaming.golden.graceful.happy.hidden.humble.jolly.joyful.keen.kind.lively.lovely.lucky.luminous.magical.majestic.mellow.merry.mighty.misty.noble.peaceful.playful.polished.precious.proud.quiet.quirky.radiant.rosy.serene.shiny.silly.sleepy.smooth.snazzy.snug.snuggly.soft.sparkling.spicy.splendid.sprightly.starry.steady.sunny.swift.tender.tidy.toasty.tranquil.twinkly.valiant.vast.velvet.vivid.warm.whimsical.wild.wise.witty.wondrous.zany.zesty.zippy.breezy.bubbly.buzzing.cheeky.cosmic.cozy.crispy.crystalline.cuddly.drifting.dreamy.effervescent.ethereal.fizzy.flickering.floating.floofy.fluttering.foamy.frolicking.fuzzy.giggly.glimmering.glistening.glittery.glowing.goofy.groovy.harmonic.hazy.humming.iridescent.jaunty.jazzy.jiggly.melodic.moonlit.mossy.nifty.peppy.prancy.purrfect.purring.quizzical.rippling.rustling.shimmering.shimmying.snappy.snoopy.squishy.swirling.ticklish.tingly.twinkling.velvety.wiggly.wobbly.woolly.zazzy.abstract.adaptive.agile.async.atomic.binary.cached.compiled.composed.compressed.concurrent.cryptic.curried.declarative.delegated.distributed.dynamic.eager.elegant.encapsulated.enumerated.eventual.expressive.federated.functional.generic.greedy.hashed.idempotent.immutable.imperative.indexed.inherited.iterative.lazy.lexical.linear.linked.logical.memoized.modular.mutable.nested.optimized.parallel.parsed.partitioned.piped.polymorphic.pure.reactive.recursive.refactored.reflective.replicated.resilient.robust.scalable.sequential.serialized.sharded.sorted.staged.stateful.stateless.streamed.structured.synchronous.synthetic.temporal.transient.typed.unified.validated.vectorized.virtual`.split(`.`),kd=`aurora.avalanche.blossom.breeze.brook.bubble.canyon.cascade.cloud.clover.comet.coral.cosmos.creek.crescent.crystal.dawn.dewdrop.dusk.eclipse.ember.feather.fern.firefly.flame.flurry.fog.forest.frost.galaxy.garden.glacier.glade.grove.harbor.horizon.island.lagoon.lake.leaf.lightning.meadow.meteor.mist.moon.moonbeam.mountain.nebula.nova.ocean.orbit.pebble.petal.pine.planet.pond.puddle.quasar.rain.rainbow.reef.ripple.river.shore.sky.snowflake.spark.spring.star.stardust.starlight.storm.stream.summit.sun.sunbeam.sunrise.sunset.thunder.tide.twilight.valley.volcano.waterfall.wave.willow.wind.alpaca.axolotl.badger.bear.beaver.bee.bird.bumblebee.bunny.cat.chipmunk.crab.crane.deer.dolphin.dove.dragon.dragonfly.duckling.eagle.elephant.falcon.finch.flamingo.fox.frog.giraffe.goose.hamster.hare.hedgehog.hippo.hummingbird.jellyfish.kitten.koala.ladybug.lark.lemur.llama.lobster.lynx.manatee.meerkat.moth.narwhal.newt.octopus.otter.owl.panda.parrot.peacock.pelican.penguin.phoenix.piglet.platypus.pony.porcupine.puffin.puppy.quail.quokka.rabbit.raccoon.raven.robin.salamander.seahorse.seal.sloth.snail.sparrow.sphinx.squid.squirrel.starfish.swan.tiger.toucan.turtle.unicorn.walrus.whale.wolf.wombat.wren.yeti.zebra.acorn.anchor.balloon.beacon.biscuit.blanket.bonbon.book.boot.cake.candle.candy.castle.charm.clock.cocoa.cookie.crayon.crown.cupcake.donut.dream.fairy.fiddle.flask.flute.fountain.gadget.gem.gizmo.globe.goblet.hammock.harp.haven.hearth.honey.journal.kazoo.kettle.key.kite.lantern.lemon.lighthouse.locket.lollipop.mango.map.marble.marshmallow.melody.mitten.mochi.muffin.music.nest.noodle.oasis.origami.pancake.parasol.peach.pearl.pebble.pie.pillow.pinwheel.pixel.pizza.plum.popcorn.pretzel.prism.pudding.pumpkin.puzzle.quiche.quill.quilt.riddle.rocket.rose.scone.scroll.shell.sketch.snowglobe.sonnet.sparkle.spindle.sprout.sundae.swing.taco.teacup.teapot.thimble.toast.token.tome.tower.treasure.treehouse.trinket.truffle.tulip.umbrella.waffle.wand.whisper.whistle.widget.wreath.zephyr.abelson.adleman.aho.allen.babbage.bachman.backus.barto.bengio.bentley.blum.boole.brooks.catmull.cerf.cherny.church.clarke.cocke.codd.conway.cook.corbato.cray.curry.dahl.diffie.dijkstra.dongarra.eich.emerson.engelbart.feigenbaum.floyd.gosling.graham.gray.hamming.hanrahan.hartmanis.hejlsberg.hellman.hennessy.hickey.hinton.hoare.hollerith.hopcroft.hopper.iverson.kahan.kahn.karp.kay.kernighan.knuth.kurzweil.lamport.lampson.lecun.lerdorf.liskov.lovelace.matsumoto.mccarthy.metcalfe.micali.milner.minsky.moler.moore.naur.neumann.newell.nygaard.papert.parnas.pascal.patterson.pearl.perlis.pike.pnueli.rabin.reddy.ritchie.rivest.rossum.russell.scott.sedgewick.shamir.shannon.sifakis.simon.stallman.stearns.steele.stonebraker.stroustrup.sutherland.sutton.tarjan.thacker.thompson.torvalds.turing.ullman.valiant.wadler.wall.wigderson.wilkes.wilkinson.wirth.wozniak.yao`.split(`.`),Ad=`baking.beaming.booping.bouncing.brewing.bubbling.chasing.churning.coalescing.conjuring.cooking.crafting.crunching.cuddling.dancing.dazzling.discovering.doodling.dreaming.drifting.enchanting.exploring.finding.floating.fluttering.foraging.forging.frolicking.gathering.giggling.gliding.greeting.growing.hatching.herding.honking.hopping.hugging.humming.imagining.inventing.jingling.juggling.jumping.kindling.knitting.launching.leaping.mapping.marinating.meandering.mixing.moseying.munching.napping.nibbling.noodling.orbiting.painting.percolating.petting.plotting.pondering.popping.prancing.purring.puzzling.questing.riding.roaming.rolling.sauteeing.scribbling.seeking.shimmying.singing.skipping.sleeping.snacking.sniffing.snuggling.soaring.sparking.spinning.splashing.sprouting.squishing.stargazing.stirring.strolling.swimming.swinging.tickling.tinkering.toasting.tumbling.twirling.waddling.wandering.watching.weaving.whistling.wibbling.wiggling.wishing.wobbling.wondering.yawning.zooming`.split(`.`)}));function jd(e){let t=e??jn(),n=ln().get(t);if(!n){let e=Rd();for(let t=0;t<Ld;t++){n=ade();let t=X(e,`${n}.md`);if(!q().existsSync(t))break}ite(t,n)}return n}function Md(e,t){ite(e,t)}function sde(){ln().clear()}function Nd(e){let t=jd(jn());return e?X(Rd(),`${t}-agent-${e}.md`):X(Rd(),`${t}.md`)}function Pd(e){let t=Nd(e);try{return q().readFileSync(t,{encoding:`utf-8`})}catch(e){return Qn(e)||J(e),null}}function Fd(e){return e.messages.find(e=>e.slug)?.slug}async function cde(e,t){let n=Fd(e);if(!n)return!1;Md(t??jn(),n);let r=X(Rd(),`${n}.md`);try{return await q().readFile(r,{encoding:`utf-8`}),!0}catch(t){if(!Qn(t))return J(t),!1;if(Td()===null)return!1;G(`Plan file missing during resume: ${r}. Attempting recovery.`);let n=dde(e.messages,`plan`),i=null;if(n&&n.content.length>0?(i=n.content,G(`Plan recovered from file snapshot, ${i.length} chars`,{level:`info`})):(i=ude(e),i&&G(`Plan recovered from message history, ${i.length} chars`,{level:`info`})),i)try{return await ll(r,i,{encoding:`utf-8`}),!0}catch(e){return J(e),!1}return G(`Plan file recovery failed: no file snapshot or plan content found in message history`),!1}}async function lde(e,t){let n=Fd(e);if(!n)return!1;let r=Rd(),i=X(r,`${n}.md`),a=X(r,`${jd(t)}.md`);try{return await Zc(i,a),!0}catch(e){return Qn(e)||J(e),!1}}function ude(e){for(let t=e.messages.length-1;t>=0;t--){let n=e.messages[t];if(n){if(n.type===`assistant`){let{content:e}=n.message;if(Array.isArray(e)){for(let t of e)if(t.type===`tool_use`&&t.name===`ExitPlanMode`){let e=t.input?.plan;if(typeof e==`string`&&e.length>0)return e}}}if(n.type===`user`){let e=n;if(typeof e.planContent==`string`&&e.planContent.length>0)return e.planContent}if(n.type===`attachment`){let e=n;if(e.attachment?.type===`plan_file_reference`){let t=e.attachment.planContent;if(typeof t==`string`&&t.length>0)return t}}}}return null}function dde(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];if(r?.type===`system`&&`subtype`in r&&r.subtype===`file_snapshot`&&`snapshotFiles`in r)return r.snapshotFiles.find(e=>e.key===t)}}async function Id(){if(Td()!==null)try{let e=[],t=Pd();if(t&&e.push({key:`plan`,path:Nd(),content:t}),e.length===0)return;let n={type:`system`,subtype:`file_snapshot`,content:`File snapshot`,level:`info`,isMeta:!0,timestamp:new Date().toISOString(),uuid:Jc(),snapshotFiles:e},{recordTranscript:r}=await import(`./sessionStorage-C_7gow_z.js`);await r([n])}catch(e){J(e)}}var Ld,Rd,zd=n((()=>{d(),Jt(),zs(),Vn(),K(),g(),qn(),Ed(),or(),Ga(),vi(),ode(),Ld=10,Rd=u(function(){let e=Vi().plansDirectory,t;if(e){let n=H(),r=Oc(n,e);!r.startsWith(n+kc)&&r!==n?(J(Error(`plansDirectory must be within project root: ${e}`)),t=X(m(),`plans`)):t=r}else t=X(m(),`plans`);try{q().mkdirSync(t)}catch(e){J(e)}return t})})),Bd,fde=n((()=>{Bd={type:`local-jsx`,name:`add-dir`,description:`添加新的工作目录`,argumentHint:`<path>`,load:()=>import(`./add-dir-CrUDs19x.js`)}})),Vd,pde=n((()=>{Vd={type:`local-jsx`,name:`btw`,description:`快速问一个旁路问题,不打断主对话`,immediate:!0,argumentHint:`<question>`,load:()=>import(`./btw-udbprVvu.js`)}})),Hd,mde=n((()=>{Hd={type:`local`,name:`clear`,description:`清空对话历史并释放上下文`,aliases:[`reset`,`new`],supportsNonInteractive:!1,load:()=>import(`./clear-B8ZtFPOK.js`)}})),Ud,hde=n((()=>{g(),Ud={type:`local`,name:`compact`,description:`清空对话历史但保留摘要在上下文中。可选:/compact [摘要生成的指示]`,isEnabled:()=>!h(process.env.DISABLE_COMPACT),supportsNonInteractive:!0,argumentHint:`<optional custom summarization instructions>`,load:()=>import(`./compact-izk6RKHQ.js`)}})),Wd,gde=n((()=>{Wd={aliases:[`settings`],type:`local-jsx`,name:`config`,description:`打开配置面板`,load:()=>import(`./config-CFqpXMFX.js`)}})),Gd,Kd,_de=n((()=>{Jt(),Gd={name:`context`,description:`以彩色网格可视化当前上下文占用`,isEnabled:()=>!qt(),type:`local-jsx`,load:()=>import(`./context-BbVm4SWK.js`)},Kd={type:`local`,name:`context`,supportsNonInteractive:!0,description:`显示当前上下文占用`,get isHidden(){return!qt()},isEnabled(){return qt()},load:()=>import(`./context-noninteractive-x0HAzWhc.js`)}})),qd,vde=n((()=>{qd={type:`local-jsx`,name:`diff`,description:`查看未提交的改动以及每一轮的 diff`,load:()=>import(`./diff-DdpHThJ7.js`)}})),Jd,yde=n((()=>{g(),Jd={name:`doctor`,description:`诊断并校验 Work Mate 的安装与设置`,isEnabled:()=>!h(process.env.DISABLE_DOCTOR_COMMAND),type:`local-jsx`,load:()=>import(`./doctor-D_kV_D_l.js`)}})),Yd,bde=n((()=>{Yd={type:`local-jsx`,name:`memory`,description:`编辑 Work Mate 记忆文件`,load:()=>import(`./memory-Qv-wGNQ5.js`)}})),Xd,xde=n((()=>{Xd={type:`local-jsx`,name:`mode`,description:`切换交互模式(default、gentle、sharp、workhorse、token-saver、super-ai)`,isEnabled:()=>!0,argumentHint:`<mode-slug>`,load:()=>import(`./mode-bFXPCR2P.js`)}})),Zd,Sde=n((()=>{Zd={type:`local-jsx`,name:`help`,description:`显示帮助与可用命令`,load:()=>import(`./help-DxanITNN.js`)}}));function Cde(e,t){let n=Fc(e,t);return n===``||!n.startsWith(`..`)&&!Lse(n)}function wde(e,t){let n=Ic(e),r=Ic(t);if(!Cde(n,r))return[n];let i=[],a=r;for(;i.push(a),a!==n;){let e=Ise(a);if(e===a)break;a=e}return i.reverse()}async function Qd(e,t){try{let n=(await q().readFile(e,{encoding:`utf-8`})).trim();return n?{path:e,relativePath:Xre(Fc(t,e))||Fse(e),content:n}:null}catch{return null}}function Tde(e){return e.length===0?null:e.map(e=>`## ${e.relativePath}\n${e.content}`).join(`
|
|
123
123
|
|
|
124
124
|
`)}function Ede(e){let t=e.slice(),n=null,r=0;for(let e=0;e<t.length;e++){let i=t[e].trim(),a=i.match(/^([`~])\1{2,}/);if(a){let o=a[1],s=a[0].length,c=i.slice(s);n===null?(n=o,r=s):n===o&&s>=r&&c.trim()===``&&(n=null,r=0),t[e]=``;continue}n!==null&&(t[e]=``)}return t}function Dde(e){let t=[],n=Ede(e.split(`
|
|
125
125
|
`)),r=e=>e.length-e.trimStart().length,i=(e,t)=>e.replace(t,``).trim().replace(/^["']|["']$/g,``);function a(e,t){let a=[],o=e;for(;o<n.length;){let e=n[o],s=e.trim(),c=r(e);if(!s){o+=1;continue}if(c<=t)break;if(!s.startsWith(`- name:`)){o+=1;continue}let l=c,u=i(s,`- name:`),d=``,f;for(o+=1;o<n.length;){let e=n[o],t=e.trim(),a=r(e);if(!t){o+=1;continue}if(a<=l)break;t.startsWith(`prompt:`)?d=i(t,`prompt:`):t.startsWith(`wait_for:`)&&(f=i(t,`wait_for:`)),o+=1}u&&d&&a.push({name:u,prompt:d,...f?{waitFor:f}:{}})}return{steps:a,nextIndex:o}}let o=n.findIndex(e=>e.trim()===`tasks:`);if(o===-1)return t;let s=r(n[o]),c=o+1;for(;c<n.length;){let e=n[c],o=e.trim(),l=r(e);if(!o){c+=1;continue}if(l<=s)break;if(!o.startsWith(`- name:`)){c+=1;continue}let u=l,d=i(o,`- name:`),f=``,p=``,m=[];for(c+=1;c<n.length;){let e=n[c],t=e.trim(),o=r(e);if(!t){c+=1;continue}if(o<=s||o===u&&t.startsWith(`- name:`)||o<=u)break;if(t.startsWith(`interval:`)){f=i(t,`interval:`),c+=1;continue}if(t.startsWith(`prompt:`)){p=i(t,`prompt:`),c+=1;continue}if(t===`steps:`){let e=a(c+1,o);m=e.steps,c=e.nextIndex;continue}c+=1}d&&f&&p&&t.push({name:d,interval:f,prompt:p,steps:m})}return t}function Ode(e){let t=e.trim().match(/^(\d+)\s*(ms|s|m|h|d)?$/i);if(!t)return null;let n=Number.parseInt(t[1],10);switch((t[2]??`m`).toLowerCase()){case`ms`:return n;case`s`:return n*1e3;case`m`:return n*6e4;case`h`:return n*60*6e4;case`d`:return n*24*60*6e4;default:return null}}function $d(e,t){return`${e}::${t.name}::${t.interval}::${t.prompt}`}function kde(e,t){let n=[];for(let r of e.heartbeatTasks){let i=Ode(r.interval);if(i==null)continue;let a=$d(e.rootDir,r),o=cf.get(a);o!==void 0&&t-o<i||n.push(r)}return n}function Ade(e,t,n){for(let r of t)cf.set($d(e.rootDir,r),n)}async function jde(e={}){let t=Ic(e.rootDir??en()),n=Ic(e.currentDir??H()),r=wde(t,n),[i,a]=await Promise.all([Promise.all(r.map(async e=>Qd(Pc(e,nf,af),t))),Qd(Pc(t,nf,of),t)]),o=i.filter(e=>e!==null);return{rootDir:t,currentDir:n,agentsFiles:o,agentsContent:Tde(o),heartbeatFile:a,heartbeatContent:a?.content??null,heartbeatTasks:a?Dde(a.content):[]}}async function Mde(e){let t=await ef(e);return tf(t),t.prompt}async function ef(e){let t=await jde({rootDir:e.rootDir,currentDir:e.currentDir}),n=e.nowMs??Date.now(),r=e.trigger===`proactive-tick`?kde(t,n):[],i=r.filter(e=>e.steps.length===0),a=[];if(t.agentsContent&&a.push(`Workspace authority from ${af}:\n${t.agentsContent}`),t.heartbeatContent&&a.push(`Workspace heartbeat guidance from ${of}:\n${t.heartbeatContent}`),i.length>0&&a.push([`Due ${of} tasks:`,...i.map(e=>`- ${e.name} (${e.interval}): ${e.prompt}`)].join(`
|
|
@@ -386,9 +386,9 @@ After writing the skill file(s), inform the user:
|
|
|
386
386
|
3. That they can edit the skills to customize them
|
|
387
387
|
4. That they can run /init-verifiers again to add more verifiers for other areas
|
|
388
388
|
5. That the verifier will offer to self-update if it detects its own instructions are outdated (wrong dev server command, changed ready signal, etc.)
|
|
389
|
-
`}]}}}));function Fde(e,t={}){let n=t.entryType||t.type;if(n===`both`&&(n=pf.FILE_DIR_TYPE),n&&(t.type=n),!e)throw Error(`readdirp: root argument is required. Usage: readdirp(root, options)`);if(typeof e!=`string`)throw TypeError(`readdirp: root argument must be a string. Usage: readdirp(root, options)`);if(n&&!_f.includes(n))throw Error(`readdirp: Invalid type passed. Use one of ${_f.join(`, `)}`);return t.root=e,new wf(t)}var pf,mf,hf,gf,_f,vf,yf,bf,xf,Sf,Cf,wf,Ide=n((()=>{b(),pf={FILE_TYPE:`files`,DIR_TYPE:`directories`,FILE_DIR_TYPE:`files_directories`,EVERYTHING_TYPE:`all`},mf={root:`.`,fileFilter:e=>!0,directoryFilter:e=>!0,type:pf.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096},Object.freeze(mf),hf=`READDIRP_RECURSIVE_ERROR`,gf=new Set([`ENOENT`,`EPERM`,`EACCES`,`ELOOP`,hf]),_f=[pf.DIR_TYPE,pf.EVERYTHING_TYPE,pf.FILE_DIR_TYPE,pf.FILE_TYPE],vf=new Set([pf.DIR_TYPE,pf.EVERYTHING_TYPE,pf.FILE_DIR_TYPE]),yf=new Set([pf.EVERYTHING_TYPE,pf.FILE_DIR_TYPE,pf.FILE_TYPE]),bf=e=>gf.has(e.code),xf=process.platform===`win32`,Sf=e=>!0,Cf=e=>{if(e===void 0)return Sf;if(typeof e==`function`)return e;if(typeof e==`string`){let t=e.trim();return e=>e.basename===t}if(Array.isArray(e)){let t=e.map(e=>e.trim());return e=>t.some(t=>e.basename===t)}return Sf},wf=class extends Lce{constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark}),x(this,`parents`,void 0),x(this,`reading`,void 0),x(this,`parent`,void 0),x(this,`_stat`,void 0),x(this,`_maxDepth`,void 0),x(this,`_wantsDir`,void 0),x(this,`_wantsFile`,void 0),x(this,`_wantsEverything`,void 0),x(this,`_root`,void 0),x(this,`_isDirent`,void 0),x(this,`_statsProp`,void 0),x(this,`_rdOptions`,void 0),x(this,`_fileFilter`,void 0),x(this,`_directoryFilter`,void 0);let t={...mf,...e},{root:n,type:r}=t;this._fileFilter=Cf(t.fileFilter),this._directoryFilter=Cf(t.directoryFilter);let i=t.lstat?ml:vl;xf?this._stat=e=>i(e,{bigint:!0}):this._stat=i,this._maxDepth=t.depth!=null&&Number.isSafeInteger(t.depth)?t.depth:mf.depth,this._wantsDir=r?vf.has(r):!1,this._wantsFile=r?yf.has(r):!1,this._wantsEverything=r===pf.EVERYTHING_TYPE,this._root=Ic(n),this._isDirent=!t.alwaysStat,this._statsProp=this._isDirent?`dirent`:`stats`,this._rdOptions={encoding:`utf8`,withFileTypes:this._isDirent},this.parents=[this._exploreDir(n,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let t=this.parent,n=t&&t.files;if(n&&n.length>0){let{path:r,depth:i}=t,a=n.splice(0,e).map(e=>this._formatEntry(e,r)),o=await Promise.all(a);for(let t of o){if(!t)continue;if(this.destroyed)return;let n=await this._getEntryType(t);n===`directory`&&this._directoryFilter(t)?(i<=this._maxDepth&&this.parents.push(this._exploreDir(t.fullPath,i+1)),this._wantsDir&&(this.push(t),e--)):(n===`file`||this._includeAsFile(t))&&this._fileFilter(t)&&this._wantsFile&&(this.push(t),e--)}}else{let e=this.parents.pop();if(!e){this.push(null);break}if(this.parent=await e,this.destroyed)return}}}catch(e){this.destroy(e)}finally{this.reading=!1}}}async _exploreDir(e,t){let n;try{n=await gl(e,this._rdOptions)}catch(e){this._onError(e)}return{files:n,depth:t,path:e}}async _formatEntry(e,t){let n,r=this._isDirent?e.name:e;try{let i=Ic(Pc(t,r));n={path:Fc(this._root,i),fullPath:i,basename:r},n[this._statsProp]=this._isDirent?e:await this._stat(i)}catch(e){this._onError(e);return}return n}_onError(e){bf(e)&&!this.destroyed?this.emit(`warn`,e):this.destroy(e)}async _getEntryType(e){if(!e&&this._statsProp in e)return``;let t=e[this._statsProp];if(t.isFile())return`file`;if(t.isDirectory())return`directory`;if(t&&t.isSymbolicLink()){let t=e.fullPath;try{let e=await _l(t),n=await ml(e);if(n.isFile())return`file`;if(n.isDirectory()){let n=e.length;if(t.startsWith(e)&&t.substr(n,1)===Rse){let n=Error(`Circular symlink detected: "${t}" points to "${e}"`);return n.code=hf,this._onError(n)}return`directory`}}catch(e){return this._onError(e),``}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}}}));function Tf(e,t,n,r,i){let a=(t,r)=>{n(e),i(t,r,{watchedPath:e}),r&&e!==r&&Zf(Mc.resolve(e,r),zf,Mc.join(e,r))};try{return hce(e,{persistent:t.persistent},a)}catch(e){r(e);return}}var Ef,Df,Of,kf,Af,jf,Mf,Nf,Pf,Ff,If,Lf,Rf,zf,Bf,Vf,Hf,Uf,Wf,Gf,Kf,qf,Jf,Yf,Xf,Zf,Qf,$f,ep,tp,Lde=n((()=>{b(),Ef=`data`,Df=`close`,Of=()=>{},kf=process.platform,Af=kf===`win32`,jf=kf===`darwin`,Mf=kf===`linux`,Nf=kf===`freebsd`,Pf=yce()===`OS400`,Ff={ALL:`all`,READY:`ready`,ADD:`add`,CHANGE:`change`,ADD_DIR:`addDir`,UNLINK:`unlink`,UNLINK_DIR:`unlinkDir`,RAW:`raw`,ERROR:`error`},If=Ff,Lf=`watch`,Rf={lstat:ml,stat:vl},zf=`listeners`,Bf=`errHandlers`,Vf=`rawEmitters`,Hf=[zf,Bf,Vf],Uf=new Set(`3dm.3ds.3g2.3gp.7z.a.aac.adp.afdesign.afphoto.afpub.ai.aif.aiff.alz.ape.apk.appimage.ar.arj.asf.au.avi.bak.baml.bh.bin.bk.bmp.btif.bz2.bzip2.cab.caf.cgm.class.cmx.cpio.cr2.cur.dat.dcm.deb.dex.djvu.dll.dmg.dng.doc.docm.docx.dot.dotm.dra.DS_Store.dsk.dts.dtshd.dvb.dwg.dxf.ecelp4800.ecelp7470.ecelp9600.egg.eol.eot.epub.exe.f4v.fbs.fh.fla.flac.flatpak.fli.flv.fpx.fst.fvt.g3.gh.gif.graffle.gz.gzip.h261.h263.h264.icns.ico.ief.img.ipa.iso.jar.jpeg.jpg.jpgv.jpm.jxr.key.ktx.lha.lib.lvp.lz.lzh.lzma.lzo.m3u.m4a.m4v.mar.mdi.mht.mid.midi.mj2.mka.mkv.mmr.mng.mobi.mov.movie.mp3.mp4.mp4a.mpeg.mpg.mpga.mxu.nef.npx.numbers.nupkg.o.odp.ods.odt.oga.ogg.ogv.otf.ott.pages.pbm.pcx.pdb.pdf.pea.pgm.pic.png.pnm.pot.potm.potx.ppa.ppam.ppm.pps.ppsm.ppsx.ppt.pptm.pptx.psd.pya.pyc.pyo.pyv.qt.rar.ras.raw.resources.rgb.rip.rlc.rmf.rmvb.rpm.rtf.rz.s3m.s7z.scpt.sgi.shar.snap.sil.sketch.slk.smv.snk.so.stl.suo.sub.swf.tar.tbz.tbz2.tga.tgz.thmx.tif.tiff.tlz.ttc.ttf.txz.udf.uvh.uvi.uvm.uvp.uvs.uvu.viv.vob.war.wav.wax.wbmp.wdp.weba.webm.webp.whl.wim.wm.wma.wmv.wmx.woff.woff2.wrm.wvx.xbm.xif.xla.xlam.xls.xlsb.xlsm.xlsx.xlt.xltm.xltx.xm.xmind.xpi.xpm.xwd.xz.z.zip.zipx`.split(`.`)),Wf=e=>Uf.has(Mc.extname(e).slice(1).toLowerCase()),Gf=(e,t)=>{e instanceof Set?e.forEach(t):t(e)},Kf=(e,t,n)=>{let r=e[t];r instanceof Set||(e[t]=r=new Set([r])),r.add(n)},qf=e=>t=>{let n=e[t];n instanceof Set?n.clear():delete e[t]},Jf=(e,t,n)=>{let r=e[t];r instanceof Set?r.delete(n):r===n&&delete e[t]},Yf=e=>e instanceof Set?e.size===0:!e,Xf=new Map,Zf=(e,t,n,r,i)=>{let a=Xf.get(e);a&&Gf(a[t],e=>{e(n,r,i)})},Qf=(e,t,n,r)=>{let{listener:i,errHandler:a,rawEmitter:o}=r,s=Xf.get(t),c;if(!n.persistent)return c=Tf(e,n,i,a,o),c?c.close.bind(c):void 0;if(s)Kf(s,zf,i),Kf(s,Bf,a),Kf(s,Vf,o);else{if(c=Tf(e,n,Zf.bind(null,t,zf),a,Zf.bind(null,t,Vf)),!c)return;c.on(If.ERROR,async n=>{let r=Zf.bind(null,t,Bf);if(s&&(s.watcherUnusable=!0),Af&&n.code===`EPERM`)try{await(await zce(e,`r`)).close(),r(n)}catch{}else r(n)}),s={listeners:i,errHandlers:a,rawEmitters:o,watcher:c},Xf.set(t,s)}return()=>{Jf(s,zf,i),Jf(s,Bf,a),Jf(s,Vf,o),Yf(s.listeners)&&(s.watcher.close(),Xf.delete(t),Hf.forEach(qf(s)),s.watcher=void 0,Object.freeze(s))}},$f=new Map,ep=(e,t,n,r)=>{let{listener:i,rawEmitter:a}=r,o=$f.get(t),s=o&&o.options;return s&&(s.persistent<n.persistent||s.interval>n.interval)&&(mce(t),o=void 0),o?(Kf(o,zf,i),Kf(o,Vf,a)):(o={listeners:i,rawEmitters:a,options:n,watcher:gce(t,n,(n,r)=>{Gf(o.rawEmitters,e=>{e(If.CHANGE,t,{curr:n,prev:r})});let i=n.mtimeMs;(n.size!==r.size||i>r.mtimeMs||i===0)&&Gf(o.listeners,t=>t(e,n))})},$f.set(t,o)),()=>{Jf(o,zf,i),Jf(o,Vf,a),Yf(o.listeners)&&($f.delete(t),mce(t),o.options=o.watcher=void 0,Object.freeze(o))}},tp=class{constructor(e){x(this,`fsw`,void 0),x(this,`_boundHandleError`,void 0),this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let n=this.fsw.options,r=Mc.dirname(e),i=Mc.basename(e);this.fsw._getWatchedDir(r).add(i);let a=Mc.resolve(e),o={persistent:n.persistent};t||(t=Of);let s;return n.usePolling?(o.interval=n.interval!==n.binaryInterval&&Wf(i)?n.binaryInterval:n.interval,s=ep(e,a,o,{listener:t,rawEmitter:this.fsw._emitRaw})):s=Qf(e,a,o,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw}),s}_handleFile(e,t,n){if(this.fsw.closed)return;let r=Mc.dirname(e),i=Mc.basename(e),a=this.fsw._getWatchedDir(r),o=t;if(a.has(i))return;let s=async(t,n)=>{if(this.fsw._throttle(Lf,e,5)){if(!n||n.mtimeMs===0)try{let n=await vl(e);if(this.fsw.closed)return;let r=n.atimeMs,i=n.mtimeMs;if((!r||r<=i||i!==o.mtimeMs)&&this.fsw._emit(If.CHANGE,e,n),(jf||Mf||Nf)&&o.ino!==n.ino){this.fsw._closeFile(t),o=n;let r=this._watchWithNodeFs(e,s);r&&this.fsw._addPathCloser(t,r)}else o=n}catch{this.fsw._remove(r,i)}else if(a.has(i)){let t=n.atimeMs,r=n.mtimeMs;(!t||t<=r||r!==o.mtimeMs)&&this.fsw._emit(If.CHANGE,e,n),o=n}}},c=this._watchWithNodeFs(e,s);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(If.ADD,e,0))return;this.fsw._emit(If.ADD,e,t)}return c}async _handleSymlink(e,t,n,r){if(this.fsw.closed)return;let i=e.fullPath,a=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let t;try{t=await _l(n)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(r)?this.fsw._symlinkPaths.get(i)!==t&&(this.fsw._symlinkPaths.set(i,t),this.fsw._emit(If.CHANGE,n,e.stats)):(a.add(r),this.fsw._symlinkPaths.set(i,t),this.fsw._emit(If.ADD,n,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(e,t,n,r,i,a,o){e=Mc.join(e,``);let s=r?`${e}:${r}`:e;if(o=this.fsw._throttle(`readdir`,s,1e3),!o)return;let c=this.fsw._getWatchedDir(n.path),l=new Set,u=this.fsw._readdirp(e,{fileFilter:e=>n.filterPath(e),directoryFilter:e=>n.filterDir(e)});if(u)return u.on(Ef,async o=>{if(this.fsw.closed){u=void 0;return}let s=o.path,d=Mc.join(e,s);if(l.add(s),!(o.stats.isSymbolicLink()&&await this._handleSymlink(o,e,d,s))){if(this.fsw.closed){u=void 0;return}(s===r||!r&&!c.has(s))&&(this.fsw._incrReadyCount(),d=Mc.join(i,Mc.relative(i,d)),this._addToNodeFs(d,t,n,a+1))}}).on(If.ERROR,this._boundHandleError),new Promise((t,s)=>{if(!u)return s();u.once(`end`,()=>{if(this.fsw.closed){u=void 0;return}let s=o?o.clear():!1;t(void 0),c.getChildren().filter(t=>t!==e&&!l.has(t)).forEach(t=>{this.fsw._remove(e,t)}),u=void 0,s&&this._handleRead(e,!1,n,r,i,a,o)})})}async _handleDir(e,t,n,r,i,a,o){let s=this.fsw._getWatchedDir(Mc.dirname(e)),c=s.has(Mc.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!i&&!c&&this.fsw._emit(If.ADD_DIR,e,t),s.add(Mc.basename(e)),this.fsw._getWatchedDir(e);let l,u=this.fsw.options.depth;if((u==null||r<=u)&&!this.fsw._symlinkPaths.has(o)){if(!i&&(await this._handleRead(e,n,a,i,e,r,void 0),this.fsw.closed))return;l=this._watchWithNodeFs(e,(t,n)=>{n&&n.mtimeMs===0||this._handleRead(t,!1,a,i,e,r,void 0)})}return l}async _addToNodeFs(e,t,n,r,i){let a=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return a(),!1;let o=this.fsw._getWatchHelpers(e);n&&(o.filterPath=e=>n.filterPath(e),o.filterDir=e=>n.filterDir(e));try{let n=await Rf[o.statMethod](o.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(o.watchPath,n))return a(),!1;let s=this.fsw.options.followSymlinks,c;if(n.isDirectory()){let a=Mc.resolve(e),l=s?await _l(e):e;if(this.fsw.closed||(c=await this._handleDir(o.watchPath,n,t,r,i,o,l),this.fsw.closed))return;a!==l&&l!==void 0&&this.fsw._symlinkPaths.set(a,l)}else if(n.isSymbolicLink()){let i=s?await _l(e):e;if(this.fsw.closed)return;let a=Mc.dirname(o.watchPath);if(this.fsw._getWatchedDir(a).add(o.watchPath),this.fsw._emit(If.ADD,o.watchPath,n),c=await this._handleDir(a,n,t,r,e,o,i),this.fsw.closed)return;i!==void 0&&this.fsw._symlinkPaths.set(Mc.resolve(e),i)}else c=this._handleFile(o.watchPath,n,t);return a(),c&&this.fsw._addPathCloser(e,c),!1}catch(t){if(this.fsw._handleError(t))return a(),e}}}}));function np(e){return Array.isArray(e)?e:[e]}function Rde(e){return typeof e==`function`?e:typeof e==`string`?t=>e===t:e instanceof RegExp?t=>e.test(t):typeof e==`object`&&e?t=>{if(e.path===t)return!0;if(e.recursive){let n=Mc.relative(e.path,t);return n?!n.startsWith(`..`)&&!Mc.isAbsolute(n):!1}return!1}:()=>!1}function zde(e){if(typeof e!=`string`)throw Error(`string expected`);e=Mc.normalize(e),e=e.replace(/\\/g,`/`);let t=!1;return e.startsWith(`//`)&&(t=!0),e=e.replace(up,`/`),t&&(e=`/`+e),e}function rp(e,t,n){let r=zde(t);for(let t=0;t<e.length;t++){let i=e[t];if(i(r,n))return!0}return!1}function Bde(e,t){if(e==null)throw TypeError(`anymatch: specify first argument`);let n=np(e).map(e=>Rde(e));return t==null?(e,t)=>rp(n,e,t):rp(n,t)}function Vde(e,t={}){let n=new wp(t);return n.add(e),n}var ip,ap,op,sp,cp,lp,up,dp,fp,pp,mp,hp,gp,_p,vp,yp,bp,xp,Sp,Cp,wp,Tp,Ep=n((()=>{Ide(),Lde(),b(),ip=`/`,ap=`//`,op=`.`,sp=`..`,cp=`string`,lp=/\\/g,up=/\/\//g,dp=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,fp=/^\.[/\\]/,pp=e=>typeof e==`object`&&!!e&&!(e instanceof RegExp),mp=e=>{let t=np(e).flat();if(!t.every(e=>typeof e===cp))throw TypeError(`Non-string provided as watch path: ${t}`);return t.map(gp)},hp=e=>{let t=e.replace(lp,ip),n=!1;return t.startsWith(ap)&&(n=!0),t=t.replace(up,ip),n&&(t=ip+t),t},gp=e=>hp(Mc.normalize(hp(e))),_p=(e=``)=>t=>typeof t==`string`?gp(Mc.isAbsolute(t)?t:Mc.join(e,t)):t,vp=(e,t)=>Mc.isAbsolute(e)?e:Mc.join(t,e),yp=Object.freeze(new Set),bp=class{constructor(e,t){x(this,`path`,void 0),x(this,`_removeWatcher`,void 0),x(this,`items`,void 0),this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==op&&e!==sp&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let n=this.path;try{await gl(n)}catch{this._removeWatcher&&this._removeWatcher(Mc.dirname(n),Mc.basename(n))}}has(e){let{items:t}=this;if(t)return t.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path=``,this._removeWatcher=Of,this.items=yp,Object.freeze(this)}},xp=`stat`,Sp=`lstat`,Cp=class{constructor(e,t,n){x(this,`fsw`,void 0),x(this,`path`,void 0),x(this,`watchPath`,void 0),x(this,`fullWatchPath`,void 0),x(this,`dirParts`,void 0),x(this,`followSymlinks`,void 0),x(this,`statMethod`,void 0),this.fsw=n;let r=e;this.path=e=e.replace(fp,``),this.watchPath=r,this.fullWatchPath=Mc.resolve(r),this.dirParts=[],this.dirParts.forEach(e=>{e.length>1&&e.pop()}),this.followSymlinks=t,this.statMethod=t?xp:Sp}entryPath(e){return Mc.join(this.watchPath,Mc.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let n=this.entryPath(e);return this.fsw._isntIgnored(n,t)&&this.fsw._hasReadPermissions(t)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},wp=class extends Pce{constructor(e={}){super(),x(this,`closed`,void 0),x(this,`options`,void 0),x(this,`_closers`,void 0),x(this,`_ignoredPaths`,void 0),x(this,`_throttled`,void 0),x(this,`_streams`,void 0),x(this,`_symlinkPaths`,void 0),x(this,`_watched`,void 0),x(this,`_pendingWrites`,void 0),x(this,`_pendingUnlinks`,void 0),x(this,`_readyCount`,void 0),x(this,`_emitReady`,void 0),x(this,`_closePromise`,void 0),x(this,`_userIgnored`,void 0),x(this,`_readyEmitted`,void 0),x(this,`_emitRaw`,void 0),x(this,`_boundRemove`,void 0),x(this,`_nodeFsHandler`,void 0),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let t=e.awaitWriteFinish,n={stabilityThreshold:2e3,pollInterval:100},r={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?np(e.ignored):np([]),awaitWriteFinish:t===!0?n:typeof t==`object`&&{...n,...t}};Pf&&(r.usePolling=!0),r.atomic===void 0&&(r.atomic=!r.usePolling);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let e=i.toLowerCase();e===`false`||e===`0`?r.usePolling=!1:e===`true`||e===`1`?r.usePolling=!0:r.usePolling=!!e}let a=process.env.CHOKIDAR_INTERVAL;a&&(r.interval=Number.parseInt(a,10));let o=0;this._emitReady=()=>{o++,o>=this._readyCount&&(this._emitReady=Of,this._readyEmitted=!0,process.nextTick(()=>this.emit(Ff.READY)))},this._emitRaw=(...e)=>this.emit(Ff.RAW,...e),this._boundRemove=this._remove.bind(this),this.options=r,this._nodeFsHandler=new tp(this),Object.freeze(r)}_addIgnoredPath(e){if(pp(e)){for(let t of this._ignoredPaths)if(pp(t)&&t.path===e.path&&t.recursive===e.recursive)return}this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),typeof e==`string`)for(let t of this._ignoredPaths)pp(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,n){let{cwd:r}=this.options;this.closed=!1,this._closePromise=void 0;let i=mp(e);return r&&(i=i.map(e=>vp(e,r))),i.forEach(e=>{this._removeIgnoredPath(e)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=i.length,Promise.all(i.map(async e=>{let r=await this._nodeFsHandler._addToNodeFs(e,!n,void 0,0,t);return r&&this._emitReady(),r})).then(e=>{this.closed||e.forEach(e=>{e&&this.add(Mc.dirname(e),Mc.basename(t||e))})}),this}unwatch(e){if(this.closed)return this;let t=mp(e),{cwd:n}=this.options;return t.forEach(e=>{!Mc.isAbsolute(e)&&!this._closers.has(e)&&(n&&(e=Mc.join(n,e)),e=Mc.resolve(e)),this._closePath(e),this._addIgnoredPath(e),this._watched.has(e)&&this._addIgnoredPath({path:e,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(t=>t.forEach(t=>{let n=t();n instanceof Promise&&e.push(n)})),this._streams.forEach(e=>e.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(e=>e.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>void 0):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((t,n)=>{let r=(this.options.cwd?Mc.relative(this.options.cwd,n):n)||op;e[r]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==Ff.ERROR&&this.emit(Ff.ALL,e,...t)}async _emit(e,t,n){if(this.closed)return;let r=this.options;Af&&(t=Mc.normalize(t)),r.cwd&&(t=Mc.relative(r.cwd,t));let i=[t];n!=null&&i.push(n);let a=r.awaitWriteFinish,o;if(a&&(o=this._pendingWrites.get(t)))return o.lastChange=new Date,this;if(r.atomic){if(e===Ff.UNLINK)return this._pendingUnlinks.set(t,[e,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((e,t)=>{this.emit(...e),this.emit(Ff.ALL,...e),this._pendingUnlinks.delete(t)})},typeof r.atomic==`number`?r.atomic:100),this;e===Ff.ADD&&this._pendingUnlinks.has(t)&&(e=Ff.CHANGE,this._pendingUnlinks.delete(t))}if(a&&(e===Ff.ADD||e===Ff.CHANGE)&&this._readyEmitted)return this._awaitWriteFinish(t,a.stabilityThreshold,e,(t,n)=>{t?(e=Ff.ERROR,i[0]=t,this.emitWithAll(e,i)):n&&(i.length>1?i[1]=n:i.push(n),this.emitWithAll(e,i))}),this;if(e===Ff.CHANGE&&!this._throttle(Ff.CHANGE,t,50))return this;if(r.alwaysStat&&n===void 0&&(e===Ff.ADD||e===Ff.ADD_DIR||e===Ff.CHANGE)){let e=r.cwd?Mc.join(r.cwd,t):t,n;try{n=await vl(e)}catch{}if(!n||this.closed)return;i.push(n)}return this.emitWithAll(e,i),this}_handleError(e){let t=e&&e.code;return e&&t!==`ENOENT`&&t!==`ENOTDIR`&&(!this.options.ignorePermissionErrors||t!==`EPERM`&&t!==`EACCES`)&&this.emit(Ff.ERROR,e),e||this.closed}_throttle(e,t,n){this._throttled.has(e)||this._throttled.set(e,new Map);let r=this._throttled.get(e);if(!r)throw Error(`invalid throttle`);let i=r.get(t);if(i)return i.count++,!1;let a,o=()=>{let e=r.get(t),n=e?e.count:0;return r.delete(t),clearTimeout(a),e&&clearTimeout(e.timeoutObject),n};a=setTimeout(o,n);let s={timeoutObject:a,clear:o,count:0};return r.set(t,s),s}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,n,r){let i=this.options.awaitWriteFinish;if(typeof i!=`object`)return;let a=i.pollInterval,o,s=e;this.options.cwd&&!Mc.isAbsolute(e)&&(s=Mc.join(this.options.cwd,e));let c=new Date,l=this._pendingWrites;function u(n){dce(s,(i,s)=>{if(i||!l.has(e)){i&&i.code!==`ENOENT`&&r(i);return}let c=Number(new Date);n&&s.size!==n.size&&(l.get(e).lastChange=c),c-l.get(e).lastChange>=t?(l.delete(e),r(void 0,s)):o=setTimeout(u,a,s)})}l.has(e)||(l.set(e,{lastChange:c,cancelWait:()=>(l.delete(e),clearTimeout(o),n)}),o=setTimeout(u,a))}_isIgnored(e,t){if(this.options.atomic&&dp.test(e))return!0;if(!this._userIgnored){let{cwd:e}=this.options,t=(this.options.ignored||[]).map(_p(e)),n=[...[...this._ignoredPaths].map(_p(e)),...t];this._userIgnored=Bde(n,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new Cp(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=Mc.resolve(e);return this._watched.has(t)||this._watched.set(t,new bp(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,n){let r=Mc.join(e,t),i=Mc.resolve(r);if(n=n??(this._watched.has(r)||this._watched.has(i)),!this._throttle(`remove`,r,100))return;!n&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(r).getChildren().forEach(e=>this._remove(r,e));let a=this._getWatchedDir(e),o=a.has(t);a.remove(t),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let s=r;if(this.options.cwd&&(s=Mc.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(s)&&this._pendingWrites.get(s).cancelWait()===Ff.ADD)return;this._watched.delete(r),this._watched.delete(i);let c=n?Ff.UNLINK_DIR:Ff.UNLINK;o&&!this._isIgnored(r)&&this._emit(c,r),this._closePath(r)}_closePath(e){this._closeFile(e);let t=Mc.dirname(e);this._getWatchedDir(t).remove(Mc.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(e=>e()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let n=this._closers.get(e);n||(n=[],this._closers.set(e,n)),n.push(t)}_readdirp(e,t){if(this.closed)return;let n=Fde(e,{type:Ff.ALL,alwaysStat:!0,lstat:!0,...t,depth:0});return this._streams.add(n),n.once(Df,()=>{n=void 0}),n.once(`end`,()=>{n&&(this._streams.delete(n),n=void 0)}),n}},Tp={watch:Vde,FSWatcher:wp}}));function Dp(){return kp||(kp=ue()),kp}function Hde(e,t){return typeof Bun<`u`?Bun.semver.order(e,t)===1:Dp().gt(e,t,{loose:!0})}function Ude(e,t){return typeof Bun<`u`?Bun.semver.order(e,t)>=0:Dp().gte(e,t,{loose:!0})}function Wde(e,t){return typeof Bun<`u`?Bun.semver.order(e,t)===-1:Dp().lt(e,t,{loose:!0})}function Op(e,t){return typeof Bun<`u`?Bun.semver.satisfies(e,t):Dp().satisfies(e,t,{loose:!0})}var kp,Ap=n((()=>{})),jp,Mp,Np,Pp=n((()=>{Ap(),Qa(),ao(),jp=io()===`windows`?`alt+v`:`ctrl+v`,Mp=io()!==`windows`||(Cie()?Op(process.versions.bun,`>=1.2.23`):Op(process.versions.node,`>=22.17.0 <23.0.0 || >=24.2.0`))?`shift+tab`:`meta+m`,Np=[{context:`Global`,bindings:{"ctrl+c":`app:interrupt`,"ctrl+d":`app:exit`,"ctrl+l":`app:redraw`,"ctrl+t":`app:toggleTodos`,"ctrl+o":`app:toggleTranscript`,"ctrl+shift+o":`app:toggleTeammatePreview`,"ctrl+r":`history:search`}},{context:`Chat`,bindings:{escape:`chat:cancel`,"ctrl+x ctrl+k":`chat:killAgents`,[Mp]:`chat:cycleMode`,"meta+p":`chat:modelPicker`,"meta+o":`chat:fastMode`,"meta+t":`chat:thinkingToggle`,enter:`chat:submit`,up:`history:previous`,down:`history:next`,"ctrl+_":`chat:undo`,"ctrl+shift+-":`chat:undo`,"ctrl+x ctrl+e":`chat:externalEditor`,"ctrl+g":`chat:externalEditor`,"ctrl+s":`chat:stash`,[jp]:`chat:imagePaste`}},{context:`Autocomplete`,bindings:{tab:`autocomplete:accept`,escape:`autocomplete:dismiss`,up:`autocomplete:previous`,down:`autocomplete:next`}},{context:`Settings`,bindings:{escape:`confirm:no`,up:`select:previous`,down:`select:next`,k:`select:previous`,j:`select:next`,"ctrl+p":`select:previous`,"ctrl+n":`select:next`,left:`select:previousValue`,right:`select:nextValue`,space:`select:accept`,enter:`settings:close`,"/":`settings:search`,r:`settings:retry`}},{context:`Confirmation`,bindings:{enter:`confirm:yes`,escape:`confirm:no`,up:`confirm:previous`,down:`confirm:next`,tab:`confirm:nextField`,space:`confirm:toggle`,"shift+tab":`confirm:cycleMode`,"ctrl+e":`confirm:toggleExplanation`,"ctrl+d":`permission:toggleDebug`}},{context:`FormField`,bindings:{tab:`tabs:next`,"shift+tab":`tabs:previous`,up:`tabs:previous`,down:`tabs:next`}},{context:`Tabs`,bindings:{tab:`tabs:next`,"shift+tab":`tabs:previous`,right:`tabs:next`,left:`tabs:previous`}},{context:`Transcript`,bindings:{"ctrl+e":`transcript:toggleShowAll`,"ctrl+c":`transcript:exit`,escape:`transcript:exit`,q:`transcript:exit`}},{context:`HistorySearch`,bindings:{"ctrl+r":`historySearch:next`,escape:`historySearch:accept`,tab:`historySearch:accept`,"ctrl+c":`historySearch:cancel`,enter:`historySearch:execute`}},{context:`Task`,bindings:{"ctrl+b":`task:background`}},{context:`ThemePicker`,bindings:{"ctrl+t":`theme:toggleSyntaxHighlighting`}},{context:`Scroll`,bindings:{pageup:`scroll:pageUp`,pagedown:`scroll:pageDown`,wheelup:`scroll:lineUp`,wheeldown:`scroll:lineDown`,"ctrl+home":`scroll:top`,"ctrl+end":`scroll:bottom`,"ctrl+shift+c":`selection:copy`,"cmd+c":`selection:copy`}},{context:`Help`,bindings:{escape:`help:dismiss`}},{context:`Attachments`,bindings:{right:`attachments:next`,left:`attachments:previous`,backspace:`attachments:remove`,delete:`attachments:remove`,down:`attachments:exit`,escape:`attachments:exit`}},{context:`Footer`,bindings:{up:`footer:up`,"ctrl+p":`footer:up`,down:`footer:down`,"ctrl+n":`footer:down`,right:`footer:next`,left:`footer:previous`,enter:`footer:openSelected`,escape:`footer:clearSelection`}},{context:`MessageSelector`,bindings:{up:`messageSelector:up`,down:`messageSelector:down`,k:`messageSelector:up`,j:`messageSelector:down`,"ctrl+p":`messageSelector:up`,"ctrl+n":`messageSelector:down`,"ctrl+up":`messageSelector:top`,"shift+up":`messageSelector:top`,"meta+up":`messageSelector:top`,"shift+k":`messageSelector:top`,"ctrl+down":`messageSelector:bottom`,"shift+down":`messageSelector:bottom`,"meta+down":`messageSelector:bottom`,"shift+j":`messageSelector:bottom`,enter:`messageSelector:select`}},{context:`DiffDialog`,bindings:{escape:`diff:dismiss`,left:`diff:previousSource`,right:`diff:nextSource`,up:`diff:previousFile`,down:`diff:nextFile`,enter:`diff:viewDetails`}},{context:`ModelPicker`,bindings:{space:`modelPicker:toggle1M`}},{context:`Select`,bindings:{up:`select:previous`,down:`select:next`,j:`select:next`,k:`select:previous`,"ctrl+n":`select:next`,"ctrl+p":`select:previous`,enter:`select:accept`,escape:`select:cancel`}},{context:`Plugin`,bindings:{space:`plugin:toggle`,i:`plugin:install`}}]})),Fp=n((()=>{ct()}));function Gde(){let e=io(),t=[...Lp,...Rp];return e===`macos`&&t.push(...zp),t}function Ip(e){return e.trim().split(/\s+/).map(Kde).join(` `)}function Kde(e){let t=e.split(`+`),n=[],r=``;for(let e of t){let t=e.trim().toLowerCase();[`ctrl`,`control`,`alt`,`opt`,`option`,`meta`,`cmd`,`command`,`shift`].includes(t)?t===`control`?n.push(`ctrl`):t===`option`||t===`opt`?n.push(`alt`):t===`command`||t===`cmd`?n.push(`cmd`):n.push(t):r=t}return n.sort(),[...n,r].join(`+`)}var Lp,Rp,zp,Bp=n((()=>{ao(),Lp=[{key:`ctrl+c`,reason:`Cannot be rebound - used for interrupt/exit (hardcoded)`,severity:`error`},{key:`ctrl+d`,reason:`Cannot be rebound - used for exit (hardcoded)`,severity:`error`},{key:`ctrl+m`,reason:`Cannot be rebound - identical to Enter in terminals (both send CR)`,severity:`error`}],Rp=[{key:`ctrl+z`,reason:`Unix process suspend (SIGTSTP)`,severity:`warning`},{key:`ctrl+\\`,reason:`Terminal quit signal (SIGQUIT)`,severity:`error`}],zp=[{key:`cmd+c`,reason:`macOS system copy`,severity:`error`},{key:`cmd+v`,reason:`macOS system paste`,severity:`error`},{key:`cmd+x`,reason:`macOS system cut`,severity:`error`},{key:`cmd+q`,reason:`macOS quit application`,severity:`error`},{key:`cmd+w`,reason:`macOS close window/tab`,severity:`error`},{key:`cmd+tab`,reason:`macOS app switcher`,severity:`error`},{key:`cmd+space`,reason:`macOS Spotlight`,severity:`error`}]}));function qde(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.context==`string`&&typeof t.bindings==`object`&&t.bindings!==null}function Jde(e){return Array.isArray(e)&&e.every(qde)}function Yde(e){return Up.includes(e)}function Xde(e){let t=e.toLowerCase().split(`+`);for(let n of t)if(!n.trim())return{type:`parse_error`,severity:`error`,message:`Empty key part in "${e}"`,key:e,suggestion:`Remove extra "+" characters`};let n=it(e);return!n.key&&!n.ctrl&&!n.alt&&!n.shift&&!n.meta?{type:`parse_error`,severity:`error`,message:`Could not parse keystroke "${e}"`,key:e}:null}function Zde(e,t){let n=[];if(typeof e!=`object`||!e)return n.push({type:`parse_error`,severity:`error`,message:`Keybinding block ${t+1} is not an object`}),n;let r=e,i=r.context,a;if(typeof i==`string`?Yde(i)?a=i:n.push({type:`invalid_context`,severity:`error`,message:`Unknown context "${i}"`,context:i,suggestion:`Valid contexts: ${Up.join(`, `)}`}):n.push({type:`parse_error`,severity:`error`,message:`Keybinding block ${t+1} missing "context" field`}),typeof r.bindings!=`object`||r.bindings===null)return n.push({type:`parse_error`,severity:`error`,message:`Keybinding block ${t+1} missing "bindings" field`}),n;let o=r.bindings;for(let[e,t]of Object.entries(o)){let r=Xde(e);r&&(r.context=a,n.push(r)),t!==null&&typeof t!=`string`?n.push({type:`invalid_action`,severity:`error`,message:`Invalid action for "${e}": must be a string or null`,key:e,context:a}):typeof t==`string`&&t.startsWith(`command:`)&&(/^command:[a-zA-Z0-9:\-_]+$/.test(t)||n.push({type:`invalid_action`,severity:`warning`,message:`Invalid command binding "${t}" for "${e}": command name may only contain alphanumeric characters, colons, hyphens, and underscores`,key:e,context:a,action:t}),a&&a!==`Chat`&&n.push({type:`invalid_action`,severity:`warning`,message:`Command binding "${t}" must be in "Chat" context, not "${a}"`,key:e,context:a,action:t,suggestion:`Move this binding to a block with "context": "Chat"`}))}return n}function Vp(e){let t=[],n=/"bindings"\s*:\s*\{([^{}]*(?:\{[^{}]*\}[^{}]*)*)\}/g,r;for(;(r=n.exec(e))!==null;){let n=r[1];if(!n)continue;let i=e.slice(0,r.index).match(/"context"\s*:\s*"([^"]+)"[^{]*$/)?.[1]??`unknown`,a=/"([^"]+)"\s*:/g,o=new Map,s;for(;(s=a.exec(n))!==null;){let e=s[1];if(!e)continue;let n=(o.get(e)??0)+1;o.set(e,n),n===2&&t.push({type:`duplicate`,severity:`warning`,message:`Duplicate key "${e}" in ${i} bindings`,key:e,context:i,suggestion:`This key appears multiple times in the same context. JSON uses the last value, earlier values are ignored.`})}}return t}function Qde(e){let t=[];if(!Array.isArray(e))return t.push({type:`parse_error`,severity:`error`,message:`keybindings.json must contain an array`,suggestion:`Wrap your bindings in [ ]`}),t;for(let n=0;n<e.length;n++)t.push(...Zde(e[n],n));return t}function $de(e){let t=[],n=new Map;for(let r of e){let e=n.get(r.context)??new Map;n.set(r.context,e);for(let[n,i]of Object.entries(r.bindings)){let a=Ip(n),o=e.get(a);o&&o!==i&&t.push({type:`duplicate`,severity:`warning`,message:`Duplicate binding "${n}" in ${r.context} context`,key:n,context:r.context,action:i??`null (unbind)`,suggestion:`Previously bound to "${o}". Only the last binding will be used.`}),e.set(a,i??`null`)}}return t}function efe(e){let t=[],n=Gde();for(let r of e){let e=Tee(r.chord),i=Ip(e);for(let a of n)Ip(a.key)===i&&t.push({type:`reserved`,severity:a.severity,message:`"${e}" may not work: ${a.reason}`,key:e,context:r.context,action:r.action??void 0})}return t}function tfe(e){let t=[];for(let n of e)for(let[e,r]of Object.entries(n.bindings)){let i=e.split(` `).map(e=>it(e));t.push({chord:i,action:r,context:n.context})}return t}function Hp(e,t){let n=[];if(n.push(...Qde(e)),Jde(e)){n.push(...$de(e));let t=tfe(e);n.push(...efe(t))}let r=new Set;return n.filter(e=>{let t=`${e.type}:${e.key}:${e.context}`;return r.has(t)?!1:(r.add(t),!0)})}var Up,nfe=n((()=>{Fp(),Bp(),Up=[`Global`,`Chat`,`Autocomplete`,`Confirmation`,`Help`,`Transcript`,`HistorySearch`,`Task`,`ThemePicker`,`Settings`,`Tabs`,`Attachments`,`Footer`,`FormField`,`MessageActions`,`MessageSelector`,`DiffDialog`,`ModelPicker`,`Scroll`,`Select`,`Plugin`]}));function Wp(){return!1}function Gp(e){let t=new Date().toISOString().slice(0,10);am!==t&&(am=t,Y(`tengu_custom_keybindings_loaded`,{user_binding_count:e}))}function rfe(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.context==`string`&&typeof t.bindings==`object`&&t.bindings!==null}function Kp(e){return Array.isArray(e)&&e.every(rfe)}function qp(){return X(m(),`keybindings.json`)}function Jp(){return st(Np)}async function ife(){let e=Jp();if(!Wp())return{bindings:e,warnings:[]};let t=qp();try{let n=await tl(t,`utf-8`),r=$n(n),i;if(typeof r==`object`&&r&&`bindings`in r)i=r.bindings;else{let t=`keybindings.json must have a "bindings" array`;return G(`[keybindings] Invalid keybindings.json: ${t}`),{bindings:e,warnings:[{type:`parse_error`,severity:`error`,message:t,suggestion:`Use format: { "bindings": [ ... ] }`}]}}if(!Kp(i)){let t=Array.isArray(i)?`keybindings.json contains invalid block structure`:`"bindings" must be an array`,n=Array.isArray(i)?`Each block must have "context" (string) and "bindings" (object)`:`Set "bindings" to an array of keybinding blocks`;return G(`[keybindings] Invalid keybindings.json: ${t}`),{bindings:e,warnings:[{type:`parse_error`,severity:`error`,message:t,suggestion:n}]}}let a=st(i);G(`[keybindings] Loaded ${a.length} user bindings from ${t}`);let o=[...e,...a];Gp(a.length);let s=[...Vp(n),...Hp(i,o)];return s.length>0&&G(`[keybindings] Found ${s.length} validation issue(s)`),{bindings:o,warnings:s}}catch(n){return Qn(n)?{bindings:e,warnings:[]}:(G(`[keybindings] Error loading ${t}: ${W(n)}`),{bindings:e,warnings:[{type:`parse_error`,severity:`error`,message:`Failed to parse keybindings.json: ${W(n)}`}]})}}function afe(){return nm||Yp().bindings}function Yp(){if(nm)return{bindings:nm,warnings:rm};let e=Jp();if(!Wp())return nm=e,rm=[],{bindings:nm,warnings:rm};let t=qp();try{let n=zc(t,`utf-8`),r=$n(n),i;if(typeof r==`object`&&r&&`bindings`in r)i=r.bindings;else return nm=e,rm=[{type:`parse_error`,severity:`error`,message:`keybindings.json must have a "bindings" array`,suggestion:`Use format: { "bindings": [ ... ] }`}],{bindings:nm,warnings:rm};if(!Kp(i)){let t=Array.isArray(i)?`keybindings.json contains invalid block structure`:`"bindings" must be an array`,n=Array.isArray(i)?`Each block must have "context" (string) and "bindings" (object)`:`Set "bindings" to an array of keybinding blocks`;return nm=e,rm=[{type:`parse_error`,severity:`error`,message:t,suggestion:n}],{bindings:nm,warnings:rm}}let a=st(i);return G(`[keybindings] Loaded ${a.length} user bindings from ${t}`),nm=[...e,...a],Gp(a.length),rm=[...Vp(n),...Hp(i,nm)],rm.length>0&&G(`[keybindings] Found ${rm.length} validation issue(s)`),{bindings:nm,warnings:rm}}catch{return nm=e,rm=[],{bindings:nm,warnings:rm}}}async function ofe(){if(em||tm)return;if(!Wp()){G(`[keybindings] Skipping file watcher - user customization disabled`);return}let e=qp(),t=xc(e);try{if(!(await ol(t)).isDirectory()){G(`[keybindings] Not watching: ${t} is not a directory`);return}}catch{G(`[keybindings] Not watching: ${t} does not exist`);return}em=!0,G(`[keybindings] Watching for changes to ${e}`),$p=Tp.watch(e,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:Zp,pollInterval:Qp},ignorePermissionErrors:!0,usePolling:!1,atomic:!0}),$p.on(`add`,Xp),$p.on(`change`,Xp),$p.on(`unlink`,cfe),ar(async()=>sfe())}function sfe(){tm=!0,$p&&($p.close(),$p=null),im.clear()}async function Xp(e){G(`[keybindings] Detected change to ${e}`);try{let e=await ife();nm=e.bindings,rm=e.warnings,im.emit(e)}catch(e){G(`[keybindings] Error reloading: ${W(e)}`)}}function cfe(e){G(`[keybindings] Detected deletion of ${e}`);let t=Jp();nm=t,rm=[],im.emit({bindings:t,warnings:[]})}function lfe(){return rm}var Zp,Qp,$p,em,tm,nm,rm,im,am,om,sm=n((()=>{Ep(),oo(),Hn(),K(),g(),qn(),Xt(),mr(),Pp(),Fp(),nfe(),Zp=500,Qp=200,$p=null,em=!1,tm=!1,nm=null,rm=[],im=Dn(),am=null,om=im.subscribe})),cm,ufe=n((()=>{sm(),cm={name:`keybindings`,description:`打开或创建你的 keybindings 配置文件`,isEnabled:()=>Wp(),supportsNonInteractive:!1,type:`local`,load:()=>import(`./keybindings-CLRaiL_Z.js`)}})),lm,dfe=n((()=>{lm={type:`local-jsx`,name:`mcp`,description:`管理 MCP 服务器`,immediate:!0,argumentHint:`[enable|disable [server-name]]`,load:()=>import(`./mcp-D0wAJrRT.js`)}})),um,ffe=n((()=>{um={type:`local-jsx`,name:`onboarding`,description:`重新运行首次启动的初始化(主题、信任、模型、MCP)`,argumentHint:`[full|theme|trust|model|mcp|status]`,isEnabled:()=>!0,isHidden:!1,load:async()=>({call:(await import(`./launchOnboarding-tqsMD8ni.js`)).callOnboarding})}})),dm,pfe=n((()=>{dm={type:`local-jsx`,name:`rename`,description:`重命名当前会话`,immediate:!0,argumentHint:`[name]`,load:()=>import(`./rename-CtBghpxZ.js`)}})),fm,mfe=n((()=>{fm={type:`local-jsx`,name:`resume`,description:`恢复之前的会话`,aliases:[`continue`],argumentHint:`[conversation id or search term]`,load:()=>import(`./resume-BWkaTDqd.js`)}})),pm,hfe=n((()=>{pm={type:`local-jsx`,name:`skills`,description:`列出可用的 skill`,load:()=>import(`./skills-CX_AvwLG.js`)}})),mm,gfe=n((()=>{mm={type:`local-jsx`,name:`status`,description:`显示 Work Mate 的状态,包括版本、模型、账号、API 连通性与工具状态`,immediate:!0,load:()=>import(`./status-Daaak6Bo.js`)}})),hm,_fe=n((()=>{hm={type:`local-jsx`,name:`tasks`,aliases:[`bashes`],description:`列出并管理后台任务`,load:()=>import(`./tasks-BWNQr2d3.js`)}})),gm,vfe=n((()=>{gm={type:`local-jsx`,name:`local-memory`,aliases:[`lm`],description:`管理本地记忆存储,用于笔记和上下文。存放在 ~/.workmate/local-memory/——无需 API key`,argumentHint:`list | create STORE | store STORE KEY VALUE | fetch STORE KEY | entries STORE | archive STORE`,isHidden:!1,isEnabled:()=>!0,load:async()=>({call:(await import(`./launchLocalMemory-DrbKrwXc.js`)).callLocalMemory})}})),_m,yfe=n((()=>{Ii(),_m={type:`local-jsx`,name:`terminal-setup`,description:$r.terminal===`Apple_Terminal`?`启用 Option+Enter 换行键绑定和视觉响铃`:`安装 Shift+Enter 换行键绑定`,isHidden:$r.terminal!==null&&$r.terminal in{ghostty:`Ghostty`,kitty:`Kitty`,"iTerm.app":`iTerm2`,WezTerm:`WezTerm`},load:()=>import(`./terminalSetup-qc2PlvOm.js`)}})),vm,bfe=n((()=>{vm={type:`local-jsx`,name:`theme`,description:`切换主题`,load:()=>import(`./theme-B7fKI6E5.js`)}})),ym,xfe=n((()=>{ym={name:`vim`,description:`在 Vim 与普通编辑模式之间切换`,supportsNonInteractive:!1,type:`local`,load:()=>import(`./vim-CoRp9lY1.js`)}})),bm=i({activateProactive:()=>Cm,deactivateProactive:()=>wm,getActivationSource:()=>Sfe,getNextTickAt:()=>jm,isContextBlocked:()=>km,isProactiveActive:()=>Sm,isProactivePaused:()=>Tm,pauseProactive:()=>Em,resumeProactive:()=>Dm,setContextBlocked:()=>Om,setNextTickAt:()=>Am,shouldTick:()=>Nm,subscribeToProactiveChanges:()=>Mm});function xm(){for(let e of zm)try{e()}catch{}}function Sm(){return Pm}function Cm(e){Pm||(Pm=!0,Fm=!1,Im=!1,Rm=e,xm())}function wm(){Pm&&(Pm=!1,Fm=!1,Im=!1,Lm=null,Rm=void 0,xm())}function Tm(){return Fm}function Em(){!Pm||Fm||(Fm=!0,Lm=null,xm())}function Dm(){!Pm||!Fm||(Fm=!1,xm())}function Om(e){Im!==e&&(Im=e,e&&(Lm=null),xm())}function km(){return Im}function Am(e){Lm=e,xm()}function jm(){return!Pm||Fm||Im?null:Lm}function Sfe(){return Rm}function Mm(e){return zm.add(e),()=>{zm.delete(e)}}function Nm(){return Pm&&!Fm&&!Im}var Pm,Fm,Im,Lm,Rm,zm,Bm=n((()=>{Pm=!1,Fm=!1,Im=!1,Lm=null,zm=new Set})),Vm,Cfe=n((()=>{Vm={type:`local-jsx`,name:`proactive`,description:`切换主动(autonomous)模式`,isEnabled:()=>!0,immediate:!0,load:()=>Promise.resolve({async call(t,n){let r=(Bm(),e(bm));return r.isProactiveActive()?(r.deactivateProactive(),t(`Proactive mode disabled`,{display:`system`})):(r.activateProactive(`slash_command`),t(`Proactive mode enabled — model will work autonomously between ticks`,{display:`system`,metaMessages:[`<system-reminder>
|
|
389
|
+
`}]}}}));function Fde(e,t={}){let n=t.entryType||t.type;if(n===`both`&&(n=pf.FILE_DIR_TYPE),n&&(t.type=n),!e)throw Error(`readdirp: root argument is required. Usage: readdirp(root, options)`);if(typeof e!=`string`)throw TypeError(`readdirp: root argument must be a string. Usage: readdirp(root, options)`);if(n&&!_f.includes(n))throw Error(`readdirp: Invalid type passed. Use one of ${_f.join(`, `)}`);return t.root=e,new wf(t)}var pf,mf,hf,gf,_f,vf,yf,bf,xf,Sf,Cf,wf,Ide=n((()=>{b(),pf={FILE_TYPE:`files`,DIR_TYPE:`directories`,FILE_DIR_TYPE:`files_directories`,EVERYTHING_TYPE:`all`},mf={root:`.`,fileFilter:e=>!0,directoryFilter:e=>!0,type:pf.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096},Object.freeze(mf),hf=`READDIRP_RECURSIVE_ERROR`,gf=new Set([`ENOENT`,`EPERM`,`EACCES`,`ELOOP`,hf]),_f=[pf.DIR_TYPE,pf.EVERYTHING_TYPE,pf.FILE_DIR_TYPE,pf.FILE_TYPE],vf=new Set([pf.DIR_TYPE,pf.EVERYTHING_TYPE,pf.FILE_DIR_TYPE]),yf=new Set([pf.EVERYTHING_TYPE,pf.FILE_DIR_TYPE,pf.FILE_TYPE]),bf=e=>gf.has(e.code),xf=process.platform===`win32`,Sf=e=>!0,Cf=e=>{if(e===void 0)return Sf;if(typeof e==`function`)return e;if(typeof e==`string`){let t=e.trim();return e=>e.basename===t}if(Array.isArray(e)){let t=e.map(e=>e.trim());return e=>t.some(t=>e.basename===t)}return Sf},wf=class extends Lce{constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark}),x(this,`parents`,void 0),x(this,`reading`,void 0),x(this,`parent`,void 0),x(this,`_stat`,void 0),x(this,`_maxDepth`,void 0),x(this,`_wantsDir`,void 0),x(this,`_wantsFile`,void 0),x(this,`_wantsEverything`,void 0),x(this,`_root`,void 0),x(this,`_isDirent`,void 0),x(this,`_statsProp`,void 0),x(this,`_rdOptions`,void 0),x(this,`_fileFilter`,void 0),x(this,`_directoryFilter`,void 0);let t={...mf,...e},{root:n,type:r}=t;this._fileFilter=Cf(t.fileFilter),this._directoryFilter=Cf(t.directoryFilter);let i=t.lstat?ml:vl;xf?this._stat=e=>i(e,{bigint:!0}):this._stat=i,this._maxDepth=t.depth!=null&&Number.isSafeInteger(t.depth)?t.depth:mf.depth,this._wantsDir=r?vf.has(r):!1,this._wantsFile=r?yf.has(r):!1,this._wantsEverything=r===pf.EVERYTHING_TYPE,this._root=Ic(n),this._isDirent=!t.alwaysStat,this._statsProp=this._isDirent?`dirent`:`stats`,this._rdOptions={encoding:`utf8`,withFileTypes:this._isDirent},this.parents=[this._exploreDir(n,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let t=this.parent,n=t&&t.files;if(n&&n.length>0){let{path:r,depth:i}=t,a=n.splice(0,e).map(e=>this._formatEntry(e,r)),o=await Promise.all(a);for(let t of o){if(!t)continue;if(this.destroyed)return;let n=await this._getEntryType(t);n===`directory`&&this._directoryFilter(t)?(i<=this._maxDepth&&this.parents.push(this._exploreDir(t.fullPath,i+1)),this._wantsDir&&(this.push(t),e--)):(n===`file`||this._includeAsFile(t))&&this._fileFilter(t)&&this._wantsFile&&(this.push(t),e--)}}else{let e=this.parents.pop();if(!e){this.push(null);break}if(this.parent=await e,this.destroyed)return}}}catch(e){this.destroy(e)}finally{this.reading=!1}}}async _exploreDir(e,t){let n;try{n=await gl(e,this._rdOptions)}catch(e){this._onError(e)}return{files:n,depth:t,path:e}}async _formatEntry(e,t){let n,r=this._isDirent?e.name:e;try{let i=Ic(Pc(t,r));n={path:Fc(this._root,i),fullPath:i,basename:r},n[this._statsProp]=this._isDirent?e:await this._stat(i)}catch(e){this._onError(e);return}return n}_onError(e){bf(e)&&!this.destroyed?this.emit(`warn`,e):this.destroy(e)}async _getEntryType(e){if(!e&&this._statsProp in e)return``;let t=e[this._statsProp];if(t.isFile())return`file`;if(t.isDirectory())return`directory`;if(t&&t.isSymbolicLink()){let t=e.fullPath;try{let e=await _l(t),n=await ml(e);if(n.isFile())return`file`;if(n.isDirectory()){let n=e.length;if(t.startsWith(e)&&t.substr(n,1)===Rse){let n=Error(`Circular symlink detected: "${t}" points to "${e}"`);return n.code=hf,this._onError(n)}return`directory`}}catch(e){return this._onError(e),``}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}}}));function Tf(e,t,n,r,i){let a=(t,r)=>{n(e),i(t,r,{watchedPath:e}),r&&e!==r&&Zf(Mc.resolve(e,r),zf,Mc.join(e,r))};try{return hce(e,{persistent:t.persistent},a)}catch(e){r(e);return}}var Ef,Df,Of,kf,Af,jf,Mf,Nf,Pf,Ff,If,Lf,Rf,zf,Bf,Vf,Hf,Uf,Wf,Gf,Kf,qf,Jf,Yf,Xf,Zf,Qf,$f,ep,tp,Lde=n((()=>{b(),Ef=`data`,Df=`close`,Of=()=>{},kf=process.platform,Af=kf===`win32`,jf=kf===`darwin`,Mf=kf===`linux`,Nf=kf===`freebsd`,Pf=yce()===`OS400`,Ff={ALL:`all`,READY:`ready`,ADD:`add`,CHANGE:`change`,ADD_DIR:`addDir`,UNLINK:`unlink`,UNLINK_DIR:`unlinkDir`,RAW:`raw`,ERROR:`error`},If=Ff,Lf=`watch`,Rf={lstat:ml,stat:vl},zf=`listeners`,Bf=`errHandlers`,Vf=`rawEmitters`,Hf=[zf,Bf,Vf],Uf=new Set(`3dm.3ds.3g2.3gp.7z.a.aac.adp.afdesign.afphoto.afpub.ai.aif.aiff.alz.ape.apk.appimage.ar.arj.asf.au.avi.bak.baml.bh.bin.bk.bmp.btif.bz2.bzip2.cab.caf.cgm.class.cmx.cpio.cr2.cur.dat.dcm.deb.dex.djvu.dll.dmg.dng.doc.docm.docx.dot.dotm.dra.DS_Store.dsk.dts.dtshd.dvb.dwg.dxf.ecelp4800.ecelp7470.ecelp9600.egg.eol.eot.epub.exe.f4v.fbs.fh.fla.flac.flatpak.fli.flv.fpx.fst.fvt.g3.gh.gif.graffle.gz.gzip.h261.h263.h264.icns.ico.ief.img.ipa.iso.jar.jpeg.jpg.jpgv.jpm.jxr.key.ktx.lha.lib.lvp.lz.lzh.lzma.lzo.m3u.m4a.m4v.mar.mdi.mht.mid.midi.mj2.mka.mkv.mmr.mng.mobi.mov.movie.mp3.mp4.mp4a.mpeg.mpg.mpga.mxu.nef.npx.numbers.nupkg.o.odp.ods.odt.oga.ogg.ogv.otf.ott.pages.pbm.pcx.pdb.pdf.pea.pgm.pic.png.pnm.pot.potm.potx.ppa.ppam.ppm.pps.ppsm.ppsx.ppt.pptm.pptx.psd.pya.pyc.pyo.pyv.qt.rar.ras.raw.resources.rgb.rip.rlc.rmf.rmvb.rpm.rtf.rz.s3m.s7z.scpt.sgi.shar.snap.sil.sketch.slk.smv.snk.so.stl.suo.sub.swf.tar.tbz.tbz2.tga.tgz.thmx.tif.tiff.tlz.ttc.ttf.txz.udf.uvh.uvi.uvm.uvp.uvs.uvu.viv.vob.war.wav.wax.wbmp.wdp.weba.webm.webp.whl.wim.wm.wma.wmv.wmx.woff.woff2.wrm.wvx.xbm.xif.xla.xlam.xls.xlsb.xlsm.xlsx.xlt.xltm.xltx.xm.xmind.xpi.xpm.xwd.xz.z.zip.zipx`.split(`.`)),Wf=e=>Uf.has(Mc.extname(e).slice(1).toLowerCase()),Gf=(e,t)=>{e instanceof Set?e.forEach(t):t(e)},Kf=(e,t,n)=>{let r=e[t];r instanceof Set||(e[t]=r=new Set([r])),r.add(n)},qf=e=>t=>{let n=e[t];n instanceof Set?n.clear():delete e[t]},Jf=(e,t,n)=>{let r=e[t];r instanceof Set?r.delete(n):r===n&&delete e[t]},Yf=e=>e instanceof Set?e.size===0:!e,Xf=new Map,Zf=(e,t,n,r,i)=>{let a=Xf.get(e);a&&Gf(a[t],e=>{e(n,r,i)})},Qf=(e,t,n,r)=>{let{listener:i,errHandler:a,rawEmitter:o}=r,s=Xf.get(t),c;if(!n.persistent)return c=Tf(e,n,i,a,o),c?c.close.bind(c):void 0;if(s)Kf(s,zf,i),Kf(s,Bf,a),Kf(s,Vf,o);else{if(c=Tf(e,n,Zf.bind(null,t,zf),a,Zf.bind(null,t,Vf)),!c)return;c.on(If.ERROR,async n=>{let r=Zf.bind(null,t,Bf);if(s&&(s.watcherUnusable=!0),Af&&n.code===`EPERM`)try{await(await zce(e,`r`)).close(),r(n)}catch{}else r(n)}),s={listeners:i,errHandlers:a,rawEmitters:o,watcher:c},Xf.set(t,s)}return()=>{Jf(s,zf,i),Jf(s,Bf,a),Jf(s,Vf,o),Yf(s.listeners)&&(s.watcher.close(),Xf.delete(t),Hf.forEach(qf(s)),s.watcher=void 0,Object.freeze(s))}},$f=new Map,ep=(e,t,n,r)=>{let{listener:i,rawEmitter:a}=r,o=$f.get(t),s=o&&o.options;return s&&(s.persistent<n.persistent||s.interval>n.interval)&&(mce(t),o=void 0),o?(Kf(o,zf,i),Kf(o,Vf,a)):(o={listeners:i,rawEmitters:a,options:n,watcher:gce(t,n,(n,r)=>{Gf(o.rawEmitters,e=>{e(If.CHANGE,t,{curr:n,prev:r})});let i=n.mtimeMs;(n.size!==r.size||i>r.mtimeMs||i===0)&&Gf(o.listeners,t=>t(e,n))})},$f.set(t,o)),()=>{Jf(o,zf,i),Jf(o,Vf,a),Yf(o.listeners)&&($f.delete(t),mce(t),o.options=o.watcher=void 0,Object.freeze(o))}},tp=class{constructor(e){x(this,`fsw`,void 0),x(this,`_boundHandleError`,void 0),this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let n=this.fsw.options,r=Mc.dirname(e),i=Mc.basename(e);this.fsw._getWatchedDir(r).add(i);let a=Mc.resolve(e),o={persistent:n.persistent};t||(t=Of);let s;return n.usePolling?(o.interval=n.interval!==n.binaryInterval&&Wf(i)?n.binaryInterval:n.interval,s=ep(e,a,o,{listener:t,rawEmitter:this.fsw._emitRaw})):s=Qf(e,a,o,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw}),s}_handleFile(e,t,n){if(this.fsw.closed)return;let r=Mc.dirname(e),i=Mc.basename(e),a=this.fsw._getWatchedDir(r),o=t;if(a.has(i))return;let s=async(t,n)=>{if(this.fsw._throttle(Lf,e,5)){if(!n||n.mtimeMs===0)try{let n=await vl(e);if(this.fsw.closed)return;let r=n.atimeMs,i=n.mtimeMs;if((!r||r<=i||i!==o.mtimeMs)&&this.fsw._emit(If.CHANGE,e,n),(jf||Mf||Nf)&&o.ino!==n.ino){this.fsw._closeFile(t),o=n;let r=this._watchWithNodeFs(e,s);r&&this.fsw._addPathCloser(t,r)}else o=n}catch{this.fsw._remove(r,i)}else if(a.has(i)){let t=n.atimeMs,r=n.mtimeMs;(!t||t<=r||r!==o.mtimeMs)&&this.fsw._emit(If.CHANGE,e,n),o=n}}},c=this._watchWithNodeFs(e,s);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(If.ADD,e,0))return;this.fsw._emit(If.ADD,e,t)}return c}async _handleSymlink(e,t,n,r){if(this.fsw.closed)return;let i=e.fullPath,a=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let t;try{t=await _l(n)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(a.has(r)?this.fsw._symlinkPaths.get(i)!==t&&(this.fsw._symlinkPaths.set(i,t),this.fsw._emit(If.CHANGE,n,e.stats)):(a.add(r),this.fsw._symlinkPaths.set(i,t),this.fsw._emit(If.ADD,n,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(e,t,n,r,i,a,o){e=Mc.join(e,``);let s=r?`${e}:${r}`:e;if(o=this.fsw._throttle(`readdir`,s,1e3),!o)return;let c=this.fsw._getWatchedDir(n.path),l=new Set,u=this.fsw._readdirp(e,{fileFilter:e=>n.filterPath(e),directoryFilter:e=>n.filterDir(e)});if(u)return u.on(Ef,async o=>{if(this.fsw.closed){u=void 0;return}let s=o.path,d=Mc.join(e,s);if(l.add(s),!(o.stats.isSymbolicLink()&&await this._handleSymlink(o,e,d,s))){if(this.fsw.closed){u=void 0;return}(s===r||!r&&!c.has(s))&&(this.fsw._incrReadyCount(),d=Mc.join(i,Mc.relative(i,d)),this._addToNodeFs(d,t,n,a+1))}}).on(If.ERROR,this._boundHandleError),new Promise((t,s)=>{if(!u)return s();u.once(`end`,()=>{if(this.fsw.closed){u=void 0;return}let s=o?o.clear():!1;t(void 0),c.getChildren().filter(t=>t!==e&&!l.has(t)).forEach(t=>{this.fsw._remove(e,t)}),u=void 0,s&&this._handleRead(e,!1,n,r,i,a,o)})})}async _handleDir(e,t,n,r,i,a,o){let s=this.fsw._getWatchedDir(Mc.dirname(e)),c=s.has(Mc.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!i&&!c&&this.fsw._emit(If.ADD_DIR,e,t),s.add(Mc.basename(e)),this.fsw._getWatchedDir(e);let l,u=this.fsw.options.depth;if((u==null||r<=u)&&!this.fsw._symlinkPaths.has(o)){if(!i&&(await this._handleRead(e,n,a,i,e,r,void 0),this.fsw.closed))return;l=this._watchWithNodeFs(e,(t,n)=>{n&&n.mtimeMs===0||this._handleRead(t,!1,a,i,e,r,void 0)})}return l}async _addToNodeFs(e,t,n,r,i){let a=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return a(),!1;let o=this.fsw._getWatchHelpers(e);n&&(o.filterPath=e=>n.filterPath(e),o.filterDir=e=>n.filterDir(e));try{let n=await Rf[o.statMethod](o.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(o.watchPath,n))return a(),!1;let s=this.fsw.options.followSymlinks,c;if(n.isDirectory()){let a=Mc.resolve(e),l=s?await _l(e):e;if(this.fsw.closed||(c=await this._handleDir(o.watchPath,n,t,r,i,o,l),this.fsw.closed))return;a!==l&&l!==void 0&&this.fsw._symlinkPaths.set(a,l)}else if(n.isSymbolicLink()){let i=s?await _l(e):e;if(this.fsw.closed)return;let a=Mc.dirname(o.watchPath);if(this.fsw._getWatchedDir(a).add(o.watchPath),this.fsw._emit(If.ADD,o.watchPath,n),c=await this._handleDir(a,n,t,r,e,o,i),this.fsw.closed)return;i!==void 0&&this.fsw._symlinkPaths.set(Mc.resolve(e),i)}else c=this._handleFile(o.watchPath,n,t);return a(),c&&this.fsw._addPathCloser(e,c),!1}catch(t){if(this.fsw._handleError(t))return a(),e}}}}));function np(e){return Array.isArray(e)?e:[e]}function Rde(e){return typeof e==`function`?e:typeof e==`string`?t=>e===t:e instanceof RegExp?t=>e.test(t):typeof e==`object`&&e?t=>{if(e.path===t)return!0;if(e.recursive){let n=Mc.relative(e.path,t);return n?!n.startsWith(`..`)&&!Mc.isAbsolute(n):!1}return!1}:()=>!1}function zde(e){if(typeof e!=`string`)throw Error(`string expected`);e=Mc.normalize(e),e=e.replace(/\\/g,`/`);let t=!1;return e.startsWith(`//`)&&(t=!0),e=e.replace(up,`/`),t&&(e=`/`+e),e}function rp(e,t,n){let r=zde(t);for(let t=0;t<e.length;t++){let i=e[t];if(i(r,n))return!0}return!1}function Bde(e,t){if(e==null)throw TypeError(`anymatch: specify first argument`);let n=np(e).map(e=>Rde(e));return t==null?(e,t)=>rp(n,e,t):rp(n,t)}function Vde(e,t={}){let n=new wp(t);return n.add(e),n}var ip,ap,op,sp,cp,lp,up,dp,fp,pp,mp,hp,gp,_p,vp,yp,bp,xp,Sp,Cp,wp,Tp,Ep=n((()=>{Ide(),Lde(),b(),ip=`/`,ap=`//`,op=`.`,sp=`..`,cp=`string`,lp=/\\/g,up=/\/\//g,dp=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,fp=/^\.[/\\]/,pp=e=>typeof e==`object`&&!!e&&!(e instanceof RegExp),mp=e=>{let t=np(e).flat();if(!t.every(e=>typeof e===cp))throw TypeError(`Non-string provided as watch path: ${t}`);return t.map(gp)},hp=e=>{let t=e.replace(lp,ip),n=!1;return t.startsWith(ap)&&(n=!0),t=t.replace(up,ip),n&&(t=ip+t),t},gp=e=>hp(Mc.normalize(hp(e))),_p=(e=``)=>t=>typeof t==`string`?gp(Mc.isAbsolute(t)?t:Mc.join(e,t)):t,vp=(e,t)=>Mc.isAbsolute(e)?e:Mc.join(t,e),yp=Object.freeze(new Set),bp=class{constructor(e,t){x(this,`path`,void 0),x(this,`_removeWatcher`,void 0),x(this,`items`,void 0),this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==op&&e!==sp&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let n=this.path;try{await gl(n)}catch{this._removeWatcher&&this._removeWatcher(Mc.dirname(n),Mc.basename(n))}}has(e){let{items:t}=this;if(t)return t.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path=``,this._removeWatcher=Of,this.items=yp,Object.freeze(this)}},xp=`stat`,Sp=`lstat`,Cp=class{constructor(e,t,n){x(this,`fsw`,void 0),x(this,`path`,void 0),x(this,`watchPath`,void 0),x(this,`fullWatchPath`,void 0),x(this,`dirParts`,void 0),x(this,`followSymlinks`,void 0),x(this,`statMethod`,void 0),this.fsw=n;let r=e;this.path=e=e.replace(fp,``),this.watchPath=r,this.fullWatchPath=Mc.resolve(r),this.dirParts=[],this.dirParts.forEach(e=>{e.length>1&&e.pop()}),this.followSymlinks=t,this.statMethod=t?xp:Sp}entryPath(e){return Mc.join(this.watchPath,Mc.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let n=this.entryPath(e);return this.fsw._isntIgnored(n,t)&&this.fsw._hasReadPermissions(t)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},wp=class extends Pce{constructor(e={}){super(),x(this,`closed`,void 0),x(this,`options`,void 0),x(this,`_closers`,void 0),x(this,`_ignoredPaths`,void 0),x(this,`_throttled`,void 0),x(this,`_streams`,void 0),x(this,`_symlinkPaths`,void 0),x(this,`_watched`,void 0),x(this,`_pendingWrites`,void 0),x(this,`_pendingUnlinks`,void 0),x(this,`_readyCount`,void 0),x(this,`_emitReady`,void 0),x(this,`_closePromise`,void 0),x(this,`_userIgnored`,void 0),x(this,`_readyEmitted`,void 0),x(this,`_emitRaw`,void 0),x(this,`_boundRemove`,void 0),x(this,`_nodeFsHandler`,void 0),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let t=e.awaitWriteFinish,n={stabilityThreshold:2e3,pollInterval:100},r={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?np(e.ignored):np([]),awaitWriteFinish:t===!0?n:typeof t==`object`&&{...n,...t}};Pf&&(r.usePolling=!0),r.atomic===void 0&&(r.atomic=!r.usePolling);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let e=i.toLowerCase();e===`false`||e===`0`?r.usePolling=!1:e===`true`||e===`1`?r.usePolling=!0:r.usePolling=!!e}let a=process.env.CHOKIDAR_INTERVAL;a&&(r.interval=Number.parseInt(a,10));let o=0;this._emitReady=()=>{o++,o>=this._readyCount&&(this._emitReady=Of,this._readyEmitted=!0,process.nextTick(()=>this.emit(Ff.READY)))},this._emitRaw=(...e)=>this.emit(Ff.RAW,...e),this._boundRemove=this._remove.bind(this),this.options=r,this._nodeFsHandler=new tp(this),Object.freeze(r)}_addIgnoredPath(e){if(pp(e)){for(let t of this._ignoredPaths)if(pp(t)&&t.path===e.path&&t.recursive===e.recursive)return}this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),typeof e==`string`)for(let t of this._ignoredPaths)pp(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,n){let{cwd:r}=this.options;this.closed=!1,this._closePromise=void 0;let i=mp(e);return r&&(i=i.map(e=>vp(e,r))),i.forEach(e=>{this._removeIgnoredPath(e)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=i.length,Promise.all(i.map(async e=>{let r=await this._nodeFsHandler._addToNodeFs(e,!n,void 0,0,t);return r&&this._emitReady(),r})).then(e=>{this.closed||e.forEach(e=>{e&&this.add(Mc.dirname(e),Mc.basename(t||e))})}),this}unwatch(e){if(this.closed)return this;let t=mp(e),{cwd:n}=this.options;return t.forEach(e=>{!Mc.isAbsolute(e)&&!this._closers.has(e)&&(n&&(e=Mc.join(n,e)),e=Mc.resolve(e)),this._closePath(e),this._addIgnoredPath(e),this._watched.has(e)&&this._addIgnoredPath({path:e,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(t=>t.forEach(t=>{let n=t();n instanceof Promise&&e.push(n)})),this._streams.forEach(e=>e.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(e=>e.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>void 0):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((t,n)=>{let r=(this.options.cwd?Mc.relative(this.options.cwd,n):n)||op;e[r]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==Ff.ERROR&&this.emit(Ff.ALL,e,...t)}async _emit(e,t,n){if(this.closed)return;let r=this.options;Af&&(t=Mc.normalize(t)),r.cwd&&(t=Mc.relative(r.cwd,t));let i=[t];n!=null&&i.push(n);let a=r.awaitWriteFinish,o;if(a&&(o=this._pendingWrites.get(t)))return o.lastChange=new Date,this;if(r.atomic){if(e===Ff.UNLINK)return this._pendingUnlinks.set(t,[e,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((e,t)=>{this.emit(...e),this.emit(Ff.ALL,...e),this._pendingUnlinks.delete(t)})},typeof r.atomic==`number`?r.atomic:100),this;e===Ff.ADD&&this._pendingUnlinks.has(t)&&(e=Ff.CHANGE,this._pendingUnlinks.delete(t))}if(a&&(e===Ff.ADD||e===Ff.CHANGE)&&this._readyEmitted)return this._awaitWriteFinish(t,a.stabilityThreshold,e,(t,n)=>{t?(e=Ff.ERROR,i[0]=t,this.emitWithAll(e,i)):n&&(i.length>1?i[1]=n:i.push(n),this.emitWithAll(e,i))}),this;if(e===Ff.CHANGE&&!this._throttle(Ff.CHANGE,t,50))return this;if(r.alwaysStat&&n===void 0&&(e===Ff.ADD||e===Ff.ADD_DIR||e===Ff.CHANGE)){let e=r.cwd?Mc.join(r.cwd,t):t,n;try{n=await vl(e)}catch{}if(!n||this.closed)return;i.push(n)}return this.emitWithAll(e,i),this}_handleError(e){let t=e&&e.code;return e&&t!==`ENOENT`&&t!==`ENOTDIR`&&(!this.options.ignorePermissionErrors||t!==`EPERM`&&t!==`EACCES`)&&this.emit(Ff.ERROR,e),e||this.closed}_throttle(e,t,n){this._throttled.has(e)||this._throttled.set(e,new Map);let r=this._throttled.get(e);if(!r)throw Error(`invalid throttle`);let i=r.get(t);if(i)return i.count++,!1;let a,o=()=>{let e=r.get(t),n=e?e.count:0;return r.delete(t),clearTimeout(a),e&&clearTimeout(e.timeoutObject),n};a=setTimeout(o,n);let s={timeoutObject:a,clear:o,count:0};return r.set(t,s),s}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,n,r){let i=this.options.awaitWriteFinish;if(typeof i!=`object`)return;let a=i.pollInterval,o,s=e;this.options.cwd&&!Mc.isAbsolute(e)&&(s=Mc.join(this.options.cwd,e));let c=new Date,l=this._pendingWrites;function u(n){dce(s,(i,s)=>{if(i||!l.has(e)){i&&i.code!==`ENOENT`&&r(i);return}let c=Number(new Date);n&&s.size!==n.size&&(l.get(e).lastChange=c),c-l.get(e).lastChange>=t?(l.delete(e),r(void 0,s)):o=setTimeout(u,a,s)})}l.has(e)||(l.set(e,{lastChange:c,cancelWait:()=>(l.delete(e),clearTimeout(o),n)}),o=setTimeout(u,a))}_isIgnored(e,t){if(this.options.atomic&&dp.test(e))return!0;if(!this._userIgnored){let{cwd:e}=this.options,t=(this.options.ignored||[]).map(_p(e)),n=[...[...this._ignoredPaths].map(_p(e)),...t];this._userIgnored=Bde(n,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new Cp(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=Mc.resolve(e);return this._watched.has(t)||this._watched.set(t,new bp(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,n){let r=Mc.join(e,t),i=Mc.resolve(r);if(n=n??(this._watched.has(r)||this._watched.has(i)),!this._throttle(`remove`,r,100))return;!n&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(r).getChildren().forEach(e=>this._remove(r,e));let a=this._getWatchedDir(e),o=a.has(t);a.remove(t),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let s=r;if(this.options.cwd&&(s=Mc.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(s)&&this._pendingWrites.get(s).cancelWait()===Ff.ADD)return;this._watched.delete(r),this._watched.delete(i);let c=n?Ff.UNLINK_DIR:Ff.UNLINK;o&&!this._isIgnored(r)&&this._emit(c,r),this._closePath(r)}_closePath(e){this._closeFile(e);let t=Mc.dirname(e);this._getWatchedDir(t).remove(Mc.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(e=>e()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let n=this._closers.get(e);n||(n=[],this._closers.set(e,n)),n.push(t)}_readdirp(e,t){if(this.closed)return;let n=Fde(e,{type:Ff.ALL,alwaysStat:!0,lstat:!0,...t,depth:0});return this._streams.add(n),n.once(Df,()=>{n=void 0}),n.once(`end`,()=>{n&&(this._streams.delete(n),n=void 0)}),n}},Tp={watch:Vde,FSWatcher:wp}}));function Dp(){return kp||(kp=ue()),kp}function Hde(e,t){return typeof Bun<`u`?Bun.semver.order(e,t)===1:Dp().gt(e,t,{loose:!0})}function Ude(e,t){return typeof Bun<`u`?Bun.semver.order(e,t)>=0:Dp().gte(e,t,{loose:!0})}function Wde(e,t){return typeof Bun<`u`?Bun.semver.order(e,t)===-1:Dp().lt(e,t,{loose:!0})}function Op(e,t){return typeof Bun<`u`?Bun.semver.satisfies(e,t):Dp().satisfies(e,t,{loose:!0})}var kp,Ap=n((()=>{})),jp,Mp,Np,Pp=n((()=>{Ap(),Qa(),ao(),jp=io()===`windows`?`alt+v`:`ctrl+v`,Mp=io()!==`windows`||(Cie()?Op(process.versions.bun,`>=1.2.23`):Op(process.versions.node,`>=22.17.0 <23.0.0 || >=24.2.0`))?`shift+tab`:`meta+m`,Np=[{context:`Global`,bindings:{"ctrl+c":`app:interrupt`,"ctrl+d":`app:exit`,"ctrl+l":`app:redraw`,"ctrl+t":`app:toggleTodos`,"ctrl+o":`app:toggleTranscript`,"ctrl+shift+o":`app:toggleTeammatePreview`,"ctrl+r":`history:search`}},{context:`Chat`,bindings:{escape:`chat:cancel`,"ctrl+x ctrl+k":`chat:killAgents`,[Mp]:`chat:cycleMode`,"meta+p":`chat:modelPicker`,"meta+o":`chat:fastMode`,"meta+t":`chat:thinkingToggle`,enter:`chat:submit`,up:`history:previous`,down:`history:next`,"ctrl+_":`chat:undo`,"ctrl+shift+-":`chat:undo`,"ctrl+x ctrl+e":`chat:externalEditor`,"ctrl+g":`chat:externalEditor`,"ctrl+s":`chat:stash`,[jp]:`chat:imagePaste`}},{context:`Autocomplete`,bindings:{tab:`autocomplete:accept`,escape:`autocomplete:dismiss`,up:`autocomplete:previous`,down:`autocomplete:next`}},{context:`Settings`,bindings:{escape:`confirm:no`,up:`select:previous`,down:`select:next`,k:`select:previous`,j:`select:next`,"ctrl+p":`select:previous`,"ctrl+n":`select:next`,left:`select:previousValue`,right:`select:nextValue`,space:`select:accept`,enter:`settings:close`,"/":`settings:search`,r:`settings:retry`}},{context:`Confirmation`,bindings:{enter:`confirm:yes`,escape:`confirm:no`,up:`confirm:previous`,down:`confirm:next`,tab:`confirm:nextField`,space:`confirm:toggle`,"shift+tab":`confirm:cycleMode`,"ctrl+e":`confirm:toggleExplanation`,"ctrl+d":`permission:toggleDebug`}},{context:`FormField`,bindings:{tab:`tabs:next`,"shift+tab":`tabs:previous`,up:`tabs:previous`,down:`tabs:next`}},{context:`Tabs`,bindings:{tab:`tabs:next`,"shift+tab":`tabs:previous`,right:`tabs:next`,left:`tabs:previous`}},{context:`Transcript`,bindings:{"ctrl+e":`transcript:toggleShowAll`,"ctrl+c":`transcript:exit`,escape:`transcript:exit`,q:`transcript:exit`}},{context:`HistorySearch`,bindings:{"ctrl+r":`historySearch:next`,escape:`historySearch:accept`,tab:`historySearch:accept`,"ctrl+c":`historySearch:cancel`,enter:`historySearch:execute`}},{context:`Task`,bindings:{"ctrl+b":`task:background`}},{context:`ThemePicker`,bindings:{"ctrl+t":`theme:toggleSyntaxHighlighting`}},{context:`Scroll`,bindings:{pageup:`scroll:pageUp`,pagedown:`scroll:pageDown`,wheelup:`scroll:lineUp`,wheeldown:`scroll:lineDown`,"ctrl+home":`scroll:top`,"ctrl+end":`scroll:bottom`,"ctrl+shift+c":`selection:copy`,"cmd+c":`selection:copy`}},{context:`Help`,bindings:{escape:`help:dismiss`}},{context:`Attachments`,bindings:{right:`attachments:next`,left:`attachments:previous`,backspace:`attachments:remove`,delete:`attachments:remove`,down:`attachments:exit`,escape:`attachments:exit`}},{context:`Footer`,bindings:{up:`footer:up`,"ctrl+p":`footer:up`,down:`footer:down`,"ctrl+n":`footer:down`,right:`footer:next`,left:`footer:previous`,enter:`footer:openSelected`,escape:`footer:clearSelection`}},{context:`MessageSelector`,bindings:{up:`messageSelector:up`,down:`messageSelector:down`,k:`messageSelector:up`,j:`messageSelector:down`,"ctrl+p":`messageSelector:up`,"ctrl+n":`messageSelector:down`,"ctrl+up":`messageSelector:top`,"shift+up":`messageSelector:top`,"meta+up":`messageSelector:top`,"shift+k":`messageSelector:top`,"ctrl+down":`messageSelector:bottom`,"shift+down":`messageSelector:bottom`,"meta+down":`messageSelector:bottom`,"shift+j":`messageSelector:bottom`,enter:`messageSelector:select`}},{context:`DiffDialog`,bindings:{escape:`diff:dismiss`,left:`diff:previousSource`,right:`diff:nextSource`,up:`diff:previousFile`,down:`diff:nextFile`,enter:`diff:viewDetails`}},{context:`ModelPicker`,bindings:{space:`modelPicker:toggle1M`}},{context:`Select`,bindings:{up:`select:previous`,down:`select:next`,j:`select:next`,k:`select:previous`,"ctrl+n":`select:next`,"ctrl+p":`select:previous`,enter:`select:accept`,escape:`select:cancel`}},{context:`Plugin`,bindings:{space:`plugin:toggle`,i:`plugin:install`}}]})),Fp=n((()=>{ct()}));function Gde(){let e=io(),t=[...Lp,...Rp];return e===`macos`&&t.push(...zp),t}function Ip(e){return e.trim().split(/\s+/).map(Kde).join(` `)}function Kde(e){let t=e.split(`+`),n=[],r=``;for(let e of t){let t=e.trim().toLowerCase();[`ctrl`,`control`,`alt`,`opt`,`option`,`meta`,`cmd`,`command`,`shift`].includes(t)?t===`control`?n.push(`ctrl`):t===`option`||t===`opt`?n.push(`alt`):t===`command`||t===`cmd`?n.push(`cmd`):n.push(t):r=t}return n.sort(),[...n,r].join(`+`)}var Lp,Rp,zp,Bp=n((()=>{ao(),Lp=[{key:`ctrl+c`,reason:`Cannot be rebound - used for interrupt/exit (hardcoded)`,severity:`error`},{key:`ctrl+d`,reason:`Cannot be rebound - used for exit (hardcoded)`,severity:`error`},{key:`ctrl+m`,reason:`Cannot be rebound - identical to Enter in terminals (both send CR)`,severity:`error`}],Rp=[{key:`ctrl+z`,reason:`Unix process suspend (SIGTSTP)`,severity:`warning`},{key:`ctrl+\\`,reason:`Terminal quit signal (SIGQUIT)`,severity:`error`}],zp=[{key:`cmd+c`,reason:`macOS system copy`,severity:`error`},{key:`cmd+v`,reason:`macOS system paste`,severity:`error`},{key:`cmd+x`,reason:`macOS system cut`,severity:`error`},{key:`cmd+q`,reason:`macOS quit application`,severity:`error`},{key:`cmd+w`,reason:`macOS close window/tab`,severity:`error`},{key:`cmd+tab`,reason:`macOS app switcher`,severity:`error`},{key:`cmd+space`,reason:`macOS Spotlight`,severity:`error`}]}));function qde(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.context==`string`&&typeof t.bindings==`object`&&t.bindings!==null}function Jde(e){return Array.isArray(e)&&e.every(qde)}function Yde(e){return Up.includes(e)}function Xde(e){let t=e.toLowerCase().split(`+`);for(let n of t)if(!n.trim())return{type:`parse_error`,severity:`error`,message:`Empty key part in "${e}"`,key:e,suggestion:`Remove extra "+" characters`};let n=it(e);return!n.key&&!n.ctrl&&!n.alt&&!n.shift&&!n.meta?{type:`parse_error`,severity:`error`,message:`Could not parse keystroke "${e}"`,key:e}:null}function Zde(e,t){let n=[];if(typeof e!=`object`||!e)return n.push({type:`parse_error`,severity:`error`,message:`Keybinding block ${t+1} is not an object`}),n;let r=e,i=r.context,a;if(typeof i==`string`?Yde(i)?a=i:n.push({type:`invalid_context`,severity:`error`,message:`Unknown context "${i}"`,context:i,suggestion:`Valid contexts: ${Up.join(`, `)}`}):n.push({type:`parse_error`,severity:`error`,message:`Keybinding block ${t+1} missing "context" field`}),typeof r.bindings!=`object`||r.bindings===null)return n.push({type:`parse_error`,severity:`error`,message:`Keybinding block ${t+1} missing "bindings" field`}),n;let o=r.bindings;for(let[e,t]of Object.entries(o)){let r=Xde(e);r&&(r.context=a,n.push(r)),t!==null&&typeof t!=`string`?n.push({type:`invalid_action`,severity:`error`,message:`Invalid action for "${e}": must be a string or null`,key:e,context:a}):typeof t==`string`&&t.startsWith(`command:`)&&(/^command:[a-zA-Z0-9:\-_]+$/.test(t)||n.push({type:`invalid_action`,severity:`warning`,message:`Invalid command binding "${t}" for "${e}": command name may only contain alphanumeric characters, colons, hyphens, and underscores`,key:e,context:a,action:t}),a&&a!==`Chat`&&n.push({type:`invalid_action`,severity:`warning`,message:`Command binding "${t}" must be in "Chat" context, not "${a}"`,key:e,context:a,action:t,suggestion:`Move this binding to a block with "context": "Chat"`}))}return n}function Vp(e){let t=[],n=/"bindings"\s*:\s*\{([^{}]*(?:\{[^{}]*\}[^{}]*)*)\}/g,r;for(;(r=n.exec(e))!==null;){let n=r[1];if(!n)continue;let i=e.slice(0,r.index).match(/"context"\s*:\s*"([^"]+)"[^{]*$/)?.[1]??`unknown`,a=/"([^"]+)"\s*:/g,o=new Map,s;for(;(s=a.exec(n))!==null;){let e=s[1];if(!e)continue;let n=(o.get(e)??0)+1;o.set(e,n),n===2&&t.push({type:`duplicate`,severity:`warning`,message:`Duplicate key "${e}" in ${i} bindings`,key:e,context:i,suggestion:`This key appears multiple times in the same context. JSON uses the last value, earlier values are ignored.`})}}return t}function Qde(e){let t=[];if(!Array.isArray(e))return t.push({type:`parse_error`,severity:`error`,message:`keybindings.json must contain an array`,suggestion:`Wrap your bindings in [ ]`}),t;for(let n=0;n<e.length;n++)t.push(...Zde(e[n],n));return t}function $de(e){let t=[],n=new Map;for(let r of e){let e=n.get(r.context)??new Map;n.set(r.context,e);for(let[n,i]of Object.entries(r.bindings)){let a=Ip(n),o=e.get(a);o&&o!==i&&t.push({type:`duplicate`,severity:`warning`,message:`Duplicate binding "${n}" in ${r.context} context`,key:n,context:r.context,action:i??`null (unbind)`,suggestion:`Previously bound to "${o}". Only the last binding will be used.`}),e.set(a,i??`null`)}}return t}function efe(e){let t=[],n=Gde();for(let r of e){let e=Tee(r.chord),i=Ip(e);for(let a of n)Ip(a.key)===i&&t.push({type:`reserved`,severity:a.severity,message:`"${e}" may not work: ${a.reason}`,key:e,context:r.context,action:r.action??void 0})}return t}function tfe(e){let t=[];for(let n of e)for(let[e,r]of Object.entries(n.bindings)){let i=e.split(` `).map(e=>it(e));t.push({chord:i,action:r,context:n.context})}return t}function Hp(e,t){let n=[];if(n.push(...Qde(e)),Jde(e)){n.push(...$de(e));let t=tfe(e);n.push(...efe(t))}let r=new Set;return n.filter(e=>{let t=`${e.type}:${e.key}:${e.context}`;return r.has(t)?!1:(r.add(t),!0)})}var Up,nfe=n((()=>{Fp(),Bp(),Up=[`Global`,`Chat`,`Autocomplete`,`Confirmation`,`Help`,`Transcript`,`HistorySearch`,`Task`,`ThemePicker`,`Settings`,`Tabs`,`Attachments`,`Footer`,`FormField`,`MessageActions`,`MessageSelector`,`DiffDialog`,`ModelPicker`,`Scroll`,`Select`,`Plugin`]}));function Wp(){return!1}function Gp(e){let t=new Date().toISOString().slice(0,10);am!==t&&(am=t,Y(`tengu_custom_keybindings_loaded`,{user_binding_count:e}))}function rfe(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.context==`string`&&typeof t.bindings==`object`&&t.bindings!==null}function Kp(e){return Array.isArray(e)&&e.every(rfe)}function qp(){return X(m(),`keybindings.json`)}function Jp(){return st(Np)}async function ife(){let e=Jp();if(!Wp())return{bindings:e,warnings:[]};let t=qp();try{let n=await tl(t,`utf-8`),r=$n(n),i;if(typeof r==`object`&&r&&`bindings`in r)i=r.bindings;else{let t=`keybindings.json must have a "bindings" array`;return G(`[keybindings] Invalid keybindings.json: ${t}`),{bindings:e,warnings:[{type:`parse_error`,severity:`error`,message:t,suggestion:`Use format: { "bindings": [ ... ] }`}]}}if(!Kp(i)){let t=Array.isArray(i)?`keybindings.json contains invalid block structure`:`"bindings" must be an array`,n=Array.isArray(i)?`Each block must have "context" (string) and "bindings" (object)`:`Set "bindings" to an array of keybinding blocks`;return G(`[keybindings] Invalid keybindings.json: ${t}`),{bindings:e,warnings:[{type:`parse_error`,severity:`error`,message:t,suggestion:n}]}}let a=st(i);G(`[keybindings] Loaded ${a.length} user bindings from ${t}`);let o=[...e,...a];Gp(a.length);let s=[...Vp(n),...Hp(i,o)];return s.length>0&&G(`[keybindings] Found ${s.length} validation issue(s)`),{bindings:o,warnings:s}}catch(n){return Qn(n)?{bindings:e,warnings:[]}:(G(`[keybindings] Error loading ${t}: ${W(n)}`),{bindings:e,warnings:[{type:`parse_error`,severity:`error`,message:`Failed to parse keybindings.json: ${W(n)}`}]})}}function afe(){return nm||Yp().bindings}function Yp(){if(nm)return{bindings:nm,warnings:rm};let e=Jp();if(!Wp())return nm=e,rm=[],{bindings:nm,warnings:rm};let t=qp();try{let n=zc(t,`utf-8`),r=$n(n),i;if(typeof r==`object`&&r&&`bindings`in r)i=r.bindings;else return nm=e,rm=[{type:`parse_error`,severity:`error`,message:`keybindings.json must have a "bindings" array`,suggestion:`Use format: { "bindings": [ ... ] }`}],{bindings:nm,warnings:rm};if(!Kp(i)){let t=Array.isArray(i)?`keybindings.json contains invalid block structure`:`"bindings" must be an array`,n=Array.isArray(i)?`Each block must have "context" (string) and "bindings" (object)`:`Set "bindings" to an array of keybinding blocks`;return nm=e,rm=[{type:`parse_error`,severity:`error`,message:t,suggestion:n}],{bindings:nm,warnings:rm}}let a=st(i);return G(`[keybindings] Loaded ${a.length} user bindings from ${t}`),nm=[...e,...a],Gp(a.length),rm=[...Vp(n),...Hp(i,nm)],rm.length>0&&G(`[keybindings] Found ${rm.length} validation issue(s)`),{bindings:nm,warnings:rm}}catch{return nm=e,rm=[],{bindings:nm,warnings:rm}}}async function ofe(){if(em||tm)return;if(!Wp()){G(`[keybindings] Skipping file watcher - user customization disabled`);return}let e=qp(),t=xc(e);try{if(!(await ol(t)).isDirectory()){G(`[keybindings] Not watching: ${t} is not a directory`);return}}catch{G(`[keybindings] Not watching: ${t} does not exist`);return}em=!0,G(`[keybindings] Watching for changes to ${e}`),$p=Tp.watch(e,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:Zp,pollInterval:Qp},ignorePermissionErrors:!0,usePolling:!1,atomic:!0}),$p.on(`add`,Xp),$p.on(`change`,Xp),$p.on(`unlink`,cfe),ar(async()=>sfe())}function sfe(){tm=!0,$p&&($p.close(),$p=null),im.clear()}async function Xp(e){G(`[keybindings] Detected change to ${e}`);try{let e=await ife();nm=e.bindings,rm=e.warnings,im.emit(e)}catch(e){G(`[keybindings] Error reloading: ${W(e)}`)}}function cfe(e){G(`[keybindings] Detected deletion of ${e}`);let t=Jp();nm=t,rm=[],im.emit({bindings:t,warnings:[]})}function lfe(){return rm}var Zp,Qp,$p,em,tm,nm,rm,im,am,om,sm=n((()=>{Ep(),oo(),Hn(),K(),g(),qn(),Xt(),mr(),Pp(),Fp(),nfe(),Zp=500,Qp=200,$p=null,em=!1,tm=!1,nm=null,rm=[],im=Dn(),am=null,om=im.subscribe})),cm,ufe=n((()=>{sm(),cm={name:`keybindings`,description:`打开或创建你的 keybindings 配置文件`,isEnabled:()=>Wp(),supportsNonInteractive:!1,type:`local`,load:()=>import(`./keybindings-DZrF9iNd.js`)}})),lm,dfe=n((()=>{lm={type:`local-jsx`,name:`mcp`,description:`管理 MCP 服务器`,immediate:!0,argumentHint:`[enable|disable [server-name]]`,load:()=>import(`./mcp-ChF12reQ.js`)}})),um,ffe=n((()=>{um={type:`local-jsx`,name:`onboarding`,description:`重新运行首次启动的初始化(主题、信任、模型、MCP)`,argumentHint:`[full|theme|trust|model|mcp|status]`,isEnabled:()=>!0,isHidden:!1,load:async()=>({call:(await import(`./launchOnboarding-DmMoZwv5.js`)).callOnboarding})}})),dm,pfe=n((()=>{dm={type:`local-jsx`,name:`rename`,description:`重命名当前会话`,immediate:!0,argumentHint:`[name]`,load:()=>import(`./rename-DyEfsZiq.js`)}})),fm,mfe=n((()=>{fm={type:`local-jsx`,name:`resume`,description:`恢复之前的会话`,aliases:[`continue`],argumentHint:`[conversation id or search term]`,load:()=>import(`./resume-BcXEDUqZ.js`)}})),pm,hfe=n((()=>{pm={type:`local-jsx`,name:`skills`,description:`列出可用的 skill`,load:()=>import(`./skills-BE5scC-g.js`)}})),mm,gfe=n((()=>{mm={type:`local-jsx`,name:`status`,description:`显示 Work Mate 的状态,包括版本、模型、账号、API 连通性与工具状态`,immediate:!0,load:()=>import(`./status-Dw09WZLd.js`)}})),hm,_fe=n((()=>{hm={type:`local-jsx`,name:`tasks`,aliases:[`bashes`],description:`列出并管理后台任务`,load:()=>import(`./tasks-DdcUQEeD.js`)}})),gm,vfe=n((()=>{gm={type:`local-jsx`,name:`local-memory`,aliases:[`lm`],description:`管理本地记忆存储,用于笔记和上下文。存放在 ~/.workmate/local-memory/——无需 API key`,argumentHint:`list | create STORE | store STORE KEY VALUE | fetch STORE KEY | entries STORE | archive STORE`,isHidden:!1,isEnabled:()=>!0,load:async()=>({call:(await import(`./launchLocalMemory-DhJ56KDc.js`)).callLocalMemory})}})),_m,yfe=n((()=>{Ii(),_m={type:`local-jsx`,name:`terminal-setup`,description:$r.terminal===`Apple_Terminal`?`启用 Option+Enter 换行键绑定和视觉响铃`:`安装 Shift+Enter 换行键绑定`,isHidden:$r.terminal!==null&&$r.terminal in{ghostty:`Ghostty`,kitty:`Kitty`,"iTerm.app":`iTerm2`,WezTerm:`WezTerm`},load:()=>import(`./terminalSetup-qc2PlvOm.js`)}})),vm,bfe=n((()=>{vm={type:`local-jsx`,name:`theme`,description:`切换主题`,load:()=>import(`./theme-f1h2QI8J.js`)}})),ym,xfe=n((()=>{ym={name:`vim`,description:`在 Vim 与普通编辑模式之间切换`,supportsNonInteractive:!1,type:`local`,load:()=>import(`./vim-CoRp9lY1.js`)}})),bm=i({activateProactive:()=>Cm,deactivateProactive:()=>wm,getActivationSource:()=>Sfe,getNextTickAt:()=>jm,isContextBlocked:()=>km,isProactiveActive:()=>Sm,isProactivePaused:()=>Tm,pauseProactive:()=>Em,resumeProactive:()=>Dm,setContextBlocked:()=>Om,setNextTickAt:()=>Am,shouldTick:()=>Nm,subscribeToProactiveChanges:()=>Mm});function xm(){for(let e of zm)try{e()}catch{}}function Sm(){return Pm}function Cm(e){Pm||(Pm=!0,Fm=!1,Im=!1,Rm=e,xm())}function wm(){Pm&&(Pm=!1,Fm=!1,Im=!1,Lm=null,Rm=void 0,xm())}function Tm(){return Fm}function Em(){!Pm||Fm||(Fm=!0,Lm=null,xm())}function Dm(){!Pm||!Fm||(Fm=!1,xm())}function Om(e){Im!==e&&(Im=e,e&&(Lm=null),xm())}function km(){return Im}function Am(e){Lm=e,xm()}function jm(){return!Pm||Fm||Im?null:Lm}function Sfe(){return Rm}function Mm(e){return zm.add(e),()=>{zm.delete(e)}}function Nm(){return Pm&&!Fm&&!Im}var Pm,Fm,Im,Lm,Rm,zm,Bm=n((()=>{Pm=!1,Fm=!1,Im=!1,Lm=null,zm=new Set})),Vm,Cfe=n((()=>{Vm={type:`local-jsx`,name:`proactive`,description:`切换主动(autonomous)模式`,isEnabled:()=>!0,immediate:!0,load:()=>Promise.resolve({async call(t,n){let r=(Bm(),e(bm));return r.isProactiveActive()?(r.deactivateProactive(),t(`Proactive mode disabled`,{display:`system`})):(r.activateProactive(`slash_command`),t(`Proactive mode enabled — model will work autonomously between ticks`,{display:`system`,metaMessages:[`<system-reminder>
|
|
390
390
|
Proactive mode is now enabled. You will receive periodic <tick> prompts. Do useful work on each tick, or call Sleep if there is nothing to do. Do not output "still waiting" — either act or sleep.
|
|
391
|
-
</system-reminder>`]})),null}})}})),Hm,wfe=n((()=>{Hm={type:`local-jsx`,name:`job`,description:`管理模板作业(job)`,argumentHint:`[list|new|reply|status]`,isEnabled:()=>!0,load:()=>import(`./job-
|
|
391
|
+
</system-reminder>`]})),null}})}})),Hm,wfe=n((()=>{Hm={type:`local-jsx`,name:`job`,description:`管理模板作业(job)`,argumentHint:`[list|new|reply|status]`,isEnabled:()=>!0,load:()=>import(`./job-YhJQWgE0.js`)}})),Um,Tfe=n((()=>{Um={type:`local-jsx`,name:`goal`,description:`设置或查看一个持久化 goal,用于驱动跨轮次的自动续作`,argumentHint:`[<objective> | status | clear | pause | resume | complete]`,load:()=>import(`./goal-CdL29Y8C.js`)}})),Wm,Efe=n((()=>{Wm={type:`local-jsx`,name:`permissions`,aliases:[`allowed-tools`],description:`管理允许 / 拒绝的工具权限规则`,load:()=>import(`./permissions-DmGFViHI.js`)}})),Gm,Dfe=n((()=>{Gm={type:`local-jsx`,name:`plan`,description:`启用 plan 模式或查看当前会话的 plan`,argumentHint:`[open|<description>]`,load:()=>import(`./plan-CzGBz_87.js`)}}));function Km(){return!1}var qm=n((()=>{})),Jm,Ofe=n((()=>{xo(),qm(),Jm={type:`local-jsx`,name:`fast`,get description(){return`Toggle fast mode (${Lie} only)`},availability:[`claude-ai`,`console`],isEnabled:()=>yo(),get isHidden(){return!yo()},argumentHint:`[on|off]`,get immediate(){return Km()},load:()=>import(`./fast-bopOPrtf.js`)}})),Ym,kfe=n((()=>{Ym={type:`local-jsx`,name:`hooks`,description:`查看工具事件的 hook 配置`,immediate:!0,load:()=>import(`./hooks-DR3IYPJ3.js`)}})),Xm,Afe=n((()=>{Xm={type:`local-jsx`,name:`branch`,aliases:[`fork`],description:`从当前时间点为当前会话创建一个分支`,argumentHint:`[name]`,load:()=>import(`./branch-Yg_taNlT.js`)}})),Zm,jfe=n((()=>{Zm={type:`local-jsx`,name:`agents`,description:`管理智能体(agent)配置`,load:()=>import(`./agents-CGaCQeLw.js`)}})),Qm,Mfe=n((()=>{Qm={type:`local-jsx`,name:`plugin`,aliases:[`plugins`,`marketplace`],description:`管理 Work Mate 插件`,immediate:!0,load:()=>import(`./plugin-CluR79xX.js`)}})),$m,Nfe=n((()=>{$m={type:`local`,name:`reload-plugins`,description:`在当前会话激活待生效的插件改动`,supportsNonInteractive:!1,load:()=>import(`./reload-plugins-CQZFQLWP.js`)}})),eh,Pfe=n((()=>{eh={description:`把代码和/或对话恢复到之前的某个时间点`,name:`rewind`,aliases:[`checkpoint`],argumentHint:``,type:`local`,supportsNonInteractive:!1,load:()=>import(`./rewind-D12hCfZD.js`)}})),th,nh,Ffe=n((()=>{th=async()=>({type:`text`,value:`0.0.24 (built 2026-08-26T10:41:05.156Z)`}),nh={type:`local`,name:`version`,description:`打印当前会话运行的版本(不是 autoupdate 下载的版本)`,isEnabled:()=>!0,supportsNonInteractive:!0,load:()=>Promise.resolve({call:th})}})),rh=i({isSkillSearchCompiledIn:()=>ih,isSkillSearchEnabled:()=>ah});function ih(){return!1}function ah(){return process.env.SKILL_SEARCH_ENABLED===`1`}var oh=n((()=>{})),sh,Ife=n((()=>{oh(),sh={type:`local-jsx`,name:`skill-search`,description:`控制对话过程中自动进行的 skill 匹配`,argumentHint:`[start|stop|about|status]`,isEnabled:()=>ih(),isHidden:!1,load:()=>import(`./skillSearchPanel-C_5yUhqn.js`)}}));function Z(e,t){if(!process.env.SRT_DEBUG)return;let n=t?.level||`info`,r=`[SandboxDebug]`;switch(n){case`error`:console.error(`${r} ${e}`);break;case`warn`:console.warn(`${r} ${e}`);break;default:console.error(`${r} ${e}`)}}var ch=n((()=>{}));function lh(e){let t=e?.http??process.env.HTTP_PROXY??process.env.http_proxy??void 0,n=e?.https??process.env.HTTPS_PROXY??process.env.https_proxy??t,r=e?.noProxy??process.env.NO_PROXY??process.env.no_proxy??``;if(!t&&!n)return;let i=e=>{if(!e)return;let t=/^[a-z][a-z0-9+.-]*:\/\//i.test(e)?e:`http://${e}`;try{let e=new bl(t);if(e.protocol!==`http:`&&e.protocol!==`https:`||!e.hostname)throw Error(`unsupported scheme or empty host`);return e}catch{Z(`Invalid parent proxy URL, ignoring: ${Rfe(e)}`,{level:`error`});return}},a=i(t),o=i(n);if(!(!a&&!o))return{httpUrl:a,httpsUrl:o,noProxy:Lfe(r)}}function Lfe(e){let t={all:!1,suffixes:[],cidr:new qce};for(let n of e.split(`,`)){if(n=n.trim(),!n)continue;if(n===`*`){t.all=!0;continue}let e=n.indexOf(`/`);if(e!==-1){let r=n.slice(0,e),i=n.slice(e+1),a=Sl(r);if(a&&i!==``&&/^\d+$/.test(i)){let e=Number(i);if(e>=0&&e<=(a===6?128:32)){try{t.cidr.addSubnet(r,e,a===6?`ipv6`:`ipv4`)}catch{}continue}}continue}let r=n.toLowerCase(),i=/^\[([^\]]+)\](?::\d+)?$/.exec(r);i&&(r=i[1]),r.startsWith(`*.`)&&(r=r.slice(1));let a=Sl(r);if(a)try{t.cidr.addAddress(r,a===6?`ipv6`:`ipv4`);continue}catch{}else{let e=r.lastIndexOf(`:`);e!==-1&&/^\d+$/.test(r.slice(e+1))&&(r=r.slice(0,e))}t.suffixes.push(r)}return t}function uh(e,t){let n=gh(t.toLowerCase().replace(/\.$/,``));if(n===`localhost`)return!0;let r=Sl(n);if(r&&Sh.check(n,r===6?`ipv6`:`ipv4`)||e.noProxy.all||r&&e.noProxy.cidr.check(n,r===6?`ipv6`:`ipv4`))return!0;for(let t of e.noProxy.suffixes)if(t.startsWith(`.`)){if(n===t.slice(1)||n.endsWith(t))return!0}else if(n===t||n.endsWith(`.`+t))return!0;return!1}function dh(e,t){return t.isHttps?e.httpsUrl??e.httpUrl:e.httpUrl}function fh(e){let{destHost:t,destPort:n}=e,r=gh(t);if(!vh(r))return Promise.reject(Error(`Invalid destination host for CONNECT: ${JSON.stringify(t)}`));if(!Number.isInteger(n)||n<1||n>65535)return Promise.reject(Error(`Invalid destination port: ${n}`));let i=Sl(r)===6?`[${r}]:${n}`:`${r}:${n}`;return new Promise((t,n)=>{let r=e.dial(),a=!1,o=e=>{a||(a=!0,r.destroy(),n(e))},s=()=>o(Error(`Proxy closed during CONNECT handshake`));r.setTimeout(e.timeoutMs??bh,()=>o(Error(`CONNECT handshake timed out`))),r.once(`error`,o),r.once(`close`,s),r.once(e.readyEvent,()=>{r.write(`CONNECT ${i} HTTP/1.1\r\nHost: ${i}\r\n`+(e.authHeader?`Proxy-Authorization: ${e.authHeader}\r\n`:``)+`\r
|
|
392
392
|
`);let n=``,c=e=>{n+=e.toString(`latin1`);let i=n.indexOf(`\r
|
|
393
393
|
\r
|
|
394
394
|
`);if(i===-1){n.length>16*1024&&o(Error(`CONNECT response header too large`));return}r.pause(),r.removeListener(`data`,c);let l=n.slice(0,n.indexOf(`\r
|
|
@@ -412,7 +412,7 @@ Connection blocked by network allowlist`);return}let c=e.getMitmSocketPath?.(o),
|
|
|
412
412
|
`);return`${o} -c ${s_.quote([i])}`}else{let e=[...s,`eval ${s_.quote([n])}`].join(`
|
|
413
413
|
`);return`${o} -c ${s_.quote([e])}`}}async function Npe(e,t,n={command:`rg`},r=c_,i=!1,a){let o=[],s=[],c=[];if(t){o.push(`--ro-bind`,`/`,`/`);for(let e of t.allowOnly||[]){let t=Hg(e);if(Z(`[Sandbox Linux] Processing write path: ${e} -> ${t}`),t.startsWith(`/dev/`)){Z(`[Sandbox Linux] Skipping /dev path: ${t}`);continue}if(!Lc.existsSync(t)){Z(`[Sandbox Linux] Skipping non-existent write path: ${t}`);continue}try{let n=Lc.realpathSync(t);if(n!==t.replace(/\/+$/,``)&&Vg(t,n)){Z(`[Sandbox Linux] Skipping symlink write path pointing outside expected location: ${e} -> ${n}`);continue}}catch{Z(`[Sandbox Linux] Skipping write path that could not be resolved: ${t}`);continue}o.push(`--bind`,t,t),s.push(t)}let e=[...t.denyWithinAllow||[],...await kpe(n,r,i,a)],l=new Set;for(let t of e){let e=Hg(t);if(l.has(e)||(l.add(e),e.startsWith(`/dev/`)))continue;let n=Epe(e,s);if(n){c.push(`--ro-bind`,`/dev/null`,n),Z(`[Sandbox Linux] Mounted /dev/null at symlink ${n} to prevent symlink replacement attack`);continue}if(!Lc.existsSync(e)){if(Dpe(e)){Z(`[Sandbox Linux] Skipping deny path with file ancestor (cannot create paths under a file): ${e}`);continue}let t=Nc.dirname(e);for(;t!==`/`&&!Lc.existsSync(t);)t=Nc.dirname(t);if(s.some(n=>t.startsWith(n+`/`)||t===n||e.startsWith(n+`/`))){let t=Ope(e);if(t!==e){let n=Lc.mkdtempSync(Nc.join(Gc(),`claude-empty-`));c.push(`--ro-bind`,n,t),u_.add(t),a_(),Z(`[Sandbox Linux] Mounted empty dir at ${t} to block creation of ${e}`)}else c.push(`--ro-bind`,`/dev/null`,t),u_.add(t),a_(),Z(`[Sandbox Linux] Mounted /dev/null at ${t} to block creation of ${e}`)}else Z(`[Sandbox Linux] Skipping non-existent deny path not within allowed paths: ${e}`);continue}s.some(t=>e.startsWith(t+`/`)||e===t)?c.push(`--ro-bind`,e,e):Z(`[Sandbox Linux] Skipping deny path not within allowed paths: ${e}`)}}else o.push(`--bind`,`/`,`/`);let l=[],u=(e?.allowWithinDeny||[]).map(e=>Hg(e)),d=new Set([`proc`,`dev`,`sys`]);for(let t of e?.denyOnly||[])if(Hg(t)===`/`)for(let e of Lc.readdirSync(`/`))d.has(e)||l.push(`/`+e);else l.push(t);Lc.existsSync(`/etc/ssh/ssh_config.d`)&&l.push(`/etc/ssh/ssh_config.d`);for(let e of l){let t=Hg(e);if(!Lc.existsSync(t)){Z(`[Sandbox Linux] Skipping non-existent read deny path: ${t}`);continue}let n=t===`/`?`/`:t+`/`;if(Lc.statSync(t).isDirectory()){o.push(`--tmpfs`,t);for(let e of s)(e.startsWith(n)||e===t)&&(o.push(`--bind`,e,e),Z(`[Sandbox Linux] Re-bound write path wiped by denyRead tmpfs: ${e}`));for(let e of u)if(e.startsWith(n)||e===t){if(!Lc.existsSync(e)){Z(`[Sandbox Linux] Skipping non-existent read allow path: ${e}`);continue}if(s.some(r=>(r.startsWith(n)||r===t)&&(e===r||e.startsWith(r+`/`))))continue;o.push(`--ro-bind`,e,e),Z(`[Sandbox Linux] Re-allowed read access within denied region: ${e}`)}}else{if(u.some(e=>t===e||t.startsWith(e+`/`))){Z(`[Sandbox Linux] Skipping read deny for re-allowed path: ${t}`);continue}o.push(`--ro-bind`,`/dev/null`,t)}}return o.push(...c),o}async function Ppe(e){let{command:t,needsNetworkRestriction:n,httpSocketPath:r,socksSocketPath:i,httpProxyPort:a,socksProxyPort:o,readConfig:s,writeConfig:c,enableWeakerNestedSandbox:l,allowAllUnixSockets:u,binShell:d,ripgrepConfig:f={command:`rg`},mandatoryDenySearchDepth:p=c_,allowGitConfig:m=!1,seccompConfig:h,abortSignal:g}=e,_=s&&s.denyOnly.length>0,v=c!==void 0;if(!n&&!_&&!v)return t;let y=[`--new-session`,`--die-with-parent`],b;try{if(u)Z(`[Sandbox Linux] Skipping seccomp filter - allowAllUnixSockets is enabled`);else{b=wpe(h?.bpfPath)??void 0;let e=t_(h?.applyPath);!b||!e?(Z(`[Sandbox Linux] Seccomp binaries not available - unix socket blocking disabled. Install @anthropic-ai/sandbox-runtime globally for full protection.`,{level:`warn`}),b=void 0):(b.includes(`/vendor/seccomp/`)||(l_.add(b),a_()),Z(`[Sandbox Linux] Generated seccomp BPF filter for Unix socket blocking`))}if(n&&(y.push(`--unshare-net`),r&&i)){if(!Lc.existsSync(r))throw Error(`Linux HTTP bridge socket does not exist: ${r}. The bridge process may have died. Try reinitializing the sandbox.`);if(!Lc.existsSync(i))throw Error(`Linux SOCKS bridge socket does not exist: ${i}. The bridge process may have died. Try reinitializing the sandbox.`);y.push(`--bind`,r,r),y.push(`--bind`,i,i);let e=Wg(3128,1080);y.push(...e.flatMap(e=>{let t=e.indexOf(`=`);return[`--setenv`,e.slice(0,t),e.slice(t+1)]})),a!==void 0&&y.push(`--setenv`,`CLAUDE_CODE_HOST_HTTP_PROXY_PORT`,String(a)),o!==void 0&&y.push(`--setenv`,`CLAUDE_CODE_HOST_SOCKS_PROXY_PORT`,String(o))}let e=await Npe(s,c,f,p,m,g);y.push(...e),y.push(`--dev`,`/dev`),y.push(`--unshare-pid`),l||y.push(`--proc`,`/proc`);let x=d||`bash`,S=kh(x);if(!S)throw Error(`Shell '${x}' not found in PATH`);if(y.push(`--`,S,`-c`),n&&r&&i){let e=Mpe(r,i,t,b,S,h?.applyPath);y.push(e)}else if(b){let e=t_(h?.applyPath);if(!e)throw Error(`apply-seccomp binary not found. This should have been caught earlier. Ensure vendor/seccomp/{x64,arm64}/apply-seccomp binaries are included in the package.`);let n=s_.quote([e,b,S,`-c`,t]);y.push(n)}else y.push(t);let C=s_.quote([`bwrap`,...y]),w=[];return n&&w.push(`network`),(_||v)&&w.push(`filesystem`),b&&w.push(`seccomp(unix-block)`),Z(`[Sandbox Linux] Wrapped command with bwrap (${w.join(`, `)} restrictions)`),C}catch(e){throw b&&!b.includes(`/vendor/seccomp/`)&&l_.delete(b),e}}var s_,c_,l_,u_,d_,Fpe=n((()=>{s_=r(Ig(),1),ch(),Ah(),bpe(),Xg(),Tpe(),c_=3,l_=new Set,u_=new Set,d_=!1}));function Ipe(e=!1){let t=process.cwd(),n=[];for(let e of Jg)n.push(yc.resolve(t,e)),n.push(`**/${e}`);for(let e of Lg())n.push(yc.resolve(t,e)),n.push(`**/${e}/**`);return n.push(yc.resolve(t,`.git/hooks`)),n.push(`**/.git/hooks/**`),e||(n.push(yc.resolve(t,`.git/config`)),n.push(`**/.git/config`)),[...new Set(n)]}function Lpe(e){return`CMD64_${Gg(e)}_END_${g_}`}function f_(e){let t=[],n=yc.dirname(e);for(;n!==`/`&&n!==`.`;){t.push(n);let e=yc.dirname(n);if(e===n)break;n=e}return t}function p_(e,t){let n=[];for(let r of e){let e=Hg(r);if(zg(e)){let r=Kg(e);n.push(`(deny file-write-unlink`,` (regex ${m_(r)})`,` (with message "${t}"))`);let i=e.split(/[*?[\]]/)[0];if(i&&i!==`/`){let e=i.endsWith(`/`)?i.slice(0,-1):yc.dirname(i);n.push(`(deny file-write-unlink`,` (literal ${m_(e)})`,` (with message "${t}"))`);for(let r of f_(e))n.push(`(deny file-write-unlink`,` (literal ${m_(r)})`,` (with message "${t}"))`)}}else{n.push(`(deny file-write-unlink`,` (subpath ${m_(e)})`,` (with message "${t}"))`);for(let r of f_(e))n.push(`(deny file-write-unlink`,` (literal ${m_(r)})`,` (with message "${t}"))`)}}return n}function Rpe(e,t){if(!e)return[`(allow file-read*)`];let n=[],r=!1;n.push(`(allow file-read*)`);for(let i of e.denyOnly||[]){let e=Hg(i);if(e===`/`&&(r=!0),zg(e)){let r=Kg(e);n.push(`(deny file-read*`,` (regex ${m_(r)})`,` (with message "${t}"))`)}else n.push(`(deny file-read*`,` (subpath ${m_(e)})`,` (with message "${t}"))`)}r&&n.push(`(allow file-read* (literal "/"))`);for(let r of e.allowWithinDeny||[]){let e=Hg(r);if(zg(e)){let r=Kg(e);n.push(`(allow file-read*`,` (regex ${m_(r)})`,` (with message "${t}"))`)}else n.push(`(allow file-read*`,` (subpath ${m_(e)})`,` (with message "${t}"))`)}return e.denyOnly.length>0&&n.push(`(allow file-read-metadata`,` (vnode-type DIRECTORY))`),n.push(...p_(e.denyOnly||[],t)),n}function zpe(e,t,n=!1){if(!e)return[`(allow file-write*)`];let r=[];for(let n of e.allowOnly||[]){let e=Hg(n);if(zg(e)){let n=Kg(e);r.push(`(allow file-write*`,` (regex ${m_(n)})`,` (with message "${t}"))`)}else r.push(`(allow file-write*`,` (subpath ${m_(e)})`,` (with message "${t}"))`)}let i=[...e.denyWithinAllow||[],...Ipe(n)];for(let e of i){let n=Hg(e);if(zg(n)){let e=Kg(n);r.push(`(deny file-write*`,` (regex ${m_(e)})`,` (with message "${t}"))`)}else r.push(`(deny file-write*`,` (subpath ${m_(n)})`,` (with message "${t}"))`)}return r.push(...p_(i,t)),r}function Bpe({readConfig:e,writeConfig:t,httpProxyPort:n,socksProxyPort:r,needsNetworkRestriction:i,allowUnixSockets:a,allowAllUnixSockets:o,allowLocalBinding:s,allowPty:c,allowGitConfig:l=!1,enableWeakerNetworkIsolation:u=!1,logTag:d}){let f=[`(version 1)`,`(deny default (with message "${d}"))`,``,`; LogTag: ${d}`,``,`; Essential permissions - based on Chrome sandbox policy`,`; Process permissions`,`(allow process-exec)`,`(allow process-fork)`,`(allow process-info* (target same-sandbox))`,`(allow signal (target same-sandbox))`,`(allow mach-priv-task-port (target same-sandbox))`,``,`; User preferences`,`(allow user-preference-read)`,``,`; Mach IPC - specific services only (no wildcard)`,`(allow mach-lookup`,` (global-name "com.apple.audio.systemsoundserver")`,` (global-name "com.apple.distributed_notifications@Uv3")`,` (global-name "com.apple.FontObjectsServer")`,` (global-name "com.apple.fonts")`,` (global-name "com.apple.logd")`,` (global-name "com.apple.lsd.mapdb")`,` (global-name "com.apple.PowerManagement.control")`,` (global-name "com.apple.system.logger")`,` (global-name "com.apple.system.notification_center")`,` (global-name "com.apple.system.opendirectoryd.libinfo")`,` (global-name "com.apple.system.opendirectoryd.membership")`,` (global-name "com.apple.bsd.dirhelper")`,` (global-name "com.apple.securityd.xpc")`,` (global-name "com.apple.coreservices.launchservicesd")`,`)`,``,...u?[`; trustd.agent - needed for Go TLS certificate verification (weaker network isolation)`,`(allow mach-lookup (global-name "com.apple.trustd.agent"))`]:[],``,`; POSIX IPC - shared memory`,`(allow ipc-posix-shm)`,``,`; POSIX IPC - semaphores for Python multiprocessing`,`(allow ipc-posix-sem)`,``,`; IOKit - specific operations only`,`(allow iokit-open`,` (iokit-registry-entry-class "IOSurfaceRootUserClient")`,` (iokit-registry-entry-class "RootDomainUserClient")`,` (iokit-user-client-class "IOSurfaceSendRight")`,`)`,``,`; IOKit properties`,`(allow iokit-get-properties)`,``,`; Specific safe system-sockets, doesn't allow network access`,`(allow system-socket (require-all (socket-domain AF_SYSTEM) (socket-protocol 2)))`,``,`; sysctl - specific sysctls only`,`(allow sysctl-read`,` (sysctl-name "hw.activecpu")`,` (sysctl-name "hw.busfrequency_compat")`,` (sysctl-name "hw.byteorder")`,` (sysctl-name "hw.cacheconfig")`,` (sysctl-name "hw.cachelinesize_compat")`,` (sysctl-name "hw.cpufamily")`,` (sysctl-name "hw.cpufrequency")`,` (sysctl-name "hw.cpufrequency_compat")`,` (sysctl-name "hw.cputype")`,` (sysctl-name "hw.l1dcachesize_compat")`,` (sysctl-name "hw.l1icachesize_compat")`,` (sysctl-name "hw.l2cachesize_compat")`,` (sysctl-name "hw.l3cachesize_compat")`,` (sysctl-name "hw.logicalcpu")`,` (sysctl-name "hw.logicalcpu_max")`,` (sysctl-name "hw.machine")`,` (sysctl-name "hw.memsize")`,` (sysctl-name "hw.ncpu")`,` (sysctl-name "hw.nperflevels")`,` (sysctl-name "hw.packages")`,` (sysctl-name "hw.pagesize_compat")`,` (sysctl-name "hw.pagesize")`,` (sysctl-name "hw.physicalcpu")`,` (sysctl-name "hw.physicalcpu_max")`,` (sysctl-name "hw.tbfrequency_compat")`,` (sysctl-name "hw.vectorunit")`,` (sysctl-name "kern.argmax")`,` (sysctl-name "kern.bootargs")`,` (sysctl-name "kern.hostname")`,` (sysctl-name "kern.maxfiles")`,` (sysctl-name "kern.maxfilesperproc")`,` (sysctl-name "kern.maxproc")`,` (sysctl-name "kern.ngroups")`,` (sysctl-name "kern.osproductversion")`,` (sysctl-name "kern.osrelease")`,` (sysctl-name "kern.ostype")`,` (sysctl-name "kern.osvariant_status")`,` (sysctl-name "kern.osversion")`,` (sysctl-name "kern.secure_kernel")`,` (sysctl-name "kern.tcsm_available")`,` (sysctl-name "kern.tcsm_enable")`,` (sysctl-name "kern.usrstack64")`,` (sysctl-name "kern.version")`,` (sysctl-name "kern.willshutdown")`,` (sysctl-name "machdep.cpu.brand_string")`,` (sysctl-name "machdep.ptrauth_enabled")`,` (sysctl-name "security.mac.lockdown_mode_state")`,` (sysctl-name "sysctl.proc_cputype")`,` (sysctl-name "vm.loadavg")`,` (sysctl-name-prefix "hw.optional.arm")`,` (sysctl-name-prefix "hw.optional.arm.")`,` (sysctl-name-prefix "hw.optional.armv8_")`,` (sysctl-name-prefix "hw.perflevel")`,` (sysctl-name-prefix "kern.proc.all")`,` (sysctl-name-prefix "kern.proc.pgrp.")`,` (sysctl-name-prefix "kern.proc.pid.")`,` (sysctl-name-prefix "machdep.cpu.")`,` (sysctl-name-prefix "net.routetable.")`,`)`,``,`; V8 thread calculations`,`(allow sysctl-write`,` (sysctl-name "kern.tcsm_enable")`,`)`,``,`; Distributed notifications`,`(allow distributed-notification-post)`,``,`; Specific mach-lookup permissions for security operations`,`(allow mach-lookup (global-name "com.apple.SecurityServer"))`,``,`; File I/O on device files`,`(allow file-ioctl (literal "/dev/null"))`,`(allow file-ioctl (literal "/dev/zero"))`,`(allow file-ioctl (literal "/dev/random"))`,`(allow file-ioctl (literal "/dev/urandom"))`,`(allow file-ioctl (literal "/dev/dtracehelper"))`,`(allow file-ioctl (literal "/dev/tty"))`,``,`(allow file-ioctl file-read-data file-write-data`,` (require-all`,` (literal "/dev/null")`,` (vnode-type CHARACTER-DEVICE)`,` )`,`)`,``];if(f.push(`; Network`),!i)f.push(`(allow network*)`);else{if(s&&(f.push(`(allow network-bind (local ip "*:*"))`),f.push(`(allow network-inbound (local ip "*:*"))`),f.push(`(allow network-outbound (local ip "*:*"))`)),o)f.push(`(allow system-socket (socket-domain AF_UNIX))`),f.push(`(allow network-bind (local unix-socket (path-regex #"^/")))`),f.push(`(allow network-outbound (remote unix-socket (path-regex #"^/")))`);else if(a&&a.length>0){f.push(`(allow system-socket (socket-domain AF_UNIX))`);for(let e of a){let t=Hg(e);f.push(`(allow network-bind (local unix-socket (subpath ${m_(t)})))`),f.push(`(allow network-outbound (remote unix-socket (subpath ${m_(t)})))`)}}n!==void 0&&(f.push(`(allow network-bind (local ip "localhost:${n}"))`),f.push(`(allow network-inbound (local ip "localhost:${n}"))`),f.push(`(allow network-outbound (remote ip "localhost:${n}"))`)),r!==void 0&&(f.push(`(allow network-bind (local ip "localhost:${r}"))`),f.push(`(allow network-inbound (local ip "localhost:${r}"))`),f.push(`(allow network-outbound (remote ip "localhost:${r}"))`))}return f.push(``),f.push(`; File read`),f.push(...Rpe(e,d)),f.push(``),f.push(`; File write`),f.push(...zpe(t,d,l)),c&&(f.push(``),f.push(`; Pseudo-terminal (pty) support`),f.push(`(allow pseudo-tty)`),f.push(`(allow file-ioctl`),f.push(` (literal "/dev/ptmx")`),f.push(` (regex #"^/dev/ttys")`),f.push(`)`),f.push(`(allow file-read* file-write*`),f.push(` (literal "/dev/ptmx")`),f.push(` (regex #"^/dev/ttys")`),f.push(`)`)),f.join(`
|
|
414
414
|
`)}function m_(e){return JSON.stringify(e)}function Vpe(e){let{command:t,needsNetworkRestriction:n,httpProxyPort:r,socksProxyPort:i,allowUnixSockets:a,allowAllUnixSockets:o,allowLocalBinding:s,readConfig:c,writeConfig:l,allowPty:u,allowGitConfig:d=!1,enableWeakerNetworkIsolation:f=!1,binShell:p}=e,m=c&&c.denyOnly.length>0;if(!n&&!m&&l===void 0)return t;let h=Bpe({readConfig:c,writeConfig:l,httpProxyPort:r,socksProxyPort:i,needsNetworkRestriction:n,allowUnixSockets:a,allowAllUnixSockets:o,allowLocalBinding:s,allowPty:u,allowGitConfig:d,enableWeakerNetworkIsolation:f,logTag:Lpe(t)}),g=Wg(r,i),_=p||`bash`,v=kh(_);if(!v)throw Error(`Shell '${_}' not found in PATH`);let y=h_.quote([`env`,...g,`sandbox-exec`,`-p`,h,v,`-c`,t]);return Z(`[Sandbox macOS] Applied restrictions - network: ${!!(r||i)}, read: ${c?`allowAllExcept`in c?`allowAllExcept`:`denyAllExcept`:`none`}, write: ${l?`allowAllExcept`in l?`allowAllExcept`:`denyAllExcept`:`none`}`),y}function Hpe(e,t){let n=/CMD64_(.+?)_END/,r=/Sandbox:\s+(.+)$/,i=t?.[`*`]||[],a=t?Object.entries(t).filter(([e])=>e!==`*`):[],o=dl(`log`,[`stream`,`--predicate`,`(eventMessage ENDSWITH "${g_}")`,`--style`,`compact`]);return o.stdout?.on(`data`,o=>{let s=o.toString().split(`
|
|
415
|
-
`),c=s.find(e=>e.includes(`Sandbox:`)&&e.includes(`deny`)),l=s.find(e=>e.startsWith(`CMD64_`));if(!c)return;let u=c.match(r);if(!u?.[1])return;let d=u[1],f,p;if(l&&(p=l.match(n)?.[1],p))try{f=xpe(p)}catch{}if(!(d.includes(`mDNSResponder`)||d.includes(`mach-lookup com.apple.diagnosticd`)||d.includes(`mach-lookup com.apple.analyticsd`))){if(t&&f){if(i.length>0&&i.some(e=>d.includes(e)))return;for(let[e,t]of a)if(f.includes(e)&&t.some(e=>d.includes(e)))return}e({line:d,command:f,encodedCommand:p,timestamp:new Date})}}),o.stderr?.on(`data`,e=>{Z(`[Sandbox Monitor] Log stream stderr: ${e.toString()}`)}),o.on(`error`,e=>{Z(`[Sandbox Monitor] Failed to start log stream: ${e.message}`)}),o.on(`exit`,e=>{Z(`[Sandbox Monitor] Log stream exited with code: ${e}`)}),()=>{Z(`[Sandbox Monitor] Stopping log monitor`),o.kill(`SIGTERM`)}}var h_,g_,Upe=n((()=>{h_=r(Ig(),1),ch(),Ah(),Xg(),g_=`_${Math.random().toString(36).slice(2,11)}_SBX`})),__,v_=n((()=>{Xg(),__=class{constructor(){this.violations=[],this.totalCount=0,this.maxSize=100,this.listeners=new Set}addViolation(e){this.violations.push(e),this.totalCount++,this.violations.length>this.maxSize&&(this.violations=this.violations.slice(-this.maxSize)),this.notifyListeners()}getViolations(e){return e===void 0?[...this.violations]:this.violations.slice(-e)}getCount(){return this.violations.length}getTotalCount(){return this.totalCount}getViolationsForCommand(e){let t=Gg(e);return this.violations.filter(e=>e.encodedCommand===t)}clear(){this.violations=[],this.notifyListeners()}subscribe(e){return this.listeners.add(e),e(this.getViolations()),()=>{this.listeners.delete(e)}}notifyListeners(){let e=this.getViolations();this.listeners.forEach(t=>t(e))}}}));function Wpe(){if(D_)return;let e=()=>x_().catch(e=>{Z(`Cleanup failed in registerCleanup ${e}`,{level:`error`})});process.once(`exit`,e),process.once(`SIGINT`,e),process.once(`SIGTERM`,e),D_=!0}function y_(e,t){let n=e.toLowerCase();if(t.startsWith(`*.`)){if(Sl(gh(n)))return!1;let e=t.substring(2).toLowerCase();return n.endsWith(`.`+e)}return n===t.toLowerCase()}async function b_(e,t,n){if(!S_)return Z(`No config available, denying network request`),!1;if(!vh(t))return Z(`Denying malformed host: ${JSON.stringify(t)}:${e}`,{level:`error`}),!1;let r=zfe(t)??t;for(let n of S_.network.deniedDomains)if(y_(r,n))return Z(`Denied by config rule: ${t}:${e}`),!1;for(let n of S_.network.allowedDomains)if(y_(r,n))return Z(`Allowed by config rule: ${t}:${e}`),!0;if(!n)return Z(`No matching config rule, denying: ${t}:${e}`),!1;Z(`No matching config rule, asking user: ${t}:${e}`);try{return await n({host:t,port:e})?(Z(`User allowed: ${t}:${e}`),!0):(Z(`User denied: ${t}:${e}`),!1)}catch(e){return Z(`Error in permission callback: ${e}`,{level:`error`}),!1}}function Gpe(e){if(!S_?.network.mitmProxy)return;let{socketPath:t,domains:n}=S_.network.mitmProxy;for(let r of n)if(y_(e,r))return Z(`Host ${e} matches MITM pattern ${r}`),t}async function Kpe(e){return C_=Bfe({filter:(t,n)=>b_(t,n,e),getMitmSocketPath:Gpe,parentProxy:k_}),new Promise((e,t)=>{if(!C_){t(Error(`HTTP proxy server undefined before listen`));return}let n=C_;n.once(`error`,t),n.once(`listening`,()=>{let r=n.address();r&&typeof r==`object`?(n.unref(),Z(`HTTP proxy listening on localhost:${r.port}`),e(r.port)):t(Error(`Failed to get proxy server address`))}),n.listen(0,`127.0.0.1`)})}async function qpe(e){return w_=Gfe({filter:(t,n)=>b_(t,n,e),parentProxy:k_}),new Promise((e,t)=>{if(!w_){t(Error(`SOCKS proxy server undefined before listen`));return}w_.listen(0,`127.0.0.1`).then(t=>{w_?.unref(),e(t)}).catch(t)})}async function Jpe(e,t,n=!1){if(E_){await E_;return}S_=e,k_=lh(e.network.parentProxy),k_&&Z(`Parent proxy configured: http=${_h(k_.httpUrl)} https=${_h(k_.httpsUrl)}`);let r=Zpe();if(r.errors.length>0)throw Error(`Sandbox dependencies not available: ${r.errors.join(`, `)}`);n&&Pg()===`macos`&&(O_=Hpe(A_.addViolation.bind(A_),S_.ignoreViolations),Z(`Started macOS sandbox log monitor`)),Wpe(),E_=(async()=>{try{let e;S_.network.httpProxyPort===void 0?e=await Kpe(t):(e=S_.network.httpProxyPort,Z(`Using external HTTP proxy on port ${e}`));let n;S_.network.socksProxyPort===void 0?n=await qpe(t):(n=S_.network.socksProxyPort,Z(`Using external SOCKS proxy on port ${n}`));let r;Pg()===`linux`&&(r=await jpe(e,n));let i={httpProxyPort:e,socksProxyPort:n,linuxBridge:r};return T_=i,Z(`Network infrastructure initialized`),i}catch(e){throw E_=void 0,T_=void 0,x_().catch(e=>{Z(`Cleanup failed in initializationPromise ${e}`,{level:`error`})}),e}})(),await E_}function Ype(){let e=Pg();return e===`linux`?gpe()!==`1`:e===`macos`}function Xpe(){return S_!==void 0}function Zpe(e){if(!Ype())return{errors:[`Unsupported platform`],warnings:[]};let t=[],n=[],r=e??S_?.ripgrep??{command:`rg`};if(kh(r.command)===null&&t.push(`ripgrep (${r.command}) not found`),Pg()===`linux`){let e=Ape(S_?.seccomp);t.push(...e.errors),n.push(...e.warnings)}return{errors:t,warnings:n}}function Qpe(){if(!S_)return{denyOnly:[],allowWithinDeny:[]};let e=[];for(let t of S_.filesystem.denyRead){let n=Bg(t);if(Pg()===`linux`&&zg(n)){let n=qg(t);Z(`[Sandbox] Expanded glob pattern "${t}" to ${n.length} paths on Linux`),e.push(...n)}else e.push(n)}let t=[];for(let e of S_.filesystem.allowRead??[]){let n=Bg(e);if(Pg()===`linux`&&zg(n)){let n=qg(e);Z(`[Sandbox] Expanded allowRead glob pattern "${e}" to ${n.length} paths on Linux`),t.push(...n)}else t.push(n)}return{denyOnly:e,allowWithinDeny:t}}function $pe(){if(!S_)return{allowOnly:Ug(),denyWithinAllow:[]};let e=S_.filesystem.allowWrite.map(e=>Bg(e)).filter(e=>Pg()===`linux`&&zg(e)?(Z(`Skipping glob pattern on Linux/WSL: ${e}`),!1):!0),t=S_.filesystem.denyWrite.map(e=>Bg(e)).filter(e=>Pg()===`linux`&&zg(e)?(Z(`Skipping glob pattern on Linux/WSL: ${e}`),!1):!0);return{allowOnly:[...Ug(),...e],denyWithinAllow:t}}function eme(){if(!S_)return{};let e=S_.network.allowedDomains,t=S_.network.deniedDomains;return{...e.length>0&&{allowedHosts:e},...t.length>0&&{deniedHosts:t}}}function tme(){return S_?.network?.allowUnixSockets}function nme(){return S_?.network?.allowAllUnixSockets}function rme(){return S_?.network?.allowLocalBinding}function ime(){return S_?.ignoreViolations}function ame(){return S_?.enableWeakerNestedSandbox}function ome(){return S_?.enableWeakerNetworkIsolation}function sme(){return S_?.ripgrep??{command:`rg`}}function cme(){return S_?.mandatoryDenySearchDepth??3}function lme(){return S_?.filesystem?.allowGitConfig??!1}function ume(){return S_?.seccomp}function dme(){return T_?.httpProxyPort}function fme(){return T_?.socksProxyPort}function pme(){return T_?.linuxBridge?.httpSocketPath}function mme(){return T_?.linuxBridge?.socksSocketPath}async function hme(){if(!S_)return!1;if(E_)try{return await E_,!0}catch{return!1}return T_!==void 0}async function gme(e,t,n,r){let i=Pg(),a=e=>e.map(e=>Bg(e)).filter(e=>Pg()===`linux`&&zg(e)?(Z(`[Sandbox] Skipping glob write pattern on Linux: ${e}`),!1):!0),o=a(n?.filesystem?.allowWrite??S_?.filesystem.allowWrite??[]),s={allowOnly:[...Ug(),...o],denyWithinAllow:a(n?.filesystem?.denyWrite??S_?.filesystem.denyWrite??[])},c=n?.filesystem?.denyRead??S_?.filesystem.denyRead??[],l=[];for(let e of c){let t=Bg(e);Pg()===`linux`&&zg(t)?l.push(...qg(e)):l.push(t)}let u=n?.filesystem?.allowRead??S_?.filesystem.allowRead??[],d=[];for(let e of u){let t=Bg(e);Pg()===`linux`&&zg(t)?d.push(...qg(e)):d.push(t)}let f={denyOnly:l,allowWithinDeny:d},p=n?.network?.allowedDomains!==void 0||S_?.network?.allowedDomains!==void 0,m=p,h=p;h&&await hme();let g=n?.allowPty??S_?.allowPty;switch(i){case`macos`:return Vpe({command:e,needsNetworkRestriction:m,httpProxyPort:h?dme():void 0,socksProxyPort:h?fme():void 0,readConfig:f,writeConfig:s,allowUnixSockets:tme(),allowAllUnixSockets:nme(),allowLocalBinding:rme(),ignoreViolations:ime(),allowPty:g,allowGitConfig:lme(),enableWeakerNetworkIsolation:ome(),binShell:t});case`linux`:return Ppe({command:e,needsNetworkRestriction:m,httpSocketPath:h?pme():void 0,socksSocketPath:h?mme():void 0,httpProxyPort:h?T_?.httpProxyPort:void 0,socksProxyPort:h?T_?.socksProxyPort:void 0,readConfig:f,writeConfig:s,enableWeakerNestedSandbox:ame(),allowAllUnixSockets:nme(),binShell:t,ripgrepConfig:sme(),mandatoryDenySearchDepth:cme(),allowGitConfig:lme(),seccompConfig:ume(),abortSignal:r});default:throw Error(`Sandbox configuration is not supported on platform: ${i}`)}}function _me(){return S_}function vme(e){S_=Tue(e),k_=lh(e.network.parentProxy),Z(`Sandbox configuration updated`)}function yme(){o_()}async function x_(){if(yme(),O_&&(O_(),O_=void 0),T_?.linuxBridge){let{httpSocketPath:e,socksSocketPath:t,httpBridgeProcess:n,socksBridgeProcess:r}=T_.linuxBridge,i=[];if(n.pid&&!n.killed)try{process.kill(n.pid,`SIGTERM`),Z(`Sent SIGTERM to HTTP bridge process`),i.push(new Promise(e=>{n.once(`exit`,()=>{Z(`HTTP bridge process exited`),e()}),setTimeout(()=>{if(!n.killed){Z(`HTTP bridge did not exit, forcing SIGKILL`,{level:`warn`});try{n.pid&&process.kill(n.pid,`SIGKILL`)}catch{}}e()},5e3)}))}catch(e){e.code!==`ESRCH`&&Z(`Error killing HTTP bridge: ${e}`,{level:`error`})}if(r.pid&&!r.killed)try{process.kill(r.pid,`SIGTERM`),Z(`Sent SIGTERM to SOCKS bridge process`),i.push(new Promise(e=>{r.once(`exit`,()=>{Z(`SOCKS bridge process exited`),e()}),setTimeout(()=>{if(!r.killed){Z(`SOCKS bridge did not exit, forcing SIGKILL`,{level:`warn`});try{r.pid&&process.kill(r.pid,`SIGKILL`)}catch{}}e()},5e3)}))}catch(e){e.code!==`ESRCH`&&Z(`Error killing SOCKS bridge: ${e}`,{level:`error`})}if(await Promise.all(i),e)try{Lc.rmSync(e,{force:!0}),Z(`Cleaned up HTTP socket`)}catch(e){Z(`HTTP socket cleanup error: ${e}`,{level:`error`})}if(t)try{Lc.rmSync(t,{force:!0}),Z(`Cleaned up SOCKS socket`)}catch(e){Z(`SOCKS socket cleanup error: ${e}`,{level:`error`})}}let e=[];if(C_){let t=C_,n=new Promise(e=>{t.close(t=>{t&&t.message!==`Server is not running.`&&Z(`Error closing HTTP proxy server: ${t.message}`,{level:`error`}),e()})});e.push(n)}if(w_){let t=w_.close().catch(e=>{Z(`Error closing SOCKS proxy server: ${e.message}`,{level:`error`})});e.push(t)}await Promise.all(e),C_=void 0,w_=void 0,T_=void 0,E_=void 0,k_=void 0}function bme(){return A_}function xme(e,t){if(!S_)return t;let n=A_.getViolationsForCommand(e);if(n.length===0)return t;let r=t;r+=Wc+`<sandbox_violations>`+Wc;for(let e of n)r+=e.line+Wc;return r+=`</sandbox_violations>`,r}function Sme(){if(Pg()!==`linux`||!S_)return[];let e=[],t=[...S_.filesystem.allowWrite,...S_.filesystem.denyWrite];for(let n of t)zg(Bg(n))&&e.push(n);return e}var S_,C_,w_,T_,E_,D_,O_,k_,A_,j_,Cme=n((()=>{Hfe(),Kfe(),ch(),Ah(),Ng(),Fg(),Fpe(),Upe(),Xg(),v_(),Ch(),D_=!1,A_=new __,j_={initialize:Jpe,isSupportedPlatform:Ype,isSandboxingEnabled:Xpe,checkDependencies:Zpe,getFsReadConfig:Qpe,getFsWriteConfig:$pe,getNetworkRestrictionConfig:eme,getAllowUnixSockets:tme,getAllowLocalBinding:rme,getIgnoreViolations:ime,getEnableWeakerNestedSandbox:ame,getProxyPort:dme,getSocksProxyPort:fme,getLinuxHttpSocketPath:pme,getLinuxSocksSocketPath:mme,waitForNetworkInitialization:hme,wrapWithSandbox:gme,cleanupAfterCommand:yme,reset:x_,getSandboxViolationStore:bme,annotateStderrWithSandboxFailures:xme,getLinuxGlobPatternWarnings:Sme,getConfig:_me,updateConfig:vme}})),M_,N_,wme,Tme,Eme,Dme,Ome,kme,Ame,jme=n((()=>{N(),M_=j().refine(e=>{if(e.includes(`://`)||e.includes(`/`)||e.includes(`:`))return!1;if(e===`localhost`)return!0;if(e.startsWith(`*.`)){let t=e.slice(2);if(!t.includes(`.`)||t.startsWith(`.`)||t.endsWith(`.`))return!1;let n=t.split(`.`);return n.length>=2&&n.every(e=>e.length>0)}return!e.includes(`*`)&&e.includes(`.`)&&!e.startsWith(`.`)&&!e.endsWith(`.`)},{message:`Invalid domain pattern. Must be a valid domain (e.g., "example.com") or wildcard (e.g., "*.example.com"). Overly broad patterns like "*.com" or "*" are not allowed for security reasons.`}),N_=j().min(1,`Path cannot be empty`),wme=se({socketPath:j().min(1).describe(`Unix socket path to the MITM proxy`),domains:M(M_).min(1).describe(`Domains to route through the MITM proxy (e.g., ["api.example.com", "*.internal.org"])`)}),Tme=se({http:j().url().optional().describe(`Upstream proxy URL for plain HTTP traffic`),https:j().url().optional().describe(`Upstream proxy URL for HTTPS/CONNECT traffic (falls back to http if unset)`),noProxy:j().optional().describe(`Comma-separated NO_PROXY list (hostname suffixes and CIDR ranges). Matching destinations connect directly instead of via the parent proxy.`)}),Eme=se({allowedDomains:M(M_).describe(`List of allowed domains (e.g., ["github.com", "*.npmjs.org"])`),deniedDomains:M(M_).describe(`List of denied domains`),allowUnixSockets:M(j()).optional().describe(`macOS only: Unix socket paths to allow. Ignored on Linux (seccomp cannot filter by path).`),allowAllUnixSockets:oe().optional().describe(`If true, allow all Unix sockets (disables blocking on both platforms).`),allowLocalBinding:oe().optional().describe(`Whether to allow binding to local ports (default: false)`),httpProxyPort:ae().int().min(1).max(65535).optional().describe(`Port of an external HTTP proxy to use instead of starting a local one. When provided, the library will skip starting its own HTTP proxy and use this port. The external proxy must handle domain filtering.`),socksProxyPort:ae().int().min(1).max(65535).optional().describe(`Port of an external SOCKS proxy to use instead of starting a local one. When provided, the library will skip starting its own SOCKS proxy and use this port. The external proxy must handle domain filtering.`),mitmProxy:wme.optional().describe(`Optional MITM proxy configuration. Routes matching domains through an upstream proxy via Unix socket while SRT still handles allow/deny filtering.`),parentProxy:Tme.optional().describe(`Upstream HTTP proxy for outbound connections. When set, SRT's proxy tunnels non-mitmProxy traffic through this parent instead of connecting directly. Falls back to HTTP_PROXY/HTTPS_PROXY/NO_PROXY env vars if unset.`)}),Dme=se({denyRead:M(N_).describe(`Paths denied for reading`),allowRead:M(N_).optional().describe(`Paths to re-allow reading within denied regions (takes precedence over denyRead). Use with denyRead to deny a broad region then allow back specific subdirectories.`),allowWrite:M(N_).describe(`Paths allowed for writing`),denyWrite:M(N_).describe(`Paths denied for writing (takes precedence over allowWrite)`),allowGitConfig:oe().optional().describe(`Allow writes to .git/config files (default: false). Enables git remote URL updates while keeping .git/hooks protected.`)}),Ome=le(j(),M(j())).describe(`Map of command patterns to filesystem paths to ignore violations for. Use "*" to match all commands`),kme=se({command:j().describe(`The ripgrep command to execute`),args:M(j()).optional().describe(`Additional arguments to pass before ripgrep args`),argv0:j().optional().describe(`Override argv[0] when spawning (for multicall binaries that dispatch on argv[0])`)}),Ame=se({bpfPath:j().optional().describe(`Path to the unix-block.bpf filter file`),applyPath:j().optional().describe(`Path to the apply-seccomp binary`)}),se({network:Eme.describe(`Network restrictions configuration`),filesystem:Dme.describe(`Filesystem restrictions configuration`),ignoreViolations:Ome.optional().describe(`Optional configuration for ignoring specific violations`),enableWeakerNestedSandbox:oe().optional().describe(`Enable weaker nested sandbox mode (for Docker environments)`),enableWeakerNetworkIsolation:oe().optional().describe(`Enable weaker network isolation to allow access to com.apple.trustd.agent (macOS only). This is needed for Go programs (gh, gcloud, terraform, kubectl, etc.) to verify TLS certificates when using httpProxyPort with a MITM proxy and custom CA. Enabling this opens a potential data exfiltration vector through the trustd service. Only enable if you need Go TLS verification.`),ripgrep:kme.optional().describe(`Custom ripgrep configuration (default: { command: "rg" })`),mandatoryDenySearchDepth:ae().int().min(1).max(10).optional().describe(`Maximum directory depth to search for dangerous files on Linux (default: 3). Higher values provide more protection but slower performance.`),allowPty:oe().optional().describe(`Allow pseudo-terminal (pty) operations (macOS only)`),seccomp:Ame.optional().describe(`Custom seccomp binary paths (Linux only).`)})})),Mme=n((()=>{Cme(),v_(),jme(),Xg(),Fg()}));async function Nme(){if(z_||B_)return;z_=!0,Bme(),ar(Pme);let{dirs:e,settingsFiles:t,dropInDir:n}=await Fme();B_||e.length!==0&&(G(`Watching for changes in setting files ${[...t].join(`, `)}...${n?` and drop-in directory ${n}`:``}`),I_=Tp.watch(e,{persistent:!0,ignoreInitial:!0,depth:0,awaitWriteFinish:{stabilityThreshold:U_?.stabilityThreshold??Ume,pollInterval:U_?.pollInterval??Wme},ignored:(e,r)=>{if(r&&!r.isFile()&&!r.isDirectory()||e.split(yc.sep).some(e=>e===`.git`))return!0;if(!r||r.isDirectory())return!1;let i=yc.normalize(e);return!(t.has(i)||n&&i.startsWith(n+yc.sep)&&i.endsWith(`.json`))},ignorePermissionErrors:!0,usePolling:!1,atomic:!0}),I_.on(`change`,Lme),I_.on(`unlink`,zme),I_.on(`add`,Rme))}function Pme(){B_=!0,L_&&(clearInterval(L_),L_=null);for(let e of V_.values())clearTimeout(e);V_.clear(),R_=null,Tne(),H_.clear();let e=I_;return I_=null,e?e.close():Promise.resolve()}async function Fme(){let e=new Map,t=new Set;for(let n of ki){if(n===`flagSettings`)continue;let r=ji(n);if(!r)continue;let i=yc.dirname(r);e.has(i)||e.set(i,new Set),e.get(i).add(r);try{(await ol(r)).isFile()&&t.add(i)}catch{}}let n=new Set;for(let r of t){let t=e.get(r);if(t)for(let e of t)n.add(e)}let r=null,i=ii();try{(await ol(i)).isDirectory()&&(t.add(i),r=i)}catch{}return{dirs:[...t],settingsFiles:n,dropInDir:r}}function Ime(e){switch(e){case`userSettings`:return`user_settings`;case`projectSettings`:return`project_settings`;case`localSettings`:return`local_settings`;case`flagSettings`:case`policySettings`:return`policy_settings`}}function Lme(e){let t=P_(e);if(!t)return;let n=V_.get(e);n&&(clearTimeout(n),V_.delete(e),G(`Cancelled pending deletion of ${e} — file was recreated`)),!Sre(e,Gme)&&(G(`Detected change to ${e}`),l7(Ime(t),e).then(n=>{if(r7(n)){G(`ConfigChange hook blocked change to ${e}`);return}F_(t)}))}function Rme(e){if(!P_(e))return;let t=V_.get(e);t&&(clearTimeout(t),V_.delete(e),G(`Cancelled pending deletion of ${e} — file was re-added`)),Lme(e)}function zme(e){let t=P_(e);if(!t||(G(`Detected deletion of ${e}`),V_.has(e)))return;let n=setTimeout((e,t)=>{V_.delete(e),l7(Ime(t),e).then(n=>{if(r7(n)){G(`ConfigChange hook blocked deletion of ${e}`);return}F_(t)})},U_?.deletionGrace??qme,e,t);V_.set(e,n)}function P_(e){let t=yc.normalize(e),n=ii();return t.startsWith(n+yc.sep)?`policySettings`:ki.find(e=>ji(e)===t)}function Bme(){let e=One(),t=Xne();R_=U({mdm:e.settings,hkcu:t.settings}),L_=setInterval(()=>{B_||(async()=>{try{let{mdm:e,hkcu:t}=await Qne();if(B_)return;let n=U({mdm:e.settings,hkcu:t.settings});n!==R_&&(R_=n,Ane(e,t),G(`Detected MDM settings change via poll`),F_(`policySettings`))}catch(e){G(`MDM poll error: ${W(e)}`)}})()},U_?.mdmPollInterval??Kme),L_.unref()}function F_(e){Nn(),H_.emit(e)}function Vme(e){G(`Programmatic settings change notification for ${e}`),F_(e)}function Hme(e){L_&&(clearInterval(L_),L_=null);for(let e of V_.values())clearTimeout(e);V_.clear(),R_=null,z_=!1,B_=!1,U_=e??null;let t=I_;return I_=null,t?t.close():Promise.resolve()}var Ume,Wme,Gme,Kme,qme,I_,L_,R_,z_,B_,V_,H_,U_,Jme,W_,G_=n((()=>{Ep(),Hn(),K(),qn(),g7(),Xt(),mr(),wi(),tie(),Ur(),rie(),vi(),pn(),Ume=1e3,Wme=500,Gme=5e3,Kme=1800*1e3,qme=1700,I_=null,L_=null,R_=null,z_=!1,B_=!1,V_=new Map,H_=Dn(),U_=null,Jme=H_.subscribe,W_={initialize:Nme,dispose:Pme,subscribe:Jme,notifyChange:Vme,resetForTesting:Hme}}));function K_(e){let t=e.match(/^([^(]+)\(([^)]+)\)$/);if(!t)return{toolName:e};let n=t[1],r=t[2];return!n||!r?{toolName:e}:{toolName:n,ruleContent:r}}function Yme(e){return e.match(/^(.+):\*$/)?.[1]??null}function q_(e,t){return e.startsWith(`//`)?e.slice(1):e.startsWith(`/`)&&!e.startsWith(`//`)?Oc(ui(t),e.slice(1)):e}function J_(e,t){return e.startsWith(`//`)?e.slice(1):hi(e,ui(t))}function Y_(){return zi(`policySettings`)?.sandbox?.network?.allowManagedDomainsOnly===!0}function Xme(){return zi(`policySettings`)?.sandbox?.filesystem?.allowManagedReadPathsOnly===!0}function X_(e){let t=e.permissions||{},n=[],r=[];if(Y_()){let e=zi(`policySettings`);for(let t of e?.sandbox?.network?.allowedDomains||[])n.push(t)}else for(let t of e.sandbox?.network?.allowedDomains||[])n.push(t);for(let e of t.deny||[]){let t=K_(e);t.ruleContent?.startsWith(`domain:`)&&r.push(t.ruleContent.substring(7))}let i=[`.`,I8()],a=[],o=[],s=[],c=ki.map(e=>ji(e)).filter(e=>e!==void 0);a.push(...c),a.push(ii());let l=Vt(),u=Yt();l!==u&&(a.push(Oc(l,`.workmate`,`settings.json`)),a.push(Oc(l,`.workmate`,`settings.local.json`))),a.push(Oc(u,`.workmate`,`skills`)),l!==u&&a.push(Oc(l,`.workmate`,`skills`)),rv.length=0;let d=[`HEAD`,`objects`,`refs`,`hooks`,`config`];for(let e of l===u?[u]:[u,l])for(let t of d){let n=Oc(e,t);try{Qse(n),a.push(n)}catch{rv.push(n)}}nv&&nv!==l&&i.push(nv);let f=new Set([...e.permissions?.additionalDirectories||[],...mn()]);i.push(...f);for(let e of ki){let t=zi(e);if(t?.permissions){for(let n of t.permissions.allow||[]){let t=K_(n);t.toolName===`Edit`&&t.ruleContent&&i.push(q_(t.ruleContent,e))}for(let n of t.permissions.deny||[]){let t=K_(n);t.toolName===`Edit`&&t.ruleContent&&a.push(q_(t.ruleContent,e)),t.toolName===`Read`&&t.ruleContent&&o.push(q_(t.ruleContent,e))}}let n=t?.sandbox?.filesystem;if(n){for(let t of n.allowWrite||[])i.push(J_(t,e));for(let t of n.denyWrite||[])a.push(J_(t,e));for(let t of n.denyRead||[])o.push(J_(t,e));if(!Xme()||e===`policySettings`)for(let t of n.allowRead||[])s.push(J_(t,e))}}let{rgPath:p,rgArgs:m,argv0:h}=rc(),g=e.sandbox?.ripgrep??{command:p,args:m,argv0:h};return{network:{allowedDomains:n,deniedDomains:r,allowUnixSockets:e.sandbox?.network?.allowUnixSockets,allowAllUnixSockets:e.sandbox?.network?.allowAllUnixSockets,allowLocalBinding:e.sandbox?.network?.allowLocalBinding,httpProxyPort:e.sandbox?.network?.httpProxyPort,socksProxyPort:e.sandbox?.network?.socksProxyPort},filesystem:{denyRead:o,allowRead:s,allowWrite:i,denyWrite:a},ignoreViolations:e.sandbox?.ignoreViolations,enableWeakerNestedSandbox:e.sandbox?.enableWeakerNestedSandbox,enableWeakerNetworkIsolation:e.sandbox?.enableWeakerNetworkIsolation,ripgrep:g}}function Zme(){for(let e of rv)try{Zse(e,{recursive:!0}),G(`[Sandbox] scrubbed planted bare-repo file: ${e}`)}catch{}}async function Qme(e){let t=X(e,`.git`);try{let n=(await tl(t,{encoding:`utf8`})).match(/^gitdir:\s*(.+)$/m);if(!n?.[1])return null;let r=Oc(e,n[1].trim()),i=`${kc}.git${kc}worktrees${kc}`,a=r.lastIndexOf(i);return a>0?r.substring(0,a):null}catch{return null}}function Z_(){try{return fi()?.sandbox?.enabled??!1}catch(e){return G(`Failed to get settings for sandbox check: ${e}`),!1}}function $me(){return fi()?.sandbox?.autoAllowBashIfSandboxed??!0}function ehe(){return fi()?.sandbox?.allowUnsandboxedCommands??!0}function the(){let e=fi();return Z_()&&(e?.sandbox?.failIfUnavailable??!1)}function Q_(){try{let e=Vi()?.sandbox?.enabledPlatforms;if(e===void 0)return!0;if(e.length===0)return!1;let t=io();return e.includes(t)}catch(e){return G(`Failed to check enabledPlatforms: ${e}`),!0}}function $_(){return!av()||iv().errors.length>0||!Q_()?!1:Z_()}function nhe(){if(!Z_())return;if(!av()){let e=io();return e===`wsl`?`sandbox.enabled is set but WSL1 is not supported (requires WSL2)`:`sandbox.enabled is set but ${e} is not supported (requires macOS, Linux, or WSL2)`}if(!Q_())return`sandbox.enabled is set but ${io()} is not in sandbox.enabledPlatforms`;let e=iv();if(e.errors.length>0){let t=io()===`macos`?`run /sandbox or /doctor for details`:`install missing tools (e.g. apt install bubblewrap socat) or run /sandbox for details`;return`sandbox.enabled is set but dependencies are missing: ${e.errors.join(`, `)} · ${t}`}}function rhe(){let e=io();if(e!==`linux`&&e!==`wsl`)return[];try{let e=fi();if(!e?.sandbox?.enabled)return[];let t=e?.permissions||{},n=[],r=e=>{let t=e.replace(/\/\*\*$/,``);return/[*?[\]]/.test(t)};for(let e of[...t.allow||[],...t.deny||[]]){let t=K_(e);(t.toolName===`Edit`||t.toolName===`Read`)&&t.ruleContent&&r(t.ruleContent)&&n.push(e)}return n}catch(e){return G(`Failed to get Linux glob pattern warnings: ${e}`),[]}}function ihe(){for(let e of[`flagSettings`,`policySettings`]){let t=zi(e);if(t?.sandbox?.enabled!==void 0||t?.sandbox?.autoAllowBashIfSandboxed!==void 0||t?.sandbox?.allowUnsandboxedCommands!==void 0)return!0}return!1}async function ahe(e){li(`localSettings`,{sandbox:{...zi(`localSettings`)?.sandbox,...e.enabled!==void 0&&{enabled:e.enabled},...e.autoAllowBashIfSandboxed!==void 0&&{autoAllowBashIfSandboxed:e.autoAllowBashIfSandboxed},...e.allowUnsandboxedCommands!==void 0&&{allowUnsandboxedCommands:e.allowUnsandboxedCommands}}})}function ohe(){return fi()?.sandbox?.excludedCommands??[]}async function she(e,t,n,r){if($_())if(ev)await ev;else throw Error(`Sandbox failed to initialize. `);return j_.wrapWithSandbox(e,t,n,r)}async function che(e){if(ev)return ev;if(!$_())return;let t=e?async t=>Y_()?(G(`[sandbox] Blocked network request to ${t.host} (allowManagedDomainsOnly)`),!1):e(t):void 0;return ev=(async()=>{try{nv===void 0&&(nv=await Qme(Vt()));let e=X_(fi());await j_.initialize(e,t),tv=W_.subscribe(()=>{let e=X_(fi());j_.updateConfig(e),G(`Sandbox configuration updated from settings change`)})}catch(e){ev=void 0,G(`Failed to initialize sandbox: ${W(e)}`)}})(),ev}function lhe(){if(!$_())return;let e=X_(fi());j_.updateConfig(e)}async function uhe(){return tv?.(),tv=void 0,nv=void 0,rv.length=0,iv.cache.clear?.(),av.cache.clear?.(),ev=void 0,j_.reset()}function dhe(e,t){let n=zi(`localSettings`),r=n?.sandbox?.excludedCommands||[],i=e;if(t){let e=t.filter(e=>e.type===`addRules`&&e.rules.some(e=>e.toolName===`Bash`));if(e.length>0&&e[0].type===`addRules`){let t=e[0].rules.find(e=>e.toolName===Vs);t?.ruleContent&&(i=Yme(t.ruleContent)||t.ruleContent)}}return r.includes(i)||li(`localSettings`,{sandbox:{...n?.sandbox,excludedCommands:[...r,i]}}),i}var ev,tv,nv,rv,iv,av,ov,sv=n((()=>{Mme(),Ng(),Jt(),K(),Ai(),ao(),G_(),wi(),Ur(),vi(),js(),Ls(),Us(),qn(),R8(),nc(),rv=[],iv=u(()=>{let{rgPath:e,rgArgs:t}=rc();return j_.checkDependencies({command:e,args:t})}),av=u(()=>j_.isSupportedPlatform()),ov={initialize:che,isSandboxingEnabled:$_,isSandboxEnabledInSettings:Z_,isPlatformInEnabledList:Q_,getSandboxUnavailableReason:nhe,isAutoAllowBashIfSandboxedEnabled:$me,areUnsandboxedCommandsAllowed:ehe,isSandboxRequired:the,areSandboxSettingsLockedByPolicy:ihe,setSandboxSettings:ahe,getExcludedCommands:ohe,wrapWithSandbox:she,refreshConfig:lhe,reset:uhe,checkDependencies:iv,getFsReadConfig:j_.getFsReadConfig,getFsWriteConfig:j_.getFsWriteConfig,getNetworkRestrictionConfig:j_.getNetworkRestrictionConfig,getIgnoreViolations:j_.getIgnoreViolations,getLinuxGlobPatternWarnings:rhe,isSupportedPlatform:av,getAllowUnixSockets:j_.getAllowUnixSockets,getAllowLocalBinding:j_.getAllowLocalBinding,getEnableWeakerNestedSandbox:j_.getEnableWeakerNestedSandbox,getProxyPort:j_.getProxyPort,getSocksProxyPort:j_.getSocksProxyPort,getLinuxHttpSocketPath:j_.getLinuxHttpSocketPath,getLinuxSocksSocketPath:j_.getLinuxSocksSocketPath,waitForNetworkInitialization:j_.waitForNetworkInitialization,getSandboxViolationStore:j_.getSandboxViolationStore,annotateStderrWithSandboxFailures:j_.annotateStderrWithSandboxFailures,cleanupAfterCommand:()=>{j_.cleanupAfterCommand(),Zme()}}})),fhe,phe=n((()=>{ne(),sv(),fhe={name:`sandbox`,get description(){let e=ov.isSandboxingEnabled(),t=ov.isAutoAllowBashIfSandboxedEnabled(),n=ov.areUnsandboxedCommandsAllowed(),r=ov.areSandboxSettingsLockedByPolicy(),i=ov.checkDependencies().errors.length===0,a;a=i?e?ie.tick:ie.circle:ie.warning;let o=`sandbox disabled`;return e&&(o=t?`sandbox enabled (auto-allow)`:`sandbox enabled`,o+=n?`, fallback allowed`:``),r&&(o+=` (managed)`),`${a} ${o} (⏎ to configure)`},argumentHint:`exclude "command pattern"`,get isHidden(){return!ov.isSupportedPlatform()||!ov.isPlatformInEnabledList()},immediate:!0,type:`local-jsx`,load:()=>import(`./sandbox-toggle-Dir9Polo.js`)}}));function cv(e){return e.type===`advisor_tool_result`||e.type===`server_tool_use`&&e.name===`advisor`}function lv(){return{}}function uv(){return h(process.env.CLAUDE_CODE_DISABLE_ADVISOR_TOOL)||!be()?!1:lv().enabled??!1}function dv(){return uv()&&(lv().canUserConfigure??!1)}function mhe(){let e=lv();return uv()&&!dv()&&e.baseModel&&e.advisorModel?{baseModel:e.baseModel,advisorModel:e.advisorModel}:void 0}function fv(e){let t=e.toLowerCase();return t.includes(`opus-4-7`)||t.includes(`opus-4-6`)||t.includes(`sonnet-4-6`)}function pv(e){let t=e.toLowerCase();return t.includes(`opus-4-7`)||t.includes(`opus-4-6`)||t.includes(`sonnet-4-6`)}function hhe(){if(uv())return Vi().advisorModel}function ghe(e){let t=e.iterations;return t?t.filter(e=>e.type===`advisor_message`):[]}var _he,mv=n((()=>{ve(),g(),vi(),_he=`# Advisor Tool
|
|
415
|
+
`),c=s.find(e=>e.includes(`Sandbox:`)&&e.includes(`deny`)),l=s.find(e=>e.startsWith(`CMD64_`));if(!c)return;let u=c.match(r);if(!u?.[1])return;let d=u[1],f,p;if(l&&(p=l.match(n)?.[1],p))try{f=xpe(p)}catch{}if(!(d.includes(`mDNSResponder`)||d.includes(`mach-lookup com.apple.diagnosticd`)||d.includes(`mach-lookup com.apple.analyticsd`))){if(t&&f){if(i.length>0&&i.some(e=>d.includes(e)))return;for(let[e,t]of a)if(f.includes(e)&&t.some(e=>d.includes(e)))return}e({line:d,command:f,encodedCommand:p,timestamp:new Date})}}),o.stderr?.on(`data`,e=>{Z(`[Sandbox Monitor] Log stream stderr: ${e.toString()}`)}),o.on(`error`,e=>{Z(`[Sandbox Monitor] Failed to start log stream: ${e.message}`)}),o.on(`exit`,e=>{Z(`[Sandbox Monitor] Log stream exited with code: ${e}`)}),()=>{Z(`[Sandbox Monitor] Stopping log monitor`),o.kill(`SIGTERM`)}}var h_,g_,Upe=n((()=>{h_=r(Ig(),1),ch(),Ah(),Xg(),g_=`_${Math.random().toString(36).slice(2,11)}_SBX`})),__,v_=n((()=>{Xg(),__=class{constructor(){this.violations=[],this.totalCount=0,this.maxSize=100,this.listeners=new Set}addViolation(e){this.violations.push(e),this.totalCount++,this.violations.length>this.maxSize&&(this.violations=this.violations.slice(-this.maxSize)),this.notifyListeners()}getViolations(e){return e===void 0?[...this.violations]:this.violations.slice(-e)}getCount(){return this.violations.length}getTotalCount(){return this.totalCount}getViolationsForCommand(e){let t=Gg(e);return this.violations.filter(e=>e.encodedCommand===t)}clear(){this.violations=[],this.notifyListeners()}subscribe(e){return this.listeners.add(e),e(this.getViolations()),()=>{this.listeners.delete(e)}}notifyListeners(){let e=this.getViolations();this.listeners.forEach(t=>t(e))}}}));function Wpe(){if(D_)return;let e=()=>x_().catch(e=>{Z(`Cleanup failed in registerCleanup ${e}`,{level:`error`})});process.once(`exit`,e),process.once(`SIGINT`,e),process.once(`SIGTERM`,e),D_=!0}function y_(e,t){let n=e.toLowerCase();if(t.startsWith(`*.`)){if(Sl(gh(n)))return!1;let e=t.substring(2).toLowerCase();return n.endsWith(`.`+e)}return n===t.toLowerCase()}async function b_(e,t,n){if(!S_)return Z(`No config available, denying network request`),!1;if(!vh(t))return Z(`Denying malformed host: ${JSON.stringify(t)}:${e}`,{level:`error`}),!1;let r=zfe(t)??t;for(let n of S_.network.deniedDomains)if(y_(r,n))return Z(`Denied by config rule: ${t}:${e}`),!1;for(let n of S_.network.allowedDomains)if(y_(r,n))return Z(`Allowed by config rule: ${t}:${e}`),!0;if(!n)return Z(`No matching config rule, denying: ${t}:${e}`),!1;Z(`No matching config rule, asking user: ${t}:${e}`);try{return await n({host:t,port:e})?(Z(`User allowed: ${t}:${e}`),!0):(Z(`User denied: ${t}:${e}`),!1)}catch(e){return Z(`Error in permission callback: ${e}`,{level:`error`}),!1}}function Gpe(e){if(!S_?.network.mitmProxy)return;let{socketPath:t,domains:n}=S_.network.mitmProxy;for(let r of n)if(y_(e,r))return Z(`Host ${e} matches MITM pattern ${r}`),t}async function Kpe(e){return C_=Bfe({filter:(t,n)=>b_(t,n,e),getMitmSocketPath:Gpe,parentProxy:k_}),new Promise((e,t)=>{if(!C_){t(Error(`HTTP proxy server undefined before listen`));return}let n=C_;n.once(`error`,t),n.once(`listening`,()=>{let r=n.address();r&&typeof r==`object`?(n.unref(),Z(`HTTP proxy listening on localhost:${r.port}`),e(r.port)):t(Error(`Failed to get proxy server address`))}),n.listen(0,`127.0.0.1`)})}async function qpe(e){return w_=Gfe({filter:(t,n)=>b_(t,n,e),parentProxy:k_}),new Promise((e,t)=>{if(!w_){t(Error(`SOCKS proxy server undefined before listen`));return}w_.listen(0,`127.0.0.1`).then(t=>{w_?.unref(),e(t)}).catch(t)})}async function Jpe(e,t,n=!1){if(E_){await E_;return}S_=e,k_=lh(e.network.parentProxy),k_&&Z(`Parent proxy configured: http=${_h(k_.httpUrl)} https=${_h(k_.httpsUrl)}`);let r=Zpe();if(r.errors.length>0)throw Error(`Sandbox dependencies not available: ${r.errors.join(`, `)}`);n&&Pg()===`macos`&&(O_=Hpe(A_.addViolation.bind(A_),S_.ignoreViolations),Z(`Started macOS sandbox log monitor`)),Wpe(),E_=(async()=>{try{let e;S_.network.httpProxyPort===void 0?e=await Kpe(t):(e=S_.network.httpProxyPort,Z(`Using external HTTP proxy on port ${e}`));let n;S_.network.socksProxyPort===void 0?n=await qpe(t):(n=S_.network.socksProxyPort,Z(`Using external SOCKS proxy on port ${n}`));let r;Pg()===`linux`&&(r=await jpe(e,n));let i={httpProxyPort:e,socksProxyPort:n,linuxBridge:r};return T_=i,Z(`Network infrastructure initialized`),i}catch(e){throw E_=void 0,T_=void 0,x_().catch(e=>{Z(`Cleanup failed in initializationPromise ${e}`,{level:`error`})}),e}})(),await E_}function Ype(){let e=Pg();return e===`linux`?gpe()!==`1`:e===`macos`}function Xpe(){return S_!==void 0}function Zpe(e){if(!Ype())return{errors:[`Unsupported platform`],warnings:[]};let t=[],n=[],r=e??S_?.ripgrep??{command:`rg`};if(kh(r.command)===null&&t.push(`ripgrep (${r.command}) not found`),Pg()===`linux`){let e=Ape(S_?.seccomp);t.push(...e.errors),n.push(...e.warnings)}return{errors:t,warnings:n}}function Qpe(){if(!S_)return{denyOnly:[],allowWithinDeny:[]};let e=[];for(let t of S_.filesystem.denyRead){let n=Bg(t);if(Pg()===`linux`&&zg(n)){let n=qg(t);Z(`[Sandbox] Expanded glob pattern "${t}" to ${n.length} paths on Linux`),e.push(...n)}else e.push(n)}let t=[];for(let e of S_.filesystem.allowRead??[]){let n=Bg(e);if(Pg()===`linux`&&zg(n)){let n=qg(e);Z(`[Sandbox] Expanded allowRead glob pattern "${e}" to ${n.length} paths on Linux`),t.push(...n)}else t.push(n)}return{denyOnly:e,allowWithinDeny:t}}function $pe(){if(!S_)return{allowOnly:Ug(),denyWithinAllow:[]};let e=S_.filesystem.allowWrite.map(e=>Bg(e)).filter(e=>Pg()===`linux`&&zg(e)?(Z(`Skipping glob pattern on Linux/WSL: ${e}`),!1):!0),t=S_.filesystem.denyWrite.map(e=>Bg(e)).filter(e=>Pg()===`linux`&&zg(e)?(Z(`Skipping glob pattern on Linux/WSL: ${e}`),!1):!0);return{allowOnly:[...Ug(),...e],denyWithinAllow:t}}function eme(){if(!S_)return{};let e=S_.network.allowedDomains,t=S_.network.deniedDomains;return{...e.length>0&&{allowedHosts:e},...t.length>0&&{deniedHosts:t}}}function tme(){return S_?.network?.allowUnixSockets}function nme(){return S_?.network?.allowAllUnixSockets}function rme(){return S_?.network?.allowLocalBinding}function ime(){return S_?.ignoreViolations}function ame(){return S_?.enableWeakerNestedSandbox}function ome(){return S_?.enableWeakerNetworkIsolation}function sme(){return S_?.ripgrep??{command:`rg`}}function cme(){return S_?.mandatoryDenySearchDepth??3}function lme(){return S_?.filesystem?.allowGitConfig??!1}function ume(){return S_?.seccomp}function dme(){return T_?.httpProxyPort}function fme(){return T_?.socksProxyPort}function pme(){return T_?.linuxBridge?.httpSocketPath}function mme(){return T_?.linuxBridge?.socksSocketPath}async function hme(){if(!S_)return!1;if(E_)try{return await E_,!0}catch{return!1}return T_!==void 0}async function gme(e,t,n,r){let i=Pg(),a=e=>e.map(e=>Bg(e)).filter(e=>Pg()===`linux`&&zg(e)?(Z(`[Sandbox] Skipping glob write pattern on Linux: ${e}`),!1):!0),o=a(n?.filesystem?.allowWrite??S_?.filesystem.allowWrite??[]),s={allowOnly:[...Ug(),...o],denyWithinAllow:a(n?.filesystem?.denyWrite??S_?.filesystem.denyWrite??[])},c=n?.filesystem?.denyRead??S_?.filesystem.denyRead??[],l=[];for(let e of c){let t=Bg(e);Pg()===`linux`&&zg(t)?l.push(...qg(e)):l.push(t)}let u=n?.filesystem?.allowRead??S_?.filesystem.allowRead??[],d=[];for(let e of u){let t=Bg(e);Pg()===`linux`&&zg(t)?d.push(...qg(e)):d.push(t)}let f={denyOnly:l,allowWithinDeny:d},p=n?.network?.allowedDomains!==void 0||S_?.network?.allowedDomains!==void 0,m=p,h=p;h&&await hme();let g=n?.allowPty??S_?.allowPty;switch(i){case`macos`:return Vpe({command:e,needsNetworkRestriction:m,httpProxyPort:h?dme():void 0,socksProxyPort:h?fme():void 0,readConfig:f,writeConfig:s,allowUnixSockets:tme(),allowAllUnixSockets:nme(),allowLocalBinding:rme(),ignoreViolations:ime(),allowPty:g,allowGitConfig:lme(),enableWeakerNetworkIsolation:ome(),binShell:t});case`linux`:return Ppe({command:e,needsNetworkRestriction:m,httpSocketPath:h?pme():void 0,socksSocketPath:h?mme():void 0,httpProxyPort:h?T_?.httpProxyPort:void 0,socksProxyPort:h?T_?.socksProxyPort:void 0,readConfig:f,writeConfig:s,enableWeakerNestedSandbox:ame(),allowAllUnixSockets:nme(),binShell:t,ripgrepConfig:sme(),mandatoryDenySearchDepth:cme(),allowGitConfig:lme(),seccompConfig:ume(),abortSignal:r});default:throw Error(`Sandbox configuration is not supported on platform: ${i}`)}}function _me(){return S_}function vme(e){S_=Tue(e),k_=lh(e.network.parentProxy),Z(`Sandbox configuration updated`)}function yme(){o_()}async function x_(){if(yme(),O_&&(O_(),O_=void 0),T_?.linuxBridge){let{httpSocketPath:e,socksSocketPath:t,httpBridgeProcess:n,socksBridgeProcess:r}=T_.linuxBridge,i=[];if(n.pid&&!n.killed)try{process.kill(n.pid,`SIGTERM`),Z(`Sent SIGTERM to HTTP bridge process`),i.push(new Promise(e=>{n.once(`exit`,()=>{Z(`HTTP bridge process exited`),e()}),setTimeout(()=>{if(!n.killed){Z(`HTTP bridge did not exit, forcing SIGKILL`,{level:`warn`});try{n.pid&&process.kill(n.pid,`SIGKILL`)}catch{}}e()},5e3)}))}catch(e){e.code!==`ESRCH`&&Z(`Error killing HTTP bridge: ${e}`,{level:`error`})}if(r.pid&&!r.killed)try{process.kill(r.pid,`SIGTERM`),Z(`Sent SIGTERM to SOCKS bridge process`),i.push(new Promise(e=>{r.once(`exit`,()=>{Z(`SOCKS bridge process exited`),e()}),setTimeout(()=>{if(!r.killed){Z(`SOCKS bridge did not exit, forcing SIGKILL`,{level:`warn`});try{r.pid&&process.kill(r.pid,`SIGKILL`)}catch{}}e()},5e3)}))}catch(e){e.code!==`ESRCH`&&Z(`Error killing SOCKS bridge: ${e}`,{level:`error`})}if(await Promise.all(i),e)try{Lc.rmSync(e,{force:!0}),Z(`Cleaned up HTTP socket`)}catch(e){Z(`HTTP socket cleanup error: ${e}`,{level:`error`})}if(t)try{Lc.rmSync(t,{force:!0}),Z(`Cleaned up SOCKS socket`)}catch(e){Z(`SOCKS socket cleanup error: ${e}`,{level:`error`})}}let e=[];if(C_){let t=C_,n=new Promise(e=>{t.close(t=>{t&&t.message!==`Server is not running.`&&Z(`Error closing HTTP proxy server: ${t.message}`,{level:`error`}),e()})});e.push(n)}if(w_){let t=w_.close().catch(e=>{Z(`Error closing SOCKS proxy server: ${e.message}`,{level:`error`})});e.push(t)}await Promise.all(e),C_=void 0,w_=void 0,T_=void 0,E_=void 0,k_=void 0}function bme(){return A_}function xme(e,t){if(!S_)return t;let n=A_.getViolationsForCommand(e);if(n.length===0)return t;let r=t;r+=Wc+`<sandbox_violations>`+Wc;for(let e of n)r+=e.line+Wc;return r+=`</sandbox_violations>`,r}function Sme(){if(Pg()!==`linux`||!S_)return[];let e=[],t=[...S_.filesystem.allowWrite,...S_.filesystem.denyWrite];for(let n of t)zg(Bg(n))&&e.push(n);return e}var S_,C_,w_,T_,E_,D_,O_,k_,A_,j_,Cme=n((()=>{Hfe(),Kfe(),ch(),Ah(),Ng(),Fg(),Fpe(),Upe(),Xg(),v_(),Ch(),D_=!1,A_=new __,j_={initialize:Jpe,isSupportedPlatform:Ype,isSandboxingEnabled:Xpe,checkDependencies:Zpe,getFsReadConfig:Qpe,getFsWriteConfig:$pe,getNetworkRestrictionConfig:eme,getAllowUnixSockets:tme,getAllowLocalBinding:rme,getIgnoreViolations:ime,getEnableWeakerNestedSandbox:ame,getProxyPort:dme,getSocksProxyPort:fme,getLinuxHttpSocketPath:pme,getLinuxSocksSocketPath:mme,waitForNetworkInitialization:hme,wrapWithSandbox:gme,cleanupAfterCommand:yme,reset:x_,getSandboxViolationStore:bme,annotateStderrWithSandboxFailures:xme,getLinuxGlobPatternWarnings:Sme,getConfig:_me,updateConfig:vme}})),M_,N_,wme,Tme,Eme,Dme,Ome,kme,Ame,jme=n((()=>{N(),M_=j().refine(e=>{if(e.includes(`://`)||e.includes(`/`)||e.includes(`:`))return!1;if(e===`localhost`)return!0;if(e.startsWith(`*.`)){let t=e.slice(2);if(!t.includes(`.`)||t.startsWith(`.`)||t.endsWith(`.`))return!1;let n=t.split(`.`);return n.length>=2&&n.every(e=>e.length>0)}return!e.includes(`*`)&&e.includes(`.`)&&!e.startsWith(`.`)&&!e.endsWith(`.`)},{message:`Invalid domain pattern. Must be a valid domain (e.g., "example.com") or wildcard (e.g., "*.example.com"). Overly broad patterns like "*.com" or "*" are not allowed for security reasons.`}),N_=j().min(1,`Path cannot be empty`),wme=se({socketPath:j().min(1).describe(`Unix socket path to the MITM proxy`),domains:M(M_).min(1).describe(`Domains to route through the MITM proxy (e.g., ["api.example.com", "*.internal.org"])`)}),Tme=se({http:j().url().optional().describe(`Upstream proxy URL for plain HTTP traffic`),https:j().url().optional().describe(`Upstream proxy URL for HTTPS/CONNECT traffic (falls back to http if unset)`),noProxy:j().optional().describe(`Comma-separated NO_PROXY list (hostname suffixes and CIDR ranges). Matching destinations connect directly instead of via the parent proxy.`)}),Eme=se({allowedDomains:M(M_).describe(`List of allowed domains (e.g., ["github.com", "*.npmjs.org"])`),deniedDomains:M(M_).describe(`List of denied domains`),allowUnixSockets:M(j()).optional().describe(`macOS only: Unix socket paths to allow. Ignored on Linux (seccomp cannot filter by path).`),allowAllUnixSockets:oe().optional().describe(`If true, allow all Unix sockets (disables blocking on both platforms).`),allowLocalBinding:oe().optional().describe(`Whether to allow binding to local ports (default: false)`),httpProxyPort:ae().int().min(1).max(65535).optional().describe(`Port of an external HTTP proxy to use instead of starting a local one. When provided, the library will skip starting its own HTTP proxy and use this port. The external proxy must handle domain filtering.`),socksProxyPort:ae().int().min(1).max(65535).optional().describe(`Port of an external SOCKS proxy to use instead of starting a local one. When provided, the library will skip starting its own SOCKS proxy and use this port. The external proxy must handle domain filtering.`),mitmProxy:wme.optional().describe(`Optional MITM proxy configuration. Routes matching domains through an upstream proxy via Unix socket while SRT still handles allow/deny filtering.`),parentProxy:Tme.optional().describe(`Upstream HTTP proxy for outbound connections. When set, SRT's proxy tunnels non-mitmProxy traffic through this parent instead of connecting directly. Falls back to HTTP_PROXY/HTTPS_PROXY/NO_PROXY env vars if unset.`)}),Dme=se({denyRead:M(N_).describe(`Paths denied for reading`),allowRead:M(N_).optional().describe(`Paths to re-allow reading within denied regions (takes precedence over denyRead). Use with denyRead to deny a broad region then allow back specific subdirectories.`),allowWrite:M(N_).describe(`Paths allowed for writing`),denyWrite:M(N_).describe(`Paths denied for writing (takes precedence over allowWrite)`),allowGitConfig:oe().optional().describe(`Allow writes to .git/config files (default: false). Enables git remote URL updates while keeping .git/hooks protected.`)}),Ome=le(j(),M(j())).describe(`Map of command patterns to filesystem paths to ignore violations for. Use "*" to match all commands`),kme=se({command:j().describe(`The ripgrep command to execute`),args:M(j()).optional().describe(`Additional arguments to pass before ripgrep args`),argv0:j().optional().describe(`Override argv[0] when spawning (for multicall binaries that dispatch on argv[0])`)}),Ame=se({bpfPath:j().optional().describe(`Path to the unix-block.bpf filter file`),applyPath:j().optional().describe(`Path to the apply-seccomp binary`)}),se({network:Eme.describe(`Network restrictions configuration`),filesystem:Dme.describe(`Filesystem restrictions configuration`),ignoreViolations:Ome.optional().describe(`Optional configuration for ignoring specific violations`),enableWeakerNestedSandbox:oe().optional().describe(`Enable weaker nested sandbox mode (for Docker environments)`),enableWeakerNetworkIsolation:oe().optional().describe(`Enable weaker network isolation to allow access to com.apple.trustd.agent (macOS only). This is needed for Go programs (gh, gcloud, terraform, kubectl, etc.) to verify TLS certificates when using httpProxyPort with a MITM proxy and custom CA. Enabling this opens a potential data exfiltration vector through the trustd service. Only enable if you need Go TLS verification.`),ripgrep:kme.optional().describe(`Custom ripgrep configuration (default: { command: "rg" })`),mandatoryDenySearchDepth:ae().int().min(1).max(10).optional().describe(`Maximum directory depth to search for dangerous files on Linux (default: 3). Higher values provide more protection but slower performance.`),allowPty:oe().optional().describe(`Allow pseudo-terminal (pty) operations (macOS only)`),seccomp:Ame.optional().describe(`Custom seccomp binary paths (Linux only).`)})})),Mme=n((()=>{Cme(),v_(),jme(),Xg(),Fg()}));async function Nme(){if(z_||B_)return;z_=!0,Bme(),ar(Pme);let{dirs:e,settingsFiles:t,dropInDir:n}=await Fme();B_||e.length!==0&&(G(`Watching for changes in setting files ${[...t].join(`, `)}...${n?` and drop-in directory ${n}`:``}`),I_=Tp.watch(e,{persistent:!0,ignoreInitial:!0,depth:0,awaitWriteFinish:{stabilityThreshold:U_?.stabilityThreshold??Ume,pollInterval:U_?.pollInterval??Wme},ignored:(e,r)=>{if(r&&!r.isFile()&&!r.isDirectory()||e.split(yc.sep).some(e=>e===`.git`))return!0;if(!r||r.isDirectory())return!1;let i=yc.normalize(e);return!(t.has(i)||n&&i.startsWith(n+yc.sep)&&i.endsWith(`.json`))},ignorePermissionErrors:!0,usePolling:!1,atomic:!0}),I_.on(`change`,Lme),I_.on(`unlink`,zme),I_.on(`add`,Rme))}function Pme(){B_=!0,L_&&(clearInterval(L_),L_=null);for(let e of V_.values())clearTimeout(e);V_.clear(),R_=null,Tne(),H_.clear();let e=I_;return I_=null,e?e.close():Promise.resolve()}async function Fme(){let e=new Map,t=new Set;for(let n of ki){if(n===`flagSettings`)continue;let r=ji(n);if(!r)continue;let i=yc.dirname(r);e.has(i)||e.set(i,new Set),e.get(i).add(r);try{(await ol(r)).isFile()&&t.add(i)}catch{}}let n=new Set;for(let r of t){let t=e.get(r);if(t)for(let e of t)n.add(e)}let r=null,i=ii();try{(await ol(i)).isDirectory()&&(t.add(i),r=i)}catch{}return{dirs:[...t],settingsFiles:n,dropInDir:r}}function Ime(e){switch(e){case`userSettings`:return`user_settings`;case`projectSettings`:return`project_settings`;case`localSettings`:return`local_settings`;case`flagSettings`:case`policySettings`:return`policy_settings`}}function Lme(e){let t=P_(e);if(!t)return;let n=V_.get(e);n&&(clearTimeout(n),V_.delete(e),G(`Cancelled pending deletion of ${e} — file was recreated`)),!Sre(e,Gme)&&(G(`Detected change to ${e}`),l7(Ime(t),e).then(n=>{if(r7(n)){G(`ConfigChange hook blocked change to ${e}`);return}F_(t)}))}function Rme(e){if(!P_(e))return;let t=V_.get(e);t&&(clearTimeout(t),V_.delete(e),G(`Cancelled pending deletion of ${e} — file was re-added`)),Lme(e)}function zme(e){let t=P_(e);if(!t||(G(`Detected deletion of ${e}`),V_.has(e)))return;let n=setTimeout((e,t)=>{V_.delete(e),l7(Ime(t),e).then(n=>{if(r7(n)){G(`ConfigChange hook blocked deletion of ${e}`);return}F_(t)})},U_?.deletionGrace??qme,e,t);V_.set(e,n)}function P_(e){let t=yc.normalize(e),n=ii();return t.startsWith(n+yc.sep)?`policySettings`:ki.find(e=>ji(e)===t)}function Bme(){let e=One(),t=Xne();R_=U({mdm:e.settings,hkcu:t.settings}),L_=setInterval(()=>{B_||(async()=>{try{let{mdm:e,hkcu:t}=await Qne();if(B_)return;let n=U({mdm:e.settings,hkcu:t.settings});n!==R_&&(R_=n,Ane(e,t),G(`Detected MDM settings change via poll`),F_(`policySettings`))}catch(e){G(`MDM poll error: ${W(e)}`)}})()},U_?.mdmPollInterval??Kme),L_.unref()}function F_(e){Nn(),H_.emit(e)}function Vme(e){G(`Programmatic settings change notification for ${e}`),F_(e)}function Hme(e){L_&&(clearInterval(L_),L_=null);for(let e of V_.values())clearTimeout(e);V_.clear(),R_=null,z_=!1,B_=!1,U_=e??null;let t=I_;return I_=null,t?t.close():Promise.resolve()}var Ume,Wme,Gme,Kme,qme,I_,L_,R_,z_,B_,V_,H_,U_,Jme,W_,G_=n((()=>{Ep(),Hn(),K(),qn(),g7(),Xt(),mr(),wi(),tie(),Ur(),rie(),vi(),pn(),Ume=1e3,Wme=500,Gme=5e3,Kme=1800*1e3,qme=1700,I_=null,L_=null,R_=null,z_=!1,B_=!1,V_=new Map,H_=Dn(),U_=null,Jme=H_.subscribe,W_={initialize:Nme,dispose:Pme,subscribe:Jme,notifyChange:Vme,resetForTesting:Hme}}));function K_(e){let t=e.match(/^([^(]+)\(([^)]+)\)$/);if(!t)return{toolName:e};let n=t[1],r=t[2];return!n||!r?{toolName:e}:{toolName:n,ruleContent:r}}function Yme(e){return e.match(/^(.+):\*$/)?.[1]??null}function q_(e,t){return e.startsWith(`//`)?e.slice(1):e.startsWith(`/`)&&!e.startsWith(`//`)?Oc(ui(t),e.slice(1)):e}function J_(e,t){return e.startsWith(`//`)?e.slice(1):hi(e,ui(t))}function Y_(){return zi(`policySettings`)?.sandbox?.network?.allowManagedDomainsOnly===!0}function Xme(){return zi(`policySettings`)?.sandbox?.filesystem?.allowManagedReadPathsOnly===!0}function X_(e){let t=e.permissions||{},n=[],r=[];if(Y_()){let e=zi(`policySettings`);for(let t of e?.sandbox?.network?.allowedDomains||[])n.push(t)}else for(let t of e.sandbox?.network?.allowedDomains||[])n.push(t);for(let e of t.deny||[]){let t=K_(e);t.ruleContent?.startsWith(`domain:`)&&r.push(t.ruleContent.substring(7))}let i=[`.`,I8()],a=[],o=[],s=[],c=ki.map(e=>ji(e)).filter(e=>e!==void 0);a.push(...c),a.push(ii());let l=Vt(),u=Yt();l!==u&&(a.push(Oc(l,`.workmate`,`settings.json`)),a.push(Oc(l,`.workmate`,`settings.local.json`))),a.push(Oc(u,`.workmate`,`skills`)),l!==u&&a.push(Oc(l,`.workmate`,`skills`)),rv.length=0;let d=[`HEAD`,`objects`,`refs`,`hooks`,`config`];for(let e of l===u?[u]:[u,l])for(let t of d){let n=Oc(e,t);try{Qse(n),a.push(n)}catch{rv.push(n)}}nv&&nv!==l&&i.push(nv);let f=new Set([...e.permissions?.additionalDirectories||[],...mn()]);i.push(...f);for(let e of ki){let t=zi(e);if(t?.permissions){for(let n of t.permissions.allow||[]){let t=K_(n);t.toolName===`Edit`&&t.ruleContent&&i.push(q_(t.ruleContent,e))}for(let n of t.permissions.deny||[]){let t=K_(n);t.toolName===`Edit`&&t.ruleContent&&a.push(q_(t.ruleContent,e)),t.toolName===`Read`&&t.ruleContent&&o.push(q_(t.ruleContent,e))}}let n=t?.sandbox?.filesystem;if(n){for(let t of n.allowWrite||[])i.push(J_(t,e));for(let t of n.denyWrite||[])a.push(J_(t,e));for(let t of n.denyRead||[])o.push(J_(t,e));if(!Xme()||e===`policySettings`)for(let t of n.allowRead||[])s.push(J_(t,e))}}let{rgPath:p,rgArgs:m,argv0:h}=rc(),g=e.sandbox?.ripgrep??{command:p,args:m,argv0:h};return{network:{allowedDomains:n,deniedDomains:r,allowUnixSockets:e.sandbox?.network?.allowUnixSockets,allowAllUnixSockets:e.sandbox?.network?.allowAllUnixSockets,allowLocalBinding:e.sandbox?.network?.allowLocalBinding,httpProxyPort:e.sandbox?.network?.httpProxyPort,socksProxyPort:e.sandbox?.network?.socksProxyPort},filesystem:{denyRead:o,allowRead:s,allowWrite:i,denyWrite:a},ignoreViolations:e.sandbox?.ignoreViolations,enableWeakerNestedSandbox:e.sandbox?.enableWeakerNestedSandbox,enableWeakerNetworkIsolation:e.sandbox?.enableWeakerNetworkIsolation,ripgrep:g}}function Zme(){for(let e of rv)try{Zse(e,{recursive:!0}),G(`[Sandbox] scrubbed planted bare-repo file: ${e}`)}catch{}}async function Qme(e){let t=X(e,`.git`);try{let n=(await tl(t,{encoding:`utf8`})).match(/^gitdir:\s*(.+)$/m);if(!n?.[1])return null;let r=Oc(e,n[1].trim()),i=`${kc}.git${kc}worktrees${kc}`,a=r.lastIndexOf(i);return a>0?r.substring(0,a):null}catch{return null}}function Z_(){try{return fi()?.sandbox?.enabled??!1}catch(e){return G(`Failed to get settings for sandbox check: ${e}`),!1}}function $me(){return fi()?.sandbox?.autoAllowBashIfSandboxed??!0}function ehe(){return fi()?.sandbox?.allowUnsandboxedCommands??!0}function the(){let e=fi();return Z_()&&(e?.sandbox?.failIfUnavailable??!1)}function Q_(){try{let e=Vi()?.sandbox?.enabledPlatforms;if(e===void 0)return!0;if(e.length===0)return!1;let t=io();return e.includes(t)}catch(e){return G(`Failed to check enabledPlatforms: ${e}`),!0}}function $_(){return!av()||iv().errors.length>0||!Q_()?!1:Z_()}function nhe(){if(!Z_())return;if(!av()){let e=io();return e===`wsl`?`sandbox.enabled is set but WSL1 is not supported (requires WSL2)`:`sandbox.enabled is set but ${e} is not supported (requires macOS, Linux, or WSL2)`}if(!Q_())return`sandbox.enabled is set but ${io()} is not in sandbox.enabledPlatforms`;let e=iv();if(e.errors.length>0){let t=io()===`macos`?`run /sandbox or /doctor for details`:`install missing tools (e.g. apt install bubblewrap socat) or run /sandbox for details`;return`sandbox.enabled is set but dependencies are missing: ${e.errors.join(`, `)} · ${t}`}}function rhe(){let e=io();if(e!==`linux`&&e!==`wsl`)return[];try{let e=fi();if(!e?.sandbox?.enabled)return[];let t=e?.permissions||{},n=[],r=e=>{let t=e.replace(/\/\*\*$/,``);return/[*?[\]]/.test(t)};for(let e of[...t.allow||[],...t.deny||[]]){let t=K_(e);(t.toolName===`Edit`||t.toolName===`Read`)&&t.ruleContent&&r(t.ruleContent)&&n.push(e)}return n}catch(e){return G(`Failed to get Linux glob pattern warnings: ${e}`),[]}}function ihe(){for(let e of[`flagSettings`,`policySettings`]){let t=zi(e);if(t?.sandbox?.enabled!==void 0||t?.sandbox?.autoAllowBashIfSandboxed!==void 0||t?.sandbox?.allowUnsandboxedCommands!==void 0)return!0}return!1}async function ahe(e){li(`localSettings`,{sandbox:{...zi(`localSettings`)?.sandbox,...e.enabled!==void 0&&{enabled:e.enabled},...e.autoAllowBashIfSandboxed!==void 0&&{autoAllowBashIfSandboxed:e.autoAllowBashIfSandboxed},...e.allowUnsandboxedCommands!==void 0&&{allowUnsandboxedCommands:e.allowUnsandboxedCommands}}})}function ohe(){return fi()?.sandbox?.excludedCommands??[]}async function she(e,t,n,r){if($_())if(ev)await ev;else throw Error(`Sandbox failed to initialize. `);return j_.wrapWithSandbox(e,t,n,r)}async function che(e){if(ev)return ev;if(!$_())return;let t=e?async t=>Y_()?(G(`[sandbox] Blocked network request to ${t.host} (allowManagedDomainsOnly)`),!1):e(t):void 0;return ev=(async()=>{try{nv===void 0&&(nv=await Qme(Vt()));let e=X_(fi());await j_.initialize(e,t),tv=W_.subscribe(()=>{let e=X_(fi());j_.updateConfig(e),G(`Sandbox configuration updated from settings change`)})}catch(e){ev=void 0,G(`Failed to initialize sandbox: ${W(e)}`)}})(),ev}function lhe(){if(!$_())return;let e=X_(fi());j_.updateConfig(e)}async function uhe(){return tv?.(),tv=void 0,nv=void 0,rv.length=0,iv.cache.clear?.(),av.cache.clear?.(),ev=void 0,j_.reset()}function dhe(e,t){let n=zi(`localSettings`),r=n?.sandbox?.excludedCommands||[],i=e;if(t){let e=t.filter(e=>e.type===`addRules`&&e.rules.some(e=>e.toolName===`Bash`));if(e.length>0&&e[0].type===`addRules`){let t=e[0].rules.find(e=>e.toolName===Vs);t?.ruleContent&&(i=Yme(t.ruleContent)||t.ruleContent)}}return r.includes(i)||li(`localSettings`,{sandbox:{...n?.sandbox,excludedCommands:[...r,i]}}),i}var ev,tv,nv,rv,iv,av,ov,sv=n((()=>{Mme(),Ng(),Jt(),K(),Ai(),ao(),G_(),wi(),Ur(),vi(),js(),Ls(),Us(),qn(),R8(),nc(),rv=[],iv=u(()=>{let{rgPath:e,rgArgs:t}=rc();return j_.checkDependencies({command:e,args:t})}),av=u(()=>j_.isSupportedPlatform()),ov={initialize:che,isSandboxingEnabled:$_,isSandboxEnabledInSettings:Z_,isPlatformInEnabledList:Q_,getSandboxUnavailableReason:nhe,isAutoAllowBashIfSandboxedEnabled:$me,areUnsandboxedCommandsAllowed:ehe,isSandboxRequired:the,areSandboxSettingsLockedByPolicy:ihe,setSandboxSettings:ahe,getExcludedCommands:ohe,wrapWithSandbox:she,refreshConfig:lhe,reset:uhe,checkDependencies:iv,getFsReadConfig:j_.getFsReadConfig,getFsWriteConfig:j_.getFsWriteConfig,getNetworkRestrictionConfig:j_.getNetworkRestrictionConfig,getIgnoreViolations:j_.getIgnoreViolations,getLinuxGlobPatternWarnings:rhe,isSupportedPlatform:av,getAllowUnixSockets:j_.getAllowUnixSockets,getAllowLocalBinding:j_.getAllowLocalBinding,getEnableWeakerNestedSandbox:j_.getEnableWeakerNestedSandbox,getProxyPort:j_.getProxyPort,getSocksProxyPort:j_.getSocksProxyPort,getLinuxHttpSocketPath:j_.getLinuxHttpSocketPath,getLinuxSocksSocketPath:j_.getLinuxSocksSocketPath,waitForNetworkInitialization:j_.waitForNetworkInitialization,getSandboxViolationStore:j_.getSandboxViolationStore,annotateStderrWithSandboxFailures:j_.annotateStderrWithSandboxFailures,cleanupAfterCommand:()=>{j_.cleanupAfterCommand(),Zme()}}})),fhe,phe=n((()=>{ne(),sv(),fhe={name:`sandbox`,get description(){let e=ov.isSandboxingEnabled(),t=ov.isAutoAllowBashIfSandboxedEnabled(),n=ov.areUnsandboxedCommandsAllowed(),r=ov.areSandboxSettingsLockedByPolicy(),i=ov.checkDependencies().errors.length===0,a;a=i?e?ie.tick:ie.circle:ie.warning;let o=`sandbox disabled`;return e&&(o=t?`sandbox enabled (auto-allow)`:`sandbox enabled`,o+=n?`, fallback allowed`:``),r&&(o+=` (managed)`),`${a} ${o} (⏎ to configure)`},argumentHint:`exclude "command pattern"`,get isHidden(){return!ov.isSupportedPlatform()||!ov.isPlatformInEnabledList()},immediate:!0,type:`local-jsx`,load:()=>import(`./sandbox-toggle-D9GDUsTl.js`)}}));function cv(e){return e.type===`advisor_tool_result`||e.type===`server_tool_use`&&e.name===`advisor`}function lv(){return{}}function uv(){return h(process.env.CLAUDE_CODE_DISABLE_ADVISOR_TOOL)||!be()?!1:lv().enabled??!1}function dv(){return uv()&&(lv().canUserConfigure??!1)}function mhe(){let e=lv();return uv()&&!dv()&&e.baseModel&&e.advisorModel?{baseModel:e.baseModel,advisorModel:e.advisorModel}:void 0}function fv(e){let t=e.toLowerCase();return t.includes(`opus-4-7`)||t.includes(`opus-4-6`)||t.includes(`sonnet-4-6`)}function pv(e){let t=e.toLowerCase();return t.includes(`opus-4-7`)||t.includes(`opus-4-6`)||t.includes(`sonnet-4-6`)}function hhe(){if(uv())return Vi().advisorModel}function ghe(e){let t=e.iterations;return t?t.filter(e=>e.type===`advisor_message`):[]}var _he,mv=n((()=>{ve(),g(),vi(),_he=`# Advisor Tool
|
|
416
416
|
|
|
417
417
|
You have access to an \`advisor\` tool backed by a stronger reviewer model. It takes NO parameters -- when you call it, your entire conversation history is automatically forwarded. The advisor sees the task, every tool call you've made, every result you've seen.
|
|
418
418
|
|
|
@@ -666,8 +666,8 @@ Reads a specific resource from an MCP server, identified by server name and reso
|
|
|
666
666
|
Parameters:
|
|
667
667
|
- server (required): The name of the MCP server from which to read the resource
|
|
668
668
|
- uri (required): The URI of the resource to read
|
|
669
|
-
`}));function VTe(e){return!e.uri||!e.server?null:`Read resource "${e.uri}" from server "${e.server}"`}function HTe(){return`readMcpResource`}function UTe(e,t,{verbose:n}){return!e?.contents||e.contents.length===0?(0,FO.jsx)(P,{justifyContent:`space-between`,overflowX:`hidden`,width:`100%`,children:(0,FO.jsx)($,{height:1,children:(0,FO.jsx)(F,{dimColor:!0,children:`(No content)`})})}):(0,FO.jsx)(yC,{content:U(e,null,2),verbose:n})}var FO,WTe=n((()=>{_C(),xC(),ct(),mr(),FO=ut()})),IO,LO,RO,zO=n((()=>{Ks(),GT(),Nt(),cj(),kt(),MO(),mr(),mC(),BTe(),WTe(),IO=V(()=>I({server:B().describe(`The MCP server name`),uri:B().describe(`The resource URI to read`)})),LO=V(()=>I({contents:L(I({uri:B().describe(`Resource URI`),mimeType:B().optional().describe(`MIME type of the content`),text:B().optional().describe(`Text content of the resource`),blobSavedTo:B().optional().describe(`Path where binary blob content was saved`)}))})),RO=Ns({isConcurrencySafe(){return!0},isReadOnly(){return!0},toAutoClassifierInput(e){return`${e.server} ${e.uri}`},shouldDefer:!0,name:`ReadMcpResourceTool`,searchHint:`read a specific MCP resource by URI`,maxResultSizeChars:1e5,async description(){return NO},async prompt(){return PO},get inputSchema(){return IO()},get outputSchema(){return LO()},async call(e,{options:{mcpClients:t}}){let{server:n,uri:r}=e,i=t.find(e=>e.name===n);if(!i)throw Error(`Server "${n}" not found. Available servers: ${t.map(e=>e.name).join(`, `)}`);if(i.type!==`connected`)throw Error(`Server "${n}" is not connected`);if(!i.capabilities?.resources)throw Error(`Server "${n}" does not support resources`);let a=await(await RA(i)).client.request({method:`resources/read`,params:{uri:r}},Qw);return{data:{contents:await Promise.all(a.contents.map(async(e,t)=>{if(`text`in e)return{uri:e.uri,mimeType:e.mimeType,text:e.text};if(!(`blob`in e)||typeof e.blob!=`string`)return{uri:e.uri,mimeType:e.mimeType};let r=`mcp-resource-${Date.now()}-${t}-${Math.random().toString(36).slice(2,8)}`,i=await AO(Buffer.from(e.blob,`base64`),e.mimeType,r);return`error`in i?{uri:e.uri,mimeType:e.mimeType,text:`Binary content could not be saved to disk: ${i.error}`}:{uri:e.uri,mimeType:e.mimeType,blobSavedTo:i.filepath,text:jO(i.filepath,e.mimeType,i.size,`[Resource from ${n} at ${e.uri}] `)}}))}}},renderToolUseMessage:VTe,userFacingName:HTe,renderToolResultMessage:UTe,isResultTruncated(e){return fC(U(e))},mapToolResultToToolResultBlockParam(e,t){return Ys(t,U(e))}})}));function BO(e=HO){let t=new AbortController;return Fce(e,t.signal),t}function GTe(e){let t=this.deref();e.deref()?.abort(t?.signal.reason)}function KTe(e){let t=this.deref(),n=e.deref();t&&n&&t.signal.removeEventListener(`abort`,n)}function VO(e,t){let n=BO(t);if(e.signal.aborted)return n.abort(e.signal.reason),n;let r=new WeakRef(n),i=new WeakRef(e),a=GTe.bind(i,r);return e.signal.addEventListener(`abort`,a,{once:!0}),n.signal.addEventListener(`abort`,KTe.bind(i,new WeakRef(a)),{once:!0}),n}var HO,UO=n((()=>{HO=50}));function qTe(e){let t=e.trim(),n=t.split(/\s+/)[0]?.toLowerCase();if(n){if(n===`npx`||n===`bunx`){let e=t.split(/\s+/)[1]?.toLowerCase();if(e&&e in WO)return WO[e]}return WO[n]}}function JTe(e){for(let{pattern:t,tool:n}of GO)if(t.test(e))return n}var WO,GO,KO=n((()=>{WO={src:`sourcegraph`,cody:`cody`,aider:`aider`,tabby:`tabby`,tabnine:`tabnine`,augment:`augment`,pieces:`pieces`,qodo:`qodo`,aide:`aide`,hound:`hound`,seagoat:`seagoat`,bloop:`bloop`,gitloop:`gitloop`,q:`amazon-q`,gemini:`gemini`},GO=[{pattern:/^sourcegraph$/i,tool:`sourcegraph`},{pattern:/^cody$/i,tool:`cody`},{pattern:/^openctx$/i,tool:`openctx`},{pattern:/^aider$/i,tool:`aider`},{pattern:/^continue$/i,tool:`continue`},{pattern:/^github[-_]?copilot$/i,tool:`github-copilot`},{pattern:/^copilot$/i,tool:`github-copilot`},{pattern:/^cursor$/i,tool:`cursor`},{pattern:/^tabby$/i,tool:`tabby`},{pattern:/^codeium$/i,tool:`codeium`},{pattern:/^tabnine$/i,tool:`tabnine`},{pattern:/^augment[-_]?code$/i,tool:`augment`},{pattern:/^augment$/i,tool:`augment`},{pattern:/^windsurf$/i,tool:`windsurf`},{pattern:/^aide$/i,tool:`aide`},{pattern:/^codestory$/i,tool:`aide`},{pattern:/^pieces$/i,tool:`pieces`},{pattern:/^qodo$/i,tool:`qodo`},{pattern:/^amazon[-_]?q$/i,tool:`amazon-q`},{pattern:/^gemini[-_]?code[-_]?assist$/i,tool:`gemini`},{pattern:/^gemini$/i,tool:`gemini`},{pattern:/^hound$/i,tool:`hound`},{pattern:/^seagoat$/i,tool:`seagoat`},{pattern:/^bloop$/i,tool:`bloop`},{pattern:/^gitloop$/i,tool:`gitloop`},{pattern:/^claude[-_]?context$/i,tool:`claude-context`},{pattern:/^code[-_]?index[-_]?mcp$/i,tool:`code-index-mcp`},{pattern:/^code[-_]?index$/i,tool:`code-index-mcp`},{pattern:/^local[-_]?code[-_]?search$/i,tool:`local-code-search`},{pattern:/^codebase$/i,tool:`autodev-codebase`},{pattern:/^autodev[-_]?codebase$/i,tool:`autodev-codebase`},{pattern:/^code[-_]?context$/i,tool:`claude-context`}]})),qO,JO,YO,YTe=n((()=>{GT(),ni(),qn(),mr(),b(),qO=0,JO=1,YO=class{constructor(e){if(x(this,`ws`,void 0),x(this,`started`,!1),x(this,`opened`,void 0),x(this,`isBun`,typeof Bun<`u`),x(this,`onclose`,void 0),x(this,`onerror`,void 0),x(this,`onmessage`,void 0),x(this,`onBunMessage`,e=>{try{let t=$n(typeof e.data==`string`?e.data:String(e.data)),n=bw.parse(t);this.onmessage?.(n)}catch(e){this.handleError(e)}}),x(this,`onBunError`,()=>{this.handleError(Error(`WebSocket error`))}),x(this,`onBunClose`,()=>{this.handleCloseCleanup()}),x(this,`onNodeMessage`,e=>{try{let t=$n(e.toString(`utf-8`)),n=bw.parse(t);this.onmessage?.(n)}catch(e){this.handleError(e)}}),x(this,`onNodeError`,e=>{this.handleError(e)}),x(this,`onNodeClose`,()=>{this.handleCloseCleanup()}),this.ws=e,this.opened=new Promise((e,t)=>{if(this.ws.readyState===JO)e();else if(this.isBun){let n=this.ws,r=()=>{n.removeEventListener(`open`,r),n.removeEventListener(`error`,i),e()},i=e=>{n.removeEventListener(`open`,r),n.removeEventListener(`error`,i),ei(`error`,`mcp_websocket_connect_fail`),t(e)};n.addEventListener(`open`,r),n.addEventListener(`error`,i)}else{let n=this.ws;n.on(`open`,()=>{e()}),n.on(`error`,e=>{ei(`error`,`mcp_websocket_connect_fail`),t(e)})}}),this.isBun){let e=this.ws;e.addEventListener(`message`,this.onBunMessage),e.addEventListener(`error`,this.onBunError),e.addEventListener(`close`,this.onBunClose)}else{let e=this.ws;e.on(`message`,this.onNodeMessage),e.on(`error`,this.onNodeError),e.on(`close`,this.onNodeClose)}}handleError(e){ei(`error`,`mcp_websocket_message_fail`),this.onerror?.(tr(e))}handleCloseCleanup(){if(this.onclose?.(),this.isBun){let e=this.ws;e.removeEventListener(`message`,this.onBunMessage),e.removeEventListener(`error`,this.onBunError),e.removeEventListener(`close`,this.onBunClose)}else{let e=this.ws;e.off(`message`,this.onNodeMessage),e.off(`error`,this.onNodeError),e.off(`close`,this.onNodeClose)}}async start(){if(this.started)throw Error(`Start can only be called once per transport.`);if(await this.opened,this.ws.readyState!==JO)throw ei(`error`,`mcp_websocket_start_not_opened`),Error(`WebSocket is not open. Cannot start transport.`);this.started=!0}async close(){(this.ws.readyState===JO||this.ws.readyState===qO)&&this.ws.close(),this.handleCloseCleanup()}async send(e){if(this.ws.readyState!==JO)throw ei(`error`,`mcp_websocket_send_not_opened`),Error(`WebSocket is not open. Cannot send message.`);let t=U(e);try{this.isBun?this.ws.send(t):await new Promise((e,n)=>{this.ws.send(t,t=>{t?n(t):e()})})}catch(e){throw this.handleError(e),e}}}}));function XTe(e){return e.mode===`url`?`url`:`form`}function ZTe(e,t,n){return e.findIndex(e=>e.serverName===t&&e.params.mode===`url`&&`elicitationId`in e.params&&e.params.elicitationId===n)}function QTe(e,t,n){try{e.setRequestHandler(AT,async(e,r)=>{Va(t,`Received elicitation request: ${U(e)}`);let i=XTe(e.params);Y(`tengu_mcp_elicitation_shown`,{mode:i});try{let a=await XO(t,e.params,r.signal);if(a)return Va(t,`Elicitation resolved by hook: ${U(a)}`),Y(`tengu_mcp_elicitation_response`,{mode:i,action:a.action}),a;let o=i===`url`&&`elicitationId`in e.params?e.params.elicitationId:void 0,s=await new Promise(a=>{let s=()=>{a({action:`cancel`})};if(r.signal.aborted){s();return}let c=o?{actionLabel:`Skip confirmation`}:void 0;n(n=>({...n,elicitation:{queue:[...n.elicitation.queue,{serverName:t,requestId:r.requestId,params:e.params,signal:r.signal,waitingState:c,respond:e=>{r.signal.removeEventListener(`abort`,s),Y(`tengu_mcp_elicitation_response`,{mode:i,action:e.action}),a(e)}}]}})),r.signal.addEventListener(`abort`,s,{once:!0})});return Va(t,`Elicitation response: ${U(s)}`),await ZO(t,s,r.signal,i,o)}catch(e){return Ua(t,`Elicitation error: ${e}`),{action:`cancel`}}}),e.setNotificationHandler(MT,e=>{let{elicitationId:r}=e.params;Va(t,`Received elicitation completion notification: ${r}`),a7({message:`MCP server "${t}" confirmed elicitation ${r} complete`,notificationType:`elicitation_complete`});let i=!1;n(e=>{let n=ZTe(e.elicitation.queue,t,r);if(n===-1)return e;i=!0;let a=[...e.elicitation.queue];return a[n]={...a[n],completed:!0},{...e,elicitation:{queue:a}}}),i||Va(t,`Ignoring completion notification for unknown elicitation: ${r}`)})}catch{return}}async function XO(e,t,n){try{let r=t.mode===`url`?`url`:`form`,i=`url`in t?t.url:void 0,a=`elicitationId`in t?t.elicitationId:void 0,{elicitationResponse:o,blockingError:s}=await vlt({serverName:e,message:t.message,requestedSchema:`requestedSchema`in t?t.requestedSchema:void 0,signal:n,mode:r,url:i,elicitationId:a});return s?{action:`decline`}:o?{action:o.action,content:o.content}:void 0}catch(t){Ua(e,`Elicitation hook error: ${t}`);return}}async function ZO(e,t,n,r,i){try{let{elicitationResultResponse:a,blockingError:o}=await ylt({serverName:e,action:t.action,content:t.content,signal:n,mode:r,elicitationId:i});if(o)return a7({message:`Elicitation response for server "${e}": decline`,notificationType:`elicitation_response`}),{action:`decline`};let s=a?{action:a.action,content:a.content??t.content}:t;return a7({message:`Elicitation response for server "${e}": ${s.action}`,notificationType:`elicitation_response`}),s}catch(n){return Ua(e,`ElicitationResult hook error: ${n}`),a7({message:`Elicitation response for server "${e}": ${t.action}`,notificationType:`elicitation_response`}),t}}var QO=n((()=>{GT(),g7(),Ga(),mr(),oo()}));function $O(e){let t=[];return{expanded:e.replace(/\$\{([^}]+)\}/g,(e,n)=>{let[r,i]=n.split(`:-`,2),a=process.env[r];return a===void 0?i===void 0?(t.push(r),e):i:a}),missingVars:t}}var ek=n((()=>{}));async function $Te(e){let{vAny:t}=await import(`./dist-DIee4wq1.js`),n=t.McpbManifestSchema.safeParse(e);if(!n.success){let e=n.error.flatten(),t=[...Object.entries(e.fieldErrors).map(([e,t])=>`${e}: ${t?.join(`, `)}`),...e.formErrors||[]].filter(Boolean).join(`; `);throw Error(`Invalid manifest: ${t}`)}return n.data}async function eEe(e){let t;try{t=$n(e)}catch(e){throw Error(`Invalid JSON in manifest.json: ${W(e)}`)}return $Te(t)}async function tk(e){return eEe(new TextDecoder().decode(e))}var tEe=n((()=>{qn(),mr()}));function nEe(e){return!(gr(e)||Cc(wc(e)))}function rEe(e,t){t.fileCount++;let n;t.fileCount>ik.MAX_FILE_COUNT&&(n=`Archive contains too many files: ${t.fileCount} (max: ${ik.MAX_FILE_COUNT})`),nEe(e.name)||(n=`Unsafe file path detected: "${e.name}". Path traversal or absolute paths are not allowed.`);let r=e.originalSize||0;r>ik.MAX_FILE_SIZE&&(n=`File "${e.name}" is too large: ${Math.round(r/1024/1024)}MB (max: ${Math.round(ik.MAX_FILE_SIZE/1024/1024)}MB)`),t.totalUncompressedSize+=r,t.totalUncompressedSize>ik.MAX_TOTAL_SIZE&&(n=`Archive total size is too large: ${Math.round(t.totalUncompressedSize/1024/1024)}MB (max: ${Math.round(ik.MAX_TOTAL_SIZE/1024/1024)}MB)`);let i=t.totalUncompressedSize/t.compressedSize;return i>ik.MAX_COMPRESSION_RATIO&&(n=`Suspicious compression ratio detected: ${i.toFixed(1)}:1 (max: ${ik.MAX_COMPRESSION_RATIO}:1). This may be a zip bomb.`),n?{isValid:!1,error:n}:{isValid:!0}}async function nk(e){let{unzipSync:t}=await import(`./esm-wGnzjq4Z.js`),n={fileCount:0,totalUncompressedSize:0,compressedSize:e.length,errors:[]},r=t(new Uint8Array(e),{filter:e=>{let t=rEe(e,n);if(!t.isValid)throw Error(t.error);return!0}});return G(`Zip extraction completed: ${n.fileCount} files, ${Math.round(n.totalUncompressedSize/1024)}KB uncompressed`),r}function rk(e){let t=Buffer.from(e.buffer,e.byteOffset,e.byteLength),n={},r=Math.max(0,t.length-22-65535),i=-1;for(let e=t.length-22;e>=r;e--)if(t.readUInt32LE(e)===101010256){i=e;break}if(i<0)return n;let a=t.readUInt16LE(i+10),o=t.readUInt32LE(i+16);for(let e=0;e<a&&!(o+46>t.length||t.readUInt32LE(o)!==33639248);e++){let e=t.readUInt16LE(o+4),r=t.readUInt16LE(o+28),i=t.readUInt16LE(o+30),a=t.readUInt16LE(o+32),s=t.readUInt32LE(o+38),c=t.toString(`utf8`,o+46,o+46+r);if(e>>8==3){let e=s>>>16&65535;e&&(n[c]=e)}o+=46+r+i+a}return n}var ik,ak=n((()=>{K(),qn(),or(),Ai(),ik={MAX_FILE_SIZE:512*1024*1024,MAX_TOTAL_SIZE:1024*1024*1024,MAX_FILE_COUNT:1e5,MAX_COMPRESSION_RATIO:50,MIN_COMPRESSION_RATIO:.5}}));function iEe(e,t){return{name:`${e.name}-with-${t.name}-fallback`,read(){return e.read()??(t.read()||{})},async readAsync(){return await e.readAsync()??(await t.readAsync()||{})},update(n){let r=e.read(),i=e.update(n);if(i.success)return r===null&&t.delete(),i;let a=t.update(n);return a.success?(r!==null&&e.delete(),{success:!0,warning:a.warning}):{success:!1}},delete(){let n=e.delete(),r=t.delete();return n||r}}}var aEe=n((()=>{}));function ok(e=``){let t=m(),n=process.env.WORKMATE_CONFIG_DIR?`-${Kc(`sha256`).update(t).digest(`hex`).substring(0,8)}`:``;return`Claude Code${Ine().OAUTH_FILE_SUFFIX}${e}${n}`}function sk(){try{return process.env.USER||Mse().username}catch{return`claude-code-user`}}function ck(){uk.cache={data:null,cachedAt:0},uk.generation++,uk.readInFlight=null}function oEe(e){if(uk.cache.cachedAt!==0)return;let t=null;if(e)try{t=JSON.parse(e)}catch{return}uk.cache={data:t,cachedAt:Date.now()}}var lk,uk,dk=n((()=>{ure(),g(),lk=`-credentials`,uk={cache:{data:null,cachedAt:0},generation:0,readInFlight:null}}));async function sEe(){try{let e=ok(lk),{stdout:t,code:n}=await Ca(`security`,[`find-generic-password`,`-a`,sk(),`-w`,`-s`,e],{useCwd:!1,preserveOutputOnError:!1});if(n===0&&t)return $n(t.trim())}catch{}return null}function cEe(){if(mk!==void 0)return mk;if(process.platform!==`darwin`)return mk=!1,!1;try{mk=ba(`security`,[`show-keychain-info`],{reject:!1,stdio:[`ignore`,`pipe`,`pipe`]}).exitCode===36}catch{mk=!1}return mk}var fk,pk,mk,hk=n((()=>{Sa(),K(),va(),mr(),dk(),fk=4032,pk={name:`keychain`,read(){let e=uk.cache;if(Date.now()-e.cachedAt<3e4)return e.data;try{let e=ok(lk),t=xa(`security find-generic-password -a "${sk()}" -w -s "${e}"`);if(t){let e=$n(t);return uk.cache={data:e,cachedAt:Date.now()},e}}catch{}return e.data===null?(uk.cache={data:null,cachedAt:Date.now()},null):(G(`[keychain] read failed; serving stale cache`,{level:`warn`}),uk.cache={data:e.data,cachedAt:Date.now()},e.data)},async readAsync(){let e=uk.cache;if(Date.now()-e.cachedAt<3e4)return e.data;if(uk.readInFlight)return uk.readInFlight;let t=uk.generation,n=sEe().then(n=>{if(t===uk.generation){n===null&&e.data!==null&&G(`[keychain] readAsync failed; serving stale cache`,{level:`warn`});let t=n??e.data;return uk.cache={data:t,cachedAt:Date.now()},uk.readInFlight=null,t}return n});return uk.readInFlight=n,n},update(e){ck();try{let t=ok(lk),n=sk(),r=U(e),i=Buffer.from(r,`utf-8`).toString(`hex`),a=`add-generic-password -U -a "${n}" -s "${t}" -X "${i}"\n`,o;return a.length<=fk?o=ba(`security`,[`-i`],{input:a,stdio:[`pipe`,`pipe`,`pipe`],reject:!1}):(G(`Keychain payload (${r.length}B JSON) exceeds security -i stdin limit; using argv`,{level:`warn`}),o=ba(`security`,[`add-generic-password`,`-U`,`-a`,n,`-s`,t,`-X`,i],{stdio:[`ignore`,`pipe`,`pipe`],reject:!1})),o.exitCode===0?(uk.cache={data:e,cachedAt:Date.now()},{success:!0}):{success:!1}}catch{return{success:!1}}},delete(){ck();try{let e=ok(lk);return xa(`security delete-generic-password -a "${sk()}" -s "${e}"`),!0}catch{return!1}}}}));function gk(){let e=m();return{storageDir:e,storagePath:X(e,`.credentials.json`)}}var _k,lEe=n((()=>{g(),qn(),or(),mr(),_k={name:`plaintext`,read(){let{storagePath:e}=gk();try{return $n(q().readFileSync(e,{encoding:`utf8`}))}catch{return null}},async readAsync(){let{storagePath:e}=gk();try{return $n(await q().readFile(e,{encoding:`utf8`}))}catch{return null}},update(e){try{let{storageDir:t,storagePath:n}=gk();try{q().mkdirSync(t)}catch(e){if(Xn(e)!==`EEXIST`)throw e}return er(n,U(e),{encoding:`utf8`,flush:!1}),Bse(n,384),{success:!0,warning:`Warning: Storing credentials in plaintext.`}}catch{return{success:!1}}},delete(){let{storagePath:e}=gk();try{return q().unlinkSync(e),!0}catch(e){return Xn(e)===`ENOENT`}}}}));function vk(){return process.platform===`darwin`?iEe(pk,_k):_k}var yk=n((()=>{aEe(),hk(),lEe()}));function uEe(e){let t=e?.platform??io(),n=e?.homedir??_c(),r=e?.env??process.env,i={HOME:n,DESKTOP:X(n,`Desktop`),DOCUMENTS:X(n,`Documents`),DOWNLOADS:X(n,`Downloads`)};switch(t){case`windows`:{let e=r.USERPROFILE||n;return{HOME:n,DESKTOP:X(e,`Desktop`),DOCUMENTS:X(e,`Documents`),DOWNLOADS:X(e,`Downloads`)}}case`linux`:case`wsl`:return{HOME:n,DESKTOP:r.XDG_DESKTOP_DIR||i.DESKTOP,DOCUMENTS:r.XDG_DOCUMENTS_DIR||i.DOCUMENTS,DOWNLOADS:r.XDG_DOWNLOAD_DIR||i.DOWNLOADS};default:return t===`unknown`&&G(`Unknown platform detected, using default paths`),i}}var dEe=n((()=>{K(),ao()}));function bk(e){return e.endsWith(`.mcpb`)||e.endsWith(`.dxt`)}function fEe(e){return e.startsWith(`http://`)||e.startsWith(`https://`)}function pEe(e){return Kc(`sha256`).update(e).digest(`hex`).substring(0,16)}function xk(e){return X(e,`.mcpb-cache`)}function Sk(e,t){return X(e,`${Kc(`md5`).update(t).digest(`hex`).substring(0,8)}.metadata.json`)}function Ck(e,t){return`${e}/${t}`}function wk(e,t){try{let n=fi().pluginConfigs?.[e]?.mcpServers?.[t],r=vk().read()?.pluginSecrets?.[Ck(e,t)];return!n&&!r?null:(G(`Loaded user config for ${e}/${t} (settings + secureStorage)`),{...n,...r})}catch(n){return J(tr(n)),G(`Failed to load user config for ${e}/${t}: ${n}`,{level:`error`}),null}}function Tk(e,t,n,r){try{let i={},a={};for(let[e,t]of Object.entries(n))r[e]?.sensitive===!0?a[e]=String(t):i[e]=t;let o=new Set(Object.keys(a)),s=new Set(Object.keys(i)),c=vk(),l=Ck(e,t),u=c.read()?.pluginSecrets?.[l]??void 0,d=u?Object.fromEntries(Object.entries(u).filter(([e])=>!s.has(e))):void 0,f=d&&u&&Object.keys(d).length!==Object.keys(u).length;if(Object.keys(a).length>0||f){let e=c.read()??{};e.pluginSecrets||(e.pluginSecrets={}),e.pluginSecrets[l]={...d,...a};let t=c.update(e);if(!t.success)throw Error(`Failed to save sensitive config to secure storage for ${l}`);t.warning&&G(`Server secrets save warning: ${t.warning}`,{level:`warn`}),f&&G(`saveMcpServerUserConfig: scrubbed ${Object.keys(u).length-Object.keys(d).length} stale non-sensitive key(s) from secureStorage for ${l}`)}let p=fi(),m=p.pluginConfigs?.[e]?.mcpServers?.[t]??{},h=Object.keys(m).filter(e=>o.has(e));if(Object.keys(i).length>0||h.length>0){p.pluginConfigs||(p.pluginConfigs={}),p.pluginConfigs[e]||(p.pluginConfigs[e]={}),p.pluginConfigs[e].mcpServers||(p.pluginConfigs[e].mcpServers={});let n=Object.fromEntries(h.map(e=>[e,void 0]));p.pluginConfigs[e].mcpServers[t]={...i,...n};let r=li(`userSettings`,p);if(r.error)throw r.error;h.length>0&&G(`saveMcpServerUserConfig: scrubbed ${h.length} plaintext sensitive key(s) from settings.json for ${e}/${t}`)}G(`Saved user config for ${e}/${t} (${Object.keys(i).length} non-sensitive, ${Object.keys(a).length} sensitive)`)}catch(n){let r=tr(n);throw J(r),Error(`Failed to save user configuration for ${e}/${t}: ${r.message}`)}}function Ek(e,t){let n=[];for(let[r,i]of Object.entries(t)){let t=e[r];if(i.required&&(t===void 0||t===``)){n.push(`${i.title||r} is required but not provided`);continue}t===void 0||t===``||(i.type===`string`?Array.isArray(t)?i.multiple?t.every(e=>typeof e==`string`)||n.push(`${i.title||r} must be an array of strings`):n.push(`${i.title||r} must be a string, not an array`):typeof t!=`string`&&n.push(`${i.title||r} must be a string`):i.type===`number`&&typeof t!=`number`?n.push(`${i.title||r} must be a number`):i.type===`boolean`&&typeof t!=`boolean`?n.push(`${i.title||r} must be a boolean`):(i.type===`file`||i.type===`directory`)&&typeof t!=`string`&&n.push(`${i.title||r} must be a path string`),i.type===`number`&&typeof t==`number`&&(i.min!==void 0&&t<i.min&&n.push(`${i.title||r} must be at least ${i.min}`),i.max!==void 0&&t>i.max&&n.push(`${i.title||r} must be at most ${i.max}`)))}return{valid:n.length===0,errors:n}}async function Dk(e,t,n={}){let{getMcpConfigForManifest:r}=await import(`./dist-DIee4wq1.js`),i=await r({manifest:e,extensionPath:t,systemDirs:uEe(),userConfig:n,pathSeparator:`/`});if(!i){let t=Error(`Failed to generate MCP server configuration from manifest "${e.name}"`);throw J(t),t}return i}async function Ok(e,t){let n=q(),r=Sk(e,t);try{return $n(await n.readFile(r,{encoding:`utf-8`}))}catch(e){return Xn(e)===`ENOENT`?null:(J(tr(e)),G(`Failed to load MCPB cache metadata: ${e}`,{level:`error`}),null)}}async function kk(e,t,n){let r=Sk(e,t);await q().mkdir(e),await ll(r,U(n,null,2),`utf-8`)}async function mEe(e,t,n){G(`Downloading MCPB from ${e}`),n&&n(`Downloading ${e}...`);let r=performance.now(),i=!1;try{let a=await Le.get(e,{timeout:12e4,responseType:`arraybuffer`,maxRedirects:5,onDownloadProgress:e=>{e.total&&n&&n(`Downloading... ${Math.round(e.loaded/e.total*100)}%`)}}),o=new Uint8Array(a.data);return Ny(`mcpb`,e,`success`,performance.now()-r),i=!0,await ll(t,Buffer.from(o)),G(`Downloaded ${o.length} bytes to ${t}`),n&&n(`Download complete`),o}catch(t){i||Ny(`mcpb`,e,`failure`,performance.now()-r,Py(t));let n=W(t),a=Error(`Failed to download MCPB file from ${e}: ${n}`);throw J(a),a}}async function hEe(e,t,n,r){r&&r(`Extracting files...`),await q().mkdir(t);let i=0,a=Object.entries(e).filter(([e])=>!e.endsWith(`/`)),o=a.length;for(let[e,s]of a){let a=X(t,e),c=xc(a);c!==t&&await q().mkdir(c),e.endsWith(`.json`)||e.endsWith(`.js`)||e.endsWith(`.ts`)||e.endsWith(`.txt`)||e.endsWith(`.md`)||e.endsWith(`.yml`)||e.endsWith(`.yaml`)?await ll(a,new TextDecoder().decode(s),`utf-8`):await ll(a,Buffer.from(s));let l=n[e];l&&l&73&&await Xc(a,l&511).catch(()=>{}),i++,r&&i%10==0&&r(`Extracted ${i}/${o} files`)}G(`Extracted ${i} files to ${t}`),r&&r(`Extraction complete (${i} files)`)}async function gEe(e,t){let n=q(),r=await Ok(xk(t),e);if(!r)return!0;try{await n.stat(r.extractedPath)}catch(e){return Xn(e)===`ENOENT`?G(`MCPB extraction path missing: ${r.extractedPath}`):G(`MCPB extraction path inaccessible: ${r.extractedPath}: ${e}`,{level:`error`}),!0}if(!fEe(e)){let i=X(t,e),a;try{a=await n.stat(i)}catch(e){return Xn(e)===`ENOENT`?G(`MCPB source file missing: ${i}`):G(`MCPB source file inaccessible: ${i}: ${e}`,{level:`error`}),!0}let o=new Date(r.cachedAt).getTime(),s=Math.floor(a.mtimeMs);if(s>o)return G(`MCPB file modified: ${new Date(s)} > ${new Date(o)}`),!0}return!1}async function Ak(e,t,n,r,i,a){let o=q(),s=xk(t);await o.mkdir(s),G(`Loading MCPB from source: ${e}`);let c=await Ok(s,e);if(c&&!await gEe(e,t)){G(`Using cached MCPB from ${c.extractedPath} (hash: ${c.contentHash})`);let e=X(c.extractedPath,`manifest.json`),t;try{t=await o.readFile(e,{encoding:`utf-8`})}catch(t){if(Qn(t)){let t=Error(`Cached manifest not found: ${e}`);throw J(t),t}throw t}let r=await tk(new TextEncoder().encode(t));if(r.user_config&&Object.keys(r.user_config).length>0){let e=r.name,t=wk(n,e),o=i||t||{},s=Ek(o,r.user_config);return a||!s.valid?{status:`needs-config`,manifest:r,extractedPath:c.extractedPath,contentHash:c.contentHash,configSchema:r.user_config,existingConfig:t||{},validationErrors:s.valid?[]:s.errors}:(i&&Tk(n,e,i,r.user_config??{}),{manifest:r,mcpConfig:await Dk(r,c.extractedPath,o),extractedPath:c.extractedPath,contentHash:c.contentHash})}return{manifest:r,mcpConfig:await Dk(r,c.extractedPath),extractedPath:c.extractedPath,contentHash:c.contentHash}}let l,u;if(fEe(e))u=X(s,`${Kc(`md5`).update(e).digest(`hex`).substring(0,8)}.mcpb`),l=await mEe(e,u,r);else{let n=X(t,e);r&&r(`Loading ${e}...`);try{l=await o.readFileBytes(n),u=n}catch(e){if(Qn(e)){let e=Error(`MCPB file not found: ${n}`);throw J(e),e}throw e}}let d=pEe(l);G(`MCPB content hash: ${d}`),r&&r(`Extracting MCPB archive...`);let f=await nk(Buffer.from(l)),p=rk(l),m=f[`manifest.json`];if(!m){let e=Error(`No manifest.json found in MCPB file`);throw J(e),e}let h=await tk(m);if(G(`MCPB manifest: ${h.name} v${h.version} by ${h.author.name}`),!h.server){let e=Error(`MCPB manifest for "${h.name}" does not define a server configuration`);throw J(e),e}let g=X(s,d);if(await hEe(f,g,p,r),h.user_config&&Object.keys(h.user_config).length>0){let t=h.name,a=wk(n,t),o=i||a||{},c=Ek(o,h.user_config);if(!c.valid)return await kk(s,e,{source:e,contentHash:d,extractedPath:g,cachedAt:new Date().toISOString(),lastChecked:new Date().toISOString()}),{status:`needs-config`,manifest:h,extractedPath:g,contentHash:d,configSchema:h.user_config,existingConfig:a||{},validationErrors:c.errors};i&&Tk(n,t,i,h.user_config??{}),r&&r(`Generating MCP server configuration...`);let l=await Dk(h,g,o);return await kk(s,e,{source:e,contentHash:d,extractedPath:g,cachedAt:new Date().toISOString(),lastChecked:new Date().toISOString()}),{manifest:h,mcpConfig:l,extractedPath:g,contentHash:d}}r&&r(`Generating MCP server configuration...`);let _=await Dk(h,g);return await kk(s,e,{source:e,contentHash:d,extractedPath:g,cachedAt:new Date().toISOString(),lastChecked:new Date().toISOString()}),G(`Successfully loaded MCPB: ${h.name} (extracted to ${g})`),{manifest:h,mcpConfig:_,extractedPath:g,contentHash:d}}var jk=n((()=>{Re(),K(),tEe(),ak(),qn(),or(),Ga(),yk(),vi(),mr(),dEe(),Fy()}));function Mk(e){return e.source}function Nk(){Rk.cache?.clear?.()}function _Ee(e,t,n){let r={},i={};for(let[e,a]of Object.entries(t))n[e]?.sensitive===!0?i[e]=String(a):r[e]=a;let a=new Set(Object.keys(i)),o=new Set(Object.keys(r)),s=vk(),c=s.read()?.pluginSecrets?.[e]??void 0,l=c?Object.fromEntries(Object.entries(c).filter(([e])=>!o.has(e))):void 0,u=l&&c&&Object.keys(l).length!==Object.keys(c).length;if(Object.keys(i).length>0||u){let t=s.read()??{};t.pluginSecrets||(t.pluginSecrets={}),t.pluginSecrets[e]={...l,...i};let n=s.update(t);if(!n.success){let t=Error(`Failed to save sensitive plugin options for ${e} to secure storage`);throw J(t),t}n.warning&&G(`Plugin secrets save warning: ${n.warning}`,{level:`warn`})}let d=fi(),f=d.pluginConfigs?.[e]?.options??{},p=Object.keys(f).filter(e=>a.has(e));if(Object.keys(r).length>0||p.length>0){d.pluginConfigs||(d.pluginConfigs={}),d.pluginConfigs[e]||(d.pluginConfigs[e]={});let t=Object.fromEntries(p.map(e=>[e,void 0]));d.pluginConfigs[e].options={...r,...t};let n=li(`userSettings`,d);if(n.error)throw J(n.error),Error(`Failed to save plugin options for ${e}: ${n.error.message}`)}Nk()}function Pk(e){if(fi().pluginConfigs?.[e]){let{error:t}=li(`userSettings`,{pluginConfigs:{[e]:void 0}});t&&G(`deletePluginOptions: failed to clear settings.pluginConfigs[${e}]: ${t.message}`,{level:`warn`})}let t=vk(),n=t.read();if(n?.pluginSecrets){let r=`${e}/`,i=Object.entries(n.pluginSecrets).filter(([t])=>t!==e&&!t.startsWith(r));i.length!==Object.keys(n.pluginSecrets).length&&(t.update({...n,pluginSecrets:i.length>0?Object.fromEntries(i):void 0}).success||G(`deletePluginOptions: failed to clear pluginSecrets for ${e} from keychain`,{level:`warn`}))}Nk()}function vEe(e){let t=e.manifest.userConfig;if(!t||Object.keys(t).length===0)return{};let n=Rk(Mk(e));if(Ek(n,t).valid)return{};let r={};for(let[e,i]of Object.entries(t))Ek({[e]:n[e]},{[e]:i}).valid||(r[e]=i);return r}function Fk(e,t){let n=e=>process.platform===`win32`?e.replace(/\\/g,`/`):e,r=e.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g,()=>n(t.path));if(t.source){let e=t.source;r=r.replace(/\$\{CLAUDE_PLUGIN_DATA\}/g,()=>n(lb(e)))}return r}function Ik(e,t){return e.replace(/\$\{user_config\.([^}]+)\}/g,(e,n)=>{let r=t[n];if(r===void 0)throw Error(`Missing required user configuration value: ${n}. This should have been validated before variable substitution.`);return String(r)})}function Lk(e,t,n){return e.replace(/\$\{user_config\.([^}]+)\}/g,(e,r)=>{if(n[r]?.sensitive===!0)return`[sensitive option '${r}' not available in skill content]`;let i=t[r];return i===void 0?e:String(i)})}var Rk,zk=n((()=>{d(),K(),Ga(),yk(),vi(),jk(),ub(),Rk=u(e=>{let t=fi().pluginConfigs?.[e]?.options??{},n=vk().read()?.pluginSecrets?.[e]??{};return{...t,...n}})}));async function Bk(e,t,n){try{G(`Loading MCP servers from MCPB: ${t}`);let n=e.repository,r=await Ak(t,e.path,n,t=>{G(`MCPB [${e.name}]: ${t}`)});if(`status`in r&&r.status===`needs-config`)return G(`MCPB ${t} requires user configuration. User can configure via: /plugin → Manage plugins → ${e.name} → Configure`),null;let i=r,a=i.manifest.name;return G(`Loaded MCP server "${a}" from MCPB (extracted to ${i.extractedPath})`),{[a]:i.mcpConfig}}catch(r){let i=W(r);G(`Failed to load MCPB ${t}: ${i}`,{level:`error`});let a=`${e.name}@${e.repository}`;return t.startsWith(`http`)&&(i.includes(`download`)||i.includes(`network`))?n.push({type:`mcpb-download-failed`,source:a,plugin:e.name,url:t,reason:i}):i.includes(`manifest`)||i.includes(`user configuration`)?n.push({type:`mcpb-invalid-manifest`,source:a,plugin:e.name,mcpbPath:t,validationError:i}):n.push({type:`mcpb-extract-failed`,source:a,plugin:e.name,mcpbPath:t,reason:i}),null}}async function Vk(e,t=[]){let n={},r=await Hk(e.path,`.mcp.json`);if(r&&(n={...n,...r}),e.manifest.mcpServers){let r=e.manifest.mcpServers;if(typeof r==`string`)if(bk(r)){let i=await Bk(e,r,t);i&&(n={...n,...i})}else{let t=await Hk(e.path,r);t&&(n={...n,...t})}else if(Array.isArray(r)){let i=await Promise.all(r.map(async n=>{try{return typeof n==`string`?bk(n)?await Bk(e,n,t):await Hk(e.path,n):n}catch(t){return G(`Failed to load MCP servers from spec for plugin ${e.name}: ${t}`,{level:`error`}),null}}));for(let e of i)e&&(n={...n,...e})}else n={...n,...r}}return Object.keys(n).length>0?n:void 0}async function Hk(e,t){let n=q(),r=X(e,t),i;try{i=await n.readFile(r,{encoding:`utf-8`})}catch(e){return Qn(e)||G(`Failed to load MCP servers from ${r}: ${e}`,{level:`error`}),null}try{let e=$n(i),t=e.mcpServers||e,n={};for(let[e,i]of Object.entries(t)){let t=At().safeParse(i);t.success?n[e]=t.data:G(`Invalid MCP server config for ${e} in ${r}: ${t.error.message}`,{level:`error`})}return n}catch(e){return G(`Failed to load MCP servers from ${r}: ${e}`,{level:`error`}),null}}function yEe(e){let t=e.manifest.channels;if(!t||t.length===0)return[];let n=e.repository,r=[];for(let e of t)!e.userConfig||Object.keys(e.userConfig).length===0||Ek(wk(n,e.server)??{},e.userConfig).valid||r.push({server:e.server,displayName:e.displayName??e.server,configSchema:e.userConfig});return r}function bEe(e,t){if(e.manifest.channels?.find(e=>e.server===t)?.userConfig)return wk(e.repository,t)??void 0}function xEe(e,t,n){let r={};for(let[i,a]of Object.entries(e)){let e=`plugin:${t}:${i}`;r[e]={...a,scope:`dynamic`,pluginSource:n}}return r}function SEe(e,t){let n=e.manifest.userConfig?Rk(Mk(e)):void 0,r=bEe(e,t);if(!(!n&&!r))return{...n,...r}}function CEe(e,t,n,r,i,a){let o=[],s=e=>{let r=Fk(e,t);n&&(r=Ik(r,n));let{expanded:i,missingVars:a}=$O(r);return o.push(...a),i},c;switch(e.type){case void 0:case`stdio`:{let n={...e};n.command&&(n.command=s(n.command)),n.args&&(n.args=n.args.map(e=>s(e)));let r={CLAUDE_PLUGIN_ROOT:t.path,CLAUDE_PLUGIN_DATA:lb(t.source),...n.env||{}};for(let[e,t]of Object.entries(r))e!==`CLAUDE_PLUGIN_ROOT`&&e!==`CLAUDE_PLUGIN_DATA`&&(r[e]=s(t));n.env=r,c=n;break}case`sse`:case`http`:case`ws`:{let t={...e};if(t.url&&(t.url=s(t.url)),t.headers){let e={};for(let[n,r]of Object.entries(t.headers))e[n]=s(r);t.headers=e}c=t;break}case`sse-ide`:case`ws-ide`:case`sdk`:case`claudeai-proxy`:c=e;break}if(r&&o.length>0){let e=[...new Set(o)].join(`, `);G(`Missing environment variables in plugin MCP config: ${e}`,{level:`warn`}),i&&a&&r.push({type:`mcp-config-invalid`,source:`plugin:${i}`,plugin:i,serverName:a,validationError:`Missing environment variables: ${e}`})}return c}async function wEe(e,t=[]){if(!e.enabled)return;let n=e.mcpServers||await Vk(e,t);if(!n)return;let r={};for(let[i,a]of Object.entries(n)){let n=SEe(e,i);try{r[i]=CEe(a,e,n,t,e.name,i)}catch(n){t?.push({type:`generic-error`,source:i,plugin:e.name,error:W(n)})}}return xEe(r,e.name,e.source)}var Uk=n((()=>{ek(),wt(),K(),qn(),or(),mr(),jk(),ub(),zk()}));function Wk(){return X(ti(),`managed-mcp.json`)}function Gk(e,t){if(!e)return{};let n={};for(let[r,i]of Object.entries(e))n[r]={...i,scope:t};return n}async function Kk(e){let t=X(H(),`.mcp.json`),n;try{n=(await ol(t)).mode}catch(e){if(Xn(e)!==`ENOENT`)throw e}let r=`${t}.tmp.${process.pid}.${Date.now()}`,i=await el(r,`w`,n??420);try{await i.writeFile(U(e,null,2),{encoding:`utf8`}),await i.datasync()}finally{await i.close()}try{n!==void 0&&await Xc(r,n),await il(r,t)}catch(e){try{await cl(r)}catch{}throw e}}function qk(e){if(e.type!==void 0&&e.type!==`stdio`)return null;let t=e;return[t.command,...t.args??[]]}function Jk(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Yk(e){return`url`in e?e.url:null}function TEe(e){if(!uA.some(t=>e.includes(t)))return e;try{return new URL(e).searchParams.get(`mcp_url`)||e}catch{return e}}function Xk(e){let t=qk(e);if(t)return`stdio:${U(t)}`;let n=Yk(e);return n?`url:${TEe(n)}`:null}function EEe(e,t){let n=new Map;for(let[e,r]of Object.entries(t)){let t=Xk(r);t&&!n.has(t)&&n.set(t,e)}let r={},i=[],a=new Map;for(let[t,o]of Object.entries(e)){let e=Xk(o);if(e===null){r[t]=o;continue}let s=n.get(e);if(s!==void 0){G(`Suppressing plugin MCP server "${t}": duplicates manually-configured "${s}"`),i.push({name:t,duplicateOf:s});continue}let c=a.get(e);if(c!==void 0){G(`Suppressing plugin MCP server "${t}": duplicates earlier plugin server "${c}"`),i.push({name:t,duplicateOf:c});continue}a.set(e,t),r[t]=o}return{servers:r,suppressed:i}}function DEe(e){let t=e.replace(/[.+?^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`.*`);return RegExp(`^${t}$`)}function Zk(e,t){return DEe(t).test(e)}function OEe(){return PEe()?zi(`policySettings`)??{}:Vi()}function kEe(){return Vi()}function Qk(e,t){let n=kEe();if(!n.deniedMcpServers)return!1;for(let t of n.deniedMcpServers)if(Or(t)&&t.serverName===e)return!0;if(t){let e=qk(t);if(e){for(let t of n.deniedMcpServers)if(Vr(t)&&Jk(t.serverCommand,e))return!0}let r=Yk(t);if(r){for(let e of n.deniedMcpServers)if(Mr(e)&&Zk(r,e.serverUrl))return!0}}return!1}function $k(e,t){if(Qk(e,t))return!1;let n=OEe();if(!n.allowedMcpServers)return!0;if(n.allowedMcpServers.length===0)return!1;let r=n.allowedMcpServers.some(Vr),i=n.allowedMcpServers.some(Mr);if(t){let a=qk(t),o=Yk(t);if(a)if(r){for(let e of n.allowedMcpServers)if(Vr(e)&&Jk(e.serverCommand,a))return!0;return!1}else{for(let t of n.allowedMcpServers)if(Or(t)&&t.serverName===e)return!0;return!1}else if(o)if(i){for(let e of n.allowedMcpServers)if(Mr(e)&&Zk(o,e.serverUrl))return!0;return!1}else{for(let t of n.allowedMcpServers)if(Or(t)&&t.serverName===e)return!0;return!1}else{for(let t of n.allowedMcpServers)if(Or(t)&&t.serverName===e)return!0;return!1}}for(let t of n.allowedMcpServers)if(Or(t)&&t.serverName===e)return!0;return!1}function AEe(e){let t={},n=[];for(let[r,i]of Object.entries(e)){let e=i;e.type===`sdk`||$k(r,e)?t[r]=i:n.push(r)}return{allowed:t,blocked:n}}function jEe(e){let t=[];function n(e){let{expanded:n,missingVars:r}=$O(e);return t.push(...r),n}let r;switch(e.type){case void 0:case`stdio`:{let t=e;r={...t,command:n(t.command),args:t.args.map(n),env:t.env?_g(t.env,n):void 0};break}case`sse`:case`http`:case`ws`:{let t=e;r={...t,url:n(t.url),headers:t.headers?_g(t.headers,n):void 0};break}case`sse-ide`:case`ws-ide`:r=e;break;case`sdk`:r=e;break;case`claudeai-proxy`:r=e;break}return{expanded:r,missingVars:[...new Set(t)]}}async function MEe(e,t,n){if(e.match(/[^a-zA-Z0-9_-]/))throw Error(`Invalid name ${e}. Names can only contain letters, numbers, hyphens, and underscores.`);if(dA())throw Error(`Cannot add MCP server: enterprise MCP configuration is active and has exclusive control over MCP servers`);let r=At().safeParse(t);if(!r.success){let e=r.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`, `);throw Error(`Invalid configuration: ${e}`)}let i=r.data;if(Qk(e,i))throw Error(`Cannot add MCP server "${e}": server is explicitly blocked by enterprise policy`);if(!$k(e,i))throw Error(`Cannot add MCP server "${e}": not allowed by enterprise policy`);switch(n){case`project`:{let{servers:t}=eA();if(t[e])throw Error(`MCP server ${e} already exists in .mcp.json`);break}case`user`:if(ha().mcpServers?.[e])throw Error(`MCP server ${e} already exists in user config`);break;case`local`:if(pa().mcpServers?.[e])throw Error(`MCP server ${e} already exists in local config`);break;case`dynamic`:throw Error(`Cannot add MCP server to scope: dynamic`);case`enterprise`:throw Error(`Cannot add MCP server to scope: enterprise`);case`claudeai`:throw Error(`Cannot add MCP server to scope: claudeai`)}switch(n){case`project`:{let{servers:t}=eA(),n={};for(let[e,r]of Object.entries(t)){let{scope:t,...i}=r;n[e]=i}n[e]=i;let r={mcpServers:n};try{await Kk(r)}catch(e){throw Error(`Failed to write to .mcp.json: ${e}`)}break}case`user`:aa(t=>({...t,mcpServers:{...t.mcpServers,[e]:i}}));break;case`local`:la(t=>({...t,mcpServers:{...t.mcpServers,[e]:i}}));break;default:throw Error(`Cannot add MCP server to scope: ${n}`)}}async function NEe(e,t){switch(t){case`project`:{let{servers:t}=eA();if(!t[e])throw Error(`No MCP server found with name: ${e} in .mcp.json`);let n={};for(let[r,i]of Object.entries(t))if(r!==e){let{scope:e,...t}=i;n[r]=t}let r={mcpServers:n};try{await Kk(r)}catch(e){throw Error(`Failed to remove from .mcp.json: ${e}`)}break}case`user`:if(!ha().mcpServers?.[e])throw Error(`No user-scoped MCP server found with name: ${e}`);aa(t=>{let{[e]:n,...r}=t.mcpServers??{};return{...t,mcpServers:r}});break;case`local`:if(!pa().mcpServers?.[e])throw Error(`No project-local MCP server found with name: ${e}`);la(t=>{let{[e]:n,...r}=t.mcpServers??{};return{...t,mcpServers:r}});break;default:throw Error(`Cannot remove MCP server from scope: ${t}`)}}function eA(){if(!Wi(`projectSettings`))return{servers:{},errors:[]};let e=X(H(),`.mcp.json`),{config:t,errors:n}=oA({filePath:e,expandVars:!0,scope:`project`});if(!t){let t=n.filter(e=>!e.message.startsWith(`MCP config file not found`));return t.length>0?(G(`MCP config errors for ${e}: ${U(t.map(e=>e.message))}`,{level:`error`}),{servers:{},errors:t}):{servers:{},errors:[]}}return{servers:t.mcpServers?Gk(t.mcpServers,`project`):{},errors:n||[]}}function tA(e){let t={project:`projectSettings`,user:`userSettings`,local:`localSettings`};if(e in t&&!Wi(t[e]))return{servers:{},errors:[]};switch(e){case`project`:{let t={},n=[],r=[],i=H();for(;i!==Tc(i).root;)r.push(i),i=xc(i);for(let i of r.reverse()){let r=X(i,`.mcp.json`),{config:a,errors:o}=oA({filePath:r,expandVars:!0,scope:`project`});if(!a){let e=o.filter(e=>!e.message.startsWith(`MCP config file not found`));e.length>0&&(G(`MCP config errors for ${r}: ${U(e.map(e=>e.message))}`,{level:`error`}),n.push(...e));continue}a.mcpServers&&Object.assign(t,Gk(a.mcpServers,e)),o.length>0&&n.push(...o)}return{servers:t,errors:n}}case`user`:{let t=ha().mcpServers;if(!t)return{servers:{},errors:[]};let{config:n,errors:r}=aA({configObject:{mcpServers:t},expandVars:!0,scope:`user`});return{servers:Gk(n?.mcpServers,e),errors:r}}case`local`:{let t=pa().mcpServers;if(!t)return{servers:{},errors:[]};let{config:n,errors:r}=aA({configObject:{mcpServers:t},expandVars:!0,scope:`local`});return{servers:Gk(n?.mcpServers,e),errors:r}}case`enterprise`:{let t=Wk(),{config:n,errors:r}=oA({filePath:t,expandVars:!0,scope:`enterprise`});if(!n){let e=r.filter(e=>!e.message.startsWith(`MCP config file not found`));return e.length>0?(G(`Enterprise MCP config errors for ${t}: ${U(e.map(e=>e.message))}`,{level:`error`}),{servers:{},errors:e}):{servers:{},errors:[]}}return{servers:Gk(n.mcpServers,e),errors:r}}}}function nA(e){let{servers:t}=tA(`enterprise`);if(fx(`mcp`))return t[e]??null;let{servers:n}=tA(`user`),{servers:r}=tA(`project`),{servers:i}=tA(`local`);return t[e]?t[e]:i[e]?i[e]:r[e]?r[e]:n[e]?n[e]:null}async function rA(e={},t=Promise.resolve({})){let{servers:n}=tA(`enterprise`);if(dA()){let e={};for(let[t,r]of Object.entries(n))$k(t,r)&&(e[t]=r);return{servers:e,errors:[]}}let r=fx(`mcp`),i={servers:{}},{servers:a}=r?i:tA(`user`),{servers:o}=r?i:tA(`project`),{servers:s}=r?i:tA(`local`),c={},l=await F4(),u=[];if(l.errors.length>0)for(let e of l.errors)if(e.type===`mcp-config-invalid`||e.type===`mcpb-download-failed`||e.type===`mcpb-extract-failed`||e.type===`mcpb-invalid-manifest`){let t=`Plugin MCP loading error - ${e.type}: ${_y(e)}`;J(Error(t))}else{let t=e.type;G(`Plugin not available for MCP: ${e.source} - error type: ${t}`)}let d=await Promise.all(l.enabled.map(e=>wEe(e,u)));for(let e of d)e&&Object.assign(c,e);if(u.length>0)for(let e of u){let t=`Plugin MCP server error - ${e.type}: ${_y(e)}`;J(Error(t))}let f={};for(let[e,t]of Object.entries(o))bA(e)===`approved`&&(f[e]=t);let p=await t,m={};for(let[t,n]of Object.entries({...a,...f,...s,...e,...p}))!cA(t)&&$k(t,n)&&(m[t]=n);let h={},g={};for(let[e,t]of Object.entries(c))cA(e)||!$k(e,t)?g[e]=t:h[e]=t;let{servers:_,suppressed:v}=EEe(h,m);Object.assign(_,g);for(let{name:e,duplicateOf:t}of v){let n=e.split(`:`);n[0]!==`plugin`||n.length<3||u.push({type:`mcp-server-suppressed-duplicate`,source:e,plugin:n[1],serverName:n.slice(2).join(`:`),duplicateOf:t})}let y=Object.assign({},_,a,f,s),b={};for(let[e,t]of Object.entries(y))$k(e,t)&&(b[e]=t);return{servers:b,errors:u}}async function iA(){if(dA())return rA();let{servers:e,errors:t}=await rA();return{servers:e,errors:t}}function aA(e){let{configObject:t,expandVars:n,scope:r,filePath:i}=e,a=Bee().safeParse(t);if(!a.success)return{config:null,errors:a.error.issues.map(e=>({...i&&{file:i},path:e.path.join(`.`),message:`Does not adhere to MCP server configuration schema`,mcpErrorMetadata:{scope:r,severity:`fatal`}}))};let o=[],s={};for(let[e,t]of Object.entries(a.data.mcpServers)){let a=t;if(n){let{expanded:n,missingVars:s}=jEe(t);s.length>0&&o.push({...i&&{file:i},path:`mcpServers.${e}`,message:`Missing environment variables: ${s.join(`, `)}`,suggestion:`Set the following environment variables: ${s.join(`, `)}`,mcpErrorMetadata:{scope:r,serverName:e,severity:`warning`}}),a=n}io()===`windows`&&(!a.type||a.type===`stdio`)&&`command`in a&&(a.command===`npx`||a.command.endsWith(`\\npx`)||a.command.endsWith(`/npx`))&&o.push({...i&&{file:i},path:`mcpServers.${e}`,message:`Windows requires 'cmd /c' wrapper to execute npx`,suggestion:`Change command to "cmd" with args ["/c", "npx", ...]. See: https://code.workmate.com/docs/en/mcp#configure-mcp-servers`,mcpErrorMetadata:{scope:r,serverName:e,severity:`warning`}}),s[e]=a}return{config:{mcpServers:s},errors:o}}function oA(e){let{filePath:t,expandVars:n,scope:r}=e,i=q(),a;try{a=i.readFileSync(t,{encoding:`utf8`})}catch(e){return Xn(e)===`ENOENT`?{config:null,errors:[{file:t,path:``,message:`MCP config file not found: ${t}`,suggestion:`Check that the file path is correct`,mcpErrorMetadata:{scope:r,severity:`fatal`}}]}:(G(`MCP config read error for ${t} (scope=${r}): ${e}`,{level:`error`}),{config:null,errors:[{file:t,path:``,message:`Failed to read file: ${e}`,suggestion:`Check file permissions and ensure the file exists`,mcpErrorMetadata:{scope:r,severity:`fatal`}}]})}let o=Et(a);return o?aA({configObject:o,expandVars:n,scope:r,filePath:t}):(G(`MCP config is not valid JSON: ${t} (scope=${r}, length=${a.length}, first100=${U(a.slice(0,100))})`,{level:`error`}),{config:null,errors:[{file:t,path:``,message:`MCP config is not a valid JSON`,suggestion:`Fix the JSON syntax errors in the file`,mcpErrorMetadata:{scope:r,severity:`fatal`}}]})}function PEe(){return zi(`policySettings`)?.allowManagedMcpServersOnly===!0}function FEe(e){return Object.values(e).every(e=>e.type===`sdk`&&e.name===`claude-vscode`)}function sA(e){return fA.has(e)}function cA(e){let t=pa();return sA(e)?!(t.enabledMcpServers||[]).includes(e):(t.disabledMcpServers||[]).includes(e)}function lA(e,t,n){return e.includes(t)===n?e:n?[...e,t]:e.filter(e=>e!==t)}function IEe(e,t){let n=sA(e)&&cA(e)===t;la(n=>{if(sA(e)){let r=n.enabledMcpServers||[],i=lA(r,e,t);return i===r?n:{...n,enabledMcpServers:i}}let r=n.disabledMcpServers||[],i=lA(r,e,!t);return i===r?n:{...n,disabledMcpServers:i}}),n&&Y(`tengu_builtin_mcp_toggle`,{serverName:e,enabled:t})}var uA,dA,fA,pA=n((()=>{vg(),d(),ao(),vy(),ma(),Vn(),K(),qn(),or(),Ot(),Ga(),Uk(),I4(),wi(),Ur(),mx(),vi(),Rr(),mr(),oo(),ek(),wt(),CA(),uA=[`/v2/session_ingress/shttp/mcp/`,`/v2/ccr-sessions/`],dA=u(()=>{let{config:e}=oA({filePath:Wk(),expandVars:!0,scope:`enterprise`});return e!==null}),fA=new Set([])}));function LEe(e,t){let n=`mcp__${Mi(t)}__`;return e.filter(e=>e.name?.startsWith(n))}function mA(e,t){let n=Mi(t),r=e.name;return r?r.startsWith(`mcp__${n}__`)||r.startsWith(`${n}:`):!1}function REe(e,t){return e.filter(e=>mA(e,t)&&!(e.type===`prompt`&&e.loadedFrom===`mcp`))}function hA(e,t){let n=`mcp__${Mi(t)}__`;return e.filter(e=>!e.name?.startsWith(n))}function gA(e,t){return e.filter(e=>!mA(e,t))}function _A(e,t){let n={...e};return delete n[t],n}function vA(e){let{scope:t,...n}=e,r=U(n,(e,t)=>{if(t&&typeof t==`object`&&!Array.isArray(t)){let e=t,n={};for(let t of Object.keys(e).sort())n[t]=e[t];return n}return t});return Kc(`sha256`).update(r).digest(`hex`).slice(0,16)}function zEe(e,t){let n=e.clients.filter(e=>{let n=t[e.name];return n?vA(e.config)!==vA(n):e.config.scope===`dynamic`});if(n.length===0)return{...e,stale:[]};let{tools:r,commands:i,resources:a}=e;for(let e of n)r=hA(r,e.name),i=gA(i,e.name),a=_A(a,e.name);let o=new Set(n.map(e=>e.name));return{clients:e.clients.filter(e=>!o.has(e.name)),tools:r,commands:i,resources:a,stale:n}}function yA(e){return e.name?.startsWith(`mcp__`)||e.isMcp===!0}function BEe(e){switch(e){case`user`:return Rne();case`project`:return X(H(),`.mcp.json`);case`local`:return`${Rne()} [project: ${H()}]`;case`dynamic`:return`Dynamically configured`;case`enterprise`:return Wk();case`claudeai`:return`claude.ai`;default:return e}}function VEe(e){switch(e){case`local`:return`Local config (private to you in this project)`;case`project`:return`Project config (shared via .mcp.json)`;case`user`:return`User config (available in all your projects)`;case`dynamic`:return`Dynamic config (from command line)`;case`enterprise`:return`Enterprise config (managed by your organization)`;case`claudeai`:return`claude.ai config`;default:return e}}function HEe(e){if(!e)return`local`;if(!jt().options.includes(e))throw Error(`Invalid scope: ${e}. Must be one of: ${jt().options.join(`, `)}`);return e}function UEe(e){if(!e)return`stdio`;if(e!==`stdio`&&e!==`sse`&&e!==`http`)throw Error(`Invalid transport type: ${e}. Must be one of: stdio, sse, http`);return e}function WEe(e){let t={};for(let n of e){let e=n.indexOf(`:`);if(e===-1)throw Error(`Invalid header format: "${n}". Expected format: "Header-Name: value"`);let r=n.substring(0,e).trim(),i=n.substring(e+1).trim();if(!r)throw Error(`Invalid header: "${n}". Header name cannot be empty.`);t[r]=i}return t}function bA(e){let t=fi(),n=Mi(e);return t?.disabledMcpjsonServers?.some(e=>Mi(e)===n)?`rejected`:t?.enabledMcpjsonServers?.some(e=>Mi(e)===n)||t?.enableAllProjectMcpServers||Rre()&&Wi(`projectSettings`)||qt()&&Wi(`projectSettings`)?`approved`:`pending`}function xA(e){if(!yA({name:e}))return null;let t=bi(e);if(!t)return null;let n=nA(t.serverName);return!n&&t.serverName.startsWith(`claude_ai_`)?`claudeai`:n?.scope??null}function GEe(e){return e.type===`stdio`||e.type===void 0}function KEe(e){return e.type===`sse`}function qEe(e){return e.type===`http`}function JEe(e){return e.type===`ws`}function YEe(e){let t=new Map;for(let n of e)if(n.mcpServers?.length)for(let e of n.mcpServers){if(typeof e==`string`)continue;let r=Object.entries(e);if(r.length!==1)continue;let[i,a]=r[0],o=t.get(i);o?o.sourceAgents.includes(n.agentType)||o.sourceAgents.push(n.agentType):t.set(i,{config:{...a,name:i},sourceAgents:[n.agentType]})}let n=[];for(let[e,{config:r,sourceAgents:i}]of t)GEe(r)?n.push({name:e,sourceAgents:i,transport:`stdio`,command:r.command,needsAuth:!1}):KEe(r)?n.push({name:e,sourceAgents:i,transport:`sse`,url:r.url,needsAuth:!0}):qEe(r)?n.push({name:e,sourceAgents:i,transport:`http`,url:r.url,needsAuth:!0}):JEe(r)&&n.push({name:e,sourceAgents:i,transport:`ws`,url:r.url,needsAuth:!1});return n.sort((e,t)=>e.name.localeCompare(t.name))}function SA(e){if(!(!(`url`in e)||typeof e.url!=`string`))try{let t=new URL(e.url);return t.search=``,t.toString().replace(/\/$/,``)}catch{return}}var CA=n((()=>{Jt(),Vn(),Ii(),wi(),vi(),mr(),pA(),Ri(),ci(),wt()}));function XEe(e){return e.replace(/([a-z])([A-Z])/g,`$1_$2`).replace(/-/g,`_`).toLowerCase()}function ZEe(e,t){let n=XEe(t);return{isSearch:wA.has(n),isRead:TA.has(n)}}var wA,TA,QEe=n((()=>{wA=new Set(`slack_search_public.slack_search_public_and_private.slack_search_channels.slack_search_users.search_code.search_repositories.search_issues.search_pull_requests.search_orgs.search_users.search_documentation.search_logs.search_spans.search_rum_events.search_audit_logs.search_monitors.search_monitor_groups.find_slow_spans.find_monitors_matching_pattern.search_docs.search_events.search_issue_events.find_organizations.find_teams.find_projects.find_releases.find_dsns.search.gmail_search_messages.google_drive_search.gcal_find_my_free_time.gcal_find_meeting_times.gcal_find_user_emails.search_jira_issues_using_jql.search_confluence_using_cql.lookup_jira_account_id.confluence_search.jira_search.jira_search_fields.asana_search_tasks.asana_typeahead_search.search_files.search_nodes.brave_web_search.brave_local_search.search_dashboards.search_folders.search_docs.search_stripe_resources.search_stripe_documentation.search_articles.find_related_articles.lookup_article_by_citation.search_papers.search_pubmed.search_pubmed_key_words.search_pubmed_advanced.pubmed_search.pubmed_mesh_lookup.firecrawl_search.web_search_exa.web_search_advanced_exa.people_search_exa.linkedin_search_exa.deep_search_exa.perplexity_search.perplexity_search_web.tavily_search.obsidian_simple_search.obsidian_complex_search.find.search_knowledge.search_memories.find_memories_by_name.search_records.find_tasks.find_tasks_by_date.find_completed_tasks.find_projects.find_sections.find_comments.find_project_collaborators.find_activity.find_labels.find_filters.search_documentation.search_catalog.search_modules.search_providers.search_policies`.split(`.`)),TA=new Set(`slack_read_channel.slack_read_thread.slack_read_canvas.slack_read_user_profile.slack_list_channels.slack_get_channel_history.slack_get_thread_replies.slack_get_users.slack_get_user_profile.get_me.get_team_members.get_teams.get_commit.get_file_contents.get_repository_tree.list_branches.list_commits.list_releases.list_tags.get_latest_release.get_release_by_tag.get_tag.list_issues.issue_read.list_issue_types.get_label.list_label.pull_request_read.get_gist.list_gists.list_notifications.get_notification_details.projects_list.projects_get.actions_get.actions_list.get_job_logs.get_code_scanning_alert.list_code_scanning_alerts.get_dependabot_alert.list_dependabot_alerts.get_secret_scanning_alert.list_secret_scanning_alerts.get_global_security_advisory.list_global_security_advisories.list_org_repository_security_advisories.list_repository_security_advisories.get_discussion.get_discussion_comments.list_discussion_categories.list_discussions.list_starred_repositories.get_issue.get_pull_request.list_pull_requests.get_pull_request_files.get_pull_request_status.get_pull_request_comments.get_pull_request_reviews.list_comments.list_cycles.get_document.list_documents.list_issue_statuses.get_issue_status.list_my_issues.list_issue_labels.list_projects.get_project.list_project_labels.list_teams.get_team.list_users.get_user.aggregate_logs.list_spans.aggregate_spans.analyze_trace.trace_critical_path.query_metrics.aggregate_rum_events.list_rum_metrics.get_rum_metric.list_monitors.get_monitor.check_can_delete_monitor.validate_monitor.validate_existing_monitor.list_dashboards.get_dashboard.query_dashboard_widget.list_notebooks.get_notebook.query_notebook_cell.get_profiling_metrics.compare_profiling_metrics.whoami.get_issue_details.get_issue_tag_values.get_trace_details.get_event_attachment.get_doc.get_sentry_resource.list_events.list_issue_events.get_sentry_issue.fetch.get_comments.get_users.get_self.gmail_get_profile.gmail_read_message.gmail_read_thread.gmail_list_drafts.gmail_list_labels.google_drive_fetch.google_drive_export.gcal_list_calendars.gcal_list_events.gcal_get_event.atlassian_user_info.get_accessible_atlassian_resources.get_visible_jira_projects.get_jira_project_issue_types_metadata.get_jira_issue.get_transitions_for_jira_issue.get_jira_issue_remote_issue_links.get_confluence_spaces.get_confluence_page.get_pages_in_confluence_space.get_confluence_page_ancestors.get_confluence_page_descendants.get_confluence_page_footer_comments.get_confluence_page_inline_comments.confluence_get_page.confluence_get_page_children.confluence_get_comments.confluence_get_labels.jira_get_issue.jira_get_transitions.jira_get_worklog.jira_get_agile_boards.jira_get_board_issues.jira_get_sprints_from_board.jira_get_sprint_issues.jira_get_link_types.jira_download_attachments.jira_batch_get_changelogs.jira_get_user_profile.jira_get_project_issues.jira_get_project_versions.asana_get_attachment.asana_get_attachments_for_object.asana_get_goal.asana_get_goals.asana_get_parent_goals_for_goal.asana_get_portfolio.asana_get_portfolios.asana_get_items_for_portfolio.asana_get_project.asana_get_projects.asana_get_project_sections.asana_get_project_status.asana_get_project_statuses.asana_get_project_task_counts.asana_get_projects_for_team.asana_get_projects_for_workspace.asana_get_task.asana_get_tasks.asana_get_stories_for_task.asana_get_teams_for_workspace.asana_get_teams_for_user.asana_get_team_users.asana_get_time_period.asana_get_time_periods.asana_get_user.asana_get_workspace_users.asana_list_workspaces.read_file.read_text_file.read_media_file.read_multiple_files.list_directory.list_directory_with_sizes.directory_tree.get_file_info.list_allowed_directories.read_graph.open_nodes.query.read_query.list_tables.describe_table.git_status.git_diff.git_diff_unstaged.git_diff_staged.git_log.git_show.git_branch.list_teams.list_users_by_org.get_dashboard_by_uid.get_dashboard_summary.get_dashboard_property.get_dashboard_panel_queries.run_panel_query.list_datasources.get_datasource.get_query_examples.query_prometheus.query_prometheus_histogram.list_prometheus_metric_metadata.list_prometheus_metric_names.list_prometheus_label_names.list_prometheus_label_values.query_loki_logs.query_loki_stats.query_loki_patterns.list_loki_label_names.list_loki_label_values.list_incidents.get_incident.list_sift_investigations.get_sift_investigation.get_sift_analysis.list_oncall_schedules.get_oncall_shift.get_current_oncall_users.list_oncall_teams.list_oncall_users.list_alert_groups.get_alert_group.get_annotations.get_annotation_tags.get_panel_image.list_incidents.get_incident.get_outlier_incident.get_past_incidents.get_related_incidents.list_incident_notes.list_incident_workflows.get_incident_workflow.list_services.get_service.list_team_members.get_user_data.list_schedules.get_schedule.list_schedule_users.list_oncalls.list_log_entries.get_log_entry.list_escalation_policies.get_escalation_policy.list_event_orchestrations.get_event_orchestration.list_status_pages.get_status_page_post.list_alerts_from_incident.get_alert_from_incident.list_change_events.get_change_event.list_organizations.get_organization.get_cost.list_extensions.list_migrations.get_logs.get_advisors.get_project_url.get_publishable_keys.generate_typescript_types.list_edge_functions.get_edge_function.list_storage_buckets.get_storage_config.get_stripe_account_info.retrieve_balance.list_customers.list_products.list_prices.list_invoices.list_payment_intents.list_subscriptions.list_coupons.list_disputes.fetch_stripe_resources.get_article_metadata.get_full_text_article.convert_article_ids.get_copyright_status.download_paper.list_papers.read_paper.get_paper_fulltext.get_pubmed_article_metadata.download_pubmed_pdf.pubmed_fetch.pubmed_pmc_fetch.pubmed_spell.pubmed_cite.pubmed_related.bigquery_query.bigquery_schema.list_dataset_ids.list_table_ids.get_dataset_info.get_table_info.firecrawl_scrape.firecrawl_map.firecrawl_crawl.firecrawl_check_crawl_status.firecrawl_extract.get_code_context_exa.company_research_exa.crawling_exa.deep_researcher_check.perplexity_ask.perplexity_research.perplexity_reason.tavily_extract.tavily_crawl.tavily_map.tavily_research.obsidian_list_files_in_vault.obsidian_list_files_in_dir.obsidian_get_file_contents.obsidian_batch_get_file_contents.obsidian_get_periodic_note.obsidian_get_recent_periodic_notes.obsidian_get_recent_changes.get_figma_data.download_figma_images.browser_console_messages.browser_network_requests.browser_take_screenshot.browser_snapshot.browser_get_config.browser_route_list.browser_cookie_list.browser_cookie_get.browser_localstorage_list.browser_localstorage_get.browser_sessionstorage_list.browser_sessionstorage_get.browser_storage_state.puppeteer_screenshot.list_databases.list_collections.collection_indexes.collection_schema.collection_storage_size.db_stats.explain.mongodb_logs.aggregate.count.export.get_neo4j_schema.read_neo4j_cypher.list_instances.get_instance_details.get_instance_by_name.list_indices.get_mappings.esql.get_shards.list_records.list_bases.get_record.get_productivity_stats.get_overview.fetch_object.user_info.list_workspaces.view_attachment.get_available_services.read_documentation.read_sections.recommend.analyze_log_group.analyze_metric.describe_log_groups.get_active_alarms.get_alarm_history.get_metric_data.get_metric_metadata.kubectl_get.kubectl_describe.kubectl_logs.kubectl_context.explain_resource.list_api_resources.namespaces_list.nodes_log.nodes_top.pods_get.pods_list.pods_list_in_namespace.pods_log.pods_top.resources_get.resources_list`.split(`.`))}));function $Ee(e){return e.scope===`project`||e.scope===`local`}async function eDe(e,t){if(!t.headersHelper)return null;if(`scope`in t&&$Ee(t)&&!qt()&&!fa())return pr(`MCP headersHelper invoked before trust check`,Error(`Security: headersHelper for MCP server '${e}' executed before workspace trust is confirmed. If you see this message, post in .`)),Y(`tengu_mcp_headersHelper_missing_trust`,{}),null;try{Va(e,`Executing headersHelper to get dynamic headers`);let n=await ya(t.headersHelper,[],{shell:!0,timeout:1e4,env:{...process.env,CLAUDE_CODE_MCP_SERVER_NAME:e,CLAUDE_CODE_MCP_SERVER_URL:t.url}});if(n.code!==0||!n.stdout)throw Error(`headersHelper for MCP server '${e}' did not return a valid value`);let r=$n(n.stdout.trim());if(typeof r!=`object`||!r||Array.isArray(r))throw Error(`headersHelper for MCP server '${e}' must return a JSON object with string key-value pairs`);for(let[t,n]of Object.entries(r))if(typeof n!=`string`)throw Error(`headersHelper for MCP server '${e}' returned non-string value for key "${t}": ${typeof n}`);return Va(e,`Successfully retrieved ${Object.keys(r).length} headers from headersHelper`),r}catch(t){return Ua(e,`Error getting headers from headersHelper: ${W(t)}`),J(Error(`Error getting MCP headers from headersHelper for server '${e}': ${W(t)}`)),null}}async function EA(e,t){let n=t.headers||{},r=await eDe(e,t)||{};return{...n,...r}}var tDe=n((()=>{Jt(),ma(),K(),qn(),va(),Ga(),mr(),oo()})),DA,nDe=n((()=>{b(),DA=class{constructor(e,t){x(this,`serverName`,void 0),x(this,`sendMcpMessage`,void 0),x(this,`isClosed`,!1),x(this,`onclose`,void 0),x(this,`onerror`,void 0),x(this,`onmessage`,void 0),this.serverName=e,this.sendMcpMessage=t}async start(){}async send(e){if(this.isClosed)throw Error(`Transport is closed`);let t=await this.sendMcpMessage(this.serverName,e);this.onmessage&&this.onmessage(t)}async close(){this.isClosed||(this.isClosed=!0,this.onclose?.())}}}));function OA(e){return(`code`in e?e.code:void 0)===404?e.message.includes(`"code":-32001`)||e.message.includes(`"code": -32001`):!1}function rDe(){return parseInt(process.env.MCP_TOOL_TIMEOUT||``,10)||ZA}function kA(e){let t=SA(e);return t?{mcpServerBaseUrl:t}:{}}function AA(e,t,n){return Y(`tengu_mcp_server_needs_auth`,{transportType:n,...kA(t)}),Va(e,`Authentication required for ${{sse:`SSE`,http:`HTTP`,"claudeai-proxy":`claude.ai proxy`}[n]} server`),{name:e,type:`needs-auth`,config:t}}async function jA(e,t){let n=(await import(`./wrapper-K8ZapJVu.js`)).default;return new n(e,[`mcp`],t)}function MA(){return parseInt(process.env.MCP_TIMEOUT||``,10)||3e4}function NA(e){return async(t,n)=>{if((n?.method??`GET`).toUpperCase()===`GET`)return e(t,n);let r=new Headers(n?.headers);r.has(`accept`)||r.set(`accept`,tj);let i=new AbortController,a=setTimeout(e=>e.abort(new DOMException(`The operation timed out.`,`TimeoutError`)),ej,i);a.unref?.();let o=n?.signal,s=()=>i.abort(o?.reason);o?.addEventListener(`abort`,s),o?.aborted&&i.abort(o.reason);let c=()=>{clearTimeout(a),o?.removeEventListener(`abort`,s)};try{let a=await e(t,{...n,headers:r,signal:i.signal});return c(),a}catch(e){throw c(),e}}}function PA(){return parseInt(process.env.MCP_SERVER_CONNECTION_BATCH_SIZE||``,10)||3}function iDe(){return parseInt(process.env.MCP_REMOTE_SERVER_CONNECTION_BATCH_SIZE||``,10)||20}function FA(e){return!e.type||e.type===`stdio`||e.type===`sdk`}function aDe(e){return!e.name.startsWith(`mcp__ide__`)||nj.includes(e.name)}function IA(e,t){return`${e}-${U(t)}`}async function LA(e,t){let n=IA(e,t);try{let n=await rj(e,t);n.type===`connected`&&await n.cleanup()}catch{}rj.cache.delete(n),aj.cache.delete(e),oj.cache.delete(e),sj.cache.delete(e)}async function RA(e){if(e.config.type===`sdk`)return e;let t=await rj(e.name,e.config);if(t.type!==`connected`)throw new cr(`MCP server "${e.name}" is not connected`,`MCP server not connected`);return t}function oDe(e,t){if(e.type!==t.type)return!1;let{scope:n,...r}=e,{scope:i,...a}=t;return U(r)===U(a)}function sDe(e,t){let n=Object.keys(e);return n.length>0?n.map(t=>`${t}=${String(e[t])}`).join(` `):t}async function zA(e,t,n){return(await qA({client:n,tool:e,args:t,signal:BO().signal})).content}async function cDe(e,t){try{ck(),await LA(e,t);let n=await rj(e,t);if(n.type!==`connected`)return{client:n,tools:[],commands:[]};let r=!!n.capabilities?.resources,[i,a,o,s]=await Promise.all([aj(n),sj(n),Promise.resolve([]),r?oj(n):Promise.resolve([])]),c=[...a,...o],l=[];return r&&([fO,RO].some(e=>i.some(t=>Cs(t,e.name)))||l.push(fO,RO)),{client:n,tools:[...i,...l],commands:c,resources:s.length>0?s:void 0}}catch(n){return Ua(e,`Error during reconnection: ${W(n)}`),{client:{name:e,type:`failed`,config:t},tools:[],commands:[]}}}async function BA(e,t,n){await Zce(e,n,{concurrency:t})}async function VA(e,t){let n=!1,r=Object.entries(t??(await iA()).servers),i=[];for(let t of r)cA(t[0])?e({client:{name:t[0],type:`disabled`,config:t[1]},tools:[],commands:[]}):i.push(t);let a=i.length,o=Xr(i,([e,t])=>t.type===`stdio`),s=Xr(i,([e,t])=>t.type===`sse`),c=Xr(i,([e,t])=>t.type===`http`),l=Xr(i,([e,t])=>t.type===`sse-ide`),u=Xr(i,([e,t])=>t.type===`ws-ide`),d=i.filter(([e,t])=>FA(t)),f=i.filter(([e,t])=>!FA(t)),p={totalServers:a,stdioCount:o,sseCount:s,httpCount:c,sseIdeCount:l,wsIdeCount:u},m=async([t,r])=>{try{if(cA(t)){e({client:{name:t,type:`disabled`,config:r},tools:[],commands:[]});return}let i=await rj(t,r,p);if(i.type!==`connected`){e({client:i,tools:[],commands:[]});return}let a=!!i.capabilities?.resources,[o,s,c,l]=await Promise.all([aj(i),sj(i),Promise.resolve([]),a?oj(i):Promise.resolve([])]),u=[...s,...c],d=[];a&&!n&&(n=!0,d.push(fO,RO)),e({client:i,tools:[...o,...d],commands:u,resources:l.length>0?l:void 0})}catch(n){Ua(t,`Error fetching tools/commands/resources: ${W(n)}`),e({client:{name:t,type:`failed`,config:r},tools:[],commands:[]})}};await Promise.all([BA(d,PA(),m),BA(f,iDe(),m)])}function HA(e){return new Promise(t=>{let n=0,r=0;if(n=Object.keys(e).length,n===0){t({clients:[],tools:[],commands:[]});return}let i=[],a=[],o=[];VA(e=>{if(i.push(e.client),a.push(...e.tools),o.push(...e.commands),r++,r>=n){let e=o.reduce((e,t)=>e+(t.name.length+(t.description??``).length+(t.argumentHint??``).length),0);Y(`tengu_mcp_tools_commands_loaded`,{tools_count:a.length,commands_count:o.length,commands_metadata_length:e}),t({clients:i,tools:a,commands:o})}},e).catch(e=>{Ua(`prefetchAllMcpResources`,`Failed to get MCP resources: ${W(e)}`),t({clients:[],tools:[],commands:[]})})})}async function UA(e,t,n,r=!1){switch(e.type){case`text`:{let t={type:`text`,text:e.text};if(r){let n=e._meta;n&&(t._meta=n)}return[t]}case`audio`:{let n=e;return await WA(Buffer.from(n.data,`base64`),n.mimeType,t,`[Audio from ${t}] `)}case`image`:{let t=Buffer.from(String(e.data),`base64`),r=e.mimeType?.split(`/`)[1]||`png`,i=await wb(t,t.length,r,n);return[{type:`image`,source:{data:i.buffer.toString(`base64`),media_type:`image/${i.mediaType}`,type:`base64`}}]}case`resource`:{let r=e.resource,i=`[Resource from ${t} at ${r.uri}] `;if(`text`in r)return[{type:`text`,text:`${i}${r.text}`}];if(`blob`in r)if($A.has(r.mimeType??``)){let e=Buffer.from(r.blob,`base64`),t=r.mimeType?.split(`/`)[1]||`png`,a=await wb(e,e.length,t,n),o=[];return i&&o.push({type:`text`,text:i}),o.push({type:`image`,source:{data:a.buffer.toString(`base64`),media_type:`image/${a.mediaType}`,type:`base64`}}),o}else return await WA(Buffer.from(r.blob,`base64`),r.mimeType,t,i);return[]}case`resource_link`:{let t=e,n=`[Resource link: ${t.name}] ${t.uri}`;return t.description&&(n+=` (${t.description})`),[{type:`text`,text:n}]}default:return[]}}async function WA(e,t,n,r){let i=await AO(e,t,`mcp-${Mi(n)}-blob-${Date.now()}-${Math.random().toString(36).slice(2,8)}`);return`error`in i?[{type:`text`,text:`${r}Binary content (${t||`unknown type`}, ${e.length} bytes) could not be saved to disk: ${i.error}`}]:[{type:`text`,text:jO(i.filepath,t,i.size,r)}]}function GA(e,t=2){if(e===null)return`null`;if(Array.isArray(e))return e.length===0?`[]`:`[${GA(e[0],t-1)}]`;if(typeof e==`object`){if(t<=0)return`{...}`;let n=Object.entries(e).slice(0,10).map(([e,n])=>`${e}: ${GA(n,t-1)}`),r=Object.keys(e).length>10?`, ...`:``;return`{${n.join(`, `)}${r}}`}return typeof e}async function lDe(e,t,n,r){if(e&&typeof e==`object`){if(`toolResult`in e)return{content:String(e.toolResult),type:`toolResult`};if(`structuredContent`in e&&e.structuredContent!==void 0)return{content:U(e.structuredContent),type:`structuredContent`,schema:GA(e.structuredContent)};if(`content`in e&&Array.isArray(e.content)){let t=(await Promise.all(e.content.map(e=>UA(e,n,r,!0)))).flat();return{content:t,type:`contentArray`,schema:GA(t)}}}let i=`MCP server "${n}" tool "${t}": unexpected response format`;throw Ua(n,i),new cr(i,`MCP tool unexpected response format`)}function KA(e){return!e||typeof e==`string`?!1:e.some(e=>e.type===`image`)}async function uDe(e,t,n,r,i=!1){let{content:a,type:o,schema:s}=await lDe(e,t,n,r);if(n===`ide`||i&&!KA(a)||!await vO(a))return a;let c=_O(a);if(f(process.env.ENABLE_MCP_LARGE_OUTPUT_FILES))return Y(`tengu_mcp_large_result_handled`,{outcome:`truncated`,reason:`env_disabled`,sizeEstimateTokens:c}),await yO(a);if(!a)return a;if(KA(a))return Y(`tengu_mcp_large_result_handled`,{outcome:`truncated`,reason:`contains_images`,sizeEstimateTokens:c}),await yO(a);let l=Date.now(),u=`mcp-${Mi(n)}-${Mi(t)}-${l}`,d=fDe(a),p=typeof a==`string`?a:d??U(a,null,2),m=await dS(p,u);if(hS(m)){let e=p.length;return Y(`tengu_mcp_large_result_handled`,{outcome:`truncated`,reason:`persist_failed`,sizeEstimateTokens:c}),`Error: result (${e.toLocaleString()} characters) exceeds maximum allowed tokens. Failed to save output to file: ${m.error}. If this MCP server provides pagination or filtering tools, use them to retrieve specific portions of the data.`}Y(`tengu_mcp_large_result_handled`,{outcome:`persisted`,reason:`file_saved`,sizeEstimateTokens:c,persistedSizeChars:m.originalSize});let h=d===void 0?kO(o,s):kO(`toolResult`);return RTe(m.filepath,m.originalSize,h)}function dDe(){let e=process.env.MCP_TRUNCATION_PROMPT_OVERRIDE;return e?e!==`legacy`:!1}function fDe(e){if(!dDe()||!Array.isArray(e)||e.length!==1)return;let t=e[0];if(t?.type===`text`&&!(`annotations`in t||`_meta`in t))return t.text}async function pDe({client:e,clientConnection:t,tool:n,args:r,meta:i,signal:a,setAppState:o,onProgress:s,imageLimits:c,hasResultSizeAnnotation:l=!1,callToolFn:u=qA,handleElicitation:d}){for(let f=0;;f++)try{return await u({client:e,tool:n,args:r,meta:i,signal:a,onProgress:s,imageLimits:c,hasResultSizeAnnotation:l})}catch(e){if(!(e instanceof UT)||e.code!==vw.UrlElicitationRequired||f>=3)throw e;let r=e.data,i=(typeof r==`object`&&r&&`elicitations`in r&&Array.isArray(r.elicitations)?r.elicitations:[]).filter(e=>{if(typeof e!=`object`||!e)return!1;let t=e;return t.mode===`url`&&typeof t.url==`string`&&typeof t.elicitationId==`string`&&typeof t.message==`string`}),s=t.type===`connected`?t.name:`unknown`;if(i.length===0)throw Va(s,`Tool '${n}' returned -32042 but no valid elicitations in error data`),e;Va(s,`Tool '${n}' requires URL elicitation (error -32042, attempt ${f+1}), processing ${i.length} elicitation(s)`);for(let e of i){let{elicitationId:t}=e,r=await XO(s,e,a);if(r){if(Va(s,`URL elicitation ${t} resolved by hook: ${U(r)}`),r.action!==`accept`)return{content:`URL elicitation was ${r.action===`decline`?`declined`:`${r.action}ed`} by a hook. The tool "${n}" could not complete because it requires the user to open a URL.`};continue}let i;if(d)i=await d(s,e,a);else{let n={actionLabel:`Retry now`,showCancel:!0};i=await new Promise(r=>{let i=()=>{r({action:`cancel`})};if(a.aborted){i();return}a.addEventListener(`abort`,i,{once:!0}),o(o=>({...o,elicitation:{queue:[...o.elicitation.queue,{serverName:s,requestId:`error-elicit-${t}`,params:e,signal:a,waitingState:n,respond:e=>{e.action!==`accept`&&(a.removeEventListener(`abort`,i),r(e))},onWaitingDismiss:e=>{a.removeEventListener(`abort`,i),r(e===`retry`?{action:`accept`}:{action:`cancel`})}}]}}))})}let c=await ZO(s,i,a,`url`,t);if(c.action!==`accept`)return Va(s,`User ${c.action===`decline`?`declined`:`${c.action}ed`} URL elicitation ${t}`),{content:`URL elicitation was ${c.action===`decline`?`declined`:`${c.action}ed`} by the user. The tool "${n}" could not complete because it requires the user to open a URL.`};Va(s,`Elicitation ${t} completed, retrying tool call`)}}}async function qA({client:{client:e,name:t,config:n},tool:r,args:i,meta:a,signal:o,onProgress:s,imageLimits:c,hasResultSizeAnnotation:l=!1}){let u=Date.now(),d;try{Va(t,`Calling MCP tool: ${r}`),d=setInterval((e,t,n)=>{let r=Date.now()-e;Va(t,`Tool '${n}' still running (${`${Math.floor(r/1e3)}s`} elapsed)`)},3e4,u,t,r);let n=rDe(),f,p=new Promise((e,i)=>{f=setTimeout((e,t,n,r)=>{e(new cr(`MCP server "${t}" tool "${n}" timed out after ${Math.floor(r/1e3)}s`,`MCP tool timeout`))},n,i,t,r,n)}),m=await Promise.race([e.callTool({name:r,arguments:i,_meta:a},uT,{signal:o,timeout:n,onprogress:s?e=>{s({type:`mcp_progress`,status:`progress`,serverName:t,toolName:r,progress:e.progress,total:e.total,progressMessage:e.message})}:void 0}),p]).finally(()=>{f&&clearTimeout(f)});if(`isError`in m&&m.isError){let e=`Unknown error`;if(`content`in m&&Array.isArray(m.content)&&m.content.length>0){let t=m.content[0];t&&typeof t==`object`&&`text`in t&&(e=t.text)}else`error`in m&&(e=String(m.error));throw Ua(t,e),new XA(e,`MCP tool returned error`,`_meta`in m&&m._meta?{_meta:m._meta}:void 0)}let h=Date.now()-u;Va(t,`Tool '${r}' completed successfully in ${h<1e3?`${h}ms`:h<6e4?`${Math.floor(h/1e3)}s`:`${Math.floor(h/6e4)}m ${Math.floor(h%6e4/1e3)}s`}`);let g=JTe(t);return g&&Y(`tengu_code_indexing_tool_used`,{tool:g,source:`mcp`,success:!0}),{content:await uDe(m,r,t,c,l),_meta:m._meta,structuredContent:m.structuredContent}}catch(e){d!==void 0&&clearInterval(d);let i=Date.now()-u;if(e instanceof Error&&e.name!==`AbortError`&&Va(t,`Tool '${r}' failed after ${Math.floor(i/1e3)}s: ${e.message}`),e instanceof Error){if((`code`in e?e.code:void 0)===401||e instanceof VD)throw Va(t,`Tool call returned 401 Unauthorized - token may have expired`),Y(`tengu_mcp_tool_call_auth_error`,{}),new JA(t,`MCP server "${t}" requires re-authorization (token expired)`);let r=OA(e),i=`code`in e&&e.code===-32e3&&e.message.includes(`Connection closed`)&&n.type===`http`;if(r||i)throw Va(t,`MCP session expired during tool call (${r?`404/-32001`:`connection closed`}), clearing connection cache for re-initialization`),Y(`tengu_mcp_session_expired`,{}),await LA(t,n),new YA(t)}if(!(e instanceof Error)||e.name!==`AbortError`)throw e;return{content:void 0}}finally{d!==void 0&&clearInterval(d)}}function mDe(e){let t=e.message.content?.[0];if(!(!t||typeof t==`string`||t.type!==`tool_use`))return t.id}async function hDe(e,t){let n=[],r=[],i=await Promise.allSettled(Object.entries(e).map(async([e,n])=>{let r=new DA(e,t),i=new cE({name:`workmate`,title:`Work Mate`,version:`0.0.23`,description:`Agentic coding tool`,websiteUrl:rO},{capabilities:{}});try{await i.connect(r);let t=i.getServerCapabilities(),a={type:`connected`,name:e,capabilities:t||{},client:i,config:{...n,scope:`dynamic`},cleanup:async()=>{await i.close()}},o=[];if(t?.tools){let e=await aj(a);o.push(...e)}return{client:a,tools:o}}catch(t){return Ua(e,`Failed to connect SDK MCP server: ${t}`),{client:{type:`failed`,name:e,config:{...n,scope:`user`}},tools:[]}}}));for(let e of i)e.status===`fulfilled`&&(n.push(e.value.client),r.push(...e.value.tools));return{clients:n,tools:r}}var JA,YA,XA,ZA,QA,$A,ej,tj,nj,rj,ij,aj,oj,sj,cj=n((()=>{Lwe(),gTe(),yTe(),xTe(),$E(),GT(),vg(),d(),Mg(),Qce(),Jt(),iO(),Ks(),pO(),LTe(),zO(),UO(),Ar(),Hn(),KO(),K(),g(),qn(),jie(),Wj(),Ab(),Ga(),MO(),SO(),YTe(),Dt(),voe(),Qs(),Bx(),vS(),oo(),QO(),Ri(),ci(),CA(),Yoe(),b(),WD(),QEe(),dk(),lc(),pA(),tDe(),nDe(),mr(),JA=class extends Error{constructor(e,t){super(t),x(this,`serverName`,void 0),this.name=`McpAuthError`,this.serverName=e}},YA=class extends Error{constructor(e){super(`MCP server "${e}" session expired`),this.name=`McpSessionExpiredError`}},XA=class extends cr{constructor(e,t,n){super(e,t),x(this,`mcpMeta`,void 0),this.mcpMeta=n,this.name=`McpToolCallError`}},ZA=1e8,QA=2048,$A=new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]),ej=6e4,tj=`application/json, text/event-stream`,nj=[`mcp__ide__executeCode`,`mcp__ide__getDiagnostics`],rj=u(async(e,t,n)=>{let r=Date.now();try{let i;if(t.type===`sse`){let n=await EA(e,t),r={fetch:NA(QE()),requestInit:{headers:{"User-Agent":Do(),...n}}};r.eventSourceInit={fetch:async(e,t)=>{let r=$s();return fetch(e,{...t,...r,headers:{"User-Agent":Do(),...t?.headers,...n,Accept:`text/event-stream`}})}},i=new KD(new URL(t.url),r),Va(e,`SSE transport initialized, awaiting connection`)}else if(t.type===`sse-ide`){Va(e,`Setting up SSE-IDE transport to ${t.url}`);let n=$s(),r=n.dispatcher?{eventSourceInit:{fetch:async(e,t)=>fetch(e,{...t,...n,headers:{"User-Agent":Do(),...t?.headers}})}}:{};i=new KD(new URL(t.url),Object.keys(r).length>0?r:void 0)}else if(t.type===`ws-ide`){let e=boe(),n={"User-Agent":Do(),...t.authToken&&{"X-Work Mate-Code-Ide-Authorization":t.authToken}},r;r=typeof Bun<`u`?new globalThis.WebSocket(t.url,{protocols:[`mcp`],headers:n,proxy:xoe(t.url),tls:e||void 0}):await jA(t.url,{headers:n,agent:yoe(t.url),...e||{}}),i=new YO(r)}else if(t.type===`ws`){Va(e,`Initializing WebSocket transport to ${t.url}`);let n=await EA(e,t),r=boe(),a={"User-Agent":Do(),...n},o=_g(a,(e,t)=>t.toLowerCase()===`authorization`?`[REDACTED]`:e);Va(e,`WebSocket transport options: ${U({url:t.url,headers:o})}`);let s;s=typeof Bun<`u`?new globalThis.WebSocket(t.url,{protocols:[`mcp`],headers:a,proxy:xoe(t.url),tls:r||void 0}):await jA(t.url,{headers:a,agent:yoe(t.url),...r||{}}),i=new YO(s)}else if(t.type===`http`){Va(e,`Initializing HTTP transport to ${t.url}`),Va(e,`Node version: ${process.version}, Platform: ${process.platform}`),Va(e,`Environment: ${U({NODE_OPTIONS:process.env.NODE_OPTIONS||`not set`,UV_THREADPOOL_SIZE:process.env.UV_THREADPOOL_SIZE||`default`,HTTP_PROXY:process.env.HTTP_PROXY||`not set`,HTTPS_PROXY:process.env.HTTPS_PROXY||`not set`,NO_PROXY:process.env.NO_PROXY||`not set`})}`);let n=await EA(e,t),r=$s();Va(e,`Proxy options: ${r.dispatcher?`custom dispatcher`:`default`}`);let a={fetch:NA(QE()),requestInit:{...r,headers:{"User-Agent":Do(),...n}}},o=a.requestInit?.headers?_g(a.requestInit.headers,(e,t)=>t.toLowerCase()===`authorization`?`[REDACTED]`:e):void 0;Va(e,`HTTP transport options: ${U({url:t.url,headers:o,timeoutMs:ej})}`),i=new nO(new URL(t.url),a),Va(e,`HTTP transport created successfully`)}else if(t.type===`sdk`)throw Error(`SDK servers should be handled in print.ts`);else if(t.type===`stdio`||!t.type){let e=t;i=new QD({command:process.env.CLAUDE_CODE_SHELL_PREFIX||e.command,args:process.env.CLAUDE_CODE_SHELL_PREFIX?[[e.command,...e.args].join(` `)]:e.args,env:{...zx(),...e.env},stderr:`pipe`})}else throw Error(`Unsupported server type: ${t.type}`);let a,o=``;if(t.type===`stdio`||!t.type){let e=i;e.stderr&&(a=e=>{if(o.length<64*1024*1024)try{o+=e.toString()}catch{}},e.stderr.on(`data`,a))}let s=new cE({name:`workmate`,title:`Work Mate`,version:`0.0.23`,description:`Agentic coding tool`,websiteUrl:rO},{capabilities:{roots:{},elicitation:{}}});if(t.type===`http`&&Va(e,`Client created, setting up request handler`),s.setRequestHandler(BT,async()=>(Va(e,`Received ListRoots request from server`),{roots:[{uri:`file://${Yt()}`}]})),Va(e,`Starting connection with timeout of ${MA()}ms`),t.type===`http`){Va(e,`Testing basic HTTP connectivity to ${t.url}`);try{let n=new URL(t.url);Va(e,`Parsed URL: host=${n.hostname}, port=${n.port||`default`}, protocol=${n.protocol}`),(n.hostname===`127.0.0.1`||n.hostname===`localhost`)&&Va(e,`Using loopback address: ${n.hostname}`)}catch(t){Va(e,`Failed to parse URL: ${t}`)}}let c=s.connect(i),l=new Promise((t,n)=>{let a=setTimeout(()=>{Va(e,`Connection timeout triggered after ${Date.now()-r}ms (limit: ${MA()}ms)`),i.close().catch(()=>{}),n(new cr(`MCP server "${e}" connection timed out after ${MA()}ms`,`MCP connection timeout`))},MA());c.then(()=>{clearTimeout(a)},e=>{clearTimeout(a)})});try{await Promise.race([c,l]),o&&(Ua(e,`Server stderr: ${o}`),o=``);let n=Date.now()-r;Va(e,`Successfully connected (transport: ${t.type||`stdio`}) in ${n}ms`)}catch(n){let a=Date.now()-r;if(t.type===`sse`&&n instanceof Error){if(Va(e,`SSE Connection failed after ${a}ms: ${U({url:t.url,error:n.message,errorType:n.constructor.name,stack:n.stack})}`),Ua(e,n),n instanceof VD)return AA(e,t,`sse`)}else if(t.type===`http`&&n instanceof Error){let r=n;if(Va(e,`HTTP Connection failed after ${a}ms: ${n.message} (code: ${r.code||`none`}, errno: ${r.errno||`none`})`),Ua(e,n),n instanceof VD)return AA(e,t,`http`)}else(t.type===`sse-ide`||t.type===`ws-ide`)&&Y(`tengu_mcp_ide_server_connection_failed`,{connectionDurationMs:a});throw i.close().catch(()=>{}),o&&Ua(e,`Server stderr: ${o}`),n}let u=s.getServerCapabilities(),d=s.getServerVersion(),f=s.getInstructions(),p=f;if(f&&f.length>QA&&(p=`${f.slice(0,QA)}… [truncated]`,Va(e,`Server instructions truncated from ${f.length} to ${QA} chars`)),Va(e,`Connection established with capabilities: ${U({hasTools:!!u?.tools,hasPrompts:!!u?.prompts,hasResources:!!u?.resources,hasResourceSubscribe:!!u?.resources?.subscribe,serverVersion:d||`unknown`})}`),G(`[MCP] Server "${e}" connected with subscribe=${!!u?.resources?.subscribe}`),s.setRequestHandler(AT,async t=>(Va(e,`Elicitation request received during initialization: ${U(t)}`),{action:`cancel`})),t.type===`sse-ide`||t.type===`ws-ide`){Y(`tengu_mcp_ide_server_connection_succeeded`,{connectionDurationMs:Date.now()-r,serverVersion:d});try{ADe(s)}catch(t){Ua(e,`Failed to send ide_connected notification: ${t}`)}}let m=Date.now(),h=!1,g=s.onerror,_=s.onclose,v=0,y=!1,b=t=>{y||(y=!0,Va(e,`Closing transport (${t})`),s.close().catch(t=>{Va(e,`Error during close: ${W(t)}`)}))},x=e=>e.includes(`ECONNRESET`)||e.includes(`ETIMEDOUT`)||e.includes(`EPIPE`)||e.includes(`EHOSTUNREACH`)||e.includes(`ECONNREFUSED`)||e.includes(`Body Timeout Error`)||e.includes(`terminated`)||e.includes(`SSE stream disconnected`)||e.includes(`Failed to reconnect SSE stream`);s.onerror=n=>{let r=Date.now()-m;h=!0;let i=t.type||`stdio`;if(Va(e,`${i.toUpperCase()} connection dropped after ${Math.floor(r/1e3)}s uptime`),n.message&&(n.message.includes(`ECONNRESET`)?Va(e,`Connection reset - server may have crashed or restarted`):n.message.includes(`ETIMEDOUT`)?Va(e,`Connection timeout - network issue or server unresponsive`):n.message.includes(`ECONNREFUSED`)?Va(e,`Connection refused - server may be down`):n.message.includes(`EPIPE`)?Va(e,`Broken pipe - server closed connection unexpectedly`):n.message.includes(`EHOSTUNREACH`)?Va(e,`Host unreachable - network connectivity issue`):n.message.includes(`ESRCH`)?Va(e,`Process not found - stdio server process terminated`):n.message.includes(`spawn`)?Va(e,`Failed to spawn process - check command and permissions`):Va(e,`Connection error: ${n.message}`)),i===`http`&&OA(n)){Va(e,`MCP session expired (server returned 404 with session-not-found), triggering reconnection`),b(`session expired`),g&&g(n);return}if(i===`sse`||i===`http`){if(n.message.includes(`Maximum reconnection attempts`)){b(`SSE reconnection exhausted`),g&&g(n);return}x(n.message)?(v++,Va(e,`Terminal connection error ${v}/3`),v>=3&&(v=0,b(`max consecutive terminal errors`))):v=0}g&&g(n)},s.onclose=()=>{let n=Date.now()-m;Va(e,`${(t.type??`unknown`).toUpperCase()} connection closed after ${Math.floor(n/1e3)}s (${h?`with errors`:`cleanly`})`);let r=IA(e,t);aj.cache.delete(e),oj.cache.delete(e),sj.cache.delete(e),rj.cache.delete(r),Va(e,`Cleared connection cache for reconnection`),_&&_()};let S=async()=>{if(a&&(t.type===`stdio`||!t.type)&&i.stderr?.off(`data`,a),t.type===`stdio`)try{let t=i.pid;if(t){Va(e,`Sending SIGINT to MCP server process`);try{process.kill(t,`SIGINT`)}catch(t){Va(e,`Error sending SIGINT: ${t}`);return}await new Promise(async n=>{let r=!1,i=setInterval(()=>{try{process.kill(t,0)}catch{r||(r=!0,clearInterval(i),clearTimeout(a),Va(e,`MCP server process exited cleanly`),n())}},50),a=setTimeout(()=>{r||(r=!0,clearInterval(i),Va(e,`Cleanup timeout reached, stopping process monitoring`),n())},600);try{if(await cc(100),!r){try{process.kill(t,0),Va(e,`SIGINT failed, sending SIGTERM to MCP server process`);try{process.kill(t,`SIGTERM`)}catch(t){Va(e,`Error sending SIGTERM: ${t}`),r=!0,clearInterval(i),clearTimeout(a),n();return}}catch{r=!0,clearInterval(i),clearTimeout(a),n();return}if(await cc(400),!r)try{process.kill(t,0),Va(e,`SIGTERM failed, sending SIGKILL to MCP server process`);try{process.kill(t,`SIGKILL`)}catch(t){Va(e,`Error sending SIGKILL: ${t}`)}}catch{r=!0,clearInterval(i),clearTimeout(a),n()}}r||(r=!0,clearInterval(i),clearTimeout(a),n())}catch{r||(r=!0,clearInterval(i),clearTimeout(a),n())}})}}catch(t){Va(e,`Error terminating process: ${t}`)}try{await s.close()}catch(t){Va(e,`Error closing client: ${t}`)}},C=ar(S),w=async()=>{C?.(),await S()};return Y(`tengu_mcp_server_connection_succeeded`,{connectionDurationMs:Date.now()-r,transportType:t.type??`stdio`,totalServers:n?.totalServers,stdioCount:n?.stdioCount,sseCount:n?.sseCount,httpCount:n?.httpCount,sseIdeCount:n?.sseIdeCount,wsIdeCount:n?.wsIdeCount,...kA(t)}),{name:e,client:s,type:`connected`,capabilities:u??{},serverInfo:d,instructions:p,config:t,cleanup:w}}catch(i){let a=Date.now()-r;return Y(`tengu_mcp_server_connection_failed`,{connectionDurationMs:a,totalServers:n?.totalServers||1,stdioCount:n?.stdioCount||+(t.type===`stdio`),sseCount:n?.sseCount||+(t.type===`sse`),httpCount:n?.httpCount||+(t.type===`http`),sseIdeCount:n?.sseIdeCount||+(t.type===`sse-ide`),wsIdeCount:n?.wsIdeCount||+(t.type===`ws-ide`),transportType:t.type??`stdio`,...kA(t)}),Va(e,`Connection failed after ${a}ms: ${W(i)}`),Ua(e,`Connection failed: ${W(i)}`),{name:e,type:`failed`,config:t,error:W(i)}}},IA),ij=20,aj=Ct(async e=>{if(e.type!==`connected`)return[];try{if(!e.capabilities?.tools)return[];let t=Joe((await e.client.request({method:`tools/list`},lT)).tools),n=e.config.type===`sdk`&&h(process.env.CLAUDE_AGENT_SDK_MCP_NO_PREFIX);return t.map(t=>{let r=Kne(e.name,t.name);return{...OO,name:n?t.name:r,mcpInfo:{serverName:e.name,toolName:t.name},isMcp:!0,searchHint:typeof t._meta?.[`anthropic/searchHint`]==`string`&&t._meta[`anthropic/searchHint`].replace(/\s+/g,` `).trim()||void 0,alwaysLoad:t._meta?.[`anthropic/alwaysLoad`]===!0,async description(){return t.description??``},async prompt(){let e=t.description??``;return e.length>QA?`${e.slice(0,QA)}… [truncated]`:e},isConcurrencySafe(){return t.annotations?.readOnlyHint??!1},isReadOnly(){return t.annotations?.readOnlyHint??!1},toAutoClassifierInput(e){return sDe(e,t.name)},isDestructive(){return t.annotations?.destructiveHint??!1},isOpenWorld(){return t.annotations?.openWorldHint??!1},isSearchOrReadCommand(){return ZEe(e.name,t.name)},inputJSONSchema:t.inputSchema,async checkPermissions(){return{behavior:`passthrough`,message:`MCPTool requires permission.`,suggestions:[{type:`addRules`,rules:[{toolName:r,ruleContent:void 0}],behavior:`allow`,destination:`localSettings`}]}},async call(n,r,i,a,o){let s=mDe(a),c=s?{"claudecode/toolUseId":s}:{};o&&s&&o({toolUseID:s,data:{type:`mcp_progress`,status:`started`,serverName:e.name,toolName:t.name}});let l=Date.now();for(let i=0;;i++)try{let i=await pDe({client:await RA(e),clientConnection:e,tool:t.name,args:n,meta:c,signal:r.abortController.signal,setAppState:r.setAppState,onProgress:o&&s?e=>{o({toolUseID:s,data:e})}:void 0,handleElicitation:r.handleElicitation});return o&&s&&o({toolUseID:s,data:{type:`mcp_progress`,status:`completed`,serverName:e.name,toolName:t.name,elapsedTimeMs:Date.now()-l}}),{data:i.content,...(i._meta||i.structuredContent)&&{mcpMeta:{...i._meta&&{_meta:i._meta},...i.structuredContent&&{structuredContent:i.structuredContent}}}}}catch(n){if(n instanceof YA&&i<1){Va(e.name,`Retrying tool '${t.name}' after session recovery`);continue}if(o&&s&&o({toolUseID:s,data:{type:`mcp_progress`,status:`failed`,serverName:e.name,toolName:t.name,elapsedTimeMs:Date.now()-l}}),n instanceof Error&&!(n instanceof cr)){let e=n.constructor.name;if(e===`Error`)throw new cr(n.message,n.message.slice(0,200));if(e===`McpError`&&`code`in n&&typeof n.code==`number`)throw new cr(n.message,`McpError ${n.code}`)}throw n}},userFacingName(){let n=t.annotations?.title||t.name;return`${e.name} - ${n} (MCP)`}}}).filter(aDe)}catch(t){return Ua(e.name,`Failed to fetch tools: ${W(t)}`),[]}},e=>e.name,ij),oj=Ct(async e=>{if(e.type!==`connected`)return[];try{if(!e.capabilities?.resources)return[];let t=await e.client.request({method:`resources/list`},Yw);return t.resources?t.resources.map(t=>({...t,server:e.name})):[]}catch(t){return Ua(e.name,`Failed to fetch resources: ${W(t)}`),[]}},e=>e.name,ij),sj=Ct(async e=>{if(e.type!==`connected`)return[];try{if(!e.capabilities?.prompts)return[];let t=await e.client.request({method:`prompts/list`},eT);return t.prompts?Joe(t.prompts).map(t=>{let n=Object.values(t.arguments??{}).map(e=>e.name);return{type:`prompt`,name:`mcp__${Mi(e.name)}__${t.name}`,description:t.description??``,hasUserSpecifiedDescription:!!t.description,contentLength:0,isEnabled:()=>!0,isHidden:!1,isMcp:!0,progressMessage:`running`,userFacingName(){return`${e.name}:${t.name} (MCP)`},argNames:n,source:`mcp`,async getPromptForCommand(r){let i=r.split(` `);try{let r=await RA(e),a=await r.client.getPrompt({name:t.name,arguments:hpe(n,i)});return(await Promise.all(a.messages.map(e=>UA(e.content,r.name)))).flat()}catch(n){throw Ua(e.name,`Error running command '${t.name}': ${W(n)}`),n}}}}):[]}catch(t){return Ua(e.name,`Failed to fetch commands: ${W(t)}`),[]}},e=>e.name,ij)}));function gDe(e){let t=_c(),n=[],r=uj[e.toLowerCase()];if(!r)return n;let i=process.env.APPDATA||X(t,`AppData`,`Roaming`),a=process.env.LOCALAPPDATA||X(t,`AppData`,`Local`);switch(kse()){case`darwin`:n.push(X(t,`Library`,`Application Support`,`JetBrains`),X(t,`Library`,`Application Support`)),e.toLowerCase()===`androidstudio`&&n.push(X(t,`Library`,`Application Support`,`Google`));break;case`win32`:n.push(X(i,`JetBrains`),X(a,`JetBrains`),X(i)),e.toLowerCase()===`androidstudio`&&n.push(X(a,`Google`));break;case`linux`:n.push(X(t,`.config`,`JetBrains`),X(t,`.local`,`share`,`JetBrains`));for(let e of r)n.push(X(t,`.${e}`));e.toLowerCase()===`androidstudio`&&n.push(X(t,`.config`,`Google`));break;default:break}return n}async function _De(e){let t=[],n=q(),r=gDe(e),i=uj[e.toLowerCase()];if(!i)return t;let a=i.map(e=>RegExp(`^${e}`));for(let e of r)try{let r=await n.readdir(e);for(let i of a)for(let a of r){if(!i.test(a.name)||!a.isDirectory()&&!a.isSymbolicLink())continue;let r=X(e,a.name);if(kse()===`linux`){t.push(r);continue}let o=X(r,`plugins`);try{await n.stat(o),t.push(o)}catch{}}}catch{}return t.filter((e,n)=>t.indexOf(e)===n)}async function vDe(e){let t=await _De(e);for(let e of t){let t=X(e,lj);try{return await q().stat(t),!0}catch{}}return!1}async function yDe(e,t=!1){if(!t){let t=fj.get(e);if(t)return t}let n=vDe(e).then(t=>(dj.set(e,t),t));return fj.set(e,n),n}async function bDe(e,t=!1){return t&&(dj.delete(e),fj.delete(e)),yDe(e,t)}var lj,uj,dj,fj,xDe=n((()=>{or(),lj=`claude-code-jetbrains-plugin`,uj={pycharm:[`PyCharm`],intellij:[`IntelliJIdea`,`IdeaIC`],webstorm:[`WebStorm`],phpstorm:[`PhpStorm`],rubymine:[`RubyMine`],clion:[`CLion`],goland:[`GoLand`],rider:[`Rider`],datagrip:[`DataGrip`],appcode:[`AppCode`],dataspell:[`DataSpell`],aqua:[`Aqua`],gateway:[`Gateway`],fleet:[`Fleet`],androidstudio:[`AndroidStudio`]},dj=new Map,fj=new Map}));function SDe(e,t){let n=e.match(/^\\\\wsl(?:\.localhost|\$)\\([^\\]+)(.*)$/);return!n||n[1]===t}var pj,mj=n((()=>{b(),pj=class{constructor(e){x(this,`wslDistroName`,void 0),this.wslDistroName=e}toLocalPath(e){if(!e)return e;if(this.wslDistroName){let t=e.match(/^\\\\wsl(?:\.localhost|\$)\\([^\\]+)(.*)$/);if(t&&t[1]!==this.wslDistroName)return e}try{return ul(`wslpath`,[`-u`,e],{encoding:`utf8`,stdio:[`pipe`,`pipe`,`ignore`]}).trim()}catch{return e.replace(/\\/g,`/`).replace(/^([A-Z]):/i,(e,t)=>`/mnt/${t.toLowerCase()}`)}}toIDEPath(e){if(!e)return e;try{return ul(`wslpath`,[`-w`,e],{encoding:`utf8`,stdio:[`pipe`,`pipe`,`ignore`]}).trim()}catch{return e}}}}));function CDe({onDone:e,installationStatus:t}){TDe(),Ke({"confirm:yes":e,"confirm:no":e},{context:`Confirmation`});let n=t?.ideType??bj(),r=yj(n),i=Mj(n),a=t?.installedVersion,o=r?`plugin`:`extension`,s=$r.platform===`darwin`?`Cmd+Option+K`:`Ctrl+Alt+K`;return(0,hj.jsxs)(hj.Fragment,{children:[(0,hj.jsx)(kee,{title:(0,hj.jsxs)(hj.Fragment,{children:[(0,hj.jsx)(F,{color:`claude`,children:`✻ `}),(0,hj.jsxs)(F,{children:[`Welcome to Work Mate for `,i]})]}),subtitle:a?`installed ${o} v${a}`:void 0,color:`ide`,onCancel:e,hideInputGuide:!0,children:(0,hj.jsxs)(P,{flexDirection:`column`,gap:1,children:[(0,hj.jsxs)(F,{children:[`• Work Mate has context of `,(0,hj.jsx)(F,{color:`suggestion`,children:`⧉ open files`}),` and`,` `,(0,hj.jsx)(F,{color:`suggestion`,children:`⧉ selected lines`})]}),(0,hj.jsxs)(F,{children:[`• Review Work Mate's changes `,(0,hj.jsx)(F,{color:`diffAddedWord`,children:`+11`}),` `,(0,hj.jsx)(F,{color:`diffRemovedWord`,children:`-22`}),` in the comfort of your IDE`]}),(0,hj.jsxs)(F,{children:[`• Cmd+Esc`,(0,hj.jsx)(F,{dimColor:!0,children:` for Quick Launch`})]}),(0,hj.jsxs)(F,{children:[`• `,s,(0,hj.jsx)(F,{dimColor:!0,children:` to reference files or lines in your input`})]})]})}),(0,hj.jsx)(P,{paddingX:1,children:(0,hj.jsx)(F,{dimColor:!0,italic:!0,children:`Press Enter to continue`})})]})}function wDe(){let e=ha(),t=Ne.terminal||`unknown`;return e.hasIdeOnboardingBeenShown?.[t]===!0}function TDe(){if(wDe())return;let e=Ne.terminal||`unknown`;aa(t=>({...t,hasIdeOnboardingBeenShown:{...t.hasIdeOnboardingBeenShown,[e]:!0}}))}var hj,gj=n((()=>{Ce(),ct(),US(),ma(),Ii(),Wj(),hj=ut()}));function _j(e){try{return process.kill(e,0),!0}catch{return!1}}function EDe(){let e=null;return()=>(e||(e=qoe(process.ppid,10).then(e=>new Set(e))),e)}function vj(e){if(!e)return!1;let t=Fj[e];return t&&t.ideKind===`vscode`}function yj(e){if(!e)return!1;let t=Fj[e];return t&&t.ideKind===`jetbrains`}function bj(){return Rj()?$r.terminal:null}async function xj(){try{let e=await DDe();return(await Promise.all(e.map(async e=>{try{let t=(await q().readdir(e)).filter(e=>e.name.endsWith(`.lock`));return(await Promise.all(t.map(async t=>{let n=X(e,t.name);try{return{path:n,mtime:(await q().stat(n)).mtime}}catch{return null}}))).filter(e=>e!==null)}catch(e){return hr(e)||J(e),[]}}))).flat().sort((e,t)=>t.mtime.getTime()-e.mtime.getTime()).map(e=>e.path)}catch(e){return J(e),[]}}async function Sj(e){try{let t=await q().readFile(e,{encoding:`utf-8`}),n=[],r,i,a=!1,o=!1,s;try{let e=$n(t);e.workspaceFolders&&(n=e.workspaceFolders),r=e.pid,i=e.ideName,a=e.transport===`ws`,o=e.runningInWindows===!0,s=e.authToken}catch{n=t.split(`
|
|
670
|
-
`).map(e=>e.trim())}let c=e.split(kc).pop();if(!c)return null;let l=c.replace(`.lock`,``);return{workspaceFolders:n,port:parseInt(l,10),pid:r,ideName:i,useWebSocket:a,runningInWindows:o,authToken:s}}catch(e){return J(e),null}}async function Cj(e,t,n=500){try{return new Promise(r=>{let i=Mce({host:e,port:t,timeout:n});i.on(`connect`,()=>{i.destroy(),r(!0)}),i.on(`error`,()=>{r(!1)}),i.on(`timeout`,()=>{i.destroy(),r(!1)})})}catch{return!1}}async function DDe(){let e=[X(m(),`ide`)];if(io()!==`wsl`)return e;let t=await zj();if(t){let n=new pj(process.env.WSL_DISTRO_NAME).toLocalPath(t);e.push(Oc(n,`.workmate`,`ide`))}try{let t=`/mnt/c/Users`,n=await q().readdir(t);for(let r of n)!r.isDirectory()&&!r.isSymbolicLink()||r.name===`Public`||r.name===`Default`||r.name===`Default User`||r.name===`All Users`||e.push(X(t,r.name,`.workmate`,`ide`))}catch(e){hr(e)?G(`WSL IDE lockfile path detection failed (${e.code}): ${W(e)}`):J(e)}return e}async function ODe(){try{let e=await xj();for(let t of e){let e=await Sj(t);if(!e){try{await q().unlink(t)}catch(e){J(e)}continue}let n=await Uj(e.runningInWindows,e.port),r=!1;if(e.pid?_j(e.pid)||io()===`wsl`&&await Cj(n,e.port)||(r=!0):await Cj(n,e.port)||(r=!0),r)try{await q().unlink(t)}catch(e){J(e)}}}catch(e){J(e)}}async function kDe(e){try{let t=await MDe(e);return Y(`tengu_ext_installed`,{}),ha().diffTool||aa(e=>({...e,diffTool:`auto`})),{installed:!0,error:null,installedVersion:t,ideType:e}}catch(t){Y(`tengu_ext_install_error`,{});let n=t instanceof Error?t.message:String(t);return J(t),{installed:!1,error:n,installedVersion:null,ideType:e}}}async function wj(){Bj&&Bj.abort(),Bj=BO();let e=Bj.signal;await ODe();let t=Date.now();for(;Date.now()-t<3e4&&!e.aborted;){if(tte()){await cc(1e3,e);continue}let t=await Tj(!1);if(e.aborted)return null;if(t.length===1)return t[0];await cc(1e3,e)}return null}async function Tj(e){let t=[];try{let n=process.env.CLAUDE_CODE_SSE_PORT,r=n?parseInt(n,10):null,i=Yt().normalize(`NFC`),a=await xj(),o=await Promise.all(a.map(Sj)),s=EDe(),c=io()!==`wsl`&&Rj();for(let n of o){if(!n)continue;let a=!1;if(a=h(process.env.CLAUDE_CODE_IDE_SKIP_VALID_CHECK)?!0:n.port===r||n.workspaceFolders.some(e=>{if(!e)return!1;let t=e;if(io()===`wsl`&&n.runningInWindows&&process.env.WSL_DISTRO_NAME){if(!SDe(e,process.env.WSL_DISTRO_NAME))return!1;let n=Oc(t).normalize(`NFC`);if(i===n||i.startsWith(n+kc))return!0;t=new pj(process.env.WSL_DISTRO_NAME).toLocalPath(e)}let r=Oc(t).normalize(`NFC`);if(io()===`windows`){let e=i.replace(/^[a-zA-Z]:/,e=>e.toUpperCase()),t=r.replace(/^[a-zA-Z]:/,e=>e.toUpperCase());return e===t||e.startsWith(t+kc)}return i===r||i.startsWith(r+kc)}),!a&&!e||c&&!(r!==null&&n.port===r)&&(!n.pid||!_j(n.pid)||process.ppid!==n.pid&&!(await s()).has(n.pid)))continue;let o=n.ideName??(Rj()?Mj(Ne.terminal):`IDE`),l=await Uj(n.runningInWindows,n.port),u;u=n.useWebSocket?`ws://${l}:${n.port}`:`http://${l}:${n.port}/sse`,t.push({url:u,name:o,workspaceFolders:n.workspaceFolders,port:n.port,isValid:a,authToken:n.authToken,ideRunningInWindows:n.runningInWindows})}if(!e&&r){let e=t.filter(e=>e.isValid&&e.port===r);if(e.length===1)return e}}catch(e){J(e)}return t}async function ADe(e){await e.notification({method:`ide_connected`,params:{pid:process.pid}})}function jDe(e){return e.some(e=>e.type===`connected`&&e.name===`ide`)}async function Ej(e){if(vj(e)){let t=await kj(e);if(t)try{if((await ya(t,[`--list-extensions`],{env:Dj()})).stdout?.includes(Vj))return!0}catch{}}else if(yj(e))return await bDe(e);return!1}async function MDe(e){if(vj(e)){let t=await kj(e);if(t){let e=await NDe(t);if(!e||Wde(e,Oj())){await cc(500);let n=await ya(t,[`--force`,`--install-extension`,`anthropic.claude-code`],{env:Dj()});if(n.code!==0)throw Error(`${n.code}: ${n.error} ${n.stderr}`);e=Oj()}return e}}return null}function Dj(){if(io()===`linux`)return{...process.env,DISPLAY:``}}function Oj(){return`0.0.
|
|
669
|
+
`}));function VTe(e){return!e.uri||!e.server?null:`Read resource "${e.uri}" from server "${e.server}"`}function HTe(){return`readMcpResource`}function UTe(e,t,{verbose:n}){return!e?.contents||e.contents.length===0?(0,FO.jsx)(P,{justifyContent:`space-between`,overflowX:`hidden`,width:`100%`,children:(0,FO.jsx)($,{height:1,children:(0,FO.jsx)(F,{dimColor:!0,children:`(No content)`})})}):(0,FO.jsx)(yC,{content:U(e,null,2),verbose:n})}var FO,WTe=n((()=>{_C(),xC(),ct(),mr(),FO=ut()})),IO,LO,RO,zO=n((()=>{Ks(),GT(),Nt(),cj(),kt(),MO(),mr(),mC(),BTe(),WTe(),IO=V(()=>I({server:B().describe(`The MCP server name`),uri:B().describe(`The resource URI to read`)})),LO=V(()=>I({contents:L(I({uri:B().describe(`Resource URI`),mimeType:B().optional().describe(`MIME type of the content`),text:B().optional().describe(`Text content of the resource`),blobSavedTo:B().optional().describe(`Path where binary blob content was saved`)}))})),RO=Ns({isConcurrencySafe(){return!0},isReadOnly(){return!0},toAutoClassifierInput(e){return`${e.server} ${e.uri}`},shouldDefer:!0,name:`ReadMcpResourceTool`,searchHint:`read a specific MCP resource by URI`,maxResultSizeChars:1e5,async description(){return NO},async prompt(){return PO},get inputSchema(){return IO()},get outputSchema(){return LO()},async call(e,{options:{mcpClients:t}}){let{server:n,uri:r}=e,i=t.find(e=>e.name===n);if(!i)throw Error(`Server "${n}" not found. Available servers: ${t.map(e=>e.name).join(`, `)}`);if(i.type!==`connected`)throw Error(`Server "${n}" is not connected`);if(!i.capabilities?.resources)throw Error(`Server "${n}" does not support resources`);let a=await(await RA(i)).client.request({method:`resources/read`,params:{uri:r}},Qw);return{data:{contents:await Promise.all(a.contents.map(async(e,t)=>{if(`text`in e)return{uri:e.uri,mimeType:e.mimeType,text:e.text};if(!(`blob`in e)||typeof e.blob!=`string`)return{uri:e.uri,mimeType:e.mimeType};let r=`mcp-resource-${Date.now()}-${t}-${Math.random().toString(36).slice(2,8)}`,i=await AO(Buffer.from(e.blob,`base64`),e.mimeType,r);return`error`in i?{uri:e.uri,mimeType:e.mimeType,text:`Binary content could not be saved to disk: ${i.error}`}:{uri:e.uri,mimeType:e.mimeType,blobSavedTo:i.filepath,text:jO(i.filepath,e.mimeType,i.size,`[Resource from ${n} at ${e.uri}] `)}}))}}},renderToolUseMessage:VTe,userFacingName:HTe,renderToolResultMessage:UTe,isResultTruncated(e){return fC(U(e))},mapToolResultToToolResultBlockParam(e,t){return Ys(t,U(e))}})}));function BO(e=HO){let t=new AbortController;return Fce(e,t.signal),t}function GTe(e){let t=this.deref();e.deref()?.abort(t?.signal.reason)}function KTe(e){let t=this.deref(),n=e.deref();t&&n&&t.signal.removeEventListener(`abort`,n)}function VO(e,t){let n=BO(t);if(e.signal.aborted)return n.abort(e.signal.reason),n;let r=new WeakRef(n),i=new WeakRef(e),a=GTe.bind(i,r);return e.signal.addEventListener(`abort`,a,{once:!0}),n.signal.addEventListener(`abort`,KTe.bind(i,new WeakRef(a)),{once:!0}),n}var HO,UO=n((()=>{HO=50}));function qTe(e){let t=e.trim(),n=t.split(/\s+/)[0]?.toLowerCase();if(n){if(n===`npx`||n===`bunx`){let e=t.split(/\s+/)[1]?.toLowerCase();if(e&&e in WO)return WO[e]}return WO[n]}}function JTe(e){for(let{pattern:t,tool:n}of GO)if(t.test(e))return n}var WO,GO,KO=n((()=>{WO={src:`sourcegraph`,cody:`cody`,aider:`aider`,tabby:`tabby`,tabnine:`tabnine`,augment:`augment`,pieces:`pieces`,qodo:`qodo`,aide:`aide`,hound:`hound`,seagoat:`seagoat`,bloop:`bloop`,gitloop:`gitloop`,q:`amazon-q`,gemini:`gemini`},GO=[{pattern:/^sourcegraph$/i,tool:`sourcegraph`},{pattern:/^cody$/i,tool:`cody`},{pattern:/^openctx$/i,tool:`openctx`},{pattern:/^aider$/i,tool:`aider`},{pattern:/^continue$/i,tool:`continue`},{pattern:/^github[-_]?copilot$/i,tool:`github-copilot`},{pattern:/^copilot$/i,tool:`github-copilot`},{pattern:/^cursor$/i,tool:`cursor`},{pattern:/^tabby$/i,tool:`tabby`},{pattern:/^codeium$/i,tool:`codeium`},{pattern:/^tabnine$/i,tool:`tabnine`},{pattern:/^augment[-_]?code$/i,tool:`augment`},{pattern:/^augment$/i,tool:`augment`},{pattern:/^windsurf$/i,tool:`windsurf`},{pattern:/^aide$/i,tool:`aide`},{pattern:/^codestory$/i,tool:`aide`},{pattern:/^pieces$/i,tool:`pieces`},{pattern:/^qodo$/i,tool:`qodo`},{pattern:/^amazon[-_]?q$/i,tool:`amazon-q`},{pattern:/^gemini[-_]?code[-_]?assist$/i,tool:`gemini`},{pattern:/^gemini$/i,tool:`gemini`},{pattern:/^hound$/i,tool:`hound`},{pattern:/^seagoat$/i,tool:`seagoat`},{pattern:/^bloop$/i,tool:`bloop`},{pattern:/^gitloop$/i,tool:`gitloop`},{pattern:/^claude[-_]?context$/i,tool:`claude-context`},{pattern:/^code[-_]?index[-_]?mcp$/i,tool:`code-index-mcp`},{pattern:/^code[-_]?index$/i,tool:`code-index-mcp`},{pattern:/^local[-_]?code[-_]?search$/i,tool:`local-code-search`},{pattern:/^codebase$/i,tool:`autodev-codebase`},{pattern:/^autodev[-_]?codebase$/i,tool:`autodev-codebase`},{pattern:/^code[-_]?context$/i,tool:`claude-context`}]})),qO,JO,YO,YTe=n((()=>{GT(),ni(),qn(),mr(),b(),qO=0,JO=1,YO=class{constructor(e){if(x(this,`ws`,void 0),x(this,`started`,!1),x(this,`opened`,void 0),x(this,`isBun`,typeof Bun<`u`),x(this,`onclose`,void 0),x(this,`onerror`,void 0),x(this,`onmessage`,void 0),x(this,`onBunMessage`,e=>{try{let t=$n(typeof e.data==`string`?e.data:String(e.data)),n=bw.parse(t);this.onmessage?.(n)}catch(e){this.handleError(e)}}),x(this,`onBunError`,()=>{this.handleError(Error(`WebSocket error`))}),x(this,`onBunClose`,()=>{this.handleCloseCleanup()}),x(this,`onNodeMessage`,e=>{try{let t=$n(e.toString(`utf-8`)),n=bw.parse(t);this.onmessage?.(n)}catch(e){this.handleError(e)}}),x(this,`onNodeError`,e=>{this.handleError(e)}),x(this,`onNodeClose`,()=>{this.handleCloseCleanup()}),this.ws=e,this.opened=new Promise((e,t)=>{if(this.ws.readyState===JO)e();else if(this.isBun){let n=this.ws,r=()=>{n.removeEventListener(`open`,r),n.removeEventListener(`error`,i),e()},i=e=>{n.removeEventListener(`open`,r),n.removeEventListener(`error`,i),ei(`error`,`mcp_websocket_connect_fail`),t(e)};n.addEventListener(`open`,r),n.addEventListener(`error`,i)}else{let n=this.ws;n.on(`open`,()=>{e()}),n.on(`error`,e=>{ei(`error`,`mcp_websocket_connect_fail`),t(e)})}}),this.isBun){let e=this.ws;e.addEventListener(`message`,this.onBunMessage),e.addEventListener(`error`,this.onBunError),e.addEventListener(`close`,this.onBunClose)}else{let e=this.ws;e.on(`message`,this.onNodeMessage),e.on(`error`,this.onNodeError),e.on(`close`,this.onNodeClose)}}handleError(e){ei(`error`,`mcp_websocket_message_fail`),this.onerror?.(tr(e))}handleCloseCleanup(){if(this.onclose?.(),this.isBun){let e=this.ws;e.removeEventListener(`message`,this.onBunMessage),e.removeEventListener(`error`,this.onBunError),e.removeEventListener(`close`,this.onBunClose)}else{let e=this.ws;e.off(`message`,this.onNodeMessage),e.off(`error`,this.onNodeError),e.off(`close`,this.onNodeClose)}}async start(){if(this.started)throw Error(`Start can only be called once per transport.`);if(await this.opened,this.ws.readyState!==JO)throw ei(`error`,`mcp_websocket_start_not_opened`),Error(`WebSocket is not open. Cannot start transport.`);this.started=!0}async close(){(this.ws.readyState===JO||this.ws.readyState===qO)&&this.ws.close(),this.handleCloseCleanup()}async send(e){if(this.ws.readyState!==JO)throw ei(`error`,`mcp_websocket_send_not_opened`),Error(`WebSocket is not open. Cannot send message.`);let t=U(e);try{this.isBun?this.ws.send(t):await new Promise((e,n)=>{this.ws.send(t,t=>{t?n(t):e()})})}catch(e){throw this.handleError(e),e}}}}));function XTe(e){return e.mode===`url`?`url`:`form`}function ZTe(e,t,n){return e.findIndex(e=>e.serverName===t&&e.params.mode===`url`&&`elicitationId`in e.params&&e.params.elicitationId===n)}function QTe(e,t,n){try{e.setRequestHandler(AT,async(e,r)=>{Va(t,`Received elicitation request: ${U(e)}`);let i=XTe(e.params);Y(`tengu_mcp_elicitation_shown`,{mode:i});try{let a=await XO(t,e.params,r.signal);if(a)return Va(t,`Elicitation resolved by hook: ${U(a)}`),Y(`tengu_mcp_elicitation_response`,{mode:i,action:a.action}),a;let o=i===`url`&&`elicitationId`in e.params?e.params.elicitationId:void 0,s=await new Promise(a=>{let s=()=>{a({action:`cancel`})};if(r.signal.aborted){s();return}let c=o?{actionLabel:`Skip confirmation`}:void 0;n(n=>({...n,elicitation:{queue:[...n.elicitation.queue,{serverName:t,requestId:r.requestId,params:e.params,signal:r.signal,waitingState:c,respond:e=>{r.signal.removeEventListener(`abort`,s),Y(`tengu_mcp_elicitation_response`,{mode:i,action:e.action}),a(e)}}]}})),r.signal.addEventListener(`abort`,s,{once:!0})});return Va(t,`Elicitation response: ${U(s)}`),await ZO(t,s,r.signal,i,o)}catch(e){return Ua(t,`Elicitation error: ${e}`),{action:`cancel`}}}),e.setNotificationHandler(MT,e=>{let{elicitationId:r}=e.params;Va(t,`Received elicitation completion notification: ${r}`),a7({message:`MCP server "${t}" confirmed elicitation ${r} complete`,notificationType:`elicitation_complete`});let i=!1;n(e=>{let n=ZTe(e.elicitation.queue,t,r);if(n===-1)return e;i=!0;let a=[...e.elicitation.queue];return a[n]={...a[n],completed:!0},{...e,elicitation:{queue:a}}}),i||Va(t,`Ignoring completion notification for unknown elicitation: ${r}`)})}catch{return}}async function XO(e,t,n){try{let r=t.mode===`url`?`url`:`form`,i=`url`in t?t.url:void 0,a=`elicitationId`in t?t.elicitationId:void 0,{elicitationResponse:o,blockingError:s}=await vlt({serverName:e,message:t.message,requestedSchema:`requestedSchema`in t?t.requestedSchema:void 0,signal:n,mode:r,url:i,elicitationId:a});return s?{action:`decline`}:o?{action:o.action,content:o.content}:void 0}catch(t){Ua(e,`Elicitation hook error: ${t}`);return}}async function ZO(e,t,n,r,i){try{let{elicitationResultResponse:a,blockingError:o}=await ylt({serverName:e,action:t.action,content:t.content,signal:n,mode:r,elicitationId:i});if(o)return a7({message:`Elicitation response for server "${e}": decline`,notificationType:`elicitation_response`}),{action:`decline`};let s=a?{action:a.action,content:a.content??t.content}:t;return a7({message:`Elicitation response for server "${e}": ${s.action}`,notificationType:`elicitation_response`}),s}catch(n){return Ua(e,`ElicitationResult hook error: ${n}`),a7({message:`Elicitation response for server "${e}": ${t.action}`,notificationType:`elicitation_response`}),t}}var QO=n((()=>{GT(),g7(),Ga(),mr(),oo()}));function $O(e){let t=[];return{expanded:e.replace(/\$\{([^}]+)\}/g,(e,n)=>{let[r,i]=n.split(`:-`,2),a=process.env[r];return a===void 0?i===void 0?(t.push(r),e):i:a}),missingVars:t}}var ek=n((()=>{}));async function $Te(e){let{vAny:t}=await import(`./dist-DIee4wq1.js`),n=t.McpbManifestSchema.safeParse(e);if(!n.success){let e=n.error.flatten(),t=[...Object.entries(e.fieldErrors).map(([e,t])=>`${e}: ${t?.join(`, `)}`),...e.formErrors||[]].filter(Boolean).join(`; `);throw Error(`Invalid manifest: ${t}`)}return n.data}async function eEe(e){let t;try{t=$n(e)}catch(e){throw Error(`Invalid JSON in manifest.json: ${W(e)}`)}return $Te(t)}async function tk(e){return eEe(new TextDecoder().decode(e))}var tEe=n((()=>{qn(),mr()}));function nEe(e){return!(gr(e)||Cc(wc(e)))}function rEe(e,t){t.fileCount++;let n;t.fileCount>ik.MAX_FILE_COUNT&&(n=`Archive contains too many files: ${t.fileCount} (max: ${ik.MAX_FILE_COUNT})`),nEe(e.name)||(n=`Unsafe file path detected: "${e.name}". Path traversal or absolute paths are not allowed.`);let r=e.originalSize||0;r>ik.MAX_FILE_SIZE&&(n=`File "${e.name}" is too large: ${Math.round(r/1024/1024)}MB (max: ${Math.round(ik.MAX_FILE_SIZE/1024/1024)}MB)`),t.totalUncompressedSize+=r,t.totalUncompressedSize>ik.MAX_TOTAL_SIZE&&(n=`Archive total size is too large: ${Math.round(t.totalUncompressedSize/1024/1024)}MB (max: ${Math.round(ik.MAX_TOTAL_SIZE/1024/1024)}MB)`);let i=t.totalUncompressedSize/t.compressedSize;return i>ik.MAX_COMPRESSION_RATIO&&(n=`Suspicious compression ratio detected: ${i.toFixed(1)}:1 (max: ${ik.MAX_COMPRESSION_RATIO}:1). This may be a zip bomb.`),n?{isValid:!1,error:n}:{isValid:!0}}async function nk(e){let{unzipSync:t}=await import(`./esm-wGnzjq4Z.js`),n={fileCount:0,totalUncompressedSize:0,compressedSize:e.length,errors:[]},r=t(new Uint8Array(e),{filter:e=>{let t=rEe(e,n);if(!t.isValid)throw Error(t.error);return!0}});return G(`Zip extraction completed: ${n.fileCount} files, ${Math.round(n.totalUncompressedSize/1024)}KB uncompressed`),r}function rk(e){let t=Buffer.from(e.buffer,e.byteOffset,e.byteLength),n={},r=Math.max(0,t.length-22-65535),i=-1;for(let e=t.length-22;e>=r;e--)if(t.readUInt32LE(e)===101010256){i=e;break}if(i<0)return n;let a=t.readUInt16LE(i+10),o=t.readUInt32LE(i+16);for(let e=0;e<a&&!(o+46>t.length||t.readUInt32LE(o)!==33639248);e++){let e=t.readUInt16LE(o+4),r=t.readUInt16LE(o+28),i=t.readUInt16LE(o+30),a=t.readUInt16LE(o+32),s=t.readUInt32LE(o+38),c=t.toString(`utf8`,o+46,o+46+r);if(e>>8==3){let e=s>>>16&65535;e&&(n[c]=e)}o+=46+r+i+a}return n}var ik,ak=n((()=>{K(),qn(),or(),Ai(),ik={MAX_FILE_SIZE:512*1024*1024,MAX_TOTAL_SIZE:1024*1024*1024,MAX_FILE_COUNT:1e5,MAX_COMPRESSION_RATIO:50,MIN_COMPRESSION_RATIO:.5}}));function iEe(e,t){return{name:`${e.name}-with-${t.name}-fallback`,read(){return e.read()??(t.read()||{})},async readAsync(){return await e.readAsync()??(await t.readAsync()||{})},update(n){let r=e.read(),i=e.update(n);if(i.success)return r===null&&t.delete(),i;let a=t.update(n);return a.success?(r!==null&&e.delete(),{success:!0,warning:a.warning}):{success:!1}},delete(){let n=e.delete(),r=t.delete();return n||r}}}var aEe=n((()=>{}));function ok(e=``){let t=m(),n=process.env.WORKMATE_CONFIG_DIR?`-${Kc(`sha256`).update(t).digest(`hex`).substring(0,8)}`:``;return`Claude Code${Ine().OAUTH_FILE_SUFFIX}${e}${n}`}function sk(){try{return process.env.USER||Mse().username}catch{return`claude-code-user`}}function ck(){uk.cache={data:null,cachedAt:0},uk.generation++,uk.readInFlight=null}function oEe(e){if(uk.cache.cachedAt!==0)return;let t=null;if(e)try{t=JSON.parse(e)}catch{return}uk.cache={data:t,cachedAt:Date.now()}}var lk,uk,dk=n((()=>{ure(),g(),lk=`-credentials`,uk={cache:{data:null,cachedAt:0},generation:0,readInFlight:null}}));async function sEe(){try{let e=ok(lk),{stdout:t,code:n}=await Ca(`security`,[`find-generic-password`,`-a`,sk(),`-w`,`-s`,e],{useCwd:!1,preserveOutputOnError:!1});if(n===0&&t)return $n(t.trim())}catch{}return null}function cEe(){if(mk!==void 0)return mk;if(process.platform!==`darwin`)return mk=!1,!1;try{mk=ba(`security`,[`show-keychain-info`],{reject:!1,stdio:[`ignore`,`pipe`,`pipe`]}).exitCode===36}catch{mk=!1}return mk}var fk,pk,mk,hk=n((()=>{Sa(),K(),va(),mr(),dk(),fk=4032,pk={name:`keychain`,read(){let e=uk.cache;if(Date.now()-e.cachedAt<3e4)return e.data;try{let e=ok(lk),t=xa(`security find-generic-password -a "${sk()}" -w -s "${e}"`);if(t){let e=$n(t);return uk.cache={data:e,cachedAt:Date.now()},e}}catch{}return e.data===null?(uk.cache={data:null,cachedAt:Date.now()},null):(G(`[keychain] read failed; serving stale cache`,{level:`warn`}),uk.cache={data:e.data,cachedAt:Date.now()},e.data)},async readAsync(){let e=uk.cache;if(Date.now()-e.cachedAt<3e4)return e.data;if(uk.readInFlight)return uk.readInFlight;let t=uk.generation,n=sEe().then(n=>{if(t===uk.generation){n===null&&e.data!==null&&G(`[keychain] readAsync failed; serving stale cache`,{level:`warn`});let t=n??e.data;return uk.cache={data:t,cachedAt:Date.now()},uk.readInFlight=null,t}return n});return uk.readInFlight=n,n},update(e){ck();try{let t=ok(lk),n=sk(),r=U(e),i=Buffer.from(r,`utf-8`).toString(`hex`),a=`add-generic-password -U -a "${n}" -s "${t}" -X "${i}"\n`,o;return a.length<=fk?o=ba(`security`,[`-i`],{input:a,stdio:[`pipe`,`pipe`,`pipe`],reject:!1}):(G(`Keychain payload (${r.length}B JSON) exceeds security -i stdin limit; using argv`,{level:`warn`}),o=ba(`security`,[`add-generic-password`,`-U`,`-a`,n,`-s`,t,`-X`,i],{stdio:[`ignore`,`pipe`,`pipe`],reject:!1})),o.exitCode===0?(uk.cache={data:e,cachedAt:Date.now()},{success:!0}):{success:!1}}catch{return{success:!1}}},delete(){ck();try{let e=ok(lk);return xa(`security delete-generic-password -a "${sk()}" -s "${e}"`),!0}catch{return!1}}}}));function gk(){let e=m();return{storageDir:e,storagePath:X(e,`.credentials.json`)}}var _k,lEe=n((()=>{g(),qn(),or(),mr(),_k={name:`plaintext`,read(){let{storagePath:e}=gk();try{return $n(q().readFileSync(e,{encoding:`utf8`}))}catch{return null}},async readAsync(){let{storagePath:e}=gk();try{return $n(await q().readFile(e,{encoding:`utf8`}))}catch{return null}},update(e){try{let{storageDir:t,storagePath:n}=gk();try{q().mkdirSync(t)}catch(e){if(Xn(e)!==`EEXIST`)throw e}return er(n,U(e),{encoding:`utf8`,flush:!1}),Bse(n,384),{success:!0,warning:`Warning: Storing credentials in plaintext.`}}catch{return{success:!1}}},delete(){let{storagePath:e}=gk();try{return q().unlinkSync(e),!0}catch(e){return Xn(e)===`ENOENT`}}}}));function vk(){return process.platform===`darwin`?iEe(pk,_k):_k}var yk=n((()=>{aEe(),hk(),lEe()}));function uEe(e){let t=e?.platform??io(),n=e?.homedir??_c(),r=e?.env??process.env,i={HOME:n,DESKTOP:X(n,`Desktop`),DOCUMENTS:X(n,`Documents`),DOWNLOADS:X(n,`Downloads`)};switch(t){case`windows`:{let e=r.USERPROFILE||n;return{HOME:n,DESKTOP:X(e,`Desktop`),DOCUMENTS:X(e,`Documents`),DOWNLOADS:X(e,`Downloads`)}}case`linux`:case`wsl`:return{HOME:n,DESKTOP:r.XDG_DESKTOP_DIR||i.DESKTOP,DOCUMENTS:r.XDG_DOCUMENTS_DIR||i.DOCUMENTS,DOWNLOADS:r.XDG_DOWNLOAD_DIR||i.DOWNLOADS};default:return t===`unknown`&&G(`Unknown platform detected, using default paths`),i}}var dEe=n((()=>{K(),ao()}));function bk(e){return e.endsWith(`.mcpb`)||e.endsWith(`.dxt`)}function fEe(e){return e.startsWith(`http://`)||e.startsWith(`https://`)}function pEe(e){return Kc(`sha256`).update(e).digest(`hex`).substring(0,16)}function xk(e){return X(e,`.mcpb-cache`)}function Sk(e,t){return X(e,`${Kc(`md5`).update(t).digest(`hex`).substring(0,8)}.metadata.json`)}function Ck(e,t){return`${e}/${t}`}function wk(e,t){try{let n=fi().pluginConfigs?.[e]?.mcpServers?.[t],r=vk().read()?.pluginSecrets?.[Ck(e,t)];return!n&&!r?null:(G(`Loaded user config for ${e}/${t} (settings + secureStorage)`),{...n,...r})}catch(n){return J(tr(n)),G(`Failed to load user config for ${e}/${t}: ${n}`,{level:`error`}),null}}function Tk(e,t,n,r){try{let i={},a={};for(let[e,t]of Object.entries(n))r[e]?.sensitive===!0?a[e]=String(t):i[e]=t;let o=new Set(Object.keys(a)),s=new Set(Object.keys(i)),c=vk(),l=Ck(e,t),u=c.read()?.pluginSecrets?.[l]??void 0,d=u?Object.fromEntries(Object.entries(u).filter(([e])=>!s.has(e))):void 0,f=d&&u&&Object.keys(d).length!==Object.keys(u).length;if(Object.keys(a).length>0||f){let e=c.read()??{};e.pluginSecrets||(e.pluginSecrets={}),e.pluginSecrets[l]={...d,...a};let t=c.update(e);if(!t.success)throw Error(`Failed to save sensitive config to secure storage for ${l}`);t.warning&&G(`Server secrets save warning: ${t.warning}`,{level:`warn`}),f&&G(`saveMcpServerUserConfig: scrubbed ${Object.keys(u).length-Object.keys(d).length} stale non-sensitive key(s) from secureStorage for ${l}`)}let p=fi(),m=p.pluginConfigs?.[e]?.mcpServers?.[t]??{},h=Object.keys(m).filter(e=>o.has(e));if(Object.keys(i).length>0||h.length>0){p.pluginConfigs||(p.pluginConfigs={}),p.pluginConfigs[e]||(p.pluginConfigs[e]={}),p.pluginConfigs[e].mcpServers||(p.pluginConfigs[e].mcpServers={});let n=Object.fromEntries(h.map(e=>[e,void 0]));p.pluginConfigs[e].mcpServers[t]={...i,...n};let r=li(`userSettings`,p);if(r.error)throw r.error;h.length>0&&G(`saveMcpServerUserConfig: scrubbed ${h.length} plaintext sensitive key(s) from settings.json for ${e}/${t}`)}G(`Saved user config for ${e}/${t} (${Object.keys(i).length} non-sensitive, ${Object.keys(a).length} sensitive)`)}catch(n){let r=tr(n);throw J(r),Error(`Failed to save user configuration for ${e}/${t}: ${r.message}`)}}function Ek(e,t){let n=[];for(let[r,i]of Object.entries(t)){let t=e[r];if(i.required&&(t===void 0||t===``)){n.push(`${i.title||r} is required but not provided`);continue}t===void 0||t===``||(i.type===`string`?Array.isArray(t)?i.multiple?t.every(e=>typeof e==`string`)||n.push(`${i.title||r} must be an array of strings`):n.push(`${i.title||r} must be a string, not an array`):typeof t!=`string`&&n.push(`${i.title||r} must be a string`):i.type===`number`&&typeof t!=`number`?n.push(`${i.title||r} must be a number`):i.type===`boolean`&&typeof t!=`boolean`?n.push(`${i.title||r} must be a boolean`):(i.type===`file`||i.type===`directory`)&&typeof t!=`string`&&n.push(`${i.title||r} must be a path string`),i.type===`number`&&typeof t==`number`&&(i.min!==void 0&&t<i.min&&n.push(`${i.title||r} must be at least ${i.min}`),i.max!==void 0&&t>i.max&&n.push(`${i.title||r} must be at most ${i.max}`)))}return{valid:n.length===0,errors:n}}async function Dk(e,t,n={}){let{getMcpConfigForManifest:r}=await import(`./dist-DIee4wq1.js`),i=await r({manifest:e,extensionPath:t,systemDirs:uEe(),userConfig:n,pathSeparator:`/`});if(!i){let t=Error(`Failed to generate MCP server configuration from manifest "${e.name}"`);throw J(t),t}return i}async function Ok(e,t){let n=q(),r=Sk(e,t);try{return $n(await n.readFile(r,{encoding:`utf-8`}))}catch(e){return Xn(e)===`ENOENT`?null:(J(tr(e)),G(`Failed to load MCPB cache metadata: ${e}`,{level:`error`}),null)}}async function kk(e,t,n){let r=Sk(e,t);await q().mkdir(e),await ll(r,U(n,null,2),`utf-8`)}async function mEe(e,t,n){G(`Downloading MCPB from ${e}`),n&&n(`Downloading ${e}...`);let r=performance.now(),i=!1;try{let a=await Le.get(e,{timeout:12e4,responseType:`arraybuffer`,maxRedirects:5,onDownloadProgress:e=>{e.total&&n&&n(`Downloading... ${Math.round(e.loaded/e.total*100)}%`)}}),o=new Uint8Array(a.data);return Ny(`mcpb`,e,`success`,performance.now()-r),i=!0,await ll(t,Buffer.from(o)),G(`Downloaded ${o.length} bytes to ${t}`),n&&n(`Download complete`),o}catch(t){i||Ny(`mcpb`,e,`failure`,performance.now()-r,Py(t));let n=W(t),a=Error(`Failed to download MCPB file from ${e}: ${n}`);throw J(a),a}}async function hEe(e,t,n,r){r&&r(`Extracting files...`),await q().mkdir(t);let i=0,a=Object.entries(e).filter(([e])=>!e.endsWith(`/`)),o=a.length;for(let[e,s]of a){let a=X(t,e),c=xc(a);c!==t&&await q().mkdir(c),e.endsWith(`.json`)||e.endsWith(`.js`)||e.endsWith(`.ts`)||e.endsWith(`.txt`)||e.endsWith(`.md`)||e.endsWith(`.yml`)||e.endsWith(`.yaml`)?await ll(a,new TextDecoder().decode(s),`utf-8`):await ll(a,Buffer.from(s));let l=n[e];l&&l&73&&await Xc(a,l&511).catch(()=>{}),i++,r&&i%10==0&&r(`Extracted ${i}/${o} files`)}G(`Extracted ${i} files to ${t}`),r&&r(`Extraction complete (${i} files)`)}async function gEe(e,t){let n=q(),r=await Ok(xk(t),e);if(!r)return!0;try{await n.stat(r.extractedPath)}catch(e){return Xn(e)===`ENOENT`?G(`MCPB extraction path missing: ${r.extractedPath}`):G(`MCPB extraction path inaccessible: ${r.extractedPath}: ${e}`,{level:`error`}),!0}if(!fEe(e)){let i=X(t,e),a;try{a=await n.stat(i)}catch(e){return Xn(e)===`ENOENT`?G(`MCPB source file missing: ${i}`):G(`MCPB source file inaccessible: ${i}: ${e}`,{level:`error`}),!0}let o=new Date(r.cachedAt).getTime(),s=Math.floor(a.mtimeMs);if(s>o)return G(`MCPB file modified: ${new Date(s)} > ${new Date(o)}`),!0}return!1}async function Ak(e,t,n,r,i,a){let o=q(),s=xk(t);await o.mkdir(s),G(`Loading MCPB from source: ${e}`);let c=await Ok(s,e);if(c&&!await gEe(e,t)){G(`Using cached MCPB from ${c.extractedPath} (hash: ${c.contentHash})`);let e=X(c.extractedPath,`manifest.json`),t;try{t=await o.readFile(e,{encoding:`utf-8`})}catch(t){if(Qn(t)){let t=Error(`Cached manifest not found: ${e}`);throw J(t),t}throw t}let r=await tk(new TextEncoder().encode(t));if(r.user_config&&Object.keys(r.user_config).length>0){let e=r.name,t=wk(n,e),o=i||t||{},s=Ek(o,r.user_config);return a||!s.valid?{status:`needs-config`,manifest:r,extractedPath:c.extractedPath,contentHash:c.contentHash,configSchema:r.user_config,existingConfig:t||{},validationErrors:s.valid?[]:s.errors}:(i&&Tk(n,e,i,r.user_config??{}),{manifest:r,mcpConfig:await Dk(r,c.extractedPath,o),extractedPath:c.extractedPath,contentHash:c.contentHash})}return{manifest:r,mcpConfig:await Dk(r,c.extractedPath),extractedPath:c.extractedPath,contentHash:c.contentHash}}let l,u;if(fEe(e))u=X(s,`${Kc(`md5`).update(e).digest(`hex`).substring(0,8)}.mcpb`),l=await mEe(e,u,r);else{let n=X(t,e);r&&r(`Loading ${e}...`);try{l=await o.readFileBytes(n),u=n}catch(e){if(Qn(e)){let e=Error(`MCPB file not found: ${n}`);throw J(e),e}throw e}}let d=pEe(l);G(`MCPB content hash: ${d}`),r&&r(`Extracting MCPB archive...`);let f=await nk(Buffer.from(l)),p=rk(l),m=f[`manifest.json`];if(!m){let e=Error(`No manifest.json found in MCPB file`);throw J(e),e}let h=await tk(m);if(G(`MCPB manifest: ${h.name} v${h.version} by ${h.author.name}`),!h.server){let e=Error(`MCPB manifest for "${h.name}" does not define a server configuration`);throw J(e),e}let g=X(s,d);if(await hEe(f,g,p,r),h.user_config&&Object.keys(h.user_config).length>0){let t=h.name,a=wk(n,t),o=i||a||{},c=Ek(o,h.user_config);if(!c.valid)return await kk(s,e,{source:e,contentHash:d,extractedPath:g,cachedAt:new Date().toISOString(),lastChecked:new Date().toISOString()}),{status:`needs-config`,manifest:h,extractedPath:g,contentHash:d,configSchema:h.user_config,existingConfig:a||{},validationErrors:c.errors};i&&Tk(n,t,i,h.user_config??{}),r&&r(`Generating MCP server configuration...`);let l=await Dk(h,g,o);return await kk(s,e,{source:e,contentHash:d,extractedPath:g,cachedAt:new Date().toISOString(),lastChecked:new Date().toISOString()}),{manifest:h,mcpConfig:l,extractedPath:g,contentHash:d}}r&&r(`Generating MCP server configuration...`);let _=await Dk(h,g);return await kk(s,e,{source:e,contentHash:d,extractedPath:g,cachedAt:new Date().toISOString(),lastChecked:new Date().toISOString()}),G(`Successfully loaded MCPB: ${h.name} (extracted to ${g})`),{manifest:h,mcpConfig:_,extractedPath:g,contentHash:d}}var jk=n((()=>{Re(),K(),tEe(),ak(),qn(),or(),Ga(),yk(),vi(),mr(),dEe(),Fy()}));function Mk(e){return e.source}function Nk(){Rk.cache?.clear?.()}function _Ee(e,t,n){let r={},i={};for(let[e,a]of Object.entries(t))n[e]?.sensitive===!0?i[e]=String(a):r[e]=a;let a=new Set(Object.keys(i)),o=new Set(Object.keys(r)),s=vk(),c=s.read()?.pluginSecrets?.[e]??void 0,l=c?Object.fromEntries(Object.entries(c).filter(([e])=>!o.has(e))):void 0,u=l&&c&&Object.keys(l).length!==Object.keys(c).length;if(Object.keys(i).length>0||u){let t=s.read()??{};t.pluginSecrets||(t.pluginSecrets={}),t.pluginSecrets[e]={...l,...i};let n=s.update(t);if(!n.success){let t=Error(`Failed to save sensitive plugin options for ${e} to secure storage`);throw J(t),t}n.warning&&G(`Plugin secrets save warning: ${n.warning}`,{level:`warn`})}let d=fi(),f=d.pluginConfigs?.[e]?.options??{},p=Object.keys(f).filter(e=>a.has(e));if(Object.keys(r).length>0||p.length>0){d.pluginConfigs||(d.pluginConfigs={}),d.pluginConfigs[e]||(d.pluginConfigs[e]={});let t=Object.fromEntries(p.map(e=>[e,void 0]));d.pluginConfigs[e].options={...r,...t};let n=li(`userSettings`,d);if(n.error)throw J(n.error),Error(`Failed to save plugin options for ${e}: ${n.error.message}`)}Nk()}function Pk(e){if(fi().pluginConfigs?.[e]){let{error:t}=li(`userSettings`,{pluginConfigs:{[e]:void 0}});t&&G(`deletePluginOptions: failed to clear settings.pluginConfigs[${e}]: ${t.message}`,{level:`warn`})}let t=vk(),n=t.read();if(n?.pluginSecrets){let r=`${e}/`,i=Object.entries(n.pluginSecrets).filter(([t])=>t!==e&&!t.startsWith(r));i.length!==Object.keys(n.pluginSecrets).length&&(t.update({...n,pluginSecrets:i.length>0?Object.fromEntries(i):void 0}).success||G(`deletePluginOptions: failed to clear pluginSecrets for ${e} from keychain`,{level:`warn`}))}Nk()}function vEe(e){let t=e.manifest.userConfig;if(!t||Object.keys(t).length===0)return{};let n=Rk(Mk(e));if(Ek(n,t).valid)return{};let r={};for(let[e,i]of Object.entries(t))Ek({[e]:n[e]},{[e]:i}).valid||(r[e]=i);return r}function Fk(e,t){let n=e=>process.platform===`win32`?e.replace(/\\/g,`/`):e,r=e.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g,()=>n(t.path));if(t.source){let e=t.source;r=r.replace(/\$\{CLAUDE_PLUGIN_DATA\}/g,()=>n(lb(e)))}return r}function Ik(e,t){return e.replace(/\$\{user_config\.([^}]+)\}/g,(e,n)=>{let r=t[n];if(r===void 0)throw Error(`Missing required user configuration value: ${n}. This should have been validated before variable substitution.`);return String(r)})}function Lk(e,t,n){return e.replace(/\$\{user_config\.([^}]+)\}/g,(e,r)=>{if(n[r]?.sensitive===!0)return`[sensitive option '${r}' not available in skill content]`;let i=t[r];return i===void 0?e:String(i)})}var Rk,zk=n((()=>{d(),K(),Ga(),yk(),vi(),jk(),ub(),Rk=u(e=>{let t=fi().pluginConfigs?.[e]?.options??{},n=vk().read()?.pluginSecrets?.[e]??{};return{...t,...n}})}));async function Bk(e,t,n){try{G(`Loading MCP servers from MCPB: ${t}`);let n=e.repository,r=await Ak(t,e.path,n,t=>{G(`MCPB [${e.name}]: ${t}`)});if(`status`in r&&r.status===`needs-config`)return G(`MCPB ${t} requires user configuration. User can configure via: /plugin → Manage plugins → ${e.name} → Configure`),null;let i=r,a=i.manifest.name;return G(`Loaded MCP server "${a}" from MCPB (extracted to ${i.extractedPath})`),{[a]:i.mcpConfig}}catch(r){let i=W(r);G(`Failed to load MCPB ${t}: ${i}`,{level:`error`});let a=`${e.name}@${e.repository}`;return t.startsWith(`http`)&&(i.includes(`download`)||i.includes(`network`))?n.push({type:`mcpb-download-failed`,source:a,plugin:e.name,url:t,reason:i}):i.includes(`manifest`)||i.includes(`user configuration`)?n.push({type:`mcpb-invalid-manifest`,source:a,plugin:e.name,mcpbPath:t,validationError:i}):n.push({type:`mcpb-extract-failed`,source:a,plugin:e.name,mcpbPath:t,reason:i}),null}}async function Vk(e,t=[]){let n={},r=await Hk(e.path,`.mcp.json`);if(r&&(n={...n,...r}),e.manifest.mcpServers){let r=e.manifest.mcpServers;if(typeof r==`string`)if(bk(r)){let i=await Bk(e,r,t);i&&(n={...n,...i})}else{let t=await Hk(e.path,r);t&&(n={...n,...t})}else if(Array.isArray(r)){let i=await Promise.all(r.map(async n=>{try{return typeof n==`string`?bk(n)?await Bk(e,n,t):await Hk(e.path,n):n}catch(t){return G(`Failed to load MCP servers from spec for plugin ${e.name}: ${t}`,{level:`error`}),null}}));for(let e of i)e&&(n={...n,...e})}else n={...n,...r}}return Object.keys(n).length>0?n:void 0}async function Hk(e,t){let n=q(),r=X(e,t),i;try{i=await n.readFile(r,{encoding:`utf-8`})}catch(e){return Qn(e)||G(`Failed to load MCP servers from ${r}: ${e}`,{level:`error`}),null}try{let e=$n(i),t=e.mcpServers||e,n={};for(let[e,i]of Object.entries(t)){let t=At().safeParse(i);t.success?n[e]=t.data:G(`Invalid MCP server config for ${e} in ${r}: ${t.error.message}`,{level:`error`})}return n}catch(e){return G(`Failed to load MCP servers from ${r}: ${e}`,{level:`error`}),null}}function yEe(e){let t=e.manifest.channels;if(!t||t.length===0)return[];let n=e.repository,r=[];for(let e of t)!e.userConfig||Object.keys(e.userConfig).length===0||Ek(wk(n,e.server)??{},e.userConfig).valid||r.push({server:e.server,displayName:e.displayName??e.server,configSchema:e.userConfig});return r}function bEe(e,t){if(e.manifest.channels?.find(e=>e.server===t)?.userConfig)return wk(e.repository,t)??void 0}function xEe(e,t,n){let r={};for(let[i,a]of Object.entries(e)){let e=`plugin:${t}:${i}`;r[e]={...a,scope:`dynamic`,pluginSource:n}}return r}function SEe(e,t){let n=e.manifest.userConfig?Rk(Mk(e)):void 0,r=bEe(e,t);if(!(!n&&!r))return{...n,...r}}function CEe(e,t,n,r,i,a){let o=[],s=e=>{let r=Fk(e,t);n&&(r=Ik(r,n));let{expanded:i,missingVars:a}=$O(r);return o.push(...a),i},c;switch(e.type){case void 0:case`stdio`:{let n={...e};n.command&&(n.command=s(n.command)),n.args&&(n.args=n.args.map(e=>s(e)));let r={CLAUDE_PLUGIN_ROOT:t.path,CLAUDE_PLUGIN_DATA:lb(t.source),...n.env||{}};for(let[e,t]of Object.entries(r))e!==`CLAUDE_PLUGIN_ROOT`&&e!==`CLAUDE_PLUGIN_DATA`&&(r[e]=s(t));n.env=r,c=n;break}case`sse`:case`http`:case`ws`:{let t={...e};if(t.url&&(t.url=s(t.url)),t.headers){let e={};for(let[n,r]of Object.entries(t.headers))e[n]=s(r);t.headers=e}c=t;break}case`sse-ide`:case`ws-ide`:case`sdk`:case`claudeai-proxy`:c=e;break}if(r&&o.length>0){let e=[...new Set(o)].join(`, `);G(`Missing environment variables in plugin MCP config: ${e}`,{level:`warn`}),i&&a&&r.push({type:`mcp-config-invalid`,source:`plugin:${i}`,plugin:i,serverName:a,validationError:`Missing environment variables: ${e}`})}return c}async function wEe(e,t=[]){if(!e.enabled)return;let n=e.mcpServers||await Vk(e,t);if(!n)return;let r={};for(let[i,a]of Object.entries(n)){let n=SEe(e,i);try{r[i]=CEe(a,e,n,t,e.name,i)}catch(n){t?.push({type:`generic-error`,source:i,plugin:e.name,error:W(n)})}}return xEe(r,e.name,e.source)}var Uk=n((()=>{ek(),wt(),K(),qn(),or(),mr(),jk(),ub(),zk()}));function Wk(){return X(ti(),`managed-mcp.json`)}function Gk(e,t){if(!e)return{};let n={};for(let[r,i]of Object.entries(e))n[r]={...i,scope:t};return n}async function Kk(e){let t=X(H(),`.mcp.json`),n;try{n=(await ol(t)).mode}catch(e){if(Xn(e)!==`ENOENT`)throw e}let r=`${t}.tmp.${process.pid}.${Date.now()}`,i=await el(r,`w`,n??420);try{await i.writeFile(U(e,null,2),{encoding:`utf8`}),await i.datasync()}finally{await i.close()}try{n!==void 0&&await Xc(r,n),await il(r,t)}catch(e){try{await cl(r)}catch{}throw e}}function qk(e){if(e.type!==void 0&&e.type!==`stdio`)return null;let t=e;return[t.command,...t.args??[]]}function Jk(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Yk(e){return`url`in e?e.url:null}function TEe(e){if(!uA.some(t=>e.includes(t)))return e;try{return new URL(e).searchParams.get(`mcp_url`)||e}catch{return e}}function Xk(e){let t=qk(e);if(t)return`stdio:${U(t)}`;let n=Yk(e);return n?`url:${TEe(n)}`:null}function EEe(e,t){let n=new Map;for(let[e,r]of Object.entries(t)){let t=Xk(r);t&&!n.has(t)&&n.set(t,e)}let r={},i=[],a=new Map;for(let[t,o]of Object.entries(e)){let e=Xk(o);if(e===null){r[t]=o;continue}let s=n.get(e);if(s!==void 0){G(`Suppressing plugin MCP server "${t}": duplicates manually-configured "${s}"`),i.push({name:t,duplicateOf:s});continue}let c=a.get(e);if(c!==void 0){G(`Suppressing plugin MCP server "${t}": duplicates earlier plugin server "${c}"`),i.push({name:t,duplicateOf:c});continue}a.set(e,t),r[t]=o}return{servers:r,suppressed:i}}function DEe(e){let t=e.replace(/[.+?^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`.*`);return RegExp(`^${t}$`)}function Zk(e,t){return DEe(t).test(e)}function OEe(){return PEe()?zi(`policySettings`)??{}:Vi()}function kEe(){return Vi()}function Qk(e,t){let n=kEe();if(!n.deniedMcpServers)return!1;for(let t of n.deniedMcpServers)if(Or(t)&&t.serverName===e)return!0;if(t){let e=qk(t);if(e){for(let t of n.deniedMcpServers)if(Vr(t)&&Jk(t.serverCommand,e))return!0}let r=Yk(t);if(r){for(let e of n.deniedMcpServers)if(Mr(e)&&Zk(r,e.serverUrl))return!0}}return!1}function $k(e,t){if(Qk(e,t))return!1;let n=OEe();if(!n.allowedMcpServers)return!0;if(n.allowedMcpServers.length===0)return!1;let r=n.allowedMcpServers.some(Vr),i=n.allowedMcpServers.some(Mr);if(t){let a=qk(t),o=Yk(t);if(a)if(r){for(let e of n.allowedMcpServers)if(Vr(e)&&Jk(e.serverCommand,a))return!0;return!1}else{for(let t of n.allowedMcpServers)if(Or(t)&&t.serverName===e)return!0;return!1}else if(o)if(i){for(let e of n.allowedMcpServers)if(Mr(e)&&Zk(o,e.serverUrl))return!0;return!1}else{for(let t of n.allowedMcpServers)if(Or(t)&&t.serverName===e)return!0;return!1}else{for(let t of n.allowedMcpServers)if(Or(t)&&t.serverName===e)return!0;return!1}}for(let t of n.allowedMcpServers)if(Or(t)&&t.serverName===e)return!0;return!1}function AEe(e){let t={},n=[];for(let[r,i]of Object.entries(e)){let e=i;e.type===`sdk`||$k(r,e)?t[r]=i:n.push(r)}return{allowed:t,blocked:n}}function jEe(e){let t=[];function n(e){let{expanded:n,missingVars:r}=$O(e);return t.push(...r),n}let r;switch(e.type){case void 0:case`stdio`:{let t=e;r={...t,command:n(t.command),args:t.args.map(n),env:t.env?_g(t.env,n):void 0};break}case`sse`:case`http`:case`ws`:{let t=e;r={...t,url:n(t.url),headers:t.headers?_g(t.headers,n):void 0};break}case`sse-ide`:case`ws-ide`:r=e;break;case`sdk`:r=e;break;case`claudeai-proxy`:r=e;break}return{expanded:r,missingVars:[...new Set(t)]}}async function MEe(e,t,n){if(e.match(/[^a-zA-Z0-9_-]/))throw Error(`Invalid name ${e}. Names can only contain letters, numbers, hyphens, and underscores.`);if(dA())throw Error(`Cannot add MCP server: enterprise MCP configuration is active and has exclusive control over MCP servers`);let r=At().safeParse(t);if(!r.success){let e=r.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`, `);throw Error(`Invalid configuration: ${e}`)}let i=r.data;if(Qk(e,i))throw Error(`Cannot add MCP server "${e}": server is explicitly blocked by enterprise policy`);if(!$k(e,i))throw Error(`Cannot add MCP server "${e}": not allowed by enterprise policy`);switch(n){case`project`:{let{servers:t}=eA();if(t[e])throw Error(`MCP server ${e} already exists in .mcp.json`);break}case`user`:if(ha().mcpServers?.[e])throw Error(`MCP server ${e} already exists in user config`);break;case`local`:if(pa().mcpServers?.[e])throw Error(`MCP server ${e} already exists in local config`);break;case`dynamic`:throw Error(`Cannot add MCP server to scope: dynamic`);case`enterprise`:throw Error(`Cannot add MCP server to scope: enterprise`);case`claudeai`:throw Error(`Cannot add MCP server to scope: claudeai`)}switch(n){case`project`:{let{servers:t}=eA(),n={};for(let[e,r]of Object.entries(t)){let{scope:t,...i}=r;n[e]=i}n[e]=i;let r={mcpServers:n};try{await Kk(r)}catch(e){throw Error(`Failed to write to .mcp.json: ${e}`)}break}case`user`:aa(t=>({...t,mcpServers:{...t.mcpServers,[e]:i}}));break;case`local`:la(t=>({...t,mcpServers:{...t.mcpServers,[e]:i}}));break;default:throw Error(`Cannot add MCP server to scope: ${n}`)}}async function NEe(e,t){switch(t){case`project`:{let{servers:t}=eA();if(!t[e])throw Error(`No MCP server found with name: ${e} in .mcp.json`);let n={};for(let[r,i]of Object.entries(t))if(r!==e){let{scope:e,...t}=i;n[r]=t}let r={mcpServers:n};try{await Kk(r)}catch(e){throw Error(`Failed to remove from .mcp.json: ${e}`)}break}case`user`:if(!ha().mcpServers?.[e])throw Error(`No user-scoped MCP server found with name: ${e}`);aa(t=>{let{[e]:n,...r}=t.mcpServers??{};return{...t,mcpServers:r}});break;case`local`:if(!pa().mcpServers?.[e])throw Error(`No project-local MCP server found with name: ${e}`);la(t=>{let{[e]:n,...r}=t.mcpServers??{};return{...t,mcpServers:r}});break;default:throw Error(`Cannot remove MCP server from scope: ${t}`)}}function eA(){if(!Wi(`projectSettings`))return{servers:{},errors:[]};let e=X(H(),`.mcp.json`),{config:t,errors:n}=oA({filePath:e,expandVars:!0,scope:`project`});if(!t){let t=n.filter(e=>!e.message.startsWith(`MCP config file not found`));return t.length>0?(G(`MCP config errors for ${e}: ${U(t.map(e=>e.message))}`,{level:`error`}),{servers:{},errors:t}):{servers:{},errors:[]}}return{servers:t.mcpServers?Gk(t.mcpServers,`project`):{},errors:n||[]}}function tA(e){let t={project:`projectSettings`,user:`userSettings`,local:`localSettings`};if(e in t&&!Wi(t[e]))return{servers:{},errors:[]};switch(e){case`project`:{let t={},n=[],r=[],i=H();for(;i!==Tc(i).root;)r.push(i),i=xc(i);for(let i of r.reverse()){let r=X(i,`.mcp.json`),{config:a,errors:o}=oA({filePath:r,expandVars:!0,scope:`project`});if(!a){let e=o.filter(e=>!e.message.startsWith(`MCP config file not found`));e.length>0&&(G(`MCP config errors for ${r}: ${U(e.map(e=>e.message))}`,{level:`error`}),n.push(...e));continue}a.mcpServers&&Object.assign(t,Gk(a.mcpServers,e)),o.length>0&&n.push(...o)}return{servers:t,errors:n}}case`user`:{let t=ha().mcpServers;if(!t)return{servers:{},errors:[]};let{config:n,errors:r}=aA({configObject:{mcpServers:t},expandVars:!0,scope:`user`});return{servers:Gk(n?.mcpServers,e),errors:r}}case`local`:{let t=pa().mcpServers;if(!t)return{servers:{},errors:[]};let{config:n,errors:r}=aA({configObject:{mcpServers:t},expandVars:!0,scope:`local`});return{servers:Gk(n?.mcpServers,e),errors:r}}case`enterprise`:{let t=Wk(),{config:n,errors:r}=oA({filePath:t,expandVars:!0,scope:`enterprise`});if(!n){let e=r.filter(e=>!e.message.startsWith(`MCP config file not found`));return e.length>0?(G(`Enterprise MCP config errors for ${t}: ${U(e.map(e=>e.message))}`,{level:`error`}),{servers:{},errors:e}):{servers:{},errors:[]}}return{servers:Gk(n.mcpServers,e),errors:r}}}}function nA(e){let{servers:t}=tA(`enterprise`);if(fx(`mcp`))return t[e]??null;let{servers:n}=tA(`user`),{servers:r}=tA(`project`),{servers:i}=tA(`local`);return t[e]?t[e]:i[e]?i[e]:r[e]?r[e]:n[e]?n[e]:null}async function rA(e={},t=Promise.resolve({})){let{servers:n}=tA(`enterprise`);if(dA()){let e={};for(let[t,r]of Object.entries(n))$k(t,r)&&(e[t]=r);return{servers:e,errors:[]}}let r=fx(`mcp`),i={servers:{}},{servers:a}=r?i:tA(`user`),{servers:o}=r?i:tA(`project`),{servers:s}=r?i:tA(`local`),c={},l=await F4(),u=[];if(l.errors.length>0)for(let e of l.errors)if(e.type===`mcp-config-invalid`||e.type===`mcpb-download-failed`||e.type===`mcpb-extract-failed`||e.type===`mcpb-invalid-manifest`){let t=`Plugin MCP loading error - ${e.type}: ${_y(e)}`;J(Error(t))}else{let t=e.type;G(`Plugin not available for MCP: ${e.source} - error type: ${t}`)}let d=await Promise.all(l.enabled.map(e=>wEe(e,u)));for(let e of d)e&&Object.assign(c,e);if(u.length>0)for(let e of u){let t=`Plugin MCP server error - ${e.type}: ${_y(e)}`;J(Error(t))}let f={};for(let[e,t]of Object.entries(o))bA(e)===`approved`&&(f[e]=t);let p=await t,m={};for(let[t,n]of Object.entries({...a,...f,...s,...e,...p}))!cA(t)&&$k(t,n)&&(m[t]=n);let h={},g={};for(let[e,t]of Object.entries(c))cA(e)||!$k(e,t)?g[e]=t:h[e]=t;let{servers:_,suppressed:v}=EEe(h,m);Object.assign(_,g);for(let{name:e,duplicateOf:t}of v){let n=e.split(`:`);n[0]!==`plugin`||n.length<3||u.push({type:`mcp-server-suppressed-duplicate`,source:e,plugin:n[1],serverName:n.slice(2).join(`:`),duplicateOf:t})}let y=Object.assign({},_,a,f,s),b={};for(let[e,t]of Object.entries(y))$k(e,t)&&(b[e]=t);return{servers:b,errors:u}}async function iA(){if(dA())return rA();let{servers:e,errors:t}=await rA();return{servers:e,errors:t}}function aA(e){let{configObject:t,expandVars:n,scope:r,filePath:i}=e,a=Bee().safeParse(t);if(!a.success)return{config:null,errors:a.error.issues.map(e=>({...i&&{file:i},path:e.path.join(`.`),message:`Does not adhere to MCP server configuration schema`,mcpErrorMetadata:{scope:r,severity:`fatal`}}))};let o=[],s={};for(let[e,t]of Object.entries(a.data.mcpServers)){let a=t;if(n){let{expanded:n,missingVars:s}=jEe(t);s.length>0&&o.push({...i&&{file:i},path:`mcpServers.${e}`,message:`Missing environment variables: ${s.join(`, `)}`,suggestion:`Set the following environment variables: ${s.join(`, `)}`,mcpErrorMetadata:{scope:r,serverName:e,severity:`warning`}}),a=n}io()===`windows`&&(!a.type||a.type===`stdio`)&&`command`in a&&(a.command===`npx`||a.command.endsWith(`\\npx`)||a.command.endsWith(`/npx`))&&o.push({...i&&{file:i},path:`mcpServers.${e}`,message:`Windows requires 'cmd /c' wrapper to execute npx`,suggestion:`Change command to "cmd" with args ["/c", "npx", ...]. See: https://code.workmate.com/docs/en/mcp#configure-mcp-servers`,mcpErrorMetadata:{scope:r,serverName:e,severity:`warning`}}),s[e]=a}return{config:{mcpServers:s},errors:o}}function oA(e){let{filePath:t,expandVars:n,scope:r}=e,i=q(),a;try{a=i.readFileSync(t,{encoding:`utf8`})}catch(e){return Xn(e)===`ENOENT`?{config:null,errors:[{file:t,path:``,message:`MCP config file not found: ${t}`,suggestion:`Check that the file path is correct`,mcpErrorMetadata:{scope:r,severity:`fatal`}}]}:(G(`MCP config read error for ${t} (scope=${r}): ${e}`,{level:`error`}),{config:null,errors:[{file:t,path:``,message:`Failed to read file: ${e}`,suggestion:`Check file permissions and ensure the file exists`,mcpErrorMetadata:{scope:r,severity:`fatal`}}]})}let o=Et(a);return o?aA({configObject:o,expandVars:n,scope:r,filePath:t}):(G(`MCP config is not valid JSON: ${t} (scope=${r}, length=${a.length}, first100=${U(a.slice(0,100))})`,{level:`error`}),{config:null,errors:[{file:t,path:``,message:`MCP config is not a valid JSON`,suggestion:`Fix the JSON syntax errors in the file`,mcpErrorMetadata:{scope:r,severity:`fatal`}}]})}function PEe(){return zi(`policySettings`)?.allowManagedMcpServersOnly===!0}function FEe(e){return Object.values(e).every(e=>e.type===`sdk`&&e.name===`claude-vscode`)}function sA(e){return fA.has(e)}function cA(e){let t=pa();return sA(e)?!(t.enabledMcpServers||[]).includes(e):(t.disabledMcpServers||[]).includes(e)}function lA(e,t,n){return e.includes(t)===n?e:n?[...e,t]:e.filter(e=>e!==t)}function IEe(e,t){let n=sA(e)&&cA(e)===t;la(n=>{if(sA(e)){let r=n.enabledMcpServers||[],i=lA(r,e,t);return i===r?n:{...n,enabledMcpServers:i}}let r=n.disabledMcpServers||[],i=lA(r,e,!t);return i===r?n:{...n,disabledMcpServers:i}}),n&&Y(`tengu_builtin_mcp_toggle`,{serverName:e,enabled:t})}var uA,dA,fA,pA=n((()=>{vg(),d(),ao(),vy(),ma(),Vn(),K(),qn(),or(),Ot(),Ga(),Uk(),I4(),wi(),Ur(),mx(),vi(),Rr(),mr(),oo(),ek(),wt(),CA(),uA=[`/v2/session_ingress/shttp/mcp/`,`/v2/ccr-sessions/`],dA=u(()=>{let{config:e}=oA({filePath:Wk(),expandVars:!0,scope:`enterprise`});return e!==null}),fA=new Set([])}));function LEe(e,t){let n=`mcp__${Mi(t)}__`;return e.filter(e=>e.name?.startsWith(n))}function mA(e,t){let n=Mi(t),r=e.name;return r?r.startsWith(`mcp__${n}__`)||r.startsWith(`${n}:`):!1}function REe(e,t){return e.filter(e=>mA(e,t)&&!(e.type===`prompt`&&e.loadedFrom===`mcp`))}function hA(e,t){let n=`mcp__${Mi(t)}__`;return e.filter(e=>!e.name?.startsWith(n))}function gA(e,t){return e.filter(e=>!mA(e,t))}function _A(e,t){let n={...e};return delete n[t],n}function vA(e){let{scope:t,...n}=e,r=U(n,(e,t)=>{if(t&&typeof t==`object`&&!Array.isArray(t)){let e=t,n={};for(let t of Object.keys(e).sort())n[t]=e[t];return n}return t});return Kc(`sha256`).update(r).digest(`hex`).slice(0,16)}function zEe(e,t){let n=e.clients.filter(e=>{let n=t[e.name];return n?vA(e.config)!==vA(n):e.config.scope===`dynamic`});if(n.length===0)return{...e,stale:[]};let{tools:r,commands:i,resources:a}=e;for(let e of n)r=hA(r,e.name),i=gA(i,e.name),a=_A(a,e.name);let o=new Set(n.map(e=>e.name));return{clients:e.clients.filter(e=>!o.has(e.name)),tools:r,commands:i,resources:a,stale:n}}function yA(e){return e.name?.startsWith(`mcp__`)||e.isMcp===!0}function BEe(e){switch(e){case`user`:return Rne();case`project`:return X(H(),`.mcp.json`);case`local`:return`${Rne()} [project: ${H()}]`;case`dynamic`:return`Dynamically configured`;case`enterprise`:return Wk();case`claudeai`:return`claude.ai`;default:return e}}function VEe(e){switch(e){case`local`:return`Local config (private to you in this project)`;case`project`:return`Project config (shared via .mcp.json)`;case`user`:return`User config (available in all your projects)`;case`dynamic`:return`Dynamic config (from command line)`;case`enterprise`:return`Enterprise config (managed by your organization)`;case`claudeai`:return`claude.ai config`;default:return e}}function HEe(e){if(!e)return`local`;if(!jt().options.includes(e))throw Error(`Invalid scope: ${e}. Must be one of: ${jt().options.join(`, `)}`);return e}function UEe(e){if(!e)return`stdio`;if(e!==`stdio`&&e!==`sse`&&e!==`http`)throw Error(`Invalid transport type: ${e}. Must be one of: stdio, sse, http`);return e}function WEe(e){let t={};for(let n of e){let e=n.indexOf(`:`);if(e===-1)throw Error(`Invalid header format: "${n}". Expected format: "Header-Name: value"`);let r=n.substring(0,e).trim(),i=n.substring(e+1).trim();if(!r)throw Error(`Invalid header: "${n}". Header name cannot be empty.`);t[r]=i}return t}function bA(e){let t=fi(),n=Mi(e);return t?.disabledMcpjsonServers?.some(e=>Mi(e)===n)?`rejected`:t?.enabledMcpjsonServers?.some(e=>Mi(e)===n)||t?.enableAllProjectMcpServers||Rre()&&Wi(`projectSettings`)||qt()&&Wi(`projectSettings`)?`approved`:`pending`}function xA(e){if(!yA({name:e}))return null;let t=bi(e);if(!t)return null;let n=nA(t.serverName);return!n&&t.serverName.startsWith(`claude_ai_`)?`claudeai`:n?.scope??null}function GEe(e){return e.type===`stdio`||e.type===void 0}function KEe(e){return e.type===`sse`}function qEe(e){return e.type===`http`}function JEe(e){return e.type===`ws`}function YEe(e){let t=new Map;for(let n of e)if(n.mcpServers?.length)for(let e of n.mcpServers){if(typeof e==`string`)continue;let r=Object.entries(e);if(r.length!==1)continue;let[i,a]=r[0],o=t.get(i);o?o.sourceAgents.includes(n.agentType)||o.sourceAgents.push(n.agentType):t.set(i,{config:{...a,name:i},sourceAgents:[n.agentType]})}let n=[];for(let[e,{config:r,sourceAgents:i}]of t)GEe(r)?n.push({name:e,sourceAgents:i,transport:`stdio`,command:r.command,needsAuth:!1}):KEe(r)?n.push({name:e,sourceAgents:i,transport:`sse`,url:r.url,needsAuth:!0}):qEe(r)?n.push({name:e,sourceAgents:i,transport:`http`,url:r.url,needsAuth:!0}):JEe(r)&&n.push({name:e,sourceAgents:i,transport:`ws`,url:r.url,needsAuth:!1});return n.sort((e,t)=>e.name.localeCompare(t.name))}function SA(e){if(!(!(`url`in e)||typeof e.url!=`string`))try{let t=new URL(e.url);return t.search=``,t.toString().replace(/\/$/,``)}catch{return}}var CA=n((()=>{Jt(),Vn(),Ii(),wi(),vi(),mr(),pA(),Ri(),ci(),wt()}));function XEe(e){return e.replace(/([a-z])([A-Z])/g,`$1_$2`).replace(/-/g,`_`).toLowerCase()}function ZEe(e,t){let n=XEe(t);return{isSearch:wA.has(n),isRead:TA.has(n)}}var wA,TA,QEe=n((()=>{wA=new Set(`slack_search_public.slack_search_public_and_private.slack_search_channels.slack_search_users.search_code.search_repositories.search_issues.search_pull_requests.search_orgs.search_users.search_documentation.search_logs.search_spans.search_rum_events.search_audit_logs.search_monitors.search_monitor_groups.find_slow_spans.find_monitors_matching_pattern.search_docs.search_events.search_issue_events.find_organizations.find_teams.find_projects.find_releases.find_dsns.search.gmail_search_messages.google_drive_search.gcal_find_my_free_time.gcal_find_meeting_times.gcal_find_user_emails.search_jira_issues_using_jql.search_confluence_using_cql.lookup_jira_account_id.confluence_search.jira_search.jira_search_fields.asana_search_tasks.asana_typeahead_search.search_files.search_nodes.brave_web_search.brave_local_search.search_dashboards.search_folders.search_docs.search_stripe_resources.search_stripe_documentation.search_articles.find_related_articles.lookup_article_by_citation.search_papers.search_pubmed.search_pubmed_key_words.search_pubmed_advanced.pubmed_search.pubmed_mesh_lookup.firecrawl_search.web_search_exa.web_search_advanced_exa.people_search_exa.linkedin_search_exa.deep_search_exa.perplexity_search.perplexity_search_web.tavily_search.obsidian_simple_search.obsidian_complex_search.find.search_knowledge.search_memories.find_memories_by_name.search_records.find_tasks.find_tasks_by_date.find_completed_tasks.find_projects.find_sections.find_comments.find_project_collaborators.find_activity.find_labels.find_filters.search_documentation.search_catalog.search_modules.search_providers.search_policies`.split(`.`)),TA=new Set(`slack_read_channel.slack_read_thread.slack_read_canvas.slack_read_user_profile.slack_list_channels.slack_get_channel_history.slack_get_thread_replies.slack_get_users.slack_get_user_profile.get_me.get_team_members.get_teams.get_commit.get_file_contents.get_repository_tree.list_branches.list_commits.list_releases.list_tags.get_latest_release.get_release_by_tag.get_tag.list_issues.issue_read.list_issue_types.get_label.list_label.pull_request_read.get_gist.list_gists.list_notifications.get_notification_details.projects_list.projects_get.actions_get.actions_list.get_job_logs.get_code_scanning_alert.list_code_scanning_alerts.get_dependabot_alert.list_dependabot_alerts.get_secret_scanning_alert.list_secret_scanning_alerts.get_global_security_advisory.list_global_security_advisories.list_org_repository_security_advisories.list_repository_security_advisories.get_discussion.get_discussion_comments.list_discussion_categories.list_discussions.list_starred_repositories.get_issue.get_pull_request.list_pull_requests.get_pull_request_files.get_pull_request_status.get_pull_request_comments.get_pull_request_reviews.list_comments.list_cycles.get_document.list_documents.list_issue_statuses.get_issue_status.list_my_issues.list_issue_labels.list_projects.get_project.list_project_labels.list_teams.get_team.list_users.get_user.aggregate_logs.list_spans.aggregate_spans.analyze_trace.trace_critical_path.query_metrics.aggregate_rum_events.list_rum_metrics.get_rum_metric.list_monitors.get_monitor.check_can_delete_monitor.validate_monitor.validate_existing_monitor.list_dashboards.get_dashboard.query_dashboard_widget.list_notebooks.get_notebook.query_notebook_cell.get_profiling_metrics.compare_profiling_metrics.whoami.get_issue_details.get_issue_tag_values.get_trace_details.get_event_attachment.get_doc.get_sentry_resource.list_events.list_issue_events.get_sentry_issue.fetch.get_comments.get_users.get_self.gmail_get_profile.gmail_read_message.gmail_read_thread.gmail_list_drafts.gmail_list_labels.google_drive_fetch.google_drive_export.gcal_list_calendars.gcal_list_events.gcal_get_event.atlassian_user_info.get_accessible_atlassian_resources.get_visible_jira_projects.get_jira_project_issue_types_metadata.get_jira_issue.get_transitions_for_jira_issue.get_jira_issue_remote_issue_links.get_confluence_spaces.get_confluence_page.get_pages_in_confluence_space.get_confluence_page_ancestors.get_confluence_page_descendants.get_confluence_page_footer_comments.get_confluence_page_inline_comments.confluence_get_page.confluence_get_page_children.confluence_get_comments.confluence_get_labels.jira_get_issue.jira_get_transitions.jira_get_worklog.jira_get_agile_boards.jira_get_board_issues.jira_get_sprints_from_board.jira_get_sprint_issues.jira_get_link_types.jira_download_attachments.jira_batch_get_changelogs.jira_get_user_profile.jira_get_project_issues.jira_get_project_versions.asana_get_attachment.asana_get_attachments_for_object.asana_get_goal.asana_get_goals.asana_get_parent_goals_for_goal.asana_get_portfolio.asana_get_portfolios.asana_get_items_for_portfolio.asana_get_project.asana_get_projects.asana_get_project_sections.asana_get_project_status.asana_get_project_statuses.asana_get_project_task_counts.asana_get_projects_for_team.asana_get_projects_for_workspace.asana_get_task.asana_get_tasks.asana_get_stories_for_task.asana_get_teams_for_workspace.asana_get_teams_for_user.asana_get_team_users.asana_get_time_period.asana_get_time_periods.asana_get_user.asana_get_workspace_users.asana_list_workspaces.read_file.read_text_file.read_media_file.read_multiple_files.list_directory.list_directory_with_sizes.directory_tree.get_file_info.list_allowed_directories.read_graph.open_nodes.query.read_query.list_tables.describe_table.git_status.git_diff.git_diff_unstaged.git_diff_staged.git_log.git_show.git_branch.list_teams.list_users_by_org.get_dashboard_by_uid.get_dashboard_summary.get_dashboard_property.get_dashboard_panel_queries.run_panel_query.list_datasources.get_datasource.get_query_examples.query_prometheus.query_prometheus_histogram.list_prometheus_metric_metadata.list_prometheus_metric_names.list_prometheus_label_names.list_prometheus_label_values.query_loki_logs.query_loki_stats.query_loki_patterns.list_loki_label_names.list_loki_label_values.list_incidents.get_incident.list_sift_investigations.get_sift_investigation.get_sift_analysis.list_oncall_schedules.get_oncall_shift.get_current_oncall_users.list_oncall_teams.list_oncall_users.list_alert_groups.get_alert_group.get_annotations.get_annotation_tags.get_panel_image.list_incidents.get_incident.get_outlier_incident.get_past_incidents.get_related_incidents.list_incident_notes.list_incident_workflows.get_incident_workflow.list_services.get_service.list_team_members.get_user_data.list_schedules.get_schedule.list_schedule_users.list_oncalls.list_log_entries.get_log_entry.list_escalation_policies.get_escalation_policy.list_event_orchestrations.get_event_orchestration.list_status_pages.get_status_page_post.list_alerts_from_incident.get_alert_from_incident.list_change_events.get_change_event.list_organizations.get_organization.get_cost.list_extensions.list_migrations.get_logs.get_advisors.get_project_url.get_publishable_keys.generate_typescript_types.list_edge_functions.get_edge_function.list_storage_buckets.get_storage_config.get_stripe_account_info.retrieve_balance.list_customers.list_products.list_prices.list_invoices.list_payment_intents.list_subscriptions.list_coupons.list_disputes.fetch_stripe_resources.get_article_metadata.get_full_text_article.convert_article_ids.get_copyright_status.download_paper.list_papers.read_paper.get_paper_fulltext.get_pubmed_article_metadata.download_pubmed_pdf.pubmed_fetch.pubmed_pmc_fetch.pubmed_spell.pubmed_cite.pubmed_related.bigquery_query.bigquery_schema.list_dataset_ids.list_table_ids.get_dataset_info.get_table_info.firecrawl_scrape.firecrawl_map.firecrawl_crawl.firecrawl_check_crawl_status.firecrawl_extract.get_code_context_exa.company_research_exa.crawling_exa.deep_researcher_check.perplexity_ask.perplexity_research.perplexity_reason.tavily_extract.tavily_crawl.tavily_map.tavily_research.obsidian_list_files_in_vault.obsidian_list_files_in_dir.obsidian_get_file_contents.obsidian_batch_get_file_contents.obsidian_get_periodic_note.obsidian_get_recent_periodic_notes.obsidian_get_recent_changes.get_figma_data.download_figma_images.browser_console_messages.browser_network_requests.browser_take_screenshot.browser_snapshot.browser_get_config.browser_route_list.browser_cookie_list.browser_cookie_get.browser_localstorage_list.browser_localstorage_get.browser_sessionstorage_list.browser_sessionstorage_get.browser_storage_state.puppeteer_screenshot.list_databases.list_collections.collection_indexes.collection_schema.collection_storage_size.db_stats.explain.mongodb_logs.aggregate.count.export.get_neo4j_schema.read_neo4j_cypher.list_instances.get_instance_details.get_instance_by_name.list_indices.get_mappings.esql.get_shards.list_records.list_bases.get_record.get_productivity_stats.get_overview.fetch_object.user_info.list_workspaces.view_attachment.get_available_services.read_documentation.read_sections.recommend.analyze_log_group.analyze_metric.describe_log_groups.get_active_alarms.get_alarm_history.get_metric_data.get_metric_metadata.kubectl_get.kubectl_describe.kubectl_logs.kubectl_context.explain_resource.list_api_resources.namespaces_list.nodes_log.nodes_top.pods_get.pods_list.pods_list_in_namespace.pods_log.pods_top.resources_get.resources_list`.split(`.`))}));function $Ee(e){return e.scope===`project`||e.scope===`local`}async function eDe(e,t){if(!t.headersHelper)return null;if(`scope`in t&&$Ee(t)&&!qt()&&!fa())return pr(`MCP headersHelper invoked before trust check`,Error(`Security: headersHelper for MCP server '${e}' executed before workspace trust is confirmed. If you see this message, post in .`)),Y(`tengu_mcp_headersHelper_missing_trust`,{}),null;try{Va(e,`Executing headersHelper to get dynamic headers`);let n=await ya(t.headersHelper,[],{shell:!0,timeout:1e4,env:{...process.env,CLAUDE_CODE_MCP_SERVER_NAME:e,CLAUDE_CODE_MCP_SERVER_URL:t.url}});if(n.code!==0||!n.stdout)throw Error(`headersHelper for MCP server '${e}' did not return a valid value`);let r=$n(n.stdout.trim());if(typeof r!=`object`||!r||Array.isArray(r))throw Error(`headersHelper for MCP server '${e}' must return a JSON object with string key-value pairs`);for(let[t,n]of Object.entries(r))if(typeof n!=`string`)throw Error(`headersHelper for MCP server '${e}' returned non-string value for key "${t}": ${typeof n}`);return Va(e,`Successfully retrieved ${Object.keys(r).length} headers from headersHelper`),r}catch(t){return Ua(e,`Error getting headers from headersHelper: ${W(t)}`),J(Error(`Error getting MCP headers from headersHelper for server '${e}': ${W(t)}`)),null}}async function EA(e,t){let n=t.headers||{},r=await eDe(e,t)||{};return{...n,...r}}var tDe=n((()=>{Jt(),ma(),K(),qn(),va(),Ga(),mr(),oo()})),DA,nDe=n((()=>{b(),DA=class{constructor(e,t){x(this,`serverName`,void 0),x(this,`sendMcpMessage`,void 0),x(this,`isClosed`,!1),x(this,`onclose`,void 0),x(this,`onerror`,void 0),x(this,`onmessage`,void 0),this.serverName=e,this.sendMcpMessage=t}async start(){}async send(e){if(this.isClosed)throw Error(`Transport is closed`);let t=await this.sendMcpMessage(this.serverName,e);this.onmessage&&this.onmessage(t)}async close(){this.isClosed||(this.isClosed=!0,this.onclose?.())}}}));function OA(e){return(`code`in e?e.code:void 0)===404?e.message.includes(`"code":-32001`)||e.message.includes(`"code": -32001`):!1}function rDe(){return parseInt(process.env.MCP_TOOL_TIMEOUT||``,10)||ZA}function kA(e){let t=SA(e);return t?{mcpServerBaseUrl:t}:{}}function AA(e,t,n){return Y(`tengu_mcp_server_needs_auth`,{transportType:n,...kA(t)}),Va(e,`Authentication required for ${{sse:`SSE`,http:`HTTP`,"claudeai-proxy":`claude.ai proxy`}[n]} server`),{name:e,type:`needs-auth`,config:t}}async function jA(e,t){let n=(await import(`./wrapper-K8ZapJVu.js`)).default;return new n(e,[`mcp`],t)}function MA(){return parseInt(process.env.MCP_TIMEOUT||``,10)||3e4}function NA(e){return async(t,n)=>{if((n?.method??`GET`).toUpperCase()===`GET`)return e(t,n);let r=new Headers(n?.headers);r.has(`accept`)||r.set(`accept`,tj);let i=new AbortController,a=setTimeout(e=>e.abort(new DOMException(`The operation timed out.`,`TimeoutError`)),ej,i);a.unref?.();let o=n?.signal,s=()=>i.abort(o?.reason);o?.addEventListener(`abort`,s),o?.aborted&&i.abort(o.reason);let c=()=>{clearTimeout(a),o?.removeEventListener(`abort`,s)};try{let a=await e(t,{...n,headers:r,signal:i.signal});return c(),a}catch(e){throw c(),e}}}function PA(){return parseInt(process.env.MCP_SERVER_CONNECTION_BATCH_SIZE||``,10)||3}function iDe(){return parseInt(process.env.MCP_REMOTE_SERVER_CONNECTION_BATCH_SIZE||``,10)||20}function FA(e){return!e.type||e.type===`stdio`||e.type===`sdk`}function aDe(e){return!e.name.startsWith(`mcp__ide__`)||nj.includes(e.name)}function IA(e,t){return`${e}-${U(t)}`}async function LA(e,t){let n=IA(e,t);try{let n=await rj(e,t);n.type===`connected`&&await n.cleanup()}catch{}rj.cache.delete(n),aj.cache.delete(e),oj.cache.delete(e),sj.cache.delete(e)}async function RA(e){if(e.config.type===`sdk`)return e;let t=await rj(e.name,e.config);if(t.type!==`connected`)throw new cr(`MCP server "${e.name}" is not connected`,`MCP server not connected`);return t}function oDe(e,t){if(e.type!==t.type)return!1;let{scope:n,...r}=e,{scope:i,...a}=t;return U(r)===U(a)}function sDe(e,t){let n=Object.keys(e);return n.length>0?n.map(t=>`${t}=${String(e[t])}`).join(` `):t}async function zA(e,t,n){return(await qA({client:n,tool:e,args:t,signal:BO().signal})).content}async function cDe(e,t){try{ck(),await LA(e,t);let n=await rj(e,t);if(n.type!==`connected`)return{client:n,tools:[],commands:[]};let r=!!n.capabilities?.resources,[i,a,o,s]=await Promise.all([aj(n),sj(n),Promise.resolve([]),r?oj(n):Promise.resolve([])]),c=[...a,...o],l=[];return r&&([fO,RO].some(e=>i.some(t=>Cs(t,e.name)))||l.push(fO,RO)),{client:n,tools:[...i,...l],commands:c,resources:s.length>0?s:void 0}}catch(n){return Ua(e,`Error during reconnection: ${W(n)}`),{client:{name:e,type:`failed`,config:t},tools:[],commands:[]}}}async function BA(e,t,n){await Zce(e,n,{concurrency:t})}async function VA(e,t){let n=!1,r=Object.entries(t??(await iA()).servers),i=[];for(let t of r)cA(t[0])?e({client:{name:t[0],type:`disabled`,config:t[1]},tools:[],commands:[]}):i.push(t);let a=i.length,o=Xr(i,([e,t])=>t.type===`stdio`),s=Xr(i,([e,t])=>t.type===`sse`),c=Xr(i,([e,t])=>t.type===`http`),l=Xr(i,([e,t])=>t.type===`sse-ide`),u=Xr(i,([e,t])=>t.type===`ws-ide`),d=i.filter(([e,t])=>FA(t)),f=i.filter(([e,t])=>!FA(t)),p={totalServers:a,stdioCount:o,sseCount:s,httpCount:c,sseIdeCount:l,wsIdeCount:u},m=async([t,r])=>{try{if(cA(t)){e({client:{name:t,type:`disabled`,config:r},tools:[],commands:[]});return}let i=await rj(t,r,p);if(i.type!==`connected`){e({client:i,tools:[],commands:[]});return}let a=!!i.capabilities?.resources,[o,s,c,l]=await Promise.all([aj(i),sj(i),Promise.resolve([]),a?oj(i):Promise.resolve([])]),u=[...s,...c],d=[];a&&!n&&(n=!0,d.push(fO,RO)),e({client:i,tools:[...o,...d],commands:u,resources:l.length>0?l:void 0})}catch(n){Ua(t,`Error fetching tools/commands/resources: ${W(n)}`),e({client:{name:t,type:`failed`,config:r},tools:[],commands:[]})}};await Promise.all([BA(d,PA(),m),BA(f,iDe(),m)])}function HA(e){return new Promise(t=>{let n=0,r=0;if(n=Object.keys(e).length,n===0){t({clients:[],tools:[],commands:[]});return}let i=[],a=[],o=[];VA(e=>{if(i.push(e.client),a.push(...e.tools),o.push(...e.commands),r++,r>=n){let e=o.reduce((e,t)=>e+(t.name.length+(t.description??``).length+(t.argumentHint??``).length),0);Y(`tengu_mcp_tools_commands_loaded`,{tools_count:a.length,commands_count:o.length,commands_metadata_length:e}),t({clients:i,tools:a,commands:o})}},e).catch(e=>{Ua(`prefetchAllMcpResources`,`Failed to get MCP resources: ${W(e)}`),t({clients:[],tools:[],commands:[]})})})}async function UA(e,t,n,r=!1){switch(e.type){case`text`:{let t={type:`text`,text:e.text};if(r){let n=e._meta;n&&(t._meta=n)}return[t]}case`audio`:{let n=e;return await WA(Buffer.from(n.data,`base64`),n.mimeType,t,`[Audio from ${t}] `)}case`image`:{let t=Buffer.from(String(e.data),`base64`),r=e.mimeType?.split(`/`)[1]||`png`,i=await wb(t,t.length,r,n);return[{type:`image`,source:{data:i.buffer.toString(`base64`),media_type:`image/${i.mediaType}`,type:`base64`}}]}case`resource`:{let r=e.resource,i=`[Resource from ${t} at ${r.uri}] `;if(`text`in r)return[{type:`text`,text:`${i}${r.text}`}];if(`blob`in r)if($A.has(r.mimeType??``)){let e=Buffer.from(r.blob,`base64`),t=r.mimeType?.split(`/`)[1]||`png`,a=await wb(e,e.length,t,n),o=[];return i&&o.push({type:`text`,text:i}),o.push({type:`image`,source:{data:a.buffer.toString(`base64`),media_type:`image/${a.mediaType}`,type:`base64`}}),o}else return await WA(Buffer.from(r.blob,`base64`),r.mimeType,t,i);return[]}case`resource_link`:{let t=e,n=`[Resource link: ${t.name}] ${t.uri}`;return t.description&&(n+=` (${t.description})`),[{type:`text`,text:n}]}default:return[]}}async function WA(e,t,n,r){let i=await AO(e,t,`mcp-${Mi(n)}-blob-${Date.now()}-${Math.random().toString(36).slice(2,8)}`);return`error`in i?[{type:`text`,text:`${r}Binary content (${t||`unknown type`}, ${e.length} bytes) could not be saved to disk: ${i.error}`}]:[{type:`text`,text:jO(i.filepath,t,i.size,r)}]}function GA(e,t=2){if(e===null)return`null`;if(Array.isArray(e))return e.length===0?`[]`:`[${GA(e[0],t-1)}]`;if(typeof e==`object`){if(t<=0)return`{...}`;let n=Object.entries(e).slice(0,10).map(([e,n])=>`${e}: ${GA(n,t-1)}`),r=Object.keys(e).length>10?`, ...`:``;return`{${n.join(`, `)}${r}}`}return typeof e}async function lDe(e,t,n,r){if(e&&typeof e==`object`){if(`toolResult`in e)return{content:String(e.toolResult),type:`toolResult`};if(`structuredContent`in e&&e.structuredContent!==void 0)return{content:U(e.structuredContent),type:`structuredContent`,schema:GA(e.structuredContent)};if(`content`in e&&Array.isArray(e.content)){let t=(await Promise.all(e.content.map(e=>UA(e,n,r,!0)))).flat();return{content:t,type:`contentArray`,schema:GA(t)}}}let i=`MCP server "${n}" tool "${t}": unexpected response format`;throw Ua(n,i),new cr(i,`MCP tool unexpected response format`)}function KA(e){return!e||typeof e==`string`?!1:e.some(e=>e.type===`image`)}async function uDe(e,t,n,r,i=!1){let{content:a,type:o,schema:s}=await lDe(e,t,n,r);if(n===`ide`||i&&!KA(a)||!await vO(a))return a;let c=_O(a);if(f(process.env.ENABLE_MCP_LARGE_OUTPUT_FILES))return Y(`tengu_mcp_large_result_handled`,{outcome:`truncated`,reason:`env_disabled`,sizeEstimateTokens:c}),await yO(a);if(!a)return a;if(KA(a))return Y(`tengu_mcp_large_result_handled`,{outcome:`truncated`,reason:`contains_images`,sizeEstimateTokens:c}),await yO(a);let l=Date.now(),u=`mcp-${Mi(n)}-${Mi(t)}-${l}`,d=fDe(a),p=typeof a==`string`?a:d??U(a,null,2),m=await dS(p,u);if(hS(m)){let e=p.length;return Y(`tengu_mcp_large_result_handled`,{outcome:`truncated`,reason:`persist_failed`,sizeEstimateTokens:c}),`Error: result (${e.toLocaleString()} characters) exceeds maximum allowed tokens. Failed to save output to file: ${m.error}. If this MCP server provides pagination or filtering tools, use them to retrieve specific portions of the data.`}Y(`tengu_mcp_large_result_handled`,{outcome:`persisted`,reason:`file_saved`,sizeEstimateTokens:c,persistedSizeChars:m.originalSize});let h=d===void 0?kO(o,s):kO(`toolResult`);return RTe(m.filepath,m.originalSize,h)}function dDe(){let e=process.env.MCP_TRUNCATION_PROMPT_OVERRIDE;return e?e!==`legacy`:!1}function fDe(e){if(!dDe()||!Array.isArray(e)||e.length!==1)return;let t=e[0];if(t?.type===`text`&&!(`annotations`in t||`_meta`in t))return t.text}async function pDe({client:e,clientConnection:t,tool:n,args:r,meta:i,signal:a,setAppState:o,onProgress:s,imageLimits:c,hasResultSizeAnnotation:l=!1,callToolFn:u=qA,handleElicitation:d}){for(let f=0;;f++)try{return await u({client:e,tool:n,args:r,meta:i,signal:a,onProgress:s,imageLimits:c,hasResultSizeAnnotation:l})}catch(e){if(!(e instanceof UT)||e.code!==vw.UrlElicitationRequired||f>=3)throw e;let r=e.data,i=(typeof r==`object`&&r&&`elicitations`in r&&Array.isArray(r.elicitations)?r.elicitations:[]).filter(e=>{if(typeof e!=`object`||!e)return!1;let t=e;return t.mode===`url`&&typeof t.url==`string`&&typeof t.elicitationId==`string`&&typeof t.message==`string`}),s=t.type===`connected`?t.name:`unknown`;if(i.length===0)throw Va(s,`Tool '${n}' returned -32042 but no valid elicitations in error data`),e;Va(s,`Tool '${n}' requires URL elicitation (error -32042, attempt ${f+1}), processing ${i.length} elicitation(s)`);for(let e of i){let{elicitationId:t}=e,r=await XO(s,e,a);if(r){if(Va(s,`URL elicitation ${t} resolved by hook: ${U(r)}`),r.action!==`accept`)return{content:`URL elicitation was ${r.action===`decline`?`declined`:`${r.action}ed`} by a hook. The tool "${n}" could not complete because it requires the user to open a URL.`};continue}let i;if(d)i=await d(s,e,a);else{let n={actionLabel:`Retry now`,showCancel:!0};i=await new Promise(r=>{let i=()=>{r({action:`cancel`})};if(a.aborted){i();return}a.addEventListener(`abort`,i,{once:!0}),o(o=>({...o,elicitation:{queue:[...o.elicitation.queue,{serverName:s,requestId:`error-elicit-${t}`,params:e,signal:a,waitingState:n,respond:e=>{e.action!==`accept`&&(a.removeEventListener(`abort`,i),r(e))},onWaitingDismiss:e=>{a.removeEventListener(`abort`,i),r(e===`retry`?{action:`accept`}:{action:`cancel`})}}]}}))})}let c=await ZO(s,i,a,`url`,t);if(c.action!==`accept`)return Va(s,`User ${c.action===`decline`?`declined`:`${c.action}ed`} URL elicitation ${t}`),{content:`URL elicitation was ${c.action===`decline`?`declined`:`${c.action}ed`} by the user. The tool "${n}" could not complete because it requires the user to open a URL.`};Va(s,`Elicitation ${t} completed, retrying tool call`)}}}async function qA({client:{client:e,name:t,config:n},tool:r,args:i,meta:a,signal:o,onProgress:s,imageLimits:c,hasResultSizeAnnotation:l=!1}){let u=Date.now(),d;try{Va(t,`Calling MCP tool: ${r}`),d=setInterval((e,t,n)=>{let r=Date.now()-e;Va(t,`Tool '${n}' still running (${`${Math.floor(r/1e3)}s`} elapsed)`)},3e4,u,t,r);let n=rDe(),f,p=new Promise((e,i)=>{f=setTimeout((e,t,n,r)=>{e(new cr(`MCP server "${t}" tool "${n}" timed out after ${Math.floor(r/1e3)}s`,`MCP tool timeout`))},n,i,t,r,n)}),m=await Promise.race([e.callTool({name:r,arguments:i,_meta:a},uT,{signal:o,timeout:n,onprogress:s?e=>{s({type:`mcp_progress`,status:`progress`,serverName:t,toolName:r,progress:e.progress,total:e.total,progressMessage:e.message})}:void 0}),p]).finally(()=>{f&&clearTimeout(f)});if(`isError`in m&&m.isError){let e=`Unknown error`;if(`content`in m&&Array.isArray(m.content)&&m.content.length>0){let t=m.content[0];t&&typeof t==`object`&&`text`in t&&(e=t.text)}else`error`in m&&(e=String(m.error));throw Ua(t,e),new XA(e,`MCP tool returned error`,`_meta`in m&&m._meta?{_meta:m._meta}:void 0)}let h=Date.now()-u;Va(t,`Tool '${r}' completed successfully in ${h<1e3?`${h}ms`:h<6e4?`${Math.floor(h/1e3)}s`:`${Math.floor(h/6e4)}m ${Math.floor(h%6e4/1e3)}s`}`);let g=JTe(t);return g&&Y(`tengu_code_indexing_tool_used`,{tool:g,source:`mcp`,success:!0}),{content:await uDe(m,r,t,c,l),_meta:m._meta,structuredContent:m.structuredContent}}catch(e){d!==void 0&&clearInterval(d);let i=Date.now()-u;if(e instanceof Error&&e.name!==`AbortError`&&Va(t,`Tool '${r}' failed after ${Math.floor(i/1e3)}s: ${e.message}`),e instanceof Error){if((`code`in e?e.code:void 0)===401||e instanceof VD)throw Va(t,`Tool call returned 401 Unauthorized - token may have expired`),Y(`tengu_mcp_tool_call_auth_error`,{}),new JA(t,`MCP server "${t}" requires re-authorization (token expired)`);let r=OA(e),i=`code`in e&&e.code===-32e3&&e.message.includes(`Connection closed`)&&n.type===`http`;if(r||i)throw Va(t,`MCP session expired during tool call (${r?`404/-32001`:`connection closed`}), clearing connection cache for re-initialization`),Y(`tengu_mcp_session_expired`,{}),await LA(t,n),new YA(t)}if(!(e instanceof Error)||e.name!==`AbortError`)throw e;return{content:void 0}}finally{d!==void 0&&clearInterval(d)}}function mDe(e){let t=e.message.content?.[0];if(!(!t||typeof t==`string`||t.type!==`tool_use`))return t.id}async function hDe(e,t){let n=[],r=[],i=await Promise.allSettled(Object.entries(e).map(async([e,n])=>{let r=new DA(e,t),i=new cE({name:`workmate`,title:`Work Mate`,version:`0.0.24`,description:`Agentic coding tool`,websiteUrl:rO},{capabilities:{}});try{await i.connect(r);let t=i.getServerCapabilities(),a={type:`connected`,name:e,capabilities:t||{},client:i,config:{...n,scope:`dynamic`},cleanup:async()=>{await i.close()}},o=[];if(t?.tools){let e=await aj(a);o.push(...e)}return{client:a,tools:o}}catch(t){return Ua(e,`Failed to connect SDK MCP server: ${t}`),{client:{type:`failed`,name:e,config:{...n,scope:`user`}},tools:[]}}}));for(let e of i)e.status===`fulfilled`&&(n.push(e.value.client),r.push(...e.value.tools));return{clients:n,tools:r}}var JA,YA,XA,ZA,QA,$A,ej,tj,nj,rj,ij,aj,oj,sj,cj=n((()=>{Lwe(),gTe(),yTe(),xTe(),$E(),GT(),vg(),d(),Mg(),Qce(),Jt(),iO(),Ks(),pO(),LTe(),zO(),UO(),Ar(),Hn(),KO(),K(),g(),qn(),jie(),Wj(),Ab(),Ga(),MO(),SO(),YTe(),Dt(),voe(),Qs(),Bx(),vS(),oo(),QO(),Ri(),ci(),CA(),Yoe(),b(),WD(),QEe(),dk(),lc(),pA(),tDe(),nDe(),mr(),JA=class extends Error{constructor(e,t){super(t),x(this,`serverName`,void 0),this.name=`McpAuthError`,this.serverName=e}},YA=class extends Error{constructor(e){super(`MCP server "${e}" session expired`),this.name=`McpSessionExpiredError`}},XA=class extends cr{constructor(e,t,n){super(e,t),x(this,`mcpMeta`,void 0),this.mcpMeta=n,this.name=`McpToolCallError`}},ZA=1e8,QA=2048,$A=new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]),ej=6e4,tj=`application/json, text/event-stream`,nj=[`mcp__ide__executeCode`,`mcp__ide__getDiagnostics`],rj=u(async(e,t,n)=>{let r=Date.now();try{let i;if(t.type===`sse`){let n=await EA(e,t),r={fetch:NA(QE()),requestInit:{headers:{"User-Agent":Do(),...n}}};r.eventSourceInit={fetch:async(e,t)=>{let r=$s();return fetch(e,{...t,...r,headers:{"User-Agent":Do(),...t?.headers,...n,Accept:`text/event-stream`}})}},i=new KD(new URL(t.url),r),Va(e,`SSE transport initialized, awaiting connection`)}else if(t.type===`sse-ide`){Va(e,`Setting up SSE-IDE transport to ${t.url}`);let n=$s(),r=n.dispatcher?{eventSourceInit:{fetch:async(e,t)=>fetch(e,{...t,...n,headers:{"User-Agent":Do(),...t?.headers}})}}:{};i=new KD(new URL(t.url),Object.keys(r).length>0?r:void 0)}else if(t.type===`ws-ide`){let e=boe(),n={"User-Agent":Do(),...t.authToken&&{"X-Work Mate-Code-Ide-Authorization":t.authToken}},r;r=typeof Bun<`u`?new globalThis.WebSocket(t.url,{protocols:[`mcp`],headers:n,proxy:xoe(t.url),tls:e||void 0}):await jA(t.url,{headers:n,agent:yoe(t.url),...e||{}}),i=new YO(r)}else if(t.type===`ws`){Va(e,`Initializing WebSocket transport to ${t.url}`);let n=await EA(e,t),r=boe(),a={"User-Agent":Do(),...n},o=_g(a,(e,t)=>t.toLowerCase()===`authorization`?`[REDACTED]`:e);Va(e,`WebSocket transport options: ${U({url:t.url,headers:o})}`);let s;s=typeof Bun<`u`?new globalThis.WebSocket(t.url,{protocols:[`mcp`],headers:a,proxy:xoe(t.url),tls:r||void 0}):await jA(t.url,{headers:a,agent:yoe(t.url),...r||{}}),i=new YO(s)}else if(t.type===`http`){Va(e,`Initializing HTTP transport to ${t.url}`),Va(e,`Node version: ${process.version}, Platform: ${process.platform}`),Va(e,`Environment: ${U({NODE_OPTIONS:process.env.NODE_OPTIONS||`not set`,UV_THREADPOOL_SIZE:process.env.UV_THREADPOOL_SIZE||`default`,HTTP_PROXY:process.env.HTTP_PROXY||`not set`,HTTPS_PROXY:process.env.HTTPS_PROXY||`not set`,NO_PROXY:process.env.NO_PROXY||`not set`})}`);let n=await EA(e,t),r=$s();Va(e,`Proxy options: ${r.dispatcher?`custom dispatcher`:`default`}`);let a={fetch:NA(QE()),requestInit:{...r,headers:{"User-Agent":Do(),...n}}},o=a.requestInit?.headers?_g(a.requestInit.headers,(e,t)=>t.toLowerCase()===`authorization`?`[REDACTED]`:e):void 0;Va(e,`HTTP transport options: ${U({url:t.url,headers:o,timeoutMs:ej})}`),i=new nO(new URL(t.url),a),Va(e,`HTTP transport created successfully`)}else if(t.type===`sdk`)throw Error(`SDK servers should be handled in print.ts`);else if(t.type===`stdio`||!t.type){let e=t;i=new QD({command:process.env.CLAUDE_CODE_SHELL_PREFIX||e.command,args:process.env.CLAUDE_CODE_SHELL_PREFIX?[[e.command,...e.args].join(` `)]:e.args,env:{...zx(),...e.env},stderr:`pipe`})}else throw Error(`Unsupported server type: ${t.type}`);let a,o=``;if(t.type===`stdio`||!t.type){let e=i;e.stderr&&(a=e=>{if(o.length<64*1024*1024)try{o+=e.toString()}catch{}},e.stderr.on(`data`,a))}let s=new cE({name:`workmate`,title:`Work Mate`,version:`0.0.24`,description:`Agentic coding tool`,websiteUrl:rO},{capabilities:{roots:{},elicitation:{}}});if(t.type===`http`&&Va(e,`Client created, setting up request handler`),s.setRequestHandler(BT,async()=>(Va(e,`Received ListRoots request from server`),{roots:[{uri:`file://${Yt()}`}]})),Va(e,`Starting connection with timeout of ${MA()}ms`),t.type===`http`){Va(e,`Testing basic HTTP connectivity to ${t.url}`);try{let n=new URL(t.url);Va(e,`Parsed URL: host=${n.hostname}, port=${n.port||`default`}, protocol=${n.protocol}`),(n.hostname===`127.0.0.1`||n.hostname===`localhost`)&&Va(e,`Using loopback address: ${n.hostname}`)}catch(t){Va(e,`Failed to parse URL: ${t}`)}}let c=s.connect(i),l=new Promise((t,n)=>{let a=setTimeout(()=>{Va(e,`Connection timeout triggered after ${Date.now()-r}ms (limit: ${MA()}ms)`),i.close().catch(()=>{}),n(new cr(`MCP server "${e}" connection timed out after ${MA()}ms`,`MCP connection timeout`))},MA());c.then(()=>{clearTimeout(a)},e=>{clearTimeout(a)})});try{await Promise.race([c,l]),o&&(Ua(e,`Server stderr: ${o}`),o=``);let n=Date.now()-r;Va(e,`Successfully connected (transport: ${t.type||`stdio`}) in ${n}ms`)}catch(n){let a=Date.now()-r;if(t.type===`sse`&&n instanceof Error){if(Va(e,`SSE Connection failed after ${a}ms: ${U({url:t.url,error:n.message,errorType:n.constructor.name,stack:n.stack})}`),Ua(e,n),n instanceof VD)return AA(e,t,`sse`)}else if(t.type===`http`&&n instanceof Error){let r=n;if(Va(e,`HTTP Connection failed after ${a}ms: ${n.message} (code: ${r.code||`none`}, errno: ${r.errno||`none`})`),Ua(e,n),n instanceof VD)return AA(e,t,`http`)}else(t.type===`sse-ide`||t.type===`ws-ide`)&&Y(`tengu_mcp_ide_server_connection_failed`,{connectionDurationMs:a});throw i.close().catch(()=>{}),o&&Ua(e,`Server stderr: ${o}`),n}let u=s.getServerCapabilities(),d=s.getServerVersion(),f=s.getInstructions(),p=f;if(f&&f.length>QA&&(p=`${f.slice(0,QA)}… [truncated]`,Va(e,`Server instructions truncated from ${f.length} to ${QA} chars`)),Va(e,`Connection established with capabilities: ${U({hasTools:!!u?.tools,hasPrompts:!!u?.prompts,hasResources:!!u?.resources,hasResourceSubscribe:!!u?.resources?.subscribe,serverVersion:d||`unknown`})}`),G(`[MCP] Server "${e}" connected with subscribe=${!!u?.resources?.subscribe}`),s.setRequestHandler(AT,async t=>(Va(e,`Elicitation request received during initialization: ${U(t)}`),{action:`cancel`})),t.type===`sse-ide`||t.type===`ws-ide`){Y(`tengu_mcp_ide_server_connection_succeeded`,{connectionDurationMs:Date.now()-r,serverVersion:d});try{ADe(s)}catch(t){Ua(e,`Failed to send ide_connected notification: ${t}`)}}let m=Date.now(),h=!1,g=s.onerror,_=s.onclose,v=0,y=!1,b=t=>{y||(y=!0,Va(e,`Closing transport (${t})`),s.close().catch(t=>{Va(e,`Error during close: ${W(t)}`)}))},x=e=>e.includes(`ECONNRESET`)||e.includes(`ETIMEDOUT`)||e.includes(`EPIPE`)||e.includes(`EHOSTUNREACH`)||e.includes(`ECONNREFUSED`)||e.includes(`Body Timeout Error`)||e.includes(`terminated`)||e.includes(`SSE stream disconnected`)||e.includes(`Failed to reconnect SSE stream`);s.onerror=n=>{let r=Date.now()-m;h=!0;let i=t.type||`stdio`;if(Va(e,`${i.toUpperCase()} connection dropped after ${Math.floor(r/1e3)}s uptime`),n.message&&(n.message.includes(`ECONNRESET`)?Va(e,`Connection reset - server may have crashed or restarted`):n.message.includes(`ETIMEDOUT`)?Va(e,`Connection timeout - network issue or server unresponsive`):n.message.includes(`ECONNREFUSED`)?Va(e,`Connection refused - server may be down`):n.message.includes(`EPIPE`)?Va(e,`Broken pipe - server closed connection unexpectedly`):n.message.includes(`EHOSTUNREACH`)?Va(e,`Host unreachable - network connectivity issue`):n.message.includes(`ESRCH`)?Va(e,`Process not found - stdio server process terminated`):n.message.includes(`spawn`)?Va(e,`Failed to spawn process - check command and permissions`):Va(e,`Connection error: ${n.message}`)),i===`http`&&OA(n)){Va(e,`MCP session expired (server returned 404 with session-not-found), triggering reconnection`),b(`session expired`),g&&g(n);return}if(i===`sse`||i===`http`){if(n.message.includes(`Maximum reconnection attempts`)){b(`SSE reconnection exhausted`),g&&g(n);return}x(n.message)?(v++,Va(e,`Terminal connection error ${v}/3`),v>=3&&(v=0,b(`max consecutive terminal errors`))):v=0}g&&g(n)},s.onclose=()=>{let n=Date.now()-m;Va(e,`${(t.type??`unknown`).toUpperCase()} connection closed after ${Math.floor(n/1e3)}s (${h?`with errors`:`cleanly`})`);let r=IA(e,t);aj.cache.delete(e),oj.cache.delete(e),sj.cache.delete(e),rj.cache.delete(r),Va(e,`Cleared connection cache for reconnection`),_&&_()};let S=async()=>{if(a&&(t.type===`stdio`||!t.type)&&i.stderr?.off(`data`,a),t.type===`stdio`)try{let t=i.pid;if(t){Va(e,`Sending SIGINT to MCP server process`);try{process.kill(t,`SIGINT`)}catch(t){Va(e,`Error sending SIGINT: ${t}`);return}await new Promise(async n=>{let r=!1,i=setInterval(()=>{try{process.kill(t,0)}catch{r||(r=!0,clearInterval(i),clearTimeout(a),Va(e,`MCP server process exited cleanly`),n())}},50),a=setTimeout(()=>{r||(r=!0,clearInterval(i),Va(e,`Cleanup timeout reached, stopping process monitoring`),n())},600);try{if(await cc(100),!r){try{process.kill(t,0),Va(e,`SIGINT failed, sending SIGTERM to MCP server process`);try{process.kill(t,`SIGTERM`)}catch(t){Va(e,`Error sending SIGTERM: ${t}`),r=!0,clearInterval(i),clearTimeout(a),n();return}}catch{r=!0,clearInterval(i),clearTimeout(a),n();return}if(await cc(400),!r)try{process.kill(t,0),Va(e,`SIGTERM failed, sending SIGKILL to MCP server process`);try{process.kill(t,`SIGKILL`)}catch(t){Va(e,`Error sending SIGKILL: ${t}`)}}catch{r=!0,clearInterval(i),clearTimeout(a),n()}}r||(r=!0,clearInterval(i),clearTimeout(a),n())}catch{r||(r=!0,clearInterval(i),clearTimeout(a),n())}})}}catch(t){Va(e,`Error terminating process: ${t}`)}try{await s.close()}catch(t){Va(e,`Error closing client: ${t}`)}},C=ar(S),w=async()=>{C?.(),await S()};return Y(`tengu_mcp_server_connection_succeeded`,{connectionDurationMs:Date.now()-r,transportType:t.type??`stdio`,totalServers:n?.totalServers,stdioCount:n?.stdioCount,sseCount:n?.sseCount,httpCount:n?.httpCount,sseIdeCount:n?.sseIdeCount,wsIdeCount:n?.wsIdeCount,...kA(t)}),{name:e,client:s,type:`connected`,capabilities:u??{},serverInfo:d,instructions:p,config:t,cleanup:w}}catch(i){let a=Date.now()-r;return Y(`tengu_mcp_server_connection_failed`,{connectionDurationMs:a,totalServers:n?.totalServers||1,stdioCount:n?.stdioCount||+(t.type===`stdio`),sseCount:n?.sseCount||+(t.type===`sse`),httpCount:n?.httpCount||+(t.type===`http`),sseIdeCount:n?.sseIdeCount||+(t.type===`sse-ide`),wsIdeCount:n?.wsIdeCount||+(t.type===`ws-ide`),transportType:t.type??`stdio`,...kA(t)}),Va(e,`Connection failed after ${a}ms: ${W(i)}`),Ua(e,`Connection failed: ${W(i)}`),{name:e,type:`failed`,config:t,error:W(i)}}},IA),ij=20,aj=Ct(async e=>{if(e.type!==`connected`)return[];try{if(!e.capabilities?.tools)return[];let t=Joe((await e.client.request({method:`tools/list`},lT)).tools),n=e.config.type===`sdk`&&h(process.env.CLAUDE_AGENT_SDK_MCP_NO_PREFIX);return t.map(t=>{let r=Kne(e.name,t.name);return{...OO,name:n?t.name:r,mcpInfo:{serverName:e.name,toolName:t.name},isMcp:!0,searchHint:typeof t._meta?.[`anthropic/searchHint`]==`string`&&t._meta[`anthropic/searchHint`].replace(/\s+/g,` `).trim()||void 0,alwaysLoad:t._meta?.[`anthropic/alwaysLoad`]===!0,async description(){return t.description??``},async prompt(){let e=t.description??``;return e.length>QA?`${e.slice(0,QA)}… [truncated]`:e},isConcurrencySafe(){return t.annotations?.readOnlyHint??!1},isReadOnly(){return t.annotations?.readOnlyHint??!1},toAutoClassifierInput(e){return sDe(e,t.name)},isDestructive(){return t.annotations?.destructiveHint??!1},isOpenWorld(){return t.annotations?.openWorldHint??!1},isSearchOrReadCommand(){return ZEe(e.name,t.name)},inputJSONSchema:t.inputSchema,async checkPermissions(){return{behavior:`passthrough`,message:`MCPTool requires permission.`,suggestions:[{type:`addRules`,rules:[{toolName:r,ruleContent:void 0}],behavior:`allow`,destination:`localSettings`}]}},async call(n,r,i,a,o){let s=mDe(a),c=s?{"claudecode/toolUseId":s}:{};o&&s&&o({toolUseID:s,data:{type:`mcp_progress`,status:`started`,serverName:e.name,toolName:t.name}});let l=Date.now();for(let i=0;;i++)try{let i=await pDe({client:await RA(e),clientConnection:e,tool:t.name,args:n,meta:c,signal:r.abortController.signal,setAppState:r.setAppState,onProgress:o&&s?e=>{o({toolUseID:s,data:e})}:void 0,handleElicitation:r.handleElicitation});return o&&s&&o({toolUseID:s,data:{type:`mcp_progress`,status:`completed`,serverName:e.name,toolName:t.name,elapsedTimeMs:Date.now()-l}}),{data:i.content,...(i._meta||i.structuredContent)&&{mcpMeta:{...i._meta&&{_meta:i._meta},...i.structuredContent&&{structuredContent:i.structuredContent}}}}}catch(n){if(n instanceof YA&&i<1){Va(e.name,`Retrying tool '${t.name}' after session recovery`);continue}if(o&&s&&o({toolUseID:s,data:{type:`mcp_progress`,status:`failed`,serverName:e.name,toolName:t.name,elapsedTimeMs:Date.now()-l}}),n instanceof Error&&!(n instanceof cr)){let e=n.constructor.name;if(e===`Error`)throw new cr(n.message,n.message.slice(0,200));if(e===`McpError`&&`code`in n&&typeof n.code==`number`)throw new cr(n.message,`McpError ${n.code}`)}throw n}},userFacingName(){let n=t.annotations?.title||t.name;return`${e.name} - ${n} (MCP)`}}}).filter(aDe)}catch(t){return Ua(e.name,`Failed to fetch tools: ${W(t)}`),[]}},e=>e.name,ij),oj=Ct(async e=>{if(e.type!==`connected`)return[];try{if(!e.capabilities?.resources)return[];let t=await e.client.request({method:`resources/list`},Yw);return t.resources?t.resources.map(t=>({...t,server:e.name})):[]}catch(t){return Ua(e.name,`Failed to fetch resources: ${W(t)}`),[]}},e=>e.name,ij),sj=Ct(async e=>{if(e.type!==`connected`)return[];try{if(!e.capabilities?.prompts)return[];let t=await e.client.request({method:`prompts/list`},eT);return t.prompts?Joe(t.prompts).map(t=>{let n=Object.values(t.arguments??{}).map(e=>e.name);return{type:`prompt`,name:`mcp__${Mi(e.name)}__${t.name}`,description:t.description??``,hasUserSpecifiedDescription:!!t.description,contentLength:0,isEnabled:()=>!0,isHidden:!1,isMcp:!0,progressMessage:`running`,userFacingName(){return`${e.name}:${t.name} (MCP)`},argNames:n,source:`mcp`,async getPromptForCommand(r){let i=r.split(` `);try{let r=await RA(e),a=await r.client.getPrompt({name:t.name,arguments:hpe(n,i)});return(await Promise.all(a.messages.map(e=>UA(e.content,r.name)))).flat()}catch(n){throw Ua(e.name,`Error running command '${t.name}': ${W(n)}`),n}}}}):[]}catch(t){return Ua(e.name,`Failed to fetch commands: ${W(t)}`),[]}},e=>e.name,ij)}));function gDe(e){let t=_c(),n=[],r=uj[e.toLowerCase()];if(!r)return n;let i=process.env.APPDATA||X(t,`AppData`,`Roaming`),a=process.env.LOCALAPPDATA||X(t,`AppData`,`Local`);switch(kse()){case`darwin`:n.push(X(t,`Library`,`Application Support`,`JetBrains`),X(t,`Library`,`Application Support`)),e.toLowerCase()===`androidstudio`&&n.push(X(t,`Library`,`Application Support`,`Google`));break;case`win32`:n.push(X(i,`JetBrains`),X(a,`JetBrains`),X(i)),e.toLowerCase()===`androidstudio`&&n.push(X(a,`Google`));break;case`linux`:n.push(X(t,`.config`,`JetBrains`),X(t,`.local`,`share`,`JetBrains`));for(let e of r)n.push(X(t,`.${e}`));e.toLowerCase()===`androidstudio`&&n.push(X(t,`.config`,`Google`));break;default:break}return n}async function _De(e){let t=[],n=q(),r=gDe(e),i=uj[e.toLowerCase()];if(!i)return t;let a=i.map(e=>RegExp(`^${e}`));for(let e of r)try{let r=await n.readdir(e);for(let i of a)for(let a of r){if(!i.test(a.name)||!a.isDirectory()&&!a.isSymbolicLink())continue;let r=X(e,a.name);if(kse()===`linux`){t.push(r);continue}let o=X(r,`plugins`);try{await n.stat(o),t.push(o)}catch{}}}catch{}return t.filter((e,n)=>t.indexOf(e)===n)}async function vDe(e){let t=await _De(e);for(let e of t){let t=X(e,lj);try{return await q().stat(t),!0}catch{}}return!1}async function yDe(e,t=!1){if(!t){let t=fj.get(e);if(t)return t}let n=vDe(e).then(t=>(dj.set(e,t),t));return fj.set(e,n),n}async function bDe(e,t=!1){return t&&(dj.delete(e),fj.delete(e)),yDe(e,t)}var lj,uj,dj,fj,xDe=n((()=>{or(),lj=`claude-code-jetbrains-plugin`,uj={pycharm:[`PyCharm`],intellij:[`IntelliJIdea`,`IdeaIC`],webstorm:[`WebStorm`],phpstorm:[`PhpStorm`],rubymine:[`RubyMine`],clion:[`CLion`],goland:[`GoLand`],rider:[`Rider`],datagrip:[`DataGrip`],appcode:[`AppCode`],dataspell:[`DataSpell`],aqua:[`Aqua`],gateway:[`Gateway`],fleet:[`Fleet`],androidstudio:[`AndroidStudio`]},dj=new Map,fj=new Map}));function SDe(e,t){let n=e.match(/^\\\\wsl(?:\.localhost|\$)\\([^\\]+)(.*)$/);return!n||n[1]===t}var pj,mj=n((()=>{b(),pj=class{constructor(e){x(this,`wslDistroName`,void 0),this.wslDistroName=e}toLocalPath(e){if(!e)return e;if(this.wslDistroName){let t=e.match(/^\\\\wsl(?:\.localhost|\$)\\([^\\]+)(.*)$/);if(t&&t[1]!==this.wslDistroName)return e}try{return ul(`wslpath`,[`-u`,e],{encoding:`utf8`,stdio:[`pipe`,`pipe`,`ignore`]}).trim()}catch{return e.replace(/\\/g,`/`).replace(/^([A-Z]):/i,(e,t)=>`/mnt/${t.toLowerCase()}`)}}toIDEPath(e){if(!e)return e;try{return ul(`wslpath`,[`-w`,e],{encoding:`utf8`,stdio:[`pipe`,`pipe`,`ignore`]}).trim()}catch{return e}}}}));function CDe({onDone:e,installationStatus:t}){TDe(),Ke({"confirm:yes":e,"confirm:no":e},{context:`Confirmation`});let n=t?.ideType??bj(),r=yj(n),i=Mj(n),a=t?.installedVersion,o=r?`plugin`:`extension`,s=$r.platform===`darwin`?`Cmd+Option+K`:`Ctrl+Alt+K`;return(0,hj.jsxs)(hj.Fragment,{children:[(0,hj.jsx)(kee,{title:(0,hj.jsxs)(hj.Fragment,{children:[(0,hj.jsx)(F,{color:`claude`,children:`✻ `}),(0,hj.jsxs)(F,{children:[`Welcome to Work Mate for `,i]})]}),subtitle:a?`installed ${o} v${a}`:void 0,color:`ide`,onCancel:e,hideInputGuide:!0,children:(0,hj.jsxs)(P,{flexDirection:`column`,gap:1,children:[(0,hj.jsxs)(F,{children:[`• Work Mate has context of `,(0,hj.jsx)(F,{color:`suggestion`,children:`⧉ open files`}),` and`,` `,(0,hj.jsx)(F,{color:`suggestion`,children:`⧉ selected lines`})]}),(0,hj.jsxs)(F,{children:[`• Review Work Mate's changes `,(0,hj.jsx)(F,{color:`diffAddedWord`,children:`+11`}),` `,(0,hj.jsx)(F,{color:`diffRemovedWord`,children:`-22`}),` in the comfort of your IDE`]}),(0,hj.jsxs)(F,{children:[`• Cmd+Esc`,(0,hj.jsx)(F,{dimColor:!0,children:` for Quick Launch`})]}),(0,hj.jsxs)(F,{children:[`• `,s,(0,hj.jsx)(F,{dimColor:!0,children:` to reference files or lines in your input`})]})]})}),(0,hj.jsx)(P,{paddingX:1,children:(0,hj.jsx)(F,{dimColor:!0,italic:!0,children:`Press Enter to continue`})})]})}function wDe(){let e=ha(),t=Ne.terminal||`unknown`;return e.hasIdeOnboardingBeenShown?.[t]===!0}function TDe(){if(wDe())return;let e=Ne.terminal||`unknown`;aa(t=>({...t,hasIdeOnboardingBeenShown:{...t.hasIdeOnboardingBeenShown,[e]:!0}}))}var hj,gj=n((()=>{Ce(),ct(),US(),ma(),Ii(),Wj(),hj=ut()}));function _j(e){try{return process.kill(e,0),!0}catch{return!1}}function EDe(){let e=null;return()=>(e||(e=qoe(process.ppid,10).then(e=>new Set(e))),e)}function vj(e){if(!e)return!1;let t=Fj[e];return t&&t.ideKind===`vscode`}function yj(e){if(!e)return!1;let t=Fj[e];return t&&t.ideKind===`jetbrains`}function bj(){return Rj()?$r.terminal:null}async function xj(){try{let e=await DDe();return(await Promise.all(e.map(async e=>{try{let t=(await q().readdir(e)).filter(e=>e.name.endsWith(`.lock`));return(await Promise.all(t.map(async t=>{let n=X(e,t.name);try{return{path:n,mtime:(await q().stat(n)).mtime}}catch{return null}}))).filter(e=>e!==null)}catch(e){return hr(e)||J(e),[]}}))).flat().sort((e,t)=>t.mtime.getTime()-e.mtime.getTime()).map(e=>e.path)}catch(e){return J(e),[]}}async function Sj(e){try{let t=await q().readFile(e,{encoding:`utf-8`}),n=[],r,i,a=!1,o=!1,s;try{let e=$n(t);e.workspaceFolders&&(n=e.workspaceFolders),r=e.pid,i=e.ideName,a=e.transport===`ws`,o=e.runningInWindows===!0,s=e.authToken}catch{n=t.split(`
|
|
670
|
+
`).map(e=>e.trim())}let c=e.split(kc).pop();if(!c)return null;let l=c.replace(`.lock`,``);return{workspaceFolders:n,port:parseInt(l,10),pid:r,ideName:i,useWebSocket:a,runningInWindows:o,authToken:s}}catch(e){return J(e),null}}async function Cj(e,t,n=500){try{return new Promise(r=>{let i=Mce({host:e,port:t,timeout:n});i.on(`connect`,()=>{i.destroy(),r(!0)}),i.on(`error`,()=>{r(!1)}),i.on(`timeout`,()=>{i.destroy(),r(!1)})})}catch{return!1}}async function DDe(){let e=[X(m(),`ide`)];if(io()!==`wsl`)return e;let t=await zj();if(t){let n=new pj(process.env.WSL_DISTRO_NAME).toLocalPath(t);e.push(Oc(n,`.workmate`,`ide`))}try{let t=`/mnt/c/Users`,n=await q().readdir(t);for(let r of n)!r.isDirectory()&&!r.isSymbolicLink()||r.name===`Public`||r.name===`Default`||r.name===`Default User`||r.name===`All Users`||e.push(X(t,r.name,`.workmate`,`ide`))}catch(e){hr(e)?G(`WSL IDE lockfile path detection failed (${e.code}): ${W(e)}`):J(e)}return e}async function ODe(){try{let e=await xj();for(let t of e){let e=await Sj(t);if(!e){try{await q().unlink(t)}catch(e){J(e)}continue}let n=await Uj(e.runningInWindows,e.port),r=!1;if(e.pid?_j(e.pid)||io()===`wsl`&&await Cj(n,e.port)||(r=!0):await Cj(n,e.port)||(r=!0),r)try{await q().unlink(t)}catch(e){J(e)}}}catch(e){J(e)}}async function kDe(e){try{let t=await MDe(e);return Y(`tengu_ext_installed`,{}),ha().diffTool||aa(e=>({...e,diffTool:`auto`})),{installed:!0,error:null,installedVersion:t,ideType:e}}catch(t){Y(`tengu_ext_install_error`,{});let n=t instanceof Error?t.message:String(t);return J(t),{installed:!1,error:n,installedVersion:null,ideType:e}}}async function wj(){Bj&&Bj.abort(),Bj=BO();let e=Bj.signal;await ODe();let t=Date.now();for(;Date.now()-t<3e4&&!e.aborted;){if(tte()){await cc(1e3,e);continue}let t=await Tj(!1);if(e.aborted)return null;if(t.length===1)return t[0];await cc(1e3,e)}return null}async function Tj(e){let t=[];try{let n=process.env.CLAUDE_CODE_SSE_PORT,r=n?parseInt(n,10):null,i=Yt().normalize(`NFC`),a=await xj(),o=await Promise.all(a.map(Sj)),s=EDe(),c=io()!==`wsl`&&Rj();for(let n of o){if(!n)continue;let a=!1;if(a=h(process.env.CLAUDE_CODE_IDE_SKIP_VALID_CHECK)?!0:n.port===r||n.workspaceFolders.some(e=>{if(!e)return!1;let t=e;if(io()===`wsl`&&n.runningInWindows&&process.env.WSL_DISTRO_NAME){if(!SDe(e,process.env.WSL_DISTRO_NAME))return!1;let n=Oc(t).normalize(`NFC`);if(i===n||i.startsWith(n+kc))return!0;t=new pj(process.env.WSL_DISTRO_NAME).toLocalPath(e)}let r=Oc(t).normalize(`NFC`);if(io()===`windows`){let e=i.replace(/^[a-zA-Z]:/,e=>e.toUpperCase()),t=r.replace(/^[a-zA-Z]:/,e=>e.toUpperCase());return e===t||e.startsWith(t+kc)}return i===r||i.startsWith(r+kc)}),!a&&!e||c&&!(r!==null&&n.port===r)&&(!n.pid||!_j(n.pid)||process.ppid!==n.pid&&!(await s()).has(n.pid)))continue;let o=n.ideName??(Rj()?Mj(Ne.terminal):`IDE`),l=await Uj(n.runningInWindows,n.port),u;u=n.useWebSocket?`ws://${l}:${n.port}`:`http://${l}:${n.port}/sse`,t.push({url:u,name:o,workspaceFolders:n.workspaceFolders,port:n.port,isValid:a,authToken:n.authToken,ideRunningInWindows:n.runningInWindows})}if(!e&&r){let e=t.filter(e=>e.isValid&&e.port===r);if(e.length===1)return e}}catch(e){J(e)}return t}async function ADe(e){await e.notification({method:`ide_connected`,params:{pid:process.pid}})}function jDe(e){return e.some(e=>e.type===`connected`&&e.name===`ide`)}async function Ej(e){if(vj(e)){let t=await kj(e);if(t)try{if((await ya(t,[`--list-extensions`],{env:Dj()})).stdout?.includes(Vj))return!0}catch{}}else if(yj(e))return await bDe(e);return!1}async function MDe(e){if(vj(e)){let t=await kj(e);if(t){let e=await NDe(t);if(!e||Wde(e,Oj())){await cc(500);let n=await ya(t,[`--force`,`--install-extension`,`anthropic.claude-code`],{env:Dj()});if(n.code!==0)throw Error(`${n.code}: ${n.error} ${n.stderr}`);e=Oj()}return e}}return null}function Dj(){if(io()===`linux`)return{...process.env,DISPLAY:``}}function Oj(){return`0.0.24`}async function NDe(e){let{stdout:t}=await Ca(e,[`--list-extensions`,`--show-versions`],{env:Dj()}),n=t?.split(`
|
|
671
671
|
`)||[];for(let e of n){let[t,n]=e.split(`@`);if(t===`anthropic.claude-code`&&n)return n}return null}function PDe(){try{if(io()!==`macos`)return null;let e=process.ppid;for(let t=0;t<10&&!(!e||e===0||e===1);t++){let t=xa(`ps -o command= -p ${e}`)?.trim();if(t)for(let[e,n]of Object.entries({"Visual Studio Code.app":`code`,"Cursor.app":`cursor`,"Windsurf.app":`windsurf`,"Visual Studio Code - Insiders.app":`code`,"VSCodium.app":`codium`})){let r=t.indexOf(e+`/Contents/MacOS/Electron`);if(r!==-1){let i=r+e.length;return t.substring(0,i)+`/Contents/Resources/app/bin/`+n}}let n=xa(`ps -o ppid= -p ${e}`)?.trim();if(!n)break;e=parseInt(n.trim(),10)}return null}catch{return null}}async function kj(e){let t=PDe();if(t)try{return await q().stat(t),t}catch{}let n=io()===`windows`?`.cmd`:``;switch(e){case`vscode`:return`code${n}`;case`cursor`:return`cursor${n}`;case`windsurf`:return`windsurf${n}`;default:break}return null}function Aj(e){return jj(e.find(e=>e.type===`connected`&&e.name===`ide`))}function jj(e){let t=e?.config;return t?.type===`sse-ide`||t?.type===`ws-ide`?t.ideName:Rj()?Mj(Ne.terminal):null}function Mj(e){if(!e)return`IDE`;let t=Fj[e];if(t)return t.displayName;let n=Hj[e.toLowerCase().trim()];if(n)return n;let r=e.split(` `)[0],i=r?bc(r).toLowerCase():null;return i?Hj[i]||cg(i):cg(e)}function Nj(e){if(!e)return;let t=e.find(e=>e.type===`connected`&&e.name===`ide`);return t?.type===`connected`?t:void 0}async function FDe(e){try{await zA(`closeAllDiffTabs`,{},e)}catch{}}async function IDe(e,t,n,r){wj().then(e);let i=ha().autoInstallIdeExtension??!0;if(!h(process.env.CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL)&&i){let i=t??bj();i&&(vj(i)?Ej(i).then(async t=>{kDe(i).catch(e=>({installed:!1,error:e.message||`Installation failed`,installedVersion:null,ideType:i})).then(i=>{r(i),i?.installed&&wj().then(e),!t&&i?.installed===!0&&!Pj().hasIdeOnboardingDialogBeenShown()&&n()})}):yj(i)&&Ej(i).then(async e=>{e&&!Pj().hasIdeOnboardingDialogBeenShown()&&n()}))}}var Pj,Fj,Ij,Lj,Rj,zj,Bj,Vj,Hj,Uj,Wj=n((()=>{Sa(),lg(),d(),oo(),Jt(),cj(),ma(),Ii(),g(),va(),or(),sc(),xDe(),Ga(),ao(),Ap(),UO(),K(),Ce(),qn(),mj(),lc(),mr(),Pj=()=>gj(),Fj={cursor:{ideKind:`vscode`,displayName:`Cursor`,processKeywordsMac:[`Cursor Helper`,`Cursor.app`],processKeywordsWindows:[`cursor.exe`],processKeywordsLinux:[`cursor`]},windsurf:{ideKind:`vscode`,displayName:`Windsurf`,processKeywordsMac:[`Windsurf Helper`,`Windsurf.app`],processKeywordsWindows:[`windsurf.exe`],processKeywordsLinux:[`windsurf`]},vscode:{ideKind:`vscode`,displayName:`VS Code`,processKeywordsMac:[`Visual Studio Code`,`Code Helper`],processKeywordsWindows:[`code.exe`],processKeywordsLinux:[`code`]},intellij:{ideKind:`jetbrains`,displayName:`IntelliJ IDEA`,processKeywordsMac:[`IntelliJ IDEA`],processKeywordsWindows:[`idea64.exe`],processKeywordsLinux:[`idea`,`intellij`]},pycharm:{ideKind:`jetbrains`,displayName:`PyCharm`,processKeywordsMac:[`PyCharm`],processKeywordsWindows:[`pycharm64.exe`],processKeywordsLinux:[`pycharm`]},webstorm:{ideKind:`jetbrains`,displayName:`WebStorm`,processKeywordsMac:[`WebStorm`],processKeywordsWindows:[`webstorm64.exe`],processKeywordsLinux:[`webstorm`]},phpstorm:{ideKind:`jetbrains`,displayName:`PhpStorm`,processKeywordsMac:[`PhpStorm`],processKeywordsWindows:[`phpstorm64.exe`],processKeywordsLinux:[`phpstorm`]},rubymine:{ideKind:`jetbrains`,displayName:`RubyMine`,processKeywordsMac:[`RubyMine`],processKeywordsWindows:[`rubymine64.exe`],processKeywordsLinux:[`rubymine`]},clion:{ideKind:`jetbrains`,displayName:`CLion`,processKeywordsMac:[`CLion`],processKeywordsWindows:[`clion64.exe`],processKeywordsLinux:[`clion`]},goland:{ideKind:`jetbrains`,displayName:`GoLand`,processKeywordsMac:[`GoLand`],processKeywordsWindows:[`goland64.exe`],processKeywordsLinux:[`goland`]},rider:{ideKind:`jetbrains`,displayName:`Rider`,processKeywordsMac:[`Rider`],processKeywordsWindows:[`rider64.exe`],processKeywordsLinux:[`rider`]},datagrip:{ideKind:`jetbrains`,displayName:`DataGrip`,processKeywordsMac:[`DataGrip`],processKeywordsWindows:[`datagrip64.exe`],processKeywordsLinux:[`datagrip`]},appcode:{ideKind:`jetbrains`,displayName:`AppCode`,processKeywordsMac:[`AppCode`],processKeywordsWindows:[`appcode.exe`],processKeywordsLinux:[`appcode`]},dataspell:{ideKind:`jetbrains`,displayName:`DataSpell`,processKeywordsMac:[`DataSpell`],processKeywordsWindows:[`dataspell64.exe`],processKeywordsLinux:[`dataspell`]},aqua:{ideKind:`jetbrains`,displayName:`Aqua`,processKeywordsMac:[],processKeywordsWindows:[`aqua64.exe`],processKeywordsLinux:[]},gateway:{ideKind:`jetbrains`,displayName:`Gateway`,processKeywordsMac:[],processKeywordsWindows:[`gateway64.exe`],processKeywordsLinux:[]},fleet:{ideKind:`jetbrains`,displayName:`Fleet`,processKeywordsMac:[],processKeywordsWindows:[`fleet.exe`],processKeywordsLinux:[]},androidstudio:{ideKind:`jetbrains`,displayName:`Android Studio`,processKeywordsMac:[`Android Studio`],processKeywordsWindows:[`studio64.exe`],processKeywordsLinux:[`android-studio`]}},Ij=u(()=>vj($r.terminal)),Lj=u(()=>yj(Ne.terminal)),Rj=u(()=>Ij()||Lj()||!!process.env.FORCE_CODE_TERMINAL),zj=u(async()=>{if(process.env.USERPROFILE)return process.env.USERPROFILE;let{stdout:e,code:t}=await Ca(`powershell.exe`,[`-NoProfile`,`-NonInteractive`,`-Command`,`$env:USERPROFILE`]);if(t===0&&e.trim())return e.trim();G(`Unable to get Windows USERPROFILE via PowerShell - IDE detection may be incomplete`)}),Bj=null,Vj=`anthropic.claude-code`,Hj={code:`VS Code`,cursor:`Cursor`,windsurf:`Windsurf`,antigravity:`Antigravity`,vi:`Vim`,vim:`Vim`,nano:`nano`,notepad:`Notepad`,"start /wait notepad":`Notepad`,emacs:`Emacs`,subl:`Sublime Text`,atom:`Atom`},Uj=u(async(e,t)=>{if(process.env.CLAUDE_CODE_IDE_HOST_OVERRIDE)return process.env.CLAUDE_CODE_IDE_HOST_OVERRIDE;if(io()!==`wsl`||!e)return`127.0.0.1`;try{let e=await _a(`ip route show | grep -i default`,{shell:!0,reject:!1});if(e.exitCode===0&&e.stdout){let n=e.stdout.match(/default via (\d+\.\d+\.\d+\.\d+)/);if(n){let e=n[1];if(await Cj(e,t))return e}}}catch{}return`127.0.0.1`},(e,t)=>`${e}:${t}`)}));function Gj(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}function Kj(e){tM=e}function qj(e,t=``){let n=typeof e==`string`?e:e.source,r={replace:(e,t)=>{let i=typeof t==`string`?t:t.source;return i=i.replace(iM.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}function Jj(e,t){if(t){if(iM.escapeTest.test(e))return e.replace(iM.escapeReplace,dN)}else if(iM.escapeTestNoEncode.test(e))return e.replace(iM.escapeReplaceNoEncode,dN);return e}function Yj(e){try{e=encodeURI(e).replace(iM.percentDecode,`%`)}catch{return null}return e}function Xj(e,t){let n=e.replace(iM.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split(iM.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length<t;)n.push(``);for(;r<n.length;r++)n[r]=n[r].trim().replace(iM.slashPipe,`|`);return n}function Zj(e,t,n){let r=e.length;if(r===0)return``;let i=0;for(;i<r;){let a=e.charAt(r-i-1);if(a===t&&!n)i++;else if(a!==t&&n)i++;else break}return e.slice(0,r-i)}function LDe(e,t){if(e.indexOf(t[1])===-1)return-1;let n=0;for(let r=0;r<e.length;r++)if(e[r]===`\\`)r++;else if(e[r]===t[0])n++;else if(e[r]===t[1]&&(n--,n<0))return r;return n>0?-2:-1}function RDe(e,t=0){let n=t,r=``;for(let t of e)if(t===` `){let e=4-n%4;r+=` `.repeat(e),n+=e}else r+=t,n++;return r}function Qj(e,t,n,r,i){let a=t.href,o=t.title||null,s=e[1].replace(i.other.outputLinkReplace,`$1`);r.state.inLink=!0;let c={type:e[0].charAt(0)===`!`?`image`:`link`,raw:n,href:a,title:o,text:s,tokens:r.inlineTokens(s)};return r.state.inLink=!1,c}function zDe(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
|
|
672
672
|
`).map(e=>{let t=e.match(n.other.beginningSpace);if(t===null)return e;let[r]=t;return r.length>=i.length?e.slice(i.length):e}).join(`
|
|
673
673
|
`)}function $j(e,t){return yN.parse(e,t)}var eM,tM,nM,rM,iM,aM,oM,sM,cM,lM,uM,dM,fM,pM,mM,hM,gM,_M,vM,yM,bM,xM,SM,CM,wM,TM,EM,DM,OM,kM,AM,jM,MM,NM,PM,FM,IM,LM,RM,zM,BM,VM,HM,UM,WM,GM,KM,qM,JM,YM,XM,ZM,QM,$M,eN,tN,nN,rN,iN,aN,oN,sN,cN,lN,uN,dN,fN,pN,mN,hN,gN,_N,vN,yN,bN=n((()=>{b(),tM=Gj(),nM={exec:()=>null},rM=(()=>{try{return!0}catch{return!1}})(),iM={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,`i`),blockquoteBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}>`)},aM=/^(?:[ \t]*(?:\n|$))+/,oM=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,sM=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,cM=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,lM=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,uM=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,dM=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,fM=qj(dM).replace(/bull/g,uM).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,``).getRegex(),pM=qj(dM).replace(/bull/g,uM).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),mM=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,hM=/^[^\n]+/,gM=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,_M=qj(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,gM).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),vM=qj(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,uM).getRegex(),yM=`address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul`,bM=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,xM=qj(`^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))`,`i`).replace(`comment`,bM).replace(`tag`,yM).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),SM=qj(mM).replace(`hr`,cM).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,yM).getRegex(),CM={blockquote:qj(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,SM).getRegex(),code:oM,def:_M,fences:sM,heading:lM,hr:cM,html:xM,lheading:fM,list:vM,newline:aM,paragraph:SM,table:nM,text:hM},wM=qj(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,cM).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`blockquote`,` {0,3}>`).replace(`code`,`(?: {4}| {0,3} )[^\\n]`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,yM).getRegex(),TM={...CM,lheading:pM,table:wM,paragraph:qj(mM).replace(`hr`,cM).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,wM).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,yM).getRegex()},EM={...CM,html:qj(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,bM).replace(/tag/g,`(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b`).getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:nM,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:qj(mM).replace(`hr`,cM).replace(`heading`,` *#{1,6} *[^
|
|
@@ -776,7 +776,7 @@ Examples:
|
|
|
776
776
|
- "重构这个模块的代码" -> refactor code modularize
|
|
777
777
|
- "帮我写个 Go 单元测试" -> write test golang unit
|
|
778
778
|
|
|
779
|
-
Output ONLY keywords. Nothing else.`,uF=6e3,dF=500,fF=120,pF=200,mF=150,hF=new Map})),gF=i({collectSkillDiscoveryPrefetch:()=>SF,extractQueryFromMessages:()=>vF,getTurnZeroSkillDiscovery:()=>WOe,startSkillDiscoveryPrefetch:()=>xF});function _F(e,t){if(e.add(t),e.size>CF){let t=e.size-wF,n=e.values();for(let r=0;r<t;r++){let t=n.next();if(t.done)break;e.delete(t.value)}}}function vF(e,t){let n=[];e&&n.push(e);for(let e=t.length-1;e>=0;e--){let r=t[e];if(r.type!==`user`)continue;let i=r.content;if(typeof i==`string`){n.push(i.slice(0,500));break}if(Array.isArray(i)){let e=!1;for(let t of i){let r=t;if(r.type&&r.type!==`text`)continue;let i=r.text;if(typeof i==`string`&&i.trim()){n.push(i.slice(0,500)),e=!0;break}}if(e)break}}return n.join(` `)}function yF(e,t,n){return{type:`skill_discovery`,skills:e,signal:t,source:`native`,gap:n}}async function bF(e,t){let n=0,r=[];for(let i of e){let e={name:i.name,description:i.description,score:i.score};if(n>=OF||i.score<DF){r.push(e);continue}let a=await VOe(i);if(!a){r.push(e);continue}n++,await HOe(i.name,a.path,a.content,t),r.push({...e,autoLoaded:!0,content:a.content,path:a.path})}return r}async function VOe(e){if(!e.skillRoot)return null;let t=[Pc(e.skillRoot,`SKILL.md`),Pc(e.skillRoot,`skill.md`)];for(let e of t)try{return{path:e,content:Iu(await hl(e,`utf8`)).content.slice(0,kF)}}catch{}return null}async function HOe(e,t,n,r){try{let{addInvokedSkill:i}=await import(`./state-BhOKSFi5.js`);i(e,t,n,r.agentId??null)}catch{}}async function UOe(e,t,n,r){if(r!==`user_input`||!e.trim())return;let i=`${r}:${e.trim().toLowerCase()}`;if(!EF.has(i)){_F(EF,i);try{let[{isSkillLearningEnabled:r},{recordSkillGap:i}]=await Promise.all([import(`./featureCheck-JOur3pHb.js`),import(`./skillGapStore-
|
|
779
|
+
Output ONLY keywords. Nothing else.`,uF=6e3,dF=500,fF=120,pF=200,mF=150,hF=new Map})),gF=i({collectSkillDiscoveryPrefetch:()=>SF,extractQueryFromMessages:()=>vF,getTurnZeroSkillDiscovery:()=>WOe,startSkillDiscoveryPrefetch:()=>xF});function _F(e,t){if(e.add(t),e.size>CF){let t=e.size-wF,n=e.values();for(let r=0;r<t;r++){let t=n.next();if(t.done)break;e.delete(t.value)}}}function vF(e,t){let n=[];e&&n.push(e);for(let e=t.length-1;e>=0;e--){let r=t[e];if(r.type!==`user`)continue;let i=r.content;if(typeof i==`string`){n.push(i.slice(0,500));break}if(Array.isArray(i)){let e=!1;for(let t of i){let r=t;if(r.type&&r.type!==`text`)continue;let i=r.text;if(typeof i==`string`&&i.trim()){n.push(i.slice(0,500)),e=!0;break}}if(e)break}}return n.join(` `)}function yF(e,t,n){return{type:`skill_discovery`,skills:e,signal:t,source:`native`,gap:n}}async function bF(e,t){let n=0,r=[];for(let i of e){let e={name:i.name,description:i.description,score:i.score};if(n>=OF||i.score<DF){r.push(e);continue}let a=await VOe(i);if(!a){r.push(e);continue}n++,await HOe(i.name,a.path,a.content,t),r.push({...e,autoLoaded:!0,content:a.content,path:a.path})}return r}async function VOe(e){if(!e.skillRoot)return null;let t=[Pc(e.skillRoot,`SKILL.md`),Pc(e.skillRoot,`skill.md`)];for(let e of t)try{return{path:e,content:Iu(await hl(e,`utf8`)).content.slice(0,kF)}}catch{}return null}async function HOe(e,t,n,r){try{let{addInvokedSkill:i}=await import(`./state-BhOKSFi5.js`);i(e,t,n,r.agentId??null)}catch{}}async function UOe(e,t,n,r){if(r!==`user_input`||!e.trim())return;let i=`${r}:${e.trim().toLowerCase()}`;if(!EF.has(i)){_F(EF,i);try{let[{isSkillLearningEnabled:r},{recordSkillGap:i}]=await Promise.all([import(`./featureCheck-JOur3pHb.js`),import(`./skillGapStore-CcFoHNLl.js`)]);if(!r())return;let a=await i({prompt:e,cwd:n.cwd??process.cwd(),sessionId:n.sessionId??`unknown-session`,recommendations:t}),o=a.status;return o!==`pending`&&o!==`draft`&&o!==`active`?void 0:{key:a.key,status:o,draftName:a.draft?.name,draftPath:a.draft?.skillPath,activeName:a.active?.name,activePath:a.active?.skillPath}}catch(e){G(`[skill-search] skill gap learning error: ${e}`);return}}}async function xF(e,t,n){if(!ah())return[];let r=Date.now(),i=vF(e,t);if(!i.trim())return[];try{let e=await koe(n.cwd??process.cwd()),t=Noe(i,e).filter(e=>!TF.has(e.name));if(t.length===0)return[];for(let e of t)_F(TF,e.name);let a={trigger:`assistant_turn`,queryText:i.slice(0,200),startedAt:r,durationMs:Date.now()-r,indexSize:e.length,method:`tfidf`};return G(`[skill-search] prefetch found ${t.length} skills in ${a.durationMs}ms`),[yF(await bF(t,n),a)]}catch(e){return G(`[skill-search] prefetch error: ${e}`),[]}}async function SF(e){try{return await e}catch{return[]}}async function WOe(e,t,n){if(!ah()||!e.trim())return null;let r=Date.now();try{let t=await koe(n.cwd??process.cwd()),i=Noe(await FOe(e),t),a=await bF(i,n),o=a.some(e=>e.autoLoaded)?void 0:await UOe(e,i,n,`user_input`);if(i.length===0&&!o)return null;for(let e of i)_F(TF,e.name);let s={trigger:`user_input`,queryText:e.slice(0,200),startedAt:r,durationMs:Date.now()-r,indexSize:t.length,method:`tfidf`};return G(`[skill-search] turn-zero found ${i.length} skills in ${s.durationMs}ms`),yF(a,s,o)}catch(e){return G(`[skill-search] turn-zero error: ${e}`),null}}var CF,wF,TF,EF,DF,OF,kF,AF=n((()=>{oh(),tc(),BOe(),K(),Ku(),CF=1e3,wF=750,TF=new Set,EF=new Set,DF=Number(process.env.SKILL_SEARCH_AUTOLOAD_MIN_SCORE??`0.30`),OF=Number(process.env.SKILL_SEARCH_AUTOLOAD_LIMIT??`2`),kF=Number(process.env.SKILL_SEARCH_AUTOLOAD_MAX_CHARS??`12000`)}));function jF(e){return LF.test(e)}function GOe(e){if(e.startsWith(`mcp__`)){let t=e.replace(/^mcp__/,``).toLowerCase();return{parts:t.split(`__`).flatMap(e=>e.split(`_`)).filter(Boolean),full:t.replace(/__/g,` `).replace(/_/g,` `),isMcp:!0}}let t=e.replace(/([a-z])([A-Z])/g,`$1 $2`).replace(/_/g,` `).toLowerCase().split(/\s+/).filter(Boolean);return{parts:t,full:t.join(` `),isMcp:!1}}async function KOe(e){let t=e.filter(e=>As(e)),n=[];for(let r of t){let t=``;try{t=await r.prompt({getToolPermissionContext:async()=>({mode:`default`,additionalWorkingDirectories:new Map,alwaysAllowRules:{},alwaysDenyRules:{},alwaysAskRules:{},isBypassPermissionsModeAvailable:!1}),tools:e,agents:[]})}catch{t=``}let{parts:i,full:a}=GOe(r.name),o=r.searchHint??``,s=ec(i.join(` `)),c=ec(o),l=ec(t),u=[...new Set([...s,...c,...l])],d=Moe([{tokens:s,weight:PF.name},{tokens:c,weight:PF.searchHint},{tokens:l,weight:PF.description}]),f;r.inputJSONSchema&&(f=r.inputJSONSchema),n.push({name:r.name,normalizedName:a,description:t,searchHint:r.searchHint,isMcp:r.isMcp===!0,isDeferred:!0,inputSchema:f,tokens:u,tfVector:d})}let r=joe(n);for(let e of n)for(let[t,n]of e.tfVector)e.tfVector.set(t,n*(r.get(t)??0));return G(`[search-extra-tools] indexed ${n.length} deferred tools from ${e.length} total tools`),n}function MF(e,t,n=5){if(t.length===0||!e.trim())return[];let r=ec(e);if(r.length===0)return[];let i=new Map,a=new Map;for(let e of r)a.set(e,(a.get(e)??0)+1);let o=1;for(let e of a.values())e>o&&(o=e);for(let[e,t]of a)i.set(e,t/o);let s=joe(t),c=new Map;for(let[e,t]of i)c.set(e,t*(s.get(e)??0));let l=r.filter(e=>jF(e[0]??``)),u=r.filter(e=>!jF(e[0]??``)),d=e.toLowerCase().replace(/[-_]/g,` `),f=[];for(let e of t){let t=Aoe(c,e.tfVector);l.length>0&&t>0&&l.filter(t=>e.tfVector.has(t)).length<IF&&(u.some(t=>e.tfVector.has(t))||(t=0)),d.includes(e.normalizedName)&&(t=Math.max(t,.75)),t>=FF&&f.push({name:e.name,description:e.description,searchHint:e.searchHint,score:t,isMcp:e.isMcp,isDeferred:e.isDeferred,inputSchema:e.inputSchema})}return f.sort((e,t)=>t.score-e.score),f.slice(0,n)}async function NF(e){let t=e.map(e=>e.name).sort().join(`,`);return RF&&zF===t?RF:(RF=await KOe(e),zF=t,RF)}var PF,FF,IF,LF,RF,zF,BF=n((()=>{K(),tc(),Bs(),PF={name:3,searchHint:2.5,description:1},FF=Number(process.env.SEARCH_EXTRA_TOOLS_DISPLAY_MIN_SCORE??`0.10`),IF=2,LF=/[\u4e00-\u9fff\u3400-\u4dbf]/,RF=null,zF=null})),VF=i({buildToolDiscoveryAttachment:()=>KF,clearSearchExtraToolsPrefetchResults:()=>GF,collectSearchExtraToolsPrefetch:()=>JF,getSearchExtraToolsPrefetchSnapshot:()=>WF,getTurnZeroSearchExtraToolsPrefetch:()=>YOe,startSearchExtraToolsPrefetch:()=>qF,subscribeToSearchExtraToolsPrefetch:()=>UF});function HF(){for(let e of $F)e()}function UF(e){return $F.add(e),()=>{$F.delete(e)}}function WF(){return QF}function GF(){QF=[],HF()}function qOe(e,t){if(e.add(t),e.size>YF){let t=e.size-XF,n=e.values();for(let r=0;r<t;r++){let t=n.next();if(t.done)break;e.delete(t.value)}}}function JOe(e){return{name:e.name,description:e.description,searchHint:e.searchHint,score:e.score,isMcp:e.isMcp,isDeferred:e.isDeferred,inputSchema:e.inputSchema}}function KF(e,t,n,r,i){return{type:`tool_discovery`,tools:e,trigger:t,queryText:n.slice(0,200),durationMs:r,indexSize:i}}async function qF(e,t){let n=Date.now(),r=vF(null,t);if(!r.trim())return[];try{let t=await NF(e),i=MF(r,t,3).filter(e=>!ZF.has(e.name));if(i.length===0)return[];for(let e of i)qOe(ZF,e.name);let a=Date.now()-n;G(`[search-extra-tools] prefetch found ${i.length} tools in ${a}ms`);let o=i.map(JOe);return QF=o,HF(),[KF(o,`assistant_turn`,r,a,t.length)]}catch(e){return G(`[search-extra-tools] prefetch error: ${e}`),[]}}async function YOe(e,t){return null}async function JF(e){try{return await e}catch{return[]}}var YF,XF,ZF,QF,$F,eI=n((()=>{BF(),K(),AF(),YF=500,XF=400,ZF=new Set,QF=[],$F=new Set}));function tI(e){iI=e}function nI(){return iI}function XOe(e){aI=e}function rI(){return aI}function ZOe(e){oI=e}function QOe(){return oI}var iI,aI,oI,sI=n((()=>{iI=!1,aI=!1,oI=!1}));function cI(){return!1}function $Oe(e){return e.some(e=>{if(e.type!==`user`)return!1;let t=e.message.content;return Array.isArray(t)?t.some(e=>e.type===`text`&&e.text.includes(`<fork-boilerplate>`)):!1})}function eke(e,t){let n={...t,uuid:Jc(),message:{...t.message,content:[...Array.isArray(t.message.content)?t.message.content:[]]}},r=(Array.isArray(t.message.content)?t.message.content:[]).filter(e=>e.type===`tool_use`);return r.length===0?(G(`No tool_use blocks found in assistant message for fork directive: ${e.slice(0,50)}...`,{level:`error`}),[Q({content:[{type:`text`,text:lI(e)}]})]):[n,Q({content:[...r.map(e=>({type:`tool_result`,tool_use_id:e.id,content:[{type:`text`,text:fI}]})),{type:`text`,text:lI(e)}]})]}function lI(e){return`<${Ha}>
|
|
780
780
|
STOP. READ THIS FIRST.
|
|
781
781
|
|
|
782
782
|
You are a forked worker process. You are NOT the main agent.
|
|
@@ -862,7 +862,7 @@ Usage notes:
|
|
|
862
862
|
... (truncated because it exceeds 2k characters. If you need more information, run "git status" using BashTool)`:i;return ei(`info`,`git_status_completed`,{duration_ms:Date.now()-e,truncated:i.length>RR}),[`This is the git status at the start of the conversation. Note that this status is a snapshot in time, and will not update during the conversation.`,`Current branch: ${n}`,`Main branch (you will usually use this for PRs): ${r}`,...o?[`Git user: ${o}`]:[],`Status:\n${s||`(clean)`}`,`Recent commits:\n${a}`].join(`
|
|
863
863
|
|
|
864
864
|
`)}catch(t){return ei(`error`,`git_status_failed`,{duration_ms:Date.now()-e}),J(t),null}}),BR=u(async()=>{let e=Date.now();ei(`info`,`system_context_started`);let t=h(process.env.CLAUDE_CODE_REMOTE)||!IR()?null:await zR();return ei(`info`,`system_context_completed`,{duration_ms:Date.now()-e,has_git_status:t!==null,has_injection:!1}),{...t&&{gitStatus:t}}}),VR=u(async()=>{let e=Date.now();ei(`info`,`user_context_started`);let t=h(process.env.CLAUDE_CODE_DISABLE_CLAUDE_MDS)||v()&&mn().length===0,n=t?null:ZN(LN(await JN()));return lte(n||null),ei(`info`,`user_context_completed`,{duration_ms:Date.now()-e,agentsmd_length:n?.length??0,agentsmd_disabled:!!t}),{...n&&{agentsMd:n},currentDate:`Today's date is ${NR()}.`}})}));function gAe(){return Sm()}function UR({mainThreadAgentDefinition:e,toolUseContext:t,customSystemPrompt:n,defaultSystemPrompt:r,appendSystemPrompt:i,overrideSystemPrompt:a}){if(a)return gv([a]);let o=e?q9(e)?e.getSystemPrompt({toolUseContext:{options:t.options}}):e.getSystemPrompt():void 0;return e?.memory&&Y(`tengu_agent_memory_loaded`,{scope:e.memory,source:`main-thread`}),o&&gAe()?gv([...r,`\n# Custom Agent Instructions\n${o}`,...i?[i]:[]]):gv([...o?[o]:n?[n]:r,...i?[i]:[]])}var WR=n((()=>{oo(),$9(),cF(),Bm()})),_Ae=i({_resetCacheWarningStateForTest:()=>vAe,calculateCacheHitRate:()=>qR,createCacheWarningMessage:()=>YR,getCacheThreshold:()=>GR,isCacheWarningEnabled:()=>KR,shouldShowCacheWarning:()=>JR});function GR(){return Vi().cacheThreshold??QR}function KR(){return Vi().cacheWarningEnabled??!0}function qR(e){if(!e)return null;let{input_tokens:t,cache_creation_input_tokens:n,cache_read_input_tokens:r}=e;if(r===0&&n===0)return null;let i=t+n+r;return i===0?null:r/i*100}function JR(e,t,n){let r=qR(e);if(r===null)return null;let i=XR.get(t);if(!i){if(i={lastHitRate:null,lastTimestamp:null},XR.size>=ZR){let e=XR.keys().next().value;e!==void 0&&XR.delete(e)}XR.set(t,i)}if(i.lastHitRate===null)return i.lastHitRate=r,i.lastTimestamp=Date.now(),null;let a=r-i.lastHitRate;return i.lastHitRate=r,i.lastTimestamp=Date.now(),r<n?{hitRate:r,threshold:n,trend:a,shouldWarn:!0}:null}function YR(e){let{hitRate:t,threshold:n,trend:r}=e,i=`Cache hit rate ${t.toFixed(0)}%, below ${n}% threshold`;if(r!==null&&Math.abs(r)>.1){let e=r>0?`^`:`v`,t=Math.abs(r).toFixed(0);i+=` (${e}${t}%)`}return{type:`system`,subtype:`cache_warning`,level:`warning`,content:i,timestamp:new Date().toISOString(),uuid:Jc(),isMeta:!1}}function vAe(){XR.clear()}var XR,ZR,QR,$R=n((()=>{vi(),XR=new Map,ZR=50,QR=80}));async function ez(e,t){try{let n=await y3(e,t);if(n!==null)return n;G(`countTokensWithFallback: API returned null, trying haiku fallback (${t.length} tools)`)}catch(e){G(`countTokensWithFallback: API failed: ${W(e)}`),J(e)}try{let n=await zit(e,t);return n===null&&G(`countTokensWithFallback: haiku fallback also returned null (${t.length} tools)`),n}catch(e){return G(`countTokensWithFallback: haiku fallback failed: ${W(e)}`),J(e),null}}async function tz(e,t,n,r){let i=await ez([],await Promise.all(e.map(i=>V7(i,{getToolPermissionContext:t,tools:e,agents:n?.activeAgents??[],model:r}))));if(i===null||i===0){let t=e.map(e=>e.name).join(`, `);G(`countToolDefinitionTokens returned ${i} for ${e.length} tools: ${t.slice(0,100)}${t.length>100?`...`:``}`)}return i??0}function yAe(e){let t=e.match(/^#+\s+(.+)$/m);if(t)return t[1].trim();let n=e.split(`
|
|
865
|
-
`).find(e=>e.trim().length>0)??``;return n.length>40?`${n.slice(0,40)}…`:n}async function bAe(e){let t=await BR(),n=[...e.filter(e=>e.length>0&&e!==`__SYSTEM_PROMPT_DYNAMIC_BOUNDARY__`).map(e=>({name:yAe(e),content:e})),...Object.entries(t).filter(([,e])=>e.length>0).map(([e,t])=>({name:e,content:t}))];if(n.length<1)return{systemPromptTokens:0,systemPromptSections:[]};let r=await Promise.all(n.map(({content:e})=>ez([{role:`user`,content:e}],[]))),i=n.map((e,t)=>({name:e.name,tokens:r[t]||0}));return{systemPromptTokens:r.reduce((e,t)=>e+(t||0),0),systemPromptSections:i}}async function xAe(){if(h(process.env.CLAUDE_CODE_SIMPLE))return{memoryFileDetails:[],agentsMdTokens:0};let e=LN(await JN()),t=[],n=0;if(e.length<1)return{memoryFileDetails:[],agentsMdTokens:0};let r=await Promise.all(e.map(async e=>({file:e,tokens:await ez([{role:`user`,content:e.content}],[])||0})));for(let{file:e,tokens:i}of r)n+=i,t.push({path:e.path,type:e.type,tokens:i});return{agentsMdTokens:n,memoryFileDetails:t}}async function SAe(e,t,n,r,i){let a=e.filter(e=>!e.isMcp);if(a.length<1)return{builtInToolTokens:0,deferredBuiltinDetails:[],deferredBuiltinTokens:0,systemToolDetails:[]};let o=[],{isSearchExtraToolsEnabled:s}=await import(`./searchExtraTools-BhDq8DTJ.js`),{isDeferredTool:c}=await import(`./prompt-CHobfCB1.js`),l=await s(r??``,e,t,n?.activeAgents??[],`analyzeBuiltIn`),u=a.filter(e=>!c(e)),d=a.filter(e=>c(e)),f=u.length>0?await tz(u,t,n,r):0,p=[],m=0,h=0;if(d.length>0&&l){let e=new Set;if(i){let t=new Set(d.map(e=>e.name));for(let n of i)if(n.type===`assistant`&&Array.isArray(n.message.content))for(let r of n.message.content)typeof r!=`string`&&`type`in r&&r.type===`tool_use`&&`name`in r&&typeof r.name==`string`&&t.has(r.name)&&e.add(r.name)}let a=await Promise.all(d.map(e=>tz([e],t,n,r)));for(let[t,n]of d.entries()){let r=Math.max(0,(a[t]||0)-500),i=e.has(n.name);p.push({name:n.name,tokens:r,isLoaded:i}),h+=r,i&&(m+=r)}}else if(d.length>0)return{builtInToolTokens:f+await tz(d,t,n,r),deferredBuiltinDetails:[],deferredBuiltinTokens:0,systemToolDetails:o};return{builtInToolTokens:f+m,deferredBuiltinDetails:p,deferredBuiltinTokens:h-m,systemToolDetails:o}}function nz(e){return Ds(e,ps)}async function CAe(e,t,n){let r=await tve(H()),i=nz(e);return i?{slashCommandTokens:await tz([i],t,n),commandInfo:{totalCommands:r.totalCommands,includedCommands:r.includedCommands}}:{slashCommandTokens:0,commandInfo:{totalCommands:0,includedCommands:0}}}async function wAe(e,t,n){try{let r=await nve(H()),i=nz(e);if(!i)return{skillTokens:0,skillInfo:{totalSkills:0,includedSkills:0,skillFrontmatter:[]}};let a=await tz([i],t,n),o=r.map(e=>({name:H3(e),source:e.type===`prompt`?e.source:`plugin`,tokens:Jit(e)}));return{skillTokens:a,skillInfo:{totalSkills:r.length,includedSkills:r.length,skillFrontmatter:o}}}catch(e){return J(tr(e)),{skillTokens:0,skillInfo:{totalSkills:0,includedSkills:0,skillFrontmatter:[]}}}}async function rz(e,t,n,r,i){let a=e.filter(e=>e.isMcp),o=[],s=await tz(a,t,n,r),c=Math.max(0,(s||0)-500),l=await Promise.all(a.map(async r=>b3(U({name:r.name,description:await r.prompt({getToolPermissionContext:t,tools:e,agents:n?.activeAgents??[]}),input_schema:r.inputJSONSchema??{}})))),u=l.reduce((e,t)=>e+t,0)||1,d=l.map(e=>Math.round(e/u*c)),{isSearchExtraToolsEnabled:f}=await import(`./searchExtraTools-BhDq8DTJ.js`),{isDeferredTool:p}=await import(`./prompt-CHobfCB1.js`),m=await f(r,e,t,n?.activeAgents??[],`analyzeMcp`),h=new Set;if(m&&i){let e=new Set(a.map(e=>e.name));for(let t of i)if(t.type===`assistant`&&Array.isArray(t.message.content))for(let n of t.message.content)typeof n!=`string`&&`type`in n&&n.type===`tool_use`&&`name`in n&&typeof n.name==`string`&&e.has(n.name)&&h.add(n.name)}for(let[e,t]of a.entries())o.push({name:t.name,serverName:t.name.split(`__`)[1]||`unknown`,tokens:d[e],isLoaded:h.has(t.name)||!p(t)});let g=0,_=0;for(let e of o)e.isLoaded?g+=e.tokens:m&&(_+=e.tokens);return{mcpToolTokens:m?g:c,mcpToolDetails:o,deferredToolTokens:_,loadedMcpToolNames:h}}async function TAe(e){let t=e.activeAgents.filter(e=>e.source!==`built-in`),n=[],r=0,i=await Promise.all(t.map(e=>ez([{role:`user`,content:[e.agentType,e.whenToUse].join(` `)}],[])));for(let[e,a]of t.entries()){let t=i[e]||0;r+=t||0,n.push({agentType:a.agentType,source:a.source,tokens:t||0})}return{agentTokens:r,agentDetails:n}}function EAe(e,t){let n=Array.isArray(e.message.content)?e.message.content:[];for(let e of n){let n=b3(U(e));if(typeof e!=`string`&&`type`in e&&e.type===`tool_use`){t.toolCallTokens+=n;let r=(`name`in e?e.name:void 0)||`unknown`;t.toolCallsByType.set(r,(t.toolCallsByType.get(r)||0)+n)}else t.assistantMessageTokens+=n}}function DAe(e,t,n){if(typeof e.message.content==`string`){let n=b3(e.message.content);t.userMessageTokens+=n;return}for(let r of e.message.content??[]){let e=b3(U(r));if(`type`in r&&r.type===`tool_result`){let i=`tool_use_id`in r?r.tool_use_id:void 0,a=(i?n.get(i):void 0)||`unknown`;t.toolResultsByType.set(a,(t.toolResultsByType.get(a)||0)+e)}else t.userMessageTokens+=e}}function OAe(e,t){let n=b3(U(e.attachment));t.attachmentTokens+=n;let r=e.attachment.type||`unknown`;t.attachmentsByType.set(r,(t.attachmentsByType.get(r)||0)+n)}async function kAe(e){let t=await OR(e),n={totalTokens:0,toolCallTokens:0,toolResultTokens:0,attachmentTokens:0,assistantMessageTokens:0,userMessageTokens:0,toolCallsByType:new Map,toolResultsByType:new Map,attachmentsByType:new Map},r=new Map;for(let e of t.messages)if(e.type===`assistant`&&Array.isArray(e.message.content)){for(let t of e.message.content)if(typeof t!=`string`&&`type`in t&&t.type===`tool_use`){let e=`id`in t?t.id:void 0,n=(`name`in t?t.name:void 0)||`unknown`;e&&r.set(e,n)}}for(let e of t.messages)e.type===`assistant`?EAe(e,n):e.type===`user`?DAe(e,n,r):e.type===`attachment`&&OAe(e,n);return n.totalTokens=await ez(c3(t.messages).map(e=>e.type===`assistant`?{role:`assistant`,content:e.message.content}:e.message),[])??0,n}async function AAe(t,n,r,i,a,o,s,c,l){let u=Vo({permissionMode:(await r()).mode,mainLoopModel:n}),d=Go(u,dn()),f=await F7(i,u),p=UR({mainThreadAgentDefinition:c,toolUseContext:s??{options:{}},customSystemPrompt:s?.options.customSystemPrompt,defaultSystemPrompt:f,appendSystemPrompt:s?.options.appendSystemPrompt}),[{systemPromptTokens:m,systemPromptSections:h},{agentsMdTokens:g,memoryFileDetails:_},{builtInToolTokens:v,deferredBuiltinDetails:y,deferredBuiltinTokens:b,systemToolDetails:x},{mcpToolTokens:S,mcpToolDetails:C,deferredToolTokens:w},{agentTokens:T,agentDetails:E},{slashCommandTokens:D,commandInfo:O},k]=await Promise.all([bAe(p),xAe(),SAe(i,r,a,u,t),rz(i,r,a,u,t),TAe(a),CAe(i,r,a),kAe(t)]),A=(await wAe(i,r,a)).skillInfo,ee=A.skillFrontmatter.reduce((e,t)=>e+t.tokens,0),te=k.totalTokens,ne=vJ(),re=ne?hJ(n)-bJ:void 0,ie=[];m>0&&ie.push({name:`System prompt`,tokens:m,color:`promptBorder`});let ae=v-ee;ae>0&&ie.push({name:`System tools`,tokens:ae,color:`inactive`}),S>0&&ie.push({name:`MCP tools`,tokens:S,color:`cyan_FOR_SUBAGENTS_ONLY`}),w>0&&ie.push({name:`MCP tools (deferred)`,tokens:w,color:`inactive`,isDeferred:!0}),b>0&&ie.push({name:`System tools (deferred)`,tokens:b,color:`inactive`,isDeferred:!0}),T>0&&ie.push({name:`Custom agents`,tokens:T,color:`permission`}),g>0&&ie.push({name:`Memory files`,tokens:g,color:`claude`}),ee>0&&ie.push({name:`Skills`,tokens:ee,color:`warning`}),te!==null&&te>0&&ie.push({name:`Messages`,tokens:te,color:`purple_FOR_SUBAGENTS_ONLY`});let j=ie.reduce((e,t)=>e+(t.isDeferred?0:t.tokens),0),oe=0;ne&&re!==void 0?(oe=d-re,ie.push({name:iz,tokens:oe,color:`inactive`})):ne||(oe=xJ,ie.push({name:az,tokens:oe,color:`inactive`}));let se=Math.max(0,d-j-oe);ie.push({name:`Free space`,tokens:se,color:`promptBorder`});let ce=j,M=qL(l??t),N=(M?M.input_tokens+M.cache_creation_input_tokens+M.cache_read_input_tokens:null)??ce,le=o&&o<80,ue=d>=1e6?le?5:20:le?5:10,de=d>=1e6?10:le?5:10,fe=ue*de,pe=ie.filter(e=>!e.isDeferred).map(e=>({...e,squares:e.name===`Free space`?Math.round(e.tokens/d*fe):Math.max(1,Math.round(e.tokens/d*fe)),percentageOfTotal:Math.round(e.tokens/d*100)}));function me(e){let t=[],n=e.tokens/d*fe,r=Math.floor(n),i=n-r;for(let n=0;n<e.squares;n++){let a=1;n===r&&i>0&&(a=i),t.push({color:e.color,isFilled:!0,categoryName:e.name,tokens:e.tokens,percentage:e.percentageOfTotal,squareFullness:a})}return t}let he=[],ge=pe.find(e=>e.name===iz||e.name===az),_e=pe.filter(e=>e.name!==iz&&e.name!==az&&e.name!==`Free space`);for(let e of _e){let t=me(e);for(let e of t)he.length<fe&&he.push(e)}let ve=ge?ge.squares:0,ye=ie.find(e=>e.name===`Free space`),be=fe-ve;for(;he.length<be;)he.push({color:`promptBorder`,isFilled:!0,categoryName:`Free space`,tokens:ye?.tokens||0,percentage:ye?Math.round(ye.tokens/d*100):0,squareFullness:1});if(ge){let e=me(ge);for(let t of e)he.length<fe&&he.push(t)}let xe=[];for(let e=0;e<de;e++)xe.push(he.slice(e*ue,(e+1)*ue));let Se=new Map;for(let[e,t]of k.toolCallsByType.entries()){let n=Se.get(e)||{callTokens:0,resultTokens:0};Se.set(e,{...n,callTokens:t})}for(let[e,t]of k.toolResultsByType.entries()){let n=Se.get(e)||{callTokens:0,resultTokens:0};Se.set(e,{...n,resultTokens:t})}let Ce=Array.from(Se.entries()).map(([e,{callTokens:t,resultTokens:n}])=>({name:e,callTokens:t,resultTokens:n})).sort((e,t)=>t.callTokens+t.resultTokens-(e.callTokens+e.resultTokens)),we=Array.from(k.attachmentsByType.entries()).map(([e,t])=>({name:e,tokens:t})).sort((e,t)=>t.tokens-e.tokens),Te={toolCallTokens:k.toolCallTokens,toolResultTokens:k.toolResultTokens,attachmentTokens:k.attachmentTokens,assistantMessageTokens:k.assistantMessageTokens,userMessageTokens:k.userMessageTokens,toolCallsByType:Ce,attachmentsByType:we};return{categories:ie,totalTokens:N,maxTokens:d,rawMaxTokens:d,percentage:Math.round(N/d*100),gridRows:xe,model:u,memoryFiles:_,mcpTools:C,deferredBuiltinTools:void 0,systemTools:void 0,systemPromptSections:void 0,agents:E,slashCommands:D>0?{totalCommands:O.totalCommands,includedCommands:O.includedCommands,tokens:D}:void 0,skills:ee>0?{totalSkills:A.totalSkills,includedSkills:A.includedSkills,tokens:ee,skillFrontmatter:A.skillFrontmatter}:void 0,autoCompactThreshold:re,isAutoCompactEnabled:ne,messageBreakdown:Te,apiUsage:M,...(()=>{if(!M)return{};let{calculateCacheHitRate:t,getCacheThreshold:n}=($R(),e(_Ae)),r=t(M);return r===null?{}:{cacheHitRate:r,cacheThreshold:n()}})()}}var iz,az,oz=n((()=>{B7(),MR(),Jt(),Q3(),HR(),CJ(),T3(),z3(),Ks(),Zs(),hb(),U7(),QN(),Bo(),Vn(),K(),g(),qn(),Ga(),h3(),Uo(),mr(),WR(),ZL(),iz=`Autocompact buffer`,az=`Compact buffer`}));function sz(e){let t=cz.get(e);if(t)return t;let n=Hee(e);return cz.set(e,n),n}var cz,lz=n((()=>{Nt(),cz=new WeakMap}));function uz(e){if(!e.startsWith(`auto:`))return null;let t=e.slice(5),n=parseInt(t,10);return isNaN(n)?(G(`Invalid ENABLE_SEARCH_EXTRA_TOOLS value "${e}": expected auto:N where N is a number.`),null):Math.max(0,Math.min(100,n))}function jAe(e){return e?e===`auto`||e.startsWith(`auto:`):!1}function dz(){let e=process.env.ENABLE_SEARCH_EXTRA_TOOLS;if(!e||e===`auto`)return Sz;let t=uz(e);return t===null?Sz:t}function fz(e){let t=Go(e,Te(e)),n=dz()/100;return Math.floor(t*n)}function pz(e){return Math.floor(fz(e)*Cz)}function mz(){if(h(process.env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS))return`standard`;let e=process.env.ENABLE_SEARCH_EXTRA_TOOLS,t=e?uz(e):null;return t===0?`tst`:t===100?`standard`:jAe(e)?`tst-auto`:h(e)?`tst`:f(process.env.ENABLE_SEARCH_EXTRA_TOOLS)?`standard`:`tst`}function hz(){let e=mz();return e===`standard`?(Tz||(Tz=!0,G(`[SearchExtraTools:optimistic] mode=${e}, ENABLE_SEARCH_EXTRA_TOOLS=${process.env.ENABLE_SEARCH_EXTRA_TOOLS}, result=false`)),!1):(Tz||(Tz=!0,G(`[SearchExtraTools:optimistic] mode=${e}, ENABLE_SEARCH_EXTRA_TOOLS=${process.env.ENABLE_SEARCH_EXTRA_TOOLS}, result=true`)),!0)}function gz(e){return e.some(e=>Cs(e,Hs))}async function MAe(e,t,n){let r=e.filter(e=>As(e));return r.length===0?0:(await Promise.all(r.map(async r=>{let i=await r.prompt({getToolPermissionContext:t,tools:e,agents:n}),a=r.inputJSONSchema?U(r.inputJSONSchema):r.inputSchema?U(sz(r.inputSchema)):``;return r.name.length+i.length+a.length}))).reduce((e,t)=>e+t,0)}async function _z(e,t,n,r,i){let a=Xr(t,e=>e.isMcp);function o(t,n,r,i){Y(`tengu_search_extra_tools_mode_decision`,{enabled:t,mode:n,reason:r,checkedModel:e,mcpToolCount:a,userType:process.env.USER_TYPE??`external`,...i})}if(!gz(t))return G(`Tool search disabled: SearchExtraToolsTool is not available (may have been disallowed via disallowedTools).`),o(!1,`standard`,`mcp_search_unavailable`),!1;let s=mz();switch(s){case`tst`:return o(!0,s,`tst_enabled`),!0;case`tst-auto`:{let{enabled:a,debugDescription:c,metrics:l}=await LAe(t,n,r,e);return a?(G(`Auto tool search enabled: ${c}`+(i?` [source: ${i}]`:``)),o(!0,s,`auto_above_threshold`,l),!0):(G(`Auto tool search disabled: ${c}`+(i?` [source: ${i}]`:``)),o(!1,s,`auto_below_threshold`,l),!1)}case`standard`:return o(!1,s,`standard_mode`),!1}}function vz(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_reference`}function NAe(e){return vz(e)&&`tool_name`in e&&typeof e.tool_name==`string`}function PAe(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_result`&&`content`in e&&Array.isArray(e.content)}function FAe(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_result`&&`content`in e&&typeof e.content==`string`}function IAe(e){let t=Ez.exec(e);return t?.[1]?t[1].split(`,`).map(e=>e.trim()).filter(Boolean):[]}function yz(e){let t=new Set,n=0;for(let r of e){if(r.type===`system`&&r.subtype===`compact_boundary`){let e=r.compactMetadata?.preCompactDiscoveredTools;if(e){for(let n of e)t.add(n);n+=e.length}continue}if(r.type===`attachment`&&r.attachment?.type===`deferred_tools_delta`){let e=r.attachment.addedNames??[];for(let n of e)t.add(n);continue}if(r.type!==`user`)continue;let e=r.message?.content;if(Array.isArray(e))for(let n of e){if(PAe(n))for(let e of n.content)NAe(e)&&t.add(e.tool_name);if(FAe(n)){let e=IAe(n.content);for(let n of e)t.add(n)}}}return t.size>0&&G(`Dynamic tool loading: found ${t.size} discovered tools in message history`+(n>0?` (${n} carried from compact boundary)`:``)),t}function bz(){return!1}function xz(e,t,n){let r=new Set,i=0,a=0,o=new Set;for(let e of t)if(e.type===`attachment`&&(i++,o.add(e.attachment.type),e.attachment.type===`deferred_tools_delta`)){a++;for(let t of e.attachment.addedNames)r.add(t);for(let t of e.attachment.removedNames)r.delete(t)}let s=e.filter(As),c=new Set(s.map(e=>e.name)),l=new Set(e.map(e=>e.name)),u=s.filter(e=>!r.has(e.name)),d=[];for(let e of r)c.has(e)||l.has(e)||d.push(e);return u.length===0&&d.length===0?null:(Y(`tengu_deferred_tools_pool_change`,{addedCount:u.length,removedCount:d.length,priorAnnouncedCount:r.size,messagesLength:t.length,attachmentCount:i,dtdCount:a,callSite:n?.callSite??`unknown`,querySource:n?.querySource??`unknown`,attachmentTypesSeen:[...o].sort().join(`,`)}),{addedNames:u.map(e=>e.name).sort(),addedLines:u.map(uoe).sort(),removedNames:d.sort()})}async function LAe(e,t,n,r){let i=await wz(e,t,n,r);if(i!==null){let e=fz(r);return{enabled:i>=e,debugDescription:`${i} tokens (threshold: ${e}, ${dz()}% of context)`,metrics:{deferredToolTokens:i,threshold:e}}}let a=await MAe(e,t,n),o=pz(r);return{enabled:a>=o,debugDescription:`${a} chars (threshold: ${o}, ${dz()}% of context) (char fallback)`,metrics:{deferredToolDescriptionChars:a,charThreshold:o}}}var Sz,Cz,wz,Tz,Ez,Dz=n((()=>{d(),oo(),Ks(),Bs(),oz(),Ar(),ve(),Bo(),K(),g(),mr(),lz(),Sz=10,Cz=2.5,wz=u(async(e,t,n,r)=>{let i=e.filter(e=>As(e));if(i.length===0)return 0;try{let e=await tz(i,t,{activeAgents:n,allAgents:n},r);return e===0?null:Math.max(0,e-500)}catch{return null}},e=>e.filter(e=>As(e)).map(e=>e.name).join(`,`)),Tz=!1,Ez=/^Found \d+ deferred tool\(s\): (.+)\.$/m}));function RAe(e){return e.map(e=>e.name).sort().join(`,`)}function zAe(e){let t=RAe(e);Pz!==t&&(G(`SearchExtraToolsTool: cache invalidated - deferred tools changed`),Fz.cache.clear?.(),Pz=t)}function BAe(){Fz.cache.clear?.(),Pz=null}function Oz(e,t,n,r,i){return{data:{matches:e,query:t,total_deferred_tools:n,...r&&r.length>0?{pending_mcp_servers:r}:{},...i&&i.length>0?{already_loaded:i}:{}}}}function kz(e){if(e.startsWith(`mcp__`)){let t=e.replace(/^mcp__/,``).toLowerCase();return{parts:t.split(`__`).flatMap(e=>e.split(`_`)).filter(Boolean),full:t.replace(/__/g,` `).replace(/_/g,` `),isMcp:!0}}let t=e.replace(/([a-z])([A-Z])/g,`$1 $2`).replace(/_/g,` `).toLowerCase().split(/\s+/).filter(Boolean);return{parts:t,full:t.join(` `),isMcp:!1}}function VAe(e){let t=new Map;for(let n of e)t.has(n)||t.set(n,RegExp(`\\b${Xa(n)}\\b`));return t}async function HAe(e,t,n,r){let i=e.toLowerCase().trim(),a=t.find(e=>e.name.toLowerCase()===i)??n.find(e=>e.name.toLowerCase()===i);if(a)return[a.name];if(i.startsWith(`mcp__`)&&i.length>5){let e=t.filter(e=>e.name.toLowerCase().startsWith(i)).slice(0,r).map(e=>e.name);if(e.length>0)return e}let o=i.split(/\s+/).filter(e=>e.length>0),s=[],c=[];for(let e of o)e.startsWith(`+`)&&e.length>1?s.push(e.slice(1)):c.push(e);let l=s.length>0?[...s,...c]:o,u=VAe(l),d=t;return s.length>0&&(d=(await Promise.all(t.map(async e=>{let t=kz(e.name),r=(await Fz(e.name,n)).toLowerCase(),i=e.searchHint?.toLowerCase()??``;return s.every(e=>{let n=u.get(e);return t.parts.includes(e)||t.parts.some(t=>t.includes(e))||n.test(r)||i&&n.test(i)})?e:null}))).filter(e=>e!==null)),(await Promise.all(d.map(async e=>{let t=kz(e.name),r=(await Fz(e.name,n)).toLowerCase(),i=e.searchHint?.toLowerCase()??``,a=0;for(let e of l){let n=u.get(e);t.parts.includes(e)?a+=t.isMcp?12:10:t.parts.some(t=>t.includes(e))&&(a+=t.isMcp?6:5),t.full.includes(e)&&a===0&&(a+=3),i&&n.test(i)&&(a+=4),n.test(r)&&(a+=2)}return{name:e.name,score:a}}))).filter(e=>e.score>0).sort((e,t)=>t.score-e.score).slice(0,r).map(e=>e.name)}var Az,jz,Mz,Nz,Pz,Fz,Iz,Lz=n((()=>{d(),Nt(),oo(),Ks(),K(),kt(),$a(),Dz(),Bs(),BF(),Az=Number(process.env.SEARCH_EXTRA_TOOLS_WEIGHT_KEYWORD??`0.4`),jz=Number(process.env.SEARCH_EXTRA_TOOLS_WEIGHT_TFIDF??`0.6`),Mz=V(()=>I({query:B().describe(`Query to find deferred tools. Use "select:<tool_name>" for direct selection, or keywords to search.`),max_results:z().optional().default(5).describe(`Maximum number of results to return (default: 5)`)})),Nz=V(()=>I({matches:L(B()),query:B(),total_deferred_tools:z(),pending_mcp_servers:L(B()).optional(),already_loaded:L(B()).optional()})),Pz=null,Fz=u(async(e,t)=>{let n=Ds(t,e);return n?n.prompt({getToolPermissionContext:async()=>({mode:`default`,additionalWorkingDirectories:new Map,alwaysAllowRules:{},alwaysDenyRules:{},alwaysAskRules:{},isBypassPermissionsModeAvailable:!1}),tools:t,agents:[]}):``},e=>e),Iz=Ns({isEnabled(){return hz()},isConcurrencySafe(){return!0},isReadOnly(){return!0},name:Hs,maxResultSizeChars:1e5,async description(){return noe()},async prompt(){return noe()},get inputSchema(){return Mz()},get outputSchema(){return Nz()},async call(e,{options:{tools:t},getAppState:n}){let{query:r,max_results:i=5}=e,a=t.filter(As);zAe(a);function o(){let e=n().mcp.clients.filter(e=>e.type===`pending`);return e.length>0?e.map(e=>e.name):void 0}function s(e,t){Y(`tengu_search_extra_tools_outcome`,{query:r,queryType:t,matchCount:e.length,totalDeferredTools:a.length,maxResults:i,hasMatches:e.length>0})}let c=r.match(/^select:(.+)$/i);if(c){let e=c[1].split(`,`).map(e=>e.trim()).filter(Boolean),n=[],i=[],l=[];for(let r of e){let e=Ds(a,r),o=e??Ds(t,r);o?n.includes(o.name)||(n.push(o.name),e||i.push(o.name)):l.push(r)}if(n.length===0){G(`SearchExtraToolsTool: select failed — none found: ${l.join(`, `)}`),s([],`select`);let e=o();return Oz([],r,a.length,e)}return l.length>0?G(`SearchExtraToolsTool: partial select — found: ${n.join(`, `)}, missing: ${l.join(`, `)}`):G(`SearchExtraToolsTool: selected ${n.join(`, `)}`),s(n,`select`),Oz(n,r,a.length,void 0,i.length>0?i:void 0)}let l=r.match(/^discover:(.+)$/i);if(l){let e=MF(l[1].trim(),await NF(a),i),t=e.map(e=>{let t=`**${e.name}** (score: ${e.score.toFixed(2)})\n${e.description}`;return e.inputSchema&&(t+=`\nSchema: ${JSON.stringify(e.inputSchema)}`),t});return t.length>0&&`${t.length}${t.join(`
|
|
865
|
+
`).find(e=>e.trim().length>0)??``;return n.length>40?`${n.slice(0,40)}…`:n}async function bAe(e){let t=await BR(),n=[...e.filter(e=>e.length>0&&e!==`__SYSTEM_PROMPT_DYNAMIC_BOUNDARY__`).map(e=>({name:yAe(e),content:e})),...Object.entries(t).filter(([,e])=>e.length>0).map(([e,t])=>({name:e,content:t}))];if(n.length<1)return{systemPromptTokens:0,systemPromptSections:[]};let r=await Promise.all(n.map(({content:e})=>ez([{role:`user`,content:e}],[]))),i=n.map((e,t)=>({name:e.name,tokens:r[t]||0}));return{systemPromptTokens:r.reduce((e,t)=>e+(t||0),0),systemPromptSections:i}}async function xAe(){if(h(process.env.CLAUDE_CODE_SIMPLE))return{memoryFileDetails:[],agentsMdTokens:0};let e=LN(await JN()),t=[],n=0;if(e.length<1)return{memoryFileDetails:[],agentsMdTokens:0};let r=await Promise.all(e.map(async e=>({file:e,tokens:await ez([{role:`user`,content:e.content}],[])||0})));for(let{file:e,tokens:i}of r)n+=i,t.push({path:e.path,type:e.type,tokens:i});return{agentsMdTokens:n,memoryFileDetails:t}}async function SAe(e,t,n,r,i){let a=e.filter(e=>!e.isMcp);if(a.length<1)return{builtInToolTokens:0,deferredBuiltinDetails:[],deferredBuiltinTokens:0,systemToolDetails:[]};let o=[],{isSearchExtraToolsEnabled:s}=await import(`./searchExtraTools-D4gMMQv0.js`),{isDeferredTool:c}=await import(`./prompt-BKPmDAuL.js`),l=await s(r??``,e,t,n?.activeAgents??[],`analyzeBuiltIn`),u=a.filter(e=>!c(e)),d=a.filter(e=>c(e)),f=u.length>0?await tz(u,t,n,r):0,p=[],m=0,h=0;if(d.length>0&&l){let e=new Set;if(i){let t=new Set(d.map(e=>e.name));for(let n of i)if(n.type===`assistant`&&Array.isArray(n.message.content))for(let r of n.message.content)typeof r!=`string`&&`type`in r&&r.type===`tool_use`&&`name`in r&&typeof r.name==`string`&&t.has(r.name)&&e.add(r.name)}let a=await Promise.all(d.map(e=>tz([e],t,n,r)));for(let[t,n]of d.entries()){let r=Math.max(0,(a[t]||0)-500),i=e.has(n.name);p.push({name:n.name,tokens:r,isLoaded:i}),h+=r,i&&(m+=r)}}else if(d.length>0)return{builtInToolTokens:f+await tz(d,t,n,r),deferredBuiltinDetails:[],deferredBuiltinTokens:0,systemToolDetails:o};return{builtInToolTokens:f+m,deferredBuiltinDetails:p,deferredBuiltinTokens:h-m,systemToolDetails:o}}function nz(e){return Ds(e,ps)}async function CAe(e,t,n){let r=await tve(H()),i=nz(e);return i?{slashCommandTokens:await tz([i],t,n),commandInfo:{totalCommands:r.totalCommands,includedCommands:r.includedCommands}}:{slashCommandTokens:0,commandInfo:{totalCommands:0,includedCommands:0}}}async function wAe(e,t,n){try{let r=await nve(H()),i=nz(e);if(!i)return{skillTokens:0,skillInfo:{totalSkills:0,includedSkills:0,skillFrontmatter:[]}};let a=await tz([i],t,n),o=r.map(e=>({name:H3(e),source:e.type===`prompt`?e.source:`plugin`,tokens:Jit(e)}));return{skillTokens:a,skillInfo:{totalSkills:r.length,includedSkills:r.length,skillFrontmatter:o}}}catch(e){return J(tr(e)),{skillTokens:0,skillInfo:{totalSkills:0,includedSkills:0,skillFrontmatter:[]}}}}async function rz(e,t,n,r,i){let a=e.filter(e=>e.isMcp),o=[],s=await tz(a,t,n,r),c=Math.max(0,(s||0)-500),l=await Promise.all(a.map(async r=>b3(U({name:r.name,description:await r.prompt({getToolPermissionContext:t,tools:e,agents:n?.activeAgents??[]}),input_schema:r.inputJSONSchema??{}})))),u=l.reduce((e,t)=>e+t,0)||1,d=l.map(e=>Math.round(e/u*c)),{isSearchExtraToolsEnabled:f}=await import(`./searchExtraTools-D4gMMQv0.js`),{isDeferredTool:p}=await import(`./prompt-BKPmDAuL.js`),m=await f(r,e,t,n?.activeAgents??[],`analyzeMcp`),h=new Set;if(m&&i){let e=new Set(a.map(e=>e.name));for(let t of i)if(t.type===`assistant`&&Array.isArray(t.message.content))for(let n of t.message.content)typeof n!=`string`&&`type`in n&&n.type===`tool_use`&&`name`in n&&typeof n.name==`string`&&e.has(n.name)&&h.add(n.name)}for(let[e,t]of a.entries())o.push({name:t.name,serverName:t.name.split(`__`)[1]||`unknown`,tokens:d[e],isLoaded:h.has(t.name)||!p(t)});let g=0,_=0;for(let e of o)e.isLoaded?g+=e.tokens:m&&(_+=e.tokens);return{mcpToolTokens:m?g:c,mcpToolDetails:o,deferredToolTokens:_,loadedMcpToolNames:h}}async function TAe(e){let t=e.activeAgents.filter(e=>e.source!==`built-in`),n=[],r=0,i=await Promise.all(t.map(e=>ez([{role:`user`,content:[e.agentType,e.whenToUse].join(` `)}],[])));for(let[e,a]of t.entries()){let t=i[e]||0;r+=t||0,n.push({agentType:a.agentType,source:a.source,tokens:t||0})}return{agentTokens:r,agentDetails:n}}function EAe(e,t){let n=Array.isArray(e.message.content)?e.message.content:[];for(let e of n){let n=b3(U(e));if(typeof e!=`string`&&`type`in e&&e.type===`tool_use`){t.toolCallTokens+=n;let r=(`name`in e?e.name:void 0)||`unknown`;t.toolCallsByType.set(r,(t.toolCallsByType.get(r)||0)+n)}else t.assistantMessageTokens+=n}}function DAe(e,t,n){if(typeof e.message.content==`string`){let n=b3(e.message.content);t.userMessageTokens+=n;return}for(let r of e.message.content??[]){let e=b3(U(r));if(`type`in r&&r.type===`tool_result`){let i=`tool_use_id`in r?r.tool_use_id:void 0,a=(i?n.get(i):void 0)||`unknown`;t.toolResultsByType.set(a,(t.toolResultsByType.get(a)||0)+e)}else t.userMessageTokens+=e}}function OAe(e,t){let n=b3(U(e.attachment));t.attachmentTokens+=n;let r=e.attachment.type||`unknown`;t.attachmentsByType.set(r,(t.attachmentsByType.get(r)||0)+n)}async function kAe(e){let t=await OR(e),n={totalTokens:0,toolCallTokens:0,toolResultTokens:0,attachmentTokens:0,assistantMessageTokens:0,userMessageTokens:0,toolCallsByType:new Map,toolResultsByType:new Map,attachmentsByType:new Map},r=new Map;for(let e of t.messages)if(e.type===`assistant`&&Array.isArray(e.message.content)){for(let t of e.message.content)if(typeof t!=`string`&&`type`in t&&t.type===`tool_use`){let e=`id`in t?t.id:void 0,n=(`name`in t?t.name:void 0)||`unknown`;e&&r.set(e,n)}}for(let e of t.messages)e.type===`assistant`?EAe(e,n):e.type===`user`?DAe(e,n,r):e.type===`attachment`&&OAe(e,n);return n.totalTokens=await ez(c3(t.messages).map(e=>e.type===`assistant`?{role:`assistant`,content:e.message.content}:e.message),[])??0,n}async function AAe(t,n,r,i,a,o,s,c,l){let u=Vo({permissionMode:(await r()).mode,mainLoopModel:n}),d=Go(u,dn()),f=await F7(i,u),p=UR({mainThreadAgentDefinition:c,toolUseContext:s??{options:{}},customSystemPrompt:s?.options.customSystemPrompt,defaultSystemPrompt:f,appendSystemPrompt:s?.options.appendSystemPrompt}),[{systemPromptTokens:m,systemPromptSections:h},{agentsMdTokens:g,memoryFileDetails:_},{builtInToolTokens:v,deferredBuiltinDetails:y,deferredBuiltinTokens:b,systemToolDetails:x},{mcpToolTokens:S,mcpToolDetails:C,deferredToolTokens:w},{agentTokens:T,agentDetails:E},{slashCommandTokens:D,commandInfo:O},k]=await Promise.all([bAe(p),xAe(),SAe(i,r,a,u,t),rz(i,r,a,u,t),TAe(a),CAe(i,r,a),kAe(t)]),A=(await wAe(i,r,a)).skillInfo,ee=A.skillFrontmatter.reduce((e,t)=>e+t.tokens,0),te=k.totalTokens,ne=vJ(),re=ne?hJ(n)-bJ:void 0,ie=[];m>0&&ie.push({name:`System prompt`,tokens:m,color:`promptBorder`});let ae=v-ee;ae>0&&ie.push({name:`System tools`,tokens:ae,color:`inactive`}),S>0&&ie.push({name:`MCP tools`,tokens:S,color:`cyan_FOR_SUBAGENTS_ONLY`}),w>0&&ie.push({name:`MCP tools (deferred)`,tokens:w,color:`inactive`,isDeferred:!0}),b>0&&ie.push({name:`System tools (deferred)`,tokens:b,color:`inactive`,isDeferred:!0}),T>0&&ie.push({name:`Custom agents`,tokens:T,color:`permission`}),g>0&&ie.push({name:`Memory files`,tokens:g,color:`claude`}),ee>0&&ie.push({name:`Skills`,tokens:ee,color:`warning`}),te!==null&&te>0&&ie.push({name:`Messages`,tokens:te,color:`purple_FOR_SUBAGENTS_ONLY`});let j=ie.reduce((e,t)=>e+(t.isDeferred?0:t.tokens),0),oe=0;ne&&re!==void 0?(oe=d-re,ie.push({name:iz,tokens:oe,color:`inactive`})):ne||(oe=xJ,ie.push({name:az,tokens:oe,color:`inactive`}));let se=Math.max(0,d-j-oe);ie.push({name:`Free space`,tokens:se,color:`promptBorder`});let ce=j,M=qL(l??t),N=(M?M.input_tokens+M.cache_creation_input_tokens+M.cache_read_input_tokens:null)??ce,le=o&&o<80,ue=d>=1e6?le?5:20:le?5:10,de=d>=1e6?10:le?5:10,fe=ue*de,pe=ie.filter(e=>!e.isDeferred).map(e=>({...e,squares:e.name===`Free space`?Math.round(e.tokens/d*fe):Math.max(1,Math.round(e.tokens/d*fe)),percentageOfTotal:Math.round(e.tokens/d*100)}));function me(e){let t=[],n=e.tokens/d*fe,r=Math.floor(n),i=n-r;for(let n=0;n<e.squares;n++){let a=1;n===r&&i>0&&(a=i),t.push({color:e.color,isFilled:!0,categoryName:e.name,tokens:e.tokens,percentage:e.percentageOfTotal,squareFullness:a})}return t}let he=[],ge=pe.find(e=>e.name===iz||e.name===az),_e=pe.filter(e=>e.name!==iz&&e.name!==az&&e.name!==`Free space`);for(let e of _e){let t=me(e);for(let e of t)he.length<fe&&he.push(e)}let ve=ge?ge.squares:0,ye=ie.find(e=>e.name===`Free space`),be=fe-ve;for(;he.length<be;)he.push({color:`promptBorder`,isFilled:!0,categoryName:`Free space`,tokens:ye?.tokens||0,percentage:ye?Math.round(ye.tokens/d*100):0,squareFullness:1});if(ge){let e=me(ge);for(let t of e)he.length<fe&&he.push(t)}let xe=[];for(let e=0;e<de;e++)xe.push(he.slice(e*ue,(e+1)*ue));let Se=new Map;for(let[e,t]of k.toolCallsByType.entries()){let n=Se.get(e)||{callTokens:0,resultTokens:0};Se.set(e,{...n,callTokens:t})}for(let[e,t]of k.toolResultsByType.entries()){let n=Se.get(e)||{callTokens:0,resultTokens:0};Se.set(e,{...n,resultTokens:t})}let Ce=Array.from(Se.entries()).map(([e,{callTokens:t,resultTokens:n}])=>({name:e,callTokens:t,resultTokens:n})).sort((e,t)=>t.callTokens+t.resultTokens-(e.callTokens+e.resultTokens)),we=Array.from(k.attachmentsByType.entries()).map(([e,t])=>({name:e,tokens:t})).sort((e,t)=>t.tokens-e.tokens),Te={toolCallTokens:k.toolCallTokens,toolResultTokens:k.toolResultTokens,attachmentTokens:k.attachmentTokens,assistantMessageTokens:k.assistantMessageTokens,userMessageTokens:k.userMessageTokens,toolCallsByType:Ce,attachmentsByType:we};return{categories:ie,totalTokens:N,maxTokens:d,rawMaxTokens:d,percentage:Math.round(N/d*100),gridRows:xe,model:u,memoryFiles:_,mcpTools:C,deferredBuiltinTools:void 0,systemTools:void 0,systemPromptSections:void 0,agents:E,slashCommands:D>0?{totalCommands:O.totalCommands,includedCommands:O.includedCommands,tokens:D}:void 0,skills:ee>0?{totalSkills:A.totalSkills,includedSkills:A.includedSkills,tokens:ee,skillFrontmatter:A.skillFrontmatter}:void 0,autoCompactThreshold:re,isAutoCompactEnabled:ne,messageBreakdown:Te,apiUsage:M,...(()=>{if(!M)return{};let{calculateCacheHitRate:t,getCacheThreshold:n}=($R(),e(_Ae)),r=t(M);return r===null?{}:{cacheHitRate:r,cacheThreshold:n()}})()}}var iz,az,oz=n((()=>{B7(),MR(),Jt(),Q3(),HR(),CJ(),T3(),z3(),Ks(),Zs(),hb(),U7(),QN(),Bo(),Vn(),K(),g(),qn(),Ga(),h3(),Uo(),mr(),WR(),ZL(),iz=`Autocompact buffer`,az=`Compact buffer`}));function sz(e){let t=cz.get(e);if(t)return t;let n=Hee(e);return cz.set(e,n),n}var cz,lz=n((()=>{Nt(),cz=new WeakMap}));function uz(e){if(!e.startsWith(`auto:`))return null;let t=e.slice(5),n=parseInt(t,10);return isNaN(n)?(G(`Invalid ENABLE_SEARCH_EXTRA_TOOLS value "${e}": expected auto:N where N is a number.`),null):Math.max(0,Math.min(100,n))}function jAe(e){return e?e===`auto`||e.startsWith(`auto:`):!1}function dz(){let e=process.env.ENABLE_SEARCH_EXTRA_TOOLS;if(!e||e===`auto`)return Sz;let t=uz(e);return t===null?Sz:t}function fz(e){let t=Go(e,Te(e)),n=dz()/100;return Math.floor(t*n)}function pz(e){return Math.floor(fz(e)*Cz)}function mz(){if(h(process.env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS))return`standard`;let e=process.env.ENABLE_SEARCH_EXTRA_TOOLS,t=e?uz(e):null;return t===0?`tst`:t===100?`standard`:jAe(e)?`tst-auto`:h(e)?`tst`:f(process.env.ENABLE_SEARCH_EXTRA_TOOLS)?`standard`:`tst`}function hz(){let e=mz();return e===`standard`?(Tz||(Tz=!0,G(`[SearchExtraTools:optimistic] mode=${e}, ENABLE_SEARCH_EXTRA_TOOLS=${process.env.ENABLE_SEARCH_EXTRA_TOOLS}, result=false`)),!1):(Tz||(Tz=!0,G(`[SearchExtraTools:optimistic] mode=${e}, ENABLE_SEARCH_EXTRA_TOOLS=${process.env.ENABLE_SEARCH_EXTRA_TOOLS}, result=true`)),!0)}function gz(e){return e.some(e=>Cs(e,Hs))}async function MAe(e,t,n){let r=e.filter(e=>As(e));return r.length===0?0:(await Promise.all(r.map(async r=>{let i=await r.prompt({getToolPermissionContext:t,tools:e,agents:n}),a=r.inputJSONSchema?U(r.inputJSONSchema):r.inputSchema?U(sz(r.inputSchema)):``;return r.name.length+i.length+a.length}))).reduce((e,t)=>e+t,0)}async function _z(e,t,n,r,i){let a=Xr(t,e=>e.isMcp);function o(t,n,r,i){Y(`tengu_search_extra_tools_mode_decision`,{enabled:t,mode:n,reason:r,checkedModel:e,mcpToolCount:a,userType:process.env.USER_TYPE??`external`,...i})}if(!gz(t))return G(`Tool search disabled: SearchExtraToolsTool is not available (may have been disallowed via disallowedTools).`),o(!1,`standard`,`mcp_search_unavailable`),!1;let s=mz();switch(s){case`tst`:return o(!0,s,`tst_enabled`),!0;case`tst-auto`:{let{enabled:a,debugDescription:c,metrics:l}=await LAe(t,n,r,e);return a?(G(`Auto tool search enabled: ${c}`+(i?` [source: ${i}]`:``)),o(!0,s,`auto_above_threshold`,l),!0):(G(`Auto tool search disabled: ${c}`+(i?` [source: ${i}]`:``)),o(!1,s,`auto_below_threshold`,l),!1)}case`standard`:return o(!1,s,`standard_mode`),!1}}function vz(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_reference`}function NAe(e){return vz(e)&&`tool_name`in e&&typeof e.tool_name==`string`}function PAe(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_result`&&`content`in e&&Array.isArray(e.content)}function FAe(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_result`&&`content`in e&&typeof e.content==`string`}function IAe(e){let t=Ez.exec(e);return t?.[1]?t[1].split(`,`).map(e=>e.trim()).filter(Boolean):[]}function yz(e){let t=new Set,n=0;for(let r of e){if(r.type===`system`&&r.subtype===`compact_boundary`){let e=r.compactMetadata?.preCompactDiscoveredTools;if(e){for(let n of e)t.add(n);n+=e.length}continue}if(r.type===`attachment`&&r.attachment?.type===`deferred_tools_delta`){let e=r.attachment.addedNames??[];for(let n of e)t.add(n);continue}if(r.type!==`user`)continue;let e=r.message?.content;if(Array.isArray(e))for(let n of e){if(PAe(n))for(let e of n.content)NAe(e)&&t.add(e.tool_name);if(FAe(n)){let e=IAe(n.content);for(let n of e)t.add(n)}}}return t.size>0&&G(`Dynamic tool loading: found ${t.size} discovered tools in message history`+(n>0?` (${n} carried from compact boundary)`:``)),t}function bz(){return!1}function xz(e,t,n){let r=new Set,i=0,a=0,o=new Set;for(let e of t)if(e.type===`attachment`&&(i++,o.add(e.attachment.type),e.attachment.type===`deferred_tools_delta`)){a++;for(let t of e.attachment.addedNames)r.add(t);for(let t of e.attachment.removedNames)r.delete(t)}let s=e.filter(As),c=new Set(s.map(e=>e.name)),l=new Set(e.map(e=>e.name)),u=s.filter(e=>!r.has(e.name)),d=[];for(let e of r)c.has(e)||l.has(e)||d.push(e);return u.length===0&&d.length===0?null:(Y(`tengu_deferred_tools_pool_change`,{addedCount:u.length,removedCount:d.length,priorAnnouncedCount:r.size,messagesLength:t.length,attachmentCount:i,dtdCount:a,callSite:n?.callSite??`unknown`,querySource:n?.querySource??`unknown`,attachmentTypesSeen:[...o].sort().join(`,`)}),{addedNames:u.map(e=>e.name).sort(),addedLines:u.map(uoe).sort(),removedNames:d.sort()})}async function LAe(e,t,n,r){let i=await wz(e,t,n,r);if(i!==null){let e=fz(r);return{enabled:i>=e,debugDescription:`${i} tokens (threshold: ${e}, ${dz()}% of context)`,metrics:{deferredToolTokens:i,threshold:e}}}let a=await MAe(e,t,n),o=pz(r);return{enabled:a>=o,debugDescription:`${a} chars (threshold: ${o}, ${dz()}% of context) (char fallback)`,metrics:{deferredToolDescriptionChars:a,charThreshold:o}}}var Sz,Cz,wz,Tz,Ez,Dz=n((()=>{d(),oo(),Ks(),Bs(),oz(),Ar(),ve(),Bo(),K(),g(),mr(),lz(),Sz=10,Cz=2.5,wz=u(async(e,t,n,r)=>{let i=e.filter(e=>As(e));if(i.length===0)return 0;try{let e=await tz(i,t,{activeAgents:n,allAgents:n},r);return e===0?null:Math.max(0,e-500)}catch{return null}},e=>e.filter(e=>As(e)).map(e=>e.name).join(`,`)),Tz=!1,Ez=/^Found \d+ deferred tool\(s\): (.+)\.$/m}));function RAe(e){return e.map(e=>e.name).sort().join(`,`)}function zAe(e){let t=RAe(e);Pz!==t&&(G(`SearchExtraToolsTool: cache invalidated - deferred tools changed`),Fz.cache.clear?.(),Pz=t)}function BAe(){Fz.cache.clear?.(),Pz=null}function Oz(e,t,n,r,i){return{data:{matches:e,query:t,total_deferred_tools:n,...r&&r.length>0?{pending_mcp_servers:r}:{},...i&&i.length>0?{already_loaded:i}:{}}}}function kz(e){if(e.startsWith(`mcp__`)){let t=e.replace(/^mcp__/,``).toLowerCase();return{parts:t.split(`__`).flatMap(e=>e.split(`_`)).filter(Boolean),full:t.replace(/__/g,` `).replace(/_/g,` `),isMcp:!0}}let t=e.replace(/([a-z])([A-Z])/g,`$1 $2`).replace(/_/g,` `).toLowerCase().split(/\s+/).filter(Boolean);return{parts:t,full:t.join(` `),isMcp:!1}}function VAe(e){let t=new Map;for(let n of e)t.has(n)||t.set(n,RegExp(`\\b${Xa(n)}\\b`));return t}async function HAe(e,t,n,r){let i=e.toLowerCase().trim(),a=t.find(e=>e.name.toLowerCase()===i)??n.find(e=>e.name.toLowerCase()===i);if(a)return[a.name];if(i.startsWith(`mcp__`)&&i.length>5){let e=t.filter(e=>e.name.toLowerCase().startsWith(i)).slice(0,r).map(e=>e.name);if(e.length>0)return e}let o=i.split(/\s+/).filter(e=>e.length>0),s=[],c=[];for(let e of o)e.startsWith(`+`)&&e.length>1?s.push(e.slice(1)):c.push(e);let l=s.length>0?[...s,...c]:o,u=VAe(l),d=t;return s.length>0&&(d=(await Promise.all(t.map(async e=>{let t=kz(e.name),r=(await Fz(e.name,n)).toLowerCase(),i=e.searchHint?.toLowerCase()??``;return s.every(e=>{let n=u.get(e);return t.parts.includes(e)||t.parts.some(t=>t.includes(e))||n.test(r)||i&&n.test(i)})?e:null}))).filter(e=>e!==null)),(await Promise.all(d.map(async e=>{let t=kz(e.name),r=(await Fz(e.name,n)).toLowerCase(),i=e.searchHint?.toLowerCase()??``,a=0;for(let e of l){let n=u.get(e);t.parts.includes(e)?a+=t.isMcp?12:10:t.parts.some(t=>t.includes(e))&&(a+=t.isMcp?6:5),t.full.includes(e)&&a===0&&(a+=3),i&&n.test(i)&&(a+=4),n.test(r)&&(a+=2)}return{name:e.name,score:a}}))).filter(e=>e.score>0).sort((e,t)=>t.score-e.score).slice(0,r).map(e=>e.name)}var Az,jz,Mz,Nz,Pz,Fz,Iz,Lz=n((()=>{d(),Nt(),oo(),Ks(),K(),kt(),$a(),Dz(),Bs(),BF(),Az=Number(process.env.SEARCH_EXTRA_TOOLS_WEIGHT_KEYWORD??`0.4`),jz=Number(process.env.SEARCH_EXTRA_TOOLS_WEIGHT_TFIDF??`0.6`),Mz=V(()=>I({query:B().describe(`Query to find deferred tools. Use "select:<tool_name>" for direct selection, or keywords to search.`),max_results:z().optional().default(5).describe(`Maximum number of results to return (default: 5)`)})),Nz=V(()=>I({matches:L(B()),query:B(),total_deferred_tools:z(),pending_mcp_servers:L(B()).optional(),already_loaded:L(B()).optional()})),Pz=null,Fz=u(async(e,t)=>{let n=Ds(t,e);return n?n.prompt({getToolPermissionContext:async()=>({mode:`default`,additionalWorkingDirectories:new Map,alwaysAllowRules:{},alwaysDenyRules:{},alwaysAskRules:{},isBypassPermissionsModeAvailable:!1}),tools:t,agents:[]}):``},e=>e),Iz=Ns({isEnabled(){return hz()},isConcurrencySafe(){return!0},isReadOnly(){return!0},name:Hs,maxResultSizeChars:1e5,async description(){return noe()},async prompt(){return noe()},get inputSchema(){return Mz()},get outputSchema(){return Nz()},async call(e,{options:{tools:t},getAppState:n}){let{query:r,max_results:i=5}=e,a=t.filter(As);zAe(a);function o(){let e=n().mcp.clients.filter(e=>e.type===`pending`);return e.length>0?e.map(e=>e.name):void 0}function s(e,t){Y(`tengu_search_extra_tools_outcome`,{query:r,queryType:t,matchCount:e.length,totalDeferredTools:a.length,maxResults:i,hasMatches:e.length>0})}let c=r.match(/^select:(.+)$/i);if(c){let e=c[1].split(`,`).map(e=>e.trim()).filter(Boolean),n=[],i=[],l=[];for(let r of e){let e=Ds(a,r),o=e??Ds(t,r);o?n.includes(o.name)||(n.push(o.name),e||i.push(o.name)):l.push(r)}if(n.length===0){G(`SearchExtraToolsTool: select failed — none found: ${l.join(`, `)}`),s([],`select`);let e=o();return Oz([],r,a.length,e)}return l.length>0?G(`SearchExtraToolsTool: partial select — found: ${n.join(`, `)}, missing: ${l.join(`, `)}`):G(`SearchExtraToolsTool: selected ${n.join(`, `)}`),s(n,`select`),Oz(n,r,a.length,void 0,i.length>0?i:void 0)}let l=r.match(/^discover:(.+)$/i);if(l){let e=MF(l[1].trim(),await NF(a),i),t=e.map(e=>{let t=`**${e.name}** (score: ${e.score.toFixed(2)})\n${e.description}`;return e.inputSchema&&(t+=`\nSchema: ${JSON.stringify(e.inputSchema)}`),t});return t.length>0&&`${t.length}${t.join(`
|
|
866
866
|
|
|
867
867
|
`)}`,s(e.map(e=>e.name),`keyword`),Oz(e.map(e=>e.name),r,a.length)}let u=new Set(a.map(e=>e.name)),[d,f]=await Promise.all([HAe(r,a,t,i),NF(a)]),p=MF(r,f,i),m=new Map;d.forEach((e,t)=>{let n=(d.length-t)/d.length;m.set(e,(m.get(e)??0)+n*Az)}),p.forEach(e=>{m.set(e.name,(m.get(e.name)??0)+e.score*jz)});let h=[...m.entries()].sort((e,t)=>t[1]-e[1]).slice(0,i).map(([e])=>e),g=h.filter(e=>!u.has(e));if(G(`SearchExtraToolsTool: keyword search for "${r}", found ${h.length} matches`),s(h,`keyword`),h.length===0){let e=o();return Oz(h,r,a.length,e)}return Oz(h,r,a.length,void 0,g.length>0?g:void 0)},renderToolUseMessage(e){return e.query?`"${e.query}"`:null},userFacingName(){return`SearchExtraTools`},mapToolResultToToolResultBlockParam(e,t,n){if(e.matches.length===0){let n=`No matching deferred tools found`;return e.pending_mcp_servers&&e.pending_mcp_servers.length>0&&(n+=`. Some MCP servers are still connecting: ${e.pending_mcp_servers.join(`, `)}. Their tools will become available shortly — try searching again.`),{type:`tool_result`,tool_use_id:t,content:n}}let r=e.already_loaded??[],i=e.matches.filter(e=>!r.includes(e));if(i.length===0&&r.length>0)return{type:`tool_result`,tool_use_id:t,content:`No deferred tools found. ${r.join(`, `)} ${r.length===1?`is`:`are`} already loaded as core tool(s) — call directly, do NOT search for or wrap in ExecuteExtraTool. SearchExtraTools is only for discovering tools NOT already in your tool list.`};let a=[];return r.length>0&&a.push(`Already loaded as core tool(s): ${r.join(`, `)}. Call these directly using your normal tool interface — do NOT use ExecuteExtraTool for them.`),i.length>0&&a.push(`Found ${i.length} deferred tool(s): ${i.join(`, `)}.\nUse ExecuteExtraTool with {"tool_name": "<name>", "params": {...}} to invoke any of these deferred tools.`),{type:`tool_result`,tool_use_id:t,content:a.join(`
|
|
868
868
|
`)}}})}));function UAe(e){let t={toolRequests:new Map,toolResults:new Map,humanMessages:0,assistantMessages:0,localCommandOutputs:0,other:0,attachments:new Map,duplicateFileReads:new Map,total:0},n=new Map,r=new Map,i=new Map;return e.forEach(e=>{if(e.type===`attachment`){let n=e.attachment.type||`unknown`;t.attachments.set(n,(t.attachments.get(n)||0)+1)}}),c3(e).forEach(e=>{let{content:a}=e.message;if(typeof a==`string`){let n=b3(a);t.total+=n,e.type===`user`&&a.includes(`local-command-stdout`)?t.localCommandOutputs+=n:t[e.type===`user`?`humanMessages`:`assistantMessages`]+=n}else a.forEach(a=>WAe(a,e,t,n,r,i))}),i.forEach((e,n)=>{if(e.count>1){let r=Math.floor(e.totalTokens/e.count)*(e.count-1);t.duplicateFileReads.set(n,{count:e.count,tokens:r})}}),t}function WAe(e,t,n,r,i,a){let o=b3(U(e));switch(n.total+=o,e.type){case`text`:t.type===`user`&&`text`in e&&e.text.includes(`local-command-stdout`)?n.localCommandOutputs+=o:n[t.type===`user`?`humanMessages`:`assistantMessages`]+=o;break;case`tool_use`:if(`name`in e&&`id`in e){let t=e.name||`unknown`;if(Rz(n.toolRequests,t,o),r.set(e.id,t),t===`Read`&&`input`in e&&e.input&&typeof e.input==`object`&&`file_path`in e.input){let t=String(e.input.file_path);i.set(e.id,t)}}break;case`tool_result`:if(`tool_use_id`in e){let t=r.get(e.tool_use_id)||`unknown`;if(Rz(n.toolResults,t,o),t===`Read`){let t=i.get(e.tool_use_id);if(t){let e=a.get(t)||{count:0,totalTokens:0};a.set(t,{count:e.count+1,totalTokens:e.totalTokens+o})}}}break;case`image`:case`server_tool_use`:case`web_search_tool_result`:case`search_result`:case`document`:case`thinking`:case`redacted_thinking`:case`code_execution_tool_result`:case`mcp_tool_use`:case`mcp_tool_result`:case`container_upload`:case`web_fetch_tool_result`:case`bash_code_execution_tool_result`:case`text_editor_code_execution_tool_result`:case`tool_search_tool_result`:case`compaction`:n.other+=o;break}}function Rz(e,t,n){e.set(t,(e.get(t)||0)+n)}function GAe(e){let t={total_tokens:e.total,human_message_tokens:e.humanMessages,assistant_message_tokens:e.assistantMessages,local_command_output_tokens:e.localCommandOutputs,other_tokens:e.other};e.attachments.forEach((e,n)=>{t[`attachment_${n}_count`]=e}),e.toolRequests.forEach((e,n)=>{t[`tool_request_${n}_tokens`]=e}),e.toolResults.forEach((e,n)=>{t[`tool_result_${n}_tokens`]=e});let n=[...e.duplicateFileReads.values()].reduce((e,t)=>e+t.tokens,0);if(t.duplicate_read_tokens=n,t.duplicate_read_file_count=e.duplicateFileReads.size,e.total>0){t.human_message_percent=Math.round(e.humanMessages/e.total*100),t.assistant_message_percent=Math.round(e.assistantMessages/e.total*100),t.local_command_output_percent=Math.round(e.localCommandOutputs/e.total*100),t.duplicate_read_percent=Math.round(n/e.total*100);let r=[...e.toolRequests.values()].reduce((e,t)=>e+t,0),i=[...e.toolResults.values()].reduce((e,t)=>e+t,0);t.tool_request_percent=Math.round(r/e.total*100),t.tool_result_percent=Math.round(i/e.total*100),e.toolRequests.forEach((n,r)=>{t[`tool_request_${r}_percent`]=Math.round(n/e.total*100)}),e.toolResults.forEach((n,r)=>{t[`tool_result_${r}_percent`]=Math.round(n/e.total*100)})}return t}var KAe=n((()=>{T3(),h3(),mr()})),zz,qAe=n((()=>{zz=[`User`,`Project`,`Local`,`Managed`,`AutoMem`]}));function JAe(){Bz(),Jz=setInterval(()=>{ei(`debug`,`session_keepalive_heartbeat`,{refcount:Gz}),h(process.env.CLAUDE_CODE_REMOTE_SEND_KEEPALIVES)&&Wz?.()},Uz)}function YAe(){Bz(),Wz!==null&&(Yz=setTimeout(()=>{ei(`info`,`session_idle_30s`),Yz=null},Uz))}function Bz(){Yz!==null&&(clearTimeout(Yz),Yz=null)}function XAe(){h(process.env.CLAUDE_CODE_REMOTE_SEND_KEEPALIVES)&&Wz?.()}function ZAe(){return Wz!==null}function Vz(e){Gz++,Kz.set(e,(Kz.get(e)??0)+1),Gz===1&&(qz=Date.now(),Wz!==null&&Jz===null&&JAe()),Xz||(Xz=!0,ar(async()=>{ei(`info`,`session_activity_at_shutdown`,{refcount:Gz,active:Object.fromEntries(Kz),oldest_activity_ms:Gz>0&&qz!==null?Date.now()-qz:null})}))}function Hz(e){Gz>0&&Gz--;let t=(Kz.get(e)??0)-1;t>0?Kz.set(e,t):Kz.delete(e),Gz===0&&Jz!==null&&(clearInterval(Jz),Jz=null,YAe())}var Uz,Wz,Gz,Kz,qz,Jz,Yz,Xz,Zz=n((()=>{Hn(),ni(),g(),Uz=3e4,Wz=null,Gz=0,Kz=new Map,qz=null,Jz=null,Yz=null,Xz=!1}));function QAe(e){let t={PreToolUse:[],PostToolUse:[],PostToolUseFailure:[],PermissionDenied:[],Notification:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],StopFailure:[],SubagentStart:[],SubagentStop:[],PreCompact:[],PostCompact:[],PermissionRequest:[],Setup:[],TeammateIdle:[],TaskCreated:[],TaskCompleted:[],Elicitation:[],ElicitationResult:[],ConfigChange:[],WorktreeCreate:[],WorktreeRemove:[],InstructionsLoaded:[],CwdChanged:[],FileChanged:[]};if(!e.hooksConfig)return t;for(let[n,r]of Object.entries(e.hooksConfig)){let i=n;if(t[i])for(let n of r??[])n.hooks.length>0&&t[i].push({matcher:n.matcher,hooks:n.hooks,pluginRoot:e.path,pluginName:e.name,pluginId:e.source})}return t}function Qz(){rB.cache?.clear?.()}async function $z(){if(!On())return;let{enabled:e}=await F4(),t=new Set(e.map(e=>e.path)),n=On();if(!n)return;let r={};for(let[e,i]of Object.entries(n)){let n=(i??[]).filter(e=>`pluginRoot`in e&&t.has(e.pluginRoot));n.length>0&&(r[e]=n)}Nte(),cn(r)}function eB(){let e=fi(),t=zi(`policySettings`),n=e=>e?Object.fromEntries(Object.entries(e).sort()):{};return U({enabledPlugins:n(e.enabledPlugins),extraKnownMarketplaces:n(e.extraKnownMarketplaces),strictKnownMarketplaces:t?.strictKnownMarketplaces??[],blockedMarketplaces:t?.blockedMarketplaces??[]})}function $Ae(){tB||(tB=!0,nB=eB(),W_.subscribe(e=>{if(e===`policySettings`){let e=eB();if(e===nB){G(`Plugin hooks: skipping reload, plugin-affecting settings unchanged`);return}nB=e,G(`Plugin hooks: reloading due to plugin-affecting settings change`),N4(`loadPluginHooks: plugin-affecting settings changed`),Qz(),rB()}}))}var tB,nB,rB,iB=n((()=>{d(),Jt(),K(),G_(),vi(),mr(),I4(),tB=!1,rB=u(async()=>{let{enabled:e}=await F4(),t={PreToolUse:[],PostToolUse:[],PostToolUseFailure:[],PermissionDenied:[],Notification:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],StopFailure:[],SubagentStart:[],SubagentStop:[],PreCompact:[],PostCompact:[],PermissionRequest:[],Setup:[],TeammateIdle:[],TaskCreated:[],TaskCompleted:[],Elicitation:[],ElicitationResult:[],ConfigChange:[],WorktreeCreate:[],WorktreeRemove:[],InstructionsLoaded:[],CwdChanged:[],FileChanged:[]};for(let n of e){if(!n.hooksConfig)continue;G(`Loading hooks from plugin: ${n.name}`);let e=QAe(n);for(let n of Object.keys(e))t[n].push(...e[n])}Nte(),cn(t),G(`Registered ${Object.values(t).reduce((e,t)=>e+t.reduce((e,t)=>e+t.hooks.length,0),0)} hooks from ${e.length} plugins`)})}));function eje(){let e=oB;return oB=void 0,e}async function aB(e,{sessionId:t,agentType:n,model:r,forceSyncExecution:i}={}){if(v())return[];let a=[],o=[],s=[];if(hx())G(`Skipping plugin hooks - allowManagedHooksOnly is enabled`);else try{await fre(`load_plugin_hooks`,()=>rB())}catch(t){let n=t instanceof Error?Error(`Failed to load plugin hooks during ${e}: ${t.message}`):Error(`Failed to load plugin hooks during ${e}: ${String(t)}`);t instanceof Error&&t.stack&&(n.stack=t.stack),J(n);let r=t instanceof Error?t.message:String(t),i=``;i=r.includes(`Failed to clone`)||r.includes(`network`)||r.includes(`ETIMEDOUT`)||r.includes(`ENOTFOUND`)?`This appears to be a network issue. Check your internet connection and try again.`:r.includes(`Permission denied`)||r.includes(`EACCES`)||r.includes(`EPERM`)?`This appears to be a permissions issue. Check file permissions on ~/.workmate/plugins/`:r.includes(`Invalid`)||r.includes(`parse`)||r.includes(`JSON`)||r.includes(`schema`)?`This appears to be a configuration issue. Check your plugin settings in .workmate/settings.json`:`Please fix the plugin configuration or remove problematic plugins from your settings.`,G(`Warning: Failed to load plugin hooks. SessionStart hooks from plugins will not execute. Error: ${r}. ${i}`,{level:`warn`})}let c=n??Wt();for await(let n of llt(e,t,c,r,void 0,void 0,i))n.message&&a.push(n.message),n.additionalContexts&&n.additionalContexts.length>0&&o.push(...n.additionalContexts),n.initialUserMessage&&(oB=n.initialUserMessage),n.watchPaths&&n.watchPaths.length>0&&s.push(...n.watchPaths);if(s.length>0&&sye(s),o.length>0){let e=r2({type:`hook_additional_context`,content:o,hookName:`SessionStart`,toolUseID:`SessionStart`,hookEvent:`SessionStart`});a.push(e)}return a}async function tje(e,{forceSyncExecution:t}={}){if(v())return[];let n=[],r=[];if(hx())G(`Skipping plugin hooks - allowManagedHooksOnly is enabled`);else try{await rB()}catch(e){G(`Warning: Failed to load plugin hooks. Setup hooks from plugins will not execute. Error: ${e instanceof Error?e.message:String(e)}`,{level:`warn`})}for await(let i of ult(e,void 0,void 0,t))i.message&&n.push(i.message),i.additionalContexts&&i.additionalContexts.length>0&&r.push(...i.additionalContexts);if(r.length>0){let e=r2({type:`hook_additional_context`,content:r,hookName:`Setup`,toolUseID:`Setup`,hookEvent:`Setup`});n.push(e)}return n}var oB,sB=n((()=>{Jt(),m2(),K(),ni(),g(),kx(),bx(),g7(),Ga(),iB()}));async function nje(e,t){}var cB=n((()=>{}));function rje(e){let t=[],n=[],r;for(let i of e)i.type===`assistant`&&i.message.id!==r&&n.length>0?(t.push(n),n=[i]):n.push(i),i.type===`assistant`&&(r=i.message.id);return n.length>0&&t.push(n),t}var ije=n((()=>{}));function aje(e,t=`from`){let n=uB+(t===`up_to`?hB:mB);return e&&e.trim()!==``&&(n+=`\n\nAdditional Instructions:\n${e}`),n+=gB,n}function oje(e){let t=uB+pB;return e&&e.trim()!==``&&(t+=`\n\nAdditional Instructions:\n${e}`),t+=gB,t}function sje(e){let t=e;t=t.replace(/<analysis>[\s\S]*?<\/analysis>/,``);let n=t.match(/<summary>([\s\S]*?)<\/summary>/);if(n){let e=n[1]||``;t=t.replace(/<summary>[\s\S]*?<\/summary>/,`Summary:\n${e.trim()}`)}return t=t.replace(/\n\n+/g,`
|
|
@@ -1161,7 +1161,7 @@ https://github.com/highlightjs/highlight.js/issues/2277`),i=e,r=t),n===void 0&&(
|
|
|
1161
1161
|
`),`utf8`)),p=XW(s,a,f),m=a.length),p!==-1)return await zIe(e,s,c-u+p,m,n,l+ZW(s,0,p));c+=d;let h=Math.min(o,f);l+=ZW(s,0,f-h),u=h,s.copyWithin(0,f-u,f)}return{content:``,lineOffset:1,truncated:c>=eG}}async function YW(e){let t=Buffer.allocUnsafe($W),n=0;for(;;){if(n===t.length){let e=Buffer.allocUnsafe(Math.min(t.length*2,10493952));t.copy(e,0,0,n),t=e}let{bytesRead:r}=await e.read(t,n,t.length-n,n);if(r===0)break;if(n+=r,n>10485760)return null}return QW(t,n)}function XW(e,t,n){let r=e.indexOf(t);return r===-1||r+t.length>n?-1:r}function ZW(e,t,n){let r=0;for(let i=t;i<n;i++)e[i]===tG&&r++;return r}function QW(e,t){let n=e.toString(`utf8`,0,t);return n.includes(`\r`)?n.replaceAll(`\r
|
|
1162
1162
|
`,`
|
|
1163
1163
|
`):n}async function zIe(e,t,n,r,i,a){let o=Math.min(n,$W),{bytesRead:s}=await e.read(t,0,o,n-o),c=n,l=0;for(let e=s-1;e>=0&&l<=i&&!(t[e]===tG&&(l++,l>i));e--)c--;let u=a-ZW(t,s-(n-c),s)+1,d=n+r,{bytesRead:f}=await e.read(t,0,$W,d),p=d;l=0;for(let e=0;e<f&&(p++,!(t[e]===tG&&(l++,l>=i+1)));e++);let m=p-c,h=m<=t.length?t:Buffer.allocUnsafe(m),{bytesRead:g}=await e.read(h,0,m,c);return{content:QW(h,g),lineOffset:u,truncated:!1}}var $W,eG,tG,nG=n((()=>{qn(),$W=8*1024,eG=10*1024*1024,tG=10}));function rG(e){return e?e.file_path?.startsWith(Rd())?`Updated plan`:e.edits==null&&e.old_string===``?`Create`:`Update`:`Update`}function iG(e){return e?.file_path?Zi(e.file_path):null}function BIe({file_path:e},{verbose:t}){return e?e.startsWith(Rd())?``:(0,oG.jsx)(EC,{filePath:e,children:t?e:Zi(e)}):null}function VIe({filePath:e,structuredPatch:t,originalFile:n},r,{style:i,verbose:a}){let o=e.startsWith(Rd());return(0,oG.jsx)(WW,{filePath:e,structuredPatch:t,firstLine:n.split(`
|
|
1164
|
-
`)[0]??null,fileContent:n,style:i,verbose:a,previewHint:o?`/plan to preview`:void 0})}function HIe(e,t){let{style:n,verbose:r}=t,i=e.file_path,a=e.old_string??``,o=e.new_string??``,s=e.replace_all??!1;return`edits`in e&&e.edits!=null?(0,oG.jsx)(BW,{file_path:i,operation:`update`,firstLine:null,verbose:r}):a===``?(0,oG.jsx)(BW,{file_path:i,operation:`write`,content:o,firstLine:Ya(o),verbose:r}):(0,oG.jsx)(WIe,{filePath:i,oldString:a,newString:o,replaceAll:s,style:n,verbose:r})}function UIe(e,t){let{verbose:n}=t;return!n&&typeof e==`string`&&sy(e,`tool_use_error`)?sy(e,`tool_use_error`)?.includes(`Note: your current working directory is`)?(0,oG.jsx)($,{children:(0,oG.jsx)(F,{color:`error`,children:`File not found`})}):(0,oG.jsx)($,{children:(0,oG.jsx)(F,{color:`error`,children:`Error editing file`})}):(0,oG.jsx)(SC,{result:e,verbose:n})}function WIe({filePath:e,oldString:t,newString:n,replaceAll:r,style:i,verbose:a}){let[o]=(0,aG.useState)(()=>KIe(e,t,n,r));return(0,oG.jsx)(aG.Suspense,{fallback:(0,oG.jsx)(BW,{file_path:e,operation:`update`,firstLine:null,verbose:a}),children:(0,oG.jsx)(GIe,{promise:o,filePath:e,style:i,verbose:a})})}function GIe({promise:e,filePath:t,style:n,verbose:r}){let{patch:i,firstLine:a,fileContent:o}=(0,aG.use)(e);return(0,oG.jsx)(BW,{file_path:t,operation:`update`,patch:i,firstLine:a,fileContent:o,style:n,verbose:r})}async function KIe(e,t,n,r){try{let i=await RIe(e,t,3);if(i===null||i.truncated||i.content===``){let{patch:r}=rF({filePath:e,fileContents:t,oldString:t,newString:n});return{patch:r,firstLine:null,fileContent:void 0}}let a=nF(i.content,t)||t,{patch:o}=rF({filePath:e,fileContents:i.content,oldString:a,newString:n,replaceAll:r});return{patch:GP(o,i.lineOffset-1),firstLine:i.lineOffset===1?Ya(i.content):null,fileContent:i.content}}catch(e){return J(e),{patch:[],firstLine:null,fileContent:void 0}}}var aG,oG,sG=n((()=>{aG=r(tt(),1),UW(),_C(),h3(),TC(),KW(),ct(),DC(),eF(),Yi(),Ga(),zd(),nG(),$a(),sF(),oG=ut()}));function cG(e,t=``){return RegExp(`\\bgit(?:\\s+-[cC]\\s+\\S+|\\s+--\\S+=\\S+)*\\s+${e}\\b${t}`)}function qIe(e){let t=e.match(/https:\/\/github\.com\/([^/]+\/[^/]+)\/pull\/(\d+)/);return t?.[1]&&t?.[2]?{prNumber:parseInt(t[2],10),prUrl:e,prRepository:t[1]}:null}function lG(e){let t=e.match(/https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/\d+/);return t?qIe(t[0]):null}function uG(e){return e.match(/\[[\w./-]+(?: \(root-commit\))? ([0-9a-f]+)\]/)?.[1]}function JIe(e){return e.match(/^\s*[+\-*!= ]?\s*(?:\[new branch\]|\S+\.\.+\S+)\s+\S+\s*->\s*(\S+)/m)?.[1]}function YIe(e){let t=e.match(/[Pp]ull request (?:\S+#)?#?(\d+)/);return t?.[1]?parseInt(t[1],10):void 0}function dG(e,t){let n=e.split(cG(t))[1];if(n)for(let e of n.trim().split(/\s+/)){if(/^[&|;><]/.test(e))break;if(!e.startsWith(`-`))return e}}function XIe(e,t){let n={},r=hG.test(e);if(pG.test(e)||r){let i=uG(t);i&&(n.commit={sha:i.slice(0,6),kind:r?`cherry-picked`:/--amend\b/.test(e)?`amended`:`committed`})}if(mG.test(e)){let e=JIe(t);e&&(n.push={branch:e})}if(gG.test(e)&&/(Fast-forward|Merge made by)/.test(t)){let t=dG(e,`merge`);t&&(n.branch={ref:t,action:`merged`})}if(_G.test(e)&&/Successfully rebased/.test(t)){let t=dG(e,`rebase`);t&&(n.branch={ref:t,action:`rebased`})}let i=vG.find(t=>t.re.test(e))?.action;if(i){let e=lG(t);if(e)n.pr={number:e.prNumber,url:e.prUrl,action:i};else{let e=YIe(t);e&&(n.pr={number:e,action:i})}}return n}function fG(e,t,n){if(t!==0)return;pG.test(e)&&(Y(`tengu_git_operation`,{operation:`commit`}),e.match(/--amend\b/)&&Y(`tengu_git_operation`,{operation:`commit_amend`}),Yee()?.add(1)),mG.test(e)&&Y(`tengu_git_operation`,{operation:`push`});let r=vG.find(t=>t.re.test(e));if(r&&Y(`tengu_git_operation`,{operation:r.op}),r?.action===`created`&&(un()?.add(1),n)){let e=lG(n);e&&import(`./sessionStorage-BcAscOGE.js`).then(({linkSessionToPR:t})=>{import(`./state-BhOKSFi5.js`).then(({getSessionId:n})=>{let r=n();r&&t(r,e.prNumber,e.prUrl,e.prRepository)})})}e.match(/\bglab\s+mr\s+create\b/)&&(Y(`tengu_git_operation`,{operation:`pr_create`}),un()?.add(1));let i=e.match(/\bcurl\b/)&&(e.match(/-X\s*POST\b/i)||e.match(/--request\s*=?\s*POST\b/i)||e.match(/\s-d\s/)),a=e.match(/https?:\/\/[^\s'"]*\/(pulls|pull-requests|merge[-_]requests)(?!\/\d)/i);i&&a&&(Y(`tengu_git_operation`,{operation:`pr_create`}),un()?.add(1))}var pG,mG,hG,gG,_G,vG,yG=n((()=>{Jt(),oo(),pG=cG(`commit`),mG=cG(`push`),hG=cG(`cherry-pick`),gG=cG(`merge`,`(?!-)`),_G=cG(`rebase`),vG=[{re:/\bgh\s+pr\s+create\b/,action:`created`,op:`pr_create`},{re:/\bgh\s+pr\s+edit\b/,action:`edited`,op:`pr_edit`},{re:/\bgh\s+pr\s+merge\b/,action:`merged`,op:`pr_merge`},{re:/\bgh\s+pr\s+comment\b/,action:`commented`,op:`pr_comment`},{re:/\bgh\s+pr\s+close\b/,action:`closed`,op:`pr_close`},{re:/\bgh\s+pr\s+ready\b/,action:`ready`,op:`pr_ready`}]}));function ZIe(e){let t=$Ie(e),n=xG.get(t);return n===void 0?bG:n}function QIe(e){return e.trim().split(/\s+/)[0]||``}function $Ie(e){let t=i9(e);return QIe(t[t.length-1]||e)}function eLe(e,t,n,r){let i=ZIe(e)(t,n,r);return{isError:i.isError,message:i.message}}var bG,xG,tLe=n((()=>{h9(),bG=(e,t,n)=>({isError:e!==0,message:e===0?void 0:`Command failed with exit code ${e}`}),xG=new Map([[`grep`,(e,t,n)=>({isError:e>=2,message:e===1?`No matches found`:void 0})],[`rg`,(e,t,n)=>({isError:e>=2,message:e===1?`No matches found`:void 0})],[`find`,(e,t,n)=>({isError:e>=2,message:e===1?`Some directories were inaccessible`:void 0})],[`diff`,(e,t,n)=>({isError:e>=2,message:e===1?`Files differ`:void 0})],[`test`,(e,t,n)=>({isError:e>=2,message:e===1?`Condition is false`:void 0})],[`[`,(e,t,n)=>({isError:e>=2,message:e===1?`Condition is false`:void 0})]])}));function nLe(){return Br(H())??Yt()}function rLe(){return process.env.CLAUDE_CODE_ENTRYPOINT??`cli`}function SG(){return{fileStates:new Map,sessionBaselines:new Map,surface:rLe(),startingHeadSha:null,promptCount:0,promptCountAtLastCommit:0,permissionPromptCount:0,permissionPromptCountAtLastCommit:0,escapeCount:0,escapeCountAtLastCommit:0}}function iLe(e,t){let n={};for(let[t,r]of e.fileStates)n[t]=r;return{type:`attribution-snapshot`,messageId:t,surface:e.surface,fileStates:n,promptCount:e.promptCount,promptCountAtLastCommit:e.promptCountAtLastCommit,permissionPromptCount:e.permissionPromptCount,permissionPromptCountAtLastCommit:e.permissionPromptCountAtLastCommit,escapeCount:e.escapeCount,escapeCountAtLastCommit:e.escapeCountAtLastCommit}}function aLe(e,t){let n={...e,promptCount:e.promptCount+1};return t(iLe(n,Jc())),n}var CG,wG,TG=n((()=>{Jt(),Vn(),K(),va(),or(),Jr(),Ir(),Ga(),Uo(),tae(),CG=`github.com:anthropics/claude-cli-internal,github.com/anthropics/claude-cli-internal,github.com:anthropics/anthropic,github.com/anthropics/anthropic,github.com:anthropics/apps,github.com/anthropics/apps,github.com:anthropics/casino,github.com/anthropics/casino,github.com:anthropics/dbt,github.com/anthropics/dbt,github.com:anthropics/dotfiles,github.com/anthropics/dotfiles,github.com:anthropics/terraform-config,github.com/anthropics/terraform-config,github.com:anthropics/hex-export,github.com/anthropics/hex-export,github.com:anthropics/feedback-v2,github.com/anthropics/feedback-v2,github.com:anthropics/labs,github.com/anthropics/labs,github.com:anthropics/argo-rollouts,github.com/anthropics/argo-rollouts,github.com:anthropics/starling-configs,github.com/anthropics/starling-configs,github.com:anthropics/ts-tools,github.com/anthropics/ts-tools,github.com:anthropics/ts-capsules,github.com/anthropics/ts-capsules,github.com:anthropics/feldspar-testing,github.com/anthropics/feldspar-testing,github.com:anthropics/trellis,github.com/anthropics/trellis,github.com:anthropics/claude-for-hiring,github.com/anthropics/claude-for-hiring,github.com:anthropics/forge-web,github.com/anthropics/forge-web,github.com:anthropics/infra-manifests,github.com/anthropics/infra-manifests,github.com:anthropics/mycro_manifests,github.com/anthropics/mycro_manifests,github.com:anthropics/mycro_configs,github.com/anthropics/mycro_configs,github.com:anthropics/mobile-apps,github.com/anthropics/mobile-apps`.split(`,`),wG=null,Wie(async()=>{if(wG!==null)return wG===`internal`;let e=await Nne(nLe());if(!e)return wG=`none`,!1;let t=CG.some(t=>e.includes(t));return wG=t?`internal`:`external`,t})}));function oLe(e){let t=e.toLowerCase();for(let{keywords:e,email:n}of EG)if(e.some(e=>t.includes(e)))return n;return`noreply@anthropic.com`}var EG,sLe=n((()=>{EG=[{keywords:[`claude`],email:`noreply@anthropic.com`},{keywords:[`gpt`,`dall-e`,`o1-`,`o3-`,`o4-`],email:`openai@readmagic.workmate.win`},{keywords:[`gemini`],email:`google-gemini@readmagic.workmate.win`},{keywords:[`grok`],email:`xai-org@readmagic.workmate.win`},{keywords:[`glm`],email:`zai-org@readmagic.workmate.win`},{keywords:[`deepseek`],email:`deepseek-ai@readmagic.workmate.win`},{keywords:[`qwen`],email:`QwenLM@readmagic.workmate.win`},{keywords:[`minimax`],email:`MiniMax-AI@readmagic.workmate.win`},{keywords:[`mimo`],email:`XiaomiMiMo@readmagic.workmate.win`},{keywords:[`kimi`],email:`MoonshotAI@readmagic.workmate.win`}]}));function cLe(e){switch(Fo()){case`openai`:return _v(e);case`gemini`:return xv(e);case`grok`:return vv(e);default:return e}}function lLe(){return cLe(Xo())}var uLe=n((()=>{Nv(),Uo(),Io()})),DG,OG,kG,AG,jG=n((()=>{Nt(),kt(),iU(),DG=V(()=>xt({file_path:B().describe(`The absolute path to the file to modify`),old_string:B().describe(`The text to replace`),new_string:B().describe(`The text to replace it with (must be different from old_string)`),replace_all:rU(pt().default(!1).optional()).describe(`Replace all occurrences of old_string (default false)`)})),OG=V(()=>I({oldStart:z(),oldLines:z(),newStart:z(),newLines:z(),lines:L(B())})),kG=V(()=>I({filename:B(),status:ft([`modified`,`added`]),additions:z(),deletions:z(),changes:z(),patch:B(),repository:B().nullable().optional().describe(`GitHub owner/repo when available`)})),AG=V(()=>I({filePath:B().describe(`The file path that was edited`),oldString:B().describe(`The original string that was replaced`),newString:B().describe(`The new string that replaced it`),originalFile:B().describe(`The original file contents before editing`),structuredPatch:L(OG()).describe(`Diff patch showing the changes`),userModified:pt().describe(`Whether the user modified the proposed changes`),replaceAll:pt().describe(`Whether all occurrences were replaced`),gitDiff:kG().optional()}))}));function dLe({serverName:e,files:t}){let n=Jc();G(`LSP Diagnostics: Registering ${t.length} diagnostic file(s) from ${e} (ID: ${n})`),RG.set(n,{serverName:e,files:t,timestamp:Date.now(),attachmentSent:!1})}function MG(e){switch(e){case`Error`:return 1;case`Warning`:return 2;case`Info`:return 3;case`Hint`:return 4;default:return 4}}function NG(e){return U({message:e.message,severity:e.severity,range:e.range,source:e.source||null,code:e.code||null})}function fLe(e){let t=new Map,n=[];for(let r of e){t.has(r.uri)||(t.set(r.uri,new Set),n.push({uri:r.uri,diagnostics:[]}));let e=t.get(r.uri),i=n.find(e=>e.uri===r.uri),a=zG.get(r.uri)||new Set;for(let t of r.diagnostics)try{let n=NG(t);if(e.has(n)||a.has(n))continue;e.add(n),i.diagnostics.push(t)}catch(e){let n=tr(e),a=t.message?.substring(0,100)||`<no message>`;J(Error(`Failed to deduplicate diagnostic in ${r.uri}: ${n.message}. Diagnostic message: ${a}`)),i.diagnostics.push(t)}}return n.filter(e=>e.diagnostics.length>0)}function pLe(){G(`LSP Diagnostics: Checking registry - ${RG.size} pending`);let e=[],t=new Set,n=[];for(let r of RG.values())r.attachmentSent||(e.push(...r.files),t.add(r.serverName),n.push(r));if(e.length===0)return[];let r;try{r=fLe(e)}catch(t){let n=tr(t);J(Error(`Failed to deduplicate LSP diagnostics: ${n.message}`)),r=e}for(let e of n)e.attachmentSent=!0;for(let[e,t]of RG)t.attachmentSent&&RG.delete(e);let i=e.reduce((e,t)=>e+t.diagnostics.length,0),a=r.reduce((e,t)=>e+t.diagnostics.length,0);i>a&&G(`LSP Diagnostics: Deduplication removed ${i-a} duplicate diagnostic(s)`);let o=0,s=0;for(let e of r){e.diagnostics.sort((e,t)=>MG(e.severity)-MG(t.severity)),e.diagnostics.length>FG&&(s+=e.diagnostics.length-FG,e.diagnostics=e.diagnostics.slice(0,FG));let t=IG-o;e.diagnostics.length>t&&(s+=e.diagnostics.length-t,e.diagnostics=e.diagnostics.slice(0,t)),o+=e.diagnostics.length}r=r.filter(e=>e.diagnostics.length>0),s>0&&G(`LSP Diagnostics: Volume limiting removed ${s} diagnostic(s) (max ${FG}/file, ${IG} total)`);for(let e of r){zG.has(e.uri)||zG.set(e.uri,new Set);let t=zG.get(e.uri);for(let n of e.diagnostics)try{t.add(NG(n))}catch(t){let r=tr(t),i=n.message?.substring(0,100)||`<no message>`;J(Error(`Failed to track delivered diagnostic in ${e.uri}: ${r.message}. Diagnostic message: ${i}`))}}let c=r.reduce((e,t)=>e+t.diagnostics.length,0);return c===0?(G(`LSP Diagnostics: No new diagnostics to deliver (all filtered by deduplication)`),[]):(G(`LSP Diagnostics: Delivering ${r.length} file(s) with ${c} diagnostic(s) from ${t.size} server(s)`),[{serverName:Array.from(t).join(`, `),files:r}])}function mLe(){G(`LSP Diagnostics: Clearing ${RG.size} pending diagnostic(s)`),RG.clear()}function hLe(){G(`LSP Diagnostics: Resetting all state (${RG.size} pending, ${zG.size} files tracked)`),RG.clear(),zG.clear()}function PG(e){zG.has(e)&&(G(`LSP Diagnostics: Clearing delivered diagnostics for ${e}`),zG.delete(e))}var FG,IG,LG,RG,zG,BG=n((()=>{Tt(),K(),qn(),Ga(),mr(),FG=10,IG=30,LG=500,RG=new Map,zG=new Pt({max:LG})}));function gLe(e,t){let n=Oc(e),r=Oc(e,t),i=Dc(n,r);return i.startsWith(`..`)||Oc(i)===i?null:r}async function VG(e,t=[]){let n={},r=X(e.path,`.lsp.json`);try{let i=$n(await tl(r,`utf-8`)),a=St(B(),mi()).safeParse(i);if(a.success)Object.assign(n,a.data);else{let n=`LSP config validation failed for .lsp.json in plugin ${e.name}: ${a.error.message}`;J(Error(n)),t.push({type:`lsp-config-invalid`,plugin:e.name,serverName:`.lsp.json`,validationError:a.error.message,source:`plugin`})}}catch(n){Qn(n)||(n instanceof Error?`${e.name}${n.message}`:`${e.name}`,J(tr(n)),t.push({type:`lsp-config-invalid`,plugin:e.name,serverName:`.lsp.json`,validationError:n instanceof Error?`Failed to parse JSON: ${n.message}`:`Failed to parse JSON file`,source:`plugin`}))}if(e.manifest.lspServers){let r=await _Le(e.manifest.lspServers,e.path,e.name,t);r&&Object.assign(n,r)}return Object.keys(n).length>0?n:void 0}async function _Le(e,t,n,r){let i={},a=Array.isArray(e)?e:[e];for(let e of a)if(typeof e==`string`){let a=gLe(t,e);if(!a){let t=`Security: Path traversal attempt blocked in plugin ${n}: ${e}`;J(Error(t)),G(t,{level:`warn`}),r.push({type:`lsp-config-invalid`,plugin:n,serverName:e,validationError:`Invalid path: must be relative and within plugin directory`,source:`plugin`});continue}try{let t=$n(await tl(a,`utf-8`)),o=St(B(),mi()).safeParse(t);if(o.success)Object.assign(i,o.data);else{let t=`LSP config validation failed for ${e} in plugin ${n}: ${o.error.message}`;J(Error(t)),r.push({type:`lsp-config-invalid`,plugin:n,serverName:e,validationError:o.error.message,source:`plugin`})}}catch(t){t instanceof Error?`${e}${n}${t.message}`:`${e}${n}`,J(tr(t)),r.push({type:`lsp-config-invalid`,plugin:n,serverName:e,validationError:t instanceof Error?`Failed to parse JSON: ${t.message}`:`Failed to parse JSON file`,source:`plugin`})}}else for(let[t,a]of Object.entries(e)){let e=mi().safeParse(a);if(e.success)i[t]=e.data;else{let i=`LSP config validation failed for inline server "${t}" in plugin ${n}: ${e.error.message}`;J(Error(i)),r.push({type:`lsp-config-invalid`,plugin:n,serverName:t,validationError:e.error.message,source:`plugin`})}}return Object.keys(i).length>0?i:void 0}function vLe(e,t,n,r){let i=[],a=e=>{let r=Fk(e,t);n&&(r=Ik(r,n));let{expanded:a,missingVars:o}=$O(r);return i.push(...o),a},o={...e};o.command&&(o.command=a(o.command)),o.args&&(o.args=o.args.map(e=>a(e)));let s={CLAUDE_PLUGIN_ROOT:t.path,CLAUDE_PLUGIN_DATA:lb(t.source),...o.env||{}};for(let[e,t]of Object.entries(s))e!==`CLAUDE_PLUGIN_ROOT`&&e!==`CLAUDE_PLUGIN_DATA`&&(s[e]=a(t));if(o.env=s,o.workspaceFolder&&(o.workspaceFolder=a(o.workspaceFolder)),i.length>0){let e=`Missing environment variables in plugin LSP config: ${[...new Set(i)].join(`, `)}`;J(Error(e)),G(e,{level:`warn`})}return o}function yLe(e,t){let n={};for(let[r,i]of Object.entries(e)){let e=`plugin:${t}:${r}`;n[e]={...i,scope:`dynamic`,source:t}}return n}async function bLe(e,t=[]){if(!e.enabled)return;let n=e.lspServers||await VG(e,t);if(!n)return;let r=e.manifest.userConfig?Rk(Mk(e)):void 0,i={};for(let[a,o]of Object.entries(n))i[a]=vLe(o,e,r,t);return yLe(i,e.name)}var HG=n((()=>{Nt(),ek(),K(),qn(),Ga(),mr(),ub(),zk(),oi()}));async function xLe(){let e={};try{let{enabled:t}=await F4(),n=await Promise.all(t.map(async e=>{let t=[];try{return{plugin:e,scopedServers:await bLe(e,t),errors:t}}catch(n){return G(`Failed to load LSP servers for plugin ${e.name}: ${n}`,{level:`error`}),{plugin:e,scopedServers:void 0,errors:t}}}));for(let{plugin:t,scopedServers:r,errors:i}of n){let n=r?Object.keys(r).length:0;n>0&&(Object.assign(e,r),G(`Loaded ${n} LSP server(s) from plugin: ${t.name}`)),i.length>0&&G(`${i.length} error(s) loading LSP servers from plugin: ${t.name}`)}G(`Total LSP servers loaded: ${Object.keys(e).length}`)}catch(e){J(tr(e)),G(`Error loading LSP servers: ${W(e)}`)}return{servers:e}}var SLe=n((()=>{K(),qn(),Ga(),HG(),I4()})),UG=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.stringArray=e.array=e.func=e.error=e.number=e.string=e.boolean=void 0;function t(e){return e===!0||e===!1}e.boolean=t;function n(e){return typeof e==`string`||e instanceof String}e.string=n;function r(e){return typeof e==`number`||e instanceof Number}e.number=r;function i(e){return e instanceof Error}e.error=i;function a(e){return typeof e==`function`}e.func=a;function o(e){return Array.isArray(e)}e.array=o;function s(e){return o(e)&&e.every(e=>n(e))}e.stringArray=s})),WG=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Message=e.NotificationType9=e.NotificationType8=e.NotificationType7=e.NotificationType6=e.NotificationType5=e.NotificationType4=e.NotificationType3=e.NotificationType2=e.NotificationType1=e.NotificationType0=e.NotificationType=e.RequestType9=e.RequestType8=e.RequestType7=e.RequestType6=e.RequestType5=e.RequestType4=e.RequestType3=e.RequestType2=e.RequestType1=e.RequestType=e.RequestType0=e.AbstractMessageSignature=e.ParameterStructures=e.ResponseError=e.ErrorCodes=void 0;var t=UG(),n;(function(e){e.ParseError=-32700,e.InvalidRequest=-32600,e.MethodNotFound=-32601,e.InvalidParams=-32602,e.InternalError=-32603,e.jsonrpcReservedErrorRangeStart=-32099,e.serverErrorStart=-32099,e.MessageWriteError=-32099,e.MessageReadError=-32098,e.PendingResponseRejected=-32097,e.ConnectionInactive=-32096,e.ServerNotInitialized=-32002,e.UnknownErrorCode=-32001,e.jsonrpcReservedErrorRangeEnd=-32e3,e.serverErrorEnd=-32e3})(n||(e.ErrorCodes=n={})),e.ResponseError=class e extends Error{constructor(r,i,a){super(i),this.code=t.number(r)?r:n.UnknownErrorCode,this.data=a,Object.setPrototypeOf(this,e.prototype)}toJson(){let e={code:this.code,message:this.message};return this.data!==void 0&&(e.data=this.data),e}};var r=class e{constructor(e){this.kind=e}static is(t){return t===e.auto||t===e.byName||t===e.byPosition}toString(){return this.kind}};e.ParameterStructures=r,r.auto=new r(`auto`),r.byPosition=new r(`byPosition`),r.byName=new r(`byName`);var i=class{constructor(e,t){this.method=e,this.numberOfParams=t}get parameterStructures(){return r.auto}};e.AbstractMessageSignature=i,e.RequestType0=class extends i{constructor(e){super(e,0)}},e.RequestType=class extends i{constructor(e,t=r.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}},e.RequestType1=class extends i{constructor(e,t=r.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}},e.RequestType2=class extends i{constructor(e){super(e,2)}},e.RequestType3=class extends i{constructor(e){super(e,3)}},e.RequestType4=class extends i{constructor(e){super(e,4)}},e.RequestType5=class extends i{constructor(e){super(e,5)}},e.RequestType6=class extends i{constructor(e){super(e,6)}},e.RequestType7=class extends i{constructor(e){super(e,7)}},e.RequestType8=class extends i{constructor(e){super(e,8)}},e.RequestType9=class extends i{constructor(e){super(e,9)}},e.NotificationType=class extends i{constructor(e,t=r.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}},e.NotificationType0=class extends i{constructor(e){super(e,0)}},e.NotificationType1=class extends i{constructor(e,t=r.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}},e.NotificationType2=class extends i{constructor(e){super(e,2)}},e.NotificationType3=class extends i{constructor(e){super(e,3)}},e.NotificationType4=class extends i{constructor(e){super(e,4)}},e.NotificationType5=class extends i{constructor(e){super(e,5)}},e.NotificationType6=class extends i{constructor(e){super(e,6)}},e.NotificationType7=class extends i{constructor(e){super(e,7)}},e.NotificationType8=class extends i{constructor(e){super(e,8)}},e.NotificationType9=class extends i{constructor(e){super(e,9)}};var a;(function(e){function n(e){let n=e;return n&&t.string(n.method)&&(t.string(n.id)||t.number(n.id))}e.isRequest=n;function r(e){let n=e;return n&&t.string(n.method)&&e.id===void 0}e.isNotification=r;function i(e){let n=e;return n&&(n.result!==void 0||!!n.error)&&(t.string(n.id)||t.number(n.id)||n.id===null)}e.isResponse=i})(a||(e.Message=a={}))})),GG=a((e=>{var t;Object.defineProperty(e,"__esModule",{value:!0}),e.LRUCache=e.LinkedMap=e.Touch=void 0;var n;(function(e){e.None=0,e.First=1,e.AsOld=e.First,e.Last=2,e.AsNew=e.Last})(n||(e.Touch=n={}));var r=class{constructor(){this[t]=`LinkedMap`,this._map=new Map,this._head=void 0,this._tail=void 0,this._size=0,this._state=0}clear(){this._map.clear(),this._head=void 0,this._tail=void 0,this._size=0,this._state++}isEmpty(){return!this._head&&!this._tail}get size(){return this._size}get first(){return this._head?.value}get last(){return this._tail?.value}has(e){return this._map.has(e)}get(e,t=n.None){let r=this._map.get(e);if(r)return t!==n.None&&this.touch(r,t),r.value}set(e,t,r=n.None){let i=this._map.get(e);if(i)i.value=t,r!==n.None&&this.touch(i,r);else{switch(i={key:e,value:t,next:void 0,previous:void 0},r){case n.None:this.addItemLast(i);break;case n.First:this.addItemFirst(i);break;case n.Last:this.addItemLast(i);break;default:this.addItemLast(i);break}this._map.set(e,i),this._size++}return this}delete(e){return!!this.remove(e)}remove(e){let t=this._map.get(e);if(t)return this._map.delete(e),this.removeItem(t),this._size--,t.value}shift(){if(!this._head&&!this._tail)return;if(!this._head||!this._tail)throw Error(`Invalid list`);let e=this._head;return this._map.delete(e.key),this.removeItem(e),this._size--,e.value}forEach(e,t){let n=this._state,r=this._head;for(;r;){if(t?e.bind(t)(r.value,r.key,this):e(r.value,r.key,this),this._state!==n)throw Error(`LinkedMap got modified during iteration.`);r=r.next}}keys(){let e=this._state,t=this._head,n={[Symbol.iterator]:()=>n,next:()=>{if(this._state!==e)throw Error(`LinkedMap got modified during iteration.`);if(t){let e={value:t.key,done:!1};return t=t.next,e}else return{value:void 0,done:!0}}};return n}values(){let e=this._state,t=this._head,n={[Symbol.iterator]:()=>n,next:()=>{if(this._state!==e)throw Error(`LinkedMap got modified during iteration.`);if(t){let e={value:t.value,done:!1};return t=t.next,e}else return{value:void 0,done:!0}}};return n}entries(){let e=this._state,t=this._head,n={[Symbol.iterator]:()=>n,next:()=>{if(this._state!==e)throw Error(`LinkedMap got modified during iteration.`);if(t){let e={value:[t.key,t.value],done:!1};return t=t.next,e}else return{value:void 0,done:!0}}};return n}[(t=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}trimOld(e){if(e>=this.size)return;if(e===0){this.clear();return}let t=this._head,n=this.size;for(;t&&n>e;)this._map.delete(t.key),t=t.next,n--;this._head=t,this._size=n,t&&(t.previous=void 0),this._state++}addItemFirst(e){if(!this._head&&!this._tail)this._tail=e;else if(this._head)e.next=this._head,this._head.previous=e;else throw Error(`Invalid list`);this._head=e,this._state++}addItemLast(e){if(!this._head&&!this._tail)this._head=e;else if(this._tail)e.previous=this._tail,this._tail.next=e;else throw Error(`Invalid list`);this._tail=e,this._state++}removeItem(e){if(e===this._head&&e===this._tail)this._head=void 0,this._tail=void 0;else if(e===this._head){if(!e.next)throw Error(`Invalid list`);e.next.previous=void 0,this._head=e.next}else if(e===this._tail){if(!e.previous)throw Error(`Invalid list`);e.previous.next=void 0,this._tail=e.previous}else{let t=e.next,n=e.previous;if(!t||!n)throw Error(`Invalid list`);t.previous=n,n.next=t}e.next=void 0,e.previous=void 0,this._state++}touch(e,t){if(!this._head||!this._tail)throw Error(`Invalid list`);if(!(t!==n.First&&t!==n.Last)){if(t===n.First){if(e===this._head)return;let t=e.next,n=e.previous;e===this._tail?(n.next=void 0,this._tail=n):(t.previous=n,n.next=t),e.previous=void 0,e.next=this._head,this._head.previous=e,this._head=e,this._state++}else if(t===n.Last){if(e===this._tail)return;let t=e.next,n=e.previous;e===this._head?(t.previous=void 0,this._head=t):(t.previous=n,n.next=t),e.next=void 0,e.previous=this._tail,this._tail.next=e,this._tail=e,this._state++}}}toJSON(){let e=[];return this.forEach((t,n)=>{e.push([n,t])}),e}fromJSON(e){this.clear();for(let[t,n]of e)this.set(t,n)}};e.LinkedMap=r,e.LRUCache=class extends r{constructor(e,t=1){super(),this._limit=e,this._ratio=Math.min(Math.max(0,t),1)}get limit(){return this._limit}set limit(e){this._limit=e,this.checkTrim()}get ratio(){return this._ratio}set ratio(e){this._ratio=Math.min(Math.max(0,e),1),this.checkTrim()}get(e,t=n.AsNew){return super.get(e,t)}peek(e){return super.get(e,n.None)}set(e,t){return super.set(e,t,n.Last),this.checkTrim(),this}checkTrim(){this.size>this._limit&&this.trimOld(Math.round(this._limit*this._ratio))}}})),CLe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Disposable=void 0;var t;(function(e){function t(e){return{dispose:e}}e.create=t})(t||(e.Disposable=t={}))})),KG=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t;function n(){if(t===void 0)throw Error(`No runtime abstraction layer installed`);return t}(function(e){function n(e){if(e===void 0)throw Error(`No runtime abstraction layer provided`);t=e}e.install=n})(n||(n={})),e.default=n})),qG=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Emitter=e.Event=void 0;var t=KG(),n;(function(e){let t={dispose(){}};e.None=function(){return t}})(n||(e.Event=n={}));var r=class{add(e,t=null,n){this._callbacks||(this._callbacks=[],this._contexts=[]),this._callbacks.push(e),this._contexts.push(t),Array.isArray(n)&&n.push({dispose:()=>this.remove(e,t)})}remove(e,t=null){if(!this._callbacks)return;let n=!1;for(let r=0,i=this._callbacks.length;r<i;r++)if(this._callbacks[r]===e)if(this._contexts[r]===t){this._callbacks.splice(r,1),this._contexts.splice(r,1);return}else n=!0;if(n)throw Error(`When adding a listener with a context, you should remove it with the same context`)}invoke(...e){if(!this._callbacks)return[];let n=[],r=this._callbacks.slice(0),i=this._contexts.slice(0);for(let a=0,o=r.length;a<o;a++)try{n.push(r[a].apply(i[a],e))}catch(e){(0,t.default)().console.error(e)}return n}isEmpty(){return!this._callbacks||this._callbacks.length===0}dispose(){this._callbacks=void 0,this._contexts=void 0}},i=class e{constructor(e){this._options=e}get event(){return this._event||(this._event=(t,n,i)=>{this._callbacks||(this._callbacks=new r),this._options&&this._options.onFirstListenerAdd&&this._callbacks.isEmpty()&&this._options.onFirstListenerAdd(this),this._callbacks.add(t,n);let a={dispose:()=>{this._callbacks&&(this._callbacks.remove(t,n),a.dispose=e._noop,this._options&&this._options.onLastListenerRemove&&this._callbacks.isEmpty()&&this._options.onLastListenerRemove(this))}};return Array.isArray(i)&&i.push(a),a}),this._event}fire(e){this._callbacks&&this._callbacks.invoke.call(this._callbacks,e)}dispose(){this._callbacks&&(this._callbacks.dispose(),this._callbacks=void 0)}};e.Emitter=i,i._noop=function(){}})),JG=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CancellationTokenSource=e.CancellationToken=void 0;var t=KG(),n=UG(),r=qG(),i;(function(e){e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:r.Event.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:r.Event.None});function t(t){let r=t;return r&&(r===e.None||r===e.Cancelled||n.boolean(r.isCancellationRequested)&&!!r.onCancellationRequested)}e.is=t})(i||(e.CancellationToken=i={}));var a=Object.freeze(function(e,n){let r=(0,t.default)().timer.setTimeout(e.bind(n),0);return{dispose(){r.dispose()}}}),o=class{constructor(){this._isCancelled=!1}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?a:(this._emitter||(this._emitter=new r.Emitter),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=void 0)}};e.CancellationTokenSource=class{get token(){return this._token||(this._token=new o),this._token}cancel(){this._token?this._token.cancel():this._token=i.Cancelled}dispose(){this._token?this._token instanceof o&&this._token.dispose():this._token=i.None}}})),wLe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SharedArrayReceiverStrategy=e.SharedArraySenderStrategy=void 0;var t=JG(),n;(function(e){e.Continue=0,e.Cancelled=1})(n||(n={})),e.SharedArraySenderStrategy=class{constructor(){this.buffers=new Map}enableCancellation(e){if(e.id===null)return;let t=new SharedArrayBuffer(4),r=new Int32Array(t,0,1);r[0]=n.Continue,this.buffers.set(e.id,t),e.$cancellationData=t}async sendCancellation(e,t){let r=this.buffers.get(t);if(r===void 0)return;let i=new Int32Array(r,0,1);Atomics.store(i,0,n.Cancelled)}cleanup(e){this.buffers.delete(e)}dispose(){this.buffers.clear()}};var r=class{constructor(e){this.data=new Int32Array(e,0,1)}get isCancellationRequested(){return Atomics.load(this.data,0)===n.Cancelled}get onCancellationRequested(){throw Error(`Cancellation over SharedArrayBuffer doesn't support cancellation events`)}},i=class{constructor(e){this.token=new r(e)}cancel(){}dispose(){}};e.SharedArrayReceiverStrategy=class{constructor(){this.kind=`request`}createCancellationTokenSource(e){let n=e.$cancellationData;return n===void 0?new t.CancellationTokenSource:new i(n)}}})),YG=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Semaphore=void 0;var t=KG();e.Semaphore=class{constructor(e=1){if(e<=0)throw Error(`Capacity must be greater than 0`);this._capacity=e,this._active=0,this._waiting=[]}lock(e){return new Promise((t,n)=>{this._waiting.push({thunk:e,resolve:t,reject:n}),this.runNext()})}get active(){return this._active}runNext(){this._waiting.length===0||this._active===this._capacity||(0,t.default)().timer.setImmediate(()=>this.doRunNext())}doRunNext(){if(this._waiting.length===0||this._active===this._capacity)return;let e=this._waiting.shift();if(this._active++,this._active>this._capacity)throw Error(`To many thunks active`);try{let t=e.thunk();t instanceof Promise?t.then(t=>{this._active--,e.resolve(t),this.runNext()},t=>{this._active--,e.reject(t),this.runNext()}):(this._active--,e.resolve(t),this.runNext())}catch(t){this._active--,e.reject(t),this.runNext()}}}})),TLe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ReadableStreamMessageReader=e.AbstractMessageReader=e.MessageReader=void 0;var t=KG(),n=UG(),r=qG(),i=YG(),a;(function(e){function t(e){let t=e;return t&&n.func(t.listen)&&n.func(t.dispose)&&n.func(t.onError)&&n.func(t.onClose)&&n.func(t.onPartialMessage)}e.is=t})(a||(e.MessageReader=a={}));var o=class{constructor(){this.errorEmitter=new r.Emitter,this.closeEmitter=new r.Emitter,this.partialMessageEmitter=new r.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError(e){this.errorEmitter.fire(this.asError(e))}get onClose(){return this.closeEmitter.event}fireClose(){this.closeEmitter.fire(void 0)}get onPartialMessage(){return this.partialMessageEmitter.event}firePartialMessage(e){this.partialMessageEmitter.fire(e)}asError(e){return e instanceof Error?e:Error(`Reader received error. Reason: ${n.string(e.message)?e.message:`unknown`}`)}};e.AbstractMessageReader=o;var s;(function(e){function n(e){let n,r,i=new Map,a,o=new Map;if(e===void 0||typeof e==`string`)n=e??`utf-8`;else{if(n=e.charset??`utf-8`,e.contentDecoder!==void 0&&(r=e.contentDecoder,i.set(r.name,r)),e.contentDecoders!==void 0)for(let t of e.contentDecoders)i.set(t.name,t);if(e.contentTypeDecoder!==void 0&&(a=e.contentTypeDecoder,o.set(a.name,a)),e.contentTypeDecoders!==void 0)for(let t of e.contentTypeDecoders)o.set(t.name,t)}return a===void 0&&(a=(0,t.default)().applicationJson.decoder,o.set(a.name,a)),{charset:n,contentDecoder:r,contentDecoders:i,contentTypeDecoder:a,contentTypeDecoders:o}}e.fromOptions=n})(s||(s={})),e.ReadableStreamMessageReader=class extends o{constructor(e,n){super(),this.readable=e,this.options=s.fromOptions(n),this.buffer=(0,t.default)().messageBuffer.create(this.options.charset),this._partialMessageTimeout=1e4,this.nextMessageLength=-1,this.messageToken=0,this.readSemaphore=new i.Semaphore(1)}set partialMessageTimeout(e){this._partialMessageTimeout=e}get partialMessageTimeout(){return this._partialMessageTimeout}listen(e){this.nextMessageLength=-1,this.messageToken=0,this.partialMessageTimer=void 0,this.callback=e;let t=this.readable.onData(e=>{this.onData(e)});return this.readable.onError(e=>this.fireError(e)),this.readable.onClose(()=>this.fireClose()),t}onData(e){try{for(this.buffer.append(e);;){if(this.nextMessageLength===-1){let e=this.buffer.tryReadHeaders(!0);if(!e)return;let t=e.get(`content-length`);if(!t){this.fireError(Error(`Header must provide a Content-Length property.\n${JSON.stringify(Object.fromEntries(e))}`));return}let n=parseInt(t);if(isNaN(n)){this.fireError(Error(`Content-Length value must be a number. Got ${t}`));return}this.nextMessageLength=n}let e=this.buffer.tryReadBody(this.nextMessageLength);if(e===void 0){this.setPartialMessageTimer();return}this.clearPartialMessageTimer(),this.nextMessageLength=-1,this.readSemaphore.lock(async()=>{let t=this.options.contentDecoder===void 0?e:await this.options.contentDecoder.decode(e),n=await this.options.contentTypeDecoder.decode(t,this.options);this.callback(n)}).catch(e=>{this.fireError(e)})}}catch(e){this.fireError(e)}}clearPartialMessageTimer(){this.partialMessageTimer&&(this.partialMessageTimer.dispose(),this.partialMessageTimer=void 0)}setPartialMessageTimer(){this.clearPartialMessageTimer(),!(this._partialMessageTimeout<=0)&&(this.partialMessageTimer=(0,t.default)().timer.setTimeout((e,t)=>{this.partialMessageTimer=void 0,e===this.messageToken&&(this.firePartialMessage({messageToken:e,waitingTime:t}),this.setPartialMessageTimer())},this._partialMessageTimeout,this.messageToken,this._partialMessageTimeout))}}})),ELe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.WriteableStreamMessageWriter=e.AbstractMessageWriter=e.MessageWriter=void 0;var t=KG(),n=UG(),r=YG(),i=qG(),a=`Content-Length: `,o=`\r
|
|
1164
|
+
`)[0]??null,fileContent:n,style:i,verbose:a,previewHint:o?`/plan to preview`:void 0})}function HIe(e,t){let{style:n,verbose:r}=t,i=e.file_path,a=e.old_string??``,o=e.new_string??``,s=e.replace_all??!1;return`edits`in e&&e.edits!=null?(0,oG.jsx)(BW,{file_path:i,operation:`update`,firstLine:null,verbose:r}):a===``?(0,oG.jsx)(BW,{file_path:i,operation:`write`,content:o,firstLine:Ya(o),verbose:r}):(0,oG.jsx)(WIe,{filePath:i,oldString:a,newString:o,replaceAll:s,style:n,verbose:r})}function UIe(e,t){let{verbose:n}=t;return!n&&typeof e==`string`&&sy(e,`tool_use_error`)?sy(e,`tool_use_error`)?.includes(`Note: your current working directory is`)?(0,oG.jsx)($,{children:(0,oG.jsx)(F,{color:`error`,children:`File not found`})}):(0,oG.jsx)($,{children:(0,oG.jsx)(F,{color:`error`,children:`Error editing file`})}):(0,oG.jsx)(SC,{result:e,verbose:n})}function WIe({filePath:e,oldString:t,newString:n,replaceAll:r,style:i,verbose:a}){let[o]=(0,aG.useState)(()=>KIe(e,t,n,r));return(0,oG.jsx)(aG.Suspense,{fallback:(0,oG.jsx)(BW,{file_path:e,operation:`update`,firstLine:null,verbose:a}),children:(0,oG.jsx)(GIe,{promise:o,filePath:e,style:i,verbose:a})})}function GIe({promise:e,filePath:t,style:n,verbose:r}){let{patch:i,firstLine:a,fileContent:o}=(0,aG.use)(e);return(0,oG.jsx)(BW,{file_path:t,operation:`update`,patch:i,firstLine:a,fileContent:o,style:n,verbose:r})}async function KIe(e,t,n,r){try{let i=await RIe(e,t,3);if(i===null||i.truncated||i.content===``){let{patch:r}=rF({filePath:e,fileContents:t,oldString:t,newString:n});return{patch:r,firstLine:null,fileContent:void 0}}let a=nF(i.content,t)||t,{patch:o}=rF({filePath:e,fileContents:i.content,oldString:a,newString:n,replaceAll:r});return{patch:GP(o,i.lineOffset-1),firstLine:i.lineOffset===1?Ya(i.content):null,fileContent:i.content}}catch(e){return J(e),{patch:[],firstLine:null,fileContent:void 0}}}var aG,oG,sG=n((()=>{aG=r(tt(),1),UW(),_C(),h3(),TC(),KW(),ct(),DC(),eF(),Yi(),Ga(),zd(),nG(),$a(),sF(),oG=ut()}));function cG(e,t=``){return RegExp(`\\bgit(?:\\s+-[cC]\\s+\\S+|\\s+--\\S+=\\S+)*\\s+${e}\\b${t}`)}function qIe(e){let t=e.match(/https:\/\/github\.com\/([^/]+\/[^/]+)\/pull\/(\d+)/);return t?.[1]&&t?.[2]?{prNumber:parseInt(t[2],10),prUrl:e,prRepository:t[1]}:null}function lG(e){let t=e.match(/https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/\d+/);return t?qIe(t[0]):null}function uG(e){return e.match(/\[[\w./-]+(?: \(root-commit\))? ([0-9a-f]+)\]/)?.[1]}function JIe(e){return e.match(/^\s*[+\-*!= ]?\s*(?:\[new branch\]|\S+\.\.+\S+)\s+\S+\s*->\s*(\S+)/m)?.[1]}function YIe(e){let t=e.match(/[Pp]ull request (?:\S+#)?#?(\d+)/);return t?.[1]?parseInt(t[1],10):void 0}function dG(e,t){let n=e.split(cG(t))[1];if(n)for(let e of n.trim().split(/\s+/)){if(/^[&|;><]/.test(e))break;if(!e.startsWith(`-`))return e}}function XIe(e,t){let n={},r=hG.test(e);if(pG.test(e)||r){let i=uG(t);i&&(n.commit={sha:i.slice(0,6),kind:r?`cherry-picked`:/--amend\b/.test(e)?`amended`:`committed`})}if(mG.test(e)){let e=JIe(t);e&&(n.push={branch:e})}if(gG.test(e)&&/(Fast-forward|Merge made by)/.test(t)){let t=dG(e,`merge`);t&&(n.branch={ref:t,action:`merged`})}if(_G.test(e)&&/Successfully rebased/.test(t)){let t=dG(e,`rebase`);t&&(n.branch={ref:t,action:`rebased`})}let i=vG.find(t=>t.re.test(e))?.action;if(i){let e=lG(t);if(e)n.pr={number:e.prNumber,url:e.prUrl,action:i};else{let e=YIe(t);e&&(n.pr={number:e,action:i})}}return n}function fG(e,t,n){if(t!==0)return;pG.test(e)&&(Y(`tengu_git_operation`,{operation:`commit`}),e.match(/--amend\b/)&&Y(`tengu_git_operation`,{operation:`commit_amend`}),Yee()?.add(1)),mG.test(e)&&Y(`tengu_git_operation`,{operation:`push`});let r=vG.find(t=>t.re.test(e));if(r&&Y(`tengu_git_operation`,{operation:r.op}),r?.action===`created`&&(un()?.add(1),n)){let e=lG(n);e&&import(`./sessionStorage-C_7gow_z.js`).then(({linkSessionToPR:t})=>{import(`./state-BhOKSFi5.js`).then(({getSessionId:n})=>{let r=n();r&&t(r,e.prNumber,e.prUrl,e.prRepository)})})}e.match(/\bglab\s+mr\s+create\b/)&&(Y(`tengu_git_operation`,{operation:`pr_create`}),un()?.add(1));let i=e.match(/\bcurl\b/)&&(e.match(/-X\s*POST\b/i)||e.match(/--request\s*=?\s*POST\b/i)||e.match(/\s-d\s/)),a=e.match(/https?:\/\/[^\s'"]*\/(pulls|pull-requests|merge[-_]requests)(?!\/\d)/i);i&&a&&(Y(`tengu_git_operation`,{operation:`pr_create`}),un()?.add(1))}var pG,mG,hG,gG,_G,vG,yG=n((()=>{Jt(),oo(),pG=cG(`commit`),mG=cG(`push`),hG=cG(`cherry-pick`),gG=cG(`merge`,`(?!-)`),_G=cG(`rebase`),vG=[{re:/\bgh\s+pr\s+create\b/,action:`created`,op:`pr_create`},{re:/\bgh\s+pr\s+edit\b/,action:`edited`,op:`pr_edit`},{re:/\bgh\s+pr\s+merge\b/,action:`merged`,op:`pr_merge`},{re:/\bgh\s+pr\s+comment\b/,action:`commented`,op:`pr_comment`},{re:/\bgh\s+pr\s+close\b/,action:`closed`,op:`pr_close`},{re:/\bgh\s+pr\s+ready\b/,action:`ready`,op:`pr_ready`}]}));function ZIe(e){let t=$Ie(e),n=xG.get(t);return n===void 0?bG:n}function QIe(e){return e.trim().split(/\s+/)[0]||``}function $Ie(e){let t=i9(e);return QIe(t[t.length-1]||e)}function eLe(e,t,n,r){let i=ZIe(e)(t,n,r);return{isError:i.isError,message:i.message}}var bG,xG,tLe=n((()=>{h9(),bG=(e,t,n)=>({isError:e!==0,message:e===0?void 0:`Command failed with exit code ${e}`}),xG=new Map([[`grep`,(e,t,n)=>({isError:e>=2,message:e===1?`No matches found`:void 0})],[`rg`,(e,t,n)=>({isError:e>=2,message:e===1?`No matches found`:void 0})],[`find`,(e,t,n)=>({isError:e>=2,message:e===1?`Some directories were inaccessible`:void 0})],[`diff`,(e,t,n)=>({isError:e>=2,message:e===1?`Files differ`:void 0})],[`test`,(e,t,n)=>({isError:e>=2,message:e===1?`Condition is false`:void 0})],[`[`,(e,t,n)=>({isError:e>=2,message:e===1?`Condition is false`:void 0})]])}));function nLe(){return Br(H())??Yt()}function rLe(){return process.env.CLAUDE_CODE_ENTRYPOINT??`cli`}function SG(){return{fileStates:new Map,sessionBaselines:new Map,surface:rLe(),startingHeadSha:null,promptCount:0,promptCountAtLastCommit:0,permissionPromptCount:0,permissionPromptCountAtLastCommit:0,escapeCount:0,escapeCountAtLastCommit:0}}function iLe(e,t){let n={};for(let[t,r]of e.fileStates)n[t]=r;return{type:`attribution-snapshot`,messageId:t,surface:e.surface,fileStates:n,promptCount:e.promptCount,promptCountAtLastCommit:e.promptCountAtLastCommit,permissionPromptCount:e.permissionPromptCount,permissionPromptCountAtLastCommit:e.permissionPromptCountAtLastCommit,escapeCount:e.escapeCount,escapeCountAtLastCommit:e.escapeCountAtLastCommit}}function aLe(e,t){let n={...e,promptCount:e.promptCount+1};return t(iLe(n,Jc())),n}var CG,wG,TG=n((()=>{Jt(),Vn(),K(),va(),or(),Jr(),Ir(),Ga(),Uo(),tae(),CG=`github.com:anthropics/claude-cli-internal,github.com/anthropics/claude-cli-internal,github.com:anthropics/anthropic,github.com/anthropics/anthropic,github.com:anthropics/apps,github.com/anthropics/apps,github.com:anthropics/casino,github.com/anthropics/casino,github.com:anthropics/dbt,github.com/anthropics/dbt,github.com:anthropics/dotfiles,github.com/anthropics/dotfiles,github.com:anthropics/terraform-config,github.com/anthropics/terraform-config,github.com:anthropics/hex-export,github.com/anthropics/hex-export,github.com:anthropics/feedback-v2,github.com/anthropics/feedback-v2,github.com:anthropics/labs,github.com/anthropics/labs,github.com:anthropics/argo-rollouts,github.com/anthropics/argo-rollouts,github.com:anthropics/starling-configs,github.com/anthropics/starling-configs,github.com:anthropics/ts-tools,github.com/anthropics/ts-tools,github.com:anthropics/ts-capsules,github.com/anthropics/ts-capsules,github.com:anthropics/feldspar-testing,github.com/anthropics/feldspar-testing,github.com:anthropics/trellis,github.com/anthropics/trellis,github.com:anthropics/claude-for-hiring,github.com/anthropics/claude-for-hiring,github.com:anthropics/forge-web,github.com/anthropics/forge-web,github.com:anthropics/infra-manifests,github.com/anthropics/infra-manifests,github.com:anthropics/mycro_manifests,github.com/anthropics/mycro_manifests,github.com:anthropics/mycro_configs,github.com/anthropics/mycro_configs,github.com:anthropics/mobile-apps,github.com/anthropics/mobile-apps`.split(`,`),wG=null,Wie(async()=>{if(wG!==null)return wG===`internal`;let e=await Nne(nLe());if(!e)return wG=`none`,!1;let t=CG.some(t=>e.includes(t));return wG=t?`internal`:`external`,t})}));function oLe(e){let t=e.toLowerCase();for(let{keywords:e,email:n}of EG)if(e.some(e=>t.includes(e)))return n;return`noreply@anthropic.com`}var EG,sLe=n((()=>{EG=[{keywords:[`claude`],email:`noreply@anthropic.com`},{keywords:[`gpt`,`dall-e`,`o1-`,`o3-`,`o4-`],email:`openai@readmagic.workmate.win`},{keywords:[`gemini`],email:`google-gemini@readmagic.workmate.win`},{keywords:[`grok`],email:`xai-org@readmagic.workmate.win`},{keywords:[`glm`],email:`zai-org@readmagic.workmate.win`},{keywords:[`deepseek`],email:`deepseek-ai@readmagic.workmate.win`},{keywords:[`qwen`],email:`QwenLM@readmagic.workmate.win`},{keywords:[`minimax`],email:`MiniMax-AI@readmagic.workmate.win`},{keywords:[`mimo`],email:`XiaomiMiMo@readmagic.workmate.win`},{keywords:[`kimi`],email:`MoonshotAI@readmagic.workmate.win`}]}));function cLe(e){switch(Fo()){case`openai`:return _v(e);case`gemini`:return xv(e);case`grok`:return vv(e);default:return e}}function lLe(){return cLe(Xo())}var uLe=n((()=>{Nv(),Uo(),Io()})),DG,OG,kG,AG,jG=n((()=>{Nt(),kt(),iU(),DG=V(()=>xt({file_path:B().describe(`The absolute path to the file to modify`),old_string:B().describe(`The text to replace`),new_string:B().describe(`The text to replace it with (must be different from old_string)`),replace_all:rU(pt().default(!1).optional()).describe(`Replace all occurrences of old_string (default false)`)})),OG=V(()=>I({oldStart:z(),oldLines:z(),newStart:z(),newLines:z(),lines:L(B())})),kG=V(()=>I({filename:B(),status:ft([`modified`,`added`]),additions:z(),deletions:z(),changes:z(),patch:B(),repository:B().nullable().optional().describe(`GitHub owner/repo when available`)})),AG=V(()=>I({filePath:B().describe(`The file path that was edited`),oldString:B().describe(`The original string that was replaced`),newString:B().describe(`The new string that replaced it`),originalFile:B().describe(`The original file contents before editing`),structuredPatch:L(OG()).describe(`Diff patch showing the changes`),userModified:pt().describe(`Whether the user modified the proposed changes`),replaceAll:pt().describe(`Whether all occurrences were replaced`),gitDiff:kG().optional()}))}));function dLe({serverName:e,files:t}){let n=Jc();G(`LSP Diagnostics: Registering ${t.length} diagnostic file(s) from ${e} (ID: ${n})`),RG.set(n,{serverName:e,files:t,timestamp:Date.now(),attachmentSent:!1})}function MG(e){switch(e){case`Error`:return 1;case`Warning`:return 2;case`Info`:return 3;case`Hint`:return 4;default:return 4}}function NG(e){return U({message:e.message,severity:e.severity,range:e.range,source:e.source||null,code:e.code||null})}function fLe(e){let t=new Map,n=[];for(let r of e){t.has(r.uri)||(t.set(r.uri,new Set),n.push({uri:r.uri,diagnostics:[]}));let e=t.get(r.uri),i=n.find(e=>e.uri===r.uri),a=zG.get(r.uri)||new Set;for(let t of r.diagnostics)try{let n=NG(t);if(e.has(n)||a.has(n))continue;e.add(n),i.diagnostics.push(t)}catch(e){let n=tr(e),a=t.message?.substring(0,100)||`<no message>`;J(Error(`Failed to deduplicate diagnostic in ${r.uri}: ${n.message}. Diagnostic message: ${a}`)),i.diagnostics.push(t)}}return n.filter(e=>e.diagnostics.length>0)}function pLe(){G(`LSP Diagnostics: Checking registry - ${RG.size} pending`);let e=[],t=new Set,n=[];for(let r of RG.values())r.attachmentSent||(e.push(...r.files),t.add(r.serverName),n.push(r));if(e.length===0)return[];let r;try{r=fLe(e)}catch(t){let n=tr(t);J(Error(`Failed to deduplicate LSP diagnostics: ${n.message}`)),r=e}for(let e of n)e.attachmentSent=!0;for(let[e,t]of RG)t.attachmentSent&&RG.delete(e);let i=e.reduce((e,t)=>e+t.diagnostics.length,0),a=r.reduce((e,t)=>e+t.diagnostics.length,0);i>a&&G(`LSP Diagnostics: Deduplication removed ${i-a} duplicate diagnostic(s)`);let o=0,s=0;for(let e of r){e.diagnostics.sort((e,t)=>MG(e.severity)-MG(t.severity)),e.diagnostics.length>FG&&(s+=e.diagnostics.length-FG,e.diagnostics=e.diagnostics.slice(0,FG));let t=IG-o;e.diagnostics.length>t&&(s+=e.diagnostics.length-t,e.diagnostics=e.diagnostics.slice(0,t)),o+=e.diagnostics.length}r=r.filter(e=>e.diagnostics.length>0),s>0&&G(`LSP Diagnostics: Volume limiting removed ${s} diagnostic(s) (max ${FG}/file, ${IG} total)`);for(let e of r){zG.has(e.uri)||zG.set(e.uri,new Set);let t=zG.get(e.uri);for(let n of e.diagnostics)try{t.add(NG(n))}catch(t){let r=tr(t),i=n.message?.substring(0,100)||`<no message>`;J(Error(`Failed to track delivered diagnostic in ${e.uri}: ${r.message}. Diagnostic message: ${i}`))}}let c=r.reduce((e,t)=>e+t.diagnostics.length,0);return c===0?(G(`LSP Diagnostics: No new diagnostics to deliver (all filtered by deduplication)`),[]):(G(`LSP Diagnostics: Delivering ${r.length} file(s) with ${c} diagnostic(s) from ${t.size} server(s)`),[{serverName:Array.from(t).join(`, `),files:r}])}function mLe(){G(`LSP Diagnostics: Clearing ${RG.size} pending diagnostic(s)`),RG.clear()}function hLe(){G(`LSP Diagnostics: Resetting all state (${RG.size} pending, ${zG.size} files tracked)`),RG.clear(),zG.clear()}function PG(e){zG.has(e)&&(G(`LSP Diagnostics: Clearing delivered diagnostics for ${e}`),zG.delete(e))}var FG,IG,LG,RG,zG,BG=n((()=>{Tt(),K(),qn(),Ga(),mr(),FG=10,IG=30,LG=500,RG=new Map,zG=new Pt({max:LG})}));function gLe(e,t){let n=Oc(e),r=Oc(e,t),i=Dc(n,r);return i.startsWith(`..`)||Oc(i)===i?null:r}async function VG(e,t=[]){let n={},r=X(e.path,`.lsp.json`);try{let i=$n(await tl(r,`utf-8`)),a=St(B(),mi()).safeParse(i);if(a.success)Object.assign(n,a.data);else{let n=`LSP config validation failed for .lsp.json in plugin ${e.name}: ${a.error.message}`;J(Error(n)),t.push({type:`lsp-config-invalid`,plugin:e.name,serverName:`.lsp.json`,validationError:a.error.message,source:`plugin`})}}catch(n){Qn(n)||(n instanceof Error?`${e.name}${n.message}`:`${e.name}`,J(tr(n)),t.push({type:`lsp-config-invalid`,plugin:e.name,serverName:`.lsp.json`,validationError:n instanceof Error?`Failed to parse JSON: ${n.message}`:`Failed to parse JSON file`,source:`plugin`}))}if(e.manifest.lspServers){let r=await _Le(e.manifest.lspServers,e.path,e.name,t);r&&Object.assign(n,r)}return Object.keys(n).length>0?n:void 0}async function _Le(e,t,n,r){let i={},a=Array.isArray(e)?e:[e];for(let e of a)if(typeof e==`string`){let a=gLe(t,e);if(!a){let t=`Security: Path traversal attempt blocked in plugin ${n}: ${e}`;J(Error(t)),G(t,{level:`warn`}),r.push({type:`lsp-config-invalid`,plugin:n,serverName:e,validationError:`Invalid path: must be relative and within plugin directory`,source:`plugin`});continue}try{let t=$n(await tl(a,`utf-8`)),o=St(B(),mi()).safeParse(t);if(o.success)Object.assign(i,o.data);else{let t=`LSP config validation failed for ${e} in plugin ${n}: ${o.error.message}`;J(Error(t)),r.push({type:`lsp-config-invalid`,plugin:n,serverName:e,validationError:o.error.message,source:`plugin`})}}catch(t){t instanceof Error?`${e}${n}${t.message}`:`${e}${n}`,J(tr(t)),r.push({type:`lsp-config-invalid`,plugin:n,serverName:e,validationError:t instanceof Error?`Failed to parse JSON: ${t.message}`:`Failed to parse JSON file`,source:`plugin`})}}else for(let[t,a]of Object.entries(e)){let e=mi().safeParse(a);if(e.success)i[t]=e.data;else{let i=`LSP config validation failed for inline server "${t}" in plugin ${n}: ${e.error.message}`;J(Error(i)),r.push({type:`lsp-config-invalid`,plugin:n,serverName:t,validationError:e.error.message,source:`plugin`})}}return Object.keys(i).length>0?i:void 0}function vLe(e,t,n,r){let i=[],a=e=>{let r=Fk(e,t);n&&(r=Ik(r,n));let{expanded:a,missingVars:o}=$O(r);return i.push(...o),a},o={...e};o.command&&(o.command=a(o.command)),o.args&&(o.args=o.args.map(e=>a(e)));let s={CLAUDE_PLUGIN_ROOT:t.path,CLAUDE_PLUGIN_DATA:lb(t.source),...o.env||{}};for(let[e,t]of Object.entries(s))e!==`CLAUDE_PLUGIN_ROOT`&&e!==`CLAUDE_PLUGIN_DATA`&&(s[e]=a(t));if(o.env=s,o.workspaceFolder&&(o.workspaceFolder=a(o.workspaceFolder)),i.length>0){let e=`Missing environment variables in plugin LSP config: ${[...new Set(i)].join(`, `)}`;J(Error(e)),G(e,{level:`warn`})}return o}function yLe(e,t){let n={};for(let[r,i]of Object.entries(e)){let e=`plugin:${t}:${r}`;n[e]={...i,scope:`dynamic`,source:t}}return n}async function bLe(e,t=[]){if(!e.enabled)return;let n=e.lspServers||await VG(e,t);if(!n)return;let r=e.manifest.userConfig?Rk(Mk(e)):void 0,i={};for(let[a,o]of Object.entries(n))i[a]=vLe(o,e,r,t);return yLe(i,e.name)}var HG=n((()=>{Nt(),ek(),K(),qn(),Ga(),mr(),ub(),zk(),oi()}));async function xLe(){let e={};try{let{enabled:t}=await F4(),n=await Promise.all(t.map(async e=>{let t=[];try{return{plugin:e,scopedServers:await bLe(e,t),errors:t}}catch(n){return G(`Failed to load LSP servers for plugin ${e.name}: ${n}`,{level:`error`}),{plugin:e,scopedServers:void 0,errors:t}}}));for(let{plugin:t,scopedServers:r,errors:i}of n){let n=r?Object.keys(r).length:0;n>0&&(Object.assign(e,r),G(`Loaded ${n} LSP server(s) from plugin: ${t.name}`)),i.length>0&&G(`${i.length} error(s) loading LSP servers from plugin: ${t.name}`)}G(`Total LSP servers loaded: ${Object.keys(e).length}`)}catch(e){J(tr(e)),G(`Error loading LSP servers: ${W(e)}`)}return{servers:e}}var SLe=n((()=>{K(),qn(),Ga(),HG(),I4()})),UG=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.stringArray=e.array=e.func=e.error=e.number=e.string=e.boolean=void 0;function t(e){return e===!0||e===!1}e.boolean=t;function n(e){return typeof e==`string`||e instanceof String}e.string=n;function r(e){return typeof e==`number`||e instanceof Number}e.number=r;function i(e){return e instanceof Error}e.error=i;function a(e){return typeof e==`function`}e.func=a;function o(e){return Array.isArray(e)}e.array=o;function s(e){return o(e)&&e.every(e=>n(e))}e.stringArray=s})),WG=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Message=e.NotificationType9=e.NotificationType8=e.NotificationType7=e.NotificationType6=e.NotificationType5=e.NotificationType4=e.NotificationType3=e.NotificationType2=e.NotificationType1=e.NotificationType0=e.NotificationType=e.RequestType9=e.RequestType8=e.RequestType7=e.RequestType6=e.RequestType5=e.RequestType4=e.RequestType3=e.RequestType2=e.RequestType1=e.RequestType=e.RequestType0=e.AbstractMessageSignature=e.ParameterStructures=e.ResponseError=e.ErrorCodes=void 0;var t=UG(),n;(function(e){e.ParseError=-32700,e.InvalidRequest=-32600,e.MethodNotFound=-32601,e.InvalidParams=-32602,e.InternalError=-32603,e.jsonrpcReservedErrorRangeStart=-32099,e.serverErrorStart=-32099,e.MessageWriteError=-32099,e.MessageReadError=-32098,e.PendingResponseRejected=-32097,e.ConnectionInactive=-32096,e.ServerNotInitialized=-32002,e.UnknownErrorCode=-32001,e.jsonrpcReservedErrorRangeEnd=-32e3,e.serverErrorEnd=-32e3})(n||(e.ErrorCodes=n={})),e.ResponseError=class e extends Error{constructor(r,i,a){super(i),this.code=t.number(r)?r:n.UnknownErrorCode,this.data=a,Object.setPrototypeOf(this,e.prototype)}toJson(){let e={code:this.code,message:this.message};return this.data!==void 0&&(e.data=this.data),e}};var r=class e{constructor(e){this.kind=e}static is(t){return t===e.auto||t===e.byName||t===e.byPosition}toString(){return this.kind}};e.ParameterStructures=r,r.auto=new r(`auto`),r.byPosition=new r(`byPosition`),r.byName=new r(`byName`);var i=class{constructor(e,t){this.method=e,this.numberOfParams=t}get parameterStructures(){return r.auto}};e.AbstractMessageSignature=i,e.RequestType0=class extends i{constructor(e){super(e,0)}},e.RequestType=class extends i{constructor(e,t=r.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}},e.RequestType1=class extends i{constructor(e,t=r.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}},e.RequestType2=class extends i{constructor(e){super(e,2)}},e.RequestType3=class extends i{constructor(e){super(e,3)}},e.RequestType4=class extends i{constructor(e){super(e,4)}},e.RequestType5=class extends i{constructor(e){super(e,5)}},e.RequestType6=class extends i{constructor(e){super(e,6)}},e.RequestType7=class extends i{constructor(e){super(e,7)}},e.RequestType8=class extends i{constructor(e){super(e,8)}},e.RequestType9=class extends i{constructor(e){super(e,9)}},e.NotificationType=class extends i{constructor(e,t=r.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}},e.NotificationType0=class extends i{constructor(e){super(e,0)}},e.NotificationType1=class extends i{constructor(e,t=r.auto){super(e,1),this._parameterStructures=t}get parameterStructures(){return this._parameterStructures}},e.NotificationType2=class extends i{constructor(e){super(e,2)}},e.NotificationType3=class extends i{constructor(e){super(e,3)}},e.NotificationType4=class extends i{constructor(e){super(e,4)}},e.NotificationType5=class extends i{constructor(e){super(e,5)}},e.NotificationType6=class extends i{constructor(e){super(e,6)}},e.NotificationType7=class extends i{constructor(e){super(e,7)}},e.NotificationType8=class extends i{constructor(e){super(e,8)}},e.NotificationType9=class extends i{constructor(e){super(e,9)}};var a;(function(e){function n(e){let n=e;return n&&t.string(n.method)&&(t.string(n.id)||t.number(n.id))}e.isRequest=n;function r(e){let n=e;return n&&t.string(n.method)&&e.id===void 0}e.isNotification=r;function i(e){let n=e;return n&&(n.result!==void 0||!!n.error)&&(t.string(n.id)||t.number(n.id)||n.id===null)}e.isResponse=i})(a||(e.Message=a={}))})),GG=a((e=>{var t;Object.defineProperty(e,"__esModule",{value:!0}),e.LRUCache=e.LinkedMap=e.Touch=void 0;var n;(function(e){e.None=0,e.First=1,e.AsOld=e.First,e.Last=2,e.AsNew=e.Last})(n||(e.Touch=n={}));var r=class{constructor(){this[t]=`LinkedMap`,this._map=new Map,this._head=void 0,this._tail=void 0,this._size=0,this._state=0}clear(){this._map.clear(),this._head=void 0,this._tail=void 0,this._size=0,this._state++}isEmpty(){return!this._head&&!this._tail}get size(){return this._size}get first(){return this._head?.value}get last(){return this._tail?.value}has(e){return this._map.has(e)}get(e,t=n.None){let r=this._map.get(e);if(r)return t!==n.None&&this.touch(r,t),r.value}set(e,t,r=n.None){let i=this._map.get(e);if(i)i.value=t,r!==n.None&&this.touch(i,r);else{switch(i={key:e,value:t,next:void 0,previous:void 0},r){case n.None:this.addItemLast(i);break;case n.First:this.addItemFirst(i);break;case n.Last:this.addItemLast(i);break;default:this.addItemLast(i);break}this._map.set(e,i),this._size++}return this}delete(e){return!!this.remove(e)}remove(e){let t=this._map.get(e);if(t)return this._map.delete(e),this.removeItem(t),this._size--,t.value}shift(){if(!this._head&&!this._tail)return;if(!this._head||!this._tail)throw Error(`Invalid list`);let e=this._head;return this._map.delete(e.key),this.removeItem(e),this._size--,e.value}forEach(e,t){let n=this._state,r=this._head;for(;r;){if(t?e.bind(t)(r.value,r.key,this):e(r.value,r.key,this),this._state!==n)throw Error(`LinkedMap got modified during iteration.`);r=r.next}}keys(){let e=this._state,t=this._head,n={[Symbol.iterator]:()=>n,next:()=>{if(this._state!==e)throw Error(`LinkedMap got modified during iteration.`);if(t){let e={value:t.key,done:!1};return t=t.next,e}else return{value:void 0,done:!0}}};return n}values(){let e=this._state,t=this._head,n={[Symbol.iterator]:()=>n,next:()=>{if(this._state!==e)throw Error(`LinkedMap got modified during iteration.`);if(t){let e={value:t.value,done:!1};return t=t.next,e}else return{value:void 0,done:!0}}};return n}entries(){let e=this._state,t=this._head,n={[Symbol.iterator]:()=>n,next:()=>{if(this._state!==e)throw Error(`LinkedMap got modified during iteration.`);if(t){let e={value:[t.key,t.value],done:!1};return t=t.next,e}else return{value:void 0,done:!0}}};return n}[(t=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}trimOld(e){if(e>=this.size)return;if(e===0){this.clear();return}let t=this._head,n=this.size;for(;t&&n>e;)this._map.delete(t.key),t=t.next,n--;this._head=t,this._size=n,t&&(t.previous=void 0),this._state++}addItemFirst(e){if(!this._head&&!this._tail)this._tail=e;else if(this._head)e.next=this._head,this._head.previous=e;else throw Error(`Invalid list`);this._head=e,this._state++}addItemLast(e){if(!this._head&&!this._tail)this._head=e;else if(this._tail)e.previous=this._tail,this._tail.next=e;else throw Error(`Invalid list`);this._tail=e,this._state++}removeItem(e){if(e===this._head&&e===this._tail)this._head=void 0,this._tail=void 0;else if(e===this._head){if(!e.next)throw Error(`Invalid list`);e.next.previous=void 0,this._head=e.next}else if(e===this._tail){if(!e.previous)throw Error(`Invalid list`);e.previous.next=void 0,this._tail=e.previous}else{let t=e.next,n=e.previous;if(!t||!n)throw Error(`Invalid list`);t.previous=n,n.next=t}e.next=void 0,e.previous=void 0,this._state++}touch(e,t){if(!this._head||!this._tail)throw Error(`Invalid list`);if(!(t!==n.First&&t!==n.Last)){if(t===n.First){if(e===this._head)return;let t=e.next,n=e.previous;e===this._tail?(n.next=void 0,this._tail=n):(t.previous=n,n.next=t),e.previous=void 0,e.next=this._head,this._head.previous=e,this._head=e,this._state++}else if(t===n.Last){if(e===this._tail)return;let t=e.next,n=e.previous;e===this._head?(t.previous=void 0,this._head=t):(t.previous=n,n.next=t),e.next=void 0,e.previous=this._tail,this._tail.next=e,this._tail=e,this._state++}}}toJSON(){let e=[];return this.forEach((t,n)=>{e.push([n,t])}),e}fromJSON(e){this.clear();for(let[t,n]of e)this.set(t,n)}};e.LinkedMap=r,e.LRUCache=class extends r{constructor(e,t=1){super(),this._limit=e,this._ratio=Math.min(Math.max(0,t),1)}get limit(){return this._limit}set limit(e){this._limit=e,this.checkTrim()}get ratio(){return this._ratio}set ratio(e){this._ratio=Math.min(Math.max(0,e),1),this.checkTrim()}get(e,t=n.AsNew){return super.get(e,t)}peek(e){return super.get(e,n.None)}set(e,t){return super.set(e,t,n.Last),this.checkTrim(),this}checkTrim(){this.size>this._limit&&this.trimOld(Math.round(this._limit*this._ratio))}}})),CLe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Disposable=void 0;var t;(function(e){function t(e){return{dispose:e}}e.create=t})(t||(e.Disposable=t={}))})),KG=a((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t;function n(){if(t===void 0)throw Error(`No runtime abstraction layer installed`);return t}(function(e){function n(e){if(e===void 0)throw Error(`No runtime abstraction layer provided`);t=e}e.install=n})(n||(n={})),e.default=n})),qG=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Emitter=e.Event=void 0;var t=KG(),n;(function(e){let t={dispose(){}};e.None=function(){return t}})(n||(e.Event=n={}));var r=class{add(e,t=null,n){this._callbacks||(this._callbacks=[],this._contexts=[]),this._callbacks.push(e),this._contexts.push(t),Array.isArray(n)&&n.push({dispose:()=>this.remove(e,t)})}remove(e,t=null){if(!this._callbacks)return;let n=!1;for(let r=0,i=this._callbacks.length;r<i;r++)if(this._callbacks[r]===e)if(this._contexts[r]===t){this._callbacks.splice(r,1),this._contexts.splice(r,1);return}else n=!0;if(n)throw Error(`When adding a listener with a context, you should remove it with the same context`)}invoke(...e){if(!this._callbacks)return[];let n=[],r=this._callbacks.slice(0),i=this._contexts.slice(0);for(let a=0,o=r.length;a<o;a++)try{n.push(r[a].apply(i[a],e))}catch(e){(0,t.default)().console.error(e)}return n}isEmpty(){return!this._callbacks||this._callbacks.length===0}dispose(){this._callbacks=void 0,this._contexts=void 0}},i=class e{constructor(e){this._options=e}get event(){return this._event||(this._event=(t,n,i)=>{this._callbacks||(this._callbacks=new r),this._options&&this._options.onFirstListenerAdd&&this._callbacks.isEmpty()&&this._options.onFirstListenerAdd(this),this._callbacks.add(t,n);let a={dispose:()=>{this._callbacks&&(this._callbacks.remove(t,n),a.dispose=e._noop,this._options&&this._options.onLastListenerRemove&&this._callbacks.isEmpty()&&this._options.onLastListenerRemove(this))}};return Array.isArray(i)&&i.push(a),a}),this._event}fire(e){this._callbacks&&this._callbacks.invoke.call(this._callbacks,e)}dispose(){this._callbacks&&(this._callbacks.dispose(),this._callbacks=void 0)}};e.Emitter=i,i._noop=function(){}})),JG=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CancellationTokenSource=e.CancellationToken=void 0;var t=KG(),n=UG(),r=qG(),i;(function(e){e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:r.Event.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:r.Event.None});function t(t){let r=t;return r&&(r===e.None||r===e.Cancelled||n.boolean(r.isCancellationRequested)&&!!r.onCancellationRequested)}e.is=t})(i||(e.CancellationToken=i={}));var a=Object.freeze(function(e,n){let r=(0,t.default)().timer.setTimeout(e.bind(n),0);return{dispose(){r.dispose()}}}),o=class{constructor(){this._isCancelled=!1}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?a:(this._emitter||(this._emitter=new r.Emitter),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=void 0)}};e.CancellationTokenSource=class{get token(){return this._token||(this._token=new o),this._token}cancel(){this._token?this._token.cancel():this._token=i.Cancelled}dispose(){this._token?this._token instanceof o&&this._token.dispose():this._token=i.None}}})),wLe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SharedArrayReceiverStrategy=e.SharedArraySenderStrategy=void 0;var t=JG(),n;(function(e){e.Continue=0,e.Cancelled=1})(n||(n={})),e.SharedArraySenderStrategy=class{constructor(){this.buffers=new Map}enableCancellation(e){if(e.id===null)return;let t=new SharedArrayBuffer(4),r=new Int32Array(t,0,1);r[0]=n.Continue,this.buffers.set(e.id,t),e.$cancellationData=t}async sendCancellation(e,t){let r=this.buffers.get(t);if(r===void 0)return;let i=new Int32Array(r,0,1);Atomics.store(i,0,n.Cancelled)}cleanup(e){this.buffers.delete(e)}dispose(){this.buffers.clear()}};var r=class{constructor(e){this.data=new Int32Array(e,0,1)}get isCancellationRequested(){return Atomics.load(this.data,0)===n.Cancelled}get onCancellationRequested(){throw Error(`Cancellation over SharedArrayBuffer doesn't support cancellation events`)}},i=class{constructor(e){this.token=new r(e)}cancel(){}dispose(){}};e.SharedArrayReceiverStrategy=class{constructor(){this.kind=`request`}createCancellationTokenSource(e){let n=e.$cancellationData;return n===void 0?new t.CancellationTokenSource:new i(n)}}})),YG=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Semaphore=void 0;var t=KG();e.Semaphore=class{constructor(e=1){if(e<=0)throw Error(`Capacity must be greater than 0`);this._capacity=e,this._active=0,this._waiting=[]}lock(e){return new Promise((t,n)=>{this._waiting.push({thunk:e,resolve:t,reject:n}),this.runNext()})}get active(){return this._active}runNext(){this._waiting.length===0||this._active===this._capacity||(0,t.default)().timer.setImmediate(()=>this.doRunNext())}doRunNext(){if(this._waiting.length===0||this._active===this._capacity)return;let e=this._waiting.shift();if(this._active++,this._active>this._capacity)throw Error(`To many thunks active`);try{let t=e.thunk();t instanceof Promise?t.then(t=>{this._active--,e.resolve(t),this.runNext()},t=>{this._active--,e.reject(t),this.runNext()}):(this._active--,e.resolve(t),this.runNext())}catch(t){this._active--,e.reject(t),this.runNext()}}}})),TLe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ReadableStreamMessageReader=e.AbstractMessageReader=e.MessageReader=void 0;var t=KG(),n=UG(),r=qG(),i=YG(),a;(function(e){function t(e){let t=e;return t&&n.func(t.listen)&&n.func(t.dispose)&&n.func(t.onError)&&n.func(t.onClose)&&n.func(t.onPartialMessage)}e.is=t})(a||(e.MessageReader=a={}));var o=class{constructor(){this.errorEmitter=new r.Emitter,this.closeEmitter=new r.Emitter,this.partialMessageEmitter=new r.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError(e){this.errorEmitter.fire(this.asError(e))}get onClose(){return this.closeEmitter.event}fireClose(){this.closeEmitter.fire(void 0)}get onPartialMessage(){return this.partialMessageEmitter.event}firePartialMessage(e){this.partialMessageEmitter.fire(e)}asError(e){return e instanceof Error?e:Error(`Reader received error. Reason: ${n.string(e.message)?e.message:`unknown`}`)}};e.AbstractMessageReader=o;var s;(function(e){function n(e){let n,r,i=new Map,a,o=new Map;if(e===void 0||typeof e==`string`)n=e??`utf-8`;else{if(n=e.charset??`utf-8`,e.contentDecoder!==void 0&&(r=e.contentDecoder,i.set(r.name,r)),e.contentDecoders!==void 0)for(let t of e.contentDecoders)i.set(t.name,t);if(e.contentTypeDecoder!==void 0&&(a=e.contentTypeDecoder,o.set(a.name,a)),e.contentTypeDecoders!==void 0)for(let t of e.contentTypeDecoders)o.set(t.name,t)}return a===void 0&&(a=(0,t.default)().applicationJson.decoder,o.set(a.name,a)),{charset:n,contentDecoder:r,contentDecoders:i,contentTypeDecoder:a,contentTypeDecoders:o}}e.fromOptions=n})(s||(s={})),e.ReadableStreamMessageReader=class extends o{constructor(e,n){super(),this.readable=e,this.options=s.fromOptions(n),this.buffer=(0,t.default)().messageBuffer.create(this.options.charset),this._partialMessageTimeout=1e4,this.nextMessageLength=-1,this.messageToken=0,this.readSemaphore=new i.Semaphore(1)}set partialMessageTimeout(e){this._partialMessageTimeout=e}get partialMessageTimeout(){return this._partialMessageTimeout}listen(e){this.nextMessageLength=-1,this.messageToken=0,this.partialMessageTimer=void 0,this.callback=e;let t=this.readable.onData(e=>{this.onData(e)});return this.readable.onError(e=>this.fireError(e)),this.readable.onClose(()=>this.fireClose()),t}onData(e){try{for(this.buffer.append(e);;){if(this.nextMessageLength===-1){let e=this.buffer.tryReadHeaders(!0);if(!e)return;let t=e.get(`content-length`);if(!t){this.fireError(Error(`Header must provide a Content-Length property.\n${JSON.stringify(Object.fromEntries(e))}`));return}let n=parseInt(t);if(isNaN(n)){this.fireError(Error(`Content-Length value must be a number. Got ${t}`));return}this.nextMessageLength=n}let e=this.buffer.tryReadBody(this.nextMessageLength);if(e===void 0){this.setPartialMessageTimer();return}this.clearPartialMessageTimer(),this.nextMessageLength=-1,this.readSemaphore.lock(async()=>{let t=this.options.contentDecoder===void 0?e:await this.options.contentDecoder.decode(e),n=await this.options.contentTypeDecoder.decode(t,this.options);this.callback(n)}).catch(e=>{this.fireError(e)})}}catch(e){this.fireError(e)}}clearPartialMessageTimer(){this.partialMessageTimer&&(this.partialMessageTimer.dispose(),this.partialMessageTimer=void 0)}setPartialMessageTimer(){this.clearPartialMessageTimer(),!(this._partialMessageTimeout<=0)&&(this.partialMessageTimer=(0,t.default)().timer.setTimeout((e,t)=>{this.partialMessageTimer=void 0,e===this.messageToken&&(this.firePartialMessage({messageToken:e,waitingTime:t}),this.setPartialMessageTimer())},this._partialMessageTimeout,this.messageToken,this._partialMessageTimeout))}}})),ELe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.WriteableStreamMessageWriter=e.AbstractMessageWriter=e.MessageWriter=void 0;var t=KG(),n=UG(),r=YG(),i=qG(),a=`Content-Length: `,o=`\r
|
|
1165
1165
|
`,s;(function(e){function t(e){let t=e;return t&&n.func(t.dispose)&&n.func(t.onClose)&&n.func(t.onError)&&n.func(t.write)}e.is=t})(s||(e.MessageWriter=s={}));var c=class{constructor(){this.errorEmitter=new i.Emitter,this.closeEmitter=new i.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError(e,t,n){this.errorEmitter.fire([this.asError(e),t,n])}get onClose(){return this.closeEmitter.event}fireClose(){this.closeEmitter.fire(void 0)}asError(e){return e instanceof Error?e:Error(`Writer received error. Reason: ${n.string(e.message)?e.message:`unknown`}`)}};e.AbstractMessageWriter=c;var l;(function(e){function n(e){return e===void 0||typeof e==`string`?{charset:e??`utf-8`,contentTypeEncoder:(0,t.default)().applicationJson.encoder}:{charset:e.charset??`utf-8`,contentEncoder:e.contentEncoder,contentTypeEncoder:e.contentTypeEncoder??(0,t.default)().applicationJson.encoder}}e.fromOptions=n})(l||(l={})),e.WriteableStreamMessageWriter=class extends c{constructor(e,t){super(),this.writable=e,this.options=l.fromOptions(t),this.errorCount=0,this.writeSemaphore=new r.Semaphore(1),this.writable.onError(e=>this.fireError(e)),this.writable.onClose(()=>this.fireClose())}async write(e){return this.writeSemaphore.lock(async()=>this.options.contentTypeEncoder.encode(e,this.options).then(e=>this.options.contentEncoder===void 0?e:this.options.contentEncoder.encode(e)).then(t=>{let n=[];return n.push(a,t.byteLength.toString(),o),n.push(o),this.doWrite(e,n,t)},e=>{throw this.fireError(e),e}))}async doWrite(e,t,n){try{return await this.writable.write(t.join(``),`ascii`),this.writable.write(n)}catch(t){return this.handleError(t,e),Promise.reject(t)}}handleError(e,t){this.errorCount++,this.fireError(e,t,this.errorCount)}end(){this.writable.end()}}})),DLe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AbstractMessageBuffer=void 0;var t=13,n=10,r=`\r
|
|
1166
1166
|
`;e.AbstractMessageBuffer=class{constructor(e=`utf-8`){this._encoding=e,this._chunks=[],this._totalLength=0}get encoding(){return this._encoding}append(e){let t=typeof e==`string`?this.fromString(e,this._encoding):e;this._chunks.push(t),this._totalLength+=t.byteLength}tryReadHeaders(e=!1){if(this._chunks.length===0)return;let i=0,a=0,o=0,s=0;row:for(;a<this._chunks.length;){let e=this._chunks[a];o=0;column:for(;o<e.length;){switch(e[o]){case t:switch(i){case 0:i=1;break;case 2:i=3;break;default:i=0}break;case n:switch(i){case 1:i=2;break;case 3:i=4,o++;break row;default:i=0}break;default:i=0}o++}s+=e.byteLength,a++}if(i!==4)return;let c=this._read(s+o),l=new Map,u=this.toString(c,`ascii`).split(r);if(u.length<2)return l;for(let t=0;t<u.length-2;t++){let n=u[t],r=n.indexOf(`:`);if(r===-1)throw Error(`Message header must separate key and value using ':'\n${n}`);let i=n.substr(0,r),a=n.substr(r+1).trim();l.set(e?i.toLowerCase():i,a)}return l}tryReadBody(e){if(!(this._totalLength<e))return this._read(e)}get numberOfBytes(){return this._totalLength}_read(e){if(e===0)return this.emptyBuffer();if(e>this._totalLength)throw Error(`Cannot read so many bytes!`);if(this._chunks[0].byteLength===e){let t=this._chunks[0];return this._chunks.shift(),this._totalLength-=e,this.asNative(t)}if(this._chunks[0].byteLength>e){let t=this._chunks[0],n=this.asNative(t,e);return this._chunks[0]=t.slice(e),this._totalLength-=e,n}let t=this.allocNative(e),n=0;for(;e>0;){let r=this._chunks[0];if(r.byteLength>e){let i=r.slice(0,e);t.set(i,n),n+=e,this._chunks[0]=r.slice(e),this._totalLength-=e,e-=e}else t.set(r,n),n+=r.byteLength,this._chunks.shift(),this._totalLength-=r.byteLength,e-=r.byteLength}return t}}})),OLe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.createMessageConnection=e.ConnectionOptions=e.MessageStrategy=e.CancellationStrategy=e.CancellationSenderStrategy=e.CancellationReceiverStrategy=e.RequestCancellationReceiverStrategy=e.IdCancellationReceiverStrategy=e.ConnectionStrategy=e.ConnectionError=e.ConnectionErrors=e.LogTraceNotification=e.SetTraceNotification=e.TraceFormat=e.TraceValues=e.Trace=e.NullLogger=e.ProgressType=e.ProgressToken=void 0;var t=KG(),n=UG(),r=WG(),i=GG(),a=qG(),o=JG(),s;(function(e){e.type=new r.NotificationType(`$/cancelRequest`)})(s||(s={}));var c;(function(e){function t(e){return typeof e==`string`||typeof e==`number`}e.is=t})(c||(e.ProgressToken=c={}));var l;(function(e){e.type=new r.NotificationType(`$/progress`)})(l||(l={})),e.ProgressType=class{constructor(){}};var u;(function(e){function t(e){return n.func(e)}e.is=t})(u||(u={})),e.NullLogger=Object.freeze({error:()=>{},warn:()=>{},info:()=>{},log:()=>{}});var d;(function(e){e[e.Off=0]=`Off`,e[e.Messages=1]=`Messages`,e[e.Compact=2]=`Compact`,e[e.Verbose=3]=`Verbose`})(d||(e.Trace=d={}));var f;(function(e){e.Off=`off`,e.Messages=`messages`,e.Compact=`compact`,e.Verbose=`verbose`})(f||(e.TraceValues=f={})),(function(e){function t(t){if(!n.string(t))return e.Off;switch(t=t.toLowerCase(),t){case`off`:return e.Off;case`messages`:return e.Messages;case`compact`:return e.Compact;case`verbose`:return e.Verbose;default:return e.Off}}e.fromString=t;function r(t){switch(t){case e.Off:return`off`;case e.Messages:return`messages`;case e.Compact:return`compact`;case e.Verbose:return`verbose`;default:return`off`}}e.toString=r})(d||(e.Trace=d={}));var p;(function(e){e.Text=`text`,e.JSON=`json`})(p||(e.TraceFormat=p={})),(function(e){function t(t){return n.string(t)?(t=t.toLowerCase(),t===`json`?e.JSON:e.Text):e.Text}e.fromString=t})(p||(e.TraceFormat=p={}));var m;(function(e){e.type=new r.NotificationType(`$/setTrace`)})(m||(e.SetTraceNotification=m={}));var h;(function(e){e.type=new r.NotificationType(`$/logTrace`)})(h||(e.LogTraceNotification=h={}));var g;(function(e){e[e.Closed=1]=`Closed`,e[e.Disposed=2]=`Disposed`,e[e.AlreadyListening=3]=`AlreadyListening`})(g||(e.ConnectionErrors=g={}));var _=class e extends Error{constructor(t,n){super(n),this.code=t,Object.setPrototypeOf(this,e.prototype)}};e.ConnectionError=_;var v;(function(e){function t(e){let t=e;return t&&n.func(t.cancelUndispatched)}e.is=t})(v||(e.ConnectionStrategy=v={}));var y;(function(e){function t(e){let t=e;return t&&(t.kind===void 0||t.kind===`id`)&&n.func(t.createCancellationTokenSource)&&(t.dispose===void 0||n.func(t.dispose))}e.is=t})(y||(e.IdCancellationReceiverStrategy=y={}));var b;(function(e){function t(e){let t=e;return t&&t.kind===`request`&&n.func(t.createCancellationTokenSource)&&(t.dispose===void 0||n.func(t.dispose))}e.is=t})(b||(e.RequestCancellationReceiverStrategy=b={}));var x;(function(e){e.Message=Object.freeze({createCancellationTokenSource(e){return new o.CancellationTokenSource}});function t(e){return y.is(e)||b.is(e)}e.is=t})(x||(e.CancellationReceiverStrategy=x={}));var S;(function(e){e.Message=Object.freeze({sendCancellation(e,t){return e.sendNotification(s.type,{id:t})},cleanup(e){}});function t(e){let t=e;return t&&n.func(t.sendCancellation)&&n.func(t.cleanup)}e.is=t})(S||(e.CancellationSenderStrategy=S={}));var C;(function(e){e.Message=Object.freeze({receiver:x.Message,sender:S.Message});function t(e){let t=e;return t&&x.is(t.receiver)&&S.is(t.sender)}e.is=t})(C||(e.CancellationStrategy=C={}));var w;(function(e){function t(e){let t=e;return t&&n.func(t.handleMessage)}e.is=t})(w||(e.MessageStrategy=w={}));var T;(function(e){function t(e){let t=e;return t&&(C.is(t.cancellationStrategy)||v.is(t.connectionStrategy)||w.is(t.messageStrategy))}e.is=t})(T||(e.ConnectionOptions=T={}));var E;(function(e){e[e.New=1]=`New`,e[e.Listening=2]=`Listening`,e[e.Closed=3]=`Closed`,e[e.Disposed=4]=`Disposed`})(E||(E={}));function D(f,v,b,x){let S=b===void 0?e.NullLogger:b,T=0,D=0,O=0,k,A=new Map,ee,te=new Map,ne=new Map,re,ie=new i.LinkedMap,ae=new Map,j=new Set,oe=new Map,se=d.Off,ce=p.Text,M,N=E.New,le=new a.Emitter,ue=new a.Emitter,de=new a.Emitter,fe=new a.Emitter,pe=new a.Emitter,me=x&&x.cancellationStrategy?x.cancellationStrategy:C.Message;function he(e){if(e===null)throw Error(`Can't send requests with id null since the response can't be correlated.`);return`req-`+e.toString()}function ge(e){return e===null?`res-unknown-`+(++O).toString():`res-`+e.toString()}function _e(){return`not-`+(++D).toString()}function ve(e,t){r.Message.isRequest(t)?e.set(he(t.id),t):r.Message.isResponse(t)?e.set(ge(t.id),t):e.set(_e(),t)}function ye(e){}function be(){return N===E.Listening}function xe(){return N===E.Closed}function Se(){return N===E.Disposed}function Ce(){(N===E.New||N===E.Listening)&&(N=E.Closed,ue.fire(void 0))}function we(e){le.fire([e,void 0,void 0])}function Te(e){le.fire(e)}f.onClose(Ce),f.onError(we),v.onClose(Ce),v.onError(Te);function Ee(){re||ie.size===0||(re=(0,t.default)().timer.setImmediate(()=>{re=void 0,Oe()}))}function De(e){r.Message.isRequest(e)?Ae(e):r.Message.isNotification(e)?Me(e):r.Message.isResponse(e)?je(e):Ne(e)}function Oe(){if(ie.size===0)return;let e=ie.shift();try{let t=x?.messageStrategy;w.is(t)?t.handleMessage(e,De):De(e)}finally{Ee()}}let ke=e=>{try{if(r.Message.isNotification(e)&&e.method===s.type.method){let t=e.params.id,n=he(t),i=ie.get(n);if(r.Message.isRequest(i)){let r=x?.connectionStrategy,a=r&&r.cancelUndispatched?r.cancelUndispatched(i,ye):void 0;if(a&&(a.error!==void 0||a.result!==void 0)){ie.delete(n),oe.delete(t),a.id=i.id,Le(a,e.method,Date.now()),v.write(a).catch(()=>S.error(`Sending response for canceled message failed.`));return}}let a=oe.get(t);if(a!==void 0){a.cancel(),ze(e);return}else j.add(t)}ve(ie,e)}finally{Ee()}};function Ae(e){if(Se())return;function t(t,n,i){let a={jsonrpc:`2.0`,id:e.id};t instanceof r.ResponseError?a.error=t.toJson():a.result=t===void 0?null:t,Le(a,n,i),v.write(a).catch(()=>S.error(`Sending response failed.`))}function i(t,n,r){let i={jsonrpc:`2.0`,id:e.id,error:t.toJson()};Le(i,n,r),v.write(i).catch(()=>S.error(`Sending response failed.`))}function a(t,n,r){t===void 0&&(t=null);let i={jsonrpc:`2.0`,id:e.id,result:t};Le(i,n,r),v.write(i).catch(()=>S.error(`Sending response failed.`))}Re(e);let o=A.get(e.method),s,c;o&&(s=o.type,c=o.handler);let l=Date.now();if(c||k){let o=e.id??String(Date.now()),u=y.is(me.receiver)?me.receiver.createCancellationTokenSource(o):me.receiver.createCancellationTokenSource(e);e.id!==null&&j.has(e.id)&&u.cancel(),e.id!==null&&oe.set(o,u);try{let d;if(c)if(e.params===void 0){if(s!==void 0&&s.numberOfParams!==0){i(new r.ResponseError(r.ErrorCodes.InvalidParams,`Request ${e.method} defines ${s.numberOfParams} params but received none.`),e.method,l);return}d=c(u.token)}else if(Array.isArray(e.params)){if(s!==void 0&&s.parameterStructures===r.ParameterStructures.byName){i(new r.ResponseError(r.ErrorCodes.InvalidParams,`Request ${e.method} defines parameters by name but received parameters by position`),e.method,l);return}d=c(...e.params,u.token)}else{if(s!==void 0&&s.parameterStructures===r.ParameterStructures.byPosition){i(new r.ResponseError(r.ErrorCodes.InvalidParams,`Request ${e.method} defines parameters by position but received parameters by name`),e.method,l);return}d=c(e.params,u.token)}else k&&(d=k(e.method,e.params,u.token));let f=d;d?f.then?f.then(n=>{oe.delete(o),t(n,e.method,l)},t=>{oe.delete(o),t instanceof r.ResponseError?i(t,e.method,l):t&&n.string(t.message)?i(new r.ResponseError(r.ErrorCodes.InternalError,`Request ${e.method} failed with message: ${t.message}`),e.method,l):i(new r.ResponseError(r.ErrorCodes.InternalError,`Request ${e.method} failed unexpectedly without providing any details.`),e.method,l)}):(oe.delete(o),t(d,e.method,l)):(oe.delete(o),a(d,e.method,l))}catch(a){oe.delete(o),a instanceof r.ResponseError?t(a,e.method,l):a&&n.string(a.message)?i(new r.ResponseError(r.ErrorCodes.InternalError,`Request ${e.method} failed with message: ${a.message}`),e.method,l):i(new r.ResponseError(r.ErrorCodes.InternalError,`Request ${e.method} failed unexpectedly without providing any details.`),e.method,l)}}else i(new r.ResponseError(r.ErrorCodes.MethodNotFound,`Unhandled method ${e.method}`),e.method,l)}function je(e){if(!Se())if(e.id===null)e.error?S.error(`Received response message without id: Error is: \n${JSON.stringify(e.error,void 0,4)}`):S.error(`Received response message without id. No further error information provided.`);else{let t=e.id,n=ae.get(t);if(Be(e,n),n!==void 0){ae.delete(t);try{if(e.error){let t=e.error;n.reject(new r.ResponseError(t.code,t.message,t.data))}else if(e.result!==void 0)n.resolve(e.result);else throw Error(`Should never happen.`)}catch(e){e.message?S.error(`Response handler '${n.method}' failed with message: ${e.message}`):S.error(`Response handler '${n.method}' failed unexpectedly.`)}}}}function Me(e){if(Se())return;let t,n;if(e.method===s.type.method){let t=e.params.id;j.delete(t),ze(e);return}else{let r=te.get(e.method);r&&(n=r.handler,t=r.type)}if(n||ee)try{if(ze(e),n)if(e.params===void 0)t!==void 0&&t.numberOfParams!==0&&t.parameterStructures!==r.ParameterStructures.byName&&S.error(`Notification ${e.method} defines ${t.numberOfParams} params but received none.`),n();else if(Array.isArray(e.params)){let i=e.params;e.method===l.type.method&&i.length===2&&c.is(i[0])?n({token:i[0],value:i[1]}):(t!==void 0&&(t.parameterStructures===r.ParameterStructures.byName&&S.error(`Notification ${e.method} defines parameters by name but received parameters by position`),t.numberOfParams!==e.params.length&&S.error(`Notification ${e.method} defines ${t.numberOfParams} params but received ${i.length} arguments`)),n(...i))}else t!==void 0&&t.parameterStructures===r.ParameterStructures.byPosition&&S.error(`Notification ${e.method} defines parameters by position but received parameters by name`),n(e.params);else ee&&ee(e.method,e.params)}catch(t){t.message?S.error(`Notification handler '${e.method}' failed with message: ${t.message}`):S.error(`Notification handler '${e.method}' failed unexpectedly.`)}else de.fire(e)}function Ne(e){if(!e){S.error(`Received empty message.`);return}S.error(`Received message which is neither a response nor a notification message:\n${JSON.stringify(e,null,4)}`);let t=e;if(n.string(t.id)||n.number(t.id)){let e=t.id,n=ae.get(e);n&&n.reject(Error(`The received response has neither a result nor an error property.`))}}function Pe(e){if(e!=null)switch(se){case d.Verbose:return JSON.stringify(e,null,4);case d.Compact:return JSON.stringify(e);default:return}}function Fe(e){if(!(se===d.Off||!M))if(ce===p.Text){let t;(se===d.Verbose||se===d.Compact)&&e.params&&(t=`Params: ${Pe(e.params)}\n\n`),M.log(`Sending request '${e.method} - (${e.id})'.`,t)}else Ve(`send-request`,e)}function Ie(e){if(!(se===d.Off||!M))if(ce===p.Text){let t;(se===d.Verbose||se===d.Compact)&&(t=e.params?`Params: ${Pe(e.params)}\n\n`:`No parameters provided.
|
|
1167
1167
|
|
|
@@ -1595,7 +1595,7 @@ Guidelines:
|
|
|
1595
1595
|
- For analysis: Start broad and narrow down. Use multiple search strategies if the first doesn't yield results.
|
|
1596
1596
|
- Be thorough: Check multiple locations, consider different naming conventions, look for related files.
|
|
1597
1597
|
- NEVER create files unless they're absolutely necessary for achieving your goal. ALWAYS prefer editing an existing file to creating a new one.
|
|
1598
|
-
- NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested.`,yY={agentType:`general-purpose`,whenToUse:`General-purpose agent for researching complex questions, searching for code, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you.`,tools:[`*`],source:`built-in`,baseDir:`built-in`,getSystemPrompt:bGe}}));function CGe(e,t){if(e.type!==t.type)return!1;let n=(e,t)=>(e.if??``)===(t.if??``);switch(e.type){case`command`:return t.type===`command`&&e.command===t.command&&(e.shell??`bash`)===(t.shell??`bash`)&&n(e,t);case`prompt`:return t.type===`prompt`&&e.prompt===t.prompt&&n(e,t);case`agent`:return t.type===`agent`&&e.prompt===t.prompt&&n(e,t);case`http`:return t.type===`http`&&e.url===t.url&&n(e,t);case`function`:return!1}}function xY(e){if(`statusMessage`in e&&e.statusMessage)return e.statusMessage;switch(e.type){case`command`:return e.command;case`prompt`:return e.prompt;case`agent`:return e.prompt;case`http`:return e.url;case`callback`:return`callback`;case`function`:return`function`}}function wGe(e){let t=[];if(zi(`policySettings`)?.allowManagedHooksOnly!==!0){let e=[`userSettings`,`projectSettings`,`localSettings`],n=new Set;for(let r of e){let e=ji(r);if(e){let t=Oc(e);if(n.has(t))continue;n.add(t)}let i=zi(r);if(i?.hooks)for(let[e,n]of Object.entries(i.hooks))for(let i of n)for(let n of i.hooks)t.push({event:e,config:n,matcher:i.matcher,source:r})}}let n=PGe(e,jn());for(let[e,r]of n.entries())for(let n of r)for(let r of n.hooks)t.push({event:e,config:r,matcher:n.matcher,source:`sessionHook`});return t}function TGe(e){switch(e){case`userSettings`:return`User settings (~/.workmate/settings.json)`;case`projectSettings`:return`Project settings (.workmate/settings.json)`;case`localSettings`:return`Local settings (.workmate/settings.local.json)`;case`pluginHook`:return`Plugin hooks (~/.workmate/plugins/*/hooks/hooks.json)`;case`sessionHook`:return`Session hooks (in-memory, temporary)`;case`builtinHook`:return`Built-in hooks (registered internally by Work Mate)`;default:return e}}function EGe(e){switch(e){case`userSettings`:return`User Settings`;case`projectSettings`:return`Project Settings`;case`localSettings`:return`Local Settings`;case`pluginHook`:return`Plugin Hooks`;case`sessionHook`:return`Session Hooks`;case`builtinHook`:return`Built-in Hooks`;default:return e}}function DGe(e){switch(e){case`userSettings`:return`User`;case`projectSettings`:return`Project`;case`localSettings`:return`Local`;case`pluginHook`:return`Plugin`;case`sessionHook`:return`Session`;case`builtinHook`:return`Built-in`;default:return e}}function OGe(e,t,n){let r=Yre.reduce((e,t,n)=>(e[t]=n,e),{});return[...e].sort((e,i)=>{let a=t[n]?.[e]||[],o=t[n]?.[i]||[],s=Array.from(new Set(a.map(e=>e.source))),c=Array.from(new Set(o.map(e=>e.source))),l=e=>e===`pluginHook`||e===`builtinHook`?999:r[e],u=Math.min(...s.map(l)),d=Math.min(...c.map(l));return u===d?e.localeCompare(i):u-d})}var SY=n((()=>{Jt(),wi(),vi(),ere(),wY()}));function kGe(e,t,n,r,i,a,o){jGe(e,t,n,r,i,a,o)}function AGe(e,t,n,r,i,a,o){let s=o?.id||`function-hook-${Date.now()}-${Math.random()}`;return jGe(e,t,n,r,{type:`function`,id:s,timeout:o?.timeout||5e3,callback:i,errorMessage:a}),s}function jGe(e,t,n,r,i,a,o){e(e=>{let s=e.sessionHooks.get(t)??{hooks:{}},c=s.hooks[n]||[],l=c.findIndex(e=>e.matcher===r&&e.skillRoot===o),u;if(l>=0){u=[...c];let e=u[l];u[l]={matcher:e.matcher,skillRoot:e.skillRoot,hooks:[...e.hooks,{hook:i,onHookSuccess:a}]}}else u=[...c,{matcher:r,skillRoot:o,hooks:[{hook:i,onHookSuccess:a}]}];let d={...s.hooks,[n]:u};return e.sessionHooks.set(t,{hooks:d}),e}),G(`Added session hook for event ${n} in session ${t}`)}function MGe(e,t,n,r){e(e=>{let i=e.sessionHooks.get(t);if(!i)return e;let a=(i.hooks[n]||[]).map(e=>{let t=e.hooks.filter(e=>!CGe(e.hook,r));return t.length>0?{...e,hooks:t}:null}).filter(e=>e!==null),o=a.length>0?{...i.hooks,[n]:a}:{...i.hooks};return a.length===0&&delete o[n],e.sessionHooks.set(t,{...i,hooks:o}),e}),G(`Removed session hook for event ${n} in session ${t}`)}function NGe(e){return e.map(e=>({matcher:e.matcher,skillRoot:e.skillRoot,hooks:e.hooks.map(e=>e.hook).filter(e=>e.type!==`function`)}))}function PGe(e,t,n){let r=e.sessionHooks.get(t);if(!r)return new Map;let i=new Map;if(n){let e=r.hooks[n];return e&&i.set(n,NGe(e)),i}for(let e of Tr){let t=r.hooks[e];t&&i.set(e,NGe(t))}return i}function FGe(e,t,n){let r=e.sessionHooks.get(t);if(!r)return new Map;let i=new Map,a=e=>e.map(e=>({matcher:e.matcher,hooks:e.hooks.map(e=>e.hook).filter(e=>e.type===`function`)})).filter(e=>e.hooks.length>0);if(n){let e=r.hooks[n];if(e){let t=a(e);t.length>0&&i.set(n,t)}return i}for(let e of Tr){let t=r.hooks[e];if(t){let n=a(t);n.length>0&&i.set(e,n)}}return i}function IGe(e,t,n,r,i){let a=e.sessionHooks.get(t);if(!a)return;let o=a.hooks[n];if(o){for(let e of o)if(e.matcher===r||r===``){let t=e.hooks.find(e=>CGe(e.hook,i));if(t)return t}}}function CY(e,t){e(e=>(e.sessionHooks.delete(t),e)),G(`Cleared all session hooks for session ${t}`)}var wY=n((()=>{Dr(),K(),SY()}));function LGe(e,t,n,r,i=!1){if(!n||Object.keys(n).length===0)return;let a=0;for(let o of Tr){let s=n[o];if(!s||s.length===0)continue;let c=o;i&&o===`Stop`&&(c=`SubagentStop`,G(`Converting Stop hook to SubagentStop for ${r} (subagents trigger SubagentStop)`));for(let n of s){let r=n.matcher??``,i=n.hooks;if(!(!i||i.length===0))for(let n of i)kGe(e,t,c,r,n),a++}}a>0&&G(`Registered ${a} frontmatter hook(s) from ${r} for session ${t}`)}var RGe=n((()=>{Dr(),K(),wY()}));async function zGe(e,t){if(!e.mcpServers?.length)return{clients:t,tools:[],cleanup:async()=>{}};let n=px(e.source);if(fx(`mcp`)&&!n)return G(`[Agent: ${e.agentType}] Skipping MCP servers: strictPluginOnlyCustomization locks MCP to plugin-only (agent source: ${e.source})`),{clients:t,tools:[],cleanup:async()=>{}};let r=[],i=[],a=[];for(let t of e.mcpServers){let n=null,o,s=!1;if(typeof t==`string`){if(o=t,n=nA(t),!n){G(`[Agent: ${e.agentType}] MCP server not found: ${t}`,{level:`warn`});continue}}else{let r=Object.entries(t);if(r.length!==1){G(`[Agent: ${e.agentType}] Invalid MCP server spec: expected exactly one key`,{level:`warn`});continue}let[i,a]=r[0];o=i,n={...a,scope:`dynamic`},s=!0}let c=await rj(o,n);if(r.push(c),s&&i.push(c),c.type===`connected`){let t=await aj(c);a.push(...t),G(`[Agent: ${e.agentType}] Connected to MCP server '${o}' with ${t.length} tools`)}else G(`[Agent: ${e.agentType}] Failed to connect to MCP server '${o}': ${c.type}`,{level:`warn`})}let o=async()=>{for(let t of i)if(t.type===`connected`)try{await t.cleanup()}catch(n){G(`[Agent: ${e.agentType}] Error cleaning up MCP server '${t.name}': ${n}`,{level:`warn`})}};return{clients:[...t,...r],tools:a,cleanup:o}}function BGe(e){return e.type===`assistant`||e.type===`user`||e.type===`progress`||e.type===`system`&&`subtype`in e&&e.subtype===`compact_boundary`}async function*TY({agentDefinition:e,promptMessages:t,toolUseContext:n,canUseTool:r,isAsync:i,canShowPermissionPrompts:a,forkContextMessages:o,querySource:s,override:c,model:l,maxTurns:u,preserveToolUseResults:d,availableTools:f,allowedTools:p,onCacheSafeParams:m,contentReplacementState:h,useExactTools:g,worktreePath:_,description:v,transcriptSubdir:y,onQueryProgress:b}){let x=n.getAppState(),S=x.toolPermissionContext.mode,C=n.setAppStateForTasks??n.setAppState,w=UWe(e.model,n.options.mainLoopModel,l,S),T=c?.agentId?c.agentId:oY();if(y&&p6(T,y),_se()){let t=n.agentId??jn();yse(T,e.agentType,t)}let E=[...o?eY(o):[],...t],D=o===void 0?CN(100):EN(n.readFileState),[O,k]=await Promise.all([c?.userContext??VR(),c?.systemContext??BR()]),A=e.omitAgentsMd&&!c?.userContext&&!0,{agentsMd:ee,...te}=O,ne=A?te:O,{gitStatus:re,...ie}=k,ae=e.agentType===`Explore`||e.agentType===`Plan`?ie:k,j=e.permissionMode,oe=()=>{let e=n.getAppState(),t=e.toolPermissionContext;j&&e.toolPermissionContext.mode!==`bypassPermissions`&&e.toolPermissionContext.mode!==`acceptEdits`&&e.toolPermissionContext.mode!==`auto`&&(t={...t,mode:j});let r=a===void 0?j!==`bubble`&&i:!a;return r&&(t={...t,shouldAvoidPermissionPrompts:!0}),i&&!r&&(t={...t,awaitAutomatedChecksBeforeDialog:!0}),p!==void 0&&(t={...t,alwaysAllowRules:{cliArg:e.toolPermissionContext.alwaysAllowRules.cliArg,session:[...p]}}),t===e.toolPermissionContext?e:{...e,toolPermissionContext:t}},se=g?f:hGe(e,f,i).resolvedTools,ce=Array.from(x.toolPermissionContext.additionalWorkingDirectories.keys()),M=c?.systemPrompt?c.systemPrompt:gv(await VGe(e,n,w,ce,se)),N=c?.abortController?c.abortController:i?new AbortController:n.abortController,le=[];for await(let t of dlt(T,e.agentType,N.signal))t.additionalContexts&&t.additionalContexts.length>0&&le.push(...t.additionalContexts);if(le.length>0){let e=r2({type:`hook_additional_context`,content:le,hookName:`SubagentStart`,toolUseID:Jc(),hookEvent:`SubagentStart`});E.push(e)}let ue=!fx(`hooks`)||px(e.source);e.hooks&&ue&&LGe(C,T,e.hooks,`agent '${e.agentType}'`,!0);let de=e.skills??[];if(de.length>0){let t=await X3(en()),r=[];for(let n of de){let i=HGe(n,t,e);if(!i){G(`[Agent: ${e.agentType}] Warning: Skill '${n}' specified in frontmatter was not found`,{level:`warn`});continue}let a=zat(i,t);if(a.type!==`prompt`){G(`[Agent: ${e.agentType}] Warning: Skill '${n}' is not a prompt-based skill`,{level:`warn`});continue}r.push({skillName:n,skill:a})}let{formatSkillLoadingMetadata:i}=await import(`./processSlashCommand-Cq9kaoSF.js`),a=await Promise.all(r.map(async({skillName:e,skill:t})=>({skillName:e,skill:t,content:await t.getPromptForCommand(``,n)})));for(let{skillName:t,skill:n,content:r}of a){G(`[Agent: ${e.agentType}] Preloaded skill '${t}'`);let a=i(t,n.progressMessage);E.push(Q({content:[{type:`text`,text:a},...r],isMeta:!0}))}}let{clients:fe,tools:pe,cleanup:me}=await zGe(e,n.options.mcpClients),he=pe.length>0?kg([...se,...pe],`name`):se,ge=r0(n,{options:{isNonInteractiveSession:g?n.options.isNonInteractiveSession:i?!0:n.options.isNonInteractiveSession??!1,appendSystemPrompt:n.options.appendSystemPrompt,tools:he,commands:[],debug:n.options.debug,verbose:n.options.verbose,mainLoopModel:w,thinkingConfig:g?n.options.thinkingConfig:{type:`disabled`},mcpClients:fe,mcpResources:n.options.mcpResources,agentDefinitions:n.options.agentDefinitions,...g&&{querySource:s}},agentId:T,agentType:e.agentType,messages:E,readFileState:D,abortController:N,getAppState:oe,shareSetAppState:!i,shareSetResponseLength:!0,criticalSystemReminder_EXPERIMENTAL:e.criticalSystemReminder_EXPERIMENTAL,contentReplacementState:h});d&&(ge.preserveToolUseResults=!0),m&&m({systemPrompt:M,userContext:ne,systemContext:ae,toolUseContext:ge,forkContextMessages:E}),S6(E,T).catch(e=>G(`Failed to record sidechain transcript: ${e}`)),g6(T,{agentType:e.agentType,..._&&{worktreePath:_},...v&&{description:v}}).catch(e=>G(`Failed to write agent metadata: ${e}`));let _e=E.at(-1)?.uuid??null;try{for await(let t of Q1({messages:E,systemPrompt:M,userContext:ne,systemContext:ae,canUseTool:r,toolUseContext:ge,querySource:s,maxTurns:u??e.maxTurns})){if(b?.(),t.type===`stream_event`&&t.event.type===`message_start`&&t.ttftMs!=null){n.pushApiMetricsEntry?.(t.ttftMs);continue}if(t.type===`attachment`){if(t.attachment.type===`max_turns_reached`){G(`[Agent
|
|
1598
|
+
- NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested.`,yY={agentType:`general-purpose`,whenToUse:`General-purpose agent for researching complex questions, searching for code, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you.`,tools:[`*`],source:`built-in`,baseDir:`built-in`,getSystemPrompt:bGe}}));function CGe(e,t){if(e.type!==t.type)return!1;let n=(e,t)=>(e.if??``)===(t.if??``);switch(e.type){case`command`:return t.type===`command`&&e.command===t.command&&(e.shell??`bash`)===(t.shell??`bash`)&&n(e,t);case`prompt`:return t.type===`prompt`&&e.prompt===t.prompt&&n(e,t);case`agent`:return t.type===`agent`&&e.prompt===t.prompt&&n(e,t);case`http`:return t.type===`http`&&e.url===t.url&&n(e,t);case`function`:return!1}}function xY(e){if(`statusMessage`in e&&e.statusMessage)return e.statusMessage;switch(e.type){case`command`:return e.command;case`prompt`:return e.prompt;case`agent`:return e.prompt;case`http`:return e.url;case`callback`:return`callback`;case`function`:return`function`}}function wGe(e){let t=[];if(zi(`policySettings`)?.allowManagedHooksOnly!==!0){let e=[`userSettings`,`projectSettings`,`localSettings`],n=new Set;for(let r of e){let e=ji(r);if(e){let t=Oc(e);if(n.has(t))continue;n.add(t)}let i=zi(r);if(i?.hooks)for(let[e,n]of Object.entries(i.hooks))for(let i of n)for(let n of i.hooks)t.push({event:e,config:n,matcher:i.matcher,source:r})}}let n=PGe(e,jn());for(let[e,r]of n.entries())for(let n of r)for(let r of n.hooks)t.push({event:e,config:r,matcher:n.matcher,source:`sessionHook`});return t}function TGe(e){switch(e){case`userSettings`:return`User settings (~/.workmate/settings.json)`;case`projectSettings`:return`Project settings (.workmate/settings.json)`;case`localSettings`:return`Local settings (.workmate/settings.local.json)`;case`pluginHook`:return`Plugin hooks (~/.workmate/plugins/*/hooks/hooks.json)`;case`sessionHook`:return`Session hooks (in-memory, temporary)`;case`builtinHook`:return`Built-in hooks (registered internally by Work Mate)`;default:return e}}function EGe(e){switch(e){case`userSettings`:return`User Settings`;case`projectSettings`:return`Project Settings`;case`localSettings`:return`Local Settings`;case`pluginHook`:return`Plugin Hooks`;case`sessionHook`:return`Session Hooks`;case`builtinHook`:return`Built-in Hooks`;default:return e}}function DGe(e){switch(e){case`userSettings`:return`User`;case`projectSettings`:return`Project`;case`localSettings`:return`Local`;case`pluginHook`:return`Plugin`;case`sessionHook`:return`Session`;case`builtinHook`:return`Built-in`;default:return e}}function OGe(e,t,n){let r=Yre.reduce((e,t,n)=>(e[t]=n,e),{});return[...e].sort((e,i)=>{let a=t[n]?.[e]||[],o=t[n]?.[i]||[],s=Array.from(new Set(a.map(e=>e.source))),c=Array.from(new Set(o.map(e=>e.source))),l=e=>e===`pluginHook`||e===`builtinHook`?999:r[e],u=Math.min(...s.map(l)),d=Math.min(...c.map(l));return u===d?e.localeCompare(i):u-d})}var SY=n((()=>{Jt(),wi(),vi(),ere(),wY()}));function kGe(e,t,n,r,i,a,o){jGe(e,t,n,r,i,a,o)}function AGe(e,t,n,r,i,a,o){let s=o?.id||`function-hook-${Date.now()}-${Math.random()}`;return jGe(e,t,n,r,{type:`function`,id:s,timeout:o?.timeout||5e3,callback:i,errorMessage:a}),s}function jGe(e,t,n,r,i,a,o){e(e=>{let s=e.sessionHooks.get(t)??{hooks:{}},c=s.hooks[n]||[],l=c.findIndex(e=>e.matcher===r&&e.skillRoot===o),u;if(l>=0){u=[...c];let e=u[l];u[l]={matcher:e.matcher,skillRoot:e.skillRoot,hooks:[...e.hooks,{hook:i,onHookSuccess:a}]}}else u=[...c,{matcher:r,skillRoot:o,hooks:[{hook:i,onHookSuccess:a}]}];let d={...s.hooks,[n]:u};return e.sessionHooks.set(t,{hooks:d}),e}),G(`Added session hook for event ${n} in session ${t}`)}function MGe(e,t,n,r){e(e=>{let i=e.sessionHooks.get(t);if(!i)return e;let a=(i.hooks[n]||[]).map(e=>{let t=e.hooks.filter(e=>!CGe(e.hook,r));return t.length>0?{...e,hooks:t}:null}).filter(e=>e!==null),o=a.length>0?{...i.hooks,[n]:a}:{...i.hooks};return a.length===0&&delete o[n],e.sessionHooks.set(t,{...i,hooks:o}),e}),G(`Removed session hook for event ${n} in session ${t}`)}function NGe(e){return e.map(e=>({matcher:e.matcher,skillRoot:e.skillRoot,hooks:e.hooks.map(e=>e.hook).filter(e=>e.type!==`function`)}))}function PGe(e,t,n){let r=e.sessionHooks.get(t);if(!r)return new Map;let i=new Map;if(n){let e=r.hooks[n];return e&&i.set(n,NGe(e)),i}for(let e of Tr){let t=r.hooks[e];t&&i.set(e,NGe(t))}return i}function FGe(e,t,n){let r=e.sessionHooks.get(t);if(!r)return new Map;let i=new Map,a=e=>e.map(e=>({matcher:e.matcher,hooks:e.hooks.map(e=>e.hook).filter(e=>e.type===`function`)})).filter(e=>e.hooks.length>0);if(n){let e=r.hooks[n];if(e){let t=a(e);t.length>0&&i.set(n,t)}return i}for(let e of Tr){let t=r.hooks[e];if(t){let n=a(t);n.length>0&&i.set(e,n)}}return i}function IGe(e,t,n,r,i){let a=e.sessionHooks.get(t);if(!a)return;let o=a.hooks[n];if(o){for(let e of o)if(e.matcher===r||r===``){let t=e.hooks.find(e=>CGe(e.hook,i));if(t)return t}}}function CY(e,t){e(e=>(e.sessionHooks.delete(t),e)),G(`Cleared all session hooks for session ${t}`)}var wY=n((()=>{Dr(),K(),SY()}));function LGe(e,t,n,r,i=!1){if(!n||Object.keys(n).length===0)return;let a=0;for(let o of Tr){let s=n[o];if(!s||s.length===0)continue;let c=o;i&&o===`Stop`&&(c=`SubagentStop`,G(`Converting Stop hook to SubagentStop for ${r} (subagents trigger SubagentStop)`));for(let n of s){let r=n.matcher??``,i=n.hooks;if(!(!i||i.length===0))for(let n of i)kGe(e,t,c,r,n),a++}}a>0&&G(`Registered ${a} frontmatter hook(s) from ${r} for session ${t}`)}var RGe=n((()=>{Dr(),K(),wY()}));async function zGe(e,t){if(!e.mcpServers?.length)return{clients:t,tools:[],cleanup:async()=>{}};let n=px(e.source);if(fx(`mcp`)&&!n)return G(`[Agent: ${e.agentType}] Skipping MCP servers: strictPluginOnlyCustomization locks MCP to plugin-only (agent source: ${e.source})`),{clients:t,tools:[],cleanup:async()=>{}};let r=[],i=[],a=[];for(let t of e.mcpServers){let n=null,o,s=!1;if(typeof t==`string`){if(o=t,n=nA(t),!n){G(`[Agent: ${e.agentType}] MCP server not found: ${t}`,{level:`warn`});continue}}else{let r=Object.entries(t);if(r.length!==1){G(`[Agent: ${e.agentType}] Invalid MCP server spec: expected exactly one key`,{level:`warn`});continue}let[i,a]=r[0];o=i,n={...a,scope:`dynamic`},s=!0}let c=await rj(o,n);if(r.push(c),s&&i.push(c),c.type===`connected`){let t=await aj(c);a.push(...t),G(`[Agent: ${e.agentType}] Connected to MCP server '${o}' with ${t.length} tools`)}else G(`[Agent: ${e.agentType}] Failed to connect to MCP server '${o}': ${c.type}`,{level:`warn`})}let o=async()=>{for(let t of i)if(t.type===`connected`)try{await t.cleanup()}catch(n){G(`[Agent: ${e.agentType}] Error cleaning up MCP server '${t.name}': ${n}`,{level:`warn`})}};return{clients:[...t,...r],tools:a,cleanup:o}}function BGe(e){return e.type===`assistant`||e.type===`user`||e.type===`progress`||e.type===`system`&&`subtype`in e&&e.subtype===`compact_boundary`}async function*TY({agentDefinition:e,promptMessages:t,toolUseContext:n,canUseTool:r,isAsync:i,canShowPermissionPrompts:a,forkContextMessages:o,querySource:s,override:c,model:l,maxTurns:u,preserveToolUseResults:d,availableTools:f,allowedTools:p,onCacheSafeParams:m,contentReplacementState:h,useExactTools:g,worktreePath:_,description:v,transcriptSubdir:y,onQueryProgress:b}){let x=n.getAppState(),S=x.toolPermissionContext.mode,C=n.setAppStateForTasks??n.setAppState,w=UWe(e.model,n.options.mainLoopModel,l,S),T=c?.agentId?c.agentId:oY();if(y&&p6(T,y),_se()){let t=n.agentId??jn();yse(T,e.agentType,t)}let E=[...o?eY(o):[],...t],D=o===void 0?CN(100):EN(n.readFileState),[O,k]=await Promise.all([c?.userContext??VR(),c?.systemContext??BR()]),A=e.omitAgentsMd&&!c?.userContext&&!0,{agentsMd:ee,...te}=O,ne=A?te:O,{gitStatus:re,...ie}=k,ae=e.agentType===`Explore`||e.agentType===`Plan`?ie:k,j=e.permissionMode,oe=()=>{let e=n.getAppState(),t=e.toolPermissionContext;j&&e.toolPermissionContext.mode!==`bypassPermissions`&&e.toolPermissionContext.mode!==`acceptEdits`&&e.toolPermissionContext.mode!==`auto`&&(t={...t,mode:j});let r=a===void 0?j!==`bubble`&&i:!a;return r&&(t={...t,shouldAvoidPermissionPrompts:!0}),i&&!r&&(t={...t,awaitAutomatedChecksBeforeDialog:!0}),p!==void 0&&(t={...t,alwaysAllowRules:{cliArg:e.toolPermissionContext.alwaysAllowRules.cliArg,session:[...p]}}),t===e.toolPermissionContext?e:{...e,toolPermissionContext:t}},se=g?f:hGe(e,f,i).resolvedTools,ce=Array.from(x.toolPermissionContext.additionalWorkingDirectories.keys()),M=c?.systemPrompt?c.systemPrompt:gv(await VGe(e,n,w,ce,se)),N=c?.abortController?c.abortController:i?new AbortController:n.abortController,le=[];for await(let t of dlt(T,e.agentType,N.signal))t.additionalContexts&&t.additionalContexts.length>0&&le.push(...t.additionalContexts);if(le.length>0){let e=r2({type:`hook_additional_context`,content:le,hookName:`SubagentStart`,toolUseID:Jc(),hookEvent:`SubagentStart`});E.push(e)}let ue=!fx(`hooks`)||px(e.source);e.hooks&&ue&&LGe(C,T,e.hooks,`agent '${e.agentType}'`,!0);let de=e.skills??[];if(de.length>0){let t=await X3(en()),r=[];for(let n of de){let i=HGe(n,t,e);if(!i){G(`[Agent: ${e.agentType}] Warning: Skill '${n}' specified in frontmatter was not found`,{level:`warn`});continue}let a=zat(i,t);if(a.type!==`prompt`){G(`[Agent: ${e.agentType}] Warning: Skill '${n}' is not a prompt-based skill`,{level:`warn`});continue}r.push({skillName:n,skill:a})}let{formatSkillLoadingMetadata:i}=await import(`./processSlashCommand-DOQFjJ88.js`),a=await Promise.all(r.map(async({skillName:e,skill:t})=>({skillName:e,skill:t,content:await t.getPromptForCommand(``,n)})));for(let{skillName:t,skill:n,content:r}of a){G(`[Agent: ${e.agentType}] Preloaded skill '${t}'`);let a=i(t,n.progressMessage);E.push(Q({content:[{type:`text`,text:a},...r],isMeta:!0}))}}let{clients:fe,tools:pe,cleanup:me}=await zGe(e,n.options.mcpClients),he=pe.length>0?kg([...se,...pe],`name`):se,ge=r0(n,{options:{isNonInteractiveSession:g?n.options.isNonInteractiveSession:i?!0:n.options.isNonInteractiveSession??!1,appendSystemPrompt:n.options.appendSystemPrompt,tools:he,commands:[],debug:n.options.debug,verbose:n.options.verbose,mainLoopModel:w,thinkingConfig:g?n.options.thinkingConfig:{type:`disabled`},mcpClients:fe,mcpResources:n.options.mcpResources,agentDefinitions:n.options.agentDefinitions,...g&&{querySource:s}},agentId:T,agentType:e.agentType,messages:E,readFileState:D,abortController:N,getAppState:oe,shareSetAppState:!i,shareSetResponseLength:!0,criticalSystemReminder_EXPERIMENTAL:e.criticalSystemReminder_EXPERIMENTAL,contentReplacementState:h});d&&(ge.preserveToolUseResults=!0),m&&m({systemPrompt:M,userContext:ne,systemContext:ae,toolUseContext:ge,forkContextMessages:E}),S6(E,T).catch(e=>G(`Failed to record sidechain transcript: ${e}`)),g6(T,{agentType:e.agentType,..._&&{worktreePath:_},...v&&{description:v}}).catch(e=>G(`Failed to write agent metadata: ${e}`));let _e=E.at(-1)?.uuid??null;try{for await(let t of Q1({messages:E,systemPrompt:M,userContext:ne,systemContext:ae,canUseTool:r,toolUseContext:ge,querySource:s,maxTurns:u??e.maxTurns})){if(b?.(),t.type===`stream_event`&&t.event.type===`message_start`&&t.ttftMs!=null){n.pushApiMetricsEntry?.(t.ttftMs);continue}if(t.type===`attachment`){if(t.attachment.type===`max_turns_reached`){G(`[Agent
|
|
1599
1599
|
: $
|
|
1600
1600
|
{
|
|
1601
1601
|
agentDefinition.agentType
|
|
@@ -1637,7 +1637,7 @@ Rejected plan:
|
|
|
1637
1637
|
`);{let e=s.getAppState(),t=await _Y({agentMessages:i,tools:s.options.tools,toolPermissionContext:e.toolPermissionContext,abortSignal:a.abortController.signal,subagentType:v.agentType,totalToolUseCount:c.totalToolUseCount});t&&(l=`${t}\n\n${l}`)}let u=await re();P0({taskId:o,description:n,status:`completed`,setAppState:h,finalMessage:l,usage:{totalTokens:k0(t),toolUses:c.totalToolUseCount,durationMs:c.totalDurationMs},toolUseId:s.toolUseId,...u})}catch(e){if(e instanceof Wn){F0(o,h),Y(`tengu_agent_tool_terminated`,{agent_type:T.agentType,model:T.resolvedAgentModel,duration_ms:Date.now()-T.startTime,is_async:!0,is_built_in_agent:T.isBuiltInAgent,reason:`user_cancel_background`});let e=await re(),t=_Ge(i);P0({taskId:o,description:n,status:`killed`,setAppState:h,toolUseId:s.toolUseId,finalMessage:t,...e});return}let t=W(e);K7e(o,t,h);let r=await re();P0({taskId:o,description:n,status:`failed`,error:t,setAppState:h,toolUseId:s.toolUseId,...r})}finally{e?.(),Pn(t)}});let c=s.options.tools.some(e=>Cs(e,`Read`)||Cs(e,`Bash`));return{data:{isAsync:!0,status:`async_launched`,agentId:o,description:n,prompt:e,outputFile:V8(o),canReadOutputFile:c}}}}if(S.type!==`message`)continue;let{result:C}=S;if(C.done)break;let w=C.value;if(i.push(w),A0(o,w,c,s.options.tools),f){let e=hY(w);e&&(gY(o,f,s.toolUseId,n,a,e),hn()&&I0(f,j0(o),h))}if(w.type===`progress`&&(w.data?.type===`bash_progress`||w.data?.type===`powershell_progress`)&&u&&u({toolUseID:w.toolUseID,data:w.data}),w.type!==`assistant`&&w.type!==`user`)continue;if(w.type===`assistant`){let e=YL(w);e>0&&s.setResponseLength(t=>t+e)}let E=s3([w]);for(let e of E)for(let n of e.message?.content??[])n.type!==`tool_use`&&n.type!==`tool_result`||u&&u({toolUseID:`agent_${l.message.id}`,data:{message:e,type:`agent_progress`,prompt:``,agentId:t}})}}catch(e){if(e instanceof Wn)throw C=!0,Y(`tengu_agent_tool_terminated`,{agent_type:T.agentType,model:T.resolvedAgentModel,duration_ms:Date.now()-T.startTime,is_async:!1,is_built_in_agent:T.isBuiltInAgent,reason:`user_cancel_sync`}),e;G(`Sync agent error: ${W(e)}`,{level:`error`}),S=tr(e)}finally{if(s.setToolJSX&&s.setToolJSX(null),y?.(),f&&(X7e(f,h),!_)){let e=j0(o);UI({type:`system`,subtype:`task_notification`,task_id:f,tool_use_id:s.toolUseId,status:S?`failed`:C?`stopped`:`completed`,output_file:``,summary:n,usage:{total_tokens:e.tokenCount,tool_uses:e.toolUseCount,duration_ms:Date.now()-a}})}Pn(t),m?.(),_||(E=await re())}let D=i.findLast(e=>e.type!==`system`&&e.type!==`progress`);if(D&&Hge(D))throw Y(`tengu_agent_tool_terminated`,{agent_type:T.agentType,model:T.resolvedAgentModel,duration_ms:Date.now()-T.startTime,is_async:!1,is_built_in_agent:T.isBuiltInAgent,reason:`user_cancel_sync`}),new Wn;if(S){if(!i.some(e=>e.type===`assistant`))throw S;G(`Sync agent recovering from error with ${i.length} messages`)}let O=mY(i,t,T);{let e=s.getAppState(),t=await _Y({agentMessages:i,tools:s.options.tools,toolPermissionContext:e.toolPermissionContext,abortSignal:s.abortController.signal,subagentType:v.agentType,totalToolUseCount:O.totalToolUseCount});t&&(O.content=[{type:`text`,text:t},...O.content])}return{data:{status:`completed`,prompt:e,...O,...E}}}))}},isReadOnly(){return!0},toAutoClassifierInput(e){let t=e,n=[t.subagent_type].filter(e=>e!==void 0);return`${n.length>0?`(${n.join(`, `)}): `:`: `}${t.prompt}`},isConcurrencySafe(){return!0},userFacingName:lXe,userFacingNameBackgroundColor:uXe,getActivityDescription(e){return e?.description??`Running task`},async checkPermissions(e,t){return{behavior:`allow`,updatedInput:e}},mapToolResultToToolResultBlockParam(e,t){let n=e;if(`status`in n&&n.status===`remote_launched`){let e=n;return{tool_use_id:t,type:`tool_result`,content:[{type:`text`,text:`Remote agent launched in CCR.\ntaskId: ${e.taskId}\nsession_url: ${e.sessionUrl}\noutput_file: ${e.outputFile}\nThe agent is running remotely. You will be notified automatically when it completes.\nBriefly tell the user what you launched and end your response.`}]}}if(e.status===`async_launched`)return{tool_use_id:t,type:`tool_result`,content:[{type:`text`,text:`${`Async agent launched successfully.\nagentId: ${e.agentId} (internal ID - do not mention to user. Use SendMessage with to: '${e.agentId}' to continue this agent.)\nThe agent is working in the background. You will be notified automatically when it completes.`}\n${e.canReadOutputFile?`Do not duplicate this agent's work — avoid working with the same files or topics it is using. Work on non-overlapping tasks, or briefly tell the user what you launched and end your response.\noutput_file: ${e.outputFile}\nIf asked, you can check progress before completion by using ${ys} or ${Vs} tail on the output file.`:`Briefly tell the user what you launched and end your response. Do not generate any other text — agent results will arrive in a subsequent message.`}`}]};if(e.status===`completed`){let n=e,r=n.worktreePath?`\nworktreePath: ${n.worktreePath}\nworktreeBranch: ${n.worktreeBranch}`:``,i=e.content.length>0?e.content:[{type:`text`,text:`(Subagent completed but returned no output.)`}];return e.agentType&&cre.has(e.agentType)&&!r?Ys(t,i):{tool_use_id:t,type:`tool_result`,content:[...i,{type:`text`,text:`agentId: ${e.agentId} (use SendMessage with to: '${e.agentId}' to continue this agent)${r}
|
|
1638
1638
|
<usage>total_tokens: ${e.totalTokens}
|
|
1639
1639
|
tool_uses: ${e.totalToolUseCount}
|
|
1640
|
-
duration_ms: ${e.totalDurationMs}</usage>`}]}}throw Error(`Unexpected agent tool result status: ${e.status}`)},renderToolResultMessage:nXe,renderToolUseMessage:rXe,renderToolUseTag:iXe,renderToolUseProgressMessage:vZ,renderToolUseRejectedMessage:aXe,renderToolUseErrorMessage:oXe,renderGroupedToolUse:cXe})}));function SXe(e,t){let n=t?`${e}@${t.toLowerCase()}`:e;return Kc(`sha256`).update(n+kXe).digest(`hex`).slice(0,16)}function CXe(e,t,n){return t===OXe?`default-bundle`:Ey(t)?`official`:n?.has(e)?`org`:`user-local`}function wXe(e,t,n){return e.isBuiltin?`default-enable`:t?.has(e.name)?`org-policy`:n.some(t=>e.path.startsWith(t.endsWith(kc)?t:t+kc))?`seed-mount`:`user-install`}function EZ(e,t,n=null){let r=CXe(e,t,n),i=r===`official`||r===`default-bundle`;return{plugin_id_hash:SXe(e,t),plugin_scope:r,plugin_name_redacted:i?e:`third-party`,marketplace_name_redacted:i&&t?t:`third-party`,is_official_plugin:i}}function DZ(e,t=null){let{marketplace:n}=Ty(e.repository);return EZ(e.pluginManifest.name,n,t)}function TXe(e,t,n){for(let r of e){let{marketplace:e}=Ty(r.repository);Y(`tengu_plugin_enabled_for_session`,{_PROTO_plugin_name:r.name,...e&&{_PROTO_marketplace_name:e},...EZ(r.name,e,t),enabled_via:wXe(r,t,n),skill_path_count:+!!r.skillsPath+(r.skillsPaths?.length??0),command_path_count:+!!r.commandsPath+(r.commandsPaths?.length??0),has_mcp:r.manifest.mcpServers!==void 0,has_hooks:r.hooksConfig!==void 0,...r.manifest.version&&{version:r.manifest.version}})}}function EXe(e){let t=String(e?.message??e);return/ENOTFOUND|ECONNREFUSED|EAI_AGAIN|ETIMEDOUT|ECONNRESET|network|Could not resolve|Connection refused|timed out/i.test(t)?`network`:/\b404\b|not found|does not exist|no such plugin/i.test(t)?`not-found`:/\b40[13]\b|EACCES|EPERM|permission denied|unauthorized/i.test(t)?`permission`:/invalid|malformed|schema|validation|parse error/i.test(t)?`validation`:`unknown`}function DXe(e,t){for(let n of e){let{name:e,marketplace:r}=Ty(n.source),i=`plugin`in n&&n.plugin?n.plugin:e;Y(`tengu_plugin_load_failed`,{error_category:n.type,_PROTO_plugin_name:i,...r&&{_PROTO_marketplace_name:r},...EZ(i,r,t)})}}var OXe,kXe,OZ=n((()=>{oo(),Dy(),OXe=`builtin`,kXe=`claude-plugin-telemetry-v1`}));function AXe(e){let t=Date.now(),n=kZ.get(e);n!==void 0&&t-n<MXe||(kZ.set(e,t),aa(n=>{let r=n.skillUsage?.[e];return{...n,skillUsage:{...n.skillUsage,[e]:{usageCount:(r?.usageCount??0)+1,lastUsedAt:t}}}}))}function jXe(e){let t=ha().skillUsage?.[e];if(!t)return 0;let n=.5**((Date.now()-t.lastUsedAt)/(1e3*60*60*24)/7);return t.usageCount*Math.max(n,.1)}var MXe,kZ,NXe=n((()=>{ma(),MXe=6e4,kZ=new Map}));function PXe(e,t){return t?e.map(e=>e.type===`user`?{...e,sourceToolUseID:t}:e):e}function FXe(e,t){let n=Array.isArray(e.message.content)?e.message.content.find(e=>e.type===`tool_use`&&e.name===t):void 0;return n&&n.type===`tool_use`?n.id:void 0}var IXe=n((()=>{}));function LXe(e){if(`status`in e&&e.status===`forked`)return(0,jZ.jsx)($,{height:1,children:(0,jZ.jsx)(F,{children:(0,jZ.jsx)($e,{children:[`Done`]})})});let t=[`Successfully loaded skill`];if(`allowedTools`in e&&e.allowedTools&&e.allowedTools.length>0){let n=e.allowedTools.length;t.push(`${n} ${Za(n,`tool`)} allowed`)}return`model`in e&&e.model&&t.push(e.model),(0,jZ.jsx)($,{height:1,children:(0,jZ.jsx)(F,{children:(0,jZ.jsx)($e,{children:t})})})}function RXe({skill:e},{commands:t}){return e?t?.find(t=>t.name===e)?.loadedFrom===`commands_DEPRECATED`?`/${e}`:e:null}function AZ(e,{tools:t,verbose:n}){if(!e.length)return(0,jZ.jsx)($,{height:1,children:(0,jZ.jsx)(F,{dimColor:!0,children:VXe})});let r=n?e:e.slice(-3),i=e.length-r.length,{inProgressToolUseIDs:a}=p3(e.map(e=>e.data));return(0,jZ.jsx)($,{children:(0,jZ.jsxs)(P,{flexDirection:`column`,children:[(0,jZ.jsx)(iC,{children:r.map(e=>(0,jZ.jsx)(P,{height:1,overflow:`hidden`,children:(0,jZ.jsx)(mZ,{message:e.data.message,lookups:m3,addMargin:!1,tools:t,commands:[],verbose:n,inProgressToolUseIDs:a,progressMessagesForMessage:[],shouldAnimate:!1,shouldShowDot:!1,style:`condensed`,isTranscriptMode:!1,isStatic:!0})},e.uuid))}),i>0&&(0,jZ.jsxs)(F,{dimColor:!0,children:[`+`,i,` more tool `,Za(i,`use`)]})]})})}function zXe(e,{progressMessagesForMessage:t,tools:n,verbose:r}){return(0,jZ.jsxs)(jZ.Fragment,{children:[AZ(t,{tools:n,verbose:r}),(0,jZ.jsx)(NY,{})]})}function BXe(e,{progressMessagesForMessage:t,tools:n,verbose:r}){return(0,jZ.jsxs)(jZ.Fragment,{children:[AZ(t,{tools:n,verbose:r}),(0,jZ.jsx)(SC,{result:e,verbose:r})]})}var jZ,VXe,HXe=n((()=>{lC(),TC(),FY(),ct(),hZ(),_C(),h3(),$a(),jZ=ut(),VXe=`Initializing…`})),UXe=i({getDiscoveredRemoteSkill:()=>GXe,stripCanonicalPrefix:()=>WXe});function WXe(e){return null}function GXe(e){}var KXe=n((()=>{})),qXe=i({loadRemoteSkill:()=>JXe});function JXe(e,t){return Promise.resolve({cacheHit:!1,latencyMs:0,skillPath:``,content:``})}var YXe=n((()=>{})),XXe=i({logRemoteSkillLoaded:()=>ZXe});function ZXe(e){}var QXe=n((()=>{}));async function MZ(e){let t=e.getAppState().mcp.commands.filter(e=>e.type===`prompt`&&e.loadedFrom===`mcp`);return t.length===0?W3(en()):kg([...await W3(en()),...t],`name`)}async function $Xe(e,t,n,r,i,a,o){let s=Date.now(),c=oY(),l=J3().has(t),u=tZe(e),d=e.source===`bundled`,f=l||d||u?t:`custom`,p=NZ.isSkillSearchEnabled()?{was_discovered:r.discoveredSkillNames?.has(t)??!1}:{},m=e.pluginInfo?Ty(e.pluginInfo.repository).marketplace:void 0,h=r.queryTracking?.depth??0,g=ke()?.agentId;Y(`tengu_skill_tool_invocation`,{command_name:f,_PROTO_skill_name:t,execution_context:`fork`,invocation_trigger:h>0?`nested-skill`:`claude-proactive`,query_depth:h,...g&&{parent_agent_id:g},...p,...e.pluginInfo&&{_PROTO_plugin_name:e.pluginInfo.pluginManifest.name,...m&&{_PROTO_marketplace_name:m},plugin_name:u?e.pluginInfo.pluginManifest.name:`third-party`,plugin_repository:u?e.pluginInfo.repository:`third-party`,...DZ(e.pluginInfo)}});let{modifiedGetAppState:_,baseAgent:v,promptMessages:y,skillContent:b}=await K5e(e,n||``,r),x=[];G(`SkillTool executing forked skill ${t} with agent ${v.agentType}`);try{for await(let t of TY({agentDefinition:v,promptMessages:y,toolUseContext:{...r,getAppState:_},canUseTool:i,isAsync:!1,querySource:`agent:custom`,model:e.model,availableTools:r.options.tools,override:{agentId:c}}))if(x.push(t),(t.type===`assistant`||t.type===`user`)&&o){let e=s3([t]);for(let t of e){let e=t.message?.content;Array.isArray(e)&&e.some(e=>e.type===`tool_use`||e.type===`tool_result`)&&o({toolUseID:`skill_${a.message.id}`,data:{message:t,type:`skill_progress`,prompt:b,agentId:c}})}}let n=q5e(x,`Skill execution completed`);return x.length=0,G(`SkillTool forked skill ${t} completed in ${Date.now()-s}ms`),{data:{success:!0,commandName:t,status:`forked`,agentId:c,result:n}}}finally{Pn(c)}}function eZe(e){for(let t of Object.keys(e)){if(iZe.has(t))continue;let n=e[t];if(n!=null&&!(Array.isArray(n)&&n.length===0)&&!(typeof n==`object`&&!Array.isArray(n)&&Object.keys(n).length===0))return!1}return!0}function tZe(e){return e.source!==`plugin`||!e.pluginInfo?.repository?!1:Ey(Ty(e.pluginInfo.repository).marketplace)}var NZ,nZe,rZe,PZ,iZe,aZe=n((()=>{Ag(),Jt(),Q3(),Ks(),K(),A9(),Dy(),OZ(),Nt(),Ka(),oo(),xe(),o0(),kt(),h3(),Uo(),NXe(),sY(),EY(),IXe(),Zs(),hb(),HXe(),KXe(),YXe(),QXe(),oh(),NZ={...UXe,...qXe,...XXe,...rh},nZe=V(()=>I({skill:B().describe(`The skill name. E.g., "commit", "review-pr", or "pdf"`),args:B().optional().describe(`Optional arguments for the skill`)})),rZe=V(()=>yt([I({success:pt().describe(`Whether the skill is valid`),commandName:B().describe(`The name of the skill`),allowedTools:L(B()).optional().describe(`Tools allowed by this skill`),model:B().optional().describe(`Model override if specified`),status:R(`inline`).optional().describe(`Execution status`)}),I({success:pt().describe(`Whether the skill completed successfully`),commandName:B().describe(`The name of the skill`),status:R(`forked`).describe(`Execution status`),agentId:B().describe(`The ID of the sub-agent that executed the skill`),result:B().describe(`The result from the forked skill execution`)})])),PZ=Ns({name:ps,searchHint:`invoke a slash-command skill`,maxResultSizeChars:1e5,get inputSchema(){return nZe()},get outputSchema(){return rZe()},description:async({skill:e})=>`Execute skill: ${e}`,prompt:async()=>mb(en()),toAutoClassifierInput:({skill:e})=>e??``,async validateInput({skill:e},t){let n=e.trim();if(!n)return{result:!1,message:`Invalid skill format: ${e}`,errorCode:1};let r=n.startsWith(`/`);r&&Y(`tengu_skill_tool_slash_prefix`,{});let i=r?n.substring(1):n,a=G3(i,await MZ(t));return a?a.disableModelInvocation?{result:!1,message:`Skill ${i} cannot be used with ${ps} tool due to disable-model-invocation`,errorCode:4}:a.type===`prompt`?{result:!0}:{result:!1,message:`Skill ${i} is not a prompt-based skill`,errorCode:5}:{result:!1,message:`Unknown skill: ${i}`,errorCode:2}},async checkPermissions({skill:e,args:t},n){let r=e.trim(),i=r.startsWith(`/`)?r.substring(1):r,a=n.getAppState().toolPermissionContext,o=G3(i,await MZ(n)),s=e=>{let t=e.startsWith(`/`)?e.substring(1):e;if(t===i)return!0;if(t.endsWith(`:*`)){let e=t.slice(0,-2);return i.startsWith(e)}return!1},c=T9(a,PZ,`deny`);for(let[e,t]of c.entries())if(s(e))return{behavior:`deny`,message:`Skill execution blocked by permission rules`,decisionReason:{type:`rule`,rule:t}};let l=T9(a,PZ,`allow`);for(let[n,r]of l.entries())if(s(n))return{behavior:`allow`,updatedInput:{skill:e,args:t},decisionReason:{type:`rule`,rule:r}};if(o?.type===`prompt`&&eZe(o))return{behavior:`allow`,updatedInput:{skill:e,args:t},decisionReason:void 0};let u=[{type:`addRules`,rules:[{toolName:ps,ruleContent:i}],behavior:`allow`,destination:`localSettings`},{type:`addRules`,rules:[{toolName:ps,ruleContent:`${i}:*`}],behavior:`allow`,destination:`localSettings`}];return{behavior:`ask`,message:`Execute skill: ${i}`,decisionReason:void 0,suggestions:u,updatedInput:{skill:e,args:t},metadata:o?{command:o}:void 0}},async call({skill:e,args:t},n,r,i,a){let o=e.trim(),s=o.startsWith(`/`)?o.substring(1):o,c=await MZ(n),l=G3(s,c);if(AXe(s),l?.type===`prompt`&&l.context===`fork`)return $Xe(l,s,t,n,r,i,a);let{processPromptSlashCommand:u}=await import(`./processSlashCommand-Cq9kaoSF.js`),d=await u(s,t||``,c,n);if(!d.shouldQuery)throw Error(`Command processing failed`);let f=d.allowedTools||[],p=d.model,m=J3().has(s),h=l?.type===`prompt`&&l.source===`bundled`,g=l?.type===`prompt`&&tZe(l),_=m||h||g?s:`custom`,v=NZ.isSkillSearchEnabled()?{was_discovered:n.discoveredSkillNames?.has(s)??!1}:{},y=l?.type===`prompt`&&l.pluginInfo?Ty(l.pluginInfo.repository).marketplace:void 0,b=n.queryTracking?.depth??0,x=ke()?.agentId;Y(`tengu_skill_tool_invocation`,{command_name:_,_PROTO_skill_name:s,execution_context:`inline`,invocation_trigger:b>0?`nested-skill`:`claude-proactive`,query_depth:b,...x&&{parent_agent_id:x},...v,...l?.type===`prompt`&&l.pluginInfo&&{_PROTO_plugin_name:l.pluginInfo.pluginManifest.name,...y&&{_PROTO_marketplace_name:y},plugin_name:g?l.pluginInfo.pluginManifest.name:`third-party`,plugin_repository:g?l.pluginInfo.repository:`third-party`,...DZ(l.pluginInfo)}});let S=FXe(i,ps),C=PXe(d.messages.filter(e=>{if(e.type===`progress`)return!1;if(e.type===`user`&&`message`in e){let t=e.message.content;if(typeof t==`string`&&t.includes(`<command-message>`))return!1}return!0}),S);return G(`SkillTool returning ${C.length} newMessages for skill ${s}`),{data:{success:!0,commandName:s,allowedTools:f.length>0?f:void 0,model:p},newMessages:C,contextModifier(e){let t=e;if(f.length>0){let e=t.getAppState;t={...t,getAppState(){let t=e();return{...t,toolPermissionContext:{...t.toolPermissionContext,alwaysAllowRules:{...t.toolPermissionContext.alwaysAllowRules,command:[...new Set([...t.toolPermissionContext.alwaysAllowRules.command||[],...f])]}}}}}}return p&&(t={...t,options:{...t.options,mainLoopModel:rae(p,e.options.mainLoopModel)}}),t}}},mapToolResultToToolResultBlockParam(e,t){return`status`in e&&e.status===`forked`?{type:`tool_result`,tool_use_id:t,content:`Skill "${e.commandName}" completed (forked execution).\n\nResult:\n${e.result}`}:{type:`tool_result`,tool_use_id:t,content:`Launching skill: ${e.commandName}`}},renderToolResultMessage:LXe,renderToolUseMessage:RXe,renderToolUseProgressMessage:AZ,renderToolUseRejectedMessage:zXe,renderToolUseErrorMessage:BXe}),iZe=new Set(`type.progressMessage.contentLength.argNames.model.source.pluginInfo.disableNonInteractive.skillRoot.context.agent.getPromptForCommand.frontmatterKeys.name.description.hasUserSpecifiedDescription.isEnabled.isHidden.aliases.isMcp.argumentHint.whenToUse.paths.version.disableModelInvocation.userInvocable.loadedFrom.immediate.userFacingName`.split(`.`))}));function oZe(e,t,n){let{head:r,tail:i,mtime:a,size:o}=t,s=r.indexOf(`
|
|
1640
|
+
duration_ms: ${e.totalDurationMs}</usage>`}]}}throw Error(`Unexpected agent tool result status: ${e.status}`)},renderToolResultMessage:nXe,renderToolUseMessage:rXe,renderToolUseTag:iXe,renderToolUseProgressMessage:vZ,renderToolUseRejectedMessage:aXe,renderToolUseErrorMessage:oXe,renderGroupedToolUse:cXe})}));function SXe(e,t){let n=t?`${e}@${t.toLowerCase()}`:e;return Kc(`sha256`).update(n+kXe).digest(`hex`).slice(0,16)}function CXe(e,t,n){return t===OXe?`default-bundle`:Ey(t)?`official`:n?.has(e)?`org`:`user-local`}function wXe(e,t,n){return e.isBuiltin?`default-enable`:t?.has(e.name)?`org-policy`:n.some(t=>e.path.startsWith(t.endsWith(kc)?t:t+kc))?`seed-mount`:`user-install`}function EZ(e,t,n=null){let r=CXe(e,t,n),i=r===`official`||r===`default-bundle`;return{plugin_id_hash:SXe(e,t),plugin_scope:r,plugin_name_redacted:i?e:`third-party`,marketplace_name_redacted:i&&t?t:`third-party`,is_official_plugin:i}}function DZ(e,t=null){let{marketplace:n}=Ty(e.repository);return EZ(e.pluginManifest.name,n,t)}function TXe(e,t,n){for(let r of e){let{marketplace:e}=Ty(r.repository);Y(`tengu_plugin_enabled_for_session`,{_PROTO_plugin_name:r.name,...e&&{_PROTO_marketplace_name:e},...EZ(r.name,e,t),enabled_via:wXe(r,t,n),skill_path_count:+!!r.skillsPath+(r.skillsPaths?.length??0),command_path_count:+!!r.commandsPath+(r.commandsPaths?.length??0),has_mcp:r.manifest.mcpServers!==void 0,has_hooks:r.hooksConfig!==void 0,...r.manifest.version&&{version:r.manifest.version}})}}function EXe(e){let t=String(e?.message??e);return/ENOTFOUND|ECONNREFUSED|EAI_AGAIN|ETIMEDOUT|ECONNRESET|network|Could not resolve|Connection refused|timed out/i.test(t)?`network`:/\b404\b|not found|does not exist|no such plugin/i.test(t)?`not-found`:/\b40[13]\b|EACCES|EPERM|permission denied|unauthorized/i.test(t)?`permission`:/invalid|malformed|schema|validation|parse error/i.test(t)?`validation`:`unknown`}function DXe(e,t){for(let n of e){let{name:e,marketplace:r}=Ty(n.source),i=`plugin`in n&&n.plugin?n.plugin:e;Y(`tengu_plugin_load_failed`,{error_category:n.type,_PROTO_plugin_name:i,...r&&{_PROTO_marketplace_name:r},...EZ(i,r,t)})}}var OXe,kXe,OZ=n((()=>{oo(),Dy(),OXe=`builtin`,kXe=`claude-plugin-telemetry-v1`}));function AXe(e){let t=Date.now(),n=kZ.get(e);n!==void 0&&t-n<MXe||(kZ.set(e,t),aa(n=>{let r=n.skillUsage?.[e];return{...n,skillUsage:{...n.skillUsage,[e]:{usageCount:(r?.usageCount??0)+1,lastUsedAt:t}}}}))}function jXe(e){let t=ha().skillUsage?.[e];if(!t)return 0;let n=.5**((Date.now()-t.lastUsedAt)/(1e3*60*60*24)/7);return t.usageCount*Math.max(n,.1)}var MXe,kZ,NXe=n((()=>{ma(),MXe=6e4,kZ=new Map}));function PXe(e,t){return t?e.map(e=>e.type===`user`?{...e,sourceToolUseID:t}:e):e}function FXe(e,t){let n=Array.isArray(e.message.content)?e.message.content.find(e=>e.type===`tool_use`&&e.name===t):void 0;return n&&n.type===`tool_use`?n.id:void 0}var IXe=n((()=>{}));function LXe(e){if(`status`in e&&e.status===`forked`)return(0,jZ.jsx)($,{height:1,children:(0,jZ.jsx)(F,{children:(0,jZ.jsx)($e,{children:[`Done`]})})});let t=[`Successfully loaded skill`];if(`allowedTools`in e&&e.allowedTools&&e.allowedTools.length>0){let n=e.allowedTools.length;t.push(`${n} ${Za(n,`tool`)} allowed`)}return`model`in e&&e.model&&t.push(e.model),(0,jZ.jsx)($,{height:1,children:(0,jZ.jsx)(F,{children:(0,jZ.jsx)($e,{children:t})})})}function RXe({skill:e},{commands:t}){return e?t?.find(t=>t.name===e)?.loadedFrom===`commands_DEPRECATED`?`/${e}`:e:null}function AZ(e,{tools:t,verbose:n}){if(!e.length)return(0,jZ.jsx)($,{height:1,children:(0,jZ.jsx)(F,{dimColor:!0,children:VXe})});let r=n?e:e.slice(-3),i=e.length-r.length,{inProgressToolUseIDs:a}=p3(e.map(e=>e.data));return(0,jZ.jsx)($,{children:(0,jZ.jsxs)(P,{flexDirection:`column`,children:[(0,jZ.jsx)(iC,{children:r.map(e=>(0,jZ.jsx)(P,{height:1,overflow:`hidden`,children:(0,jZ.jsx)(mZ,{message:e.data.message,lookups:m3,addMargin:!1,tools:t,commands:[],verbose:n,inProgressToolUseIDs:a,progressMessagesForMessage:[],shouldAnimate:!1,shouldShowDot:!1,style:`condensed`,isTranscriptMode:!1,isStatic:!0})},e.uuid))}),i>0&&(0,jZ.jsxs)(F,{dimColor:!0,children:[`+`,i,` more tool `,Za(i,`use`)]})]})})}function zXe(e,{progressMessagesForMessage:t,tools:n,verbose:r}){return(0,jZ.jsxs)(jZ.Fragment,{children:[AZ(t,{tools:n,verbose:r}),(0,jZ.jsx)(NY,{})]})}function BXe(e,{progressMessagesForMessage:t,tools:n,verbose:r}){return(0,jZ.jsxs)(jZ.Fragment,{children:[AZ(t,{tools:n,verbose:r}),(0,jZ.jsx)(SC,{result:e,verbose:r})]})}var jZ,VXe,HXe=n((()=>{lC(),TC(),FY(),ct(),hZ(),_C(),h3(),$a(),jZ=ut(),VXe=`Initializing…`})),UXe=i({getDiscoveredRemoteSkill:()=>GXe,stripCanonicalPrefix:()=>WXe});function WXe(e){return null}function GXe(e){}var KXe=n((()=>{})),qXe=i({loadRemoteSkill:()=>JXe});function JXe(e,t){return Promise.resolve({cacheHit:!1,latencyMs:0,skillPath:``,content:``})}var YXe=n((()=>{})),XXe=i({logRemoteSkillLoaded:()=>ZXe});function ZXe(e){}var QXe=n((()=>{}));async function MZ(e){let t=e.getAppState().mcp.commands.filter(e=>e.type===`prompt`&&e.loadedFrom===`mcp`);return t.length===0?W3(en()):kg([...await W3(en()),...t],`name`)}async function $Xe(e,t,n,r,i,a,o){let s=Date.now(),c=oY(),l=J3().has(t),u=tZe(e),d=e.source===`bundled`,f=l||d||u?t:`custom`,p=NZ.isSkillSearchEnabled()?{was_discovered:r.discoveredSkillNames?.has(t)??!1}:{},m=e.pluginInfo?Ty(e.pluginInfo.repository).marketplace:void 0,h=r.queryTracking?.depth??0,g=ke()?.agentId;Y(`tengu_skill_tool_invocation`,{command_name:f,_PROTO_skill_name:t,execution_context:`fork`,invocation_trigger:h>0?`nested-skill`:`claude-proactive`,query_depth:h,...g&&{parent_agent_id:g},...p,...e.pluginInfo&&{_PROTO_plugin_name:e.pluginInfo.pluginManifest.name,...m&&{_PROTO_marketplace_name:m},plugin_name:u?e.pluginInfo.pluginManifest.name:`third-party`,plugin_repository:u?e.pluginInfo.repository:`third-party`,...DZ(e.pluginInfo)}});let{modifiedGetAppState:_,baseAgent:v,promptMessages:y,skillContent:b}=await K5e(e,n||``,r),x=[];G(`SkillTool executing forked skill ${t} with agent ${v.agentType}`);try{for await(let t of TY({agentDefinition:v,promptMessages:y,toolUseContext:{...r,getAppState:_},canUseTool:i,isAsync:!1,querySource:`agent:custom`,model:e.model,availableTools:r.options.tools,override:{agentId:c}}))if(x.push(t),(t.type===`assistant`||t.type===`user`)&&o){let e=s3([t]);for(let t of e){let e=t.message?.content;Array.isArray(e)&&e.some(e=>e.type===`tool_use`||e.type===`tool_result`)&&o({toolUseID:`skill_${a.message.id}`,data:{message:t,type:`skill_progress`,prompt:b,agentId:c}})}}let n=q5e(x,`Skill execution completed`);return x.length=0,G(`SkillTool forked skill ${t} completed in ${Date.now()-s}ms`),{data:{success:!0,commandName:t,status:`forked`,agentId:c,result:n}}}finally{Pn(c)}}function eZe(e){for(let t of Object.keys(e)){if(iZe.has(t))continue;let n=e[t];if(n!=null&&!(Array.isArray(n)&&n.length===0)&&!(typeof n==`object`&&!Array.isArray(n)&&Object.keys(n).length===0))return!1}return!0}function tZe(e){return e.source!==`plugin`||!e.pluginInfo?.repository?!1:Ey(Ty(e.pluginInfo.repository).marketplace)}var NZ,nZe,rZe,PZ,iZe,aZe=n((()=>{Ag(),Jt(),Q3(),Ks(),K(),A9(),Dy(),OZ(),Nt(),Ka(),oo(),xe(),o0(),kt(),h3(),Uo(),NXe(),sY(),EY(),IXe(),Zs(),hb(),HXe(),KXe(),YXe(),QXe(),oh(),NZ={...UXe,...qXe,...XXe,...rh},nZe=V(()=>I({skill:B().describe(`The skill name. E.g., "commit", "review-pr", or "pdf"`),args:B().optional().describe(`Optional arguments for the skill`)})),rZe=V(()=>yt([I({success:pt().describe(`Whether the skill is valid`),commandName:B().describe(`The name of the skill`),allowedTools:L(B()).optional().describe(`Tools allowed by this skill`),model:B().optional().describe(`Model override if specified`),status:R(`inline`).optional().describe(`Execution status`)}),I({success:pt().describe(`Whether the skill completed successfully`),commandName:B().describe(`The name of the skill`),status:R(`forked`).describe(`Execution status`),agentId:B().describe(`The ID of the sub-agent that executed the skill`),result:B().describe(`The result from the forked skill execution`)})])),PZ=Ns({name:ps,searchHint:`invoke a slash-command skill`,maxResultSizeChars:1e5,get inputSchema(){return nZe()},get outputSchema(){return rZe()},description:async({skill:e})=>`Execute skill: ${e}`,prompt:async()=>mb(en()),toAutoClassifierInput:({skill:e})=>e??``,async validateInput({skill:e},t){let n=e.trim();if(!n)return{result:!1,message:`Invalid skill format: ${e}`,errorCode:1};let r=n.startsWith(`/`);r&&Y(`tengu_skill_tool_slash_prefix`,{});let i=r?n.substring(1):n,a=G3(i,await MZ(t));return a?a.disableModelInvocation?{result:!1,message:`Skill ${i} cannot be used with ${ps} tool due to disable-model-invocation`,errorCode:4}:a.type===`prompt`?{result:!0}:{result:!1,message:`Skill ${i} is not a prompt-based skill`,errorCode:5}:{result:!1,message:`Unknown skill: ${i}`,errorCode:2}},async checkPermissions({skill:e,args:t},n){let r=e.trim(),i=r.startsWith(`/`)?r.substring(1):r,a=n.getAppState().toolPermissionContext,o=G3(i,await MZ(n)),s=e=>{let t=e.startsWith(`/`)?e.substring(1):e;if(t===i)return!0;if(t.endsWith(`:*`)){let e=t.slice(0,-2);return i.startsWith(e)}return!1},c=T9(a,PZ,`deny`);for(let[e,t]of c.entries())if(s(e))return{behavior:`deny`,message:`Skill execution blocked by permission rules`,decisionReason:{type:`rule`,rule:t}};let l=T9(a,PZ,`allow`);for(let[n,r]of l.entries())if(s(n))return{behavior:`allow`,updatedInput:{skill:e,args:t},decisionReason:{type:`rule`,rule:r}};if(o?.type===`prompt`&&eZe(o))return{behavior:`allow`,updatedInput:{skill:e,args:t},decisionReason:void 0};let u=[{type:`addRules`,rules:[{toolName:ps,ruleContent:i}],behavior:`allow`,destination:`localSettings`},{type:`addRules`,rules:[{toolName:ps,ruleContent:`${i}:*`}],behavior:`allow`,destination:`localSettings`}];return{behavior:`ask`,message:`Execute skill: ${i}`,decisionReason:void 0,suggestions:u,updatedInput:{skill:e,args:t},metadata:o?{command:o}:void 0}},async call({skill:e,args:t},n,r,i,a){let o=e.trim(),s=o.startsWith(`/`)?o.substring(1):o,c=await MZ(n),l=G3(s,c);if(AXe(s),l?.type===`prompt`&&l.context===`fork`)return $Xe(l,s,t,n,r,i,a);let{processPromptSlashCommand:u}=await import(`./processSlashCommand-DOQFjJ88.js`),d=await u(s,t||``,c,n);if(!d.shouldQuery)throw Error(`Command processing failed`);let f=d.allowedTools||[],p=d.model,m=J3().has(s),h=l?.type===`prompt`&&l.source===`bundled`,g=l?.type===`prompt`&&tZe(l),_=m||h||g?s:`custom`,v=NZ.isSkillSearchEnabled()?{was_discovered:n.discoveredSkillNames?.has(s)??!1}:{},y=l?.type===`prompt`&&l.pluginInfo?Ty(l.pluginInfo.repository).marketplace:void 0,b=n.queryTracking?.depth??0,x=ke()?.agentId;Y(`tengu_skill_tool_invocation`,{command_name:_,_PROTO_skill_name:s,execution_context:`inline`,invocation_trigger:b>0?`nested-skill`:`claude-proactive`,query_depth:b,...x&&{parent_agent_id:x},...v,...l?.type===`prompt`&&l.pluginInfo&&{_PROTO_plugin_name:l.pluginInfo.pluginManifest.name,...y&&{_PROTO_marketplace_name:y},plugin_name:g?l.pluginInfo.pluginManifest.name:`third-party`,plugin_repository:g?l.pluginInfo.repository:`third-party`,...DZ(l.pluginInfo)}});let S=FXe(i,ps),C=PXe(d.messages.filter(e=>{if(e.type===`progress`)return!1;if(e.type===`user`&&`message`in e){let t=e.message.content;if(typeof t==`string`&&t.includes(`<command-message>`))return!1}return!0}),S);return G(`SkillTool returning ${C.length} newMessages for skill ${s}`),{data:{success:!0,commandName:s,allowedTools:f.length>0?f:void 0,model:p},newMessages:C,contextModifier(e){let t=e;if(f.length>0){let e=t.getAppState;t={...t,getAppState(){let t=e();return{...t,toolPermissionContext:{...t.toolPermissionContext,alwaysAllowRules:{...t.toolPermissionContext.alwaysAllowRules,command:[...new Set([...t.toolPermissionContext.alwaysAllowRules.command||[],...f])]}}}}}}return p&&(t={...t,options:{...t.options,mainLoopModel:rae(p,e.options.mainLoopModel)}}),t}}},mapToolResultToToolResultBlockParam(e,t){return`status`in e&&e.status===`forked`?{type:`tool_result`,tool_use_id:t,content:`Skill "${e.commandName}" completed (forked execution).\n\nResult:\n${e.result}`}:{type:`tool_result`,tool_use_id:t,content:`Launching skill: ${e.commandName}`}},renderToolResultMessage:LXe,renderToolUseMessage:RXe,renderToolUseProgressMessage:AZ,renderToolUseRejectedMessage:zXe,renderToolUseErrorMessage:BXe}),iZe=new Set(`type.progressMessage.contentLength.argNames.model.source.pluginInfo.disableNonInteractive.skillRoot.context.agent.getPromptForCommand.frontmatterKeys.name.description.hasUserSpecifiedDescription.isEnabled.isHidden.aliases.isMcp.argumentHint.whenToUse.paths.version.disableModelInvocation.userInvocable.loadedFrom.immediate.userFacingName`.split(`.`))}));function oZe(e,t,n){let{head:r,tail:i,mtime:a,size:o}=t,s=r.indexOf(`
|
|
1641
1641
|
`),c=s>=0?r.slice(0,s):r;if(c.includes(`"isSidechain":true`)||c.includes(`"isSidechain": true`))return null;let l=Gi(i,`customTitle`)||Gi(r,`customTitle`)||Gi(i,`aiTitle`)||Gi(r,`aiTitle`)||void 0,u=yre(r)||void 0,d=Ti(r,`timestamp`),f;if(d){let e=Date.parse(d);Number.isNaN(e)||(f=e)}let p=l||Gi(i,`lastPrompt`)||Gi(i,`summary`)||u;if(!p)return null;let m=Gi(i,`gitBranch`)||Ti(r,`gitBranch`)||void 0,h=Ti(r,`cwd`)||n||void 0,g=i.split(`
|
|
1642
1642
|
`).findLast(e=>e.startsWith(`{"type":"tag"`));return{sessionId:e,summary:p,lastModified:a,fileSize:o,customTitle:l,firstPrompt:u,gitBranch:m,cwd:h,tag:g&&Gi(g,`tag`)||void 0,createdAt:f}}async function FZ(e,t,n){let r;try{r=await nl(e)}catch{return[]}return(await Promise.all(r.map(async r=>{if(!r.endsWith(`.jsonl`))return null;let i=sie(r.slice(0,-6));if(!i)return null;let a=X(e,r);if(!t)return{sessionId:i,filePath:a,mtime:0,projectPath:n};try{return{sessionId:i,filePath:a,mtime:(await ol(a)).mtime.getTime(),projectPath:n}}catch{return null}}))).filter(e=>e!==null)}async function sZe(e){let t=await Mre(e.filePath);if(!t)return null;let n=oZe(e.sessionId,t,e.projectPath);return n?(e.mtime&&(n.lastModified=e.mtime),n):null}function cZe(e,t){return t.mtime===e.mtime?t.sessionId<e.sessionId?-1:+(t.sessionId>e.sessionId):t.mtime-e.mtime}async function lZe(e,t,n){e.sort(cZe);let r=[],i=t&&t>0?t:1/0,a=0,o=new Set;for(let t=0;t<e.length&&r.length<i;){let s=Math.min(t+mZe,e.length),c=e.slice(t,s),l=await Promise.all(c.map(sZe));for(let e=0;e<l.length&&r.length<i;e++){t++;let i=l[e];if(i&&!o.has(i.sessionId)){if(o.add(i.sessionId),a<n){a++;continue}r.push(i)}}}return r}async function uZe(e){let t=await Promise.all(e.map(sZe)),n=new Map;for(let e of t){if(!e)continue;let t=n.get(e.sessionId);(!t||e.lastModified>t.lastModified)&&n.set(e.sessionId,e)}let r=[...n.values()];return r.sort((e,t)=>t.lastModified===e.lastModified?t.sessionId<e.sessionId?-1:+(t.sessionId>e.sessionId):t.lastModified-e.lastModified),r}async function dZe(e,t,n){let r=await $re(e),i;if(t)try{i=await _re(r)}catch{i=[]}else i=[];if(i.length<=1){let e=await pi(r);return e?FZ(e,n,r):[]}let a=Tre(),o=process.platform===`win32`,s=i.map(e=>{let t=qi(e);return{path:e,prefix:o?t.toLowerCase():t}});s.sort((e,t)=>t.prefix.length-e.prefix.length);let c;try{c=await nl(a,{withFileTypes:!0})}catch{let e=await pi(r);return e?FZ(e,n,r):[]}let l=[],u=new Set,d=await pi(r);if(d){let e=bc(d);u.add(o?e.toLowerCase():e),l.push(...await FZ(d,n,r))}for(let e of c){if(!e.isDirectory())continue;let t=o?e.name.toLowerCase():e.name;if(!u.has(t)){for(let{path:r,prefix:i}of s)if(t===i||i.length>=200&&t.startsWith(`${i}-`)){u.add(t),l.push(...await FZ(X(a,e.name),n,r));break}}}return l}async function fZe(e){let t=Tre(),n;try{n=await nl(t,{withFileTypes:!0})}catch{return[]}return(await Promise.all(n.filter(e=>e.isDirectory()).map(n=>FZ(X(t,n.name),e)))).flat()}async function pZe(e){let{dir:t,limit:n,offset:r,includeWorktrees:i}=e??{},a=r??0,o=n!==void 0&&n>0||a>0,s=t?await dZe(t,i??!0,o):await fZe(o);return o?lZe(s,n,a):uZe(s)}var mZe,hZe=n((()=>{iie(),Pi(),mZe=32}));function IZ(){return X(ia(),xZe)}async function gZe(){try{return(await ol(IZ())).mtimeMs}catch{return 0}}async function _Ze(){let e=IZ(),t,n;try{let[r,i]=await Promise.all([ol(e),tl(e,`utf8`)]);t=r.mtimeMs;let a=parseInt(i.trim(),10);n=Number.isFinite(a)?a:void 0}catch{}if(t!==void 0&&Date.now()-t<SZe&&n!==void 0&&oc(n))return G(`[autoDream] lock held by live PID ${n} (mtime ${Math.round((Date.now()-t)/1e3)}s ago)`),null;await $c(ia(),{recursive:!0}),await ll(e,String(process.pid));let r;try{r=await tl(e,`utf8`)}catch{return null}return parseInt(r.trim(),10)===process.pid?t??0:null}async function vZe(e){let t=IZ();try{if(e===0){await cl(t);return}await ll(t,``);let n=e/1e3;await Oce(t,n,n)}catch(e){G(`[autoDream] rollback failed: ${e.message} — next trigger delayed to minHours`)}}async function yZe(e){return(await FZ(c8(Yt()),!0)).filter(t=>t.mtime>e).map(e=>e.sessionId)}async function bZe(){try{await $c(ia(),{recursive:!0}),await ll(IZ(),String(process.pid))}catch(e){G(`[autoDream] recordConsolidation write failed: ${e.message}`)}}var xZe,SZe,LZ=n((()=>{Jt(),ra(),K(),sc(),hZe(),h8(),xZe=`.consolidate-lock`,SZe=3600*1e3}));function CZe(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`dream`}function wZe(e,t){let n=o5(`dream`);return YI({...s5(n,`dream`,`dreaming`),type:`dream`,status:`running`,phase:`starting`,sessionsReviewing:t.sessionsReviewing,filesTouched:[],turns:[],abortController:t.abortController,priorMtime:t.priorMtime},e),n}function TZe(e,t,n,r){JI(e,r,e=>{let r=new Set(e.filesTouched),i=n.filter(e=>!r.has(e)&&r.add(e));return t.text===``&&t.toolUseCount===0&&i.length===0?e:{...e,phase:i.length>0?`updating`:e.phase,filesTouched:i.length>0?[...e.filesTouched,...i]:e.filesTouched,turns:e.turns.slice(-29).concat(t)}})}function EZe(e,t){JI(e,t,e=>({...e,status:`completed`,endTime:Date.now(),notified:!0,abortController:void 0}))}function DZe(e,t){JI(e,t,e=>({...e,status:`failed`,endTime:Date.now(),notified:!0,abortController:void 0}))}var RZ,zZ=n((()=>{LZ(),c5(),ZI(),RZ={name:`DreamTask`,type:`dream`,async kill(e,t){let n;JI(e,t,e=>e.status===`running`?(e.abortController?.abort(),n=e.priorMtime,{...e,status:`killed`,endTime:Date.now(),notified:!0,abortController:void 0}):e),n!==void 0&&await vZe(n)}}}));function OZe(e,t){let n=o5(`local_workflow`);return YI({...s5(n,`local_workflow`,t.description,t.toolUseId),type:`local_workflow`,status:`running`,workflowName:t.workflowName,workflowFile:t.workflowFile,summary:t.summary,agentId:t.agentId,abortController:t.abortController},e),n}function kZe(e,t){JI(e,t,e=>({...e,status:`completed`,endTime:Date.now(),notified:!0,abortController:void 0}))}function AZe(e,t,n){JI(e,t,e=>({...e,status:`failed`,endTime:Date.now(),notified:!0,abortController:void 0,...n===void 0?{}:{error:n}}))}function BZ(e,t){JI(e,t,e=>e.status===`running`?(e.abortController?.abort(),{...e,status:`killed`,endTime:Date.now(),notified:!0,abortController:void 0}):e)}var jZe,VZ=n((()=>{c5(),K(),ZI(),jZe={name:`LocalWorkflowTask`,type:`local_workflow`,async kill(e,t){BZ(e,t)}}}));function MZe(){return[jH,L0,RZ,jZe]}function NZe(e){return MZe().find(t=>t.type===e)}var PZe=n((()=>{zZ(),z0(),MH(),VZ()}));async function FZe(e,t){let{getAppState:n,setAppState:r}=t,i=n().tasks?.[e];if(!i)throw new HZ(`No task found with ID: ${e}`,`not_found`);if(i.status!==`running`)throw new HZ(`Task ${e} is not running (status: ${i.status})`,`not_running`);let a=NZe(i.type);if(!a)throw new HZ(`Unsupported task type: ${i.type}`,`unsupported_type`);if(await a.kill(e,r),pH(i)){let t=!1;r(n=>{let r=n.tasks[e];return!r||r.notified?n:(t=!0,{...n,tasks:{...n.tasks,[e]:{...r,notified:!0}}})}),t&&WI(e,`stopped`,{toolUseId:i.toolUseId,summary:i.description})}let o=pH(i)?i.command:i.description;return{taskId:e,taskType:i.type,command:o}}var HZ,IZe=n((()=>{PZe(),qI(),mH(),b(),HZ=class extends Error{constructor(e,t){super(e),x(this,`code`,void 0),this.code=t,this.name=`StopTaskError`}}}));function LZe(){return``}function RZe(e){let t=e.split(`
|
|
1643
1643
|
`),n=e;return t.length>WZ&&(n=t.slice(0,WZ).join(`
|
|
@@ -2050,7 +2050,7 @@ Use this when:
|
|
|
2050
2050
|
|
|
2051
2051
|
The search uses TF-IDF keyword matching against all registered skills (bundled, user-defined, and MCP-provided). Results include skill name, description, and relevance score.`})),Z0e,Q0e,$0e=n((()=>{Nt(),Ks(),kt(),X0e(),Z0e=V(()=>xt({description:B().describe(`Description of what you want to do. Be specific — e.g. "deploy a Next.js app to Cloudflare Workers" rather than just "deploy".`),limit:z().optional().describe(`Maximum number of results to return (default: 5)`)})),Q0e=Ns({name:$Q,searchHint:`find search discover skills commands tools capabilities`,maxResultSizeChars:1e4,strict:!0,get inputSchema(){return Z0e()},async description(){return J0e},async prompt(){return Y0e},isConcurrencySafe(){return!0},isReadOnly(){return!0},userFacingName(){return`Discover Skills`},renderToolUseMessage(e){return`Searching skills: ${e.description?.slice(0,80)??`...`}`},mapToolResultToToolResultBlockParam(e,t){if(e.count===0)return Ys(t,`No matching skills found for that description.`);let n=e.results.map((e,t)=>`${t+1}. **${e.name}** (score: ${e.score.toFixed(2)})\n ${e.description}`);return Ys(t,`Found ${e.count} relevant skill(s):\n\n${n.join(`
|
|
2052
2052
|
|
|
2053
|
-
`)}`)},async call(e,t){let{getSkillIndex:n,searchSkills:r}=await import(`./localSearch-
|
|
2053
|
+
`)}`)},async call(e,t){let{getSkillIndex:n,searchSkills:r}=await import(`./localSearch-zfn7jgrh.js`),{getCwd:i}=await import(`./cwd-Dc3NV7s8.js`),a=await n(i()),o=r(e.description,a,e.limit??5);return{data:{results:o.map(e=>({name:e.name,description:e.description,score:e.score})),count:o.length}}}})}));function e2e(e,t,n){return{toolUseContext:e,canUseTool:t,...n===void 0?{}:{parentMessage:n},agentId:e.agentId}}function t2e(e){return mae(e)}function n2e(e){return Dae(e)}var e$=n((()=>{Es()}));function r2e(e,t=s2e){let n=new Map,r=e.subscribe(()=>{let r=e.listRuns();for(let e of r){let r=n.get(e.runId);if(r===void 0){n.set(e.runId,e.status);continue}r!==e.status&&o2e.has(e.status)&&t(i2e(e)),n.set(e.runId,e.status)}});return()=>{r(),n.clear()}}function i2e(e){let t=e.status===`completed`?`completed successfully`:e.status===`failed`?`failed`:`was stopped`,n=e.status===`failed`&&e.error?`: ${e.error}`:``,r=`Workflow "${e.workflowName}" ${t}${n}`;return`<${wa}>
|
|
2054
2054
|
<${qa}>${e.runId}</${qa}>
|
|
2055
2055
|
<${za}>${a2e}</${za}>
|
|
2056
2056
|
<${Ma}>${e.status}</${Ma}>
|
|
@@ -2396,7 +2396,7 @@ ${t?`${t}\n`:``}\
|
|
|
2396
2396
|
`,M6e=new Set([`select-string`,`get-childitem`,`findstr`,`where.exe`]),N6e=new Set([`get-content`,`get-item`,`test-path`,`resolve-path`,`get-process`,`get-service`,`get-childitem`,`get-location`,`get-filehash`,`get-acl`,`format-hex`]),P6e=new Set([`write-output`,`write-host`]),m1=2e3,F6e=1e3,I6e=15e3,L6e=[`start-sleep`,`sleep`],h1=`Enterprise policy requires sandboxing, but sandboxing is not available on native Windows. Shell command execution is blocked on this platform by policy.`,g1=h(process.env.CLAUDE_CODE_DISABLE_BACKGROUND_TASKS),_1=V(()=>xt({command:B().describe(`The PowerShell command to execute`),timeout:AS(z().optional()).describe(`Optional timeout in milliseconds (max ${s1()})`),description:B().optional().describe(`Clear, concise description of what this command does in active voice.`),run_in_background:rU(pt().optional()).describe(`Set to true to run this command in the background. Use Read to read the output later.`),dangerouslyDisableSandbox:rU(pt().optional()).describe(`Set this to true to dangerously override sandbox mode and run commands without sandboxing.`)})),R6e=V(()=>g1?_1().omit({run_in_background:!0}):_1()),z6e=V(()=>I({stdout:B().describe(`The standard output of the command`),stderr:B().describe(`The standard error output of the command`),interrupted:pt().describe(`Whether the command was interrupted`),returnCodeInterpretation:B().optional().describe(`Semantic interpretation for non-error exit codes with special meaning`),isImage:pt().optional().describe(`Flag to indicate if stdout contains image data`),persistedOutputPath:B().optional().describe(`Path to persisted full output when too large for inline`),persistedOutputSize:z().optional().describe(`Total output size in bytes when persisted`),backgroundTaskId:B().optional().describe(`ID of the background task if command is running in background`),backgroundedByUser:pt().optional().describe(`True if the user manually backgrounded the command with Ctrl+B`),assistantAutoBackgrounded:pt().optional().describe(`True if the command was auto-backgrounded by the assistant-mode blocking budget`)})),B6e=[`npm`,`yarn`,`pnpm`,`node`,`python`,`python3`,`go`,`cargo`,`make`,`docker`,`terraform`,`webpack`,`vite`,`jest`,`pytest`,`curl`,`Invoke-WebRequest`,`build`,`test`,`serve`,`watch`,`dev`],v1=Ns({name:Js,searchHint:`execute Windows PowerShell commands`,maxResultSizeChars:3e4,strict:!0,async description({description:e}){return e||`Run PowerShell command`},async prompt(){return y6e()},isConcurrencySafe(e){return this.isReadOnly?.(e)??!1},isSearchOrReadCommand(e){return e?.command?D6e(e.command):{isSearch:!1,isRead:!1}},isReadOnly(e){return!z4e(e.command)&&B4e(e.command)},toAutoClassifierInput(e){return e.command},get inputSchema(){return R6e()},get outputSchema(){return z6e()},userFacingName(){return`PowerShell`},getToolUseSummary(e){if(!e?.command)return null;let{command:t,description:n}=e;return n||_o(t,50)},getActivityDescription(e){return e?.command?`Running ${e.description??_o(e.command,50)}`:`Running command`},isEnabled(){return!0},async validateInput(e){return k6e()?{result:!1,message:h1,errorCode:11}:{result:!0}},async checkPermissions(e,t){return await f6e(e,t)},renderToolUseMessage:x6e,renderToolUseProgressMessage:S6e,renderToolUseQueuedMessage:C6e,renderToolResultMessage:w6e,renderToolUseErrorMessage:T6e,mapToolResultToToolResultBlockParam({interrupted:e,stdout:t,stderr:n,isImage:r,persistedOutputPath:i,persistedOutputSize:a,backgroundTaskId:o,backgroundedByUser:s,assistantAutoBackgrounded:c},l){if(r){let e=lbe(t,l);if(e)return e}let u=t;if(i){let e=mS(t?t.replace(/^(\s*\n)+/,``).trimEnd():``,_S);u=fS({filepath:i,originalSize:a??0,isJson:!1,preview:e.preview,hasMore:e.hasMore})}else t&&(u=t.replace(/^(\s*\n)+/,``),u=u.trimEnd());let d=n.trim();e&&(n&&(d+=p1),d+=`<error>Command was aborted before completion</error>`);let f=``;if(o){let e=V8(o);f=c?`Command exceeded the assistant-mode blocking budget (${I6e/1e3}s) and was moved to the background with ID: ${o}. It is still running — you will be notified when it completes. Output is being written to: ${e}. In assistant mode, delegate long-running work to a subagent or use run_in_background to keep this conversation responsive.`:s?`Command was manually backgrounded by user with ID: ${o}. Output is being written to: ${e}`:`Command running in background with ID: ${o}. Output is being written to: ${e}`}return{tool_use_id:l,type:`tool_result`,content:[u,d,f].filter(Boolean).join(`
|
|
2397
2397
|
`),is_error:e}},async call(e,t,n,r,i){if(k6e())throw Error(h1);let{abortController:a,setAppState:o,setToolJSX:s}=t,c=!t.agentId,l=0;try{let n=A6e({input:e,abortController:a,setAppState:t.setAppStateForTasks??o,setToolJSX:s,preventCwdChanges:!c,isMainThread:c,toolUseId:t.toolUseId,agentId:t.agentId}),r;do if(r=await n.next(),!r.done&&i){let e=r.value;i({toolUseID:`ps-progress-${l++}`,data:{type:`powershell_progress`,output:e.output,fullOutput:e.fullOutput,elapsedTimeSeconds:e.elapsedTimeSeconds,totalLines:e.totalLines,totalBytes:e.totalBytes,timeoutMs:e.timeoutMs,taskId:e.taskId}})}while(!r.done);let u=r.value;u.code===0&&!u.stdout&&u.stderr&&!u.backgroundTaskId||fG(e.command,u.code,u.stdout);let d=u.interrupted&&a.signal.reason===`interrupt`,f=``;if(c&&fbe(t.getAppState().toolPermissionContext)&&(f=nS(``)),u.backgroundTaskId){let t=NH(u.stdout||``,e.command);if(c&&t.hints.length>0)for(let e of t.hints);return{data:{stdout:t.stripped,stderr:[u.stderr||``,f].filter(Boolean).join(`
|
|
2398
2398
|
`),interrupted:!1,backgroundTaskId:u.backgroundTaskId,backgroundedByUser:u.backgroundedByUser,assistantAutoBackgrounded:u.assistantAutoBackgrounded}}}let p=new to,m=(u.stdout||``).trimEnd();p.append(m+p1);let h=Z2e(e.command,u.code,m,u.stderr||``),g=sbe(p.toString()),_=NH(g,e.command);if(g=_.stripped,c&&_.hints.length>0)for(let e of _.hints);if(u.preSpawnError)throw Error(u.preSpawnError);if(h.isError&&!d)throw new Un(g,u.stderr||``,u.code,u.interrupted);let v=64*1024*1024,y,b;if(u.outputFilePath&&u.outputTaskId)try{let e=await ol(u.outputFilePath);b=e.size,await uS();let t=lS(u.outputTaskId,!1);e.size>v&&await Dce(u.outputFilePath,v);try{await Qc(u.outputFilePath,t)}catch{await Zc(u.outputFilePath,t)}y=t}catch{}let x=tS(g),S=g;if(x){let e=await ube(g,u.outputFilePath,b);e?S=e:x=!1}let C=[u.stderr||``,f].filter(Boolean).join(`
|
|
2399
|
-
`);return Y(`tengu_powershell_tool_command_executed`,{command_type:f1(e.command),stdout_length:S.length,stderr_length:C.length,exit_code:u.code,interrupted:u.interrupted}),{data:{stdout:S,stderr:C,interrupted:u.interrupted,returnCodeInterpretation:h.message,isImage:x,persistedOutputPath:y,persistedOutputSize:b}}}finally{s&&s(null)}},isResultTruncated(e){return fC(e.stdout)||fC(e.stderr)}})}));function V6e(e){let t=e.toLowerCase();return W6e.includes(t)?t:null}function H6e(){let e=b1(),t=e.map(e=>e.isEnabled());return e.filter((e,n)=>t[n]).map(e=>e.name)}function b1(){return[wZ,aQ,Rq,...Lx()?[]:[OK,TK],lQ,NC,PX,mK,RX,MK,KZ,gQ,PZ,AQ,v0e,N1e,...RC()?[T0e,M0e,z0e,K0e]:[],...h(process.env.ENABLE_LSP_TOOL)?[wQ]:[],...Sse()?[q$e,i1e]:[],...C1?[C1]:[],U6e,aQe,...w1()?[w1()]:[],Q0e,fO,RO,...hz()?[Iz]:[],w$e]}function x1(e,t){return e.filter(e=>!C9(t,e))}function S1(e,t){let n=T1(e),r=x1(t,e),i=(e,t)=>e.name.localeCompare(t.name);return kg([...n].sort(i).concat(r.sort(i)),`name`)}var C1,U6e,w1,W6e,T1,E1=n((()=>{Ks(),TZ(),aZe(),zq(),FX(),FC(),hK(),kK(),zX(),UZe(),oQe(),pQe(),NK(),uQ(),CQe(),EK(),AQe(),h$e(),pO(),zO(),Lz(),T$e(),z$e(),J$e(),a1e(),P1e(),y0e(),E0e(),N0e(),B0e(),q0e(),Ag(),Dz(),JC(),Ss(),ws(),$0e(),W2e(),A9(),Rx(),g(),Xs(),Cse(),BX(),C1=process.env.CLAUDE_CODE_VERIFY_PLAN===`true`?(J2e(),e(G2e)).VerifyPlanExecutionTool:null,U6e=U2e(),w1=()=>Vae()?(y1(),e(d1)).PowerShellTool:null,W6e=[`default`],T1=e=>{if(h(process.env.CLAUDE_CODE_SIMPLE))return x1([Rq,NC,PX],e);let t=new Set([fO.name,RO.name,Fs]),n=x1(b1().filter(e=>!t.has(e.name)),e);OJe()&&n.some(e=>Cs(e,`REPL`))&&(n=n.filter(e=>!kJe.has(e.name)));let r=n.map(e=>e.isEnabled());return n.filter((e,t)=>r[t])}})),G6e,D1,K6e=n((()=>{b(),G6e=Symbol.asyncIterator,D1=class{constructor(e){x(this,`returned`,void 0),x(this,`queue`,[]),x(this,`readResolve`,void 0),x(this,`readReject`,void 0),x(this,`isDone`,!1),x(this,`hasError`,void 0),x(this,`started`,!1),this.returned=e}[G6e](){if(this.started)throw Error(`Stream can only be iterated once`);return this.started=!0,this}next(){return this.queue.length>0?Promise.resolve({done:!1,value:this.queue.shift()}):this.isDone?Promise.resolve({done:!0,value:void 0}):this.hasError?Promise.reject(this.hasError):new Promise((e,t)=>{this.readResolve=e,this.readReject=t})}enqueue(e){if(this.readResolve){let t=this.readResolve;this.readResolve=void 0,this.readReject=void 0,t({done:!1,value:e})}else this.queue.push(e)}done(){if(this.isDone=!0,this.readResolve){let e=this.readResolve;this.readResolve=void 0,this.readReject=void 0,e({done:!0,value:void 0})}}error(e){if(this.hasError=e,this.readReject){let t=this.readReject;this.readResolve=void 0,this.readReject=void 0,t(e)}}return(){return this.isDone=!0,this.returned&&this.returned(),Promise.resolve({done:!0,value:void 0})}}}));function q6e(e){switch(e){case`allow`:return`allowed`;case`deny`:return`denied`;default:return`asked for confirmation for`}}var J6e=n((()=>{}));async function*Y6e(e,t,n,r,i,a,o,s,c){let l=Date.now();try{let c=e.getAppState().toolPermissionContext.mode,u=a;for await(let a of nlt(t.name,n,i,u,e,c,e.abortController.signal))try{if(a.message?.type===`attachment`&&a.message.attachment.type===`hook_cancelled`){Y(`tengu_post_tool_hooks_cancelled`,{toolName:Ae(t.name),queryChainId:e.queryTracking?.chainId,queryDepth:e.queryTracking?.depth}),yield{message:r2({type:`hook_cancelled`,hookName:`PostToolUse:${t.name}`,toolUseID:n,hookEvent:`PostToolUse`})};continue}if(a.message&&!(a.message.type===`attachment`&&a.message.attachment.type===`hook_blocking_error`)&&(yield{message:a.message}),a.blockingError&&(yield{message:r2({type:`hook_blocking_error`,hookName:`PostToolUse:${t.name}`,toolUseID:n,hookEvent:`PostToolUse`,blockingError:a.blockingError})}),a.preventContinuation){yield{message:r2({type:`hook_stopped_continuation`,message:a.stopReason||`Execution stopped by PostToolUse hook`,hookName:`PostToolUse:${t.name}`,toolUseID:n,hookEvent:`PostToolUse`})};return}a.additionalContexts&&a.additionalContexts.length>0&&(yield{message:r2({type:`hook_additional_context`,content:a.additionalContexts,hookName:`PostToolUse:${t.name}`,toolUseID:n,hookEvent:`PostToolUse`})}),a.updatedMCPToolOutput&&yA(t)&&(u=a.updatedMCPToolOutput,yield{updatedMCPToolOutput:u})}catch(i){let a=Date.now()-l;Y(`tengu_post_tool_hook_error`,{messageID:r,toolName:Ae(t.name),isMcp:t.isMcp??!1,duration:a,queryChainId:e.queryTracking?.chainId,queryDepth:e.queryTracking?.depth,...s?{mcpServerType:s}:{},...o?{requestId:o}:{}}),yield{message:r2({type:`hook_error_during_execution`,content:TQ(i),hookName:`PostToolUse:${t.name}`,toolUseID:n,hookEvent:`PostToolUse`})}}}catch(e){J(e)}}async function*X6e(e,t,n,r,i,a,o,s,c,l){let u=Date.now();try{let l=e.getAppState().toolPermissionContext.mode;for await(let d of rlt(t.name,n,i,a,e,o,l,e.abortController.signal))try{if(d.message?.type===`attachment`&&d.message.attachment.type===`hook_cancelled`){Y(`tengu_post_tool_failure_hooks_cancelled`,{toolName:Ae(t.name),queryChainId:e.queryTracking?.chainId,queryDepth:e.queryTracking?.depth}),yield{message:r2({type:`hook_cancelled`,hookName:`PostToolUseFailure:${t.name}`,toolUseID:n,hookEvent:`PostToolUseFailure`})};continue}d.message&&!(d.message.type===`attachment`&&d.message.attachment.type===`hook_blocking_error`)&&(yield{message:d.message}),d.blockingError&&(yield{message:r2({type:`hook_blocking_error`,hookName:`PostToolUseFailure:${t.name}`,toolUseID:n,hookEvent:`PostToolUseFailure`,blockingError:d.blockingError})}),d.additionalContexts&&d.additionalContexts.length>0&&(yield{message:r2({type:`hook_additional_context`,content:d.additionalContexts,hookName:`PostToolUseFailure:${t.name}`,toolUseID:n,hookEvent:`PostToolUseFailure`})})}catch(i){let a=Date.now()-u;Y(`tengu_post_tool_failure_hook_error`,{messageID:r,toolName:Ae(t.name),isMcp:t.isMcp??!1,duration:a,queryChainId:e.queryTracking?.chainId,queryDepth:e.queryTracking?.depth,...c?{mcpServerType:c}:{},...s?{requestId:s}:{}}),yield{message:r2({type:`hook_error_during_execution`,content:TQ(i),hookName:`PostToolUseFailure:${t.name}`,toolUseID:n,hookEvent:`PostToolUseFailure`})}}}catch(e){J(e)}}async function Z6e(e,t,n,r,i,a,o){let s=t.requiresUserInteraction?.(),c=r.requireCanUseTool;if(e?.behavior===`allow`){let l=e.updatedInput??n,u=s&&e.updatedInput!==void 0;if(s&&!u||c)return G(`Hook approved tool use for ${t.name}, but canUseTool is required`),{decision:await i(t,l,r,a,o),input:l};let d=await tft(t,l,r);return d===null?(G(u?`Hook satisfied user interaction for ${t.name} via updatedInput`:`Hook approved tool use for ${t.name}, bypassing permission prompt`),{decision:e,input:l}):d.behavior===`deny`?(G(`Hook approved tool use for ${t.name}, but deny rule overrides: ${d.message}`),{decision:d,input:l}):(G(`Hook approved tool use for ${t.name}, but ask rule requires prompt`),{decision:await i(t,l,r,a,o),input:l})}if(e?.behavior===`deny`)return G(`Hook denied tool use for ${t.name}`),{decision:e,input:n};let l=e?.behavior===`ask`?e:void 0,u=e?.behavior===`ask`&&e.updatedInput?e.updatedInput:n;return{decision:await i(t,u,r,a,o,l),input:u}}async function*Q6e(e,t,n,r,i,a,o,s){let c=Date.now();try{let s=e.getAppState();for await(let l of tlt(t.name,r,n,e,s.toolPermissionContext.mode,e.abortController.signal,void 0,e.requestPrompt,t.getToolUseSummary?.(n)))try{if(l.message&&(yield{type:`message`,message:{message:l.message}}),l.blockingError){let e=Xct(`PreToolUse:${t.name}`,l.blockingError);yield{type:`hookPermissionResult`,hookPermissionResult:{behavior:`deny`,message:e,decisionReason:{type:`hook`,hookName:`PreToolUse:${t.name}`,reason:e}}}}if(l.preventContinuation&&(yield{type:`preventContinuation`,shouldPreventContinuation:!0},l.stopReason&&(yield{type:`stopReason`,stopReason:l.stopReason})),l.permissionBehavior!==void 0){G(`Hook result has permissionBehavior=${l.permissionBehavior}`);let e={type:`hook`,hookName:`PreToolUse:${t.name}`,hookSource:l.hookSource,reason:l.hookPermissionDecisionReason};l.permissionBehavior===`allow`?yield{type:`hookPermissionResult`,hookPermissionResult:{behavior:`allow`,updatedInput:l.updatedInput,decisionReason:e}}:l.permissionBehavior===`ask`?yield{type:`hookPermissionResult`,hookPermissionResult:{behavior:`ask`,updatedInput:l.updatedInput,message:l.hookPermissionDecisionReason||`Hook PreToolUse:${t.name} ${q6e(l.permissionBehavior)} this tool`,decisionReason:e}}:yield{type:`hookPermissionResult`,hookPermissionResult:{behavior:l.permissionBehavior,message:l.hookPermissionDecisionReason||`Hook PreToolUse:${t.name} ${q6e(l.permissionBehavior)} this tool`,decisionReason:e}}}if(l.updatedInput&&l.permissionBehavior===void 0&&(yield{type:`hookUpdatedInput`,updatedInput:l.updatedInput}),l.additionalContexts&&l.additionalContexts.length>0&&(yield{type:`additionalContext`,message:{message:r2({type:`hook_additional_context`,content:l.additionalContexts,hookName:`PreToolUse:${t.name}`,toolUseID:r,hookEvent:`PreToolUse`})}}),e.abortController.signal.aborted){Y(`tengu_pre_tool_hooks_cancelled`,{toolName:Ae(t.name),queryChainId:e.queryTracking?.chainId,queryDepth:e.queryTracking?.depth}),yield{type:`message`,message:{message:r2({type:`hook_cancelled`,hookName:`PreToolUse:${t.name}`,toolUseID:r,hookEvent:`PreToolUse`})}},yield{type:`stop`};return}}catch(n){J(n);let s=Date.now()-c;Y(`tengu_pre_tool_hook_error`,{messageID:i,toolName:Ae(t.name),isMcp:t.isMcp??!1,duration:s,queryChainId:e.queryTracking?.chainId,queryDepth:e.queryTracking?.depth,...o?{mcpServerType:o}:{},...a?{requestId:a}:{}}),yield{type:`message`,message:{message:r2({type:`hook_error_during_execution`,content:TQ(n),hookName:`PreToolUse:${t.name}`,toolUseID:r,hookEvent:`PreToolUse`})}},yield{type:`stop`}}}catch(e){J(e),yield{type:`stop`};return}}var $6e=n((()=>{oo(),Se(),m2(),K(),g7(),Ga(),J6e(),A9(),EQ(),CA()}));function e8e(){return k1||(k1=import(`./toolEventObserver-BL06sDI4.js`).catch(e=>{throw k1=void 0,e})),k1}function t8e(e){if(e instanceof cr)return e.telemetryMessage.slice(0,200);if(e instanceof Error){let t=Xn(e);return typeof t==`string`?`Error:${t}`:e.name&&e.name!==`Error`&&e.name.length>3?e.name.slice(0,60):`Error`}return`UnknownError`}function n8e(e,t){switch(e){case`session`:return t===`allow`?`user_temporary`:`user_reject`;case`localSettings`:case`userSettings`:return t===`allow`?`user_permanent`:`user_reject`;default:return`config`}}function r8e(e,t){if(!e)return`config`;switch(e.type){case`permissionPromptTool`:{let n=e.toolResult?.decisionClassification;return n===`user_temporary`||n===`user_permanent`||n===`user_reject`?n:t===`allow`?`user_temporary`:`user_reject`}case`rule`:return n8e(e.rule.source,t);case`hook`:return`hook`;case`mode`:case`classifier`:case`subcommandResults`:case`asyncAgent`:case`sandboxOverride`:case`workingDir`:case`safetyCheck`:case`other`:return`config`;default:return`config`}}function i8e(e){let t=0;for(let n of e)if(n.type===`user`&&n.imagePasteIds)for(let e of n.imagePasteIds)e>t&&(t=e);return t+1}function a8e(e,t){if(!e.startsWith(`mcp__`))return;let n=bi(e);if(n)return t.find(e=>Mi(e.name)===n.serverName)}function o8e(e,t){let n=a8e(e,t);if(n?.type===`connected`)return n.config.type??`stdio`}function s8e(e,t){let n=a8e(e,t);if(n?.type===`connected`)return SA(n.config)}async function*O1(e,t,n,r){let i=e.name,a=Ds(r.options.tools,i);if(!a){let e=Ds(b1(),i);e?.aliases?.includes(i)&&(a=e)}let o=t.message.id,s=t.requestId,c=o8e(i,r.options.mcpClients),l=s8e(i,r.options.mcpClients);if(!a){let n=Ae(i);G(`Unknown tool ${i}: ${e.id}`),Y(`tengu_tool_use_error`,{error:`No such tool available: ${n}`,toolName:n,toolUseID:e.id,isMcp:i.startsWith(`mcp__`),queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Oe(i,c,l)}),yield{message:Q({content:[{type:`tool_result`,content:`<tool_use_error>Error: No such tool available: ${i}</tool_use_error>`,is_error:!0,tool_use_id:e.id}],toolUseResult:`Error: No such tool available: ${i}`,sourceToolAssistantUUID:t.uuid})};return}let u=e.input;try{if(r.abortController.signal.aborted){Y(`tengu_tool_use_cancelled`,{toolName:Ae(a.name),toolUseID:e.id,isMcp:a.isMcp??!1,queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Oe(a.name,c,l)});let n=n_e(e.id);n.content=r3(Hv),yield{message:Q({content:[n],toolUseResult:Hv,sourceToolAssistantUUID:t.uuid})};return}for await(let i of c8e(a,e.id,u,r,n,t,o,s,c,l))yield i}catch(n){J(n);let r=n instanceof Error?n.message:String(n),i=`Error calling tool${a?` (${a.name})`:``}: ${r}`;yield{message:Q({content:[{type:`tool_result`,content:`<tool_use_error>${i}</tool_use_error>`,is_error:!0,tool_use_id:e.id}],toolUseResult:i,sourceToolAssistantUUID:t.uuid})}}}function c8e(e,t,n,r,i,a,o,s,c,l){let u=new D1;return u8e(e,t,n,r,i,a,o,s,c,l,n=>{Y(`tengu_tool_use_progress`,{messageID:o,toolName:Ae(e.name),isMcp:e.isMcp??!1,queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Oe(e.name,c,l)}),u.enqueue({message:t_e({toolUseID:n.toolUseID,parentToolUseID:t,data:n.data})})}).then(e=>{for(let t of e)u.enqueue(t)}).catch(e=>{u.error(e)}).finally(()=>{u.done()}),u}function l8e(e,t,n){if(!hz()||!gz(n)||!As(e)||yz(t).has(e.name))return null;let r=e.userFacingName?e.userFacingName(void 0):e.name;return`\n\nTool "${r}" is deferred-loading and needs to be discovered before use.\nWhen using OpenAI-compatible models (DeepSeek, Ollama, etc.), follow these steps:\n1. First discover the tool with SearchExtraTools: ${Hs}("select:${e.name}")\n2. Then call ${r} tool\n\nExample:\n${Hs}("select:${e.name}") → ${r}({ ... })\n\nImportant notes:\n• Use camelCase parameter names (e.g., taskId), not snake_case (task_id)\n• All task tools (TaskGet, TaskCreate, TaskUpdate, TaskList) need to be discovered first\n• You can discover them all at once: ${Hs}("select:TaskGet,TaskCreate,TaskUpdate,TaskList")\n\nSee docs/openai-task-tools.md for detailed guide.`}async function u8e(e,t,n,r,i,a,o,s,c,l,u){let d=e.inputSchema.safeParse(n);if(!d.success){let n=v$e(e.name,d.error),i=l8e(e,r.messages,r.options.tools);return i&&(Y(`tengu_deferred_tool_schema_not_sent`,{toolName:Ae(e.name),isMcp:e.isMcp??!1}),n+=i),G(`${e.name} tool input error: ${n.slice(0,200)}`),Y(`tengu_tool_use_error`,{error:`InputValidationError`,errorDetails:n.slice(0,2e3),messageID:o,toolName:Ae(e.name),isMcp:e.isMcp??!1,queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Oe(e.name,c,l)}),[{message:Q({content:[{type:`tool_result`,content:`<tool_use_error>InputValidationError: ${n}</tool_use_error>`,is_error:!0,tool_use_id:t}],toolUseResult:`InputValidationError: ${d.error.message}`,sourceToolAssistantUUID:a.uuid})}]}let f=await e.validateInput?.(d.data,r);if(f?.result===!1)return G(`${e.name} tool validation error: ${f.message?.slice(0,200)}`),Y(`tengu_tool_use_error`,{messageID:o,toolName:Ae(e.name),error:f.message,errorCode:f.errorCode,isMcp:e.isMcp??!1,queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Oe(e.name,c,l)}),[{message:Q({content:[{type:`tool_result`,content:`<tool_use_error>${f.message}</tool_use_error>`,is_error:!0,tool_use_id:t}],toolUseResult:`Error: ${f.message}`,sourceToolAssistantUUID:a.uuid})}];if(e.name===`Bash`&&d.data&&`command`in d.data){let e=r.getAppState();XVe(d.data.command,e.toolPermissionContext,r.abortController.signal,r.options.isNonInteractiveSession)}let p=[],m=d.data;if(e.name===`Bash`&&m&&typeof m==`object`&&`_simulatedSedEdit`in m){let{_simulatedSedEdit:e,...t}=m;m=t}let h=m,g=e.backfillObservableInput&&typeof m==`object`&&m?{...m}:null;g&&(e.backfillObservableInput(g),m=g);let _=!1,v,y,b=[],x=Date.now();for await(let n of Q6e(r,e,m,t,a.message.id,s,c,l))switch(n.type){case`message`:if(n.message.message.type===`progress`)u(n.message.message);else{p.push(n.message);let e=n.message.message.attachment;e&&`command`in e&&e.command!==void 0&&`durationMs`in e&&e.durationMs!==void 0&&b.push({command:e.command,durationMs:e.durationMs})}break;case`hookPermissionResult`:y=n.hookPermissionResult;break;case`hookUpdatedInput`:m=n.updatedInput;break;case`preventContinuation`:_=n.shouldPreventContinuation;break;case`stopReason`:v=n.stopReason;break;case`additionalContext`:p.push(n.message);break;case`stop`:return Fn()?.observe(`pre_tool_hook_duration_ms`,Date.now()-x),p.push({message:Q({content:[n_e(t)],toolUseResult:`Error: ${v}`,sourceToolAssistantUUID:a.uuid})}),p}let S=Date.now()-x;Fn()?.observe(`pre_tool_hook_duration_ms`,S),S>=A1&&G(`Slow PreToolUse hooks: ${S}ms for ${e.name} (${b.length} hooks)`,{level:`info`});let C={};m&&typeof m==`object`&&(e.name===`Read`&&`file_path`in m||(e.name===`Edit`||e.name===`Write`)&&`file_path`in m?C.file_path=String(m.file_path):e.name===`Bash`&&`command`in m&&(C.full_command=m.command)),lse(e.name,C,dc()?U(m):void 0),mse();let w=r.getAppState().toolPermissionContext.mode,T=Date.now(),E=await Z6e(y,e,m,r,i,a,t),D=E.decision;m=E.input;let O=Date.now()-T;if(O>=A1&&w===`auto`&&G(`Slow permission decision: ${O}ms for ${e.name} (mode=${w}, behavior=${D.behavior})`,{level:`info`}),D.behavior!==`ask`&&!r.toolDecisions?.has(t)){let t=D.behavior===`allow`?`accept`:`reject`,n=r8e(D.decisionReason,D.behavior);fc(`tool_decision`,{decision:t,source:n,tool_name:Ae(e.name)}),hWe(e.name)&&gWe(e,m,t,n).then(e=>ute()?.add(1,e))}if(D.decisionReason?.type===`hook`&&D.decisionReason.hookName===`PermissionRequest`&&D.behavior!==`ask`&&p.push({message:r2({type:`hook_permission_decision`,decision:D.behavior,toolUseID:t,hookEvent:`PermissionRequest`})}),D.behavior!==`allow`){G(`${e.name} tool permission denied`);let n=r.toolDecisions?.get(t);ase(`reject`,n?.source||`unknown`),mc(),Y(`tengu_tool_use_can_use_tool_rejected`,{messageID:o,toolName:Ae(e.name),queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Oe(e.name,c,l)});let i=D.message;_&&!i&&(i=`Execution stopped by PreToolUse hook${v?`: ${v}`:``}`);let u=[{type:`tool_result`,content:i,is_error:!0,tool_use_id:t}],d=D.behavior===`ask`?D.contentBlocks:void 0;d?.length&&u.push(...d);let f;if(d?.length){let e=Xr(d,e=>e.type===`image`);if(e>0){let t=i8e(r.messages);f=Array.from({length:e},(e,n)=>t+n)}}return p.push({message:Q({content:u,imagePasteIds:f,toolUseResult:`Error: ${i}`,sourceToolAssistantUUID:a.uuid})}),p}Y(`tengu_tool_use_can_use_tool_allowed`,{messageID:o,toolName:Ae(e.name),queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Oe(e.name,c,l)}),D.updatedInput!==void 0&&(m=D.updatedInput);let k=ge(m),A={};if(Me()){if(e.name===`Bash`&&`command`in m){let e=m;A={bash_command:e.command.trim().split(/\s+/)[0]||``,full_command:e.command,...e.timeout!==void 0&&{timeout:e.timeout},...e.description!==void 0&&{description:e.description},...`dangerouslyDisableSandbox`in e&&{dangerouslyDisableSandbox:e.dangerouslyDisableSandbox}}}let t=pe(e.name);t&&(A.mcp_server_name=t.serverName,A.mcp_tool_name=t.mcpToolName);let n=_e(e.name,m);n&&(A.skill_name=n)}let ee=r.toolDecisions?.get(t);ase(ee?.decision||`unknown`,ee?.source||`unknown`),dse();let te=Date.now();Vz(`tool_exec`),g&&m!==h&&typeof m==`object`&&m&&`file_path`in m&&`file_path`in h&&m.file_path===g.file_path?h={...m,file_path:h.file_path}:m!==g&&(h=m);try{let n=()=>e.call(h,{...r,toolUseId:t,userModified:D.userModified??!1},i,a,e=>{u({toolUseID:e.toolUseID,data:e.data})}),d=wse()?await(async()=>{let{runToolCallWithSkillLearningHooks:t}=await e8e();return t(e.name,h,{sessionId:r.sessionId},n)})():await n(),f=Date.now()-te;if(xn(f),d.data&&typeof d.data==`object`){let t={};e.name===`Read`&&`content`in d.data&&(`file_path`in m&&(t.file_path=String(m.file_path)),t.content=String(d.data.content)),(e.name===`Edit`||e.name===`Write`)&&`file_path`in m&&(t.file_path=String(m.file_path),e.name===`Edit`&&`diff`in d.data&&(t.diff=String(d.data.diff)),e.name===`Write`&&`content`in m&&(t.content=String(m.content))),e.name===`Bash`&&`command`in m&&(t.bash_command=m.command,`output`in d.data&&(t.output=String(d.data.output))),Object.keys(t).length>0&&hse(`tool.output`,t)}typeof d==`object`&&`structured_output`in d&&p.push({message:r2({type:`structured_output`,data:d.structured_output})}),pse({success:!0}),mc(d.data&&typeof d.data==`object`?U(d.data):String(d.data??``));let g=e.mapToolResultToToolResultBlockParam(d.data,t),y=g.content,b=y?typeof y==`string`?y.length:U(y).length:0,x;if(m&&typeof m==`object`){if((e.name===`Read`||e.name===`Edit`||e.name===`Write`)&&`file_path`in m)x=me(String(m.file_path));else if(e.name===`NotebookEdit`&&`notebook_path`in m)x=me(String(m.notebook_path));else if(e.name===`Bash`&&`command`in m){let e=m;x=de(e.command,e._simulatedSedEdit?.filePath)}}if(Y(`tengu_tool_use_success`,{messageID:o,toolName:Ae(e.name),isMcp:e.isMcp??!1,durationMs:f,preToolHookDurationMs:S,toolResultSizeBytes:b,...x!==void 0&&{fileExtension:x},queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Oe(e.name,c,l)}),Me()&&(e.name===`Bash`||e.name===`PowerShell`)&&`command`in m&&typeof m.command==`string`&&m.command.match(/\bgit\s+commit\b/)&&d.data&&typeof d.data==`object`&&`stdout`in d.data){let e=uG(String(d.data.stdout));e&&(A.git_commit_id=e)}let C=yA(e)?xA(e.name):null;fc(`tool_result`,{tool_name:Ae(e.name),success:`true`,duration_ms:String(f),...Object.keys(A).length>0&&{tool_parameters:U(A)},...k&&{tool_input:k},tool_result_size_bytes:String(b),...ee&&{decision_source:ee.source,decision_type:ee.decision},...C&&{mcp_server_scope:C}});let w=d.data,T=[],E=d.contextModifier,O=d.mcpMeta;async function ne(n,i){let o=[i?await Abe(i,e.name,e.maxResultSizeChars):await pS(e,n,t)];`acceptFeedback`in D&&D.acceptFeedback&&o.push({type:`text`,text:D.acceptFeedback});let s=`contentBlocks`in D?D.contentBlocks:void 0;s?.length&&o.push(...s);let c;if(s?.length){let e=Xr(s,e=>e.type===`image`);if(e>0){let t=i8e(r.messages);c=Array.from({length:e},(e,n)=>t+n)}}p.push({message:Q({content:o,imagePasteIds:c,toolUseResult:r.agentId&&!r.preserveToolUseResults?void 0:n,mcpMeta:r.agentId?void 0:O,sourceToolAssistantUUID:a.uuid}),contextModifier:E?{toolUseID:t,modifyContext:E}:void 0})}yA(e)||await ne(w,g);let re=[],ie=Date.now();for await(let n of Y6e(r,e,t,a.message.id,m,w,s,c,l))if(`updatedMCPToolOutput`in n)yA(e)&&(w=n.updatedMCPToolOutput);else if(yA(e)){if(T.push(n),n.message.type===`attachment`){let e=n.message.attachment;`command`in e&&e.command!==void 0&&`durationMs`in e&&e.durationMs!==void 0&&re.push({command:e.command,durationMs:e.durationMs})}}else if(p.push(n),n.message.type===`attachment`){let e=n.message.attachment;`command`in e&&e.command!==void 0&&`durationMs`in e&&e.durationMs!==void 0&&re.push({command:e.command,durationMs:e.durationMs})}let ae=Date.now()-ie;if(ae>=A1&&G(`Slow PostToolUse hooks: ${ae}ms for ${e.name} (${re.length} hooks)`,{level:`info`}),yA(e)&&await ne(w),d.newMessages&&d.newMessages.length>0)for(let e of d.newMessages)p.push({message:e});_&&p.push({message:r2({type:`hook_stopped_continuation`,message:v||`Execution stopped by hook`,hookName:`PreToolUse:${e.name}`,toolUseID:t,hookEvent:`PreToolUse`})});for(let e of T)p.push(e);return p}catch(n){let i=Date.now()-te;if(xn(i),pse({success:!1,error:W(n)}),mc(),n instanceof JA&&r.setAppState(e=>{let t=n.serverName,r=e.mcp.clients.findIndex(e=>e.name===t);if(r===-1)return e;let i=e.mcp.clients[r];if(i?.type!==`connected`)return e;let a=[...e.mcp.clients];return a[r]={name:t,type:`needs-auth`,config:i.config},{...e,mcp:{...e.mcp,clients:a}}}),!(n instanceof Wn)){let a=W(n);G(`${e.name} tool error (${i}ms): ${a.slice(0,200)}`),n instanceof Un||J(n),Y(`tengu_tool_use_error`,{messageID:o,toolName:Ae(e.name),error:t8e(n),isMcp:e.isMcp??!1,queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Oe(e.name,c,l)});let u=yA(e)?xA(e.name):null;fc(`tool_result`,{tool_name:Ae(e.name),use_id:t,success:`false`,duration_ms:String(i),error:W(n),...Object.keys(A).length>0&&{tool_parameters:U(A)},...k&&{tool_input:k},...ee&&{decision_source:ee.source,decision_type:ee.decision},...u&&{mcp_server_scope:u}})}let u=TQ(n),d=n instanceof Wn,f=[];for await(let n of X6e(r,e,t,o,m,u,d,s,c,l))f.push(n);return[{message:Q({content:[{type:`tool_result`,content:u,is_error:!0,tool_use_id:t}],toolUseResult:`Error: ${u}`,mcpMeta:r.agentId?void 0:n instanceof XA?n.mcpMeta:void 0,sourceToolAssistantUUID:a.uuid})},...f]}finally{Hz(`tool_exec`),ee&&r.toolDecisions?.delete(t)}}var k1,A1,d8e=n((()=>{oo(),Se(),Jt(),SWe(),Ks(),iJ(),js(),Ls(),Us(),bs(),Ps(),ms(),yG(),Bs(),E1(),Ar(),m2(),K(),qn(),g7(),Ga(),h3(),Zz(),mr(),K6e(),hc(),pc(),EQ(),vS(),Dz(),cj(),Ri(),ci(),CA(),$6e(),Tse(),A1=2e3}));function f8e(e,t){e.setInProgressToolUseIDs(e=>{let n=new Set(e);return n.delete(t),n})}var j1,p8e=n((()=>{h3(),Ks(),js(),UO(),d8e(),b(),j1=class{constructor(e,t,n){x(this,`toolDefinitions`,void 0),x(this,`canUseTool`,void 0),x(this,`tools`,[]),x(this,`toolUseContext`,void 0),x(this,`hasErrored`,!1),x(this,`erroredToolDescription`,``),x(this,`siblingAbortController`,void 0),x(this,`discarded`,!1),x(this,`progressAvailableResolve`,void 0),this.toolDefinitions=e,this.canUseTool=t,this.toolUseContext=n,this.siblingAbortController=VO(n.abortController)}discard(){this.discarded=!0,this.siblingAbortController.abort(`streaming_fallback`),this.tools.length=0,this.progressAvailableResolve=void 0}addTool(e,t){let n=Ds(this.toolDefinitions,e.name);if(!n){this.tools.push({id:e.id,block:e,assistantMessage:t,status:`completed`,isConcurrencySafe:!0,pendingProgress:[],results:[Q({content:[{type:`tool_result`,content:`<tool_use_error>Error: No such tool available: ${e.name}</tool_use_error>`,is_error:!0,tool_use_id:e.id}],toolUseResult:`Error: No such tool available: ${e.name}`,sourceToolAssistantUUID:t.uuid})]});return}let r=n.inputSchema.safeParse(e.input),i=r?.success?(()=>{try{return!!n.isConcurrencySafe(r.data)}catch{return!1}})():!1;this.tools.push({id:e.id,block:e,assistantMessage:t,status:`queued`,isConcurrencySafe:i,pendingProgress:[]}),this.processQueue()}canExecuteTool(e){let t=this.tools.filter(e=>e.status===`executing`);return t.length===0||e&&t.every(e=>e.isConcurrencySafe)}async processQueue(){for(let e of this.tools)if(e.status===`queued`){if(this.canExecuteTool(e.isConcurrencySafe))await this.executeTool(e);else if(!e.isConcurrencySafe)break}}createSyntheticErrorMessage(e,t,n){if(t===`user_interrupted`)return Q({content:[{type:`tool_result`,content:r3(Uv),is_error:!0,tool_use_id:e}],toolUseResult:`User rejected tool use`,sourceToolAssistantUUID:n.uuid});if(t===`streaming_fallback`)return Q({content:[{type:`tool_result`,content:`<tool_use_error>Error: Streaming fallback - tool execution discarded</tool_use_error>`,is_error:!0,tool_use_id:e}],toolUseResult:`Streaming fallback - tool execution discarded`,sourceToolAssistantUUID:n.uuid});let r=this.erroredToolDescription,i=r?`Cancelled: parallel tool call ${r} errored`:`Cancelled: parallel tool call errored`;return Q({content:[{type:`tool_result`,content:`<tool_use_error>${i}</tool_use_error>`,is_error:!0,tool_use_id:e}],toolUseResult:i,sourceToolAssistantUUID:n.uuid})}getAbortReason(e){return this.discarded?`streaming_fallback`:this.hasErrored?`sibling_error`:this.toolUseContext.abortController.signal.aborted?this.toolUseContext.abortController.signal.reason===`interrupt`?this.getToolInterruptBehavior(e)===`cancel`?`user_interrupted`:null:`user_interrupted`:null}getToolInterruptBehavior(e){let t=Ds(this.toolDefinitions,e.block.name);if(!t?.interruptBehavior)return`block`;try{return t.interruptBehavior()}catch{return`block`}}getToolDescription(e){let t=e.block.input,n=t?.command??t?.file_path??t?.pattern??``;if(typeof n==`string`&&n.length>0){let t=n.length>40?`${n.slice(0,40)}\u2026`:n;return`${e.block.name}(${t})`}return e.block.name}updateInterruptibleState(){let e=this.tools.filter(e=>e.status===`executing`);this.toolUseContext.setHasInterruptibleToolInProgress?.(e.length>0&&e.every(e=>this.getToolInterruptBehavior(e)===`cancel`))}async executeTool(e){e.status=`executing`,this.toolUseContext.setInProgressToolUseIDs(t=>new Set(t).add(e.id)),this.updateInterruptibleState();let t=[],n=[],r=(async()=>{let r=this.getAbortReason(e);if(r){t.push(this.createSyntheticErrorMessage(e.id,r,e.assistantMessage)),e.results=t,e.contextModifiers=n,e.status=`completed`,this.updateInterruptibleState();return}let i=VO(this.siblingAbortController);i.signal.addEventListener(`abort`,()=>{i.signal.reason!==`sibling_error`&&!this.toolUseContext.abortController.signal.aborted&&!this.discarded&&this.toolUseContext.abortController.abort(i.signal.reason)},{once:!0});let a=O1(e.block,e.assistantMessage,this.canUseTool,{...this.toolUseContext,abortController:i}),o=!1;for await(let r of a){let i=this.getAbortReason(e);if(i&&!o){t.push(this.createSyntheticErrorMessage(e.id,i,e.assistantMessage));break}r.message.type===`user`&&Array.isArray(r.message.message.content)&&r.message.message.content.some(e=>e.type===`tool_result`&&e.is_error===!0)&&(o=!0,e.block.name===`Bash`&&(this.hasErrored=!0,this.erroredToolDescription=this.getToolDescription(e),this.siblingAbortController.abort(`sibling_error`))),r.message&&(r.message.type===`progress`?(e.pendingProgress.push(r.message),this.progressAvailableResolve&&(this.progressAvailableResolve(),this.progressAvailableResolve=void 0)):t.push(r.message)),r.contextModifier&&n.push(r.contextModifier.modifyContext)}if(e.results=t,e.contextModifiers=n,e.status=`completed`,this.updateInterruptibleState(),!e.isConcurrencySafe&&n.length>0)for(let e of n)this.toolUseContext=e(this.toolUseContext)})();e.promise=r,r.finally(()=>{this.processQueue()})}*getCompletedResults(){if(!this.discarded)for(let e of this.tools){for(;e.pendingProgress.length>0;)yield{message:e.pendingProgress.shift(),newContext:this.toolUseContext};if(e.status!==`yielded`){if(e.status===`completed`&&e.results){e.status=`yielded`;for(let t of e.results)yield{message:t,newContext:this.toolUseContext};f8e(this.toolUseContext,e.id)}else if(e.status===`executing`&&!e.isConcurrencySafe)break}}}hasPendingProgress(){return this.tools.some(e=>e.pendingProgress.length>0)}async*getRemainingResults(){if(!this.discarded){for(;this.hasUnfinishedTools();){await this.processQueue();for(let e of this.getCompletedResults())yield e;if(this.hasExecutingTools()&&!this.hasCompletedResults()&&!this.hasPendingProgress()){let e=this.tools.filter(e=>e.status===`executing`&&e.promise).map(e=>e.promise),t=new Promise(e=>{this.progressAvailableResolve=e});e.length>0&&await Promise.race([...e,t])}}for(let e of this.getCompletedResults())yield e}}hasCompletedResults(){return this.tools.some(e=>e.status===`completed`)}hasExecutingTools(){return this.tools.some(e=>e.status===`executing`)}hasUnfinishedTools(){return this.tools.some(e=>e.status!==`yielded`)}getUpdatedContext(){return this.toolUseContext}}}));function m8e(){N1&&(ho().clearMarks(),P1.clear(),I1=null,F1++,M1(`query_user_input_received`))}function M1(e){if(!N1)return;let t=ho();if(t.mark(e),P1.set(e,process.memoryUsage()),e===`query_first_chunk_received`&&I1===null){let e=t.getEntriesByType(`mark`);e.length>0&&(I1=e[e.length-1]?.startTime??0)}}function h8e(){N1&&M1(`query_profile_end`)}function g8e(e,t){return t===`query_user_input_received`?``:e>1e3?` ⚠️ VERY SLOW`:e>100?` ⚠️ SLOW`:t.includes(`git_status`)&&e>50?` ⚠️ git status`:t.includes(`tool_schema`)&&e>50?` ⚠️ tool schemas`:t.includes(`client_creation`)&&e>50?` ⚠️ client creation`:``}function _8e(){if(!N1)return`Query profiling not enabled (set CLAUDE_CODE_PROFILE_QUERY=1)`;let e=ho().getEntriesByType(`mark`);if(e.length===0)return`No query profiling checkpoints recorded`;let t=[];t.push(`=`.repeat(80)),t.push(`QUERY PROFILING REPORT - Query #${F1}`),t.push(`=`.repeat(80)),t.push(``);let n=e[0]?.startTime??0,r=n,i=0,a=0;for(let o of e){let e=o.startTime-n,s=o.startTime-r;t.push(kie(e,s,o.name,P1.get(o.name),10,9,g8e(s,o.name))),o.name===`query_api_request_sent`&&(i=e),o.name===`query_first_chunk_received`&&(a=e),r=o.startTime}let o=e[e.length-1],s=o?o.startTime-n:0;if(t.push(``),t.push(`-`.repeat(80)),a>0){let e=i,n=a-i,r=(e/a*100).toFixed(1),o=(n/a*100).toFixed(1);t.push(`Total TTFT: ${co(a)}ms`),t.push(` - Pre-request overhead: ${co(e)}ms (${r}%)`),t.push(` - Network latency: ${co(n)}ms (${o}%)`)}else t.push(`Total time: ${co(s)}ms`);return t.push(v8e(e,n)),t.push(`=`.repeat(80)),t.join(`
|
|
2399
|
+
`);return Y(`tengu_powershell_tool_command_executed`,{command_type:f1(e.command),stdout_length:S.length,stderr_length:C.length,exit_code:u.code,interrupted:u.interrupted}),{data:{stdout:S,stderr:C,interrupted:u.interrupted,returnCodeInterpretation:h.message,isImage:x,persistedOutputPath:y,persistedOutputSize:b}}}finally{s&&s(null)}},isResultTruncated(e){return fC(e.stdout)||fC(e.stderr)}})}));function V6e(e){let t=e.toLowerCase();return W6e.includes(t)?t:null}function H6e(){let e=b1(),t=e.map(e=>e.isEnabled());return e.filter((e,n)=>t[n]).map(e=>e.name)}function b1(){return[wZ,aQ,Rq,...Lx()?[]:[OK,TK],lQ,NC,PX,mK,RX,MK,KZ,gQ,PZ,AQ,v0e,N1e,...RC()?[T0e,M0e,z0e,K0e]:[],...h(process.env.ENABLE_LSP_TOOL)?[wQ]:[],...Sse()?[q$e,i1e]:[],...C1?[C1]:[],U6e,aQe,...w1()?[w1()]:[],Q0e,fO,RO,...hz()?[Iz]:[],w$e]}function x1(e,t){return e.filter(e=>!C9(t,e))}function S1(e,t){let n=T1(e),r=x1(t,e),i=(e,t)=>e.name.localeCompare(t.name);return kg([...n].sort(i).concat(r.sort(i)),`name`)}var C1,U6e,w1,W6e,T1,E1=n((()=>{Ks(),TZ(),aZe(),zq(),FX(),FC(),hK(),kK(),zX(),UZe(),oQe(),pQe(),NK(),uQ(),CQe(),EK(),AQe(),h$e(),pO(),zO(),Lz(),T$e(),z$e(),J$e(),a1e(),P1e(),y0e(),E0e(),N0e(),B0e(),q0e(),Ag(),Dz(),JC(),Ss(),ws(),$0e(),W2e(),A9(),Rx(),g(),Xs(),Cse(),BX(),C1=process.env.CLAUDE_CODE_VERIFY_PLAN===`true`?(J2e(),e(G2e)).VerifyPlanExecutionTool:null,U6e=U2e(),w1=()=>Vae()?(y1(),e(d1)).PowerShellTool:null,W6e=[`default`],T1=e=>{if(h(process.env.CLAUDE_CODE_SIMPLE))return x1([Rq,NC,PX],e);let t=new Set([fO.name,RO.name,Fs]),n=x1(b1().filter(e=>!t.has(e.name)),e);OJe()&&n.some(e=>Cs(e,`REPL`))&&(n=n.filter(e=>!kJe.has(e.name)));let r=n.map(e=>e.isEnabled());return n.filter((e,t)=>r[t])}})),G6e,D1,K6e=n((()=>{b(),G6e=Symbol.asyncIterator,D1=class{constructor(e){x(this,`returned`,void 0),x(this,`queue`,[]),x(this,`readResolve`,void 0),x(this,`readReject`,void 0),x(this,`isDone`,!1),x(this,`hasError`,void 0),x(this,`started`,!1),this.returned=e}[G6e](){if(this.started)throw Error(`Stream can only be iterated once`);return this.started=!0,this}next(){return this.queue.length>0?Promise.resolve({done:!1,value:this.queue.shift()}):this.isDone?Promise.resolve({done:!0,value:void 0}):this.hasError?Promise.reject(this.hasError):new Promise((e,t)=>{this.readResolve=e,this.readReject=t})}enqueue(e){if(this.readResolve){let t=this.readResolve;this.readResolve=void 0,this.readReject=void 0,t({done:!1,value:e})}else this.queue.push(e)}done(){if(this.isDone=!0,this.readResolve){let e=this.readResolve;this.readResolve=void 0,this.readReject=void 0,e({done:!0,value:void 0})}}error(e){if(this.hasError=e,this.readReject){let t=this.readReject;this.readResolve=void 0,this.readReject=void 0,t(e)}}return(){return this.isDone=!0,this.returned&&this.returned(),Promise.resolve({done:!0,value:void 0})}}}));function q6e(e){switch(e){case`allow`:return`allowed`;case`deny`:return`denied`;default:return`asked for confirmation for`}}var J6e=n((()=>{}));async function*Y6e(e,t,n,r,i,a,o,s,c){let l=Date.now();try{let c=e.getAppState().toolPermissionContext.mode,u=a;for await(let a of nlt(t.name,n,i,u,e,c,e.abortController.signal))try{if(a.message?.type===`attachment`&&a.message.attachment.type===`hook_cancelled`){Y(`tengu_post_tool_hooks_cancelled`,{toolName:Ae(t.name),queryChainId:e.queryTracking?.chainId,queryDepth:e.queryTracking?.depth}),yield{message:r2({type:`hook_cancelled`,hookName:`PostToolUse:${t.name}`,toolUseID:n,hookEvent:`PostToolUse`})};continue}if(a.message&&!(a.message.type===`attachment`&&a.message.attachment.type===`hook_blocking_error`)&&(yield{message:a.message}),a.blockingError&&(yield{message:r2({type:`hook_blocking_error`,hookName:`PostToolUse:${t.name}`,toolUseID:n,hookEvent:`PostToolUse`,blockingError:a.blockingError})}),a.preventContinuation){yield{message:r2({type:`hook_stopped_continuation`,message:a.stopReason||`Execution stopped by PostToolUse hook`,hookName:`PostToolUse:${t.name}`,toolUseID:n,hookEvent:`PostToolUse`})};return}a.additionalContexts&&a.additionalContexts.length>0&&(yield{message:r2({type:`hook_additional_context`,content:a.additionalContexts,hookName:`PostToolUse:${t.name}`,toolUseID:n,hookEvent:`PostToolUse`})}),a.updatedMCPToolOutput&&yA(t)&&(u=a.updatedMCPToolOutput,yield{updatedMCPToolOutput:u})}catch(i){let a=Date.now()-l;Y(`tengu_post_tool_hook_error`,{messageID:r,toolName:Ae(t.name),isMcp:t.isMcp??!1,duration:a,queryChainId:e.queryTracking?.chainId,queryDepth:e.queryTracking?.depth,...s?{mcpServerType:s}:{},...o?{requestId:o}:{}}),yield{message:r2({type:`hook_error_during_execution`,content:TQ(i),hookName:`PostToolUse:${t.name}`,toolUseID:n,hookEvent:`PostToolUse`})}}}catch(e){J(e)}}async function*X6e(e,t,n,r,i,a,o,s,c,l){let u=Date.now();try{let l=e.getAppState().toolPermissionContext.mode;for await(let d of rlt(t.name,n,i,a,e,o,l,e.abortController.signal))try{if(d.message?.type===`attachment`&&d.message.attachment.type===`hook_cancelled`){Y(`tengu_post_tool_failure_hooks_cancelled`,{toolName:Ae(t.name),queryChainId:e.queryTracking?.chainId,queryDepth:e.queryTracking?.depth}),yield{message:r2({type:`hook_cancelled`,hookName:`PostToolUseFailure:${t.name}`,toolUseID:n,hookEvent:`PostToolUseFailure`})};continue}d.message&&!(d.message.type===`attachment`&&d.message.attachment.type===`hook_blocking_error`)&&(yield{message:d.message}),d.blockingError&&(yield{message:r2({type:`hook_blocking_error`,hookName:`PostToolUseFailure:${t.name}`,toolUseID:n,hookEvent:`PostToolUseFailure`,blockingError:d.blockingError})}),d.additionalContexts&&d.additionalContexts.length>0&&(yield{message:r2({type:`hook_additional_context`,content:d.additionalContexts,hookName:`PostToolUseFailure:${t.name}`,toolUseID:n,hookEvent:`PostToolUseFailure`})})}catch(i){let a=Date.now()-u;Y(`tengu_post_tool_failure_hook_error`,{messageID:r,toolName:Ae(t.name),isMcp:t.isMcp??!1,duration:a,queryChainId:e.queryTracking?.chainId,queryDepth:e.queryTracking?.depth,...c?{mcpServerType:c}:{},...s?{requestId:s}:{}}),yield{message:r2({type:`hook_error_during_execution`,content:TQ(i),hookName:`PostToolUseFailure:${t.name}`,toolUseID:n,hookEvent:`PostToolUseFailure`})}}}catch(e){J(e)}}async function Z6e(e,t,n,r,i,a,o){let s=t.requiresUserInteraction?.(),c=r.requireCanUseTool;if(e?.behavior===`allow`){let l=e.updatedInput??n,u=s&&e.updatedInput!==void 0;if(s&&!u||c)return G(`Hook approved tool use for ${t.name}, but canUseTool is required`),{decision:await i(t,l,r,a,o),input:l};let d=await tft(t,l,r);return d===null?(G(u?`Hook satisfied user interaction for ${t.name} via updatedInput`:`Hook approved tool use for ${t.name}, bypassing permission prompt`),{decision:e,input:l}):d.behavior===`deny`?(G(`Hook approved tool use for ${t.name}, but deny rule overrides: ${d.message}`),{decision:d,input:l}):(G(`Hook approved tool use for ${t.name}, but ask rule requires prompt`),{decision:await i(t,l,r,a,o),input:l})}if(e?.behavior===`deny`)return G(`Hook denied tool use for ${t.name}`),{decision:e,input:n};let l=e?.behavior===`ask`?e:void 0,u=e?.behavior===`ask`&&e.updatedInput?e.updatedInput:n;return{decision:await i(t,u,r,a,o,l),input:u}}async function*Q6e(e,t,n,r,i,a,o,s){let c=Date.now();try{let s=e.getAppState();for await(let l of tlt(t.name,r,n,e,s.toolPermissionContext.mode,e.abortController.signal,void 0,e.requestPrompt,t.getToolUseSummary?.(n)))try{if(l.message&&(yield{type:`message`,message:{message:l.message}}),l.blockingError){let e=Xct(`PreToolUse:${t.name}`,l.blockingError);yield{type:`hookPermissionResult`,hookPermissionResult:{behavior:`deny`,message:e,decisionReason:{type:`hook`,hookName:`PreToolUse:${t.name}`,reason:e}}}}if(l.preventContinuation&&(yield{type:`preventContinuation`,shouldPreventContinuation:!0},l.stopReason&&(yield{type:`stopReason`,stopReason:l.stopReason})),l.permissionBehavior!==void 0){G(`Hook result has permissionBehavior=${l.permissionBehavior}`);let e={type:`hook`,hookName:`PreToolUse:${t.name}`,hookSource:l.hookSource,reason:l.hookPermissionDecisionReason};l.permissionBehavior===`allow`?yield{type:`hookPermissionResult`,hookPermissionResult:{behavior:`allow`,updatedInput:l.updatedInput,decisionReason:e}}:l.permissionBehavior===`ask`?yield{type:`hookPermissionResult`,hookPermissionResult:{behavior:`ask`,updatedInput:l.updatedInput,message:l.hookPermissionDecisionReason||`Hook PreToolUse:${t.name} ${q6e(l.permissionBehavior)} this tool`,decisionReason:e}}:yield{type:`hookPermissionResult`,hookPermissionResult:{behavior:l.permissionBehavior,message:l.hookPermissionDecisionReason||`Hook PreToolUse:${t.name} ${q6e(l.permissionBehavior)} this tool`,decisionReason:e}}}if(l.updatedInput&&l.permissionBehavior===void 0&&(yield{type:`hookUpdatedInput`,updatedInput:l.updatedInput}),l.additionalContexts&&l.additionalContexts.length>0&&(yield{type:`additionalContext`,message:{message:r2({type:`hook_additional_context`,content:l.additionalContexts,hookName:`PreToolUse:${t.name}`,toolUseID:r,hookEvent:`PreToolUse`})}}),e.abortController.signal.aborted){Y(`tengu_pre_tool_hooks_cancelled`,{toolName:Ae(t.name),queryChainId:e.queryTracking?.chainId,queryDepth:e.queryTracking?.depth}),yield{type:`message`,message:{message:r2({type:`hook_cancelled`,hookName:`PreToolUse:${t.name}`,toolUseID:r,hookEvent:`PreToolUse`})}},yield{type:`stop`};return}}catch(n){J(n);let s=Date.now()-c;Y(`tengu_pre_tool_hook_error`,{messageID:i,toolName:Ae(t.name),isMcp:t.isMcp??!1,duration:s,queryChainId:e.queryTracking?.chainId,queryDepth:e.queryTracking?.depth,...o?{mcpServerType:o}:{},...a?{requestId:a}:{}}),yield{type:`message`,message:{message:r2({type:`hook_error_during_execution`,content:TQ(n),hookName:`PreToolUse:${t.name}`,toolUseID:r,hookEvent:`PreToolUse`})}},yield{type:`stop`}}}catch(e){J(e),yield{type:`stop`};return}}var $6e=n((()=>{oo(),Se(),m2(),K(),g7(),Ga(),J6e(),A9(),EQ(),CA()}));function e8e(){return k1||(k1=import(`./toolEventObserver-7QP38x4t.js`).catch(e=>{throw k1=void 0,e})),k1}function t8e(e){if(e instanceof cr)return e.telemetryMessage.slice(0,200);if(e instanceof Error){let t=Xn(e);return typeof t==`string`?`Error:${t}`:e.name&&e.name!==`Error`&&e.name.length>3?e.name.slice(0,60):`Error`}return`UnknownError`}function n8e(e,t){switch(e){case`session`:return t===`allow`?`user_temporary`:`user_reject`;case`localSettings`:case`userSettings`:return t===`allow`?`user_permanent`:`user_reject`;default:return`config`}}function r8e(e,t){if(!e)return`config`;switch(e.type){case`permissionPromptTool`:{let n=e.toolResult?.decisionClassification;return n===`user_temporary`||n===`user_permanent`||n===`user_reject`?n:t===`allow`?`user_temporary`:`user_reject`}case`rule`:return n8e(e.rule.source,t);case`hook`:return`hook`;case`mode`:case`classifier`:case`subcommandResults`:case`asyncAgent`:case`sandboxOverride`:case`workingDir`:case`safetyCheck`:case`other`:return`config`;default:return`config`}}function i8e(e){let t=0;for(let n of e)if(n.type===`user`&&n.imagePasteIds)for(let e of n.imagePasteIds)e>t&&(t=e);return t+1}function a8e(e,t){if(!e.startsWith(`mcp__`))return;let n=bi(e);if(n)return t.find(e=>Mi(e.name)===n.serverName)}function o8e(e,t){let n=a8e(e,t);if(n?.type===`connected`)return n.config.type??`stdio`}function s8e(e,t){let n=a8e(e,t);if(n?.type===`connected`)return SA(n.config)}async function*O1(e,t,n,r){let i=e.name,a=Ds(r.options.tools,i);if(!a){let e=Ds(b1(),i);e?.aliases?.includes(i)&&(a=e)}let o=t.message.id,s=t.requestId,c=o8e(i,r.options.mcpClients),l=s8e(i,r.options.mcpClients);if(!a){let n=Ae(i);G(`Unknown tool ${i}: ${e.id}`),Y(`tengu_tool_use_error`,{error:`No such tool available: ${n}`,toolName:n,toolUseID:e.id,isMcp:i.startsWith(`mcp__`),queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Oe(i,c,l)}),yield{message:Q({content:[{type:`tool_result`,content:`<tool_use_error>Error: No such tool available: ${i}</tool_use_error>`,is_error:!0,tool_use_id:e.id}],toolUseResult:`Error: No such tool available: ${i}`,sourceToolAssistantUUID:t.uuid})};return}let u=e.input;try{if(r.abortController.signal.aborted){Y(`tengu_tool_use_cancelled`,{toolName:Ae(a.name),toolUseID:e.id,isMcp:a.isMcp??!1,queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Oe(a.name,c,l)});let n=n_e(e.id);n.content=r3(Hv),yield{message:Q({content:[n],toolUseResult:Hv,sourceToolAssistantUUID:t.uuid})};return}for await(let i of c8e(a,e.id,u,r,n,t,o,s,c,l))yield i}catch(n){J(n);let r=n instanceof Error?n.message:String(n),i=`Error calling tool${a?` (${a.name})`:``}: ${r}`;yield{message:Q({content:[{type:`tool_result`,content:`<tool_use_error>${i}</tool_use_error>`,is_error:!0,tool_use_id:e.id}],toolUseResult:i,sourceToolAssistantUUID:t.uuid})}}}function c8e(e,t,n,r,i,a,o,s,c,l){let u=new D1;return u8e(e,t,n,r,i,a,o,s,c,l,n=>{Y(`tengu_tool_use_progress`,{messageID:o,toolName:Ae(e.name),isMcp:e.isMcp??!1,queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Oe(e.name,c,l)}),u.enqueue({message:t_e({toolUseID:n.toolUseID,parentToolUseID:t,data:n.data})})}).then(e=>{for(let t of e)u.enqueue(t)}).catch(e=>{u.error(e)}).finally(()=>{u.done()}),u}function l8e(e,t,n){if(!hz()||!gz(n)||!As(e)||yz(t).has(e.name))return null;let r=e.userFacingName?e.userFacingName(void 0):e.name;return`\n\nTool "${r}" is deferred-loading and needs to be discovered before use.\nWhen using OpenAI-compatible models (DeepSeek, Ollama, etc.), follow these steps:\n1. First discover the tool with SearchExtraTools: ${Hs}("select:${e.name}")\n2. Then call ${r} tool\n\nExample:\n${Hs}("select:${e.name}") → ${r}({ ... })\n\nImportant notes:\n• Use camelCase parameter names (e.g., taskId), not snake_case (task_id)\n• All task tools (TaskGet, TaskCreate, TaskUpdate, TaskList) need to be discovered first\n• You can discover them all at once: ${Hs}("select:TaskGet,TaskCreate,TaskUpdate,TaskList")\n\nSee docs/openai-task-tools.md for detailed guide.`}async function u8e(e,t,n,r,i,a,o,s,c,l,u){let d=e.inputSchema.safeParse(n);if(!d.success){let n=v$e(e.name,d.error),i=l8e(e,r.messages,r.options.tools);return i&&(Y(`tengu_deferred_tool_schema_not_sent`,{toolName:Ae(e.name),isMcp:e.isMcp??!1}),n+=i),G(`${e.name} tool input error: ${n.slice(0,200)}`),Y(`tengu_tool_use_error`,{error:`InputValidationError`,errorDetails:n.slice(0,2e3),messageID:o,toolName:Ae(e.name),isMcp:e.isMcp??!1,queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Oe(e.name,c,l)}),[{message:Q({content:[{type:`tool_result`,content:`<tool_use_error>InputValidationError: ${n}</tool_use_error>`,is_error:!0,tool_use_id:t}],toolUseResult:`InputValidationError: ${d.error.message}`,sourceToolAssistantUUID:a.uuid})}]}let f=await e.validateInput?.(d.data,r);if(f?.result===!1)return G(`${e.name} tool validation error: ${f.message?.slice(0,200)}`),Y(`tengu_tool_use_error`,{messageID:o,toolName:Ae(e.name),error:f.message,errorCode:f.errorCode,isMcp:e.isMcp??!1,queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Oe(e.name,c,l)}),[{message:Q({content:[{type:`tool_result`,content:`<tool_use_error>${f.message}</tool_use_error>`,is_error:!0,tool_use_id:t}],toolUseResult:`Error: ${f.message}`,sourceToolAssistantUUID:a.uuid})}];if(e.name===`Bash`&&d.data&&`command`in d.data){let e=r.getAppState();XVe(d.data.command,e.toolPermissionContext,r.abortController.signal,r.options.isNonInteractiveSession)}let p=[],m=d.data;if(e.name===`Bash`&&m&&typeof m==`object`&&`_simulatedSedEdit`in m){let{_simulatedSedEdit:e,...t}=m;m=t}let h=m,g=e.backfillObservableInput&&typeof m==`object`&&m?{...m}:null;g&&(e.backfillObservableInput(g),m=g);let _=!1,v,y,b=[],x=Date.now();for await(let n of Q6e(r,e,m,t,a.message.id,s,c,l))switch(n.type){case`message`:if(n.message.message.type===`progress`)u(n.message.message);else{p.push(n.message);let e=n.message.message.attachment;e&&`command`in e&&e.command!==void 0&&`durationMs`in e&&e.durationMs!==void 0&&b.push({command:e.command,durationMs:e.durationMs})}break;case`hookPermissionResult`:y=n.hookPermissionResult;break;case`hookUpdatedInput`:m=n.updatedInput;break;case`preventContinuation`:_=n.shouldPreventContinuation;break;case`stopReason`:v=n.stopReason;break;case`additionalContext`:p.push(n.message);break;case`stop`:return Fn()?.observe(`pre_tool_hook_duration_ms`,Date.now()-x),p.push({message:Q({content:[n_e(t)],toolUseResult:`Error: ${v}`,sourceToolAssistantUUID:a.uuid})}),p}let S=Date.now()-x;Fn()?.observe(`pre_tool_hook_duration_ms`,S),S>=A1&&G(`Slow PreToolUse hooks: ${S}ms for ${e.name} (${b.length} hooks)`,{level:`info`});let C={};m&&typeof m==`object`&&(e.name===`Read`&&`file_path`in m||(e.name===`Edit`||e.name===`Write`)&&`file_path`in m?C.file_path=String(m.file_path):e.name===`Bash`&&`command`in m&&(C.full_command=m.command)),lse(e.name,C,dc()?U(m):void 0),mse();let w=r.getAppState().toolPermissionContext.mode,T=Date.now(),E=await Z6e(y,e,m,r,i,a,t),D=E.decision;m=E.input;let O=Date.now()-T;if(O>=A1&&w===`auto`&&G(`Slow permission decision: ${O}ms for ${e.name} (mode=${w}, behavior=${D.behavior})`,{level:`info`}),D.behavior!==`ask`&&!r.toolDecisions?.has(t)){let t=D.behavior===`allow`?`accept`:`reject`,n=r8e(D.decisionReason,D.behavior);fc(`tool_decision`,{decision:t,source:n,tool_name:Ae(e.name)}),hWe(e.name)&&gWe(e,m,t,n).then(e=>ute()?.add(1,e))}if(D.decisionReason?.type===`hook`&&D.decisionReason.hookName===`PermissionRequest`&&D.behavior!==`ask`&&p.push({message:r2({type:`hook_permission_decision`,decision:D.behavior,toolUseID:t,hookEvent:`PermissionRequest`})}),D.behavior!==`allow`){G(`${e.name} tool permission denied`);let n=r.toolDecisions?.get(t);ase(`reject`,n?.source||`unknown`),mc(),Y(`tengu_tool_use_can_use_tool_rejected`,{messageID:o,toolName:Ae(e.name),queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Oe(e.name,c,l)});let i=D.message;_&&!i&&(i=`Execution stopped by PreToolUse hook${v?`: ${v}`:``}`);let u=[{type:`tool_result`,content:i,is_error:!0,tool_use_id:t}],d=D.behavior===`ask`?D.contentBlocks:void 0;d?.length&&u.push(...d);let f;if(d?.length){let e=Xr(d,e=>e.type===`image`);if(e>0){let t=i8e(r.messages);f=Array.from({length:e},(e,n)=>t+n)}}return p.push({message:Q({content:u,imagePasteIds:f,toolUseResult:`Error: ${i}`,sourceToolAssistantUUID:a.uuid})}),p}Y(`tengu_tool_use_can_use_tool_allowed`,{messageID:o,toolName:Ae(e.name),queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Oe(e.name,c,l)}),D.updatedInput!==void 0&&(m=D.updatedInput);let k=ge(m),A={};if(Me()){if(e.name===`Bash`&&`command`in m){let e=m;A={bash_command:e.command.trim().split(/\s+/)[0]||``,full_command:e.command,...e.timeout!==void 0&&{timeout:e.timeout},...e.description!==void 0&&{description:e.description},...`dangerouslyDisableSandbox`in e&&{dangerouslyDisableSandbox:e.dangerouslyDisableSandbox}}}let t=pe(e.name);t&&(A.mcp_server_name=t.serverName,A.mcp_tool_name=t.mcpToolName);let n=_e(e.name,m);n&&(A.skill_name=n)}let ee=r.toolDecisions?.get(t);ase(ee?.decision||`unknown`,ee?.source||`unknown`),dse();let te=Date.now();Vz(`tool_exec`),g&&m!==h&&typeof m==`object`&&m&&`file_path`in m&&`file_path`in h&&m.file_path===g.file_path?h={...m,file_path:h.file_path}:m!==g&&(h=m);try{let n=()=>e.call(h,{...r,toolUseId:t,userModified:D.userModified??!1},i,a,e=>{u({toolUseID:e.toolUseID,data:e.data})}),d=wse()?await(async()=>{let{runToolCallWithSkillLearningHooks:t}=await e8e();return t(e.name,h,{sessionId:r.sessionId},n)})():await n(),f=Date.now()-te;if(xn(f),d.data&&typeof d.data==`object`){let t={};e.name===`Read`&&`content`in d.data&&(`file_path`in m&&(t.file_path=String(m.file_path)),t.content=String(d.data.content)),(e.name===`Edit`||e.name===`Write`)&&`file_path`in m&&(t.file_path=String(m.file_path),e.name===`Edit`&&`diff`in d.data&&(t.diff=String(d.data.diff)),e.name===`Write`&&`content`in m&&(t.content=String(m.content))),e.name===`Bash`&&`command`in m&&(t.bash_command=m.command,`output`in d.data&&(t.output=String(d.data.output))),Object.keys(t).length>0&&hse(`tool.output`,t)}typeof d==`object`&&`structured_output`in d&&p.push({message:r2({type:`structured_output`,data:d.structured_output})}),pse({success:!0}),mc(d.data&&typeof d.data==`object`?U(d.data):String(d.data??``));let g=e.mapToolResultToToolResultBlockParam(d.data,t),y=g.content,b=y?typeof y==`string`?y.length:U(y).length:0,x;if(m&&typeof m==`object`){if((e.name===`Read`||e.name===`Edit`||e.name===`Write`)&&`file_path`in m)x=me(String(m.file_path));else if(e.name===`NotebookEdit`&&`notebook_path`in m)x=me(String(m.notebook_path));else if(e.name===`Bash`&&`command`in m){let e=m;x=de(e.command,e._simulatedSedEdit?.filePath)}}if(Y(`tengu_tool_use_success`,{messageID:o,toolName:Ae(e.name),isMcp:e.isMcp??!1,durationMs:f,preToolHookDurationMs:S,toolResultSizeBytes:b,...x!==void 0&&{fileExtension:x},queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Oe(e.name,c,l)}),Me()&&(e.name===`Bash`||e.name===`PowerShell`)&&`command`in m&&typeof m.command==`string`&&m.command.match(/\bgit\s+commit\b/)&&d.data&&typeof d.data==`object`&&`stdout`in d.data){let e=uG(String(d.data.stdout));e&&(A.git_commit_id=e)}let C=yA(e)?xA(e.name):null;fc(`tool_result`,{tool_name:Ae(e.name),success:`true`,duration_ms:String(f),...Object.keys(A).length>0&&{tool_parameters:U(A)},...k&&{tool_input:k},tool_result_size_bytes:String(b),...ee&&{decision_source:ee.source,decision_type:ee.decision},...C&&{mcp_server_scope:C}});let w=d.data,T=[],E=d.contextModifier,O=d.mcpMeta;async function ne(n,i){let o=[i?await Abe(i,e.name,e.maxResultSizeChars):await pS(e,n,t)];`acceptFeedback`in D&&D.acceptFeedback&&o.push({type:`text`,text:D.acceptFeedback});let s=`contentBlocks`in D?D.contentBlocks:void 0;s?.length&&o.push(...s);let c;if(s?.length){let e=Xr(s,e=>e.type===`image`);if(e>0){let t=i8e(r.messages);c=Array.from({length:e},(e,n)=>t+n)}}p.push({message:Q({content:o,imagePasteIds:c,toolUseResult:r.agentId&&!r.preserveToolUseResults?void 0:n,mcpMeta:r.agentId?void 0:O,sourceToolAssistantUUID:a.uuid}),contextModifier:E?{toolUseID:t,modifyContext:E}:void 0})}yA(e)||await ne(w,g);let re=[],ie=Date.now();for await(let n of Y6e(r,e,t,a.message.id,m,w,s,c,l))if(`updatedMCPToolOutput`in n)yA(e)&&(w=n.updatedMCPToolOutput);else if(yA(e)){if(T.push(n),n.message.type===`attachment`){let e=n.message.attachment;`command`in e&&e.command!==void 0&&`durationMs`in e&&e.durationMs!==void 0&&re.push({command:e.command,durationMs:e.durationMs})}}else if(p.push(n),n.message.type===`attachment`){let e=n.message.attachment;`command`in e&&e.command!==void 0&&`durationMs`in e&&e.durationMs!==void 0&&re.push({command:e.command,durationMs:e.durationMs})}let ae=Date.now()-ie;if(ae>=A1&&G(`Slow PostToolUse hooks: ${ae}ms for ${e.name} (${re.length} hooks)`,{level:`info`}),yA(e)&&await ne(w),d.newMessages&&d.newMessages.length>0)for(let e of d.newMessages)p.push({message:e});_&&p.push({message:r2({type:`hook_stopped_continuation`,message:v||`Execution stopped by hook`,hookName:`PreToolUse:${e.name}`,toolUseID:t,hookEvent:`PreToolUse`})});for(let e of T)p.push(e);return p}catch(n){let i=Date.now()-te;if(xn(i),pse({success:!1,error:W(n)}),mc(),n instanceof JA&&r.setAppState(e=>{let t=n.serverName,r=e.mcp.clients.findIndex(e=>e.name===t);if(r===-1)return e;let i=e.mcp.clients[r];if(i?.type!==`connected`)return e;let a=[...e.mcp.clients];return a[r]={name:t,type:`needs-auth`,config:i.config},{...e,mcp:{...e.mcp,clients:a}}}),!(n instanceof Wn)){let a=W(n);G(`${e.name} tool error (${i}ms): ${a.slice(0,200)}`),n instanceof Un||J(n),Y(`tengu_tool_use_error`,{messageID:o,toolName:Ae(e.name),error:t8e(n),isMcp:e.isMcp??!1,queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Oe(e.name,c,l)});let u=yA(e)?xA(e.name):null;fc(`tool_result`,{tool_name:Ae(e.name),use_id:t,success:`false`,duration_ms:String(i),error:W(n),...Object.keys(A).length>0&&{tool_parameters:U(A)},...k&&{tool_input:k},...ee&&{decision_source:ee.source,decision_type:ee.decision},...u&&{mcp_server_scope:u}})}let u=TQ(n),d=n instanceof Wn,f=[];for await(let n of X6e(r,e,t,o,m,u,d,s,c,l))f.push(n);return[{message:Q({content:[{type:`tool_result`,content:u,is_error:!0,tool_use_id:t}],toolUseResult:`Error: ${u}`,mcpMeta:r.agentId?void 0:n instanceof XA?n.mcpMeta:void 0,sourceToolAssistantUUID:a.uuid})},...f]}finally{Hz(`tool_exec`),ee&&r.toolDecisions?.delete(t)}}var k1,A1,d8e=n((()=>{oo(),Se(),Jt(),SWe(),Ks(),iJ(),js(),Ls(),Us(),bs(),Ps(),ms(),yG(),Bs(),E1(),Ar(),m2(),K(),qn(),g7(),Ga(),h3(),Zz(),mr(),K6e(),hc(),pc(),EQ(),vS(),Dz(),cj(),Ri(),ci(),CA(),$6e(),Tse(),A1=2e3}));function f8e(e,t){e.setInProgressToolUseIDs(e=>{let n=new Set(e);return n.delete(t),n})}var j1,p8e=n((()=>{h3(),Ks(),js(),UO(),d8e(),b(),j1=class{constructor(e,t,n){x(this,`toolDefinitions`,void 0),x(this,`canUseTool`,void 0),x(this,`tools`,[]),x(this,`toolUseContext`,void 0),x(this,`hasErrored`,!1),x(this,`erroredToolDescription`,``),x(this,`siblingAbortController`,void 0),x(this,`discarded`,!1),x(this,`progressAvailableResolve`,void 0),this.toolDefinitions=e,this.canUseTool=t,this.toolUseContext=n,this.siblingAbortController=VO(n.abortController)}discard(){this.discarded=!0,this.siblingAbortController.abort(`streaming_fallback`),this.tools.length=0,this.progressAvailableResolve=void 0}addTool(e,t){let n=Ds(this.toolDefinitions,e.name);if(!n){this.tools.push({id:e.id,block:e,assistantMessage:t,status:`completed`,isConcurrencySafe:!0,pendingProgress:[],results:[Q({content:[{type:`tool_result`,content:`<tool_use_error>Error: No such tool available: ${e.name}</tool_use_error>`,is_error:!0,tool_use_id:e.id}],toolUseResult:`Error: No such tool available: ${e.name}`,sourceToolAssistantUUID:t.uuid})]});return}let r=n.inputSchema.safeParse(e.input),i=r?.success?(()=>{try{return!!n.isConcurrencySafe(r.data)}catch{return!1}})():!1;this.tools.push({id:e.id,block:e,assistantMessage:t,status:`queued`,isConcurrencySafe:i,pendingProgress:[]}),this.processQueue()}canExecuteTool(e){let t=this.tools.filter(e=>e.status===`executing`);return t.length===0||e&&t.every(e=>e.isConcurrencySafe)}async processQueue(){for(let e of this.tools)if(e.status===`queued`){if(this.canExecuteTool(e.isConcurrencySafe))await this.executeTool(e);else if(!e.isConcurrencySafe)break}}createSyntheticErrorMessage(e,t,n){if(t===`user_interrupted`)return Q({content:[{type:`tool_result`,content:r3(Uv),is_error:!0,tool_use_id:e}],toolUseResult:`User rejected tool use`,sourceToolAssistantUUID:n.uuid});if(t===`streaming_fallback`)return Q({content:[{type:`tool_result`,content:`<tool_use_error>Error: Streaming fallback - tool execution discarded</tool_use_error>`,is_error:!0,tool_use_id:e}],toolUseResult:`Streaming fallback - tool execution discarded`,sourceToolAssistantUUID:n.uuid});let r=this.erroredToolDescription,i=r?`Cancelled: parallel tool call ${r} errored`:`Cancelled: parallel tool call errored`;return Q({content:[{type:`tool_result`,content:`<tool_use_error>${i}</tool_use_error>`,is_error:!0,tool_use_id:e}],toolUseResult:i,sourceToolAssistantUUID:n.uuid})}getAbortReason(e){return this.discarded?`streaming_fallback`:this.hasErrored?`sibling_error`:this.toolUseContext.abortController.signal.aborted?this.toolUseContext.abortController.signal.reason===`interrupt`?this.getToolInterruptBehavior(e)===`cancel`?`user_interrupted`:null:`user_interrupted`:null}getToolInterruptBehavior(e){let t=Ds(this.toolDefinitions,e.block.name);if(!t?.interruptBehavior)return`block`;try{return t.interruptBehavior()}catch{return`block`}}getToolDescription(e){let t=e.block.input,n=t?.command??t?.file_path??t?.pattern??``;if(typeof n==`string`&&n.length>0){let t=n.length>40?`${n.slice(0,40)}\u2026`:n;return`${e.block.name}(${t})`}return e.block.name}updateInterruptibleState(){let e=this.tools.filter(e=>e.status===`executing`);this.toolUseContext.setHasInterruptibleToolInProgress?.(e.length>0&&e.every(e=>this.getToolInterruptBehavior(e)===`cancel`))}async executeTool(e){e.status=`executing`,this.toolUseContext.setInProgressToolUseIDs(t=>new Set(t).add(e.id)),this.updateInterruptibleState();let t=[],n=[],r=(async()=>{let r=this.getAbortReason(e);if(r){t.push(this.createSyntheticErrorMessage(e.id,r,e.assistantMessage)),e.results=t,e.contextModifiers=n,e.status=`completed`,this.updateInterruptibleState();return}let i=VO(this.siblingAbortController);i.signal.addEventListener(`abort`,()=>{i.signal.reason!==`sibling_error`&&!this.toolUseContext.abortController.signal.aborted&&!this.discarded&&this.toolUseContext.abortController.abort(i.signal.reason)},{once:!0});let a=O1(e.block,e.assistantMessage,this.canUseTool,{...this.toolUseContext,abortController:i}),o=!1;for await(let r of a){let i=this.getAbortReason(e);if(i&&!o){t.push(this.createSyntheticErrorMessage(e.id,i,e.assistantMessage));break}r.message.type===`user`&&Array.isArray(r.message.message.content)&&r.message.message.content.some(e=>e.type===`tool_result`&&e.is_error===!0)&&(o=!0,e.block.name===`Bash`&&(this.hasErrored=!0,this.erroredToolDescription=this.getToolDescription(e),this.siblingAbortController.abort(`sibling_error`))),r.message&&(r.message.type===`progress`?(e.pendingProgress.push(r.message),this.progressAvailableResolve&&(this.progressAvailableResolve(),this.progressAvailableResolve=void 0)):t.push(r.message)),r.contextModifier&&n.push(r.contextModifier.modifyContext)}if(e.results=t,e.contextModifiers=n,e.status=`completed`,this.updateInterruptibleState(),!e.isConcurrencySafe&&n.length>0)for(let e of n)this.toolUseContext=e(this.toolUseContext)})();e.promise=r,r.finally(()=>{this.processQueue()})}*getCompletedResults(){if(!this.discarded)for(let e of this.tools){for(;e.pendingProgress.length>0;)yield{message:e.pendingProgress.shift(),newContext:this.toolUseContext};if(e.status!==`yielded`){if(e.status===`completed`&&e.results){e.status=`yielded`;for(let t of e.results)yield{message:t,newContext:this.toolUseContext};f8e(this.toolUseContext,e.id)}else if(e.status===`executing`&&!e.isConcurrencySafe)break}}}hasPendingProgress(){return this.tools.some(e=>e.pendingProgress.length>0)}async*getRemainingResults(){if(!this.discarded){for(;this.hasUnfinishedTools();){await this.processQueue();for(let e of this.getCompletedResults())yield e;if(this.hasExecutingTools()&&!this.hasCompletedResults()&&!this.hasPendingProgress()){let e=this.tools.filter(e=>e.status===`executing`&&e.promise).map(e=>e.promise),t=new Promise(e=>{this.progressAvailableResolve=e});e.length>0&&await Promise.race([...e,t])}}for(let e of this.getCompletedResults())yield e}}hasCompletedResults(){return this.tools.some(e=>e.status===`completed`)}hasExecutingTools(){return this.tools.some(e=>e.status===`executing`)}hasUnfinishedTools(){return this.tools.some(e=>e.status!==`yielded`)}getUpdatedContext(){return this.toolUseContext}}}));function m8e(){N1&&(ho().clearMarks(),P1.clear(),I1=null,F1++,M1(`query_user_input_received`))}function M1(e){if(!N1)return;let t=ho();if(t.mark(e),P1.set(e,process.memoryUsage()),e===`query_first_chunk_received`&&I1===null){let e=t.getEntriesByType(`mark`);e.length>0&&(I1=e[e.length-1]?.startTime??0)}}function h8e(){N1&&M1(`query_profile_end`)}function g8e(e,t){return t===`query_user_input_received`?``:e>1e3?` ⚠️ VERY SLOW`:e>100?` ⚠️ SLOW`:t.includes(`git_status`)&&e>50?` ⚠️ git status`:t.includes(`tool_schema`)&&e>50?` ⚠️ tool schemas`:t.includes(`client_creation`)&&e>50?` ⚠️ client creation`:``}function _8e(){if(!N1)return`Query profiling not enabled (set CLAUDE_CODE_PROFILE_QUERY=1)`;let e=ho().getEntriesByType(`mark`);if(e.length===0)return`No query profiling checkpoints recorded`;let t=[];t.push(`=`.repeat(80)),t.push(`QUERY PROFILING REPORT - Query #${F1}`),t.push(`=`.repeat(80)),t.push(``);let n=e[0]?.startTime??0,r=n,i=0,a=0;for(let o of e){let e=o.startTime-n,s=o.startTime-r;t.push(kie(e,s,o.name,P1.get(o.name),10,9,g8e(s,o.name))),o.name===`query_api_request_sent`&&(i=e),o.name===`query_first_chunk_received`&&(a=e),r=o.startTime}let o=e[e.length-1],s=o?o.startTime-n:0;if(t.push(``),t.push(`-`.repeat(80)),a>0){let e=i,n=a-i,r=(e/a*100).toFixed(1),o=(n/a*100).toFixed(1);t.push(`Total TTFT: ${co(a)}ms`),t.push(` - Pre-request overhead: ${co(e)}ms (${r}%)`),t.push(` - Network latency: ${co(n)}ms (${o}%)`)}else t.push(`Total time: ${co(s)}ms`);return t.push(v8e(e,n)),t.push(`=`.repeat(80)),t.join(`
|
|
2400
2400
|
`)}function v8e(e,t){let n=[{name:`Context loading`,start:`query_context_loading_start`,end:`query_context_loading_end`},{name:`Microcompact`,start:`query_microcompact_start`,end:`query_microcompact_end`},{name:`Autocompact`,start:`query_autocompact_start`,end:`query_autocompact_end`},{name:`Query setup`,start:`query_setup_start`,end:`query_setup_end`},{name:`Tool schemas`,start:`query_tool_schema_build_start`,end:`query_tool_schema_build_end`},{name:`Message normalization`,start:`query_message_normalization_start`,end:`query_message_normalization_end`},{name:`Client creation`,start:`query_client_creation_start`,end:`query_client_creation_end`},{name:`Network TTFB`,start:`query_api_request_sent`,end:`query_first_chunk_received`},{name:`Tool execution`,start:`query_tool_execution_start`,end:`query_tool_execution_end`}],r=new Map(e.map(e=>[e.name,e.startTime-t])),i=[];i.push(``),i.push(`PHASE BREAKDOWN:`);for(let e of n){let t=r.get(e.start),n=r.get(e.end);if(t!==void 0&&n!==void 0){let r=n-t,a=`█`.repeat(Math.min(Math.ceil(r/10),50));i.push(` ${e.name.padEnd(22)} ${co(r).padStart(10)}ms ${a}`)}}let a=r.get(`query_api_request_sent`);return a!==void 0&&(i.push(``),i.push(` ${`Total pre-API overhead`.padEnd(22)} ${co(a).padStart(10)}ms`)),i.join(`
|
|
2401
2401
|
`)}function y8e(){N1&&G(_8e())}var N1,P1,F1,I1,L1=n((()=>{K(),g(),lo(),N1=h(process.env.CLAUDE_CODE_PROFILE_QUERY),P1=new Map,F1=0,I1=null}));async function*b8e(e,t=1/0){let n=e=>{let t=e.next().then(({done:n,value:r})=>({done:n,value:r,generator:e,promise:t}));return t},r=[...e],i=new Set;for(;i.size<t&&r.length>0;){let e=r.shift();i.add(n(e))}for(;i.size>0;){let{done:e,value:t,generator:a,promise:o}=await Promise.race(i);if(i.delete(o),!e)i.add(n(a)),t!==void 0&&(yield t);else if(r.length>0){let e=r.shift();i.add(n(e))}}}async function x8e(e){let t=[];for await(let n of e)t.push(n);return t}async function*S8e(e){for(let t of e)yield t}var R1=n((()=>{}));function C8e(){return parseInt(process.env.CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY||``,10)||10}async function*w8e(e,t,n,r){let i=r;for(let{isConcurrencySafe:r,blocks:a}of T8e(e,i))if(r){let e={};for await(let r of D8e(a,t,n,i)){if(r.contextModifier){let{toolUseID:t,modifyContext:n}=r.contextModifier;e[t]||(e[t]=[]),e[t].push(n)}yield{message:r.message,newContext:i}}for(let t of a){let n=e[t.id];if(n)for(let e of n)i=e(i)}yield{newContext:i}}else for await(let e of E8e(a,t,n,i))e.newContext&&(i=e.newContext),yield{message:e.message,newContext:i}}function T8e(e,t){return e.reduce((e,n)=>{let r=Ds(t.options.tools,n.name),i=r?.inputSchema.safeParse(n.input),a=i?.success?(()=>{try{return!!r?.isConcurrencySafe(i.data)}catch{return!1}})():!1;return a&&e[e.length-1]?.isConcurrencySafe?e[e.length-1].blocks.push(n):e.push({isConcurrencySafe:a,blocks:[n]}),e},[])}async function*E8e(e,t,n,r){let i=r;for(let a of e){r.setInProgressToolUseIDs(e=>new Set(e).add(a.id));for await(let e of O1(a,t.find(e=>Array.isArray(e.message.content)&&e.message.content.some(e=>e.type===`tool_use`&&e.id===a.id)),n,i))e.contextModifier&&(i=e.contextModifier.modifyContext(i)),yield{message:e.message,newContext:i};O8e(r,a.id)}}async function*D8e(e,t,n,r){yield*b8e(e.map(async function*(e){r.setInProgressToolUseIDs(t=>new Set(t).add(e.id)),yield*O1(e,t.find(t=>Array.isArray(t.message.content)&&t.message.content.some(t=>t.type===`tool_use`&&t.id===e.id)),n,r),O8e(r,e.id)}),C8e())}function O8e(e,t){e.setInProgressToolUseIDs(e=>{let n=new Set(e);return n.delete(t),n})}var k8e=n((()=>{Ks(),R1(),d8e()}));async function A8e(e,t){let n=X(e,`state.json`),r;try{r=JSON.parse(zc(n,`utf-8`))}catch{return}let i=j8e(t);r.status=i,r.updatedAt=new Date().toISOString(),ece(n,JSON.stringify(r,null,2),`utf-8`)}function j8e(e){if(e.length===0)return`running`;let t=e[e.length-1],n=t.message?.content;return Array.isArray(n)&&n.some(e=>typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_use`)?`running`:t.message?.stop_reason===`end_turn`?`completed`:`running`}var M8e=n((()=>{}));function N8e(){let e=Vi().autoDreamEnabled;return e!==void 0&&e}var P8e=n((()=>{vi()}));async function F8e(e,t){try{let n=(await nl(e,{recursive:!0})).filter(e=>e.endsWith(`.md`)&&bc(e)!==`MEMORY.md`);return(await Promise.allSettled(n.map(async n=>{let r=X(e,n),{content:i,mtimeMs:a}=await ES(r,0,R8e,void 0,t),{frontmatter:o}=Iu(i,r);return{filename:n,filePath:r,mtimeMs:a,description:o.description||null,type:ede(o.type)}}))).filter(e=>e.status===`fulfilled`).map(e=>e.value).sort((e,t)=>t.mtimeMs-e.mtimeMs).slice(0,L8e)}catch{return[]}}function I8e(e){return e.map(e=>{let t=e.type?`[${e.type}] `:``,n=new Date(e.mtimeMs).toISOString();return e.description?`- ${t}${e.filename} (${n}): ${e.description}`:`- ${t}${e.filename} (${n})`}).join(`
|
|
2402
2402
|
`)}var L8e,R8e,z8e=n((()=>{Ku(),kS(),ld(),L8e=200,R8e=30}));function B8e(e,t){let n=t.length>0?`\n\n## Existing memory files\n\n${t}\n\nCheck this list before writing — update an existing file rather than creating a duplicate.`:``;return[`You are now acting as the memory extraction subagent. Analyze the most recent ~${e} messages above and use them to update your persistent memory systems.`,``,`Available tools: ${ys}, ${ss}, ${qs}, read-only ${Vs} (ls/find/cat/stat/wc/head/tail and similar), and ${Gs}/${ks} for paths inside the memory directory only. ${Vs} rm is not permitted. All other tools — MCP, Agent, write-capable ${Vs}, etc — will be denied.`,``,`You have a limited turn budget. ${Gs} requires a prior ${ys} of the same file, so the efficient strategy is: turn 1 — issue all ${ys} calls in parallel for every file you might update; turn 2 — issue all ${ks}/${Gs} calls in parallel. Do not interleave reads and writes across multiple turns.`,``,`You MUST only use content from the last ~${e} messages to update your persistent memories. Do not waste any turns attempting to investigate or verify that content further — no grepping source files, no reading code to confirm a pattern exists, no git commands.`+n].join(`
|
|
@@ -2456,7 +2456,7 @@ Return a brief summary of what you consolidated, updated, or pruned. If nothing
|
|
|
2456
2456
|
|
|
2457
2457
|
Sessions since last consolidation (${c.length}):
|
|
2458
2458
|
${c.map(e=>`- ${e}`).join(`
|
|
2459
|
-
`)}`)})],cacheSafeParams:n0(t),canUseTool:B1(e),querySource:`auto_dream`,forkLabel:`auto_dream`,maxTurns:20,skipTranscript:!0,overrides:{abortController:f},onMessage:i5e(p,d)});EZe(p,d);let i=t.toolUseContext.getAppState().tasks?.[p];n&&CZe(i)&&i.filesTouched.length>0&&n({...o_e(i.filesTouched),verb:`Improved`}),G(`[autoDream] completed — cache: read=${r.totalUsage.cache_read_input_tokens} created=${r.totalUsage.cache_creation_input_tokens}`),Y(`tengu_auto_dream_completed`,{cache_read:r.totalUsage.cache_read_input_tokens,cache_created:r.totalUsage.cache_creation_input_tokens,output:r.totalUsage.output_tokens,sessions_reviewed:c.length})}catch(e){if(f.signal.aborted){G(`[autoDream] aborted by user`);return}G(`[autoDream] fork failed: ${e.message}`),Y(`tengu_auto_dream_failed`,{}),DZe(p,d),await vZe(u)}}}function i5e(e,t){return n=>{if(n.type!==`assistant`)return;let r=``,i=0,a=[],o=n.message.content;for(let e of o)if(e.type===`text`)r+=e.text;else if(e.type===`tool_use`&&(i++,e.name===`Edit`||e.name===`Write`)){let t=e.input;typeof t.file_path==`string`&&a.push(t.file_path)}TZe(e,{text:r.trim(),toolUseCount:i},a,t)}}async function a5e(e,t){await U1?.(e,t)}var o5e,s5e,U1,c5e=n((()=>{o0(),h3(),K(),oo(),ra(),P8e(),h8(),Jt(),Z8e(),$8e(),LZ(),zZ(),Ls(),bs(),o5e=600*1e3,s5e={minHours:24,minSessions:5},U1=null}));async function*l5e(e,t,n,r,i,a,o,s){let c=Date.now(),l={messages:[...e,...t],systemPrompt:n,userContext:r,systemContext:i,toolUseContext:a,querySource:o};if((o===`repl_main_thread`||o===`sdk`)&&U5e(n0(l)),process.env.CLAUDE_JOB_DIR&&o.startsWith(`repl_main_thread`)&&!a.agentId){let e=l.messages.filter(e=>e.type===`assistant`),t=A8e(process.env.CLAUDE_JOB_DIR,e).catch(e=>{G(`[job] classifier error: ${W(e)}`,{level:`error`})});await Promise.race([t,new Promise(e=>setTimeout(e,6e4).unref())])}let u=(await import(`./poorMode-G-pnu6NM.js`)).isPoorModeActive();v()||(!f(process.env.CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION)&&!u&&o7e(l),!a.agentId&&mie()&&!u&&import(`./extractMemories-xP63mv6R.js`).then(({executeExtractMemories:e})=>e(l,a.appendSystemMessage)).catch(()=>{}),!a.agentId&&!u&&a5e(l,a.appendSystemMessage));try{let n=[],r=a.getAppState().toolPermissionContext.mode,i=alt(r,a.abortController.signal,void 0,s??!1,a.agentId,a,[...e,...t],a.agentType),o=``,c=0,l=!1,u=``,d=!1,f=[],p=[];for await(let e of i){if(e.message){if(yield e.message,e.message.type===`progress`&&e.message.toolUseID){o=e.message.toolUseID,c++;let t=e.message.data;t.command&&p.push({command:t.command,promptText:t.promptText})}if(e.message.type===`attachment`){let t=e.message.attachment;if(`hookEvent`in t&&(t.hookEvent===`Stop`||t.hookEvent===`SubagentStop`)&&(t.type===`hook_non_blocking_error`?(f.push(t.stderr||`Exit code ${t.exitCode}`),d=!0):t.type===`hook_error_during_execution`?(f.push(t.content),d=!0):t.type===`hook_success`&&(t.stdout&&t.stdout.trim()||t.stderr&&t.stderr.trim())&&(d=!0),`durationMs`in t&&`command`in t)){let e=p.find(e=>e.command===t.command&&e.durationMs===void 0);e&&(e.durationMs=t.durationMs)}}}if(e.blockingError){let t=Q({content:Zct(e.blockingError),isMeta:!0});n.push(t),yield t,d=!0,f.push(e.blockingError.blockingError)}if(e.preventContinuation&&(l=!0,u=e.stopReason||`Stop hook prevented continuation`,yield r2({type:`hook_stopped_continuation`,message:u,hookName:`Stop`,toolUseID:o,hookEvent:`Stop`})),a.abortController.signal.aborted)return Y(`tengu_pre_stop_hooks_cancelled`,{queryChainId:a.queryTracking?.chainId,queryDepth:a.queryTracking?.depth}),yield ey({toolUse:!1}),{blockingErrors:[],preventContinuation:!0}}if(c>0&&(yield i_e(c,p,f,l,u,d,`suggestion`,o),f.length>0)){let e=LS(`app:toggleTranscript`,`Global`,`ctrl+o`);a.addNotification?.({key:`stop-hook-error`,text:`Stop hook error occurred \u00b7 ${e} to see`,priority:`immediate`})}return l?{blockingErrors:[],preventContinuation:!0}:n.length>0?{blockingErrors:n,preventContinuation:!1}:{blockingErrors:[],preventContinuation:!1}}catch(e){return Y(`tengu_stop_hook_error`,{duration:Date.now()-c,queryChainId:a.queryTracking?.chainId,queryDepth:a.queryTracking?.depth}),yield ry(`Stop hook failed: ${W(e)}`,`warning`),{blockingErrors:[],preventContinuation:!1}}}var u5e=n((()=>{zS(),ra(),oo(),m2(),K(),qn(),g7(),h3(),M8e(),c5e(),h0(),g(),o0()}));function d5e(){return{sessionId:jn(),gates:{streamingToolExecution:!1,emitToolUseSummaries:h(process.env.CLAUDE_CODE_EMIT_TOOL_USE_SUMMARIES),fastModeEnabled:!h(process.env.CLAUDE_CODE_DISABLE_FAST_MODE)}}}var f5e=n((()=>{Jt(),g()}));function p5e(){return{callModel:fdt,microcompact:OR,autocompact:IHe,uuid:Jc}}var m5e=n((()=>{n9(),CJ(),MR()}));function W1(e,t){return parseFloat(e)*y5e[t.toLowerCase()]}function h5e(e){let t=e.match(_5e);if(t)return W1(t[1],t[2]);let n=e.match(v5e);if(n)return W1(n[1],n[2]);let r=e.match(G1);return r?W1(r[1],r[2]):null}function g5e(e,t,n){let r=e=>new Intl.NumberFormat(`en-US`).format(e);return`Stopped at ${e}% of token target (${r(t)} / ${r(n)}). Keep working \u2014 do not summarize.`}var _5e,v5e,G1,y5e,b5e=n((()=>{_5e=/^\s*\+(\d+(?:\.\d+)?)\s*(k|m|b)\b/i,v5e=/\s\+(\d+(?:\.\d+)?)\s*(k|m|b)\s*[.!?]?\s*$/i,G1=/\b(?:use|spend)\s+(\d+(?:\.\d+)?)\s*(k|m|b)\s*tokens?\b/i,new RegExp(G1.source,`gi`),y5e={k:1e3,m:1e6,b:1e9}}));function x5e(){return{continuationCount:0,lastDeltaTokens:0,lastGlobalTurnTokens:0,startedAt:Date.now()}}function S5e(e,t,n,r){if(t||n===null||n<=0)return{action:`stop`,completionEvent:null};let i=r,a=Math.round(i/n*100),o=r-e.lastGlobalTurnTokens,s=e.continuationCount>=3&&o<K1&&e.lastDeltaTokens<K1;return!s&&i<n*C5e?(e.continuationCount++,e.lastDeltaTokens=o,e.lastGlobalTurnTokens=r,{action:`continue`,nudgeMessage:g5e(a,i,n),continuationCount:e.continuationCount,pct:a,turnTokens:i,budget:n}):s||e.continuationCount>0?{action:`stop`,completionEvent:{continuationCount:e.continuationCount,pct:a,turnTokens:i,budget:n,diminishingReturns:s,durationMs:Date.now()-e.startedAt}}:{action:`stop`,completionEvent:null}}var C5e,K1,w5e=n((()=>{b5e(),C5e=.9,K1=500}));function q1(){return X(m(),`sessions`)}function T5e(){let e=process.env.CLAUDE_CODE_SESSION_KIND;if(e===`bg`)return e}function E5e(){return T5e()===`bg`}async function D5e(){let e=T5e()??`interactive`,t=q1(),n=X(t,`${process.pid}.json`);ar(async()=>{try{await cl(n)}catch{}});try{return await $c(t,{recursive:!0,mode:448}),await Xc(t,448),await ll(n,U({pid:process.pid,sessionId:jn(),cwd:Yt(),startedAt:Date.now(),kind:e,entrypoint:process.env.CLAUDE_CODE_ENTRYPOINT,name:process.env.CLAUDE_CODE_SESSION_NAME,logPath:process.env.CLAUDE_CODE_SESSION_LOG,agent:process.env.CLAUDE_CODE_AGENT})),gte(e=>{J1({sessionId:e})}),!0}catch(e){return G(`[concurrentSessions] register failed: ${W(e)}`),!1}}async function J1(e){let t=X(q1(),`${process.pid}.json`);try{await ll(t,U({...$n(await tl(t,`utf8`)),...e}))}catch(e){G(`[concurrentSessions] updatePidFile failed: ${W(e)}`)}}async function O5e(e){e&&await J1({name:e})}async function k5e(e){await J1({...e,updatedAt:Date.now()})}async function A5e(){let e=q1(),t;try{t=await nl(e)}catch(e){return hr(e)||G(`[concurrentSessions] readdir failed: ${W(e)}`),0}let n=0;for(let r of t){if(!/^\d+\.json$/.test(r))continue;let t=parseInt(r.slice(0,-5),10);if(t===process.pid){n++;continue}oc(t)?n++:io()!==`wsl`&&cl(X(e,r)).catch(()=>{})}return n}var Y1=n((()=>{Jt(),Hn(),K(),g(),qn(),sc(),ao(),mr()}));function j5e(){return E5e()?Date.now()-X1>=N5e:!1}function M5e(e){X1=Date.now();try{let t=e.forkContextMessages;if(!t||t.length===0)return;let n;for(let e=t.length-1;e>=0;e--)if(t[e].type===`assistant`){n=t[e];break}let r=`busy`,i;if(n?.message?.content){let e=n.message.content;if(Array.isArray(e)){let t=e[e.length-1];t?.type===`tool_use`&&(r=`busy`,i=`tool: ${t.name||`unknown`}`)}}k5e({status:r,waitingFor:i}).catch(e=>{G(`[taskSummary] updateSessionActivity failed: ${e}`)})}catch(e){G(`[taskSummary] error: ${e}`)}}var N5e,X1,P5e=n((()=>{Y1(),K(),N5e=3e4,X1=0}));function*Z1(e,t){for(let n of e){let e=(Array.isArray(n.message?.content)?n.message.content:[]).filter(e=>e.type===`tool_use`);for(let r of e)yield Q({content:[{type:`tool_result`,content:t,is_error:!0,tool_use_id:r.id}],toolUseResult:t,sourceToolAssistantUUID:n.uuid})}}function F5e(e){return e?.type===`assistant`&&e.apiError===`max_output_tokens`}function I5e(e){if(e.thrownError!==void 0)return{type:`failed`,error:e.thrownError};let t=e.terminal,n=t?.reason;switch(n){case`completed`:return{type:`completed`};case void 0:case`aborted_streaming`:case`aborted_tools`:return{type:`cancelled`};case`model_error`:return{type:`failed`,error:t.error};default:return{type:`failed`,message:`query ended without successful completion: ${n}`}}}async function*Q1(e){let t=[],n=[],r,i=!1,a;try{r=yield*L5e(e,t,n)}catch(e){throw i=!0,a=e,e}finally{await aWe({commands:n,outcome:I5e({terminal:r,...i?{thrownError:a}:{}}),priority:`later`}).then(e=>{for(let t of e)SI(t)}).catch(J);let e=globalThis.performance;if(e&&typeof e.clearMarks==`function`)try{e.clearMarks(),e.clearMeasures?.(),e.clearResourceTimings?.()}catch{}}for(let e of t)WJ(e,`completed`);return r}async function*L5e(e,t,n){try{var r=Sne();let{systemPrompt:i,userContext:a,systemContext:o,canUseTool:s,fallbackModel:c,querySource:l,maxTurns:u,skipCacheWrite:d}=e,f=e.deps??p5e(),p={messages:e.messages,toolUseContext:e.toolUseContext,maxOutputTokensOverride:e.maxOutputTokensOverride,autoCompactTracking:void 0,stopHookActive:void 0,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,turnCount:1,pendingToolUseSummary:void 0,transition:void 0},m=x5e(),h,g=d5e(),_=r.u(G9e(p.messages,p.toolUseContext));for(;;){let{toolUseContext:r}=p,{messages:v,autoCompactTracking:y,maxOutputTokensRecoveryCount:b,hasAttemptedReactiveCompact:x,maxOutputTokensOverride:S,pendingToolUseSummary:C,stopHookActive:w,turnCount:T}=p,E=xF(null,v,r),D=qF(r.options.tools??[],v);yield{type:`stream_request_start`},M1(`query_fn_entry`),r.agentId||GJ(`query_started`);let O=r.queryTracking?{chainId:r.queryTracking.chainId,depth:r.queryTracking.depth+1}:{chainId:f.uuid(),depth:0},k=O.chainId;r={...r,queryTracking:O};let A=hy(v);A=A.map(e=>{if(e.type!==`user`||!(`toolUseResult`in e)||e.toolUseResult===void 0)return e;let t={...e};return delete t.toolUseResult,t});let ee=y,te=l.startsWith(`agent:`)||l.startsWith(`repl_main_thread`);A=await Jbe(A,r.contentReplacementState,te?e=>void T6(e,r.agentId).catch(J):void 0,new Set(r.options.tools.filter(e=>!Number.isFinite(e.maxResultSizeChars)).map(e=>e.name)));let ne=0;M1(`query_microcompact_start`);let re=await f.microcompact(A,r,l);if(A=re.messages,re.clearedToolUseIds?.length){let e=r?.contentReplacementState?.replacements;if(e)for(let t of re.clearedToolUseIds)e.delete(t)}M1(`query_microcompact_end`);let ie=gv(Iut(i,o));M1(`query_autocompact_start`);let{compactionResult:ae,consecutiveFailures:j}=await f.autocompact(A,r,{systemPrompt:i,userContext:a,systemContext:o,toolUseContext:r,forkContextMessages:A},l,ee,ne);if(M1(`query_autocompact_end`),ae){let{preCompactTokenCount:t,postCompactTokenCount:n,truePostCompactTokenCount:r,compactionUsage:i}=ae;if(Y(`tengu_auto_compact_succeeded`,{originalMessageCount:v.length,compactedMessageCount:ae.summaryMessages.length+ae.attachments.length+ae.hookResults.length,preCompactTokenCount:t,postCompactTokenCount:n,truePostCompactTokenCount:r,compactionInputTokens:i?.input_tokens,compactionOutputTokens:i?.output_tokens,compactionCacheReadTokens:i?.cache_read_input_tokens??0,compactionCacheCreationTokens:i?.cache_creation_input_tokens??0,compactionTotalTokens:i?i.input_tokens+(i.cache_creation_input_tokens??0)+(i.cache_read_input_tokens??0)+i.output_tokens:0,queryChainId:k,queryDepth:O.depth}),e.taskBudget){let t=Ike(A);h=Math.max(0,(h??e.taskBudget.total)-t)}ee={compacted:!0,turnId:f.uuid(),turnCounter:0,consecutiveFailures:0};let a=yB(ae);for(let e of a)yield e;A=a}else j!==void 0&&(ee={...ee??{compacted:!1,turnId:``,turnCounter:0},consecutiveFailures:j});r={...r,messages:A};let oe=[],se=[],ce=[],M=!1;M1(`query_setup_start`);let N=g.gates.streamingToolExecution?new j1(r.options.tools,s,r):null,le=r.getAppState(),ue=le.toolPermissionContext.mode,de=Vo({permissionMode:ue,mainLoopModel:r.options.mainLoopModel,exceeds200kTokens:ue===`plan`&&JL(A)});if(M1(`query_setup_end`),!ae&&l!==`compact`&&l!==`session_memory`){let{isAtBlockingLimit:e}=_J(XL(A)-ne,r.options.mainLoopModel);if(e)return yield $v({content:fL,error:`invalid_request`}),{reason:`blocking_limit`}}if(!ae&&vJ()){let e=r.options.mainLoopModel,t=XL(A)-ne,n=PHe(e);if(t>hJ(e)-n){let e=await f.autocompact(A,r,{systemPrompt:i,userContext:a,systemContext:o,toolUseContext:r,forkContextMessages:A},l,ee,ne);e.compactionResult&&(A=yB(e.compactionResult),ne=0,ee=ee&&{...ee,compacted:!0,consecutiveFailures:e.consecutiveFailures??0})}}let fe=!0;M1(`query_api_loop_start`);try{for(;fe;){fe=!1;try{let t=!1;M1(`query_api_streaming_start`);for await(let n of f.callModel({messages:Lut(A,a),systemPrompt:ie,thinkingConfig:r.options.thinkingConfig,tools:r.options.tools,signal:r.abortController.signal,options:{async getToolPermissionContext(){return r.getAppState().toolPermissionContext},model:de,...g.gates.fastModeEnabled&&{fastMode:le.fastMode},toolChoice:void 0,isNonInteractiveSession:r.options.isNonInteractiveSession,fallbackModel:c,onStreamingFallback:()=>{t=!0},querySource:l,agents:r.options.agentDefinitions.activeAgents,allowedAgentTypes:r.options.agentDefinitions.allowedAgentTypes,hasAppendSystemPrompt:!!r.options.appendSystemPrompt,maxOutputTokensOverride:S,mcpTools:le.mcp.tools,hasPendingMcpServers:le.mcp.clients.some(e=>e.type===`pending`),queryTracking:O,advisorModel:le.advisorModel,skipCacheWrite:d,agentId:r.agentId,addNotification:r.addNotification,...e.taskBudget&&{taskBudget:{total:e.taskBudget.total,...h!==void 0&&{remaining:h}}}}})){if(t){for(let e of oe)yield{type:`tombstone`,message:e};Y(`tengu_orphaned_messages_tombstoned`,{orphanedMessageCount:oe.length,queryChainId:k,queryDepth:O.depth}),oe.length=0,se.length=0,ce.length=0,M=!1,N&&(N.discard(),N=new j1(r.options.tools,s,r))}let e=n;if(n.type===`assistant`){let t=n,i=Array.isArray(t.message?.content)?t.message.content:[],a;for(let e=0;e<i.length;e++){let t=i[e];if(t.type===`tool_use`&&typeof t.input==`object`&&t.input!==null){let n=Ds(r.options.tools,t.name);if(n?.backfillObservableInput){let r=t.input,o={...r};n.backfillObservableInput(o),Object.keys(o).some(e=>!(e in r))&&(a??(a=[...i]),a[e]={...t,input:o})}}}a&&(e={...n,message:{...t.message??{},content:a}})}let i=!1;if(F5e(n)&&(i=!0),i||(yield e),n.type===`assistant`){let e=n;oe.push(e);let t=(Array.isArray(e.message?.content)?e.message.content:[]).filter(e=>e.type===`tool_use`);if(t.length>0&&(ce.push(...t),M=!0),N&&!r.abortController.signal.aborted)for(let n of t)N.addTool(n,e)}if(N&&!r.abortController.signal.aborted)for(let e of N.getCompletedResults())e.message&&(yield e.message,se.push(...c3([e.message],r.options.tools).filter(e=>e.type===`user`)))}M1(`query_api_streaming_end`)}catch(e){if(e instanceof RL&&c){de=c,fe=!0,yield*Z1(oe,`Model fallback triggered`),oe.length=0,se.length=0,ce.length=0,M=!1,N&&(N.discard(),N=new j1(r.options.tools,s,r)),r.options.mainLoopModel=c,Y(`tengu_model_fallback_triggered`,{original_model:e.originalModel,fallback_model:c,entrypoint:`cli`,queryChainId:k,queryDepth:O.depth}),yield ry(`Switched to ${is(e.fallbackModel)} due to high demand for ${is(e.originalModel)}`,`warning`);continue}throw e}}}catch(e){J(e);let t=e instanceof Error?e.message:String(e);return Y(`tengu_query_error`,{assistantMessages:oe.length,toolUses:oe.flatMap(e=>(Array.isArray(e.message?.content)?e.message.content:[]).filter(e=>e.type===`tool_use`)).length,queryChainId:k,queryDepth:O.depth}),e instanceof QI||e instanceof kb?(yield $v({content:e.message}),{reason:`image_error`}):(yield*Z1(oe,t),yield $v({content:t}),pr(`Query error`,e),{reason:`model_error`,error:e})}if(oe.length>0&&!r.options.isNonInteractiveSession){let e=oe.at(-1)?.message?.usage;if(e&&KR()){let t=JR(e,l,GR());t&&(yield YR(t))}}if(oe.length>0&&pWe(A.concat(oe),i,a,o,r,l),r.abortController.signal.aborted){if(N)for await(let e of N.getRemainingResults())e.message&&(yield e.message);else yield*Z1(oe,`Interrupted by user`);return r.abortController.signal.reason!==`interrupt`&&(yield ey({toolUse:!1})),{reason:`aborted_streaming`}}if(C){let e=await C;e&&(yield e)}if(!M){let e=oe.at(-1);if(e?.type===`assistant`&&e.isApiErrorMessage&&nL(e),F5e(e)){if(b<R5e){let e=Q({content:`Output token limit hit. Resume directly — no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces.`,isMeta:!0});p={messages:[...A,...oe,e],toolUseContext:r,autoCompactTracking:ee,maxOutputTokensRecoveryCount:b+1,hasAttemptedReactiveCompact:x,maxOutputTokensOverride:void 0,pendingToolUseSummary:void 0,stopHookActive:void 0,turnCount:T,transition:{reason:`max_output_tokens_recovery`,attempt:b+1}};continue}yield e}if(e?.isApiErrorMessage)return ilt(e,r),{reason:`model_error`,error:e.error??e.apiError??`api_error`};let t=yield*l5e(A,oe,i,a,o,r,l,w);if(t.preventContinuation)return{reason:`stop_hook_prevented`};if(t.blockingErrors.length>0){p={messages:[...A,...oe,...t.blockingErrors],toolUseContext:r,autoCompactTracking:ee,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:x,maxOutputTokensOverride:void 0,pendingToolUseSummary:void 0,stopHookActive:!0,turnCount:T,transition:{reason:`stop_hook_blocking`}};continue}{let e=S5e(m,r.agentId,dte(),Bt());if(e.action===`continue`){Qee(),G(`Token budget continuation #${e.continuationCount}: ${e.pct}% (${e.turnTokens.toLocaleString()} / ${e.budget.toLocaleString()})`),p={messages:[...A,...oe,Q({content:e.nudgeMessage,isMeta:!0})],toolUseContext:r,autoCompactTracking:ee,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,pendingToolUseSummary:void 0,stopHookActive:void 0,turnCount:T,transition:{reason:`token_budget_continuation`}};continue}e.completionEvent&&(e.completionEvent.diminishingReturns&&G(`Token budget early stop: diminishing returns at ${e.completionEvent.pct}%`),Y(`tengu_token_budget_completed`,{...e.completionEvent,queryChainId:k,queryDepth:O.depth}))}return{reason:`completed`}}let pe=!1,me=r;M1(`query_tool_execution_start`),Y(N?`tengu_streaming_tool_execution_used`:`tengu_streaming_tool_execution_not_used`,{tool_count:ce.length,queryChainId:k,queryDepth:O.depth});let he=N?N.getRemainingResults():w8e(ce,oe,s,r);for await(let e of he)e.message&&(yield e.message,e.message.type===`attachment`&&e.message.attachment.type===`hook_stopped_continuation`&&(pe=!0),se.push(...c3([e.message],r.options.tools).filter(e=>e.type===`user`))),e.newContext&&(me={...e.newContext,queryTracking:O});M1(`query_tool_execution_end`);let ge;if(g.gates.emitToolUseSummaries&&ce.length>0&&!r.abortController.signal.aborted&&!r.agentId){let e=oe.at(-1),t;if(e){let n=(Array.isArray(e.message?.content)?e.message.content:[]).filter(e=>e.type===`text`);if(n.length>0){let e=n.at(-1);e&&`text`in e&&(t=e.text)}}let n=ce.map(e=>e.id);ge=VHe({tools:ce.map(e=>{let t=se.find(t=>t.type===`user`&&Array.isArray(t.message.content)&&t.message.content.some(t=>t.type===`tool_result`&&t.tool_use_id===e.id)),n=t?.type===`user`&&Array.isArray(t.message.content)?t.message.content.find(t=>t.type===`tool_result`&&t.tool_use_id===e.id):void 0;return{name:e.name,input:e.input,output:n&&`content`in n?n.content:null}}),signal:r.abortController.signal,isNonInteractiveSession:r.options.isNonInteractiveSession,lastAssistantText:t}).then(e=>e?u_e(e,n):null).catch(()=>null)}if(r.abortController.signal.aborted){r.abortController.signal.reason!==`interrupt`&&(yield ey({toolUse:!0}));let e=T+1;return u&&e>u&&(yield r2({type:`max_turns_reached`,maxTurns:u,turnCount:e})),{reason:`aborted_tools`}}if(pe)return{reason:`hook_stopped`};ee?.compacted&&(ee.turnCounter++,Y(`tengu_post_autocompact_turn`,{turnId:ee.turnId,turnCounter:ee.turnCounter,queryChainId:k,queryDepth:O.depth})),Y(`tengu_query_before_attachments`,{messagesForQueryCount:A.length,assistantMessagesCount:oe.length,toolResultsCount:se.length,queryChainId:k,queryDepth:O.depth});let _e=ce.some(e=>e.name===as),ve=l.startsWith(`repl_main_thread`)||l===`sdk`,ye=r.agentId,be=await tWe(PI(_e?`later`:`next`).filter(e=>FI(e)?!1:ve?e.agentId===void 0:e.mode===`task-notification`&&e.agentId===ye));be.staleCommands.length>0&&DI(be.staleCommands);let xe=be.claimedCommands.filter(e=>e.mode===`prompt`||e.mode===`task-notification`);if(xe.length>0){n.push(...xe);for(let e of xe)e.uuid&&(t.push(e.uuid),WJ(e.uuid,`started`));DI(xe)}for await(let e of cet(null,me,null,be.attachmentCommands,A.concat(oe,se),l))yield e,se.push(e);if(_&&_.settledAt!==null&&_.consumedOnIteration===-1){let e=Y9e(await _.promise,r.readFileState);for(let t of e){let e=r2(t);yield e,se.push(e)}_.consumedOnIteration=T-1}if(gF&&E){let e=await SF(E);for(let t of e){let e=r2(t);yield e,se.push(e)}}if(VF&&D){let e=await JF(D);for(let t of e){let e=r2(t);yield e,se.push(e)}}let Se=new Set(xe),Ce=be.attachmentCommands.filter(e=>(e.mode===`prompt`||e.mode===`task-notification`)&&!Se.has(e));if(Ce.length>0){for(let e of Ce)e.uuid&&(t.push(e.uuid),WJ(e.uuid,`started`));DI(Ce)}let we=Xr(se,e=>e.type===`attachment`&&e.attachment.type===`edited_text_file`);if(Y(`tengu_query_after_attachments`,{totalToolResultsCount:se.length,fileChangeAttachmentCount:we,queryChainId:k,queryDepth:O.depth}),me.options.refreshTools){let e=me.options.refreshTools();e!==me.options.tools&&(me={...me,options:{...me.options,tools:e}})}let Te={...me,queryTracking:O},Ee=T+1;if(!r.agentId&&j5e()&&M5e({systemPrompt:i,userContext:a,systemContext:o,toolUseContext:r,forkContextMessages:A.concat(oe,se)}),u&&Ee>u)return yield r2({type:`max_turns_reached`,maxTurns:u,turnCount:Ee}),{reason:`max_turns`,turnCount:Ee};M1(`query_recursive_call`),p={messages:A.concat(oe,se),toolUseContext:Te,autoCompactTracking:ee,turnCount:Ee,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,pendingToolUseSummary:ge,maxOutputTokensOverride:void 0,stopHookActive:w,transition:{reason:`next_turn`}}}}catch(e){r.e=e}finally{r.d()}}var R5e,$1=n((()=>{HL(),CJ(),RB(),Cne(),oo(),$I(),Ab(),Ks(),cF(),Ga(),xL(),K(),h3(),WHe(),U7(),m2(),AF(),eI(),HI(),oWe(),cWe(),ZJ(),Uo(),ZL(),Bo(),Ws(),mWe(),g7(),p8e(),L1(),k8e(),vS(),h8(),u5e(),f5e(),m5e(),Jt(),w5e(),Ar(),$R(),P5e(),R5e=3}));function z5e(){return{consecutiveDenials:0,totalDenials:0}}function B5e(e){return{...e,consecutiveDenials:e.consecutiveDenials+1,totalDenials:e.totalDenials+1}}function e0(e){return e.consecutiveDenials===0?e:{...e,consecutiveDenials:0}}function V5e(e){return e.consecutiveDenials>=t0.maxConsecutive||e.totalDenials>=t0.maxTotal}var t0,H5e=n((()=>{t0={maxConsecutive:3,maxTotal:20}}));function U5e(e){a0=e}function W5e(){return a0}function n0(e){return{systemPrompt:e.systemPrompt,userContext:e.userContext,systemContext:e.systemContext,toolUseContext:e.toolUseContext,forkContextMessages:e.messages}}function G5e(e,t){return t.length===0?e:()=>{let n=e();return{...n,toolPermissionContext:{...n.toolPermissionContext,alwaysAllowRules:{...n.toolPermissionContext.alwaysAllowRules,command:[...new Set([...n.toolPermissionContext.alwaysAllowRules.command||[],...t])]}}}}}async function K5e(e,t,n){let r=(await e.getPromptForCommand(t,n)).map(e=>e.type===`text`?e.text:``).join(`
|
|
2459
|
+
`)}`)})],cacheSafeParams:n0(t),canUseTool:B1(e),querySource:`auto_dream`,forkLabel:`auto_dream`,maxTurns:20,skipTranscript:!0,overrides:{abortController:f},onMessage:i5e(p,d)});EZe(p,d);let i=t.toolUseContext.getAppState().tasks?.[p];n&&CZe(i)&&i.filesTouched.length>0&&n({...o_e(i.filesTouched),verb:`Improved`}),G(`[autoDream] completed — cache: read=${r.totalUsage.cache_read_input_tokens} created=${r.totalUsage.cache_creation_input_tokens}`),Y(`tengu_auto_dream_completed`,{cache_read:r.totalUsage.cache_read_input_tokens,cache_created:r.totalUsage.cache_creation_input_tokens,output:r.totalUsage.output_tokens,sessions_reviewed:c.length})}catch(e){if(f.signal.aborted){G(`[autoDream] aborted by user`);return}G(`[autoDream] fork failed: ${e.message}`),Y(`tengu_auto_dream_failed`,{}),DZe(p,d),await vZe(u)}}}function i5e(e,t){return n=>{if(n.type!==`assistant`)return;let r=``,i=0,a=[],o=n.message.content;for(let e of o)if(e.type===`text`)r+=e.text;else if(e.type===`tool_use`&&(i++,e.name===`Edit`||e.name===`Write`)){let t=e.input;typeof t.file_path==`string`&&a.push(t.file_path)}TZe(e,{text:r.trim(),toolUseCount:i},a,t)}}async function a5e(e,t){await U1?.(e,t)}var o5e,s5e,U1,c5e=n((()=>{o0(),h3(),K(),oo(),ra(),P8e(),h8(),Jt(),Z8e(),$8e(),LZ(),zZ(),Ls(),bs(),o5e=600*1e3,s5e={minHours:24,minSessions:5},U1=null}));async function*l5e(e,t,n,r,i,a,o,s){let c=Date.now(),l={messages:[...e,...t],systemPrompt:n,userContext:r,systemContext:i,toolUseContext:a,querySource:o};if((o===`repl_main_thread`||o===`sdk`)&&U5e(n0(l)),process.env.CLAUDE_JOB_DIR&&o.startsWith(`repl_main_thread`)&&!a.agentId){let e=l.messages.filter(e=>e.type===`assistant`),t=A8e(process.env.CLAUDE_JOB_DIR,e).catch(e=>{G(`[job] classifier error: ${W(e)}`,{level:`error`})});await Promise.race([t,new Promise(e=>setTimeout(e,6e4).unref())])}let u=(await import(`./poorMode-G-pnu6NM.js`)).isPoorModeActive();v()||(!f(process.env.CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION)&&!u&&o7e(l),!a.agentId&&mie()&&!u&&import(`./extractMemories-D4Dl1itt.js`).then(({executeExtractMemories:e})=>e(l,a.appendSystemMessage)).catch(()=>{}),!a.agentId&&!u&&a5e(l,a.appendSystemMessage));try{let n=[],r=a.getAppState().toolPermissionContext.mode,i=alt(r,a.abortController.signal,void 0,s??!1,a.agentId,a,[...e,...t],a.agentType),o=``,c=0,l=!1,u=``,d=!1,f=[],p=[];for await(let e of i){if(e.message){if(yield e.message,e.message.type===`progress`&&e.message.toolUseID){o=e.message.toolUseID,c++;let t=e.message.data;t.command&&p.push({command:t.command,promptText:t.promptText})}if(e.message.type===`attachment`){let t=e.message.attachment;if(`hookEvent`in t&&(t.hookEvent===`Stop`||t.hookEvent===`SubagentStop`)&&(t.type===`hook_non_blocking_error`?(f.push(t.stderr||`Exit code ${t.exitCode}`),d=!0):t.type===`hook_error_during_execution`?(f.push(t.content),d=!0):t.type===`hook_success`&&(t.stdout&&t.stdout.trim()||t.stderr&&t.stderr.trim())&&(d=!0),`durationMs`in t&&`command`in t)){let e=p.find(e=>e.command===t.command&&e.durationMs===void 0);e&&(e.durationMs=t.durationMs)}}}if(e.blockingError){let t=Q({content:Zct(e.blockingError),isMeta:!0});n.push(t),yield t,d=!0,f.push(e.blockingError.blockingError)}if(e.preventContinuation&&(l=!0,u=e.stopReason||`Stop hook prevented continuation`,yield r2({type:`hook_stopped_continuation`,message:u,hookName:`Stop`,toolUseID:o,hookEvent:`Stop`})),a.abortController.signal.aborted)return Y(`tengu_pre_stop_hooks_cancelled`,{queryChainId:a.queryTracking?.chainId,queryDepth:a.queryTracking?.depth}),yield ey({toolUse:!1}),{blockingErrors:[],preventContinuation:!0}}if(c>0&&(yield i_e(c,p,f,l,u,d,`suggestion`,o),f.length>0)){let e=LS(`app:toggleTranscript`,`Global`,`ctrl+o`);a.addNotification?.({key:`stop-hook-error`,text:`Stop hook error occurred \u00b7 ${e} to see`,priority:`immediate`})}return l?{blockingErrors:[],preventContinuation:!0}:n.length>0?{blockingErrors:n,preventContinuation:!1}:{blockingErrors:[],preventContinuation:!1}}catch(e){return Y(`tengu_stop_hook_error`,{duration:Date.now()-c,queryChainId:a.queryTracking?.chainId,queryDepth:a.queryTracking?.depth}),yield ry(`Stop hook failed: ${W(e)}`,`warning`),{blockingErrors:[],preventContinuation:!1}}}var u5e=n((()=>{zS(),ra(),oo(),m2(),K(),qn(),g7(),h3(),M8e(),c5e(),h0(),g(),o0()}));function d5e(){return{sessionId:jn(),gates:{streamingToolExecution:!1,emitToolUseSummaries:h(process.env.CLAUDE_CODE_EMIT_TOOL_USE_SUMMARIES),fastModeEnabled:!h(process.env.CLAUDE_CODE_DISABLE_FAST_MODE)}}}var f5e=n((()=>{Jt(),g()}));function p5e(){return{callModel:fdt,microcompact:OR,autocompact:IHe,uuid:Jc}}var m5e=n((()=>{n9(),CJ(),MR()}));function W1(e,t){return parseFloat(e)*y5e[t.toLowerCase()]}function h5e(e){let t=e.match(_5e);if(t)return W1(t[1],t[2]);let n=e.match(v5e);if(n)return W1(n[1],n[2]);let r=e.match(G1);return r?W1(r[1],r[2]):null}function g5e(e,t,n){let r=e=>new Intl.NumberFormat(`en-US`).format(e);return`Stopped at ${e}% of token target (${r(t)} / ${r(n)}). Keep working \u2014 do not summarize.`}var _5e,v5e,G1,y5e,b5e=n((()=>{_5e=/^\s*\+(\d+(?:\.\d+)?)\s*(k|m|b)\b/i,v5e=/\s\+(\d+(?:\.\d+)?)\s*(k|m|b)\s*[.!?]?\s*$/i,G1=/\b(?:use|spend)\s+(\d+(?:\.\d+)?)\s*(k|m|b)\s*tokens?\b/i,new RegExp(G1.source,`gi`),y5e={k:1e3,m:1e6,b:1e9}}));function x5e(){return{continuationCount:0,lastDeltaTokens:0,lastGlobalTurnTokens:0,startedAt:Date.now()}}function S5e(e,t,n,r){if(t||n===null||n<=0)return{action:`stop`,completionEvent:null};let i=r,a=Math.round(i/n*100),o=r-e.lastGlobalTurnTokens,s=e.continuationCount>=3&&o<K1&&e.lastDeltaTokens<K1;return!s&&i<n*C5e?(e.continuationCount++,e.lastDeltaTokens=o,e.lastGlobalTurnTokens=r,{action:`continue`,nudgeMessage:g5e(a,i,n),continuationCount:e.continuationCount,pct:a,turnTokens:i,budget:n}):s||e.continuationCount>0?{action:`stop`,completionEvent:{continuationCount:e.continuationCount,pct:a,turnTokens:i,budget:n,diminishingReturns:s,durationMs:Date.now()-e.startedAt}}:{action:`stop`,completionEvent:null}}var C5e,K1,w5e=n((()=>{b5e(),C5e=.9,K1=500}));function q1(){return X(m(),`sessions`)}function T5e(){let e=process.env.CLAUDE_CODE_SESSION_KIND;if(e===`bg`)return e}function E5e(){return T5e()===`bg`}async function D5e(){let e=T5e()??`interactive`,t=q1(),n=X(t,`${process.pid}.json`);ar(async()=>{try{await cl(n)}catch{}});try{return await $c(t,{recursive:!0,mode:448}),await Xc(t,448),await ll(n,U({pid:process.pid,sessionId:jn(),cwd:Yt(),startedAt:Date.now(),kind:e,entrypoint:process.env.CLAUDE_CODE_ENTRYPOINT,name:process.env.CLAUDE_CODE_SESSION_NAME,logPath:process.env.CLAUDE_CODE_SESSION_LOG,agent:process.env.CLAUDE_CODE_AGENT})),gte(e=>{J1({sessionId:e})}),!0}catch(e){return G(`[concurrentSessions] register failed: ${W(e)}`),!1}}async function J1(e){let t=X(q1(),`${process.pid}.json`);try{await ll(t,U({...$n(await tl(t,`utf8`)),...e}))}catch(e){G(`[concurrentSessions] updatePidFile failed: ${W(e)}`)}}async function O5e(e){e&&await J1({name:e})}async function k5e(e){await J1({...e,updatedAt:Date.now()})}async function A5e(){let e=q1(),t;try{t=await nl(e)}catch(e){return hr(e)||G(`[concurrentSessions] readdir failed: ${W(e)}`),0}let n=0;for(let r of t){if(!/^\d+\.json$/.test(r))continue;let t=parseInt(r.slice(0,-5),10);if(t===process.pid){n++;continue}oc(t)?n++:io()!==`wsl`&&cl(X(e,r)).catch(()=>{})}return n}var Y1=n((()=>{Jt(),Hn(),K(),g(),qn(),sc(),ao(),mr()}));function j5e(){return E5e()?Date.now()-X1>=N5e:!1}function M5e(e){X1=Date.now();try{let t=e.forkContextMessages;if(!t||t.length===0)return;let n;for(let e=t.length-1;e>=0;e--)if(t[e].type===`assistant`){n=t[e];break}let r=`busy`,i;if(n?.message?.content){let e=n.message.content;if(Array.isArray(e)){let t=e[e.length-1];t?.type===`tool_use`&&(r=`busy`,i=`tool: ${t.name||`unknown`}`)}}k5e({status:r,waitingFor:i}).catch(e=>{G(`[taskSummary] updateSessionActivity failed: ${e}`)})}catch(e){G(`[taskSummary] error: ${e}`)}}var N5e,X1,P5e=n((()=>{Y1(),K(),N5e=3e4,X1=0}));function*Z1(e,t){for(let n of e){let e=(Array.isArray(n.message?.content)?n.message.content:[]).filter(e=>e.type===`tool_use`);for(let r of e)yield Q({content:[{type:`tool_result`,content:t,is_error:!0,tool_use_id:r.id}],toolUseResult:t,sourceToolAssistantUUID:n.uuid})}}function F5e(e){return e?.type===`assistant`&&e.apiError===`max_output_tokens`}function I5e(e){if(e.thrownError!==void 0)return{type:`failed`,error:e.thrownError};let t=e.terminal,n=t?.reason;switch(n){case`completed`:return{type:`completed`};case void 0:case`aborted_streaming`:case`aborted_tools`:return{type:`cancelled`};case`model_error`:return{type:`failed`,error:t.error};default:return{type:`failed`,message:`query ended without successful completion: ${n}`}}}async function*Q1(e){let t=[],n=[],r,i=!1,a;try{r=yield*L5e(e,t,n)}catch(e){throw i=!0,a=e,e}finally{await aWe({commands:n,outcome:I5e({terminal:r,...i?{thrownError:a}:{}}),priority:`later`}).then(e=>{for(let t of e)SI(t)}).catch(J);let e=globalThis.performance;if(e&&typeof e.clearMarks==`function`)try{e.clearMarks(),e.clearMeasures?.(),e.clearResourceTimings?.()}catch{}}for(let e of t)WJ(e,`completed`);return r}async function*L5e(e,t,n){try{var r=Sne();let{systemPrompt:i,userContext:a,systemContext:o,canUseTool:s,fallbackModel:c,querySource:l,maxTurns:u,skipCacheWrite:d}=e,f=e.deps??p5e(),p={messages:e.messages,toolUseContext:e.toolUseContext,maxOutputTokensOverride:e.maxOutputTokensOverride,autoCompactTracking:void 0,stopHookActive:void 0,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,turnCount:1,pendingToolUseSummary:void 0,transition:void 0},m=x5e(),h,g=d5e(),_=r.u(G9e(p.messages,p.toolUseContext));for(;;){let{toolUseContext:r}=p,{messages:v,autoCompactTracking:y,maxOutputTokensRecoveryCount:b,hasAttemptedReactiveCompact:x,maxOutputTokensOverride:S,pendingToolUseSummary:C,stopHookActive:w,turnCount:T}=p,E=xF(null,v,r),D=qF(r.options.tools??[],v);yield{type:`stream_request_start`},M1(`query_fn_entry`),r.agentId||GJ(`query_started`);let O=r.queryTracking?{chainId:r.queryTracking.chainId,depth:r.queryTracking.depth+1}:{chainId:f.uuid(),depth:0},k=O.chainId;r={...r,queryTracking:O};let A=hy(v);A=A.map(e=>{if(e.type!==`user`||!(`toolUseResult`in e)||e.toolUseResult===void 0)return e;let t={...e};return delete t.toolUseResult,t});let ee=y,te=l.startsWith(`agent:`)||l.startsWith(`repl_main_thread`);A=await Jbe(A,r.contentReplacementState,te?e=>void T6(e,r.agentId).catch(J):void 0,new Set(r.options.tools.filter(e=>!Number.isFinite(e.maxResultSizeChars)).map(e=>e.name)));let ne=0;M1(`query_microcompact_start`);let re=await f.microcompact(A,r,l);if(A=re.messages,re.clearedToolUseIds?.length){let e=r?.contentReplacementState?.replacements;if(e)for(let t of re.clearedToolUseIds)e.delete(t)}M1(`query_microcompact_end`);let ie=gv(Iut(i,o));M1(`query_autocompact_start`);let{compactionResult:ae,consecutiveFailures:j}=await f.autocompact(A,r,{systemPrompt:i,userContext:a,systemContext:o,toolUseContext:r,forkContextMessages:A},l,ee,ne);if(M1(`query_autocompact_end`),ae){let{preCompactTokenCount:t,postCompactTokenCount:n,truePostCompactTokenCount:r,compactionUsage:i}=ae;if(Y(`tengu_auto_compact_succeeded`,{originalMessageCount:v.length,compactedMessageCount:ae.summaryMessages.length+ae.attachments.length+ae.hookResults.length,preCompactTokenCount:t,postCompactTokenCount:n,truePostCompactTokenCount:r,compactionInputTokens:i?.input_tokens,compactionOutputTokens:i?.output_tokens,compactionCacheReadTokens:i?.cache_read_input_tokens??0,compactionCacheCreationTokens:i?.cache_creation_input_tokens??0,compactionTotalTokens:i?i.input_tokens+(i.cache_creation_input_tokens??0)+(i.cache_read_input_tokens??0)+i.output_tokens:0,queryChainId:k,queryDepth:O.depth}),e.taskBudget){let t=Ike(A);h=Math.max(0,(h??e.taskBudget.total)-t)}ee={compacted:!0,turnId:f.uuid(),turnCounter:0,consecutiveFailures:0};let a=yB(ae);for(let e of a)yield e;A=a}else j!==void 0&&(ee={...ee??{compacted:!1,turnId:``,turnCounter:0},consecutiveFailures:j});r={...r,messages:A};let oe=[],se=[],ce=[],M=!1;M1(`query_setup_start`);let N=g.gates.streamingToolExecution?new j1(r.options.tools,s,r):null,le=r.getAppState(),ue=le.toolPermissionContext.mode,de=Vo({permissionMode:ue,mainLoopModel:r.options.mainLoopModel,exceeds200kTokens:ue===`plan`&&JL(A)});if(M1(`query_setup_end`),!ae&&l!==`compact`&&l!==`session_memory`){let{isAtBlockingLimit:e}=_J(XL(A)-ne,r.options.mainLoopModel);if(e)return yield $v({content:fL,error:`invalid_request`}),{reason:`blocking_limit`}}if(!ae&&vJ()){let e=r.options.mainLoopModel,t=XL(A)-ne,n=PHe(e);if(t>hJ(e)-n){let e=await f.autocompact(A,r,{systemPrompt:i,userContext:a,systemContext:o,toolUseContext:r,forkContextMessages:A},l,ee,ne);e.compactionResult&&(A=yB(e.compactionResult),ne=0,ee=ee&&{...ee,compacted:!0,consecutiveFailures:e.consecutiveFailures??0})}}let fe=!0;M1(`query_api_loop_start`);try{for(;fe;){fe=!1;try{let t=!1;M1(`query_api_streaming_start`);for await(let n of f.callModel({messages:Lut(A,a),systemPrompt:ie,thinkingConfig:r.options.thinkingConfig,tools:r.options.tools,signal:r.abortController.signal,options:{async getToolPermissionContext(){return r.getAppState().toolPermissionContext},model:de,...g.gates.fastModeEnabled&&{fastMode:le.fastMode},toolChoice:void 0,isNonInteractiveSession:r.options.isNonInteractiveSession,fallbackModel:c,onStreamingFallback:()=>{t=!0},querySource:l,agents:r.options.agentDefinitions.activeAgents,allowedAgentTypes:r.options.agentDefinitions.allowedAgentTypes,hasAppendSystemPrompt:!!r.options.appendSystemPrompt,maxOutputTokensOverride:S,mcpTools:le.mcp.tools,hasPendingMcpServers:le.mcp.clients.some(e=>e.type===`pending`),queryTracking:O,advisorModel:le.advisorModel,skipCacheWrite:d,agentId:r.agentId,addNotification:r.addNotification,...e.taskBudget&&{taskBudget:{total:e.taskBudget.total,...h!==void 0&&{remaining:h}}}}})){if(t){for(let e of oe)yield{type:`tombstone`,message:e};Y(`tengu_orphaned_messages_tombstoned`,{orphanedMessageCount:oe.length,queryChainId:k,queryDepth:O.depth}),oe.length=0,se.length=0,ce.length=0,M=!1,N&&(N.discard(),N=new j1(r.options.tools,s,r))}let e=n;if(n.type===`assistant`){let t=n,i=Array.isArray(t.message?.content)?t.message.content:[],a;for(let e=0;e<i.length;e++){let t=i[e];if(t.type===`tool_use`&&typeof t.input==`object`&&t.input!==null){let n=Ds(r.options.tools,t.name);if(n?.backfillObservableInput){let r=t.input,o={...r};n.backfillObservableInput(o),Object.keys(o).some(e=>!(e in r))&&(a??(a=[...i]),a[e]={...t,input:o})}}}a&&(e={...n,message:{...t.message??{},content:a}})}let i=!1;if(F5e(n)&&(i=!0),i||(yield e),n.type===`assistant`){let e=n;oe.push(e);let t=(Array.isArray(e.message?.content)?e.message.content:[]).filter(e=>e.type===`tool_use`);if(t.length>0&&(ce.push(...t),M=!0),N&&!r.abortController.signal.aborted)for(let n of t)N.addTool(n,e)}if(N&&!r.abortController.signal.aborted)for(let e of N.getCompletedResults())e.message&&(yield e.message,se.push(...c3([e.message],r.options.tools).filter(e=>e.type===`user`)))}M1(`query_api_streaming_end`)}catch(e){if(e instanceof RL&&c){de=c,fe=!0,yield*Z1(oe,`Model fallback triggered`),oe.length=0,se.length=0,ce.length=0,M=!1,N&&(N.discard(),N=new j1(r.options.tools,s,r)),r.options.mainLoopModel=c,Y(`tengu_model_fallback_triggered`,{original_model:e.originalModel,fallback_model:c,entrypoint:`cli`,queryChainId:k,queryDepth:O.depth}),yield ry(`Switched to ${is(e.fallbackModel)} due to high demand for ${is(e.originalModel)}`,`warning`);continue}throw e}}}catch(e){J(e);let t=e instanceof Error?e.message:String(e);return Y(`tengu_query_error`,{assistantMessages:oe.length,toolUses:oe.flatMap(e=>(Array.isArray(e.message?.content)?e.message.content:[]).filter(e=>e.type===`tool_use`)).length,queryChainId:k,queryDepth:O.depth}),e instanceof QI||e instanceof kb?(yield $v({content:e.message}),{reason:`image_error`}):(yield*Z1(oe,t),yield $v({content:t}),pr(`Query error`,e),{reason:`model_error`,error:e})}if(oe.length>0&&!r.options.isNonInteractiveSession){let e=oe.at(-1)?.message?.usage;if(e&&KR()){let t=JR(e,l,GR());t&&(yield YR(t))}}if(oe.length>0&&pWe(A.concat(oe),i,a,o,r,l),r.abortController.signal.aborted){if(N)for await(let e of N.getRemainingResults())e.message&&(yield e.message);else yield*Z1(oe,`Interrupted by user`);return r.abortController.signal.reason!==`interrupt`&&(yield ey({toolUse:!1})),{reason:`aborted_streaming`}}if(C){let e=await C;e&&(yield e)}if(!M){let e=oe.at(-1);if(e?.type===`assistant`&&e.isApiErrorMessage&&nL(e),F5e(e)){if(b<R5e){let e=Q({content:`Output token limit hit. Resume directly — no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces.`,isMeta:!0});p={messages:[...A,...oe,e],toolUseContext:r,autoCompactTracking:ee,maxOutputTokensRecoveryCount:b+1,hasAttemptedReactiveCompact:x,maxOutputTokensOverride:void 0,pendingToolUseSummary:void 0,stopHookActive:void 0,turnCount:T,transition:{reason:`max_output_tokens_recovery`,attempt:b+1}};continue}yield e}if(e?.isApiErrorMessage)return ilt(e,r),{reason:`model_error`,error:e.error??e.apiError??`api_error`};let t=yield*l5e(A,oe,i,a,o,r,l,w);if(t.preventContinuation)return{reason:`stop_hook_prevented`};if(t.blockingErrors.length>0){p={messages:[...A,...oe,...t.blockingErrors],toolUseContext:r,autoCompactTracking:ee,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:x,maxOutputTokensOverride:void 0,pendingToolUseSummary:void 0,stopHookActive:!0,turnCount:T,transition:{reason:`stop_hook_blocking`}};continue}{let e=S5e(m,r.agentId,dte(),Bt());if(e.action===`continue`){Qee(),G(`Token budget continuation #${e.continuationCount}: ${e.pct}% (${e.turnTokens.toLocaleString()} / ${e.budget.toLocaleString()})`),p={messages:[...A,...oe,Q({content:e.nudgeMessage,isMeta:!0})],toolUseContext:r,autoCompactTracking:ee,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,pendingToolUseSummary:void 0,stopHookActive:void 0,turnCount:T,transition:{reason:`token_budget_continuation`}};continue}e.completionEvent&&(e.completionEvent.diminishingReturns&&G(`Token budget early stop: diminishing returns at ${e.completionEvent.pct}%`),Y(`tengu_token_budget_completed`,{...e.completionEvent,queryChainId:k,queryDepth:O.depth}))}return{reason:`completed`}}let pe=!1,me=r;M1(`query_tool_execution_start`),Y(N?`tengu_streaming_tool_execution_used`:`tengu_streaming_tool_execution_not_used`,{tool_count:ce.length,queryChainId:k,queryDepth:O.depth});let he=N?N.getRemainingResults():w8e(ce,oe,s,r);for await(let e of he)e.message&&(yield e.message,e.message.type===`attachment`&&e.message.attachment.type===`hook_stopped_continuation`&&(pe=!0),se.push(...c3([e.message],r.options.tools).filter(e=>e.type===`user`))),e.newContext&&(me={...e.newContext,queryTracking:O});M1(`query_tool_execution_end`);let ge;if(g.gates.emitToolUseSummaries&&ce.length>0&&!r.abortController.signal.aborted&&!r.agentId){let e=oe.at(-1),t;if(e){let n=(Array.isArray(e.message?.content)?e.message.content:[]).filter(e=>e.type===`text`);if(n.length>0){let e=n.at(-1);e&&`text`in e&&(t=e.text)}}let n=ce.map(e=>e.id);ge=VHe({tools:ce.map(e=>{let t=se.find(t=>t.type===`user`&&Array.isArray(t.message.content)&&t.message.content.some(t=>t.type===`tool_result`&&t.tool_use_id===e.id)),n=t?.type===`user`&&Array.isArray(t.message.content)?t.message.content.find(t=>t.type===`tool_result`&&t.tool_use_id===e.id):void 0;return{name:e.name,input:e.input,output:n&&`content`in n?n.content:null}}),signal:r.abortController.signal,isNonInteractiveSession:r.options.isNonInteractiveSession,lastAssistantText:t}).then(e=>e?u_e(e,n):null).catch(()=>null)}if(r.abortController.signal.aborted){r.abortController.signal.reason!==`interrupt`&&(yield ey({toolUse:!0}));let e=T+1;return u&&e>u&&(yield r2({type:`max_turns_reached`,maxTurns:u,turnCount:e})),{reason:`aborted_tools`}}if(pe)return{reason:`hook_stopped`};ee?.compacted&&(ee.turnCounter++,Y(`tengu_post_autocompact_turn`,{turnId:ee.turnId,turnCounter:ee.turnCounter,queryChainId:k,queryDepth:O.depth})),Y(`tengu_query_before_attachments`,{messagesForQueryCount:A.length,assistantMessagesCount:oe.length,toolResultsCount:se.length,queryChainId:k,queryDepth:O.depth});let _e=ce.some(e=>e.name===as),ve=l.startsWith(`repl_main_thread`)||l===`sdk`,ye=r.agentId,be=await tWe(PI(_e?`later`:`next`).filter(e=>FI(e)?!1:ve?e.agentId===void 0:e.mode===`task-notification`&&e.agentId===ye));be.staleCommands.length>0&&DI(be.staleCommands);let xe=be.claimedCommands.filter(e=>e.mode===`prompt`||e.mode===`task-notification`);if(xe.length>0){n.push(...xe);for(let e of xe)e.uuid&&(t.push(e.uuid),WJ(e.uuid,`started`));DI(xe)}for await(let e of cet(null,me,null,be.attachmentCommands,A.concat(oe,se),l))yield e,se.push(e);if(_&&_.settledAt!==null&&_.consumedOnIteration===-1){let e=Y9e(await _.promise,r.readFileState);for(let t of e){let e=r2(t);yield e,se.push(e)}_.consumedOnIteration=T-1}if(gF&&E){let e=await SF(E);for(let t of e){let e=r2(t);yield e,se.push(e)}}if(VF&&D){let e=await JF(D);for(let t of e){let e=r2(t);yield e,se.push(e)}}let Se=new Set(xe),Ce=be.attachmentCommands.filter(e=>(e.mode===`prompt`||e.mode===`task-notification`)&&!Se.has(e));if(Ce.length>0){for(let e of Ce)e.uuid&&(t.push(e.uuid),WJ(e.uuid,`started`));DI(Ce)}let we=Xr(se,e=>e.type===`attachment`&&e.attachment.type===`edited_text_file`);if(Y(`tengu_query_after_attachments`,{totalToolResultsCount:se.length,fileChangeAttachmentCount:we,queryChainId:k,queryDepth:O.depth}),me.options.refreshTools){let e=me.options.refreshTools();e!==me.options.tools&&(me={...me,options:{...me.options,tools:e}})}let Te={...me,queryTracking:O},Ee=T+1;if(!r.agentId&&j5e()&&M5e({systemPrompt:i,userContext:a,systemContext:o,toolUseContext:r,forkContextMessages:A.concat(oe,se)}),u&&Ee>u)return yield r2({type:`max_turns_reached`,maxTurns:u,turnCount:Ee}),{reason:`max_turns`,turnCount:Ee};M1(`query_recursive_call`),p={messages:A.concat(oe,se),toolUseContext:Te,autoCompactTracking:ee,turnCount:Ee,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,pendingToolUseSummary:ge,maxOutputTokensOverride:void 0,stopHookActive:w,transition:{reason:`next_turn`}}}}catch(e){r.e=e}finally{r.d()}}var R5e,$1=n((()=>{HL(),CJ(),RB(),Cne(),oo(),$I(),Ab(),Ks(),cF(),Ga(),xL(),K(),h3(),WHe(),U7(),m2(),AF(),eI(),HI(),oWe(),cWe(),ZJ(),Uo(),ZL(),Bo(),Ws(),mWe(),g7(),p8e(),L1(),k8e(),vS(),h8(),u5e(),f5e(),m5e(),Jt(),w5e(),Ar(),$R(),P5e(),R5e=3}));function z5e(){return{consecutiveDenials:0,totalDenials:0}}function B5e(e){return{...e,consecutiveDenials:e.consecutiveDenials+1,totalDenials:e.totalDenials+1}}function e0(e){return e.consecutiveDenials===0?e:{...e,consecutiveDenials:0}}function V5e(e){return e.consecutiveDenials>=t0.maxConsecutive||e.totalDenials>=t0.maxTotal}var t0,H5e=n((()=>{t0={maxConsecutive:3,maxTotal:20}}));function U5e(e){a0=e}function W5e(){return a0}function n0(e){return{systemPrompt:e.systemPrompt,userContext:e.userContext,systemContext:e.systemContext,toolUseContext:e.toolUseContext,forkContextMessages:e.messages}}function G5e(e,t){return t.length===0?e:()=>{let n=e();return{...n,toolPermissionContext:{...n.toolPermissionContext,alwaysAllowRules:{...n.toolPermissionContext.alwaysAllowRules,command:[...new Set([...n.toolPermissionContext.alwaysAllowRules.command||[],...t])]}}}}}async function K5e(e,t,n){let r=(await e.getPromptForCommand(t,n)).map(e=>e.type===`text`?e.text:``).join(`
|
|
2460
2460
|
`),i=P9(e.allowedTools??[]),a=G5e(n.getAppState,i),o=e.agent??`general-purpose`,s=n.options.agentDefinitions.activeAgents,c=s.find(e=>e.agentType===o)??s.find(e=>e.agentType===`general-purpose`)??s[0];if(!c)throw Error(`No agent available for forked execution`);return{skillContent:r,modifiedGetAppState:a,baseAgent:c,promptMessages:[Q({content:r})]}}function q5e(e,t=`Execution completed`){let n=oy(e);return n&&fy(Array.isArray(n.message.content)?n.message.content:[],`
|
|
2461
2461
|
`)||t}function r0(e,t){let n=t?.abortController??(t?.shareAbortController?e.abortController:VO(e.abortController)),r=t?.getAppState?t.getAppState:t?.shareAbortController?e.getAppState:()=>{let t=e.getAppState();return t.toolPermissionContext.shouldAvoidPermissionPrompts?t:{...t,toolPermissionContext:{...t.toolPermissionContext,shouldAvoidPermissionPrompts:!0}}};return{readFileState:EN(t?.readFileState??e.readFileState),nestedMemoryAttachmentTriggers:new Set,loadedNestedMemoryPaths:new Set,dynamicSkillDirTriggers:new Set,discoveredSkillNames:new Set,toolDecisions:void 0,contentReplacementState:t?.contentReplacementState??(e.contentReplacementState?Pbe(e.contentReplacementState):void 0),abortController:n,getAppState:r,setAppState:t?.shareSetAppState?e.setAppState:()=>{},setAppStateForTasks:e.setAppStateForTasks??e.setAppState,localDenialTracking:t?.shareSetAppState?e.localDenialTracking:z5e(),setInProgressToolUseIDs:()=>{},setResponseLength:t?.shareSetResponseLength?e.setResponseLength:()=>{},pushApiMetricsEntry:t?.shareSetResponseLength?e.pushApiMetricsEntry:void 0,updateFileHistoryState:()=>{},updateAttributionState:e.updateAttributionState,addNotification:void 0,setToolJSX:void 0,setStreamMode:void 0,setSDKStatus:void 0,openMessageSelector:void 0,options:t?.options??e.options,messages:t?.messages??e.messages,agentId:t?.agentId??oY(),agentType:t?.agentType,queryTracking:{chainId:Jc(),depth:(e.queryTracking?.depth??-1)+1},fileReadingLimits:e.fileReadingLimits,userModified:e.userModified,criticalSystemReminder_EXPERIMENTAL:t?.criticalSystemReminder_EXPERIMENTAL,requireCanUseTool:t?.requireCanUseTool}}function J5e(e){return e.type===`stream_event`&&typeof e.event==`object`&&e.event!==null&&`type`in e.event&&e.event.type===`message_delta`}async function i0({promptMessages:e,cacheSafeParams:t,canUseTool:n,querySource:r,forkLabel:i,overrides:a,maxOutputTokens:o,maxTurns:s,onMessage:c,skipTranscript:l,skipCacheWrite:u}){let d=Date.now(),f=[],p={...hv},{systemPrompt:m,userContext:h,systemContext:g,toolUseContext:_,forkContextMessages:v}=t,y=r0(_,a),b=[...v,...e],x=l?void 0:oY(i),S=null;x&&(await S6(b,x).catch(e=>G(`Forked agent [${i}] failed to record initial transcript: ${e}`)),S=b.length>0?b[b.length-1].uuid:null);try{for await(let e of Q1({messages:b,systemPrompt:m,userContext:h,systemContext:g,canUseTool:n,toolUseContext:y,querySource:r,maxOutputTokensOverride:o,maxTurns:s,skipCacheWrite:u})){if(e.type===`stream_event`){if(J5e(e)){let t=Q7({...hv},e.event.usage);p=bdt(p,t)}continue}if(e.type===`stream_request_start`)continue;G(`Forked agent [${i}] received message: type=${e.type}`),f.push(e),c?.(e);let t=e;x&&(t.type===`assistant`||t.type===`user`||t.type===`progress`)&&(await S6([t],x,S).catch(e=>G(`Forked agent [${i}] failed to record transcript: ${e}`)),t.type!==`progress`&&(S=t.uuid))}}finally{y.readFileState.clear(),b.length=0}return G(`Forked agent [${i}] finished: ${f.length} messages, types=[${f.map(e=>e.type).join(`, `)}], totalUsage: input=${p.input_tokens} output=${p.output_tokens} cacheRead=${p.cache_read_input_tokens} cacheCreate=${p.cache_creation_input_tokens}`),Y5e({forkLabel:i,querySource:r,durationMs:Date.now()-d,messageCount:f.length,totalUsage:p,queryTracking:_.queryTracking}),{messages:f,totalUsage:p}}function Y5e({forkLabel:e,querySource:t,durationMs:n,messageCount:r,totalUsage:i,queryTracking:a}){let o=i.input_tokens+i.cache_creation_input_tokens+i.cache_read_input_tokens,s=o>0?i.cache_read_input_tokens/o:0;Y(`tengu_fork_agent_query`,{forkLabel:e,querySource:t,durationMs:n,messageCount:r,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cacheReadInputTokens:i.cache_read_input_tokens,cacheCreationInputTokens:i.cache_creation_input_tokens,serviceTier:i.service_tier,cacheCreationEphemeral1hTokens:i.cache_creation.ephemeral_1h_input_tokens,cacheCreationEphemeral5mTokens:i.cache_creation.ephemeral_5m_input_tokens,cacheHitRate:s,...a?{queryChainId:a.chainId,queryDepth:a.depth}:{}})}var a0,o0=n((()=>{$1(),oo(),n9(),Nv(),UO(),K(),AN(),h3(),H5e(),z9(),h8(),vS(),sY(),a0=null})),X5e,Z5e=n((()=>{X5e={providerId:`anthropic`,parseHeaders(e){let t=[];for(let[n,r,i]of[[`5h`,`session`,`Session`],[`7d`,`weekly`,`Weekly`]]){let a=e.get(`anthropic-ratelimit-unified-${n}-utilization`),o=e.get(`anthropic-ratelimit-unified-${n}-reset`);if(a===null||o===null)continue;let s=Number(a),c=Number(o);Number.isFinite(s)&&t.push({kind:r,label:i,utilization:s,...Number.isFinite(c)&&c>0?{resetsAt:c}:{}})}return t}}}));function Q5e(){return c0}function $5e(e){s0=e,l0.forEach(t=>t(e));let t=Math.round((e.resetsAt?e.resetsAt-Date.now()/1e3:0)/3600);Y(`tengu_claudeai_limits_status_changed`,{status:e.status,unifiedRateLimitFallbackAvailable:e.unifiedRateLimitFallbackAvailable,hoursTillReset:t})}async function e7e(){}function t7e(e){c0={},Roe(`anthropic`,X5e.parseHeaders(e)),(s0.status!==`allowed`||s0.resetsAt)&&$5e({status:`allowed`,unifiedRateLimitFallbackAvailable:!1,isUsingOverage:!1})}var s0,c0,l0,u0=n((()=>{oo(),Z5e(),zoe(),aX(),s0={status:`allowed`,unifiedRateLimitFallbackAvailable:!1,isUsingOverage:!1},c0={},l0=new Set}));function d0(){return`user_intent`}function n7e(){let e=process.env.CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION;return f(e)?(Y(`tengu_prompt_suggestion_init`,{enabled:!1,source:`env`}),!1):h(e)?(Y(`tengu_prompt_suggestion_init`,{enabled:!0,source:`env`}),!0):(Y(`tengu_prompt_suggestion_init`,{enabled:!1,source:`growthbook`}),!1)}function r7e(){p0&&(p0.abort(),p0=null)}function i7e(e){return e.promptSuggestionEnabled?e.elicitation.queue.length>0?`elicitation_active`:e.toolPermissionContext.mode===`plan`?`plan_mode`:s0.status===`allowed`?null:`rate_limit`:`disabled`}async function a7e(e,t,n,r,i){if(e.signal.aborted)return f0(`aborted`,void 0,void 0,i),null;if(Xr(t,e=>e.type===`assistant`)<2)return f0(`early_conversation`,void 0,void 0,i),null;let a=oy(t);if(a?.isApiErrorMessage)return f0(`last_response_error`,void 0,void 0,i),null;let o=s7e(a);if(o)return f0(o,void 0,void 0,i),null;let s=i7e(n());if(s)return f0(s,void 0,void 0,i),null;let c=d0(),{suggestion:l,generationRequestId:u}=await c7e(e,c,r);return e.signal.aborted?(f0(`aborted`,void 0,void 0,i),null):l?l7e(l,c,i)?null:{suggestion:l,promptId:c,generationRequestId:u}:(f0(`empty`,void 0,c,i),null)}async function o7e(e){if(e.querySource!==`repl_main_thread`)return;p0=new AbortController;let t=p0,n=n0(e);try{let r=await a7e(t,e.messages,e.toolUseContext.getAppState,n,`cli`);if(!r)return;e.toolUseContext.setAppState(e=>({...e,promptSuggestion:{text:r.suggestion,promptId:r.promptId,shownAt:0,acceptedAt:0,generationRequestId:r.generationRequestId}})),M7e()&&r.suggestion&&P7e(r.suggestion,e,e.toolUseContext.setAppState,!1,n)}catch(e){if(e instanceof Error&&(e.name===`AbortError`||e.name===`APIUserAbortError`)){f0(`aborted`,void 0,void 0,`cli`);return}J(tr(e))}finally{p0===t&&(p0=null)}}function s7e(e){if(!e)return null;let t=e.message.usage,n=t.input_tokens??0,r=t.cache_creation_input_tokens??0,i=t.output_tokens??0;return n+r+i>d7e?`cache_cold`:null}async function c7e(e,t,n){let r=f7e[t],i=await i0({promptMessages:[Q({content:r})],cacheSafeParams:n,canUseTool:async()=>({behavior:`deny`,message:`No tools needed for suggestion`,decisionReason:{type:`other`,reason:`suggestion only`}}),querySource:`prompt_suggestion`,forkLabel:`prompt_suggestion`,overrides:{abortController:e},skipTranscript:!0,skipCacheWrite:!0}),a=i.messages.find(e=>e.type===`assistant`),o=a?.type===`assistant`?a.requestId??null:null;for(let e of i.messages){if(e.type!==`assistant`)continue;let t=(Array.isArray(e.message.content)?e.message.content:[]).find(e=>e.type===`text`);if(t?.type===`text`&&typeof t.text==`string`){let e=t.text.trim();if(e)return{suggestion:e,generationRequestId:o}}}return{suggestion:null,generationRequestId:o}}function l7e(e,t,n){if(!e)return f0(`empty`,void 0,t,n),!0;let r=e.toLowerCase(),i=e.trim().split(/\s+/).length,a=[[`done`,()=>r===`done`],[`meta_text`,()=>r===`nothing found`||r===`nothing found.`||r.startsWith(`nothing to suggest`)||r.startsWith(`no suggestion`)||/\bsilence is\b|\bstay(s|ing)? silent\b/.test(r)||/^\W*silence\W*$/.test(r)],[`meta_wrapped`,()=>/^\(.*\)$|^\[.*\]$/.test(e)],[`error_message`,()=>r.startsWith(`api error:`)||r.startsWith(`prompt is too long`)||r.startsWith(`request timed out`)||r.startsWith(`invalid api key`)||r.startsWith(`image was too large`)],[`prefixed_label`,()=>/^\w+:\s/.test(e)],[`too_few_words`,()=>i>=2||e.startsWith(`/`)?!1:!new Set([`yes`,`yeah`,`yep`,`yea`,`yup`,`sure`,`ok`,`okay`,`push`,`commit`,`deploy`,`stop`,`continue`,`check`,`exit`,`quit`,`no`]).has(r)],[`too_many_words`,()=>i>12],[`too_long`,()=>e.length>=100],[`multiple_sentences`,()=>/[.!?]\s+[A-Z]/.test(e)],[`has_formatting`,()=>/[\n*]|\*\*/.test(e)],[`evaluative`,()=>/thanks|thank you|looks good|sounds good|that works|that worked|that's all|nice|great|perfect|makes sense|awesome|excellent/.test(r)],[`claude_voice`,()=>/^(let me|i'll|i've|i'm|i can|i would|i think|i notice|here's|here is|here are|that's|this is|this will|you can|you should|you could|sure,|of course|certainly)/i.test(e)]];for(let[r,i]of a)if(i())return f0(r,e,t,n),!0;return!1}function u7e(e,t,n,r,i){let a=Math.round(t.length/(e.length||1)*100)/100,o=t===e,s=Math.max(0,Date.now()-n);Y(`tengu_prompt_suggestion`,{source:`sdk`,outcome:o?`accepted`:`ignored`,prompt_id:r,...i&&{generationRequestId:i},...o&&{timeToAcceptMs:s},...!o&&{timeToIgnoreMs:s},similarity:a})}function f0(e,t,n,r){let i=n??d0();Y(`tengu_prompt_suggestion`,{...r&&{source:r},outcome:`suppressed`,reason:e,prompt_id:i})}var p0,d7e,m0,f7e,h0=n((()=>{Jt(),Ar(),g(),qn(),o0(),Ga(),h3(),vi(),oo(),u0(),D0(),p0=null,d7e=1e4,m0=`[SUGGESTION MODE: Suggest what the user might naturally type next into Work Mate.]
|
|
2462
2462
|
|
|
@@ -3059,13 +3059,13 @@ Goal: Write your final plan to the plan file (the only file you can edit).
|
|
|
3059
3059
|
- **Hard limit: 40 lines.** If the plan is longer, delete prose — not file paths.`}));function mit(e,t){let n=new Map,r=new Map,i=new Map;for(let e of t)if(e.type===`assistant`){let t=e,a=t.message.id,o=n.get(a);if(o||(o=new Set,n.set(a,o)),Array.isArray(t.message.content)){for(let e of t.message.content)if(typeof e!=`string`&&e.type===`tool_use`){let t=e;o.add(t.id),r.set(t.id,a),i.set(t.id,e)}}}let a=new Map;for(let[e,t]of r)a.set(e,n.get(t));let o=new Map,s=new Map,c=new Map,l=new Map,u=new Set,d=new Set;for(let t of e){if(t.type===`progress`){let e=t.parentToolUseID,n=o.get(e);n?n.push(t):o.set(e,[t]);let r=t.data;if(r.type===`hook_progress`){let t=r.hookEvent,n=s.get(e);n||(n=new Map,s.set(e,n)),n.set(t,(n.get(t)??0)+1)}}if(t.type===`user`&&Array.isArray(t.message?.content)){for(let e of t.message?.content??[])if(typeof e!=`string`&&e.type===`tool_result`){let n=e;l.set(n.tool_use_id,t),u.add(n.tool_use_id),n.is_error&&d.add(n.tool_use_id)}}if(t.type===`assistant`&&Array.isArray(t.message?.content)){for(let e of t.message?.content??[])if(typeof e!=`string`&&(`tool_use_id`in e&&typeof e.tool_use_id==`string`&&u.add(e.tool_use_id),e.type===`advisor_tool_result`)){let t=e;t.content.type===`advisor_tool_result_error`&&d.add(t.tool_use_id)}}if(cy(t)){let e=t.attachment.toolUseID,n=t.attachment.hookEvent,r=t.attachment.hookName;if(r!==void 0){let t=c.get(e);t||(t=new Map,c.set(e,t));let i=t.get(n);i||(i=new Set,t.set(n,i)),i.add(r)}}}let f=new Map;for(let[e,t]of c){let n=new Map;for(let[e,r]of t)n.set(e,r.size);f.set(e,n)}let p=t.at(-1),m=p?.type===`assistant`?p.message?.id:void 0;for(let t of e){if(t.type!==`assistant`)continue;let e=t;if(e.message.id!==m&&Array.isArray(e.message.content)){for(let t of e.message.content)if(typeof t!=`string`&&(t.type===`server_tool_use`||t.type===`mcp_tool_use`)&&!u.has(t.id)){let e=t.id;u.add(e),d.add(e)}}}return{siblingToolUseIDs:a,progressMessagesByToolUseID:o,inProgressHookCounts:s,resolvedHookCounts:f,toolResultByToolUseID:l,toolUseByToolUseID:i,normalizedMessageCount:e.length,resolvedToolUseIDs:u,erroredToolUseIDs:d}}function hit(e,t,n,r,i){if(r.length<t||i.length<n)return null;if(r.length===t&&i.length===n){let t=r[r.length-1];return t&&t.type===`progress`?null:e}let a=n;for(let t=a;t<i.length;t++){let n=i[t];if(n.type===`assistant`){let t=n;if(t.message.id,Array.isArray(t.message.content)){let n=[];for(let r of t.message.content)if(typeof r!=`string`&&r.type===`tool_use`){let t=r;n.push(t.id),e.toolUseByToolUseID.set(t.id,r)}let r=new Set(n);for(let t of n)e.siblingToolUseIDs.set(t,r)}}}let o=t;for(let t=o;t<r.length;t++){let n=r[t];if(n.type===`progress`){let t=n.parentToolUseID,r=e.progressMessagesByToolUseID.get(t);r?r.push(n):e.progressMessagesByToolUseID.set(t,[n]);let i=n.data;if(i.type===`hook_progress`){let n=i.hookEvent,r=e.inProgressHookCounts.get(t);r||(r=new Map,e.inProgressHookCounts.set(t,r)),r.set(n,(r.get(n)??0)+1)}}if(n.type===`user`&&Array.isArray(n.message?.content)){for(let t of n.message?.content??[])if(typeof t!=`string`&&t.type===`tool_result`){let r=t;e.toolResultByToolUseID.set(r.tool_use_id,n),e.resolvedToolUseIDs.add(r.tool_use_id),r.is_error&&e.erroredToolUseIDs.add(r.tool_use_id)}}if(n.type===`assistant`&&Array.isArray(n.message?.content)){for(let t of n.message?.content??[])if(typeof t!=`string`&&(`tool_use_id`in t&&typeof t.tool_use_id==`string`&&e.resolvedToolUseIDs.add(t.tool_use_id),t.type===`advisor_tool_result`)){let n=t;n.content.type===`advisor_tool_result_error`&&e.erroredToolUseIDs.add(n.tool_use_id)}}if(cy(n)){let t=n.attachment.toolUseID,r=n.attachment.hookEvent;if(n.attachment.hookName!==void 0){let n=e.resolvedHookCounts.get(t);n||(n=new Map,e.resolvedHookCounts.set(t,n)),n.set(r,(n.get(r)??0)+1)}}}e.normalizedMessageCount=r.length;let s=i.at(-1),c=s?.type===`assistant`?s.message?.id:void 0;for(let t=o;t<r.length;t++){let n=r[t];if(n.type!==`assistant`)continue;let i=n;if(i.message.id!==c&&Array.isArray(i.message.content)){for(let t of i.message.content)if(typeof t!=`string`&&(t.type===`server_tool_use`||t.type===`mcp_tool_use`)&&!e.resolvedToolUseIDs.has(t.id)){let n=t.id;e.resolvedToolUseIDs.add(n),e.erroredToolUseIDs.add(n)}}}return e}function git(e,t){let n=[String(e.length),`|`,String(t.length)];for(let e of t)if(n.push(e.type[0]),e.type===`assistant`){let t=e.message?.content;if(Array.isArray(t))for(let e of t)typeof e!=`string`&&e.type===`tool_use`&&n.push(`t`,e.id)}else if(e.type===`user`){let t=e.message?.content;if(Array.isArray(t))for(let e of t)typeof e!=`string`&&e.type===`tool_result`&&n.push(`r`,e.tool_use_id)}for(let t of e)if(t.type===`progress`){let e=t;n.push(`p`,e.parentToolUseID,e.uuid)}return n.join(`,`)}function p3(e){let t=new Map,n=new Set,r=new Map;for(let{message:i}of e)if(i.type===`assistant`&&Array.isArray(i.message.content))for(let e of i.message.content)typeof e!=`string`&&e.type===`tool_use`&&t.set(e.id,e);else if(i.type===`user`&&Array.isArray(i.message.content)){for(let e of i.message.content)if(typeof e!=`string`&&e.type===`tool_result`){let t=e;n.add(t.tool_use_id),r.set(t.tool_use_id,i)}}let i=new Set;for(let e of t.keys())n.has(e)||i.add(e);return{lookups:{...m3,toolUseByToolUseID:t,resolvedToolUseIDs:n,toolResultByToolUseID:r},inProgressToolUseIDs:i}}function _it(e,t){let n=ly(e);return n?t.siblingToolUseIDs.get(n)??qv:qv}function vit(e,t){let n=ly(e);return n?t.progressMessagesByToolUseID.get(n)??[]:[]}function yit(e,t,n){return(n.inProgressHookCounts.get(e)?.get(t)??0)>(n.resolvedHookCounts.get(e)?.get(t)??0)}function bit(e){return new Set(e.filter(e=>e.type===`assistant`&&Array.isArray(e.message?.content)&&e.message.content[0]?.type===`tool_use`).map(e=>e.message.content[0].id))}var m3,xit=n((()=>{Yv(),gy(),m3={siblingToolUseIDs:new Map,progressMessagesByToolUseID:new Map,inProgressHookCounts:new Map,resolvedHookCounts:new Map,toolResultByToolUseID:new Map,toolUseByToolUseID:new Map,normalizedMessageCount:0,resolvedToolUseIDs:new Set,erroredToolUseIDs:new Set}}));function Sit(e,t,n,r,i,a,o,s,c){if(e.type!==`stream_event`&&e.type!==`stream_request_start`){if(e.type===`tombstone`){a?.(e.message);return}if(e.type===`tool_use_summary`)return;if(e.type===`assistant`){let t=e,n=(Array.isArray(t.message?.content)?t.message.content:[]).find(e=>typeof e!=`string`&&e.type===`thinking`);if(n&&typeof n!=`string`&&n.type===`thinking`){let e=n;o?.(()=>({thinking:e.thinking,isStreaming:!1,streamingEndedAt:Date.now()}))}}c?.(()=>null),t(e);return}if(e.type===`stream_request_start`){r(`requesting`);return}let l=e;if(l.event.type===`message_start`&&l.ttftMs!=null&&s?.({ttftMs:l.ttftMs}),l.event.type===`message_stop`){r(`tool-use`),i(()=>[]);return}switch(l.event.type){case`content_block_start`:switch(c?.(()=>null),l.event.content_block.type){case`thinking`:case`redacted_thinking`:r(`thinking`);return;case`text`:r(`responding`);return;case`tool_use`:{r(`tool-input`);let e=l.event.content_block,t=l.event.index;i(n=>[...n,{index:t,contentBlock:e,unparsedToolInput:``}]);return}case`server_tool_use`:case`web_search_tool_result`:case`code_execution_tool_result`:case`mcp_tool_use`:case`mcp_tool_result`:case`container_upload`:case`web_fetch_tool_result`:case`bash_code_execution_tool_result`:case`text_editor_code_execution_tool_result`:case`tool_search_tool_result`:case`compaction`:r(`tool-input`);return}return;case`content_block_delta`:switch(l.event.delta.type){case`text_delta`:{let e=l.event.delta.text;n(e),c?.(t=>(t??``)+e);return}case`input_json_delta`:{let e=l.event.delta.partial_json,t=l.event.index;n(e),i(n=>{let r=n.find(e=>e.index===t);return r?[...n.filter(e=>e!==r),{...r,unparsedToolInput:r.unparsedToolInput+e}]:n});return}case`thinking_delta`:n(l.event.delta.thinking);return;case`signature_delta`:return;default:return}case`content_block_stop`:return;case`message_delta`:r(`responding`);return;default:r(`responding`);return}}var Cit=n((()=>{})),h3=n((()=>{Yv(),ay(),gy(),pit(),xit(),Cit(),n3(),a3()}));function g3(){return!1}async function wit(e,t,n){if(!g3())return await n();let r=Kc(`sha1`).update(U(e)).digest(`hex`).slice(0,12),i=X(process.env.CLAUDE_CODE_TEST_FIXTURES_ROOT??H(),`fixtures/${t}-${r}.json`);try{return $n(await tl(i,{encoding:`utf8`}))}catch(e){if(Xn(e)!==`ENOENT`)throw e}if(($r.isCI||process.env.CI)&&!h(process.env.VCR_RECORD))throw Error(`Fixture missing: ${i}. Re-run tests with VCR_RECORD=1, then commit the result.`);let a=await n();return await $c(xc(i),{recursive:!0}),await ll(i,U(a,null,2),{encoding:`utf8`}),a}async function Tit(e,t){if(!g3())return await t();let n=Dit(c3(e.filter(e=>e.type!==`user`||!e.isMeta)).map(e=>e.message.content),v3),r=X(process.env.CLAUDE_CODE_TEST_FIXTURES_ROOT??H(),`fixtures/${n.map(e=>Kc(`sha1`).update(U(e)).digest(`hex`).slice(0,6)).join(`-`)}.json`);try{let e=$n(await tl(r,{encoding:`utf8`}));return e.output.forEach(Eit),e.output.map((e,t)=>kit(e,Ait,t,Jc()))}catch(e){if(Xn(e)!==`ENOENT`)throw e}if($r.isCI&&!h(process.env.VCR_RECORD))throw Error(`API fixture missing: ${r}. Re-run tests with VCR_RECORD=1, then commit the result. Input messages:\n${U(n,null,2)}`);let i=await t();return $r.isCI&&!h(process.env.VCR_RECORD)?i:(await $c(xc(r),{recursive:!0}),await ll(r,U({input:n,output:i.map((e,t)=>kit(e,v3,t))},null,2),{encoding:`utf8`}),i)}function Eit(e){if(e.type===`stream_event`)return;let t=e.message.model,n=e.message.usage;UP(qo(t,n),n,t)}function Dit(e,t){return e.map(e=>typeof e==`string`?t(e):e.map(e=>{switch(e.type){case`tool_result`:return typeof e.content==`string`?{...e,content:t(e.content)}:Array.isArray(e.content)?{...e,content:e.content.map(e=>{switch(e.type){case`text`:return{...e,text:t(e.text)};case`image`:return e;default:return}})}:e;case`text`:return{...e,text:t(e.text)};case`tool_use`:return{...e,input:_3(e.input,t)};case`image`:return e;default:return}}))}function _3(e,t){return _g(e,(n,r)=>Array.isArray(n)?n.map(e=>_3(e,t)):sre(n)?_3(n,t):t(n,r,e))}function Oit(e,t,n,r){return{uuid:r??`UUID-${n}`,requestId:`REQUEST_ID`,timestamp:e.timestamp,message:{...e.message,content:e.message.content.map(e=>{switch(e.type){case`text`:return{...e,text:t(e.text),citations:e.citations||[]};case`tool_use`:return{...e,input:_3(e.input,t)};default:return e}}).filter(Boolean)},type:`assistant`}}function kit(e,t,n,r){return e.type===`assistant`?Oit(e,t,n,r):e}function v3(e){if(typeof e!=`string`)return e;let t=H(),n=m(),r=e.replace(/num_files="\d+"/g,`num_files="[NUM]"`).replace(/duration_ms="\d+"/g,`duration_ms="[DURATION]"`).replace(/cost_usd="\d+"/g,`cost_usd="[COST]"`).replaceAll(n,`[CONFIG_HOME]`).replaceAll(t,`[CWD]`).replace(/Available commands:.+/,`Available commands: [COMMANDS]`);if(process.platform===`win32`){let e=t.replaceAll(`\\`,`/`),i=n.replaceAll(`\\`,`/`),a=U(t).slice(1,-1),o=U(n).slice(1,-1);r=r.replaceAll(a,`[CWD]`).replaceAll(o,`[CONFIG_HOME]`).replaceAll(e,`[CWD]`).replaceAll(i,`[CONFIG_HOME]`)}return r=r.replace(/\[CWD\][^\s"'<>]*/g,e=>e.replaceAll(`\\\\`,`/`).replaceAll(`\\`,`/`)).replace(/\[CONFIG_HOME\][^\s"'<>]*/g,e=>e.replaceAll(`\\\\`,`/`).replaceAll(`\\`,`/`)),r.includes(`Files modified by user:`)?`Files modified by user: [FILES]`:r}function Ait(e){return typeof e==`string`?e.replaceAll(`[NUM]`,`1`).replaceAll(`[DURATION]`,`100`).replaceAll(`[CONFIG_HOME]`,m()).replaceAll(`[CWD]`,H()):e}async function*jit(e,t){if(!g3())return yield*t();let n=[],r=await Tit(e,async()=>{for await(let e of t())n.push(e);return n});if(r.length>0){yield*r;return}yield*n}async function Mit(e,t,n){let r=H().replace(/[^a-zA-Z0-9]/g,`-`);return(await wit(v3(U({messages:e,tools:t})).replaceAll(r,`[CWD_SLUG]`).replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,`[UUID]`).replace(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z?/g,`[TIMESTAMP]`),`token-count`,async()=>({tokenCount:await n()}))).tokenCount}var Nit=n((()=>{lre(),vg(),WP(),wo(),Vn(),Ii(),g(),qn(),h3(),mr()}));function Pit(e){for(let t of e)if(t.role===`assistant`&&Array.isArray(t.content)){for(let e of t.content)if(typeof e==`object`&&e&&`type`in e&&(e.type===`thinking`||e.type===`redacted_thinking`))return!0}return!1}function Fit(e){return e.map(e=>{if(!Array.isArray(e.content))return e;let t=e.content.map(e=>{if(e.type===`tool_use`){let t=e;return{type:`tool_use`,id:t.id,name:t.name,input:t.input}}if(e.type===`tool_result`){let t=e;if(Array.isArray(t.content)){let e=t.content.filter(e=>!vz(e));if(e.length===0)return{...t,content:[{type:`text`,text:`[tool references]`}]};if(e.length!==t.content.length)return{...t,content:e}}}return e});return{...e,content:t}})}async function Iit(e){return e?y3([{role:`user`,content:e}],[]):0}async function y3(e,t){return Mit(e,t,async()=>{try{let n=Fo();if(n===`gemini`)return Vit(e,t);let r=Xo(),i=we(r),a=Pit(e);if(n===`bedrock`)return Uit({model:Wo(r),messages:e,tools:t,betas:i,containsThinking:a});let o=await Ao({maxRetries:1,model:r,source:`count_tokens`}),s=Fo()===`vertex`?i.filter(e=>No.has(e)):i,c=await o.beta.messages.countTokens({model:Wo(r),messages:e.length>0?e:[{role:`user`,content:`foo`}],tools:t,...s.length>0&&{betas:s},...a&&{thinking:{type:`enabled`,budget_tokens:C3}}});return typeof c.input_tokens==`number`?c.input_tokens:null}catch(e){return J(e),null}})}function b3(e,t=4){return Math.round(e.length/t)}function Lit(e){switch(e){case`json`:case`jsonl`:case`jsonc`:return 2;default:return 4}}function Rit(e,t){return b3(e,Lit(t))}async function zit(e,t){if(Fo()===`gemini`)return Vit(e,t);let n=Pit(e),r=h(process.env.CLAUDE_CODE_USE_VERTEX)&&_(Jo())===`global`,i=h(process.env.CLAUDE_CODE_USE_BEDROCK)&&n,a=h(process.env.CLAUDE_CODE_USE_VERTEX)&&n,o=r||i||a?zo():Jo(),s=await Ao({maxRetries:1,model:o,source:`count_tokens`}),c=Fit(e),l=c.length>0?c:[{role:`user`,content:`count`}],u=we(o),d=Fo()===`vertex`?u.filter(e=>No.has(e)):u,f=(await s.beta.messages.create({model:Wo(o),max_tokens:n?w3:1,messages:l,tools:t.length>0?t:void 0,...d.length>0&&{betas:d},metadata:Y7(),...q7(),...n&&{thinking:{type:`enabled`,budget_tokens:C3}}})).usage,p=f.input_tokens,m=f.cache_creation_input_tokens||0,g=f.cache_read_input_tokens||0;return p+m+g}function x3(e){let t=0;for(let n of e)t+=Bit(n);return t}function Bit(e){if((e.type===`assistant`||e.type===`user`)&&e.message?.content)return S3(e.message?.content);if(e.type===`attachment`&&e.attachment){let t=sit(e.attachment),n=0;for(let e of t)n+=S3(e.message.content);return n}return 0}function S3(e){if(!e)return 0;if(typeof e==`string`)return b3(e);let t=0;for(let n of e)t+=Hit(n);return t}function Vit(e,t){let n=0;for(let t of e)n+=S3(t.content);return t.length>0&&(n+=b3(U(t))),n}function Hit(e){return typeof e==`string`?b3(e):e.type===`text`?b3(e.text):e.type===`image`||e.type===`document`?2e3:e.type===`tool_result`?S3(e.content):e.type===`tool_use`?b3(e.name+U(e.input??{})):e.type===`thinking`?b3(e.thinking):e.type===`redacted_thinking`?b3(e.data):b3(U(e))}async function Uit({model:e,messages:t,tools:n,betas:r,containsThinking:i}){try{let a=await Jie(),o=Yie(e)?e:await es(e);if(!o)return null;let s={anthropic_version:`bedrock-2023-05-31`,messages:t.length>0?t:[{role:`user`,content:`foo`}],max_tokens:i?w3:1,...n.length>0&&{tools:n},...r.length>0&&{anthropic_beta:r},...i&&{thinking:{type:`enabled`,budget_tokens:C3}}},{CountTokensCommand:c}=await import(`./dist-es-CzTYn7xo.js`),l={modelId:o,input:{invokeModel:{body:new TextEncoder().encode(U(s))}}};return(await a.send(new c(l))).inputTokens??null}catch(e){return J(e),null}}var C3,w3,T3=n((()=>{Io(),bo(),ve(),g(),Ga(),h3(),Ho(),Uo(),mr(),Dz(),n9(),vo(),Nit(),C3=1024,w3=2048}));function Wit(e){Git=e}var Git,Kit=n((()=>{}));function qit(e,t){switch(e){case`policySettings`:return X(ti(),`.workmate`,t);case`userSettings`:return X(m(),t);case`projectSettings`:return`.workmate/${t}`;case`plugin`:return`plugin`;default:return``}}function Jit(e){return b3([e.name,e.description,e.whenToUse].filter(Boolean).join(` `))}async function Yit(e){try{return await rl(e)}catch{return null}}function Xit(e,t){if(!e.hooks)return;let n=qr().safeParse(e.hooks);if(!n.success){G(`Invalid hooks in skill '${t}': ${n.error.message}`);return}return n.data}function Zit(e){if(!e.paths)return;let t=Lu(e.paths).map(e=>e.endsWith(`/**`)?e.slice(0,-3):e).filter(e=>e.length>0);if(!(t.length===0||t.every(e=>e===`**`)))return t}function E3(e,t,n,r=`Skill`){let i=Bu(e.description,n),a=i??B9(t,r),o=e[`user-invocable`]===void 0||Vu(e[`user-invocable`]),s=e.model===`inherit`?void 0:e.model?Lo(e.model):void 0;return{displayName:e.name==null?void 0:String(e.name),description:a,hasUserSpecifiedDescription:i!==null,allowedTools:H9(e[`allowed-tools`]),argumentHint:e[`argument-hint`]==null?void 0:String(e[`argument-hint`]),argumentNames:Met(e.arguments),whenToUse:e.when_to_use,version:e.version,model:s,disableModelInvocation:Vu(e[`disable-model-invocation`]),userInvocable:o,hooks:Xit(e,n),executionContext:e.context===`fork`?`fork`:void 0,agent:e.agent,shell:Hu(e.shell,n)}}function D3({skillName:e,displayName:t,description:n,hasUserSpecifiedDescription:r,markdownContent:i,allowedTools:a,argumentHint:o,argumentNames:s,whenToUse:c,version:l,model:u,disableModelInvocation:d,userInvocable:f,source:p,baseDir:m,loadedFrom:h,hooks:g,executionContext:_,agent:v,paths:y,shell:b}){return{type:`prompt`,name:e,description:n,hasUserSpecifiedDescription:r,allowedTools:a,argumentHint:o,argNames:s.length>0?s:void 0,whenToUse:c,version:l,model:u,disableModelInvocation:d,userInvocable:f,context:_,agent:v,paths:y,contentLength:i.length,isHidden:!f,progressMessage:`running`,userFacingName(){return t||e},source:p,loadedFrom:h,hooks:g,skillRoot:m,async getPromptForCommand(t,n){let r=m?`Base directory for this skill: ${m}\n\n${i}`:i;if(r=b2(r,t,!0,s),m){let e=process.platform===`win32`?m.replace(/\\/g,`/`):m;r=r.replace(/\$\{CLAUDE_SKILL_DIR\}/g,e)}return r=r.replace(/\$\{CLAUDE_SESSION_ID\}/g,jn()),h!==`mcp`&&(r=await Pet(r,{...n,getAppState(){let e=n.getAppState();return{...e,toolPermissionContext:{...e.toolPermissionContext,alwaysAllowRules:{...e.toolPermissionContext.alwaysAllowRules,command:a}}}}},`/${e}`,b)),[{type:`text`,text:r}]}}}async function O3(e,t){let n=q(),r;try{r=await n.readdir(e)}catch(e){return hr(e)||J(e),[]}return(await Promise.all(r.map(async r=>{try{if(!r.isDirectory()&&!r.isSymbolicLink())return null;let i=X(e,r.name),a=X(i,`SKILL.md`),o;try{o=await n.readFile(a,{encoding:`utf-8`})}catch(e){return Qn(e)||G(`[skills] failed to read ${a}: ${e}`,{level:`warn`}),null}let{frontmatter:s,content:c}=Iu(o,a),l=r.name,u=E3(s,c,l),d=Zit(s);return{skill:D3({...u,skillName:l,markdownContent:c,source:t,baseDir:i,loadedFrom:`skills`,paths:d}),filePath:a}}catch(e){return J(e),null}}))).filter(e=>e!==null)}function k3(e){return/^skill\.md$/i.test(bc(e))}function Qit(e){let t=new Map;for(let n of e){let e=xc(n.filePath),r=t.get(e)??[];r.push(n),t.set(e,r)}let n=[];for(let[e,r]of t){let t=r.filter(e=>k3(e.filePath));if(t.length>0){let r=t[0];t.length>1&&G(`Multiple skill files found in ${e}, using ${bc(r.filePath)}`),n.push(r)}else n.push(...r)}return n}function $it(e,t){let n=t.endsWith(kc)?t.slice(0,-1):t;if(e===n)return``;let r=e.slice(n.length+1);return r?r.split(kc).join(`:`):``}function eat(e,t){let n=xc(e),r=xc(n),i=bc(n),a=$it(r,t);return a?`${a}:${i}`:i}function tat(e,t){let n=bc(e),r=xc(e),i=n.replace(/\.md$/,``),a=$it(r,t);return a?`${a}:${i}`:i}function nat(e){return k3(e.filePath)?eat(e.filePath,e.baseDir):tat(e.filePath,e.baseDir)}async function rat(e){try{let t=Qit(await G9(`commands`,e)),n=[];for(let{baseDir:e,filePath:r,frontmatter:i,content:a,source:o}of t)try{let t=k3(r)?xc(r):void 0,s=nat({baseDir:e,filePath:r,frontmatter:i,content:a,source:o}),c=E3(i,a,s,`Custom command`);n.push({skill:D3({...c,skillName:s,displayName:void 0,markdownContent:a,source:o,baseDir:t,loadedFrom:`commands_DEPRECATED`,paths:void 0}),filePath:r})}catch(e){J(e)}return n}catch(e){return J(e),[]}}function iat(){N3.cache?.clear?.(),G9.cache?.clear?.(),I3.clear(),L3.clear()}function aat(e){return R3.subscribe(()=>{try{e()}catch(e){J(e)}})}async function A3(e,t){let n=q(),r=t.endsWith(kc)?t.slice(0,-1):t,i=[];for(let t of e){let e=xc(t);for(;e.startsWith(r+kc);){let t=X(e,`.workmate`,`skills`);if(!P3.has(t)){P3.add(t);try{if(await n.stat(t),await Kre(e,r)){G(`[skills] Skipped gitignored skills dir: ${t}`);continue}i.push(t)}catch{}}let a=xc(e);if(a===e)break;e=a}}return i.sort((e,t)=>t.split(kc).length-e.split(kc).length)}async function j3(e){if(!Wi(`projectSettings`)||fx(`skills`)){G(`[skills] Dynamic skill discovery skipped: projectSettings disabled or plugin-only policy`);return}if(e.length===0)return;let t=new Set(F3.keys()),n=await Promise.all(e.map(e=>O3(e,`projectSettings`)));for(let e=n.length-1;e>=0;e--)for(let{skill:t}of n[e]??[])t.type===`prompt`&&F3.set(t.name,t);let r=n.flat().length;if(r>0){let n=[...F3.keys()].filter(e=>!t.has(e));G(`[skills] Dynamically discovered ${r} skills from ${e.length} directories`),n.length>0&&Y(`tengu_dynamic_skills_changed`,{source:`file_operation`,previousCount:t.size,newCount:F3.size,addedCount:n.length,directoryCount:e.length})}R3.emit()}function oat(){return Array.from(F3.values())}function M3(e,t){if(I3.size===0)return[];let n=[];for(let[r,i]of I3){if(i.type!==`prompt`||!i.paths||i.paths.length===0)continue;let a=(0,cat.default)().add(i.paths);for(let o of e){let e=Cc(o)?Dc(t,o):o;if(!(!e||e.startsWith(`..`)||Cc(e))&&a.ignores(e)){F3.set(r,i),I3.delete(r),L3.add(r),n.push(r),G(`[skills] Activated conditional skill '${r}' (matched path: ${e})`);break}}}return n.length>0&&(Y(`tengu_dynamic_skills_changed`,{source:`conditional_paths`,previousCount:F3.size-n.length,newCount:F3.size,addedCount:n.length,directoryCount:0}),R3.emit()),n}function sat(){P3.clear(),F3.clear(),I3.clear(),L3.clear()}var cat,N3,P3,F3,I3,L3,R3,z3=n((()=>{cat=r(ce(),1),d(),Jt(),oo(),T3(),x2(),K(),g(),qn(),Ku(),or(),wre(),Ga(),K9(),Uo(),Bet(),wi(),Ur(),mx(),Rr(),Xt(),Kit(),N3=u(async e=>{let t=X(m(),`skills`),n=X(ti(),`.workmate`,`skills`),r=U9(`skills`,e);G(`Loading skills from: managed=${n}, user=${t}, project=[${r.join(`, `)}]`);let i=mn(),a=fx(`skills`),o=Wi(`projectSettings`)&&!a;if(v())return i.length===0||!o?(G(`[bare] Skipping skill dir discovery (${i.length===0?`no --add-dir`:`projectSettings disabled or skillsLocked`})`),[]):(await Promise.all(i.map(e=>O3(X(e,`.workmate`,`skills`),`projectSettings`)))).flat().map(e=>e.skill);let[s,c,l,u,d]=await Promise.all([h(process.env.CLAUDE_CODE_DISABLE_POLICY_SKILLS)?Promise.resolve([]):O3(n,`policySettings`),Wi(`userSettings`)&&!a?O3(t,`userSettings`):Promise.resolve([]),o?Promise.all(r.map(e=>O3(e,`projectSettings`))):Promise.resolve([]),o?Promise.all(i.map(e=>O3(X(e,`.workmate`,`skills`),`projectSettings`))):Promise.resolve([]),a?Promise.resolve([]):rat(e)]),f=[...s,...c,...l.flat(),...u.flat(),...d],p=await Promise.all(f.map(({skill:e,filePath:t})=>e.type===`prompt`?Yit(t):Promise.resolve(null))),g=new Map,_=[];for(let e=0;e<f.length;e++){let t=f[e];if(t===void 0||t.skill.type!==`prompt`)continue;let{skill:n}=t,r=p[e];if(r==null){_.push(n);continue}let i=g.get(r);if(i!==void 0){G(`Skipping duplicate skill '${n.name}' from ${n.source} (same file already loaded from ${i})`);continue}g.set(r,n.source),_.push(n)}let y=f.length-_.length;y>0&&G(`Deduplicated ${y} skills (same file)`);let b=[],x=[];for(let e of _)e.type===`prompt`&&e.paths&&e.paths.length>0&&!L3.has(e.name)?x.push(e):b.push(e);for(let e of x)I3.set(e.name,e);return x.length>0&&G(`[skills] ${x.length} conditional skills stored (activated when matching files are touched)`),G(`Loaded ${_.length} unique skills (${b.length} unconditional, ${x.length} conditional, managed: ${s.length}, user: ${c.length}, project: ${l.flat().length}, additional: ${u.flat().length}, legacy commands: ${d.length})`),b}),P3=new Set,F3=new Map,I3=new Map,L3=new Set,R3=Dn(),Wit({createSkillCommand:D3,parseSkillFrontmatterFields:E3})}));function lat(e){let{files:t}=e,n,r=e.getPromptForCommand;if(t&&Object.keys(t).length>0){n=dat(e.name);let i,a=e.getPromptForCommand;r=async(n,r)=>{i??(i=fat(e.name,t));let o=await i,s=await a(n,r);return o===null?s:gat(s,o)}}let i={type:`prompt`,name:e.name,description:e.description,aliases:e.aliases,hasUserSpecifiedDescription:!0,allowedTools:e.allowedTools??[],argumentHint:e.argumentHint,whenToUse:e.whenToUse,model:e.model,disableModelInvocation:e.disableModelInvocation??!1,userInvocable:e.userInvocable??!0,contentLength:0,source:`bundled`,loadedFrom:`bundled`,hooks:e.hooks,skillRoot:n,context:e.context,agent:e.agent,isEnabled:e.isEnabled,isHidden:!(e.userInvocable??!0),progressMessage:`running`,getPromptForCommand:r};B3.push(i)}function uat(){return[...B3]}function dat(e){return X(L8(),e)}async function fat(e,t){let n=dat(e);try{return await pat(n,t),n}catch(t){return G(`Failed to extract bundled skill '${e}' to ${n}: ${t instanceof Error?t.message:String(t)}`),null}}async function pat(e,t){let n=new Map;for(let[r,i]of Object.entries(t)){let t=hat(e,r),a=xc(t),o=[t,i],s=n.get(a);s?s.push(o):n.set(a,[o])}await Promise.all([...n].map(async([e,t])=>{await $c(e,{recursive:!0,mode:448}),await Promise.all(t.map(([e,t])=>mat(e,t)))}))}async function mat(e,t){let n=await el(e,vat,384);try{await n.writeFile(t,`utf8`)}finally{await n.close()}}function hat(e,t){let n=wc(t);if(Cc(n)||n.split(kc).includes(`..`)||n.split(`/`).includes(`..`))throw Error(`bundled skill file path escapes skill dir: ${t}`);return X(e,n)}function gat(e,t){let n=`Base directory for this skill: ${t}\n\n`;return e.length>0&&e[0].type===`text`?[{type:`text`,text:n+e[0].text},...e.slice(1)]:[{type:`text`,text:n},...e]}var B3,_at,vat,yat=n((()=>{K(),R8(),B3=[],_at=Rc.O_NOFOLLOW??0,vat=process.platform===`win32`?`wx`:Rc.O_WRONLY|Rc.O_CREAT|Rc.O_EXCL|_at}));function bat(e){return Tat.some(t=>t.test(e))}function xat(e){return e.length<=8?`***`:`${e.slice(0,4)}…${e.slice(-2)} (${e.length} chars)`}function Sat(e){return Eat.some(t=>e.startsWith(t))}function Cat(){let e=Object.entries(process.env).filter(([e])=>Sat(e)).map(([e,t])=>[e,bat(e)&&t?xat(t):t??``]).sort(([e],[t])=>e.localeCompare(t));return e.length===0?` (no recognized env vars set)`:e.map(([e,t])=>` ${e}=${t}`).join(`
|
|
3060
3060
|
`)}function wat(){return[` platform: ${process.platform} ${process.arch}`,` cwd: ${process.cwd()}`,` pid: ${process.pid}`,` bun: ${typeof Bun<`u`?Bun.version:`n/a`}`,` node: ${process.version}`,` session: ${jn()}`].join(`
|
|
3061
3061
|
`)}var Tat,Eat,Dat,Oat=n((()=>{Jt(),Tat=[/token/i,/secret/i,/password/i,/api[_-]?key/i,/auth/i,/private/i,/credential/i,/jwt/i,/session[_-]?id$/i],Eat=[`CLAUDE_`,`FEATURE_`,`ANTHROPIC_`,`BUN_`,`NODE_`,`GEMINI_`,`OPENAI_`,`GROK_`,`CCR_`,`BUGHUNTER_`],Dat={type:`local`,name:`env`,description:`显示当前环境、运行时与 feature flag`,isHidden:!1,isEnabled:()=>!0,supportsNonInteractive:!0,load:async()=>({call:async()=>({type:`text`,value:[`## Runtime`,wat(),``,`## Environment Variables (allowlisted prefixes)`,Cat(),``,"_Secrets matching token/password/auth/api_key are masked. Set additional `CLAUDE_*` / `FEATURE_*` env vars to see them here._"].join(`
|
|
3062
|
-
`)})})}})),V3,kat=n((()=>{V3={type:`local-jsx`,name:`exit`,aliases:[`quit`],description:`退出 REPL`,immediate:!0,load:()=>import(`./exit-
|
|
3063
|
-
`).filter(e=>e.startsWith(`worktree `)).map(e=>e.slice(9).normalize(`NFC`));Y(`tengu_worktree_detection`,{duration_ms:i,worktree_count:a.length,success:!0});let o=a.find(t=>e===t||e.startsWith(t+kc)),s=a.filter(e=>e!==o).sort((e,t)=>e.localeCompare(t));return o?[o,...s]:s}var Hat=n((()=>{oo(),va(),Ir()}));function $3(){if(process.stdout.isTTY)try{Bc(1,pee);let e=Qe.get(process.stdout);if(e?.isAltScreenActive)try{e.unmount()}catch{Bc(1,Aee)}e?.drainStdin(),e?.detachForShutdown(),Bc(1,ze),Bc(1,ree),Bc(1,hee),Bc(1,yee),Bc(1,Oee),Bc(1,See),fee()&&Bc(1,wee(Eee)),h(process.env.CLAUDE_CODE_DISABLE_TERMINAL_TITLE)||(process.platform===`win32`?process.title=``:Bc(1,uee))}catch{}}function e6(){if(!r6&&process.stdout.isTTY&&Ut()&&!Zt())try{let e=jn();if(!_6(e))return;let t=z6(e),n;n=t?`"${t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`:e,Bc(1,nt.dim(`\nResume this session with:\nclaude --resume ${n}\n`)),r6=!0}catch{}}function t6(e){a6!==void 0&&(clearTimeout(a6),a6=void 0);try{Qe.get(process.stdout)?.drainStdin()}catch{}try{process.exit(e)}catch{process.kill(process.pid,`SIGKILL`)}throw Error(`unreachable`)}function Uat(e=0,t=`other`,n){process.exitCode=e,Kat=n6(e,t,n).catch(t=>{G(`Graceful shutdown failed: ${t}`,{level:`error`}),$3(),e6(),t6(e)}).catch(()=>{})}function Wat(){return i6}async function n6(e=0,t=`other`,n){if(i6)return;i6=!0;let{executeSessionEndHooks:r,getSessionEndHookTimeoutMs:i}=await import(`./hooks-BNuUlMzL.js`),a=i();a6=setTimeout(e=>{$3(),e6(),t6(e)},Math.max(5e3,a+3500),e),a6.unref(),process.exitCode=e,$3(),e6();let o;try{let e=(async()=>{try{await xne()}catch{}})();await Promise.race([e,new Promise((e,t)=>{o=setTimeout(e=>e(new qat),2e3,t)})]),clearTimeout(o)}catch{clearTimeout(o)}try{await r(t,{...n,signal:AbortSignal.timeout(a),timeoutMs:a})}catch{}try{Die()}catch{}let s=hte();s&&Y(`tengu_cache_eviction_hint`,{scope:`session_end`,last_request_id:s});try{await Promise.race([Promise.all([$oe(),Ese()]),cc(500)])}catch{}if(n?.finalMessage)try{Bc(2,`${n.finalMessage}\n`)}catch{}t6(e)}var r6,Gat,i6,a6,o6,Kat,qat,s6=n((()=>{rt(),d(),re(),Jt(),ct(),Dse(),Qoe(),oo(),Hn(),K(),ni(),g(),h8(),lc(),Oie(),r6=!1,Gat=u(()=>{te(()=>{}),process.on(`SIGINT`,()=>{process.argv.includes(`-p`)||process.argv.includes(`--print`)||(ei(`info`,`shutdown_signal`,{signal:`SIGINT`}),n6(0))}),process.on(`SIGTERM`,()=>{ei(`info`,`shutdown_signal`,{signal:`SIGTERM`}),n6(143)}),process.platform!==`win32`&&(process.on(`SIGHUP`,()=>{ei(`info`,`shutdown_signal`,{signal:`SIGHUP`}),n6(129)}),process.stdin.isTTY&&(o6=setInterval(()=>{tte()||(!process.stdout.writable||!process.stdin.readable)&&(clearInterval(o6),ei(`info`,`shutdown_signal`,{signal:`orphan_detected`}),n6(129))},3e4),o6.unref())),process.on(`uncaughtException`,e=>{ei(`error`,`uncaught_exception`,{error_name:e.name,error_message:e.message.slice(0,2e3)}),Y(`tengu_uncaught_exception`,{error_name:e.name})}),process.on(`unhandledRejection`,e=>{let t=e instanceof Error?e.name:typeof e==`string`?`string`:`unknown`;ei(`error`,`unhandled_rejection`,e instanceof Error?{error_name:e.name,error_message:e.message.slice(0,2e3),error_stack:e.stack?.slice(0,4e3)}:{error_message:String(e).slice(0,2e3)}),Y(`tengu_unhandled_rejection`,{error_name:t})})}),i6=!1,qat=class extends Error{constructor(){super(`Cleanup timeout`)}}})),Jat=i({MAX_TRANSCRIPT_READ_BYTES:()=>o8,adoptResumedSessionFile:()=>lot,buildConversationChain:()=>A6,cacheSessionTitle:()=>Not,checkResumeConsistency:()=>_ot,cleanMessagesForLogging:()=>e8,clearAgentTranscriptSubdir:()=>m6,clearGoalEntry:()=>R6,clearSessionMessagesCache:()=>q6,clearSessionMetadata:()=>Aot,doesMessageExistInSession:()=>Hot,enrichLogs:()=>i8,extractAgentIdsFromMessages:()=>Jot,fetchLogs:()=>F6,findUnresolvedToolUse:()=>$ot,flushSessionStorage:()=>fot,getAgentTranscript:()=>Z6,getAgentTranscriptPath:()=>h6,getCurrentSessionTag:()=>Oot,getCurrentSessionTitle:()=>z6,getFirstMeaningfulUserMessageTextContent:()=>D6,getLastSessionLog:()=>Uot,getLogByIndex:()=>Qot,getNodeEnv:()=>v6,getProjectDir:()=>c8,getProjectsDir:()=>u6,getSessionFilesLite:()=>r8,getSessionFilesWithMtime:()=>t8,getSessionIdFromLog:()=>H6,getSessionMessages:()=>G6,getSessionMessagesCache:()=>K6,getTranscriptPath:()=>d6,getTranscriptPathForSession:()=>f6,getUserType:()=>y6,hydrateFromCCRv2InternalEvents:()=>pot,isChainParticipant:()=>l6,isCustomTitleEnabled:()=>eot,isEphemeralToolProgress:()=>Xat,isLiteLog:()=>U6,isLoggableMessage:()=>$6,isTranscriptMessage:()=>c6,linkSessionToPR:()=>Dot,loadAllLogsFromSessionFile:()=>n8,loadAllProjectsMessageLogs:()=>Wot,loadAllProjectsMessageLogsProgressive:()=>Y6,loadAllSubagentTranscriptsFromDisk:()=>Yot,loadFullLog:()=>Fot,loadMessageLogs:()=>J6,loadSameRepoMessageLogs:()=>Kot,loadSameRepoMessageLogsProgressive:()=>X6,loadSubagentTranscripts:()=>Q6,loadTranscriptFile:()=>W6,loadTranscriptFromFile:()=>vot,reAppendSessionMetadata:()=>B6,readAgentMetadata:()=>Qat,recordAttributionSnapshot:()=>sot,recordContentReplacement:()=>T6,recordContextCollapseCommit:()=>uot,recordContextCollapseSnapshot:()=>dot,recordFileHistorySnapshot:()=>w6,recordQueueOperation:()=>C6,recordSidechainTranscript:()=>S6,recordTranscript:()=>x6,removeExtraFields:()=>O6,removeTranscriptMessage:()=>oot,resetProjectFlushStateForTesting:()=>tot,resetProjectForTesting:()=>not,resetSessionFilePointer:()=>cot,restoreSessionMetadata:()=>kot,saveAgentName:()=>jot,saveAgentSetting:()=>Mot,saveAiGeneratedTitle:()=>wot,saveCustomTitle:()=>Cot,saveGoal:()=>L6,saveMode:()=>Pot,saveTag:()=>Eot,saveTaskSummary:()=>Tot,saveWorktreeState:()=>V6,searchSessionsByCustomTitle:()=>Iot,sessionIdExists:()=>_6,setAgentTranscriptSubdir:()=>p6,setInternalEventReader:()=>aot,setInternalEventWriter:()=>iot,setSessionFileForTesting:()=>rot,writeAgentMetadata:()=>g6});function c6(e){return e.type===`user`||e.type===`assistant`||e.type===`attachment`||e.type===`system`}function l6(e){return e.type!==`progress`}function Yat(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`progress`&&`uuid`in e&&typeof e.uuid==`string`}function Xat(e){return typeof e==`string`&&cst.has(e)}function u6(){return X(m(),`projects`)}function d6(){return X(fn()??c8(Yt()),`${jn()}.jsonl`)}function f6(e){return e===jn()?d6():X(c8(Yt()),`${e}.jsonl`)}function p6(e,t){s8.set(e,t)}function m6(e){s8.delete(e)}function h6(e){let t=fn()??c8(Yt()),n=jn(),r=s8.get(e);return X(r?X(t,n,`subagents`,r):X(t,n,`subagents`),`agent-${e}.jsonl`)}function Zat(e){return h6(e).replace(/\.jsonl$/,`.meta.json`)}async function g6(e,t){let n=Zat(e);await $c(xc(n),{recursive:!0}),await ll(n,JSON.stringify(t))}async function Qat(e){let t=Zat(e);try{let e=await tl(t,`utf-8`);return JSON.parse(e)}catch(e){if(hr(e))return null;throw e}}function _6(e){let t=X(c8(Yt()),`${e}.jsonl`),n=q();try{return n.statSync(t),!0}catch{return!1}}function v6(){return`production`}function y6(){return`external`}function $at(){return process.env.CLAUDE_CODE_ENTRYPOINT}function eot(){return!0}function b6(){return l8||(l8=new ust,u8||(ar(async()=>{await l8?.flush();try{l8?.reAppendSessionMetadata()}catch{}}),u8=!0)),l8}function tot(){l8?._resetFlushState()}function not(){l8=null}function rot(e){b6().sessionFile=e}function iot(e){b6().setInternalEventWriter(e)}function aot(e,t){b6().setInternalEventReader(e),b6().setInternalSubagentEventReader(t)}async function x6(e,t,n,r){let i=e8(e,r),a=await G6(jn()),o=[],s=n,c=!1;for(let e of i)a.has(e.uuid)?!c&&l6(e)&&(s=e.uuid):(o.push(e),c=!0);return o.length>0&&await b6().insertMessageChain(o,!1,void 0,s,t),o.findLast(l6)?.uuid??s??null}async function S6(e,t,n){await b6().insertMessageChain(e8(e),!0,t,n)}async function C6(e){await b6().insertQueueOperation(e)}async function oot(e){await b6().removeMessageByUuid(e)}async function w6(e,t,n){await b6().insertFileHistorySnapshot(e,t,n)}async function sot(e){await b6().insertAttributionSnapshot(e)}async function T6(e,t){await b6().insertContentReplacement(e,t)}async function cot(){b6().resetSessionFile()}function lot(){let e=b6();e.sessionFile=d6(),e.reAppendSessionMetadata(!0)}async function uot(e){let t=jn();t&&await b6().appendEntry({type:`marble-origami-commit`,sessionId:t,...e})}async function dot(e){let t=jn();t&&await b6().appendEntry({type:`marble-origami-snapshot`,sessionId:t,...e})}async function fot(){await b6().flush()}async function pot(e){let t=Date.now();_te(aH(e));let n=b6(),r=n.getInternalEventReader();if(!r)return G(`No internal event reader registered for CCR v2 resume`),!1;try{let i=await r();if(!i)return G(`Failed to read internal events for resume`),ei(`error`,`hydrate_ccr_v2_read_fail`),!1;await $c(c8(Yt()),{recursive:!0,mode:448}),await ll(f6(e),i.map(e=>`${U(e.payload)}\n`).join(``),{encoding:`utf8`,mode:384}),G(`Hydrated ${i.length} foreground entries from CCR v2 internal events`);let a=0,o=n.getInternalSubagentEventReader();if(o){let e=await o();if(e&&e.length>0){a=e.length;let t=new Map;for(let n of e){let e=n.agent_id||``;if(!e)continue;let r=t.get(e);r||(r=[],t.set(e,r)),r.push(n.payload)}for(let[e,n]of t){let t=h6(oH(e));await $c(xc(t),{recursive:!0,mode:448}),await ll(t,n.map(e=>`${U(e)}\n`).join(``),{encoding:`utf8`,mode:384})}G(`Hydrated ${e.length} subagent entries across ${t.size} agents`)}}return ei(`info`,`hydrate_ccr_v2_completed`,{duration_ms:Date.now()-t,event_count:i.length,subagent_event_count:a}),i.length>0}catch(e){if(e instanceof Error&&e.message===`CCRClient: Epoch mismatch (409)`)throw e;return G(`Error hydrating session from CCR v2: ${e}`),ei(`error`,`hydrate_ccr_v2_fail`),!1}}function E6(e){let t=D6(e);if(t){let e=t.replace(/\n/g,` `).trim();return e.length>200&&(e=`${e.slice(0,200).trim()}…`),e}return`No prompt`}function D6(e){for(let t of e){if(t.type!==`user`||t.isMeta||`isCompactSummary`in t&&t.isCompactSummary)continue;let e=t.message?.content;if(!e)continue;let n=[];if(typeof e==`string`)n.push(e);else if(Array.isArray(e))for(let t of e)t.type===`text`&&t.text&&n.push(t.text);for(let e of n){if(!e)continue;let t=sy(e,Fa);if(t){let n=t.replace(/^\//,``);if(J3().has(n))continue;{let n=sy(e,`command-args`)?.trim();if(!n)continue;return`${t} ${n}`}}let n=sy(e,`bash-input`);if(n)return`! ${n}`;if(!a8.test(e))return e}}}function O6(e){return e.map(e=>{let{isSidechain:t,parentUuid:n,...r}=e;return r})}function mot(e){let t,n=-1,r=-1,i=new Map,a=0;for(let o of e.values()){if(i.set(o.uuid,a),my(o)){r=a;let e=o.compactMetadata?.preservedSegment;e&&(t=e,n=a)}a++}if(!t)return;let o=n===r,s=new Set;if(o){let n=new Set,r=e.get(t.tailUuid),i=!1;for(;r&&!n.has(r.uuid);){if(n.add(r.uuid),s.add(r.uuid),r.uuid===t.headUuid){i=!0;break}r=r.parentUuid?e.get(r.parentUuid):void 0}if(!i){Y(`tengu_relink_walk_broken`,{tailInTranscript:e.has(t.tailUuid),headInTranscript:e.has(t.headUuid),anchorInTranscript:e.has(t.anchorUuid),walkSteps:n.size,transcriptSize:e.size});return}}if(o){let n=e.get(t.headUuid);n&&e.set(t.headUuid,{...n,parentUuid:t.anchorUuid});for(let[n,r]of e)r.parentUuid===t.anchorUuid&&n!==t.headUuid&&e.set(n,{...r,parentUuid:t.tailUuid});for(let t of s){let n=e.get(t);n?.type===`assistant`&&e.set(t,{...n,message:{...n.message,usage:{...n.message.usage,input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0}}})}}let c=[];for(let[t]of e){let e=i.get(t);e!==void 0&&e<r&&!s.has(t)&&c.push(t)}for(let t of c)e.delete(t)}function hot(e){let t=new Set;for(let n of e.values()){let e=n.snipMetadata?.removedUuids;if(e)for(let n of e)t.add(n)}if(t.size===0)return;let n=new Map,r=0;for(let i of t){let t=e.get(i);t&&(n.set(i,t.parentUuid),e.delete(i),r++)}let i=e=>{let r=[],i=e;for(;i&&t.has(i);)if(r.push(i),i=n.get(i),i===void 0){i=null;break}for(let e of r)n.set(e,i);return i},a=0;for(let[n,r]of e)!r.parentUuid||!t.has(r.parentUuid)||(e.set(n,{...r,parentUuid:i(r.parentUuid)}),a++);Y(`tengu_snip_resume_filtered`,{removed_count:r,relinked_count:a})}function k6(e,t){let n,r=-1/0;for(let i of e){if(!t(i))continue;let e=Date.parse(i.timestamp);e>r&&(r=e,n=i)}return n}function A6(e,t){let n=[],r=new Set,i=t;for(;i;){if(r.has(i.uuid)){J(Error(`Cycle detected in parentUuid chain at message ${i.uuid}. Returning partial transcript.`)),Y(`tengu_chain_parent_cycle`,{});break}r.add(i.uuid),n.push(i),i=i.parentUuid?e.get(i.parentUuid):void 0}return n.reverse(),got(e,n,r)}function got(e,t,n){let r=t.filter(e=>e.type===`assistant`);if(r.length===0)return t;let i=new Map;for(let e of r)e.message.id&&i.set(e.message.id,e);let a=new Map,o=new Map;for(let t of e.values())if(t.type===`assistant`&&t.message.id){let e=a.get(t.message.id);e?e.push(t):a.set(t.message.id,[t])}else if(t.type===`user`&&t.parentUuid&&Array.isArray(t.message.content)&&t.message.content.some(e=>e.type===`tool_result`)){let e=o.get(t.parentUuid);e?e.push(t):o.set(t.parentUuid,[t])}let s=new Set,c=new Map,l=0;for(let e of r){let t=e.message.id;if(!t||s.has(t))continue;s.add(t);let r=a.get(t)??[e],u=r.filter(e=>!n.has(e.uuid)),d=[];for(let e of r){let t=o.get(e.uuid);if(t)for(let e of t)n.has(e.uuid)||d.push(e)}if(u.length===0&&d.length===0)continue;u.sort((e,t)=>e.timestamp.localeCompare(t.timestamp)),d.sort((e,t)=>e.timestamp.localeCompare(t.timestamp));let f=i.get(t),p=[...u,...d];for(let e of p)n.add(e.uuid);l+=p.length,c.set(f.uuid,p)}if(l===0)return t;Y(`tengu_chain_parallel_tr_recovered`,{recovered_count:l});let u=[];for(let e of t){u.push(e);let t=c.get(e.uuid);t&&u.push(...t)}return u}function _ot(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.type!==`system`||n.subtype!==`turn_duration`)continue;let r=n.messageCount;if(r===void 0)return;let i=t;Y(`tengu_resume_consistency_delta`,{expected:r,actual:i,delta:i-r,chain_length:e.length,checkpoint_age_entries:e.length-1-t});return}}function j6(e,t){let n=[],r=new Map;for(let i of t){let t=e.get(i.uuid);if(!t)continue;let{snapshot:a,isSnapshotUpdate:o}=t,s=o?r.get(a.messageId):void 0;s===void 0?(r.set(a.messageId,n.length),n.push(a)):n[s]=a}return n}function M6(e,t){return Array.from(e.values())}async function vot(e){if(e.endsWith(`.jsonl`)){let{messages:t,summaries:n,customTitles:r,tags:i,fileHistorySnapshots:a,attributionSnapshots:o,contextCollapseCommits:s,contextCollapseSnapshot:c,leafUuids:l,contentReplacements:u,worktreeStates:d}=await W6(e);if(t.size===0)throw Error(`No messages found in JSONL file`);let f=k6(t.values(),e=>l.has(e.uuid));if(!f)throw Error(`No valid conversation chain found in JSONL file`);let p=A6(t,f),m=n.get(f.uuid),h=r.get(f.sessionId),g=i.get(f.sessionId),_=f.sessionId;return{...P6(p,0,m,h,j6(a,p),g,e,M6(o,p),void 0,u.get(_)??[]),contextCollapseCommits:s.filter(e=>e.sessionId===_),contextCollapseSnapshot:c?.sessionId===_?c:void 0,worktreeSession:d.has(_)?d.get(_):void 0}}let t=await tl(e,{encoding:`utf-8`}),n;try{n=$n(t)}catch(e){throw Error(`Invalid JSON in transcript file: ${e}`)}let r;if(Array.isArray(n))r=n;else if(n&&typeof n==`object`&&`messages`in n){if(!Array.isArray(n.messages))throw Error(`Transcript messages must be an array`);r=n.messages}else throw Error(`Transcript must be an array of messages or an object with a messages array`);return P6(r,0,void 0,void 0,void 0,void 0,e)}function yot(e){if(e.type!==`user`||e.isMeta)return!1;let t=e.message?.content;return t?typeof t==`string`?t.trim().length>0:Array.isArray(t)?t.some(e=>e.type===`text`||e.type===`image`||e.type===`document`):!1:!1}function bot(e){if(e.type!==`assistant`)return!1;let t=e.message?.content;return!t||!Array.isArray(t)?!1:t.some(e=>e.type===`text`&&typeof e.text==`string`&&e.text.trim().length>0)}function N6(e){let t=0;for(let n of e)switch(n.type){case`user`:yot(n)&&t++;break;case`assistant`:bot(n)&&t++;break;case`attachment`:case`system`:case`progress`:break}return t}function P6(e,t=0,n,r,i,a,o,s,c,l){let u=e.at(-1),d=e[0],f=E6(e),p=new Date(d.timestamp),m=new Date(u.timestamp);return{date:u.timestamp,messages:O6(e),fullPath:o,value:t,created:p,modified:m,firstPrompt:f,messageCount:N6(e),isSidechain:d.isSidechain,agentName:d.agentName,agentSetting:c,leafUuid:u.uuid,summary:n,customTitle:r,tag:a,fileHistorySnapshots:i,attributionSnapshots:s,contentReplacements:l,gitBranch:u.gitBranch,projectPath:d.cwd}}async function xot(e){let t=new Map,n=0;for(let r of e){let e=H6(r);if(e){let r=(t.get(e)||0)+1;t.set(e,r),n=Math.max(r,n)}}if(n<=1)return;let r=Array.from(t.values()).filter(e=>e>1),i=r.length,a=r.reduce((e,t)=>e+t,0);Y(`tengu_session_forked_branches_fetched`,{total_sessions:t.size,sessions_with_branches:i,max_branches_per_session:Math.max(...r),avg_branches_per_session:Math.round(a/i),total_transcript_count:e.length})}async function F6(e){let t=await r8(c8(Yt()),e,Yt());return await xot(t),t}function I6(e,t){let n=q(),r=`${U(t)}\n`;try{n.appendFileSync(e,r,{mode:384})}catch{n.mkdirSync(xc(e),{mode:448}),n.appendFileSync(e,r,{mode:384})}}function Sot(e){let t;try{t=qse(e,`r`);let n=Gse(t),r=Math.max(0,n.size-si),i=Buffer.allocUnsafe(Math.min(si,n.size-r)),a=Jse(t,i,0,i.length,r);return i.toString(`utf8`,0,a)}catch{return``}finally{if(t!==void 0)try{Vse(t)}catch{}}}async function Cot(e,t,n,r=`user`){I6(n??f6(e),{type:`custom-title`,customTitle:t,sessionId:e}),e===jn()&&(b6().currentSessionTitle=t),Y(`tengu_session_renamed`,{source:r})}function wot(e,t){I6(f6(e),{type:`ai-title`,aiTitle:t,sessionId:e})}function Tot(e,t){I6(f6(e),{type:`task-summary`,summary:t,sessionId:e,timestamp:new Date().toISOString()})}async function Eot(e,t,n){I6(n??f6(e),{type:`tag`,tag:t,sessionId:e}),e===jn()&&(b6().currentSessionTag=t),Y(`tengu_session_tagged`,{})}function L6(e,t,n){I6(n??f6(e),{type:`goal`,sessionId:e,state:t,timestamp:new Date().toISOString()}),e===jn()&&(b6().currentSessionGoal=t)}function R6(e,t){I6(t??f6(e),{type:`goal-cleared`,sessionId:e,timestamp:new Date().toISOString()}),e===jn()&&(b6().currentSessionGoal=void 0)}async function Dot(e,t,n,r,i){if(I6(i??f6(e),{type:`pr-link`,sessionId:e,prNumber:t,prUrl:n,prRepository:r,timestamp:new Date().toISOString()}),e===jn()){let e=b6();e.currentSessionPrNumber=t,e.currentSessionPrUrl=n,e.currentSessionPrRepository=r}Y(`tengu_session_linked_to_pr`,{prNumber:t})}function Oot(e){if(e===jn())return b6().currentSessionTag}function z6(e){if(e===jn())return b6().currentSessionTitle}function kot(e){let t=b6();e.customTitle&&(t.currentSessionTitle??(t.currentSessionTitle=e.customTitle)),e.tag!==void 0&&(t.currentSessionTag=e.tag||void 0),e.agentName&&(t.currentSessionAgentName=e.agentName),e.agentColor&&(t.currentSessionAgentColor=e.agentColor),e.agentSetting&&(t.currentSessionAgentSetting=e.agentSetting),e.mode&&(t.currentSessionMode=e.mode),e.worktreeSession!==void 0&&(t.currentSessionWorktree=e.worktreeSession),e.prNumber!==void 0&&(t.currentSessionPrNumber=e.prNumber),e.prUrl&&(t.currentSessionPrUrl=e.prUrl),e.prRepository&&(t.currentSessionPrRepository=e.prRepository),e.goal&&(t.currentSessionGoal=e.goal)}function Aot(){let e=b6();e.currentSessionTitle=void 0,e.currentSessionTag=void 0,e.currentSessionAgentName=void 0,e.currentSessionAgentColor=void 0,e.currentSessionLastPrompt=void 0,e.currentSessionAgentSetting=void 0,e.currentSessionMode=void 0,e.currentSessionGoal=void 0,e.currentSessionWorktree=void 0,e.currentSessionPrNumber=void 0,e.currentSessionPrUrl=void 0,e.currentSessionPrRepository=void 0}function B6(){b6().reAppendSessionMetadata()}async function jot(e,t,n,r=`user`){I6(n??f6(e),{type:`agent-name`,agentName:t,sessionId:e}),e===jn()&&(b6().currentSessionAgentName=t,O5e(t)),Y(`tengu_agent_name_set`,{source:r})}function Mot(e){b6().currentSessionAgentSetting=e}function Not(e){b6().currentSessionTitle=e}function Pot(e){b6().currentSessionMode=e}function V6(e){let t=e?{originalCwd:e.originalCwd,worktreePath:e.worktreePath,worktreeName:e.worktreeName,worktreeBranch:e.worktreeBranch,originalBranch:e.originalBranch,originalHeadCommit:e.originalHeadCommit,sessionId:e.sessionId,tmuxSessionName:e.tmuxSessionName,hookBased:e.hookBased}:null,n=b6();n.currentSessionWorktree=t,n.sessionFile&&I6(n.sessionFile,{type:`worktree-state`,worktreeSession:t,sessionId:jn()})}function H6(e){return e.sessionId?e.sessionId:e.messages[0]?.sessionId}function U6(e){return e.messages.length===0&&e.sessionId!==void 0}async function Fot(e){if(!U6(e))return e;let t=e.fullPath;if(!t)return e;try{let{messages:n,summaries:r,customTitles:i,tags:a,agentNames:o,agentColors:s,agentSettings:c,prNumbers:l,prUrls:u,prRepositories:d,modes:f,worktreeStates:p,goals:m,fileHistorySnapshots:h,attributionSnapshots:g,contentReplacements:_,contextCollapseCommits:v,contextCollapseSnapshot:y,leafUuids:b}=await W6(t);if(n.size===0){let t=e.sessionId?m.get(e.sessionId):void 0;return t?{...e,goal:t}:e}let x=k6(n.values(),e=>b.has(e.uuid)&&(e.type===`user`||e.type===`assistant`));if(!x){let t=e.sessionId?m.get(e.sessionId):void 0;return t?{...e,goal:t}:e}let S=A6(n,x),C=x.sessionId;return{...e,messages:O6(S),firstPrompt:E6(S),messageCount:N6(S),summary:x?r.get(x.uuid):e.summary,customTitle:C?i.get(C):e.customTitle,tag:C?a.get(C):e.tag,agentName:C?o.get(C):e.agentName,agentColor:C?s.get(C):e.agentColor,agentSetting:C?c.get(C):e.agentSetting,mode:C?f.get(C):e.mode,worktreeSession:C&&p.has(C)?p.get(C):e.worktreeSession,goal:C?m.get(C):e.goal,prNumber:C?l.get(C):e.prNumber,prUrl:C?u.get(C):e.prUrl,prRepository:C?d.get(C):e.prRepository,gitBranch:x?.gitBranch??e.gitBranch,isSidechain:S[0]?.isSidechain??e.isSidechain,leafUuid:x?.uuid??e.leafUuid,fileHistorySnapshots:j6(h,S),attributionSnapshots:M6(g,S),contentReplacements:C?_.get(C)??[]:e.contentReplacements,contextCollapseCommits:C?v.filter(e=>e.sessionId===C):void 0,contextCollapseSnapshot:C&&y?.sessionId===C?y:void 0}}catch{return e}}async function Iot(e,t){let{limit:n,exact:r}=t||{},i=await qot(await Vat(Yt())),{logs:a}=await i8(i,0,i.length),o=e.toLowerCase().trim(),s=a.filter(e=>{let t=e.customTitle?.toLowerCase().trim();return t?r?t===o:t.includes(o):!1}),c=new Map;for(let e of s){let t=H6(e);if(t){let n=c.get(t);(!n||e.modified>n.modified)&&c.set(t,e)}}let l=Array.from(c.values());return l.sort((e,t)=>t.modified.getTime()-e.modified.getTime()),n?l.slice(0,n):l}function Lot(e,t){if(e===null||e.length===0)return t;if(e.length<dst)return Buffer.concat([e,t]);if(e[0]===123){for(let n of f8)if(e.compare(n,0,n.length,1,1+n.length)===0)return Buffer.concat([e,t])}let n=t.indexOf(10);return n===-1?null:t.subarray(n+1)}async function Rot(e,t){let{createReadStream:n}=await import(`fs`),r=n(e,{end:t-1}),i=[],a=null;for await(let e of r){let t=Lot(a,e);if(t===null){a=null;continue}let n=!1;for(let e of f8)if(t.includes(e)){n=!0;break}if(n){let e=0,n=t.indexOf(10);for(;n!==-1;){for(let r of f8){let a=t.indexOf(r,e);if(a!==-1&&a<n){i.push(t.toString(`utf-8`,e,n));break}}e=n+1,n=t.indexOf(10,e)}a=t.subarray(e)}else{let e=t.lastIndexOf(10);a=e>=0?t.subarray(e+1):t}a.length>64*1024&&(a=null)}if(a!==null&&a.length>0){for(let e of f8)if(a.includes(e)){i.push(a.toString(`utf-8`));break}}return i}function zot(e,t,n){let r=0,i=!1,a=!1,o=0;for(let s=t;o<n.length;s++){if(s===n[o]){if(r===1&&!i)return n[o];o++}let t=e[s];a?a=!1:i?t===92?a=!0:t===34&&(i=!1):t===34?i=!0:t===123?r++:t===125&&r--}return n.at(-1)}function Bot(e){let t=Buffer.from(`{"parentUuid":`),n=Buffer.from(`"uuid":"`),r=Buffer.from(`"isSidechain":true`),i=Buffer.from(`","timestamp":"`),a=i.length,o=t.length,s=n.length,c=[],l=[],u=new Map,d=0,f=e.length;for(;d<f;){let r=e.indexOf(10,d),p=r===-1?f:r+1;if(p-d>o&&e[d]===123&&e.compare(t,0,o,d,d+o)===0){let t=e[d+o]===34?d+o+1:-1,r=-1,f=-1,m,h=d;for(;;){let t=e.indexOf(n,h);if(t<0||t>=p)break;r<0&&(r=t);let o=t+s+36;o+a<=p&&e.compare(i,0,a,o,o+a)===0&&(f<0?f=t:(m??(m=[f])).push(t)),h=t+s}let g=m?zot(e,d,m):f>=0?f:r;if(g>=0){let n=g+s,r=e.toString(`latin1`,n,n+36);u.set(r,c.length),c.push(d,p,t)}else l.push(d,p)}else l.push(d,p);d=p}let p=-1;for(let t=c.length-3;t>=0;t-=3){let n=e.indexOf(r,c[t]);if(n===-1||n>=c[t+1]){p=t;break}}if(p<0)return e;let m=new Set,h=new Set,g=0,_=p;for(;_!==void 0&&!m.has(_);){m.add(_),h.add(c[_]),g+=c[_+1]-c[_];let t=c[_+2];if(t<0)break;let n=e.toString(`latin1`,t,t+36);_=u.get(n)}if(f-g<f>>1)return e;let v=[],y=0;for(let t=0;t<c.length;t+=3){let n=c[t];for(;y<l.length&&l[y]<n;)v.push(e.subarray(l[y],l[y+1])),y+=2;h.has(n)&&v.push(e.subarray(n,c[t+1]))}for(;y<l.length;)v.push(e.subarray(l[y],l[y+1])),y+=2;return Buffer.concat(v)}async function W6(e,t){let n=new Map,r=new Map,i=new Map,a=new Map,o=new Map,s=new Map,c=new Map,l=new Map,u=new Map,d=new Map,f=new Map,p=new Map,m=new Map,g=new Map,_=new Map,v=new Map,y=new Map,b=[],x;try{let S=null,C=null,w=!1;if(!h(process.env.CLAUDE_CODE_DISABLE_PRECOMPACT_SKIP)){let{size:t}=await ol(e);if(t>5242880){let n=await kre(e,t);S=n.postBoundaryBuf,w=n.hasPreservedSegment,n.boundaryStartOffset>0&&(C=await Rot(e,n.boundaryStartOffset))}}if(S??(S=await tl(e)),!t?.keepAllLeaves&&!w&&!h(process.env.CLAUDE_CODE_DISABLE_PRECOMPACT_SKIP)&&S.length>5242880&&(S=Bot(S)),C&&C.length>0){let e=Mt(Buffer.from(C.join(`
|
|
3062
|
+
`)})})}})),V3,kat=n((()=>{V3={type:`local-jsx`,name:`exit`,aliases:[`quit`],description:`退出 REPL`,immediate:!0,load:()=>import(`./exit-C_R_FgzR.js`)}})),Aat,jat=n((()=>{qm(),Uo(),Aat={type:`local-jsx`,name:`model`,get description(){return`Set the AI model for Work Mate (currently ${is(Xo())})`},argumentHint:`[model]`,get immediate(){return Km()},load:()=>import(`./model-6lkW4o2c.js`)}})),Mat,Nat=n((()=>{ri(),Mat={type:`prompt`,description:`设置 Work Mate 的状态栏 UI`,contentLength:0,aliases:[],name:`statusline`,progressMessage:`setting up statusLine`,allowedTools:[Fi,`Read(~/**)`,`Edit(~/.workmate/settings.json)`],source:`builtin`,disableNonInteractive:!0,async getPromptForCommand(e){return[{type:`text`,text:`Create an ${Fi} with subagent_type "statusline-setup" and the prompt "${e.trim()||`Configure my statusLine from my shell PS1 configuration`}"`}]}}}));function H3(e){return(e.userFacingName?.()??e.name)||``}function U3(e){return e.isEnabled?.()??!0}var Pat=n((()=>{}));async function Fat(e){try{let[t,n]=await Promise.all([N3(e).catch(e=>(J(tr(e)),G(`Skill directory commands failed to load, continuing without them`),[])),T2().catch(e=>(J(tr(e)),G(`Plugin skills failed to load, continuing without them`),[]))]),r=uat(),i=g_e();return G(`getSkills returning: ${t.length} skill dir commands, ${n.length} plugin skills, ${r.length} bundled skills, ${i.length} builtin plugin skills`),{skillDirCommands:t,pluginSkills:n,bundledSkills:r,builtinPluginSkills:i}}catch(e){return J(tr(e)),G(`Unexpected error in getSkills, returning empty`),{skillDirCommands:[],pluginSkills:[],bundledSkills:[],builtinPluginSkills:[]}}}async function W3(e){let t=await Y3(e),n=oat(),r=t.filter(e=>U3(e));if(n.length===0)return r;let i=new Set(r.map(e=>e.name)),a=n.filter(e=>!i.has(e.name)&&U3(e));if(a.length===0)return r;let o=new Set(q3().map(e=>e.name)),s=r.findIndex(e=>o.has(e.name));return s===-1?[...r,...a]:[...r.slice(0,s),...a,...r.slice(s)]}function Iat(){Y3.cache?.clear?.(),X3.cache?.clear?.(),Z3.cache?.clear?.(),Poe()}function Lat(){Iat(),Get(),qet(),iat()}function Rat(e){return[]}function G3(e,t){return t.find(t=>t.name===e||H3(t)===e||t.aliases?.includes(e))}function K3(e,t){return G3(e,t)!==void 0}function zat(e,t){let n=G3(e,t);if(!n)throw ReferenceError(`Command ${e} not found. Available commands: ${t.map(e=>{let t=H3(e);return e.aliases?`${t} (aliases: ${e.aliases.join(`, `)})`:t}).sort((e,t)=>e.localeCompare(t)).join(`, `)}`);return n}function Bat(e){if(e.type!==`prompt`)return e.description;if(e.kind===`workflow`)return`${e.description} (workflow)`;if(e.source===`plugin`){let t=e.pluginInfo?.pluginManifest.name;return t?`(${t}) ${e.description}`:`${e.description} (plugin)`}return e.source===`builtin`||e.source===`mcp`?e.description:e.source===`bundled`?`${e.description} (bundled)`:`${e.description} (${Qre(e.source)})`}var q3,J3,Y3,X3,Z3,Q3=n((()=>{fde(),pde(),mde(),hde(),gde(),_de(),vde(),yde(),bde(),xde(),Sde(),Nde(),Pde(),ufe(),Doe(),dfe(),ffe(),pfe(),mfe(),hfe(),gfe(),_fe(),vfe(),yfe(),bfe(),xfe(),Cfe(),tc(),wfe(),Tfe(),Efe(),Dfe(),Ofe(),kfe(),Afe(),jfe(),Mfe(),Nfe(),Pfe(),Ffe(),Ife(),phe(),kge(),Lge(),Ga(),qn(),K(),z3(),yat(),xy(),E2(),d(),Oat(),kat(),jat(),Nat(),wi(),Pat(),q3=u(()=>[Bd,Oge,gm,Ige,Zm,Xm,Vd,Hd,Ud,Wd,Gd,Kd,qd,Jd,V3,Jm,Zd,df,cm,lm,Yd,Xd,Aat,Qm,$m,dm,fm,pm,mm,Mat,vm,eh,_m,ym,Um,Vm,Wm,Gm,Ym,fhe,hm,Hm,sh,nh,ff,Dat,Ooe,Eoe,um]),J3=u(()=>new Set(q3().flatMap(e=>[e.name,...e.aliases??[]]))),Y3=u(async e=>{let[{skillDirCommands:t,pluginSkills:n,bundledSkills:r,builtinPluginSkills:i},a]=await Promise.all([Fat(e),w2()]);return[...r,...i,...t,...a,...n,...q3()]}),X3=u(async e=>(await W3(e)).filter(e=>e.type===`prompt`&&!e.disableModelInvocation&&e.source!==`builtin`&&(e.loadedFrom===`bundled`||e.loadedFrom===`skills`||e.loadedFrom===`commands_DEPRECATED`||e.hasUserSpecifiedDescription||e.whenToUse))),Z3=u(async e=>{try{return(await W3(e)).filter(e=>e.type===`prompt`&&e.source!==`builtin`&&(e.hasUserSpecifiedDescription||e.whenToUse)&&(e.loadedFrom===`skills`||e.loadedFrom===`plugin`||e.loadedFrom===`bundled`||e.disableModelInvocation))}catch(e){return J(tr(e)),G(`Returning empty skills array due to load failure`),[]}})}));async function Vat(e){let t=Date.now(),{stdout:n,code:r}=await ya(Pr(),[`worktree`,`list`,`--porcelain`],{cwd:e,preserveOutputOnError:!1}),i=Date.now()-t;if(r!==0)return Y(`tengu_worktree_detection`,{duration_ms:i,worktree_count:0,success:!1}),[];let a=n.split(`
|
|
3063
|
+
`).filter(e=>e.startsWith(`worktree `)).map(e=>e.slice(9).normalize(`NFC`));Y(`tengu_worktree_detection`,{duration_ms:i,worktree_count:a.length,success:!0});let o=a.find(t=>e===t||e.startsWith(t+kc)),s=a.filter(e=>e!==o).sort((e,t)=>e.localeCompare(t));return o?[o,...s]:s}var Hat=n((()=>{oo(),va(),Ir()}));function $3(){if(process.stdout.isTTY)try{Bc(1,pee);let e=Qe.get(process.stdout);if(e?.isAltScreenActive)try{e.unmount()}catch{Bc(1,Aee)}e?.drainStdin(),e?.detachForShutdown(),Bc(1,ze),Bc(1,ree),Bc(1,hee),Bc(1,yee),Bc(1,Oee),Bc(1,See),fee()&&Bc(1,wee(Eee)),h(process.env.CLAUDE_CODE_DISABLE_TERMINAL_TITLE)||(process.platform===`win32`?process.title=``:Bc(1,uee))}catch{}}function e6(){if(!r6&&process.stdout.isTTY&&Ut()&&!Zt())try{let e=jn();if(!_6(e))return;let t=z6(e),n;n=t?`"${t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`:e,Bc(1,nt.dim(`\nResume this session with:\nclaude --resume ${n}\n`)),r6=!0}catch{}}function t6(e){a6!==void 0&&(clearTimeout(a6),a6=void 0);try{Qe.get(process.stdout)?.drainStdin()}catch{}try{process.exit(e)}catch{process.kill(process.pid,`SIGKILL`)}throw Error(`unreachable`)}function Uat(e=0,t=`other`,n){process.exitCode=e,Kat=n6(e,t,n).catch(t=>{G(`Graceful shutdown failed: ${t}`,{level:`error`}),$3(),e6(),t6(e)}).catch(()=>{})}function Wat(){return i6}async function n6(e=0,t=`other`,n){if(i6)return;i6=!0;let{executeSessionEndHooks:r,getSessionEndHookTimeoutMs:i}=await import(`./hooks-D9ApLkBp.js`),a=i();a6=setTimeout(e=>{$3(),e6(),t6(e)},Math.max(5e3,a+3500),e),a6.unref(),process.exitCode=e,$3(),e6();let o;try{let e=(async()=>{try{await xne()}catch{}})();await Promise.race([e,new Promise((e,t)=>{o=setTimeout(e=>e(new qat),2e3,t)})]),clearTimeout(o)}catch{clearTimeout(o)}try{await r(t,{...n,signal:AbortSignal.timeout(a),timeoutMs:a})}catch{}try{Die()}catch{}let s=hte();s&&Y(`tengu_cache_eviction_hint`,{scope:`session_end`,last_request_id:s});try{await Promise.race([Promise.all([$oe(),Ese()]),cc(500)])}catch{}if(n?.finalMessage)try{Bc(2,`${n.finalMessage}\n`)}catch{}t6(e)}var r6,Gat,i6,a6,o6,Kat,qat,s6=n((()=>{rt(),d(),re(),Jt(),ct(),Dse(),Qoe(),oo(),Hn(),K(),ni(),g(),h8(),lc(),Oie(),r6=!1,Gat=u(()=>{te(()=>{}),process.on(`SIGINT`,()=>{process.argv.includes(`-p`)||process.argv.includes(`--print`)||(ei(`info`,`shutdown_signal`,{signal:`SIGINT`}),n6(0))}),process.on(`SIGTERM`,()=>{ei(`info`,`shutdown_signal`,{signal:`SIGTERM`}),n6(143)}),process.platform!==`win32`&&(process.on(`SIGHUP`,()=>{ei(`info`,`shutdown_signal`,{signal:`SIGHUP`}),n6(129)}),process.stdin.isTTY&&(o6=setInterval(()=>{tte()||(!process.stdout.writable||!process.stdin.readable)&&(clearInterval(o6),ei(`info`,`shutdown_signal`,{signal:`orphan_detected`}),n6(129))},3e4),o6.unref())),process.on(`uncaughtException`,e=>{ei(`error`,`uncaught_exception`,{error_name:e.name,error_message:e.message.slice(0,2e3)}),Y(`tengu_uncaught_exception`,{error_name:e.name})}),process.on(`unhandledRejection`,e=>{let t=e instanceof Error?e.name:typeof e==`string`?`string`:`unknown`;ei(`error`,`unhandled_rejection`,e instanceof Error?{error_name:e.name,error_message:e.message.slice(0,2e3),error_stack:e.stack?.slice(0,4e3)}:{error_message:String(e).slice(0,2e3)}),Y(`tengu_unhandled_rejection`,{error_name:t})})}),i6=!1,qat=class extends Error{constructor(){super(`Cleanup timeout`)}}})),Jat=i({MAX_TRANSCRIPT_READ_BYTES:()=>o8,adoptResumedSessionFile:()=>lot,buildConversationChain:()=>A6,cacheSessionTitle:()=>Not,checkResumeConsistency:()=>_ot,cleanMessagesForLogging:()=>e8,clearAgentTranscriptSubdir:()=>m6,clearGoalEntry:()=>R6,clearSessionMessagesCache:()=>q6,clearSessionMetadata:()=>Aot,doesMessageExistInSession:()=>Hot,enrichLogs:()=>i8,extractAgentIdsFromMessages:()=>Jot,fetchLogs:()=>F6,findUnresolvedToolUse:()=>$ot,flushSessionStorage:()=>fot,getAgentTranscript:()=>Z6,getAgentTranscriptPath:()=>h6,getCurrentSessionTag:()=>Oot,getCurrentSessionTitle:()=>z6,getFirstMeaningfulUserMessageTextContent:()=>D6,getLastSessionLog:()=>Uot,getLogByIndex:()=>Qot,getNodeEnv:()=>v6,getProjectDir:()=>c8,getProjectsDir:()=>u6,getSessionFilesLite:()=>r8,getSessionFilesWithMtime:()=>t8,getSessionIdFromLog:()=>H6,getSessionMessages:()=>G6,getSessionMessagesCache:()=>K6,getTranscriptPath:()=>d6,getTranscriptPathForSession:()=>f6,getUserType:()=>y6,hydrateFromCCRv2InternalEvents:()=>pot,isChainParticipant:()=>l6,isCustomTitleEnabled:()=>eot,isEphemeralToolProgress:()=>Xat,isLiteLog:()=>U6,isLoggableMessage:()=>$6,isTranscriptMessage:()=>c6,linkSessionToPR:()=>Dot,loadAllLogsFromSessionFile:()=>n8,loadAllProjectsMessageLogs:()=>Wot,loadAllProjectsMessageLogsProgressive:()=>Y6,loadAllSubagentTranscriptsFromDisk:()=>Yot,loadFullLog:()=>Fot,loadMessageLogs:()=>J6,loadSameRepoMessageLogs:()=>Kot,loadSameRepoMessageLogsProgressive:()=>X6,loadSubagentTranscripts:()=>Q6,loadTranscriptFile:()=>W6,loadTranscriptFromFile:()=>vot,reAppendSessionMetadata:()=>B6,readAgentMetadata:()=>Qat,recordAttributionSnapshot:()=>sot,recordContentReplacement:()=>T6,recordContextCollapseCommit:()=>uot,recordContextCollapseSnapshot:()=>dot,recordFileHistorySnapshot:()=>w6,recordQueueOperation:()=>C6,recordSidechainTranscript:()=>S6,recordTranscript:()=>x6,removeExtraFields:()=>O6,removeTranscriptMessage:()=>oot,resetProjectFlushStateForTesting:()=>tot,resetProjectForTesting:()=>not,resetSessionFilePointer:()=>cot,restoreSessionMetadata:()=>kot,saveAgentName:()=>jot,saveAgentSetting:()=>Mot,saveAiGeneratedTitle:()=>wot,saveCustomTitle:()=>Cot,saveGoal:()=>L6,saveMode:()=>Pot,saveTag:()=>Eot,saveTaskSummary:()=>Tot,saveWorktreeState:()=>V6,searchSessionsByCustomTitle:()=>Iot,sessionIdExists:()=>_6,setAgentTranscriptSubdir:()=>p6,setInternalEventReader:()=>aot,setInternalEventWriter:()=>iot,setSessionFileForTesting:()=>rot,writeAgentMetadata:()=>g6});function c6(e){return e.type===`user`||e.type===`assistant`||e.type===`attachment`||e.type===`system`}function l6(e){return e.type!==`progress`}function Yat(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`progress`&&`uuid`in e&&typeof e.uuid==`string`}function Xat(e){return typeof e==`string`&&cst.has(e)}function u6(){return X(m(),`projects`)}function d6(){return X(fn()??c8(Yt()),`${jn()}.jsonl`)}function f6(e){return e===jn()?d6():X(c8(Yt()),`${e}.jsonl`)}function p6(e,t){s8.set(e,t)}function m6(e){s8.delete(e)}function h6(e){let t=fn()??c8(Yt()),n=jn(),r=s8.get(e);return X(r?X(t,n,`subagents`,r):X(t,n,`subagents`),`agent-${e}.jsonl`)}function Zat(e){return h6(e).replace(/\.jsonl$/,`.meta.json`)}async function g6(e,t){let n=Zat(e);await $c(xc(n),{recursive:!0}),await ll(n,JSON.stringify(t))}async function Qat(e){let t=Zat(e);try{let e=await tl(t,`utf-8`);return JSON.parse(e)}catch(e){if(hr(e))return null;throw e}}function _6(e){let t=X(c8(Yt()),`${e}.jsonl`),n=q();try{return n.statSync(t),!0}catch{return!1}}function v6(){return`production`}function y6(){return`external`}function $at(){return process.env.CLAUDE_CODE_ENTRYPOINT}function eot(){return!0}function b6(){return l8||(l8=new ust,u8||(ar(async()=>{await l8?.flush();try{l8?.reAppendSessionMetadata()}catch{}}),u8=!0)),l8}function tot(){l8?._resetFlushState()}function not(){l8=null}function rot(e){b6().sessionFile=e}function iot(e){b6().setInternalEventWriter(e)}function aot(e,t){b6().setInternalEventReader(e),b6().setInternalSubagentEventReader(t)}async function x6(e,t,n,r){let i=e8(e,r),a=await G6(jn()),o=[],s=n,c=!1;for(let e of i)a.has(e.uuid)?!c&&l6(e)&&(s=e.uuid):(o.push(e),c=!0);return o.length>0&&await b6().insertMessageChain(o,!1,void 0,s,t),o.findLast(l6)?.uuid??s??null}async function S6(e,t,n){await b6().insertMessageChain(e8(e),!0,t,n)}async function C6(e){await b6().insertQueueOperation(e)}async function oot(e){await b6().removeMessageByUuid(e)}async function w6(e,t,n){await b6().insertFileHistorySnapshot(e,t,n)}async function sot(e){await b6().insertAttributionSnapshot(e)}async function T6(e,t){await b6().insertContentReplacement(e,t)}async function cot(){b6().resetSessionFile()}function lot(){let e=b6();e.sessionFile=d6(),e.reAppendSessionMetadata(!0)}async function uot(e){let t=jn();t&&await b6().appendEntry({type:`marble-origami-commit`,sessionId:t,...e})}async function dot(e){let t=jn();t&&await b6().appendEntry({type:`marble-origami-snapshot`,sessionId:t,...e})}async function fot(){await b6().flush()}async function pot(e){let t=Date.now();_te(aH(e));let n=b6(),r=n.getInternalEventReader();if(!r)return G(`No internal event reader registered for CCR v2 resume`),!1;try{let i=await r();if(!i)return G(`Failed to read internal events for resume`),ei(`error`,`hydrate_ccr_v2_read_fail`),!1;await $c(c8(Yt()),{recursive:!0,mode:448}),await ll(f6(e),i.map(e=>`${U(e.payload)}\n`).join(``),{encoding:`utf8`,mode:384}),G(`Hydrated ${i.length} foreground entries from CCR v2 internal events`);let a=0,o=n.getInternalSubagentEventReader();if(o){let e=await o();if(e&&e.length>0){a=e.length;let t=new Map;for(let n of e){let e=n.agent_id||``;if(!e)continue;let r=t.get(e);r||(r=[],t.set(e,r)),r.push(n.payload)}for(let[e,n]of t){let t=h6(oH(e));await $c(xc(t),{recursive:!0,mode:448}),await ll(t,n.map(e=>`${U(e)}\n`).join(``),{encoding:`utf8`,mode:384})}G(`Hydrated ${e.length} subagent entries across ${t.size} agents`)}}return ei(`info`,`hydrate_ccr_v2_completed`,{duration_ms:Date.now()-t,event_count:i.length,subagent_event_count:a}),i.length>0}catch(e){if(e instanceof Error&&e.message===`CCRClient: Epoch mismatch (409)`)throw e;return G(`Error hydrating session from CCR v2: ${e}`),ei(`error`,`hydrate_ccr_v2_fail`),!1}}function E6(e){let t=D6(e);if(t){let e=t.replace(/\n/g,` `).trim();return e.length>200&&(e=`${e.slice(0,200).trim()}…`),e}return`No prompt`}function D6(e){for(let t of e){if(t.type!==`user`||t.isMeta||`isCompactSummary`in t&&t.isCompactSummary)continue;let e=t.message?.content;if(!e)continue;let n=[];if(typeof e==`string`)n.push(e);else if(Array.isArray(e))for(let t of e)t.type===`text`&&t.text&&n.push(t.text);for(let e of n){if(!e)continue;let t=sy(e,Fa);if(t){let n=t.replace(/^\//,``);if(J3().has(n))continue;{let n=sy(e,`command-args`)?.trim();if(!n)continue;return`${t} ${n}`}}let n=sy(e,`bash-input`);if(n)return`! ${n}`;if(!a8.test(e))return e}}}function O6(e){return e.map(e=>{let{isSidechain:t,parentUuid:n,...r}=e;return r})}function mot(e){let t,n=-1,r=-1,i=new Map,a=0;for(let o of e.values()){if(i.set(o.uuid,a),my(o)){r=a;let e=o.compactMetadata?.preservedSegment;e&&(t=e,n=a)}a++}if(!t)return;let o=n===r,s=new Set;if(o){let n=new Set,r=e.get(t.tailUuid),i=!1;for(;r&&!n.has(r.uuid);){if(n.add(r.uuid),s.add(r.uuid),r.uuid===t.headUuid){i=!0;break}r=r.parentUuid?e.get(r.parentUuid):void 0}if(!i){Y(`tengu_relink_walk_broken`,{tailInTranscript:e.has(t.tailUuid),headInTranscript:e.has(t.headUuid),anchorInTranscript:e.has(t.anchorUuid),walkSteps:n.size,transcriptSize:e.size});return}}if(o){let n=e.get(t.headUuid);n&&e.set(t.headUuid,{...n,parentUuid:t.anchorUuid});for(let[n,r]of e)r.parentUuid===t.anchorUuid&&n!==t.headUuid&&e.set(n,{...r,parentUuid:t.tailUuid});for(let t of s){let n=e.get(t);n?.type===`assistant`&&e.set(t,{...n,message:{...n.message,usage:{...n.message.usage,input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0}}})}}let c=[];for(let[t]of e){let e=i.get(t);e!==void 0&&e<r&&!s.has(t)&&c.push(t)}for(let t of c)e.delete(t)}function hot(e){let t=new Set;for(let n of e.values()){let e=n.snipMetadata?.removedUuids;if(e)for(let n of e)t.add(n)}if(t.size===0)return;let n=new Map,r=0;for(let i of t){let t=e.get(i);t&&(n.set(i,t.parentUuid),e.delete(i),r++)}let i=e=>{let r=[],i=e;for(;i&&t.has(i);)if(r.push(i),i=n.get(i),i===void 0){i=null;break}for(let e of r)n.set(e,i);return i},a=0;for(let[n,r]of e)!r.parentUuid||!t.has(r.parentUuid)||(e.set(n,{...r,parentUuid:i(r.parentUuid)}),a++);Y(`tengu_snip_resume_filtered`,{removed_count:r,relinked_count:a})}function k6(e,t){let n,r=-1/0;for(let i of e){if(!t(i))continue;let e=Date.parse(i.timestamp);e>r&&(r=e,n=i)}return n}function A6(e,t){let n=[],r=new Set,i=t;for(;i;){if(r.has(i.uuid)){J(Error(`Cycle detected in parentUuid chain at message ${i.uuid}. Returning partial transcript.`)),Y(`tengu_chain_parent_cycle`,{});break}r.add(i.uuid),n.push(i),i=i.parentUuid?e.get(i.parentUuid):void 0}return n.reverse(),got(e,n,r)}function got(e,t,n){let r=t.filter(e=>e.type===`assistant`);if(r.length===0)return t;let i=new Map;for(let e of r)e.message.id&&i.set(e.message.id,e);let a=new Map,o=new Map;for(let t of e.values())if(t.type===`assistant`&&t.message.id){let e=a.get(t.message.id);e?e.push(t):a.set(t.message.id,[t])}else if(t.type===`user`&&t.parentUuid&&Array.isArray(t.message.content)&&t.message.content.some(e=>e.type===`tool_result`)){let e=o.get(t.parentUuid);e?e.push(t):o.set(t.parentUuid,[t])}let s=new Set,c=new Map,l=0;for(let e of r){let t=e.message.id;if(!t||s.has(t))continue;s.add(t);let r=a.get(t)??[e],u=r.filter(e=>!n.has(e.uuid)),d=[];for(let e of r){let t=o.get(e.uuid);if(t)for(let e of t)n.has(e.uuid)||d.push(e)}if(u.length===0&&d.length===0)continue;u.sort((e,t)=>e.timestamp.localeCompare(t.timestamp)),d.sort((e,t)=>e.timestamp.localeCompare(t.timestamp));let f=i.get(t),p=[...u,...d];for(let e of p)n.add(e.uuid);l+=p.length,c.set(f.uuid,p)}if(l===0)return t;Y(`tengu_chain_parallel_tr_recovered`,{recovered_count:l});let u=[];for(let e of t){u.push(e);let t=c.get(e.uuid);t&&u.push(...t)}return u}function _ot(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.type!==`system`||n.subtype!==`turn_duration`)continue;let r=n.messageCount;if(r===void 0)return;let i=t;Y(`tengu_resume_consistency_delta`,{expected:r,actual:i,delta:i-r,chain_length:e.length,checkpoint_age_entries:e.length-1-t});return}}function j6(e,t){let n=[],r=new Map;for(let i of t){let t=e.get(i.uuid);if(!t)continue;let{snapshot:a,isSnapshotUpdate:o}=t,s=o?r.get(a.messageId):void 0;s===void 0?(r.set(a.messageId,n.length),n.push(a)):n[s]=a}return n}function M6(e,t){return Array.from(e.values())}async function vot(e){if(e.endsWith(`.jsonl`)){let{messages:t,summaries:n,customTitles:r,tags:i,fileHistorySnapshots:a,attributionSnapshots:o,contextCollapseCommits:s,contextCollapseSnapshot:c,leafUuids:l,contentReplacements:u,worktreeStates:d}=await W6(e);if(t.size===0)throw Error(`No messages found in JSONL file`);let f=k6(t.values(),e=>l.has(e.uuid));if(!f)throw Error(`No valid conversation chain found in JSONL file`);let p=A6(t,f),m=n.get(f.uuid),h=r.get(f.sessionId),g=i.get(f.sessionId),_=f.sessionId;return{...P6(p,0,m,h,j6(a,p),g,e,M6(o,p),void 0,u.get(_)??[]),contextCollapseCommits:s.filter(e=>e.sessionId===_),contextCollapseSnapshot:c?.sessionId===_?c:void 0,worktreeSession:d.has(_)?d.get(_):void 0}}let t=await tl(e,{encoding:`utf-8`}),n;try{n=$n(t)}catch(e){throw Error(`Invalid JSON in transcript file: ${e}`)}let r;if(Array.isArray(n))r=n;else if(n&&typeof n==`object`&&`messages`in n){if(!Array.isArray(n.messages))throw Error(`Transcript messages must be an array`);r=n.messages}else throw Error(`Transcript must be an array of messages or an object with a messages array`);return P6(r,0,void 0,void 0,void 0,void 0,e)}function yot(e){if(e.type!==`user`||e.isMeta)return!1;let t=e.message?.content;return t?typeof t==`string`?t.trim().length>0:Array.isArray(t)?t.some(e=>e.type===`text`||e.type===`image`||e.type===`document`):!1:!1}function bot(e){if(e.type!==`assistant`)return!1;let t=e.message?.content;return!t||!Array.isArray(t)?!1:t.some(e=>e.type===`text`&&typeof e.text==`string`&&e.text.trim().length>0)}function N6(e){let t=0;for(let n of e)switch(n.type){case`user`:yot(n)&&t++;break;case`assistant`:bot(n)&&t++;break;case`attachment`:case`system`:case`progress`:break}return t}function P6(e,t=0,n,r,i,a,o,s,c,l){let u=e.at(-1),d=e[0],f=E6(e),p=new Date(d.timestamp),m=new Date(u.timestamp);return{date:u.timestamp,messages:O6(e),fullPath:o,value:t,created:p,modified:m,firstPrompt:f,messageCount:N6(e),isSidechain:d.isSidechain,agentName:d.agentName,agentSetting:c,leafUuid:u.uuid,summary:n,customTitle:r,tag:a,fileHistorySnapshots:i,attributionSnapshots:s,contentReplacements:l,gitBranch:u.gitBranch,projectPath:d.cwd}}async function xot(e){let t=new Map,n=0;for(let r of e){let e=H6(r);if(e){let r=(t.get(e)||0)+1;t.set(e,r),n=Math.max(r,n)}}if(n<=1)return;let r=Array.from(t.values()).filter(e=>e>1),i=r.length,a=r.reduce((e,t)=>e+t,0);Y(`tengu_session_forked_branches_fetched`,{total_sessions:t.size,sessions_with_branches:i,max_branches_per_session:Math.max(...r),avg_branches_per_session:Math.round(a/i),total_transcript_count:e.length})}async function F6(e){let t=await r8(c8(Yt()),e,Yt());return await xot(t),t}function I6(e,t){let n=q(),r=`${U(t)}\n`;try{n.appendFileSync(e,r,{mode:384})}catch{n.mkdirSync(xc(e),{mode:448}),n.appendFileSync(e,r,{mode:384})}}function Sot(e){let t;try{t=qse(e,`r`);let n=Gse(t),r=Math.max(0,n.size-si),i=Buffer.allocUnsafe(Math.min(si,n.size-r)),a=Jse(t,i,0,i.length,r);return i.toString(`utf8`,0,a)}catch{return``}finally{if(t!==void 0)try{Vse(t)}catch{}}}async function Cot(e,t,n,r=`user`){I6(n??f6(e),{type:`custom-title`,customTitle:t,sessionId:e}),e===jn()&&(b6().currentSessionTitle=t),Y(`tengu_session_renamed`,{source:r})}function wot(e,t){I6(f6(e),{type:`ai-title`,aiTitle:t,sessionId:e})}function Tot(e,t){I6(f6(e),{type:`task-summary`,summary:t,sessionId:e,timestamp:new Date().toISOString()})}async function Eot(e,t,n){I6(n??f6(e),{type:`tag`,tag:t,sessionId:e}),e===jn()&&(b6().currentSessionTag=t),Y(`tengu_session_tagged`,{})}function L6(e,t,n){I6(n??f6(e),{type:`goal`,sessionId:e,state:t,timestamp:new Date().toISOString()}),e===jn()&&(b6().currentSessionGoal=t)}function R6(e,t){I6(t??f6(e),{type:`goal-cleared`,sessionId:e,timestamp:new Date().toISOString()}),e===jn()&&(b6().currentSessionGoal=void 0)}async function Dot(e,t,n,r,i){if(I6(i??f6(e),{type:`pr-link`,sessionId:e,prNumber:t,prUrl:n,prRepository:r,timestamp:new Date().toISOString()}),e===jn()){let e=b6();e.currentSessionPrNumber=t,e.currentSessionPrUrl=n,e.currentSessionPrRepository=r}Y(`tengu_session_linked_to_pr`,{prNumber:t})}function Oot(e){if(e===jn())return b6().currentSessionTag}function z6(e){if(e===jn())return b6().currentSessionTitle}function kot(e){let t=b6();e.customTitle&&(t.currentSessionTitle??(t.currentSessionTitle=e.customTitle)),e.tag!==void 0&&(t.currentSessionTag=e.tag||void 0),e.agentName&&(t.currentSessionAgentName=e.agentName),e.agentColor&&(t.currentSessionAgentColor=e.agentColor),e.agentSetting&&(t.currentSessionAgentSetting=e.agentSetting),e.mode&&(t.currentSessionMode=e.mode),e.worktreeSession!==void 0&&(t.currentSessionWorktree=e.worktreeSession),e.prNumber!==void 0&&(t.currentSessionPrNumber=e.prNumber),e.prUrl&&(t.currentSessionPrUrl=e.prUrl),e.prRepository&&(t.currentSessionPrRepository=e.prRepository),e.goal&&(t.currentSessionGoal=e.goal)}function Aot(){let e=b6();e.currentSessionTitle=void 0,e.currentSessionTag=void 0,e.currentSessionAgentName=void 0,e.currentSessionAgentColor=void 0,e.currentSessionLastPrompt=void 0,e.currentSessionAgentSetting=void 0,e.currentSessionMode=void 0,e.currentSessionGoal=void 0,e.currentSessionWorktree=void 0,e.currentSessionPrNumber=void 0,e.currentSessionPrUrl=void 0,e.currentSessionPrRepository=void 0}function B6(){b6().reAppendSessionMetadata()}async function jot(e,t,n,r=`user`){I6(n??f6(e),{type:`agent-name`,agentName:t,sessionId:e}),e===jn()&&(b6().currentSessionAgentName=t,O5e(t)),Y(`tengu_agent_name_set`,{source:r})}function Mot(e){b6().currentSessionAgentSetting=e}function Not(e){b6().currentSessionTitle=e}function Pot(e){b6().currentSessionMode=e}function V6(e){let t=e?{originalCwd:e.originalCwd,worktreePath:e.worktreePath,worktreeName:e.worktreeName,worktreeBranch:e.worktreeBranch,originalBranch:e.originalBranch,originalHeadCommit:e.originalHeadCommit,sessionId:e.sessionId,tmuxSessionName:e.tmuxSessionName,hookBased:e.hookBased}:null,n=b6();n.currentSessionWorktree=t,n.sessionFile&&I6(n.sessionFile,{type:`worktree-state`,worktreeSession:t,sessionId:jn()})}function H6(e){return e.sessionId?e.sessionId:e.messages[0]?.sessionId}function U6(e){return e.messages.length===0&&e.sessionId!==void 0}async function Fot(e){if(!U6(e))return e;let t=e.fullPath;if(!t)return e;try{let{messages:n,summaries:r,customTitles:i,tags:a,agentNames:o,agentColors:s,agentSettings:c,prNumbers:l,prUrls:u,prRepositories:d,modes:f,worktreeStates:p,goals:m,fileHistorySnapshots:h,attributionSnapshots:g,contentReplacements:_,contextCollapseCommits:v,contextCollapseSnapshot:y,leafUuids:b}=await W6(t);if(n.size===0){let t=e.sessionId?m.get(e.sessionId):void 0;return t?{...e,goal:t}:e}let x=k6(n.values(),e=>b.has(e.uuid)&&(e.type===`user`||e.type===`assistant`));if(!x){let t=e.sessionId?m.get(e.sessionId):void 0;return t?{...e,goal:t}:e}let S=A6(n,x),C=x.sessionId;return{...e,messages:O6(S),firstPrompt:E6(S),messageCount:N6(S),summary:x?r.get(x.uuid):e.summary,customTitle:C?i.get(C):e.customTitle,tag:C?a.get(C):e.tag,agentName:C?o.get(C):e.agentName,agentColor:C?s.get(C):e.agentColor,agentSetting:C?c.get(C):e.agentSetting,mode:C?f.get(C):e.mode,worktreeSession:C&&p.has(C)?p.get(C):e.worktreeSession,goal:C?m.get(C):e.goal,prNumber:C?l.get(C):e.prNumber,prUrl:C?u.get(C):e.prUrl,prRepository:C?d.get(C):e.prRepository,gitBranch:x?.gitBranch??e.gitBranch,isSidechain:S[0]?.isSidechain??e.isSidechain,leafUuid:x?.uuid??e.leafUuid,fileHistorySnapshots:j6(h,S),attributionSnapshots:M6(g,S),contentReplacements:C?_.get(C)??[]:e.contentReplacements,contextCollapseCommits:C?v.filter(e=>e.sessionId===C):void 0,contextCollapseSnapshot:C&&y?.sessionId===C?y:void 0}}catch{return e}}async function Iot(e,t){let{limit:n,exact:r}=t||{},i=await qot(await Vat(Yt())),{logs:a}=await i8(i,0,i.length),o=e.toLowerCase().trim(),s=a.filter(e=>{let t=e.customTitle?.toLowerCase().trim();return t?r?t===o:t.includes(o):!1}),c=new Map;for(let e of s){let t=H6(e);if(t){let n=c.get(t);(!n||e.modified>n.modified)&&c.set(t,e)}}let l=Array.from(c.values());return l.sort((e,t)=>t.modified.getTime()-e.modified.getTime()),n?l.slice(0,n):l}function Lot(e,t){if(e===null||e.length===0)return t;if(e.length<dst)return Buffer.concat([e,t]);if(e[0]===123){for(let n of f8)if(e.compare(n,0,n.length,1,1+n.length)===0)return Buffer.concat([e,t])}let n=t.indexOf(10);return n===-1?null:t.subarray(n+1)}async function Rot(e,t){let{createReadStream:n}=await import(`fs`),r=n(e,{end:t-1}),i=[],a=null;for await(let e of r){let t=Lot(a,e);if(t===null){a=null;continue}let n=!1;for(let e of f8)if(t.includes(e)){n=!0;break}if(n){let e=0,n=t.indexOf(10);for(;n!==-1;){for(let r of f8){let a=t.indexOf(r,e);if(a!==-1&&a<n){i.push(t.toString(`utf-8`,e,n));break}}e=n+1,n=t.indexOf(10,e)}a=t.subarray(e)}else{let e=t.lastIndexOf(10);a=e>=0?t.subarray(e+1):t}a.length>64*1024&&(a=null)}if(a!==null&&a.length>0){for(let e of f8)if(a.includes(e)){i.push(a.toString(`utf-8`));break}}return i}function zot(e,t,n){let r=0,i=!1,a=!1,o=0;for(let s=t;o<n.length;s++){if(s===n[o]){if(r===1&&!i)return n[o];o++}let t=e[s];a?a=!1:i?t===92?a=!0:t===34&&(i=!1):t===34?i=!0:t===123?r++:t===125&&r--}return n.at(-1)}function Bot(e){let t=Buffer.from(`{"parentUuid":`),n=Buffer.from(`"uuid":"`),r=Buffer.from(`"isSidechain":true`),i=Buffer.from(`","timestamp":"`),a=i.length,o=t.length,s=n.length,c=[],l=[],u=new Map,d=0,f=e.length;for(;d<f;){let r=e.indexOf(10,d),p=r===-1?f:r+1;if(p-d>o&&e[d]===123&&e.compare(t,0,o,d,d+o)===0){let t=e[d+o]===34?d+o+1:-1,r=-1,f=-1,m,h=d;for(;;){let t=e.indexOf(n,h);if(t<0||t>=p)break;r<0&&(r=t);let o=t+s+36;o+a<=p&&e.compare(i,0,a,o,o+a)===0&&(f<0?f=t:(m??(m=[f])).push(t)),h=t+s}let g=m?zot(e,d,m):f>=0?f:r;if(g>=0){let n=g+s,r=e.toString(`latin1`,n,n+36);u.set(r,c.length),c.push(d,p,t)}else l.push(d,p)}else l.push(d,p);d=p}let p=-1;for(let t=c.length-3;t>=0;t-=3){let n=e.indexOf(r,c[t]);if(n===-1||n>=c[t+1]){p=t;break}}if(p<0)return e;let m=new Set,h=new Set,g=0,_=p;for(;_!==void 0&&!m.has(_);){m.add(_),h.add(c[_]),g+=c[_+1]-c[_];let t=c[_+2];if(t<0)break;let n=e.toString(`latin1`,t,t+36);_=u.get(n)}if(f-g<f>>1)return e;let v=[],y=0;for(let t=0;t<c.length;t+=3){let n=c[t];for(;y<l.length&&l[y]<n;)v.push(e.subarray(l[y],l[y+1])),y+=2;h.has(n)&&v.push(e.subarray(n,c[t+1]))}for(;y<l.length;)v.push(e.subarray(l[y],l[y+1])),y+=2;return Buffer.concat(v)}async function W6(e,t){let n=new Map,r=new Map,i=new Map,a=new Map,o=new Map,s=new Map,c=new Map,l=new Map,u=new Map,d=new Map,f=new Map,p=new Map,m=new Map,g=new Map,_=new Map,v=new Map,y=new Map,b=[],x;try{let S=null,C=null,w=!1;if(!h(process.env.CLAUDE_CODE_DISABLE_PRECOMPACT_SKIP)){let{size:t}=await ol(e);if(t>5242880){let n=await kre(e,t);S=n.postBoundaryBuf,w=n.hasPreservedSegment,n.boundaryStartOffset>0&&(C=await Rot(e,n.boundaryStartOffset))}}if(S??(S=await tl(e)),!t?.keepAllLeaves&&!w&&!h(process.env.CLAUDE_CODE_DISABLE_PRECOMPACT_SKIP)&&S.length>5242880&&(S=Bot(S)),C&&C.length>0){let e=Mt(Buffer.from(C.join(`
|
|
3064
3064
|
`)));for(let t of e)t.type===`summary`&&t.leafUuid?r.set(t.leafUuid,t.summary):t.type===`custom-title`&&t.sessionId?i.set(t.sessionId,t.customTitle):t.type===`tag`&&t.sessionId?a.set(t.sessionId,t.tag):t.type===`agent-name`&&t.sessionId?o.set(t.sessionId,t.agentName):t.type===`agent-color`&&t.sessionId?s.set(t.sessionId,t.agentColor):t.type===`agent-setting`&&t.sessionId?c.set(t.sessionId,t.agentSetting):t.type===`mode`&&t.sessionId?f.set(t.sessionId,t.mode):t.type===`worktree-state`&&t.sessionId?p.set(t.sessionId,t.worktreeSession):t.type===`goal`&&t.sessionId?m.set(t.sessionId,t.state):t.type===`goal-cleared`&&t.sessionId?m.delete(t.sessionId):t.type===`pr-link`&&t.sessionId&&(l.set(t.sessionId,t.prNumber),u.set(t.sessionId,t.prUrl),d.set(t.sessionId,t.prRepository))}let T=Mt(S),E=new Map;for(let e of T){if(Yat(e)){let t=e.parentUuid;E.set(e.uuid,t&&E.has(t)?E.get(t)??null:t);continue}if(c6(e))e.parentUuid&&E.has(e.parentUuid)&&(e.parentUuid=E.get(e.parentUuid)??null),n.set(e.uuid,e),my(e)&&(b.length=0,x=void 0);else if(e.type===`summary`&&e.leafUuid)r.set(e.leafUuid,e.summary);else if(e.type===`custom-title`&&e.sessionId)i.set(e.sessionId,e.customTitle);else if(e.type===`tag`&&e.sessionId)a.set(e.sessionId,e.tag);else if(e.type===`agent-name`&&e.sessionId)o.set(e.sessionId,e.agentName);else if(e.type===`agent-color`&&e.sessionId)s.set(e.sessionId,e.agentColor);else if(e.type===`agent-setting`&&e.sessionId)c.set(e.sessionId,e.agentSetting);else if(e.type===`mode`&&e.sessionId)f.set(e.sessionId,e.mode);else if(e.type===`worktree-state`&&e.sessionId)p.set(e.sessionId,e.worktreeSession);else if(e.type===`goal`&&e.sessionId)m.set(e.sessionId,e.state);else if(e.type===`goal-cleared`&&e.sessionId)m.delete(e.sessionId);else if(e.type===`pr-link`&&e.sessionId)l.set(e.sessionId,e.prNumber),u.set(e.sessionId,e.prUrl),d.set(e.sessionId,e.prRepository);else if(e.type===`file-history-snapshot`)g.set(e.messageId,e);else if(e.type===`attribution-snapshot`)_.set(e.messageId,e);else if(e.type===`content-replacement`)if(e.agentId){let t=y.get(e.agentId)??[];y.set(e.agentId,t),t.push(...e.replacements)}else{let t=v.get(e.sessionId)??[];v.set(e.sessionId,t),t.push(...e.replacements)}else e.type===`marble-origami-commit`?b.push(e):e.type===`marble-origami-snapshot`&&(x=e)}}catch{}mot(n),hot(n);let S=[...n.values()],C=new Set(S.map(e=>e.parentUuid).filter(e=>e!==null)),w=S.filter(e=>!C.has(e.uuid)),T=new Set,E=!1;for(let e of w){let t=new Set,r=e;for(;r;){if(t.has(r.uuid)){E=!0;break}if(t.add(r.uuid),r.type===`user`||r.type===`assistant`){T.add(r.uuid);break}r=r.parentUuid?n.get(r.parentUuid):void 0}}return E&&Y(`tengu_transcript_parent_cycle`,{}),{messages:n,summaries:r,customTitles:i,tags:a,agentNames:o,agentColors:s,agentSettings:c,prNumbers:l,prUrls:u,prRepositories:d,modes:f,worktreeStates:p,goals:m,fileHistorySnapshots:g,attributionSnapshots:_,contentReplacements:v,agentContentReplacements:y,contextCollapseCommits:b,contextCollapseSnapshot:x,leafUuids:T}}async function Vot(e){return W6(X(fn()??c8(Yt()),`${e}.jsonl`))}async function G6(e){let t=p8.get(e);if(t!==void 0)return t;if(p8.size>=d8){let e=p8.keys().next().value;e!==void 0&&p8.delete(e)}let n=(async()=>{let{messages:t}=await Vot(e);return new Set(t.keys())})();return p8.set(e,n),n}function K6(){return p8}function q6(){p8.clear()}async function Hot(e,t){return(await G6(e)).has(t)}async function Uot(e){let{messages:t,summaries:n,customTitles:r,tags:i,agentSettings:a,worktreeStates:o,fileHistorySnapshots:s,attributionSnapshots:c,contentReplacements:l,goals:u,contextCollapseCommits:d,contextCollapseSnapshot:f}=await Vot(e);if(t.size===0)return null;let p=K6();p.has(e)||p.set(e,Promise.resolve(new Set(t.keys())));let m=k6(t.values(),e=>!e.isSidechain);if(!m)return null;let h=A6(t,m),g=n.get(m.uuid),_=r.get(m.sessionId),v=i.get(m.sessionId),y=a.get(e);return{...P6(h,0,g,_,j6(s,h),v,f6(e),M6(c,h),y,l.get(e)??[]),worktreeSession:o.get(e),goal:u.get(e),contextCollapseCommits:d.filter(t=>t.sessionId===e),contextCollapseSnapshot:f?.sessionId===e?f:void 0}}async function J6(e){let t=await F6(e),{logs:n}=await i8(t,0,t.length),r=Ll(n);return r.forEach((e,t)=>{e.value=t}),r}async function Wot(e,t){return t?.skipIndex?Got(e):(await Y6(e,t?.initialEnrichCount??m8)).logs}async function Got(e){let t=u6(),n;try{n=await nl(t,{withFileTypes:!0})}catch{return[]}let r=n.filter(e=>e.isDirectory()).map(e=>X(t,e.name)),i=(await Promise.all(r.map(t=>est(t,e)))).flat(),a=new Map;for(let e of i){let t=`${e.sessionId??``}:${e.leafUuid??``}`,n=a.get(t);(!n||e.modified.getTime()>n.modified.getTime())&&a.set(t,e)}let o=Ll([...a.values()]);return o.forEach((e,t)=>{e.value=t}),o}async function Y6(e,t=m8){let n=u6(),r;try{r=await nl(n,{withFileTypes:!0})}catch{return{logs:[],allStatLogs:[],nextIndex:0}}let i=r.filter(e=>e.isDirectory()).map(e=>X(n,e.name)),a=[];for(let t of i)a.push(...await r8(t,e));let o=ist(a),{logs:s,nextIndex:c}=await i8(o,0,t);return s.forEach((e,t)=>{e.value=t}),{logs:s,allStatLogs:o,nextIndex:c}}async function Kot(e,t,n=m8){return(await X6(e,t,n)).logs}async function X6(e,t,n=m8){G(`/resume: loading sessions for cwd=${Yt()}, worktrees=[${e.join(`, `)}]`);let r=await qot(e,t);G(`/resume: found ${r.length} session files on disk`);let{logs:i,nextIndex:a}=await i8(r,0,n);return i.forEach((e,t)=>{e.value=t}),{logs:i,allStatLogs:r,nextIndex:a}}async function qot(e,t){let n=u6();if(e.length<=1){let e=Yt();return r8(c8(e),void 0,e)}let r=process.platform===`win32`,i=e.map(e=>{let t=qi(e);return{path:e,prefix:r?t.toLowerCase():t}});i.sort((e,t)=>t.prefix.length-e.prefix.length);let a=[],o=new Set,s;try{s=await nl(n,{withFileTypes:!0})}catch(e){return G(`Failed to read projects dir ${n}, falling back to current project: ${e}`),r8(c8(Yt()),t,Yt())}for(let e of s){if(!e.isDirectory())continue;let t=r?e.name.toLowerCase():e.name;if(!o.has(t)){for(let{path:r,prefix:s}of i)if(t===s||t.startsWith(`${s}-`)){o.add(t),a.push(...await r8(X(n,e.name),void 0,r));break}}}return ist(a)}async function Z6(e){let t=h6(e);try{let{messages:n,agentContentReplacements:r}=await W6(t),i=Array.from(n.values()).filter(t=>t.agentId===e&&t.isSidechain);if(i.length===0)return null;let a=new Set(i.map(e=>e.parentUuid)),o=k6(i,e=>!a.has(e.uuid));return o?{messages:A6(n,o).filter(t=>t.agentId===e).map(({isSidechain:e,parentUuid:t,...n})=>n),contentReplacements:r.get(e)??[]}:null}catch{return null}}function Jot(e){let t=[];for(let n of e)n.type===`progress`&&n.data&&typeof n.data==`object`&&`type`in n.data&&(n.data.type===`agent_progress`||n.data.type===`skill_progress`)&&`agentId`in n.data&&typeof n.data.agentId==`string`&&t.push(n.data.agentId);return Qr(t)}async function Q6(e){let t=await Promise.all(e.map(async e=>{try{let t=await Z6(oH(e));return t&&t.messages.length>0?{agentId:e,transcript:t.messages}:null}catch{return null}})),n={};for(let e of t)e&&(n[e.agentId]=e.transcript);return n}async function Yot(){let e=X(fn()??c8(Yt()),jn(),`subagents`),t;try{t=await nl(e,{withFileTypes:!0})}catch{return{}}return Q6(t.filter(e=>e.isFile()&&e.name.startsWith(`agent-`)&&e.name.endsWith(`.jsonl`)).map(e=>e.name.slice(6,-6)))}function $6(e){return e.type===`progress`?!1:e.type===`attachment`&&y6()!==`ant`?!!(e.attachment.type===`hook_additional_context`&&h(process.env.CLAUDE_CODE_SAVE_HOOK_ADDITIONAL_CONTEXT)):!0}function Xot(e){let t=new Set;for(let n of e)if(n.type===`assistant`&&Array.isArray(n.message.content))for(let e of n.message.content)e.type===`tool_use`&&e.name===`REPL`&&t.add(e.id);return t}function Zot(e,t){return e.flatMap(e=>{if(e.type===`assistant`&&Array.isArray(e.message.content)){let t=e.message.content,n=t.some(e=>e.type===`tool_use`&&e.name===`REPL`)?t.filter(e=>!(e.type===`tool_use`&&e.name===`REPL`)):t;if(n.length===0)return[];if(e.isVirtual){let{isVirtual:t,...r}=e;return[{...r,message:{...e.message,content:n}}]}return n===t?[e]:[{...e,message:{...e.message,content:n}}]}if(e.type===`user`&&Array.isArray(e.message.content)){let n=e.message.content,r=n.some(e=>e.type===`tool_result`&&t.has(e.tool_use_id))?n.filter(e=>!(e.type===`tool_result`&&t.has(e.tool_use_id))):n;if(r.length===0)return[];if(e.isVirtual){let{isVirtual:t,...n}=e;return[{...n,message:{...e.message,content:r}}]}return r===n?[e]:[{...e,message:{...e.message,content:r}}]}if(`isVirtual`in e&&e.isVirtual){let{isVirtual:t,...n}=e;return[n]}return[e]})}function e8(e,t=e){let n=e.filter($6);return y6()===`ant`?n:Zot(n,Xot(t))}async function Qot(e){return(await J6())[e]||null}async function $ot(e){try{let{messages:t}=await W6(d6()),n=null;for(let r of t.values())if(r.type===`assistant`){let t=r.message.content;if(Array.isArray(t)){for(let i of t)if(i.type===`tool_use`&&i.id===e){n=r;break}}}else if(r.type===`user`){let t=r.message.content;if(Array.isArray(t)){for(let n of t)if(n.type===`tool_result`&&n.tool_use_id===e)return null}}return n}catch{return null}}async function t8(e){let t=new Map,n;try{n=await nl(e,{withFileTypes:!0})}catch{return t}let r=[];for(let t of n){if(!t.isFile()||!t.name.endsWith(`.jsonl`))continue;let n=qWe(bc(t.name,`.jsonl`));n&&r.push({sessionId:n,filePath:X(e,t.name)})}return await Promise.all(r.map(async({sessionId:e,filePath:n})=>{try{let r=await ol(n);t.set(e,{path:n,mtime:r.mtime.getTime(),ctime:r.birthtime.getTime(),size:r.size})}catch{G(`Failed to stat session file: ${n}`)}})),t}async function n8(e,t){let{messages:n,summaries:r,customTitles:i,tags:a,agentNames:o,agentColors:s,agentSettings:c,prNumbers:l,prUrls:u,prRepositories:d,modes:f,fileHistorySnapshots:p,attributionSnapshots:m,contentReplacements:h,leafUuids:g}=await W6(e,{keepAllLeaves:!0});if(n.size===0)return[];let _=[],v=new Map;for(let e of n.values())if(g.has(e.uuid))_.push(e);else if(e.parentUuid){let t=v.get(e.parentUuid);t?t.push(e):v.set(e.parentUuid,[e])}let y=[];for(let g of _){let _=A6(n,g);if(_.length===0)continue;let b=v.get(g.uuid);b&&(b.sort((e,t)=>e.timestamp<t.timestamp?-1:+(e.timestamp>t.timestamp)),_.push(...b));let x=_[0],S=g.sessionId;y.push({date:g.timestamp,messages:O6(_),fullPath:e,value:0,created:new Date(x.timestamp),modified:new Date(g.timestamp),firstPrompt:E6(_),messageCount:N6(_),isSidechain:x.isSidechain??!1,sessionId:S,leafUuid:g.uuid,summary:r.get(g.uuid),customTitle:i.get(S),tag:a.get(S),agentName:o.get(S),agentColor:s.get(S),agentSetting:c.get(S),mode:f.get(S),prNumber:l.get(S),prUrl:u.get(S),prRepository:d.get(S),gitBranch:g.gitBranch,projectPath:t??x.cwd,fileHistorySnapshots:j6(p,_),attributionSnapshots:M6(m,_),contentReplacements:h.get(S)??[]})}return y}async function est(e,t){let n=await t8(e);if(n.size===0)return[];let r;r=t&&n.size>t?[...n.values()].sort((e,t)=>t.mtime-e.mtime).slice(0,t):[...n.values()];let i=[];for(let e of r)try{let t=await n8(e.path);i.push(...t)}catch{G(`Failed to load session file: ${e.path}`)}return i}async function tst(e,t,n){let{head:r,tail:i}=await Bre(e,t,n);if(!r)return{firstPrompt:``,isSidechain:!1};let a=r.includes(`"isSidechain":true`)||r.includes(`"isSidechain": true`),o=Ti(r,`cwd`),s=Ti(r,`agentSetting`),c=Gi(i,`lastPrompt`)||nst(r)||rst(r,`content`,200)||rst(r,`text`,200)||``,l=Gi(i,`customTitle`)??Gi(r,`customTitle`)??Gi(i,`aiTitle`)??Gi(r,`aiTitle`),u=Gi(i,`summary`),d=Gi(i,`tag`),f=Gi(i,`gitBranch`)??Ti(r,`gitBranch`),p=Gi(i,`prUrl`),m=Gi(i,`prRepository`),h,g=Gi(i,`prNumber`);if(g&&(h=parseInt(g,10)||void 0),!h){let e=i.lastIndexOf(`"prNumber":`);if(e>=0){let t=i.slice(e+11,e+25),n=parseInt(t.trim(),10);n>0&&(h=n)}}return{firstPrompt:c,gitBranch:f,isSidechain:a,projectPath:o,customTitle:l,summary:u,tag:d,agentSetting:s,prNumber:h,prUrl:p,prRepository:m}}function nst(e){let t=0,n=!1,r=``;for(;t<e.length;){let i=e.indexOf(`
|
|
3065
|
-
`,t),a=i>=0?e.slice(t,i):e.slice(t);if(t=i>=0?i+1:e.length,!(!a.includes(`"type":"user"`)&&!a.includes(`"type": "user"`))&&!a.includes(`"tool_result"`)&&!(a.includes(`"isMeta":true`)||a.includes(`"isMeta": true`)))try{let e=$n(a);if(e.type!==`user`)continue;let t=e.message;if(!t)continue;let i=t.content,o=[];if(typeof i==`string`)o.push(i);else if(Array.isArray(i))for(let e of i){let t=e;t.type===`text`&&typeof t.text==`string`&&o.push(t.text)}for(let e of o){if(!e)continue;let t=e.replace(/\n/g,` `).trim(),i=sy(t,Fa);if(i){let e=i.replace(/^\//,``),n=sy(t,`command-args`)?.trim()||``;if(J3().has(e)||!n){r||(r=i);continue}return n?`${i} ${n}`:i}let a=sy(t,`bash-input`);if(a)return`! ${a}`;if(a8.test(t)){t.startsWith(`<tick>`)&&(n=!0);continue}return t.length>200&&(t=`${t.slice(0,200).trim()}…`),t}}catch{}}return r||(n?`Proactive session`:``)}function rst(e,t,n){let r=[`"${t}":"`,`"${t}": "`];for(let t of r){let r=e.indexOf(t);if(r<0)continue;let i=r+t.length,a=i,o=0;for(;a<e.length&&o<n;){if(e[a]===`\\`){a+=2,o++;continue}if(e[a]===`"`)break;a++,o++}return e.slice(i,a).replace(/\\n/g,` `).replace(/\\t/g,` `).trim()}return``}function ist(e){let t=new Map;for(let n of e){if(!n.sessionId)continue;let e=t.get(n.sessionId);(!e||n.modified.getTime()>e.modified.getTime())&&t.set(n.sessionId,n)}return Ll([...t.values()]).map((e,t)=>({...e,value:t}))}async function r8(e,t,n){let r=[...(await t8(e)).entries()].sort((e,t)=>t[1].mtime-e[1].mtime);t&&r.length>t&&(r=r.slice(0,t));let i=[];for(let[e,t]of r)i.push({date:new Date(t.mtime).toISOString(),messages:[],isLite:!0,fullPath:t.path,value:0,created:new Date(t.ctime),modified:new Date(t.mtime),firstPrompt:``,messageCount:0,fileSize:t.size,isSidechain:!1,sessionId:e,projectPath:n});let a=Ll(i);return a.forEach((e,t)=>{e.value=t}),a}async function ast(e,t){if(!e.isLite||!e.fullPath)return e;let n=await tst(e.fullPath,e.fileSize??0,t),r={...e,isLite:!1,firstPrompt:n.firstPrompt,gitBranch:n.gitBranch,isSidechain:n.isSidechain,customTitle:n.customTitle,summary:n.summary,tag:n.tag,agentSetting:n.agentSetting,prNumber:n.prNumber,prUrl:n.prUrl,prRepository:n.prRepository,projectPath:n.projectPath??e.projectPath};return!r.firstPrompt&&!r.customTitle&&(r.firstPrompt=`(session)`),r.isSidechain?(G(`Session ${e.sessionId} filtered from /resume: isSidechain=true`),null):r}async function i8(e,t,n){let r=[],i=Buffer.alloc(si),a=t;for(;a<e.length&&r.length<n;){let t=e[a];a++;let n=await ast(t,i);n&&r.push(n)}let o=a-t,s=o-r.length;return s>0&&G(`/resume: enriched ${o} sessions, ${s} filtered out, ${r.length} visible (${e.length-a} remaining on disk)`),{logs:r,nextIndex:a}}var ost,sst,a8,cst,o8,s8,c8,l8,u8,lst,d8,ust,f8,dst,p8,m8,h8=n((()=>{d(),oo(),Jt(),Q3(),Ka(),BX(),sH(),Due(),Ar(),Hn(),Y1(),Vn(),K(),ni(),g(),qn(),so(),or(),Hat(),Ir(),s6(),Ot(),Ga(),h3(),Ai(),Pi(),vi(),mr(),sY(),b(),ost=typeof MACRO<`u`?`0.0.
|
|
3065
|
+
`,t),a=i>=0?e.slice(t,i):e.slice(t);if(t=i>=0?i+1:e.length,!(!a.includes(`"type":"user"`)&&!a.includes(`"type": "user"`))&&!a.includes(`"tool_result"`)&&!(a.includes(`"isMeta":true`)||a.includes(`"isMeta": true`)))try{let e=$n(a);if(e.type!==`user`)continue;let t=e.message;if(!t)continue;let i=t.content,o=[];if(typeof i==`string`)o.push(i);else if(Array.isArray(i))for(let e of i){let t=e;t.type===`text`&&typeof t.text==`string`&&o.push(t.text)}for(let e of o){if(!e)continue;let t=e.replace(/\n/g,` `).trim(),i=sy(t,Fa);if(i){let e=i.replace(/^\//,``),n=sy(t,`command-args`)?.trim()||``;if(J3().has(e)||!n){r||(r=i);continue}return n?`${i} ${n}`:i}let a=sy(t,`bash-input`);if(a)return`! ${a}`;if(a8.test(t)){t.startsWith(`<tick>`)&&(n=!0);continue}return t.length>200&&(t=`${t.slice(0,200).trim()}…`),t}}catch{}}return r||(n?`Proactive session`:``)}function rst(e,t,n){let r=[`"${t}":"`,`"${t}": "`];for(let t of r){let r=e.indexOf(t);if(r<0)continue;let i=r+t.length,a=i,o=0;for(;a<e.length&&o<n;){if(e[a]===`\\`){a+=2,o++;continue}if(e[a]===`"`)break;a++,o++}return e.slice(i,a).replace(/\\n/g,` `).replace(/\\t/g,` `).trim()}return``}function ist(e){let t=new Map;for(let n of e){if(!n.sessionId)continue;let e=t.get(n.sessionId);(!e||n.modified.getTime()>e.modified.getTime())&&t.set(n.sessionId,n)}return Ll([...t.values()]).map((e,t)=>({...e,value:t}))}async function r8(e,t,n){let r=[...(await t8(e)).entries()].sort((e,t)=>t[1].mtime-e[1].mtime);t&&r.length>t&&(r=r.slice(0,t));let i=[];for(let[e,t]of r)i.push({date:new Date(t.mtime).toISOString(),messages:[],isLite:!0,fullPath:t.path,value:0,created:new Date(t.ctime),modified:new Date(t.mtime),firstPrompt:``,messageCount:0,fileSize:t.size,isSidechain:!1,sessionId:e,projectPath:n});let a=Ll(i);return a.forEach((e,t)=>{e.value=t}),a}async function ast(e,t){if(!e.isLite||!e.fullPath)return e;let n=await tst(e.fullPath,e.fileSize??0,t),r={...e,isLite:!1,firstPrompt:n.firstPrompt,gitBranch:n.gitBranch,isSidechain:n.isSidechain,customTitle:n.customTitle,summary:n.summary,tag:n.tag,agentSetting:n.agentSetting,prNumber:n.prNumber,prUrl:n.prUrl,prRepository:n.prRepository,projectPath:n.projectPath??e.projectPath};return!r.firstPrompt&&!r.customTitle&&(r.firstPrompt=`(session)`),r.isSidechain?(G(`Session ${e.sessionId} filtered from /resume: isSidechain=true`),null):r}async function i8(e,t,n){let r=[],i=Buffer.alloc(si),a=t;for(;a<e.length&&r.length<n;){let t=e[a];a++;let n=await ast(t,i);n&&r.push(n)}let o=a-t,s=o-r.length;return s>0&&G(`/resume: enriched ${o} sessions, ${s} filtered out, ${r.length} visible (${e.length-a} remaining on disk)`),{logs:r,nextIndex:a}}var ost,sst,a8,cst,o8,s8,c8,l8,u8,lst,d8,ust,f8,dst,p8,m8,h8=n((()=>{d(),oo(),Jt(),Q3(),Ka(),BX(),sH(),Due(),Ar(),Hn(),Y1(),Vn(),K(),ni(),g(),qn(),so(),or(),Hat(),Ir(),s6(),Ot(),Ga(),h3(),Ai(),Pi(),vi(),mr(),sY(),b(),ost=typeof MACRO<`u`?`0.0.24`:`unknown`,sst=50*1024*1024,a8=/^(?:\s*<[a-z][\w-]*[\s>]|\[Request interrupted by user[^\]]*\])/,cst=new Set([`bash_progress`,`powershell_progress`,`mcp_progress`,`sleep_progress`]),o8=50*1024*1024,s8=new Map,c8=u(e=>X(u6(),qi(e))),l8=null,u8=!1,lst=10,d8=200,ust=class{constructor(){x(this,`currentSessionTag`,void 0),x(this,`currentSessionTitle`,void 0),x(this,`currentSessionAgentName`,void 0),x(this,`currentSessionAgentColor`,void 0),x(this,`currentSessionLastPrompt`,void 0),x(this,`currentSessionAgentSetting`,void 0),x(this,`currentSessionMode`,void 0),x(this,`currentSessionGoal`,void 0),x(this,`currentSessionWorktree`,void 0),x(this,`currentSessionPrNumber`,void 0),x(this,`currentSessionPrUrl`,void 0),x(this,`currentSessionPrRepository`,void 0),x(this,`sessionFile`,null),x(this,`pendingEntries`,[]),x(this,`internalEventWriter`,null),x(this,`internalEventReader`,null),x(this,`internalSubagentEventReader`,null),x(this,`pendingWriteCount`,0),x(this,`flushResolvers`,[]),x(this,`writeQueues`,new Map),x(this,`flushTimer`,null),x(this,`activeDrain`,null),x(this,`FLUSH_INTERVAL_MS`,100),x(this,`MAX_CHUNK_BYTES`,100*1024*1024),x(this,`existingSessionFiles`,new Map)}_resetFlushState(){this.pendingWriteCount=0,this.flushResolvers=[],this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=null,this.activeDrain=null,this.writeQueues=new Map,this.existingSessionFiles=new Map}incrementPendingWrites(){this.pendingWriteCount++}decrementPendingWrites(){if(this.pendingWriteCount--,this.pendingWriteCount===0){for(let e of this.flushResolvers)e();this.flushResolvers=[]}}async trackWrite(e){this.incrementPendingWrites();try{return await e()}finally{this.decrementPendingWrites()}}enqueueWrite(e,t){return new Promise(n=>{let r=this.writeQueues.get(e);if(r||(r=[],this.writeQueues.set(e,r)),r.length>=1e3){let e=r.splice(0,r.length-999);for(let t of e)t.resolve()}r.push({entry:t,resolve:n}),this.scheduleDrain()})}scheduleDrain(){this.flushTimer||(this.flushTimer=setTimeout(async()=>{this.flushTimer=null,this.activeDrain=this.drainWriteQueue(),await this.activeDrain,this.activeDrain=null,this.writeQueues.size>0&&this.scheduleDrain()},this.FLUSH_INTERVAL_MS))}async appendToFile(e,t){try{await Yc(e,t,{mode:384})}catch{await $c(xc(e),{recursive:!0,mode:448}),await Yc(e,t,{mode:384})}}async drainWriteQueue(){for(let[e,t]of this.writeQueues){if(t.length===0)continue;let n=t.splice(0),r=``,i=[];for(let{entry:t,resolve:a}of n){let n=`${U(t)}\n`;if(r.length+n.length>=this.MAX_CHUNK_BYTES){await this.appendToFile(e,r);for(let e of i)e();i.length=0,r=``}r+=n,i.push(a)}if(r.length>0){await this.appendToFile(e,r);for(let e of i)e()}}for(let[e,t]of this.writeQueues)t.length===0&&this.writeQueues.delete(e)}resetSessionFile(){this.sessionFile=null,this.pendingEntries=[]}reAppendSessionMetadata(e=!1){if(!this.sessionFile)return;let t=jn();if(!t)return;let n=Sot(this.sessionFile).split(`
|
|
3066
3066
|
`);if(!e){let e=n.findLast(e=>e.startsWith(`{"type":"custom-title"`));if(e){let t=Gi(e,`customTitle`);t!==void 0&&(this.currentSessionTitle=t||void 0)}}let r=n.findLast(e=>e.startsWith(`{"type":"tag"`));if(r){let e=Gi(r,`tag`);e!==void 0&&(this.currentSessionTag=e||void 0)}this.currentSessionLastPrompt&&I6(this.sessionFile,{type:`last-prompt`,lastPrompt:this.currentSessionLastPrompt,sessionId:t}),this.currentSessionTitle&&I6(this.sessionFile,{type:`custom-title`,customTitle:this.currentSessionTitle,sessionId:t}),this.currentSessionTag&&I6(this.sessionFile,{type:`tag`,tag:this.currentSessionTag,sessionId:t}),this.currentSessionAgentName&&I6(this.sessionFile,{type:`agent-name`,agentName:this.currentSessionAgentName,sessionId:t}),this.currentSessionAgentColor&&I6(this.sessionFile,{type:`agent-color`,agentColor:this.currentSessionAgentColor,sessionId:t}),this.currentSessionAgentSetting&&I6(this.sessionFile,{type:`agent-setting`,agentSetting:this.currentSessionAgentSetting,sessionId:t}),this.currentSessionMode&&I6(this.sessionFile,{type:`mode`,mode:this.currentSessionMode,sessionId:t}),this.currentSessionGoal&&I6(this.sessionFile,{type:`goal`,sessionId:t,state:this.currentSessionGoal,timestamp:new Date().toISOString()}),this.currentSessionWorktree!==void 0&&I6(this.sessionFile,{type:`worktree-state`,worktreeSession:this.currentSessionWorktree,sessionId:t}),this.currentSessionPrNumber!==void 0&&this.currentSessionPrUrl&&this.currentSessionPrRepository&&I6(this.sessionFile,{type:`pr-link`,sessionId:t,prNumber:this.currentSessionPrNumber,prUrl:this.currentSessionPrUrl,prRepository:this.currentSessionPrRepository,timestamp:new Date().toISOString()})}async flush(){if(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.activeDrain&&await this.activeDrain,await this.drainWriteQueue(),this.pendingWriteCount!==0)return new Promise(e=>{this.flushResolvers.push(e)})}async removeMessageByUuid(e){return this.trackWrite(async()=>{if(this.sessionFile!==null)try{let t=0,n=await el(this.sessionFile,`r+`);try{let{size:r}=await n.stat();if(t=r,r===0)return;let i=Math.min(r,si),a=r-i,o=Buffer.allocUnsafe(i),{bytesRead:s}=await n.read(o,0,i,a),c=o.subarray(0,s),l=`"uuid":"${e}"`,u=c.lastIndexOf(l);if(u>=0){let e=c.lastIndexOf(10,u);if(e>=0||a===0){let t=e+1,r=c.indexOf(10,u+l.length),i=r>=0?r+1:s,o=a+t,d=s-i;await n.truncate(o),d>0&&await n.write(c,i,d,o);return}}}finally{await n.close()}if(t>sst){G(`Skipping tombstone removal: session file too large (${go(t)})`,{level:`warn`});return}let r=(await tl(this.sessionFile,{encoding:`utf-8`})).split(`
|
|
3067
3067
|
`).filter(t=>{if(!t.trim())return!0;try{return $n(t).uuid!==e}catch{return!0}});await ll(this.sessionFile,r.join(`
|
|
3068
|
-
`),{encoding:`utf8`})}catch{}})}shouldSkipPersistence(){let e=h(process.env.TEST_ENABLE_SESSION_PERSISTENCE);return v6()===`test`&&!e||fi()?.cleanupPeriodDays===0||Zt()||h(process.env.CLAUDE_CODE_SKIP_PROMPT_HISTORY)}async materializeSessionFile(){if(!this.shouldSkipPersistence()&&(this.ensureCurrentSessionFile(),this.reAppendSessionMetadata(),this.pendingEntries.length>0)){let e=this.pendingEntries;this.pendingEntries=[];for(let t of e)await this.appendEntry(t)}}async insertMessageChain(e,t=!1,n,r,i){return this.trackWrite(async()=>{let a=r??null;this.sessionFile===null&&e.some(e=>e.type===`user`||e.type===`assistant`)&&await this.materializeSessionFile();let o;try{o=await Ci()}catch{o=void 0}let s=jn(),c=ln().get(s);for(let r of e){let e=my(r),l=a;r.type===`user`&&`sourceToolAssistantUUID`in r&&r.sourceToolAssistantUUID&&(l=r.sourceToolAssistantUUID);let u={parentUuid:e?null:l,logicalParentUuid:e?a:void 0,isSidechain:t,agentName:i?.agentName,promptId:r.type===`user`?one()??void 0:void 0,agentId:n,...r,userType:y6(),entrypoint:$at(),cwd:H(),sessionId:s,timestamp:new Date().toISOString(),version:ost,gitBranch:o,slug:c};await this.appendEntry(u),l6(r)&&(a=r.uuid)}if(!t){let t=D6(e);if(t){let e=t.replace(/\n/g,` `).trim();this.currentSessionLastPrompt=e.length>200?`${e.slice(0,200).trim()}…`:e}}})}async insertFileHistorySnapshot(e,t,n){return this.trackWrite(async()=>{let r={type:`file-history-snapshot`,messageId:e,snapshot:t,isSnapshotUpdate:n};await this.appendEntry(r)})}async insertQueueOperation(e){return this.trackWrite(async()=>{await this.appendEntry(e)})}async insertAttributionSnapshot(e){return this.trackWrite(async()=>{await this.appendEntry(e)})}async insertContentReplacement(e,t){return this.trackWrite(async()=>{let n={type:`content-replacement`,sessionId:jn(),agentId:t,replacements:e};await this.appendEntry(n)})}async appendEntry(e,t=jn()){if(this.shouldSkipPersistence())return;let n=t===jn(),r;if(n){if(this.sessionFile===null){this.pendingEntries.push(e);return}r=this.sessionFile}else{let e=await this.getExistingSessionFile(t);if(!e){J(Error(`appendEntry: session file not found for other session ${t}`));return}r=e}if(e.type===`summary`)this.enqueueWrite(r,e);else if(e.type===`custom-title`)this.enqueueWrite(r,e);else if(e.type===`ai-title`)this.enqueueWrite(r,e);else if(e.type===`last-prompt`)this.enqueueWrite(r,e);else if(e.type===`task-summary`)this.enqueueWrite(r,e);else if(e.type===`tag`)this.enqueueWrite(r,e);else if(e.type===`agent-name`)this.enqueueWrite(r,e);else if(e.type===`agent-color`)this.enqueueWrite(r,e);else if(e.type===`agent-setting`)this.enqueueWrite(r,e);else if(e.type===`pr-link`)this.enqueueWrite(r,e);else if(e.type===`file-history-snapshot`)this.enqueueWrite(r,e);else if(e.type===`attribution-snapshot`)this.enqueueWrite(r,e);else if(e.type===`speculation-accept`)this.enqueueWrite(r,e);else if(e.type===`mode`)this.enqueueWrite(r,e);else if(e.type===`worktree-state`)this.enqueueWrite(r,e);else if(e.type===`content-replacement`){let t=e.agentId?h6(e.agentId):r;this.enqueueWrite(t,e)}else if(e.type===`marble-origami-commit`)this.enqueueWrite(r,e);else if(e.type===`marble-origami-snapshot`)this.enqueueWrite(r,e);else if(e.type===`goal`)this.enqueueWrite(r,e);else if(e.type===`goal-cleared`)this.enqueueWrite(r,e);else{let n=await G6(t);if(e.type===`queue-operation`)this.enqueueWrite(r,e);else{let i=e.isSidechain&&e.agentId!==void 0,a=i?h6(oH(e.agentId)):r,o=!n.has(e.uuid);(i||o)&&(this.enqueueWrite(a,e),i||(n.add(e.uuid),c6(e)&&await this.persistToRemote(t,e)))}}}ensureCurrentSessionFile(){return this.sessionFile===null&&(this.sessionFile=d6()),this.sessionFile}async getExistingSessionFile(e){let t=this.existingSessionFiles.get(e);if(t)return t;let n=f6(e);try{if(await ol(n),this.existingSessionFiles.size>=d8){let e=this.existingSessionFiles.keys().next().value;e!==void 0&&this.existingSessionFiles.delete(e)}return this.existingSessionFiles.set(e,n),n}catch(e){if(hr(e))return null;throw e}}async persistToRemote(e,t){if(!Wat()&&this.internalEventWriter){try{await this.internalEventWriter(`transcript`,t,{...my(t)&&{isCompaction:!0},...t.agentId&&{agentId:t.agentId}})}catch{Y(`tengu_session_persistence_failed`,{}),G(`Failed to write transcript as internal event`)}return}}setInternalEventWriter(e){this.internalEventWriter=e,G(`CCR v2 internal event writer registered for transcript persistence`),this.FLUSH_INTERVAL_MS=lst}setInternalEventReader(e){this.internalEventReader=e,G(`CCR v2 internal event reader registered for session resume`)}setInternalSubagentEventReader(e){this.internalSubagentEventReader=e,G(`CCR v2 subagent event reader registered for session resume`)}getInternalEventReader(){return this.internalEventReader}getInternalSubagentEventReader(){return this.internalSubagentEventReader}},f8=[`"type":"summary"`,`"type":"custom-title"`,`"type":"tag"`,`"type":"agent-name"`,`"type":"agent-color"`,`"type":"agent-setting"`,`"type":"mode"`,`"type":"worktree-state"`,`"type":"goal"`,`"type":"goal-cleared"`,`"type":"pr-link"`].map(e=>Buffer.from(e)),dst=25,p8=new Map,m8=50}));function g8(e){return e.toLowerCase()}function fst(e){let t=hi(e),n=g8(t),r=[{dir:hi(X(Yt(),`.workmate`,`skills`)),prefix:`/.workmate/skills/`},{dir:hi(X(_c(),`.workmate`,`skills`)),prefix:`~/.workmate/skills/`}];for(let{dir:e,prefix:i}of r){let r=g8(e);for(let a of[kc,`/`])if(n.startsWith(r+a.toLowerCase())){let n=t.slice(e.length+a.length),r=n.indexOf(`/`),o=kc===`\\`?n.indexOf(`\\`):-1,s=r===-1?o:o===-1?r:Math.min(r,o);if(s<=0)return null;let c=n.slice(0,s);return!c||c===`.`||c.includes(`..`)||/[*?[\]]/.test(c)?null:{skillName:c,pattern:`${i+c}/**`}}}return null}function pst(e,t){if(io()===`windows`){let n=Er(e),r=Er(t);return Ec.relative(n,r)}return Ec.relative(e,t)}function mst(e){return io()===`windows`?Er(e):e}function hst(){return ki.map(e=>ji(e)).filter(e=>e!==void 0)}function gst(e){let t=g8(hi(e));return t.endsWith(`${kc}.workmate${kc}settings.json`)||t.endsWith(`${kc}.workmate${kc}settings.local.json`)?!0:hst().some(e=>g8(e)===t)}function _st(e){if(gst(e))return!0;let t=X(Yt(),`.workmate`,`commands`),n=X(Yt(),`.workmate`,`agents`),r=X(Yt(),`.workmate`,`skills`);return T8(e,t)||T8(e,n)||T8(e,r)}function vst(e){let t=X(Rd(),jd()),n=wc(e);return n.startsWith(t)&&n.endsWith(`.md`)}function _8(){return X(c8(H()),jn(),`session-memory`)+kc}function v8(){return X(_8(),`summary.md`)}function yst(e){return wc(e).startsWith(_8())}function bst(e){let t=c8(H()),n=wc(e);return n===t||n.startsWith(t+kc)}function y8(){return!1}function xst(){return io()===`windows`?`claude`:`claude-${process.getuid?.()??0}`}function b8(){return X(I8(),qi(Yt()))+kc}function x8(){return X(b8(),jn(),`scratchpad`)}async function Sst(){if(!y8())throw Error(`Scratchpad directory feature is not enabled`);let e=q(),t=x8();return await e.mkdir(t,{mode:448}),t}function Cst(e){if(!y8())return!1;let t=x8(),n=wc(e);return n===t||n.startsWith(t+kc)}function wst(e){let t=hi(e).split(kc),n=t.at(-1);if(e.startsWith(`\\\\`)||e.startsWith(`//`))return!0;for(let e=0;e<t.length;e++){let n=t[e],r=g8(n);for(let n of Mst)if(r===g8(n)){if(n===`.workmate`){let n=t[e+1];if(n&&g8(n)===`worktrees`)break}return!0}}if(n){let e=g8(n);if(jst.some(t=>g8(t)===e))return!0}return!1}function Tst(e){return!!((io()===`windows`||io()===`wsl`)&&e.indexOf(`:`,2)!==-1||/~\d/.test(e)||e.startsWith(`\\\\?\\`)||e.startsWith(`\\\\.\\`)||e.startsWith(`//?/`)||e.startsWith(`//./`)||/[.\s]+$/.test(e)||/\.(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i.test(e)||/(^|\/|\\)\.{3,}(\/|\\|$)/.test(e)||Ry(e))}function S8(e,t){let n=t??ir(e);for(let t of n)if(Tst(t))return{safe:!1,message:`Work Mate requested permissions to write to ${e}, which contains a suspicious Windows path pattern that requires manual approval.`,classifierApprovable:!1};for(let t of n)if(_st(t))return{safe:!1,message:`Work Mate requested permissions to write to ${e}, but you haven't granted it yet.`,classifierApprovable:!0};for(let t of n)if(wst(t))return{safe:!1,message:`Work Mate requested permissions to edit ${e} which is a sensitive file.`,classifierApprovable:!0};return{safe:!0}}function C8(e){return new Set([Yt(),...e.additionalWorkingDirectories.keys()])}function w8(e,t,n){let r=n??ir(e),i=Array.from(C8(t)).flatMap(e=>Nst(e));return r.every(e=>i.some(t=>T8(e,t)))}function T8(e,t){let n=hi(e),r=hi(t),i=n.replace(/^\/private\/var\//,`/var/`).replace(/^\/private\/tmp(\/|$)/,`/tmp$1`),a=r.replace(/^\/private\/var\//,`/var/`).replace(/^\/private\/tmp(\/|$)/,`/tmp$1`),o=g8(i),s=pst(g8(a),o);return s===``||!gr(s)&&!Ec.isAbsolute(s)}function Est(e){switch(e){case`cliArg`:case`command`:case`session`:return hi(Yt());case`userSettings`:case`policySettings`:case`projectSettings`:case`localSettings`:case`flagSettings`:return ui(e)}}function E8(e){return Ec.join(F8,e)}function Dst({patternRoot:e,pattern:t,rootPath:n}){let r=Ec.join(e,t);if(e===n)return E8(t);if(r.startsWith(`${n}${F8}`))return E8(r.slice(n.length));{let r=Ec.relative(n,e);return!r||r.startsWith(`..${F8}`)||r===`..`?null:E8(Ec.join(r,t))}}function D8(e,t){let n=new Set(e.get(null)??[]);for(let[r,i]of e.entries())if(r!==null)for(let e of i){let i=Dst({patternRoot:r,pattern:e,rootPath:t});i&&n.add(i)}return Array.from(n)}function O8(e){let t=kst(e,`read`,`deny`),n=new Map;for(let[e,r]of t.entries())n.set(e,Array.from(r.keys()));return n}function Ost(e,t){if(e.startsWith(`${F8}${F8}`)){let t=e.slice(1);if(io()===`windows`&&t.match(/^\/[a-z]\//i)){let e=t[1]?.toUpperCase()??`C`,n=t.slice(2),r=`${e}:\\`;return{relativePattern:n.startsWith(`/`)?n.slice(1):n,root:r}}return{relativePattern:t,root:F8}}else if(e.startsWith(`~${F8}`))return{relativePattern:e.slice(1),root:_c().normalize(`NFC`)};else if(e.startsWith(F8))return{relativePattern:e,root:Est(t)};let n=e;return e.startsWith(`.${F8}`)&&(n=e.slice(2)),{relativePattern:n,root:null}}function kst(e,t,n){let r=E9(e,(()=>{switch(t){case`edit`:return Gs;case`read`:return ys}})(),n),i=new Map;for(let[e,t]of r.entries()){let{relativePattern:n,root:r}=Ost(e,t.source),a=i.get(r);a===void 0&&(a=new Map,i.set(r,a)),a.set(n,t)}return i}function k8(e,t,n,r){let i=hi(e);io()===`windows`&&i.includes(`\\`)&&(i=Er(i));let a=kst(t,n,r);for(let[e,t]of a.entries()){let n=Array.from(t.keys()).map(e=>{let t=e;return t.endsWith(`/**`)&&(t=t.slice(0,-3)),t}),r=(0,Ast.default)().add(n),a=pst(e??H(),i??H());if(a.startsWith(`..${F8}`)||!a)continue;let o=r.test(a);if(o.ignored&&o.rule){let e=o.rule.pattern,n=`${e}/**`;return t.has(n)?t.get(n)??null:t.get(e)??null}}return null}function A8(e,t,n){if(typeof e.getPath!=`function`)return{behavior:`ask`,message:`Work Mate requested permissions to use ${e.name}, but you haven't granted it yet.`};let r=e.getPath(t),i=ir(r);for(let e of i)if(e.startsWith(`\\\\`)||e.startsWith(`//`))return{behavior:`ask`,message:`Work Mate requested permissions to read from ${r}, which appears to be a UNC path that could access network resources.`,decisionReason:{type:`other`,reason:`UNC path detected (defense-in-depth check)`}};for(let e of i)if(Tst(e))return{behavior:`ask`,message:`Work Mate requested permissions to read from ${r}, which contains a suspicious Windows path pattern that requires manual approval.`,decisionReason:{type:`other`,reason:`Path contains suspicious Windows-specific patterns (alternate data streams, short names, long path prefixes, or three or more consecutive dots) that require manual verification`}};for(let e of i){let t=k8(e,n,`read`,`deny`);if(t)return{behavior:`deny`,message:`Permission to read ${r} has been denied.`,decisionReason:{type:`rule`,rule:t}}}for(let e of i){let t=k8(e,n,`read`,`ask`);if(t)return{behavior:`ask`,message:`Work Mate requested permissions to read from ${r}, but you haven't granted it yet.`,decisionReason:{type:`rule`,rule:t}}}let a=j8(e,t,n,i);if(a.behavior===`allow`)return a;if(w8(r,n,i))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`mode`,mode:`default`}};let o=P8(hi(r),t);if(o.behavior!==`passthrough`)return o;let s=k8(r,n,`read`,`allow`);return s?{behavior:`allow`,updatedInput:t,decisionReason:{type:`rule`,rule:s}}:{behavior:`ask`,message:`Work Mate requested permissions to read from ${r}, but you haven't granted it yet.`,suggestions:M8(r,`read`,n,i),decisionReason:{type:`workingDir`,reason:`Path is outside allowed working directories`}}}function j8(e,t,n,r){if(typeof e.getPath!=`function`)return{behavior:`ask`,message:`Work Mate requested permissions to use ${e.name}, but you haven't granted it yet.`};let i=e.getPath(t),a=r??ir(i);for(let e of a){let t=k8(e,n,`edit`,`deny`);if(t)return{behavior:`deny`,message:`Permission to edit ${i} has been denied.`,decisionReason:{type:`rule`,rule:t}}}let o=N8(hi(i),t);if(o.behavior!==`passthrough`)return o;let s=k8(i,{...n,alwaysAllowRules:{session:n.alwaysAllowRules.session??[]}},`edit`,`allow`);if(s){let e=s.ruleValue.ruleContent;if(e&&(e.startsWith(`/.workmate/**`.slice(0,-2))||e.startsWith(`~/.workmate/**`.slice(0,-2)))&&!e.includes(`..`)&&e.endsWith(`/**`))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`rule`,rule:s}}}let c=S8(i,a);if(!c.safe){let e=fst(i),t=e?[{type:`addRules`,rules:[{toolName:Gs,ruleContent:e.pattern}],behavior:`allow`,destination:`session`}]:M8(i,`write`,n,a),r=c;return{behavior:`ask`,message:r.message,suggestions:t,decisionReason:{type:`safetyCheck`,reason:r.message,classifierApprovable:r.classifierApprovable}}}for(let e of a){let t=k8(e,n,`edit`,`ask`);if(t)return{behavior:`ask`,message:`Work Mate requested permissions to write to ${i}, but you haven't granted it yet.`,decisionReason:{type:`rule`,rule:t}}}let l=w8(i,n,a);if(n.mode===`acceptEdits`&&l)return{behavior:`allow`,updatedInput:t,decisionReason:{type:`mode`,mode:n.mode}};let u=k8(i,n,`edit`,`allow`);return u?{behavior:`allow`,updatedInput:t,decisionReason:{type:`rule`,rule:u}}:{behavior:`ask`,message:`Work Mate requested permissions to write to ${i}, but you haven't granted it yet.`,suggestions:M8(i,`write`,n,a),decisionReason:l?void 0:{type:`workingDir`,reason:`Path is outside allowed working directories`}}}function M8(e,t,n,r){let i=!w8(e,n,r);if(t===`read`&&i)return ir(Hi(e)).map(e=>ZV(e,`session`)).filter(e=>e!==void 0);let a=n.mode==="default"||n.mode===`plan`;if(t===`write`||t===`create`){let t=a?[{type:`setMode`,mode:`acceptEdits`,destination:`session`}]:[];if(i){let n=ir(Hi(e));t.push({type:`addDirectories`,directories:n,destination:`session`})}return t}return a?[{type:`setMode`,mode:`acceptEdits`,destination:`session`}]:[]}function N8(e,t){let n=wc(e);if(vst(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Plan files for current session are allowed for writing`}};if(Cst(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Scratchpad files for current session are allowed for writing`}};let r=process.env.CLAUDE_JOB_DIR;if(r){let n=X(m(),`jobs`),i=ir(r).map(wc),a=ir(n).map(wc);if(i.every(e=>a.some(t=>e.startsWith(t+kc)))&&ir(e).every(e=>{let t=wc(e);return i.some(e=>t===e||t.startsWith(e+kc))}))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Job directory files for current job are allowed for writing`}}}return Sd(n)?{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Agent memory files are allowed for writing`}}:!lie()&&ua(n)?{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`auto memory files are allowed for writing`}}:g8(n)===g8(X(Yt(),`.workmate`,`launch.json`))?{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Preview launch config is allowed for writing`}}:{behavior:`passthrough`,message:``}}function P8(e,t){let n=wc(e);if(yst(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Session memory files are allowed for reading`}};if(bst(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Project directory files are allowed for reading`}};if(vst(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Plan files for current session are allowed for reading`}};let r=cS(),i=r.endsWith(kc)?r:r+kc;if(n===r||n.startsWith(i))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Tool result files are allowed for reading`}};if(Cst(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Scratchpad files for current session are allowed for reading`}};let a=b8();if(n.startsWith(a))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Project temp directory files are allowed for reading`}};if(Sd(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Agent memory files are allowed for reading`}};if(ua(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`auto memory files are allowed for reading`}};let o=X(m(),`tasks`)+kc;if(n===o.slice(0,-1)||n.startsWith(o))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Task files are allowed for reading`}};let s=X(m(),`teams`)+kc;if(n===s.slice(0,-1)||n.startsWith(s))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Team files are allowed for reading`}};let c=L8()+kc;return n.startsWith(c)?{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Bundled skill reference files are allowed for reading`}}:{behavior:`passthrough`,message:``}}var Ast,jst,Mst,F8,I8,L8,Nst,R8=n((()=>{Ast=r(ce(),1),d(),ra(),wd(),Ls(),Jt(),Us(),Vn(),g(),or(),Ai(),zd(),ao(),h8(),wi(),vi(),Qy(),vS(),Cr(),QV(),A9(),jst=[`.gitconfig`,`.gitmodules`,`.bashrc`,`.bash_profile`,`.zshrc`,`.zprofile`,`.profile`,`.ripgreprc`,`.mcp.json`,`.workmate.json`],Mst=[`.git`,`.vscode`,`.idea`,`.workmate`],F8=Ec.sep,I8=u(function(){let e=process.env.CLAUDE_CODE_TMPDIR||vc(),t=q(),n=e;try{n=t.realpathSync(e)}catch{}return X(n,xst())+kc}),L8=u(function(){let e=qc(16).toString(`hex`);return X(I8(),`bundled-skills`,`0.0.23`,e)}),Nst=u(ir)}));function z8(){return J8===void 0&&(J8=X(b8(),jn(),`tasks`)),J8}async function B8(){await $c(z8(),{recursive:!0})}function V8(e){return X(z8(),`${e}.output`)}function H8(e){return Y8.add(e),e.finally(()=>Y8.delete(e)).catch(()=>{}),e}async function Pst(){for(;;){try{for(D(Z8,this)||(await B8(),k(Z8,this,await el(D(X8,this),process.platform===`win32`?`a`:Rc.O_WRONLY|Rc.O_APPEND|Rc.O_CREAT|G8)));await S(r5,this,Fst).call(this),D(Q8,this).length!==0;);}finally{if(D(Z8,this)){let e=D(Z8,this);k(Z8,this,null),await e.close()}}if(!D(Q8,this).length)break}}function Fst(){return D(Z8,this).appendFile(S(r5,this,Ist).call(this))}function Ist(){let e=D(Q8,this).splice(0,D(Q8,this).length),t=0;for(let n of e)t+=Buffer.byteLength(n,`utf8`);let n=Buffer.allocUnsafe(t),r=0;for(let t of e)r+=n.write(t,r,`utf8`);return n}async function Lst(){try{await S(r5,this,Pst).call(this)}catch(e){if(J(e),D(Q8,this).length>0)try{await S(r5,this,Pst).call(this)}catch(e){J(e)}}finally{let e=D(n5,this);k(t5,this,null),k(n5,this,null),e()}}function U8(e){return H8((async()=>{let t=i5.get(e);t&&(await t.flush(),i5.delete(e))})())}async function Rst(e,t,n=K8){try{let r=await ur(V8(e),t,n);return r?{content:r.content,newOffset:t+r.bytesRead}:{content:``,newOffset:t}}catch(e){return Xn(e)===`ENOENT`||J(e),{content:``,newOffset:t}}}async function zst(e,t=K8){try{let{content:n,bytesTotal:r,bytesRead:i}=await rr(V8(e),t);return r>i?`[${Math.round((r-i)/1024)}KB of earlier output omitted]\n${n}`:n}catch(e){return Xn(e)===`ENOENT`||J(e),``}}function Bst(e){return H8((async()=>{await B8();let t=V8(e);return await(await el(t,process.platform===`win32`?`wx`:Rc.O_WRONLY|Rc.O_CREAT|Rc.O_EXCL|G8)).close(),t})())}function W8(e,t){return H8((async()=>{try{await B8();let n=V8(e);try{await sl(t,n)}catch{await cl(n),await sl(t,n)}return n}catch(t){return J(t),Bst(e)}})())}var G8,K8,q8,J8,Y8,X8,Z8,Q8,$8,e5,t5,n5,r5,Vst,i5,a5=n((()=>{Jt(),qn(),or(),Ga(),R8(),A(),C(),T(),w(),E(),G8=Rc.O_NOFOLLOW??0,K8=8*1024*1024,q8=5*1024*1024*1024,Y8=new Set,X8=new WeakMap,Z8=new WeakMap,Q8=new WeakMap,$8=new WeakMap,e5=new WeakMap,t5=new WeakMap,n5=new WeakMap,r5=new WeakSet,Vst=class{constructor(e){ee(this,r5),O(this,X8,void 0),O(this,Z8,null),O(this,Q8,[]),O(this,$8,0),O(this,e5,!1),O(this,t5,null),O(this,n5,null),k(X8,this,V8(e))}append(e){D(e5,this)||(k($8,this,D($8,this)+e.length),D($8,this)>5368709120?(k(e5,this,!0),D(Q8,this).push(`
|
|
3068
|
+
`),{encoding:`utf8`})}catch{}})}shouldSkipPersistence(){let e=h(process.env.TEST_ENABLE_SESSION_PERSISTENCE);return v6()===`test`&&!e||fi()?.cleanupPeriodDays===0||Zt()||h(process.env.CLAUDE_CODE_SKIP_PROMPT_HISTORY)}async materializeSessionFile(){if(!this.shouldSkipPersistence()&&(this.ensureCurrentSessionFile(),this.reAppendSessionMetadata(),this.pendingEntries.length>0)){let e=this.pendingEntries;this.pendingEntries=[];for(let t of e)await this.appendEntry(t)}}async insertMessageChain(e,t=!1,n,r,i){return this.trackWrite(async()=>{let a=r??null;this.sessionFile===null&&e.some(e=>e.type===`user`||e.type===`assistant`)&&await this.materializeSessionFile();let o;try{o=await Ci()}catch{o=void 0}let s=jn(),c=ln().get(s);for(let r of e){let e=my(r),l=a;r.type===`user`&&`sourceToolAssistantUUID`in r&&r.sourceToolAssistantUUID&&(l=r.sourceToolAssistantUUID);let u={parentUuid:e?null:l,logicalParentUuid:e?a:void 0,isSidechain:t,agentName:i?.agentName,promptId:r.type===`user`?one()??void 0:void 0,agentId:n,...r,userType:y6(),entrypoint:$at(),cwd:H(),sessionId:s,timestamp:new Date().toISOString(),version:ost,gitBranch:o,slug:c};await this.appendEntry(u),l6(r)&&(a=r.uuid)}if(!t){let t=D6(e);if(t){let e=t.replace(/\n/g,` `).trim();this.currentSessionLastPrompt=e.length>200?`${e.slice(0,200).trim()}…`:e}}})}async insertFileHistorySnapshot(e,t,n){return this.trackWrite(async()=>{let r={type:`file-history-snapshot`,messageId:e,snapshot:t,isSnapshotUpdate:n};await this.appendEntry(r)})}async insertQueueOperation(e){return this.trackWrite(async()=>{await this.appendEntry(e)})}async insertAttributionSnapshot(e){return this.trackWrite(async()=>{await this.appendEntry(e)})}async insertContentReplacement(e,t){return this.trackWrite(async()=>{let n={type:`content-replacement`,sessionId:jn(),agentId:t,replacements:e};await this.appendEntry(n)})}async appendEntry(e,t=jn()){if(this.shouldSkipPersistence())return;let n=t===jn(),r;if(n){if(this.sessionFile===null){this.pendingEntries.push(e);return}r=this.sessionFile}else{let e=await this.getExistingSessionFile(t);if(!e){J(Error(`appendEntry: session file not found for other session ${t}`));return}r=e}if(e.type===`summary`)this.enqueueWrite(r,e);else if(e.type===`custom-title`)this.enqueueWrite(r,e);else if(e.type===`ai-title`)this.enqueueWrite(r,e);else if(e.type===`last-prompt`)this.enqueueWrite(r,e);else if(e.type===`task-summary`)this.enqueueWrite(r,e);else if(e.type===`tag`)this.enqueueWrite(r,e);else if(e.type===`agent-name`)this.enqueueWrite(r,e);else if(e.type===`agent-color`)this.enqueueWrite(r,e);else if(e.type===`agent-setting`)this.enqueueWrite(r,e);else if(e.type===`pr-link`)this.enqueueWrite(r,e);else if(e.type===`file-history-snapshot`)this.enqueueWrite(r,e);else if(e.type===`attribution-snapshot`)this.enqueueWrite(r,e);else if(e.type===`speculation-accept`)this.enqueueWrite(r,e);else if(e.type===`mode`)this.enqueueWrite(r,e);else if(e.type===`worktree-state`)this.enqueueWrite(r,e);else if(e.type===`content-replacement`){let t=e.agentId?h6(e.agentId):r;this.enqueueWrite(t,e)}else if(e.type===`marble-origami-commit`)this.enqueueWrite(r,e);else if(e.type===`marble-origami-snapshot`)this.enqueueWrite(r,e);else if(e.type===`goal`)this.enqueueWrite(r,e);else if(e.type===`goal-cleared`)this.enqueueWrite(r,e);else{let n=await G6(t);if(e.type===`queue-operation`)this.enqueueWrite(r,e);else{let i=e.isSidechain&&e.agentId!==void 0,a=i?h6(oH(e.agentId)):r,o=!n.has(e.uuid);(i||o)&&(this.enqueueWrite(a,e),i||(n.add(e.uuid),c6(e)&&await this.persistToRemote(t,e)))}}}ensureCurrentSessionFile(){return this.sessionFile===null&&(this.sessionFile=d6()),this.sessionFile}async getExistingSessionFile(e){let t=this.existingSessionFiles.get(e);if(t)return t;let n=f6(e);try{if(await ol(n),this.existingSessionFiles.size>=d8){let e=this.existingSessionFiles.keys().next().value;e!==void 0&&this.existingSessionFiles.delete(e)}return this.existingSessionFiles.set(e,n),n}catch(e){if(hr(e))return null;throw e}}async persistToRemote(e,t){if(!Wat()&&this.internalEventWriter){try{await this.internalEventWriter(`transcript`,t,{...my(t)&&{isCompaction:!0},...t.agentId&&{agentId:t.agentId}})}catch{Y(`tengu_session_persistence_failed`,{}),G(`Failed to write transcript as internal event`)}return}}setInternalEventWriter(e){this.internalEventWriter=e,G(`CCR v2 internal event writer registered for transcript persistence`),this.FLUSH_INTERVAL_MS=lst}setInternalEventReader(e){this.internalEventReader=e,G(`CCR v2 internal event reader registered for session resume`)}setInternalSubagentEventReader(e){this.internalSubagentEventReader=e,G(`CCR v2 subagent event reader registered for session resume`)}getInternalEventReader(){return this.internalEventReader}getInternalSubagentEventReader(){return this.internalSubagentEventReader}},f8=[`"type":"summary"`,`"type":"custom-title"`,`"type":"tag"`,`"type":"agent-name"`,`"type":"agent-color"`,`"type":"agent-setting"`,`"type":"mode"`,`"type":"worktree-state"`,`"type":"goal"`,`"type":"goal-cleared"`,`"type":"pr-link"`].map(e=>Buffer.from(e)),dst=25,p8=new Map,m8=50}));function g8(e){return e.toLowerCase()}function fst(e){let t=hi(e),n=g8(t),r=[{dir:hi(X(Yt(),`.workmate`,`skills`)),prefix:`/.workmate/skills/`},{dir:hi(X(_c(),`.workmate`,`skills`)),prefix:`~/.workmate/skills/`}];for(let{dir:e,prefix:i}of r){let r=g8(e);for(let a of[kc,`/`])if(n.startsWith(r+a.toLowerCase())){let n=t.slice(e.length+a.length),r=n.indexOf(`/`),o=kc===`\\`?n.indexOf(`\\`):-1,s=r===-1?o:o===-1?r:Math.min(r,o);if(s<=0)return null;let c=n.slice(0,s);return!c||c===`.`||c.includes(`..`)||/[*?[\]]/.test(c)?null:{skillName:c,pattern:`${i+c}/**`}}}return null}function pst(e,t){if(io()===`windows`){let n=Er(e),r=Er(t);return Ec.relative(n,r)}return Ec.relative(e,t)}function mst(e){return io()===`windows`?Er(e):e}function hst(){return ki.map(e=>ji(e)).filter(e=>e!==void 0)}function gst(e){let t=g8(hi(e));return t.endsWith(`${kc}.workmate${kc}settings.json`)||t.endsWith(`${kc}.workmate${kc}settings.local.json`)?!0:hst().some(e=>g8(e)===t)}function _st(e){if(gst(e))return!0;let t=X(Yt(),`.workmate`,`commands`),n=X(Yt(),`.workmate`,`agents`),r=X(Yt(),`.workmate`,`skills`);return T8(e,t)||T8(e,n)||T8(e,r)}function vst(e){let t=X(Rd(),jd()),n=wc(e);return n.startsWith(t)&&n.endsWith(`.md`)}function _8(){return X(c8(H()),jn(),`session-memory`)+kc}function v8(){return X(_8(),`summary.md`)}function yst(e){return wc(e).startsWith(_8())}function bst(e){let t=c8(H()),n=wc(e);return n===t||n.startsWith(t+kc)}function y8(){return!1}function xst(){return io()===`windows`?`claude`:`claude-${process.getuid?.()??0}`}function b8(){return X(I8(),qi(Yt()))+kc}function x8(){return X(b8(),jn(),`scratchpad`)}async function Sst(){if(!y8())throw Error(`Scratchpad directory feature is not enabled`);let e=q(),t=x8();return await e.mkdir(t,{mode:448}),t}function Cst(e){if(!y8())return!1;let t=x8(),n=wc(e);return n===t||n.startsWith(t+kc)}function wst(e){let t=hi(e).split(kc),n=t.at(-1);if(e.startsWith(`\\\\`)||e.startsWith(`//`))return!0;for(let e=0;e<t.length;e++){let n=t[e],r=g8(n);for(let n of Mst)if(r===g8(n)){if(n===`.workmate`){let n=t[e+1];if(n&&g8(n)===`worktrees`)break}return!0}}if(n){let e=g8(n);if(jst.some(t=>g8(t)===e))return!0}return!1}function Tst(e){return!!((io()===`windows`||io()===`wsl`)&&e.indexOf(`:`,2)!==-1||/~\d/.test(e)||e.startsWith(`\\\\?\\`)||e.startsWith(`\\\\.\\`)||e.startsWith(`//?/`)||e.startsWith(`//./`)||/[.\s]+$/.test(e)||/\.(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i.test(e)||/(^|\/|\\)\.{3,}(\/|\\|$)/.test(e)||Ry(e))}function S8(e,t){let n=t??ir(e);for(let t of n)if(Tst(t))return{safe:!1,message:`Work Mate requested permissions to write to ${e}, which contains a suspicious Windows path pattern that requires manual approval.`,classifierApprovable:!1};for(let t of n)if(_st(t))return{safe:!1,message:`Work Mate requested permissions to write to ${e}, but you haven't granted it yet.`,classifierApprovable:!0};for(let t of n)if(wst(t))return{safe:!1,message:`Work Mate requested permissions to edit ${e} which is a sensitive file.`,classifierApprovable:!0};return{safe:!0}}function C8(e){return new Set([Yt(),...e.additionalWorkingDirectories.keys()])}function w8(e,t,n){let r=n??ir(e),i=Array.from(C8(t)).flatMap(e=>Nst(e));return r.every(e=>i.some(t=>T8(e,t)))}function T8(e,t){let n=hi(e),r=hi(t),i=n.replace(/^\/private\/var\//,`/var/`).replace(/^\/private\/tmp(\/|$)/,`/tmp$1`),a=r.replace(/^\/private\/var\//,`/var/`).replace(/^\/private\/tmp(\/|$)/,`/tmp$1`),o=g8(i),s=pst(g8(a),o);return s===``||!gr(s)&&!Ec.isAbsolute(s)}function Est(e){switch(e){case`cliArg`:case`command`:case`session`:return hi(Yt());case`userSettings`:case`policySettings`:case`projectSettings`:case`localSettings`:case`flagSettings`:return ui(e)}}function E8(e){return Ec.join(F8,e)}function Dst({patternRoot:e,pattern:t,rootPath:n}){let r=Ec.join(e,t);if(e===n)return E8(t);if(r.startsWith(`${n}${F8}`))return E8(r.slice(n.length));{let r=Ec.relative(n,e);return!r||r.startsWith(`..${F8}`)||r===`..`?null:E8(Ec.join(r,t))}}function D8(e,t){let n=new Set(e.get(null)??[]);for(let[r,i]of e.entries())if(r!==null)for(let e of i){let i=Dst({patternRoot:r,pattern:e,rootPath:t});i&&n.add(i)}return Array.from(n)}function O8(e){let t=kst(e,`read`,`deny`),n=new Map;for(let[e,r]of t.entries())n.set(e,Array.from(r.keys()));return n}function Ost(e,t){if(e.startsWith(`${F8}${F8}`)){let t=e.slice(1);if(io()===`windows`&&t.match(/^\/[a-z]\//i)){let e=t[1]?.toUpperCase()??`C`,n=t.slice(2),r=`${e}:\\`;return{relativePattern:n.startsWith(`/`)?n.slice(1):n,root:r}}return{relativePattern:t,root:F8}}else if(e.startsWith(`~${F8}`))return{relativePattern:e.slice(1),root:_c().normalize(`NFC`)};else if(e.startsWith(F8))return{relativePattern:e,root:Est(t)};let n=e;return e.startsWith(`.${F8}`)&&(n=e.slice(2)),{relativePattern:n,root:null}}function kst(e,t,n){let r=E9(e,(()=>{switch(t){case`edit`:return Gs;case`read`:return ys}})(),n),i=new Map;for(let[e,t]of r.entries()){let{relativePattern:n,root:r}=Ost(e,t.source),a=i.get(r);a===void 0&&(a=new Map,i.set(r,a)),a.set(n,t)}return i}function k8(e,t,n,r){let i=hi(e);io()===`windows`&&i.includes(`\\`)&&(i=Er(i));let a=kst(t,n,r);for(let[e,t]of a.entries()){let n=Array.from(t.keys()).map(e=>{let t=e;return t.endsWith(`/**`)&&(t=t.slice(0,-3)),t}),r=(0,Ast.default)().add(n),a=pst(e??H(),i??H());if(a.startsWith(`..${F8}`)||!a)continue;let o=r.test(a);if(o.ignored&&o.rule){let e=o.rule.pattern,n=`${e}/**`;return t.has(n)?t.get(n)??null:t.get(e)??null}}return null}function A8(e,t,n){if(typeof e.getPath!=`function`)return{behavior:`ask`,message:`Work Mate requested permissions to use ${e.name}, but you haven't granted it yet.`};let r=e.getPath(t),i=ir(r);for(let e of i)if(e.startsWith(`\\\\`)||e.startsWith(`//`))return{behavior:`ask`,message:`Work Mate requested permissions to read from ${r}, which appears to be a UNC path that could access network resources.`,decisionReason:{type:`other`,reason:`UNC path detected (defense-in-depth check)`}};for(let e of i)if(Tst(e))return{behavior:`ask`,message:`Work Mate requested permissions to read from ${r}, which contains a suspicious Windows path pattern that requires manual approval.`,decisionReason:{type:`other`,reason:`Path contains suspicious Windows-specific patterns (alternate data streams, short names, long path prefixes, or three or more consecutive dots) that require manual verification`}};for(let e of i){let t=k8(e,n,`read`,`deny`);if(t)return{behavior:`deny`,message:`Permission to read ${r} has been denied.`,decisionReason:{type:`rule`,rule:t}}}for(let e of i){let t=k8(e,n,`read`,`ask`);if(t)return{behavior:`ask`,message:`Work Mate requested permissions to read from ${r}, but you haven't granted it yet.`,decisionReason:{type:`rule`,rule:t}}}let a=j8(e,t,n,i);if(a.behavior===`allow`)return a;if(w8(r,n,i))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`mode`,mode:`default`}};let o=P8(hi(r),t);if(o.behavior!==`passthrough`)return o;let s=k8(r,n,`read`,`allow`);return s?{behavior:`allow`,updatedInput:t,decisionReason:{type:`rule`,rule:s}}:{behavior:`ask`,message:`Work Mate requested permissions to read from ${r}, but you haven't granted it yet.`,suggestions:M8(r,`read`,n,i),decisionReason:{type:`workingDir`,reason:`Path is outside allowed working directories`}}}function j8(e,t,n,r){if(typeof e.getPath!=`function`)return{behavior:`ask`,message:`Work Mate requested permissions to use ${e.name}, but you haven't granted it yet.`};let i=e.getPath(t),a=r??ir(i);for(let e of a){let t=k8(e,n,`edit`,`deny`);if(t)return{behavior:`deny`,message:`Permission to edit ${i} has been denied.`,decisionReason:{type:`rule`,rule:t}}}let o=N8(hi(i),t);if(o.behavior!==`passthrough`)return o;let s=k8(i,{...n,alwaysAllowRules:{session:n.alwaysAllowRules.session??[]}},`edit`,`allow`);if(s){let e=s.ruleValue.ruleContent;if(e&&(e.startsWith(`/.workmate/**`.slice(0,-2))||e.startsWith(`~/.workmate/**`.slice(0,-2)))&&!e.includes(`..`)&&e.endsWith(`/**`))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`rule`,rule:s}}}let c=S8(i,a);if(!c.safe){let e=fst(i),t=e?[{type:`addRules`,rules:[{toolName:Gs,ruleContent:e.pattern}],behavior:`allow`,destination:`session`}]:M8(i,`write`,n,a),r=c;return{behavior:`ask`,message:r.message,suggestions:t,decisionReason:{type:`safetyCheck`,reason:r.message,classifierApprovable:r.classifierApprovable}}}for(let e of a){let t=k8(e,n,`edit`,`ask`);if(t)return{behavior:`ask`,message:`Work Mate requested permissions to write to ${i}, but you haven't granted it yet.`,decisionReason:{type:`rule`,rule:t}}}let l=w8(i,n,a);if(n.mode===`acceptEdits`&&l)return{behavior:`allow`,updatedInput:t,decisionReason:{type:`mode`,mode:n.mode}};let u=k8(i,n,`edit`,`allow`);return u?{behavior:`allow`,updatedInput:t,decisionReason:{type:`rule`,rule:u}}:{behavior:`ask`,message:`Work Mate requested permissions to write to ${i}, but you haven't granted it yet.`,suggestions:M8(i,`write`,n,a),decisionReason:l?void 0:{type:`workingDir`,reason:`Path is outside allowed working directories`}}}function M8(e,t,n,r){let i=!w8(e,n,r);if(t===`read`&&i)return ir(Hi(e)).map(e=>ZV(e,`session`)).filter(e=>e!==void 0);let a=n.mode==="default"||n.mode===`plan`;if(t===`write`||t===`create`){let t=a?[{type:`setMode`,mode:`acceptEdits`,destination:`session`}]:[];if(i){let n=ir(Hi(e));t.push({type:`addDirectories`,directories:n,destination:`session`})}return t}return a?[{type:`setMode`,mode:`acceptEdits`,destination:`session`}]:[]}function N8(e,t){let n=wc(e);if(vst(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Plan files for current session are allowed for writing`}};if(Cst(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Scratchpad files for current session are allowed for writing`}};let r=process.env.CLAUDE_JOB_DIR;if(r){let n=X(m(),`jobs`),i=ir(r).map(wc),a=ir(n).map(wc);if(i.every(e=>a.some(t=>e.startsWith(t+kc)))&&ir(e).every(e=>{let t=wc(e);return i.some(e=>t===e||t.startsWith(e+kc))}))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Job directory files for current job are allowed for writing`}}}return Sd(n)?{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Agent memory files are allowed for writing`}}:!lie()&&ua(n)?{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`auto memory files are allowed for writing`}}:g8(n)===g8(X(Yt(),`.workmate`,`launch.json`))?{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Preview launch config is allowed for writing`}}:{behavior:`passthrough`,message:``}}function P8(e,t){let n=wc(e);if(yst(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Session memory files are allowed for reading`}};if(bst(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Project directory files are allowed for reading`}};if(vst(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Plan files for current session are allowed for reading`}};let r=cS(),i=r.endsWith(kc)?r:r+kc;if(n===r||n.startsWith(i))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Tool result files are allowed for reading`}};if(Cst(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Scratchpad files for current session are allowed for reading`}};let a=b8();if(n.startsWith(a))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Project temp directory files are allowed for reading`}};if(Sd(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Agent memory files are allowed for reading`}};if(ua(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`auto memory files are allowed for reading`}};let o=X(m(),`tasks`)+kc;if(n===o.slice(0,-1)||n.startsWith(o))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Task files are allowed for reading`}};let s=X(m(),`teams`)+kc;if(n===s.slice(0,-1)||n.startsWith(s))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Team files are allowed for reading`}};let c=L8()+kc;return n.startsWith(c)?{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Bundled skill reference files are allowed for reading`}}:{behavior:`passthrough`,message:``}}var Ast,jst,Mst,F8,I8,L8,Nst,R8=n((()=>{Ast=r(ce(),1),d(),ra(),wd(),Ls(),Jt(),Us(),Vn(),g(),or(),Ai(),zd(),ao(),h8(),wi(),vi(),Qy(),vS(),Cr(),QV(),A9(),jst=[`.gitconfig`,`.gitmodules`,`.bashrc`,`.bash_profile`,`.zshrc`,`.zprofile`,`.profile`,`.ripgreprc`,`.mcp.json`,`.workmate.json`],Mst=[`.git`,`.vscode`,`.idea`,`.workmate`],F8=Ec.sep,I8=u(function(){let e=process.env.CLAUDE_CODE_TMPDIR||vc(),t=q(),n=e;try{n=t.realpathSync(e)}catch{}return X(n,xst())+kc}),L8=u(function(){let e=qc(16).toString(`hex`);return X(I8(),`bundled-skills`,`0.0.24`,e)}),Nst=u(ir)}));function z8(){return J8===void 0&&(J8=X(b8(),jn(),`tasks`)),J8}async function B8(){await $c(z8(),{recursive:!0})}function V8(e){return X(z8(),`${e}.output`)}function H8(e){return Y8.add(e),e.finally(()=>Y8.delete(e)).catch(()=>{}),e}async function Pst(){for(;;){try{for(D(Z8,this)||(await B8(),k(Z8,this,await el(D(X8,this),process.platform===`win32`?`a`:Rc.O_WRONLY|Rc.O_APPEND|Rc.O_CREAT|G8)));await S(r5,this,Fst).call(this),D(Q8,this).length!==0;);}finally{if(D(Z8,this)){let e=D(Z8,this);k(Z8,this,null),await e.close()}}if(!D(Q8,this).length)break}}function Fst(){return D(Z8,this).appendFile(S(r5,this,Ist).call(this))}function Ist(){let e=D(Q8,this).splice(0,D(Q8,this).length),t=0;for(let n of e)t+=Buffer.byteLength(n,`utf8`);let n=Buffer.allocUnsafe(t),r=0;for(let t of e)r+=n.write(t,r,`utf8`);return n}async function Lst(){try{await S(r5,this,Pst).call(this)}catch(e){if(J(e),D(Q8,this).length>0)try{await S(r5,this,Pst).call(this)}catch(e){J(e)}}finally{let e=D(n5,this);k(t5,this,null),k(n5,this,null),e()}}function U8(e){return H8((async()=>{let t=i5.get(e);t&&(await t.flush(),i5.delete(e))})())}async function Rst(e,t,n=K8){try{let r=await ur(V8(e),t,n);return r?{content:r.content,newOffset:t+r.bytesRead}:{content:``,newOffset:t}}catch(e){return Xn(e)===`ENOENT`||J(e),{content:``,newOffset:t}}}async function zst(e,t=K8){try{let{content:n,bytesTotal:r,bytesRead:i}=await rr(V8(e),t);return r>i?`[${Math.round((r-i)/1024)}KB of earlier output omitted]\n${n}`:n}catch(e){return Xn(e)===`ENOENT`||J(e),``}}function Bst(e){return H8((async()=>{await B8();let t=V8(e);return await(await el(t,process.platform===`win32`?`wx`:Rc.O_WRONLY|Rc.O_CREAT|Rc.O_EXCL|G8)).close(),t})())}function W8(e,t){return H8((async()=>{try{await B8();let n=V8(e);try{await sl(t,n)}catch{await cl(n),await sl(t,n)}return n}catch(t){return J(t),Bst(e)}})())}var G8,K8,q8,J8,Y8,X8,Z8,Q8,$8,e5,t5,n5,r5,Vst,i5,a5=n((()=>{Jt(),qn(),or(),Ga(),R8(),A(),C(),T(),w(),E(),G8=Rc.O_NOFOLLOW??0,K8=8*1024*1024,q8=5*1024*1024*1024,Y8=new Set,X8=new WeakMap,Z8=new WeakMap,Q8=new WeakMap,$8=new WeakMap,e5=new WeakMap,t5=new WeakMap,n5=new WeakMap,r5=new WeakSet,Vst=class{constructor(e){ee(this,r5),O(this,X8,void 0),O(this,Z8,null),O(this,Q8,[]),O(this,$8,0),O(this,e5,!1),O(this,t5,null),O(this,n5,null),k(X8,this,V8(e))}append(e){D(e5,this)||(k($8,this,D($8,this)+e.length),D($8,this)>5368709120?(k(e5,this,!0),D(Q8,this).push(`
|
|
3069
3069
|
[output truncated: exceeded 5GB disk cap]
|
|
3070
3070
|
`)):D(Q8,this).push(e),D(t5,this)||(k(t5,this,new Promise(e=>{k(n5,this,e)})),H8(S(r5,this,Lst).call(this))))}flush(){return D(t5,this)??Promise.resolve()}cancel(){D(Q8,this).length=0}},i5=new Map}));function Hst(e){return e===`completed`||e===`failed`||e===`killed`}function Ust(e){return Wst[e]??`x`}function o5(e){let t=Ust(e),n=qc(8),r=t;for(let e=0;e<8;e++)r+=Gst[n[e]%36];return r}function s5(e,t,n,r){return{id:e,type:t,status:`pending`,description:n,toolUseId:r,startTime:Date.now(),outputFile:V8(e),outputOffset:0,notified:!1}}var Wst,Gst,c5=n((()=>{a5(),Wst={local_bash:`b`,local_agent:`a`,local_workflow:`w`,dream:`d`},Gst=`0123456789abcdefghijklmnopqrstuvwxyz`}));function Kst(e,t){return t?`${e} ${t}`:e}function qst(e){let t=typeof e==`string`?e:e.toString();D(_5,this)?D(g5,this).writeStderr(t):D(g5,this).writeStdout(t)}function Jst(e){D(N5,e)&&D(j5,e)?D(j5,e).call(e,e.background.bind(e)):S(L5,e,d5).call(e,p5)}function Yst(){D(A5,this).reason!==`interrupt`&&this.kill()}function Xst(e,t){let n=e??(t===`SIGTERM`?144:1);S(L5,this,l5).call(this,n)}function Zst(){S(L5,this,l5).call(this,1)}function l5(e){D(F5,this)&&(D(F5,this).call(this,e),k(F5,this,null))}function u5(){S(L5,this,Qst).call(this);let e=D(E5,this);e&&(clearTimeout(e),k(E5,this,null));let t=D(I5,this);t&&(D(A5,this).removeEventListener(`abort`,t),k(I5,this,null))}function Qst(){D(D5,this)&&(clearInterval(D(D5,this)),k(D5,this,null))}function $st(){k(D5,this,setInterval(()=>{ol(this.taskOutput.path).then(e=>{e.size>D(k5,this)&&D(x5,this)===`backgrounded`&&D(D5,this)!==null&&(k(O5,this,!0),S(L5,this,Qst).call(this),S(L5,this,d5).call(this,f5))},()=>{})},oct)),D(D5,this).unref()}function ect(){k(I5,this,S(L5,this,Yst).bind(this)),D(A5,this).addEventListener(`abort`,D(I5,this),{once:!0}),D(T5,this).once(`exit`,S(L5,this,Xst).bind(this)),D(T5,this).once(`error`,S(L5,this,Zst).bind(this)),k(E5,this,setTimeout(Jst,D(M5,this),this));let e=new Promise(e=>{k(F5,this,e)});return new Promise(t=>{k(P5,this,t),e.then(S(L5,this,tct).bind(this))})}async function tct(e){S(L5,this,u5).call(this),(D(x5,this)===`running`||D(x5,this)===`backgrounded`)&&k(x5,this,`completed`);let t={code:e,stdout:await this.taskOutput.getStdout(),stderr:this.taskOutput.getStderr(),interrupted:e===f5,backgroundTaskId:D(S5,this)};this.taskOutput.stdoutToFile&&!D(S5,this)&&(this.taskOutput.outputFileRedundant?this.taskOutput.deleteOutputFile():(t.outputFilePath=this.taskOutput.path,t.outputFileSize=this.taskOutput.outputFileSize,t.outputTaskId=this.taskOutput.taskId)),D(O5,this)?t.stderr=Kst(`Background command killed: output file exceeded 5GB`,t.stderr):e===p5&&(t.stderr=Kst(`Command timed out after ${po(D(M5,this))}`,t.stderr));let n=D(P5,this);n&&(k(P5,this,null),n(t))}function d5(e){k(x5,this,`killed`),D(T5,this).pid&&(0,act.default)(D(T5,this).pid,`SIGKILL`),S(L5,this,l5).call(this,e??f5)}function nct(e,t,n,r,i=!1,a=q8){return new sct(e,t,n,r,i,a)}function rct(e,t){return new cct({backgroundTaskId:e,...t})}function ict(e){let t=new tx(o5(`local_bash`),null);return{status:`completed`,result:Promise.resolve({code:1,stdout:``,stderr:e,interrupted:!1,preSpawnError:e}),taskOutput:t,background(){return!1},kill(){},cleanup(){}}}var act,f5,p5,oct,m5,h5,g5,_5,v5,y5,b5,x5,S5,C5,w5,T5,E5,D5,O5,k5,A5,j5,M5,N5,P5,F5,I5,L5,sct,cct,lct=n((()=>{act=r($ue(),1),c5(),so(),a5(),ax(),A(),C(),E(),T(),w(),b(),f5=137,p5=143,oct=5e3,m5=new WeakMap,h5=new WeakMap,g5=new WeakMap,_5=new WeakMap,v5=new WeakMap,y5=new WeakSet,b5=class{constructor(e,t,n){ee(this,y5),O(this,m5,void 0),O(this,h5,!1),O(this,g5,void 0),O(this,_5,void 0),O(this,v5,S(y5,this,qst).bind(this)),k(m5,this,e),k(g5,this,t),k(_5,this,n),e.setEncoding(`utf-8`),e.on(`data`,D(v5,this))}cleanup(){D(h5,this)||(k(h5,this,!0),D(m5,this).removeListener(`data`,D(v5,this)),k(m5,this,null),k(g5,this,null),k(v5,this,()=>{}))}},x5=new WeakMap,S5=new WeakMap,C5=new WeakMap,w5=new WeakMap,T5=new WeakMap,E5=new WeakMap,D5=new WeakMap,O5=new WeakMap,k5=new WeakMap,A5=new WeakMap,j5=new WeakMap,M5=new WeakMap,N5=new WeakMap,P5=new WeakMap,F5=new WeakMap,I5=new WeakMap,L5=new WeakSet,sct=class{constructor(e,t,n,r,i=!1,a=q8){ee(this,L5),O(this,x5,`running`),O(this,S5,void 0),O(this,C5,void 0),O(this,w5,void 0),O(this,T5,void 0),O(this,E5,null),O(this,D5,null),O(this,O5,!1),O(this,k5,void 0),O(this,A5,void 0),O(this,j5,void 0),O(this,M5,void 0),O(this,N5,void 0),O(this,P5,null),O(this,F5,null),O(this,I5,null),x(this,`taskOutput`,void 0),x(this,`result`,void 0),x(this,`onTimeout`,void 0),k(T5,this,e),k(A5,this,t),k(M5,this,n),k(N5,this,i),k(k5,this,a),this.taskOutput=r,k(w5,this,e.stderr?new b5(e.stderr,r,!0):null),k(C5,this,e.stdout?new b5(e.stdout,r,!1):null),i&&(this.onTimeout=e=>{k(j5,this,e)}),this.result=S(L5,this,ect).call(this)}get status(){return D(x5,this)}kill(){S(L5,this,d5).call(this)}background(e){return D(x5,this)===`running`?(k(S5,this,e),k(x5,this,`backgrounded`),S(L5,this,u5).call(this),this.taskOutput.stdoutToFile?S(L5,this,$st).call(this):this.taskOutput.spillToDisk(),!0):!1}cleanup(){D(C5,this)?.cleanup(),D(w5,this)?.cleanup(),this.taskOutput.clear(),S(L5,this,u5).call(this),k(T5,this,null),k(A5,this,null),k(j5,this,void 0)}},cct=class{constructor(e){x(this,`status`,`killed`),x(this,`result`,void 0),x(this,`taskOutput`,void 0),this.taskOutput=new tx(o5(`local_bash`),null),this.result=Promise.resolve({code:e?.code??145,stdout:``,stderr:e?.stderr??`Command aborted before execution`,interrupted:!0,backgroundTaskId:e?.backgroundTaskId})}background(){return!1}kill(){}cleanup(){}}})),R5,z5,uct=n((()=>{Nt(),kt(),R5=V(()=>bt.enum([`allow`,`deny`,`ask`])),z5=V(()=>bt.object({toolName:bt.string(),ruleContent:bt.string().optional()}))})),B5,V5,dct=n((()=>{Nt(),kt(),xi(),uct(),B5=V(()=>bt.enum([`userSettings`,`projectSettings`,`localSettings`,`session`,`cliArg`])),V5=V(()=>bt.discriminatedUnion(`type`,[bt.object({type:bt.literal(`addRules`),rules:bt.array(z5()),behavior:R5(),destination:B5()}),bt.object({type:bt.literal(`replaceRules`),rules:bt.array(z5()),behavior:R5(),destination:B5()}),bt.object({type:bt.literal(`removeRules`),rules:bt.array(z5()),behavior:R5(),destination:B5()}),bt.object({type:bt.literal(`setMode`),mode:Fre(),destination:B5()}),bt.object({type:bt.literal(`addDirectories`),directories:bt.array(bt.string()),destination:B5()}),bt.object({type:bt.literal(`removeDirectories`),directories:bt.array(bt.string()),destination:B5()})]))}));function H5(e){return!(`async`in e&&e.async===!0)}function U5(e){return`async`in e&&e.async===!0}var fct,pct,W5,mct=n((()=>{Nt(),kt(),Dr(),uct(),dct(),fct=V(()=>I({prompt:B(),message:B(),options:L(I({key:B(),label:B(),description:B().optional()}))})),pct=V(()=>I({continue:pt().describe(`Whether Work Mate should continue after hook (default: true)`).optional(),suppressOutput:pt().describe(`Hide stdout from transcript (default: false)`).optional(),stopReason:B().describe(`Message shown when continue is false`).optional(),decision:ft([`approve`,`block`]).optional(),reason:B().describe(`Explanation for the decision`).optional(),systemMessage:B().describe(`Warning message shown to the user`).optional(),hookSpecificOutput:yt([I({hookEventName:R(`PreToolUse`),permissionDecision:R5().optional(),permissionDecisionReason:B().optional(),updatedInput:St(B(),dt()).optional(),additionalContext:B().optional()}),I({hookEventName:R(`UserPromptSubmit`),additionalContext:B().optional()}),I({hookEventName:R(`SessionStart`),additionalContext:B().optional(),initialUserMessage:B().optional(),watchPaths:L(B()).describe(`Absolute paths to watch for FileChanged hooks`).optional()}),I({hookEventName:R(`Setup`),additionalContext:B().optional()}),I({hookEventName:R(`SubagentStart`),additionalContext:B().optional()}),I({hookEventName:R(`PostToolUse`),additionalContext:B().optional(),updatedMCPToolOutput:dt().describe(`Updates the output for MCP tools`).optional()}),I({hookEventName:R(`PostToolUseFailure`),additionalContext:B().optional()}),I({hookEventName:R(`PermissionDenied`),retry:pt().optional()}),I({hookEventName:R(`Notification`),additionalContext:B().optional()}),I({hookEventName:R(`PermissionRequest`),decision:yt([I({behavior:R(`allow`),updatedInput:St(B(),dt()).optional(),updatedPermissions:L(V5()).optional()}),I({behavior:R(`deny`),message:B().optional(),interrupt:pt().optional()})])}),I({hookEventName:R(`Elicitation`),action:ft([`accept`,`decline`,`cancel`]).optional(),content:St(B(),dt()).optional()}),I({hookEventName:R(`ElicitationResult`),action:ft([`accept`,`decline`,`cancel`]).optional(),content:St(B(),dt()).optional()}),I({hookEventName:R(`CwdChanged`),watchPaths:L(B()).describe(`Absolute paths to watch for FileChanged hooks`).optional()}),I({hookEventName:R(`FileChanged`),watchPaths:L(B()).describe(`Absolute paths to watch for FileChanged hooks`).optional()}),I({hookEventName:R(`WorktreeCreate`),worktreePath:B()})]).optional()})),W5=V(()=>yt([I({async:R(!0),asyncTimeout:z().optional()}),pct()]))}));function G5(e,t){let{signalB:n,timeoutMs:r}=t??{},i=BO();if(e?.aborted||n?.aborted)return i.abort(),{signal:i.signal,cleanup:()=>{}};let a,o=()=>{a!==void 0&&clearTimeout(a),i.abort()};return r!==void 0&&(a=setTimeout(o,r),a.unref?.()),e?.addEventListener(`abort`,o),n?.addEventListener(`abort`,o),{signal:i.signal,cleanup:()=>{a!==void 0&&clearTimeout(a),e?.removeEventListener(`abort`,o),n?.removeEventListener(`abort`,o)}}}var K5=n((()=>{UO()}));function hct(e,t){return b2(e,t)}function gct(){return{...soe,inputSchema:q5(),inputJSONSchema:{type:`object`,properties:{ok:{type:`boolean`,description:`Whether the condition was met`},reason:{type:`string`,description:`Reason, if the condition was not met`}},required:[`ok`],additionalProperties:!1},async prompt(){return`Use this tool to return your verification result. You MUST call this tool exactly once at the end of your response.`}}}function _ct(e,t){AGe(e,t,`Stop`,``,e=>Rrt(e,Fs),`You MUST call the ${Fs} tool to complete this request. Call this tool now.`,{timeout:5e3})}var q5,J5=n((()=>{Nt(),Ss(),x2(),kt(),h3(),wY(),q5=V(()=>I({ok:pt().describe(`Whether the condition was met`),reason:B().describe(`Reason, if the condition was not met`).optional()}))}));async function vct(e,t,n,r,i,a,o,s){let c=s||`hook-${Jc()}`;try{let s=hct(e.prompt,r);G(`Hooks: Processing prompt hook with prompt: ${s}`);let l=Q({content:s}),u=o&&o.length>0?[...o,l]:[l];G(`Hooks: Querying model with ${u.length} messages`);let{signal:d,cleanup:f}=G5(i,{timeoutMs:e.timeout?e.timeout*1e3:3e4});try{let r=await X7({messages:u,systemPrompt:gv([`You are evaluating a hook in Work Mate.
|
|
3071
3071
|
|
|
@@ -3078,7 +3078,7 @@ Use as few steps as possible - be efficient and direct.
|
|
|
3078
3078
|
|
|
3079
3079
|
When done, return your result using the ${Fs} tool with:
|
|
3080
3080
|
- ok: true if the condition is met
|
|
3081
|
-
- ok: false with reason if the condition is not met`]),f=e.model??Jo(),_=oH(`hook-agent-${Jc()}`),v={...a,agentId:_,abortController:p,options:{...a.options,tools:i,mainLoopModel:f,isNonInteractiveSession:!0,thinkingConfig:{type:`disabled`}},setInProgressToolUseIDs:()=>{},getAppState(){let e=a.getAppState(),t=e.toolPermissionContext.alwaysAllowRules.session??[];return{...e,toolPermissionContext:{...e.toolPermissionContext,mode:`dontAsk`,alwaysAllowRules:{...e.toolPermissionContext.alwaysAllowRules,session:[...t,`Read(/${u})`]}}}}};_ct(a.setAppState,_);let y=null,b=0,x=!1;for await(let e of Q1({messages:s,systemPrompt:o,userContext:{},systemContext:{},canUseTool:k9,toolUseContext:v,querySource:`hook_agent`}))if(Sit(e,()=>{},e=>a.setResponseLength(t=>t+e.length),a.setStreamMode??(()=>{}),()=>{}),!(e.type===`stream_event`||e.type===`stream_request_start`)){if(e.type===`assistant`&&(b++,b>=50)){x=!0,G(`Hooks: Agent turn ${b} hit max turns, aborting`),p.abort();break}if(bct(e)){let t=q5().safeParse(e.attachment.data);if(t.success){y=t.data,G(`Hooks: Got structured output: ${U(y)}`),p.abort();break}}}return m.removeEventListener(`abort`,g),h(),CY(a.setAppState,_),y?y.ok?(G(`Hooks: Agent hook condition was met`),Y(`tengu_agent_stop_hook_success`,{durationMs:Date.now()-d,turnCount:b,agentName:c}),{hook:e,outcome:`success`,message:r2({type:`hook_success`,hookName:t,toolUseID:l,hookEvent:n,content:``})}):(G(`Hooks: Agent hook condition was not met: ${y.reason}`),{hook:e,outcome:`blocking`,blockingError:{blockingError:`Agent hook condition was not met: ${y.reason}`,command:e.prompt}}):x?(G(`Hooks: Agent hook did not complete within 50 turns`),Y(`tengu_agent_stop_hook_max_turns`,{durationMs:Date.now()-d,turnCount:b,agentName:c}),{hook:e,outcome:`cancelled`}):(G(`Hooks: Agent hook did not return structured output`),Y(`tengu_agent_stop_hook_error`,{durationMs:Date.now()-d,turnCount:b,errorType:1,agentName:c}),{hook:e,outcome:`cancelled`})}catch(t){if(m.removeEventListener(`abort`,g),h(),_.aborted)return{hook:e,outcome:`cancelled`};throw t}}catch(r){let i=W(r);return G(`Hooks: Agent hook error: ${i}`),Y(`tengu_agent_stop_hook_error`,{durationMs:Date.now()-d,errorType:2,agentName:c}),{hook:e,outcome:`non_blocking_error`,message:r2({type:`hook_non_blocking_error`,hookName:t,toolUseID:l,hookEvent:n,stderr:`Error executing agent hook: ${i}`,stdout:``,exitCode:1})}}}var Sct=n((()=>{$1(),oo(),Ks(),Ss(),E1(),sH(),UO(),m2(),K5(),K(),qn(),h3(),Uo(),A9(),h8(),mr(),cF(),J5(),wY()}));function Cct(e){let t=Nce(e);return t===4?wct(e):t===6&&Tct(e)}function wct(e){let t=e.split(`.`).map(Number),[n,r]=t;return t.length!==4||n===void 0||r===void 0||t.some(e=>Number.isNaN(e))||n===127?!1:n===0||n===10||n===169&&r===254||n===172&&r>=16&&r<=31||n===100&&r>=64&&r<=127||n===192&&r===168}function Tct(e){let t=e.toLowerCase();if(t===`::1`)return!1;if(t===`::`)return!0;let n=Dct(t);if(n!==null)return wct(n);if(t.startsWith(`fc`)||t.startsWith(`fd`))return!0;let r=t.split(`:`)[0];return!!(r&&r.length===4&&r>=`fe80`&&r<=`febf`)}function Ect(e){let t=[];if(e.includes(`.`)){let n=e.lastIndexOf(`:`),r=e.slice(n+1);e=e.slice(0,n);let i=r.split(`.`).map(Number);if(i.length!==4||i.some(e=>!Number.isInteger(e)||e<0||e>255))return null;t=[i[0]<<8|i[1],i[2]<<8|i[3]]}let n=e.indexOf(`::`),r,i;if(n===-1)r=e.split(`:`),i=[];else{let t=e.slice(0,n),a=e.slice(n+2);r=t===``?[]:t.split(`:`),i=a===``?[]:a.split(`:`)}let a=8-t.length-r.length-i.length;if(a<0)return null;let o=[...r,...Array(a).fill(`0`),...i].map(e=>parseInt(e,16));return o.some(e=>Number.isNaN(e)||e<0||e>65535)?null:(o.push(...t),o.length===8?o:null)}function Dct(e){let t=Ect(e);if(!t)return null;if(t[0]===0&&t[1]===0&&t[2]===0&&t[3]===0&&t[4]===0&&t[5]===65535){let e=t[6],n=t[7];return`${e>>8}.${e&255}.${n>>8}.${n&255}`}return null}function Oct(e,t,n){let r=`all`in t&&t.all===!0,i=Nce(e);if(i!==0){if(Cct(e)){n(kct(e,e),``);return}let t=i===6?6:4;r?n(null,[{address:e,family:t}]):n(null,e,t);return}Xce(e,{all:!0},(t,i)=>{if(t){n(t,``);return}for(let{address:t}of i)if(Cct(t)){n(kct(e,t),``);return}let a=i[0];if(!a){n(Object.assign(Error(`ENOTFOUND ${e}`),{code:`ENOTFOUND`,hostname:e}),``);return}let o=a.family===6?6:4;r?n(null,i.map(e=>({address:e.address,family:e.family===6?6:4}))):n(null,a.address,o)})}function kct(e,t){let n=Error(`HTTP hook blocked: ${e} resolves to ${t} (private/link-local address). Loopback (127.0.0.1, ::1) is allowed for local dev.`);return Object.assign(n,{code:`ERR_HTTP_HOOK_BLOCKED_ADDRESS`,hostname:e,address:t})}var Act=n((()=>{}));async function jct(){let{SandboxManager:e}=await import(`./sandbox-adapter-
|
|
3081
|
+
- ok: false with reason if the condition is not met`]),f=e.model??Jo(),_=oH(`hook-agent-${Jc()}`),v={...a,agentId:_,abortController:p,options:{...a.options,tools:i,mainLoopModel:f,isNonInteractiveSession:!0,thinkingConfig:{type:`disabled`}},setInProgressToolUseIDs:()=>{},getAppState(){let e=a.getAppState(),t=e.toolPermissionContext.alwaysAllowRules.session??[];return{...e,toolPermissionContext:{...e.toolPermissionContext,mode:`dontAsk`,alwaysAllowRules:{...e.toolPermissionContext.alwaysAllowRules,session:[...t,`Read(/${u})`]}}}}};_ct(a.setAppState,_);let y=null,b=0,x=!1;for await(let e of Q1({messages:s,systemPrompt:o,userContext:{},systemContext:{},canUseTool:k9,toolUseContext:v,querySource:`hook_agent`}))if(Sit(e,()=>{},e=>a.setResponseLength(t=>t+e.length),a.setStreamMode??(()=>{}),()=>{}),!(e.type===`stream_event`||e.type===`stream_request_start`)){if(e.type===`assistant`&&(b++,b>=50)){x=!0,G(`Hooks: Agent turn ${b} hit max turns, aborting`),p.abort();break}if(bct(e)){let t=q5().safeParse(e.attachment.data);if(t.success){y=t.data,G(`Hooks: Got structured output: ${U(y)}`),p.abort();break}}}return m.removeEventListener(`abort`,g),h(),CY(a.setAppState,_),y?y.ok?(G(`Hooks: Agent hook condition was met`),Y(`tengu_agent_stop_hook_success`,{durationMs:Date.now()-d,turnCount:b,agentName:c}),{hook:e,outcome:`success`,message:r2({type:`hook_success`,hookName:t,toolUseID:l,hookEvent:n,content:``})}):(G(`Hooks: Agent hook condition was not met: ${y.reason}`),{hook:e,outcome:`blocking`,blockingError:{blockingError:`Agent hook condition was not met: ${y.reason}`,command:e.prompt}}):x?(G(`Hooks: Agent hook did not complete within 50 turns`),Y(`tengu_agent_stop_hook_max_turns`,{durationMs:Date.now()-d,turnCount:b,agentName:c}),{hook:e,outcome:`cancelled`}):(G(`Hooks: Agent hook did not return structured output`),Y(`tengu_agent_stop_hook_error`,{durationMs:Date.now()-d,turnCount:b,errorType:1,agentName:c}),{hook:e,outcome:`cancelled`})}catch(t){if(m.removeEventListener(`abort`,g),h(),_.aborted)return{hook:e,outcome:`cancelled`};throw t}}catch(r){let i=W(r);return G(`Hooks: Agent hook error: ${i}`),Y(`tengu_agent_stop_hook_error`,{durationMs:Date.now()-d,errorType:2,agentName:c}),{hook:e,outcome:`non_blocking_error`,message:r2({type:`hook_non_blocking_error`,hookName:t,toolUseID:l,hookEvent:n,stderr:`Error executing agent hook: ${i}`,stdout:``,exitCode:1})}}}var Sct=n((()=>{$1(),oo(),Ks(),Ss(),E1(),sH(),UO(),m2(),K5(),K(),qn(),h3(),Uo(),A9(),h8(),mr(),cF(),J5(),wY()}));function Cct(e){let t=Nce(e);return t===4?wct(e):t===6&&Tct(e)}function wct(e){let t=e.split(`.`).map(Number),[n,r]=t;return t.length!==4||n===void 0||r===void 0||t.some(e=>Number.isNaN(e))||n===127?!1:n===0||n===10||n===169&&r===254||n===172&&r>=16&&r<=31||n===100&&r>=64&&r<=127||n===192&&r===168}function Tct(e){let t=e.toLowerCase();if(t===`::1`)return!1;if(t===`::`)return!0;let n=Dct(t);if(n!==null)return wct(n);if(t.startsWith(`fc`)||t.startsWith(`fd`))return!0;let r=t.split(`:`)[0];return!!(r&&r.length===4&&r>=`fe80`&&r<=`febf`)}function Ect(e){let t=[];if(e.includes(`.`)){let n=e.lastIndexOf(`:`),r=e.slice(n+1);e=e.slice(0,n);let i=r.split(`.`).map(Number);if(i.length!==4||i.some(e=>!Number.isInteger(e)||e<0||e>255))return null;t=[i[0]<<8|i[1],i[2]<<8|i[3]]}let n=e.indexOf(`::`),r,i;if(n===-1)r=e.split(`:`),i=[];else{let t=e.slice(0,n),a=e.slice(n+2);r=t===``?[]:t.split(`:`),i=a===``?[]:a.split(`:`)}let a=8-t.length-r.length-i.length;if(a<0)return null;let o=[...r,...Array(a).fill(`0`),...i].map(e=>parseInt(e,16));return o.some(e=>Number.isNaN(e)||e<0||e>65535)?null:(o.push(...t),o.length===8?o:null)}function Dct(e){let t=Ect(e);if(!t)return null;if(t[0]===0&&t[1]===0&&t[2]===0&&t[3]===0&&t[4]===0&&t[5]===65535){let e=t[6],n=t[7];return`${e>>8}.${e&255}.${n>>8}.${n&255}`}return null}function Oct(e,t,n){let r=`all`in t&&t.all===!0,i=Nce(e);if(i!==0){if(Cct(e)){n(kct(e,e),``);return}let t=i===6?6:4;r?n(null,[{address:e,family:t}]):n(null,e,t);return}Xce(e,{all:!0},(t,i)=>{if(t){n(t,``);return}for(let{address:t}of i)if(Cct(t)){n(kct(e,t),``);return}let a=i[0];if(!a){n(Object.assign(Error(`ENOTFOUND ${e}`),{code:`ENOTFOUND`,hostname:e}),``);return}let o=a.family===6?6:4;r?n(null,i.map(e=>({address:e.address,family:e.family===6?6:4}))):n(null,a.address,o)})}function kct(e,t){let n=Error(`HTTP hook blocked: ${e} resolves to ${t} (private/link-local address). Loopback (127.0.0.1, ::1) is allowed for local dev.`);return Object.assign(n,{code:`ERR_HTTP_HOOK_BLOCKED_ADDRESS`,hostname:e,address:t})}var Act=n((()=>{}));async function jct(){let{SandboxManager:e}=await import(`./sandbox-adapter-DfB9kgQD.js`);if(!e.isSandboxingEnabled())return;await e.waitForNetworkInitialization();let t=e.getProxyPort();if(t)return{host:`127.0.0.1`,port:t,protocol:`http`}}function Mct(){let e=Vi();return{allowedUrls:e.allowedHttpHookUrls,allowedEnvVars:e.httpHookAllowedEnvVars}}function Nct(e,t){let n=t.replace(/[.+?^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`.*`);return RegExp(`^${n}$`).test(e)}function Pct(e){return e.replace(/[\r\n\x00]/g,``)}function Fct(e,t){return Pct(e.replace(/\$\{([A-Z_][A-Z0-9_]*)\}|\$([A-Z_][A-Z0-9_]*)/g,(e,n,r)=>{let i=n??r;return t.has(i)?process.env[i]??``:(G(`Hooks: env var $${i} not in allowedEnvVars, skipping interpolation`,{level:`warn`}),``)}))}async function Ict(e,t,n,r){let i=Mct();if(i.allowedUrls!==void 0&&!i.allowedUrls.some(t=>Nct(e.url,t))){let t=`HTTP hook blocked: ${e.url} does not match any pattern in allowedHttpHookUrls`;return G(t,{level:`warn`}),{ok:!1,body:``,error:t}}let{signal:a,cleanup:o}=G5(r,{timeoutMs:e.timeout?e.timeout*1e3:Lct});try{let t={"Content-Type":`application/json`};if(e.headers){let n=e.allowedEnvVars??[],r=i.allowedEnvVars===void 0?n:n.filter(e=>i.allowedEnvVars.includes(e)),a=new Set(r);for(let[n,r]of Object.entries(e.headers))t[n]=Fct(r,a)}let r=await jct(),s=!r&&goe()!==void 0&&!_oe(e.url);G(r?`Hooks: HTTP hook POST to ${e.url} (via sandbox proxy :${r.port})`:s?`Hooks: HTTP hook POST to ${e.url} (via env-var proxy)`:`Hooks: HTTP hook POST to ${e.url}`);let c=await Le.post(e.url,n,{headers:t,signal:a,responseType:`text`,validateStatus:()=>!0,maxRedirects:0,proxy:r??!1,lookup:r||s?void 0:Oct});o();let l=c.data??``;return G(`Hooks: HTTP hook response status ${c.status}, body length ${l.length}`),{ok:c.status>=200&&c.status<300,statusCode:c.status,body:l}}catch(e){if(o(),a.aborted)return{ok:!1,body:``,aborted:!0};let t=W(e);return G(`Hooks: HTTP hook error: ${t}`,{level:`error`}),{ok:!1,body:``,error:t}}}var Lct,Rct=n((()=>{Re(),K5(),K(),qn(),Qs(),vi(),Act(),Lct=600*1e3}));function zct(){let e=process.env.CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS,t=e?parseInt(e,10):NaN;return Number.isFinite(t)&&t>0?t:Tlt}function Bct({processId:e,hookId:t,shellCommand:n,asyncResponse:r,hookEvent:i,hookName:a,command:o,asyncRewake:s,pluginId:c}){return s?(n.result.then(async e=>{await new Promise(e=>setImmediate(e));let r=await n.taskOutput.getStdout(),o=n.taskOutput.getStderr();n.cleanup(),U0({hookId:t,hookName:a,hookEvent:i,output:r+o,stdout:r,stderr:o,exitCode:e.code,outcome:e.code===0?`success`:`error`}),e.code===2&&CI({value:e3(`Stop hook blocking error from command "${a}": ${o||r}`),mode:`task-notification`})}),!0):n.background(e)?(s9e({processId:e,hookId:t,asyncResponse:r,hookEvent:i,hookName:a,command:o,shellCommand:n,pluginId:c}),!0):!1}function Y5(){return!qt()&&!fa()}function X5(e,t,n){let r=t??jn(),i=n?.agentType??Wt();return{session_id:r,transcript_path:f6(r),cwd:H(),permission_mode:e,agent_id:n?.agentId,agent_type:i}}function Vct(e){let t=$n(e),n=W5().safeParse(t);return n.success?(G(`Successfully parsed and validated hook JSON output`),{json:n.data}):{validationError:`Hook JSON output validation failed:\n${n.error.issues.map(e=>` - ${e.path.join(`.`)}: ${e.message}`).join(`
|
|
3082
3082
|
`)}\n\nThe hook's output was: ${U(t,null,2)}`}}function Hct(e){let t=e.trim();if(!t.startsWith(`{`))return G(`Hook output does not start with {, treating as plain text`),{plainText:e};try{let n=Vct(t);if(`json`in n)return n;let r=`${n.validationError}\n\nExpected schema:\n${U({continue:`boolean (optional)`,suppressOutput:`boolean (optional)`,stopReason:`string (optional)`,decision:`"approve" | "block" (optional)`,reason:`string (optional)`,systemMessage:`string (optional)`,permissionDecision:`"allow" | "deny" | "ask" (optional)`,hookSpecificOutput:{"for PreToolUse":{hookEventName:`"PreToolUse"`,permissionDecision:`"allow" | "deny" | "ask" (optional)`,permissionDecisionReason:`string (optional)`,updatedInput:`object (optional) - Modified tool input to use`},"for UserPromptSubmit":{hookEventName:`"UserPromptSubmit"`,additionalContext:`string (required)`},"for PostToolUse":{hookEventName:`"PostToolUse"`,additionalContext:`string (optional)`}}},null,2)}`;return G(r),{plainText:e,validationError:r}}catch(t){return G(`Failed to parse hook output as JSON: ${t}`),{plainText:e}}}function Uct(e){let t=e.trim();if(t===``){let e=W5().safeParse({});if(e.success)return G(`HTTP hook returned empty body, treating as empty JSON object`),{json:e.data}}if(!t.startsWith(`{`)){let e=`HTTP hook must return JSON, but got non-JSON response body: ${t.length>200?`${t.slice(0,200)}\u2026`:t}`;return G(e),{validationError:e}}try{let e=Vct(t);return`json`in e||G(e.validationError),e}catch(e){let t=`HTTP hook must return valid JSON, but parsing failed: ${e}`;return G(t),{validationError:t}}}function Z5({json:e,command:t,hookName:n,toolUseID:r,hookEvent:i,expectedHookEvent:a,stdout:o,stderr:s,exitCode:c,durationMs:l}){let u={},d=e,f=d;if(f.continue===!1&&(u.preventContinuation=!0,f.stopReason&&(u.stopReason=f.stopReason)),d.decision)switch(d.decision){case`approve`:u.permissionBehavior=`allow`;break;case`block`:u.permissionBehavior=`deny`,u.blockingError={blockingError:d.reason||`Blocked by hook`,command:t};break;default:throw Error(`Unknown hook decision type: ${d.decision}. Valid types are: approve, block`)}if(d.systemMessage&&(u.systemMessage=d.systemMessage),d.hookSpecificOutput?.hookEventName===`PreToolUse`&&d.hookSpecificOutput.permissionDecision)switch(d.hookSpecificOutput.permissionDecision){case`allow`:u.permissionBehavior=`allow`;break;case`deny`:u.permissionBehavior=`deny`,u.blockingError={blockingError:d.reason||`Blocked by hook`,command:t};break;case`ask`:u.permissionBehavior=`ask`;break;default:throw Error(`Unknown hook permissionDecision type: ${d.hookSpecificOutput.permissionDecision}. Valid types are: allow, deny, ask`)}if(u.permissionBehavior!==void 0&&d.reason!==void 0&&(u.hookPermissionDecisionReason=d.reason),d.hookSpecificOutput){if(a&&d.hookSpecificOutput.hookEventName!==a)throw Error(`Hook returned incorrect event name: expected '${a}' but got '${d.hookSpecificOutput.hookEventName}'. Full stdout: ${U(d,null,2)}`);switch(d.hookSpecificOutput.hookEventName){case`PreToolUse`:if(d.hookSpecificOutput.permissionDecision)switch(d.hookSpecificOutput.permissionDecision){case`allow`:u.permissionBehavior=`allow`;break;case`deny`:u.permissionBehavior=`deny`,u.blockingError={blockingError:d.hookSpecificOutput.permissionDecisionReason||d.reason||`Blocked by hook`,command:t};break;case`ask`:u.permissionBehavior=`ask`;break}u.hookPermissionDecisionReason=d.hookSpecificOutput.permissionDecisionReason,d.hookSpecificOutput.updatedInput&&(u.updatedInput=d.hookSpecificOutput.updatedInput),u.additionalContext=d.hookSpecificOutput.additionalContext;break;case`UserPromptSubmit`:u.additionalContext=d.hookSpecificOutput.additionalContext;break;case`SessionStart`:u.additionalContext=d.hookSpecificOutput.additionalContext,u.initialUserMessage=d.hookSpecificOutput.initialUserMessage,`watchPaths`in d.hookSpecificOutput&&d.hookSpecificOutput.watchPaths&&(u.watchPaths=d.hookSpecificOutput.watchPaths);break;case`Setup`:u.additionalContext=d.hookSpecificOutput.additionalContext;break;case`SubagentStart`:u.additionalContext=d.hookSpecificOutput.additionalContext;break;case`PostToolUse`:u.additionalContext=d.hookSpecificOutput.additionalContext,d.hookSpecificOutput.updatedMCPToolOutput&&(u.updatedMCPToolOutput=d.hookSpecificOutput.updatedMCPToolOutput);break;case`PostToolUseFailure`:u.additionalContext=d.hookSpecificOutput.additionalContext;break;case`PermissionDenied`:u.retry=d.hookSpecificOutput.retry;break;case`PermissionRequest`:d.hookSpecificOutput.decision&&(u.permissionRequestResult=d.hookSpecificOutput.decision,u.permissionBehavior=d.hookSpecificOutput.decision.behavior===`allow`?`allow`:`deny`,d.hookSpecificOutput.decision.behavior===`allow`&&d.hookSpecificOutput.decision.updatedInput&&(u.updatedInput=d.hookSpecificOutput.decision.updatedInput));break;case`Elicitation`:d.hookSpecificOutput.action&&(u.elicitationResponse={action:d.hookSpecificOutput.action,content:d.hookSpecificOutput.content},d.hookSpecificOutput.action===`decline`&&(u.blockingError={blockingError:d.reason||`Elicitation denied by hook`,command:t}));break;case`ElicitationResult`:d.hookSpecificOutput.action&&(u.elicitationResultResponse={action:d.hookSpecificOutput.action,content:d.hookSpecificOutput.content},d.hookSpecificOutput.action===`decline`&&(u.blockingError={blockingError:d.reason||`Elicitation result blocked by hook`,command:t}));break}}return{...u,message:u.blockingError?r2({type:`hook_blocking_error`,hookName:n,toolUseID:r,hookEvent:i,blockingError:u.blockingError}):r2({type:`hook_success`,hookName:n,toolUseID:r,hookEvent:i,content:``,stdout:o,stderr:s,exitCode:c,command:t,durationMs:l})}}async function Q5(e,t,n,r,i,a,o,s,c,l,u,d){let f=t===`SessionStart`||t===`Setup`||t===`SessionEnd`,p=Date.now(),m,h=!1,g=io()===`windows`,_=e.shell??`bash`,v=_===`powershell`,y=g&&!v?e=>Er(e):e=>e,b=en(),x=e.command,S;if(s){if(!await Si(s))throw Error(`Plugin directory does not exist: ${s}`+(c?` (${c} — run /plugin to reinstall)`:``));let e=y(s);if(x=x.replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g,()=>e),c){let e=y(lb(c));x=x.replace(/\$\{CLAUDE_PLUGIN_DATA\}/g,()=>e)}c&&(S=Rk(c),x=Ik(x,S))}g&&!v&&x.trim().match(/\.sh(\s|$|")/)&&(x.trim().startsWith(`bash `)||(x=`bash ${x}`));let C=!v&&process.env.CLAUDE_CODE_SHELL_PREFIX?Nye(process.env.CLAUDE_CODE_SHELL_PREFIX,x):x,w=e.timeout?e.timeout*1e3:h7,T={...zx(),CLAUDE_PROJECT_DIR:y(b)};if(s&&(T.CLAUDE_PLUGIN_ROOT=y(s),c&&(T.CLAUDE_PLUGIN_DATA=y(lb(c)))),S)for(let[e,t]of Object.entries(S)){let n=e.replace(/[^A-Za-z0-9_]/g,`_`).toUpperCase();T[`CLAUDE_PLUGIN_OPTION_${n}`]=String(t)}l&&(T.CLAUDE_PLUGIN_ROOT=y(l)),!v&&(t===`SessionStart`||t===`Setup`||t===`CwdChanged`||t===`FileChanged`)&&o!==void 0&&(T.CLAUDE_ENV_FILE=await Xve(t,o));let E=H(),D=await Si(E)?E:Yt();D!==E&&G(`Hooks: cwd ${E} not found, falling back to original cwd`,{level:`warn`});let O=C;if(!v&&ov.isSandboxingEnabled())try{O=await ov.wrapWithSandbox(C,void 0,{network:{allowedDomains:[],deniedDomains:[]},filesystem:{allowWrite:[`/`],denyWrite:[],allowRead:[],denyRead:[]}},i),G(`Hook command sandboxed (network-only): ${e.command}`,{level:`verbose`})}catch(e){G(`Failed to sandbox hook command, running unsandboxed: ${W(e)}`,{level:`warn`})}let k;if(_===`powershell`){let t=await Jx();if(!t)throw Error(`Hook "${e.command}" has shell: 'powershell' but no PowerShell executable (pwsh or powershell) was found on PATH. Install PowerShell, or remove "shell": "powershell" to use bash.`);k=dl(t,Zye(C),{env:T,cwd:D,windowsHide:!0})}else{let e=!g||Zne();k=dl(O,[],{env:T,cwd:D,shell:e,windowsHide:!0})}let A=new tx(`hook_${k.pid}`,null),ee=nct(k,i,w,A),te=!1,ne=!1;if((e.async||e.asyncRewake)&&!u){let i=`async_hook_${k.pid}`;if(G(`Hooks: Config-based async hook, backgrounding process ${i}`),k.stdin.write(`${r}\n`,`utf8`),k.stdin.end(),ne=!0,Bct({processId:i,hookId:a,shellCommand:ee,asyncResponse:{async:!0,asyncTimeout:w},hookEvent:t,hookName:n,command:e.command,asyncRewake:e.asyncRewake,pluginId:c}))return{stdout:``,stderr:``,output:``,status:0,backgrounded:!0}}let re=``,ie=``,ae=``;k.stdout.setEncoding(`utf8`),k.stderr.setEncoding(`utf8`);let j=!1,oe=null,se=new Promise(e=>{oe=e}),ce=new Set,M=Promise.resolve(),N=``;k.stdout.on(`data`,r=>{if(re+=r,ae+=r,d){N+=r;let e=N.split(`
|
|
3083
3083
|
`);N=e.pop()??``;for(let t of e){let e=t.trim();if(e)try{let t=$n(e),n=fct().safeParse(t);if(n.success){ce.add(e),G(`Hooks: Detected prompt request from hook: ${e}`);let t=n.data,r=d;M=M.then(async()=>{try{let e=await r(t);k.stdin.write(`${U(e)}\n`,`utf8`)}catch(e){G(`Hooks: Prompt request handling failed: ${e}`),k.stdin.destroy()}})}}catch{}}}if(!j){let r=Ya(re).trim();if(!r.includes(`}`))return;j=!0,G(`Hooks: Checking first line for async: ${r}`);try{let i=$n(r);if(G(`Hooks: Parsed initial response: ${U(i)}`),U5(i)&&!u){let r=`async_hook_${k.pid}`;G(`Hooks: Detected async hook, backgrounding process ${r}`),Bct({processId:r,hookId:a,shellCommand:ee,asyncResponse:i,hookEvent:t,hookName:n,command:e.command,pluginId:c})&&(te=!0,oe?.({stdout:re,stderr:ie,output:ae,status:0}))}else U5(i)&&u?G(`Hooks: Detected async hook but forceSyncExecution is true, waiting for completion`):G(`Hooks: Initial response is not async, continuing normal processing`)}catch(e){G(`Hooks: Failed to parse initial response as JSON: ${e}`)}}}),k.stderr.on(`data`,e=>{ie+=e,ae+=e});let le=r9e({hookId:a,hookName:n,hookEvent:t,getOutput:async()=>({stdout:re,stderr:ie,output:ae})}),ue=new Promise(e=>{k.stdout.on(`end`,()=>e())}),de=new Promise(e=>{k.stderr.on(`end`,()=>e())}),fe=ne?Promise.resolve():new Promise((e,t)=>{k.stdin.on(`error`,e=>{d?G(`Hooks: stdin error during prompt flow (likely process exited): ${e}`):t(e)}),k.stdin.write(`${r}\n`,`utf8`),d||k.stdin.end(),e()}),pe=new Promise((e,t)=>{k.on(`error`,t)}),me=new Promise(e=>{let t=null;k.on(`close`,n=>{t=n??1,Promise.all([ue,de]).then(()=>{e({stdout:ce.size===0?re:re.split(`
|
|
3084
3084
|
`).filter(e=>!ce.has(e.trim())).join(`
|
|
@@ -3275,8 +3275,8 @@ The user context may include a \`terminalFocus\` field indicating whether the us
|
|
|
3275
3275
|
`)].filter(Boolean)}function Lut(e,t){if(Object.entries(t).length===0)return e;let{agentsMd:n,...r}=t,i=[];n&&i.push(Q({content:`<project-instructions>\n${n}\n</project-instructions>\n`,isMeta:!0}));let a=Object.entries(r);return a.length>0&&i.push(Q({content:`<system-reminder>\nAs you answer the user's questions, you can use the following context:\n${a.map(([e,t])=>`# ${e}\n${t}`).join(`
|
|
3276
3276
|
`)}
|
|
3277
3277
|
|
|
3278
|
-
IMPORTANT: this context may or may not be relevant to your tasks. You should not respond to this context unless it is highly relevant to your task.\n</system-reminder>\n`,isMeta:!0})),[...i,...e]}async function Rut(e,t){if(Zoe())return;let[{tools:n},r,i,a]=await Promise.all([HA(e),T1(t),VR(),BR()]),o=a.gitStatus?.length??0,s=i.agentsMd?.length??0,c=o+s,l=H(),u=D8(O8(t),l),d=await Foe(l,AbortSignal.timeout(1e3),u),f=0,p=0,m=0,h=0,g=0,_=r.filter(e=>!e.isMcp);f=n.length,h=_.length;let v=new Set;for(let e of n){let t=e.name.split(`__`);t.length>=3&&t[1]&&v.add(t[1])}p=v.size;for(let e of n){let t=`inputJSONSchema`in e&&e.inputJSONSchema?e.inputJSONSchema:sz(e.inputSchema);m+=b3(U(t))}for(let e of _){let t=`inputJSONSchema`in e&&e.inputJSONSchema?e.inputJSONSchema:sz(e.inputSchema);g+=b3(U(t))}Y(`tengu_context_size`,{git_status_size:o,claude_md_size:s,total_context_size:c,project_file_count_rounded:d,mcp_tools_count:f,mcp_servers_count:p,mcp_tools_tokens:m,non_mcp_tools_count:h,non_mcp_tools_tokens:g})}function zut(e,t,n){switch(e.name){case us:{let e=Pd(n),r=Nd(n);return Id(),e===null?t:{...t,plan:e,planFilePath:r}}case Rq.name:{let e=Rq.inputSchema.parse(t),{command:n,timeout:r,description:i}=e,a=H(),o=n.replace(`cd ${a} && `,``);io()===`windows`&&(o=o.replace(`cd ${Er(a)} && `,``)),o=o.replace(/\\\\;/g,`\\;`),/^echo\s+["']?[^|&;><]*["']?$/i.test(o.trim())&&Y(`tengu_bash_tool_simple_echo`,{});let s=`run_in_background`in e?e.run_in_background:void 0;return{command:o,description:i,...r!==void 0&&{timeout:r},...i!==void 0&&{description:i},...s!==void 0&&{run_in_background:s},...`dangerouslyDisableSandbox`in e&&e.dangerouslyDisableSandbox!==void 0&&{dangerouslyDisableSandbox:e.dangerouslyDisableSandbox}}}case PX.name:{let e=PX.inputSchema.parse(t),{file_path:n,edits:r}=AOe({file_path:e.file_path,edits:[{old_string:e.old_string,new_string:e.new_string,replace_all:e.replace_all}]});return{replace_all:r[0].replace_all,file_path:n,old_string:r[0].old_string,new_string:r[0].new_string}}case mK.name:{let e=mK.inputSchema.parse(t),n=/\.(md|mdx)$/i.test(e.file_path);return{file_path:e.file_path,content:n?e.content:tF(e.content)}}case kr:{let e=t,n=e.task_id??e.agentId??e.bash_id,r=e.timeout??(typeof e.wait_up_to==`number`?e.wait_up_to*1e3:void 0);return{task_id:n??``,block:e.block??!0,timeout:r??3e4}}default:return t}}function But(e,t){switch(e.name){case us:if(t&&typeof t==`object`&&(`plan`in t||`planFilePath`in t)){let{plan:e,planFilePath:n,...r}=t;return r}return t;case PX.name:if(t&&typeof t==`object`&&`edits`in t){let{old_string:e,new_string:n,replace_all:r,...i}=t;return i}return t;default:return t}}var H7,U7=n((()=>{B7(),HR(),Xoe(),oo(),cj(),zq(),FX(),sF(),hK(),E1(),ed(),T3(),zs(),Fr(),ve(),Vn(),K(),g(),h3(),Io(),R8(),zd(),ao(),nc(),mr(),Mut(),Cr(),lz(),H7=!1}));function Vut(e){let{hasThinking:t=!1,isRedactThinkingActive:n=!1,clearAllThinking:r=!1}=e??{},i=[];t&&!n&&i.push({type:`clear_thinking_20251015`,keep:r?{type:`thinking_turns`,value:1}:`all`});let a=process.env.USE_API_CLEAR_TOOL_RESULTS===void 0||h(process.env.USE_API_CLEAR_TOOL_RESULTS),o=h(process.env.USE_API_CLEAR_TOOL_USES);if(!a&&!o)return i.length>0?{edits:i}:void 0;if(a){let e=process.env.API_MAX_INPUT_TOKENS?parseInt(process.env.API_MAX_INPUT_TOKENS,10):W7,t=process.env.API_TARGET_INPUT_TOKENS?parseInt(process.env.API_TARGET_INPUT_TOKENS,10):G7,n={type:`clear_tool_uses_20250919`,trigger:{type:`input_tokens`,value:e},clear_at_least:{type:`input_tokens`,value:e-t},clear_tool_inputs:Hut};i.push(n)}if(o){let e=process.env.API_MAX_INPUT_TOKENS?parseInt(process.env.API_MAX_INPUT_TOKENS,10):W7,t=process.env.API_TARGET_INPUT_TOKENS?parseInt(process.env.API_TARGET_INPUT_TOKENS,10):G7,n={type:`clear_tool_uses_20250919`,trigger:{type:`input_tokens`,value:e},clear_at_least:{type:`input_tokens`,value:e-t},exclude_tools:Uut};i.push(n)}return i.length>0?{edits:i}:void 0}var W7,G7,Hut,Uut,Wut=n((()=>{Ls(),Us(),bs(),hs(),fs(),Ps(),Xs(),g(),W7=18e4,G7=4e4,Hut=[...poe,qs,ss,ys],Uut=[Gs,ks,Rs]})),Gut,Kut=n((()=>{Gut={providerId:`bedrock`,parseHeaders(e){let t=[],n=e.get(`x-amzn-bedrock-quota-remaining`),r=e.get(`x-amzn-bedrock-quota-reset`);if(n!==null){let e=Number(n);if(Number.isFinite(e)&&e>=0&&e<=1){let n=r===null?0:Number(r);t.push({kind:`throttle`,label:`Throttle`,utilization:1-e,...Number.isFinite(n)&&n>0?{resetsAt:n}:{}})}}return t}}}));function qut(e,t){let n=-1;for(let t=0;t<e.length;t++){let r=e[t];r&&typeof r==`object`&&`type`in r&&r.type===`tool_result`&&(n=t)}if(n>=0){let r=n+1;e.splice(r,0,t),r===e.length-1&&e.push({type:`text`,text:`.`})}else{let n=Math.max(0,e.length-1);e.splice(n,0,t)}}var Jut=n((()=>{})),Yut=n((()=>{Nv()}));function Xut(e){if(e instanceof Jn){let t=e.error;if(t?.error?.message)return t.error.message}return e instanceof Error?e.message:String(e)}function Zut({headers:e,baseUrl:t}){if(e){let t=[];e.forEach((e,n)=>t.push(n));for(let[e,{prefixes:n}]of Object.entries(rdt))if(n.some(e=>t.some(t=>t.startsWith(e))))return e}if(t)try{let e=new URL(t).hostname.toLowerCase();for(let[t,n]of Object.entries(idt))if(n.some(t=>e.endsWith(t)))return t}catch{}}function K7(){return{...process.env.ANTHROPIC_BASE_URL?{baseUrl:process.env.ANTHROPIC_BASE_URL}:{},...process.env.ANTHROPIC_MODEL?{envModel:process.env.ANTHROPIC_MODEL}:{},...process.env.ANTHROPIC_SMALL_FAST_MODEL?{envSmallFastModel:process.env.ANTHROPIC_SMALL_FAST_MODEL}:{}}}function Qut(){let e=new Date(`2026-08-26T10:35:19.203Z`).getTime();if(!isNaN(e))return Math.floor((Date.now()-e)/6e4)}function $ut({model:e,messagesLength:t,temperature:n,betas:r,permissionMode:i,querySource:a,queryTracking:o,thinkingConfig:s,fastMode:c,previousRequestId:l}){let u=s?.type??`disabled`,d=s?.type===`enabled`?s.budgetTokens:void 0;Y(`tengu_api_query`,{model:e,messagesLength:t,temperature:n,provider:Po(),buildAgeMins:Qut(),...r?.length?{betas:r.join(`,`)}:{},permissionMode:i,querySource:a,...o?{queryChainId:o.chainId,queryDepth:o.depth}:{},thinkingType:u,...d!==void 0&&{thinkingBudgetTokens:d},fastMode:c,...l?{previousRequestId:l}:{},...K7()})}function edt({error:e,model:t,messageCount:n,messageTokens:r,durationMs:i,durationMsIncludingRetries:a,attempt:o,requestId:s,clientRequestId:c,didFallBackToNonStreaming:l,promptCategory:u,headers:d,queryTracking:f,querySource:p,llmSpan:m,fastMode:h,previousRequestId:g}){let _=Zut({headers:e instanceof Jn&&e.headers?e.headers:d,baseUrl:process.env.ANTHROPIC_BASE_URL}),v=Xut(e),y=e instanceof Jn?String(e.status):void 0,b=Ske(e),x=kv(e);if(x){let e=x.isSSLError?` (SSL error)`:``;G(`Connection error details: code=${x.code}${e}, message=${x.message}`,{level:`error`})}let S=ye();c&&G(`API error x-client-request-id=${c} (give this to the API team for server-log lookup)`,{level:`error`}),J(e),Y(`tengu_api_error`,{model:t,error:v,status:y,errorType:b,messageCount:n,messageTokens:r,durationMs:i,durationMsIncludingRetries:a,attempt:o,provider:Po(),requestId:s||void 0,...S?{invokingRequestId:S.invokingRequestId,invocationKind:S.invocationKind}:{},clientRequestId:c||void 0,didFallBackToNonStreaming:l,...u?{promptCategory:u}:{},..._?{gateway:_}:{},...f?{queryChainId:f.chainId,queryDepth:f.depth}:{},...p?{querySource:p}:{},fastMode:h,...g?{previousRequestId:g}:{},...K7()}),fc(`api_error`,{model:t,error:v,status_code:String(y),duration_ms:String(i),attempt:String(o),speed:h?`fast`:`normal`}),use(m,{success:!1,statusCode:y?parseInt(y,10):void 0,error:v,attempt:o})}function tdt({model:e,preNormalizedModel:t,messageCount:n,messageTokens:r,usage:i,durationMs:a,durationMsIncludingRetries:o,attempt:s,ttftMs:c,requestId:l,stopReason:u,costUSD:d,didFallBackToNonStreaming:f,querySource:p,gateway:m,queryTracking:h,permissionMode:g,globalCacheStrategy:_,textContentLength:v,thinkingContentLength:y,toolUseContentLengths:b,connectorTextBlockCount:x,fastMode:S,previousRequestId:C,betas:w}){let T=qt(),E=tne(),D=process.argv.includes(`-p`)||process.argv.includes(`--print`),O=Date.now(),k=tn(),A=k===null?void 0:O-k,ee=ye();Y(`tengu_api_success`,{model:e,...t===e?{}:{preNormalizedModel:t},...w?.length?{betas:w.join(`,`)}:{},messageCount:n,messageTokens:r,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cache_read_input_tokens??0,uncachedInputTokens:i.cache_creation_input_tokens??0,durationMs:a,durationMsIncludingRetries:o,attempt:s,ttftMs:c??void 0,buildAgeMins:Qut(),provider:Po(),requestId:l??void 0,...ee?{invokingRequestId:ee.invokingRequestId,invocationKind:ee.invocationKind}:{},stop_reason:u??void 0,costUSD:d,didFallBackToNonStreaming:f,isNonInteractiveSession:T,print:D,isTTY:process.stdout.isTTY??!1,querySource:p,...m?{gateway:m}:{},...h?{queryChainId:h.chainId,queryDepth:h.depth}:{},permissionMode:g,..._?{globalCacheStrategy:_}:{},...v===void 0?{}:{textContentLength:v},...y===void 0?{}:{thinkingContentLength:y},...b===void 0?{}:{toolUseContentLengths:U(b)},...x===void 0?{}:{connectorTextBlockCount:x},fastMode:S,...C?{previousRequestId:C}:{},...E?{isPostCompaction:E}:{},...K7(),timeSinceLastApiCallMs:A}),yn(O)}function ndt({model:e,preNormalizedModel:t,start:n,startIncludingRetries:r,ttftMs:i,usage:a,attempt:o,messageCount:s,messageTokens:c,requestId:l,stopReason:u,didFallBackToNonStreaming:d,querySource:f,headers:p,costUSD:m,queryTracking:h,permissionMode:g,newMessages:_,llmSpan:v,globalCacheStrategy:y,requestSetupMs:b,attemptStartTimes:x,fastMode:S,previousRequestId:C,betas:w}){let T=Zut({headers:p,baseUrl:process.env.ANTHROPIC_BASE_URL}),E,D,O,k;if(_){let e=0,t=0,n=!1,r={};for(let i of _){let a=Array.isArray(i.message.content)?i.message.content:[];for(let i of a)if(typeof i!=`string`){if(i.type===`text`)e+=i.text.length;else if(i.type===`thinking`)t+=i.thinking.length;else if(i.type===`tool_use`||i.type===`server_tool_use`||i.type===`mcp_tool_use`){let e=U(i.input).length,t=Ae(i.name);r[t]=(r[t]??0)+e,n=!0}}}E=e,D=t>0?t:void 0,O=n?r:void 0,k=void 0}let A=Date.now()-n,ee=Date.now()-r;qte(ee,A),tdt({model:e,preNormalizedModel:t,messageCount:s,messageTokens:c,usage:a,durationMs:A,durationMsIncludingRetries:ee,attempt:o,ttftMs:i,requestId:l,stopReason:u,costUSD:m,didFallBackToNonStreaming:d,querySource:f,gateway:T,queryTracking:h,permissionMode:g,globalCacheStrategy:y,textContentLength:E,thinkingContentLength:D,toolUseContentLengths:O,connectorTextBlockCount:k,fastMode:S,previousRequestId:C,betas:w}),fc(`api_request`,{model:e,input_tokens:String(a.input_tokens),output_tokens:String(a.output_tokens),cache_read_tokens:String(a.cache_read_input_tokens),cache_creation_tokens:String(a.cache_creation_input_tokens),cost_usd:String(m),duration_ms:String(A),speed:S?`fast`:`normal`});let te,ne;dc()&&_&&(te=_.flatMap(e=>{let t=e.message.content;return Array.isArray(t)?t.filter(e=>typeof e!=`string`&&e.type===`text`).map(e=>e.text):[]}).join(`
|
|
3279
|
-
`)||void 0,ne=_.some(e=>{let t=e.message.content;return Array.isArray(t)?t.some(e=>typeof e!=`string`&&e.type===`tool_use`):!1})),use(v,{success:!0,inputTokens:a.input_tokens,outputTokens:a.output_tokens,cacheReadTokens:a.cache_read_input_tokens,cacheCreationTokens:a.cache_creation_input_tokens,attempt:o,modelOutput:te,thinkingOutput:void 0,hasToolCall:ne,ttftMs:i??void 0,requestSetupMs:b,attemptStartTimes:x})}var rdt,idt,adt=n((()=>{Kn(),Jt(),K(),Ga(),Io(),mr(),hc(),pc(),xe(),oo(),Se(),Yut(),xL(),eL(),rdt={litellm:{prefixes:[`x-litellm-`]},helicone:{prefixes:[`helicone-`]},portkey:{prefixes:[`x-portkey-`]},"cloudflare-ai-gateway":{prefixes:[`cf-aig-`]},kong:{prefixes:[`x-kong-`]},braintrust:{prefixes:[`x-bt-`]}},idt={databricks:[`.cloud.databricks.com`,`.azuredatabricks.net`,`.gcp.databricks.com`]}}));function q7(e){let t=process.env.CLAUDE_CODE_EXTRA_BODY,n={};if(t)try{let e=Et(t);e&&typeof e==`object`&&!Array.isArray(e)?n={...e}:G(`CLAUDE_CODE_EXTRA_BODY env var must be a JSON object, but was given ${t}`,{level:`error`})}catch(e){G(`Error parsing CLAUDE_CODE_EXTRA_BODY: ${W(e)}`,{level:`error`})}if(e&&e.length>0)if(n.anthropic_beta&&Array.isArray(n.anthropic_beta)){let t=n.anthropic_beta,r=e.filter(e=>!t.includes(e));n.anthropic_beta=[...t,...r]}else n.anthropic_beta=e;return n}function odt(e){return!(h(process.env.DISABLE_PROMPT_CACHING)||h(process.env.DISABLE_PROMPT_CACHING_HAIKU)&&e===Jo()||h(process.env.DISABLE_PROMPT_CACHING_SONNET)&&e===zo()||h(process.env.DISABLE_PROMPT_CACHING_OPUS)&&e===qie())}function J7({scope:e,querySource:t}={}){return{type:`ephemeral`,...sdt(t)&&{ttl:`1h`},...e===`global`&&{scope:e}}}function sdt(e){if(Fo()===`bedrock`&&h(process.env.ENABLE_PROMPT_CACHING_1H_BEDROCK))return!0;let t=Ite();if(t===null&&(t=!1,Xte(t)),!t)return!1;let n=Wee();return n===null&&(n={}.allowlist??[],Gee(n)),e!==void 0&&n.some(t=>t.endsWith(`*`)?e.startsWith(t.slice(0,-1)):e===t)}function cdt(e,t,n){!e||`task_budget`in t||!be()||(t.task_budget={type:`tokens`,total:e.total,...e.remaining!==void 0&&{remaining:e.remaining}},n.includes(`task-budgets-2026-03-13`)||n.push(Vie))}function Y7(){let e={},t=process.env.CLAUDE_CODE_EXTRA_METADATA;if(t){let n=Et(t,!1);n&&typeof n==`object`&&!Array.isArray(n)?e=n:G(`CLAUDE_CODE_EXTRA_METADATA env var must be a JSON object, but was given ${t}`,{level:`error`})}return{user_id:U({...e,device_id:hie(),account_uuid:``,session_id:jn()})}}function ldt(e,t=!1,n,r){return t?typeof e.message.content==`string`?{role:`user`,content:[{type:`text`,text:e.message.content,...n&&{cache_control:J7({querySource:r})}}]}:{role:`user`,content:e.message.content.map((t,i)=>({...t,...i===e.message.content.length-1&&n?{cache_control:J7({querySource:r})}:{}}))}:{role:`user`,content:Array.isArray(e.message.content)?[...e.message.content]:e.message.content}}function udt(e,t=!1,n,r){return t?typeof e.message.content==`string`?{role:`assistant`,content:[{type:`text`,text:e.message.content,...n&&{cache_control:J7({querySource:r})}}]}:{role:`assistant`,content:e.message.content.map((t,i)=>{let a=ddt(t);return{...a,...i===e.message.content.length-1&&a.type!==`thinking`&&a.type!==`redacted_thinking`&&!td(a)&&n?{cache_control:J7({querySource:r})}:{}}})}:{role:`assistant`,content:typeof e.message.content==`string`?e.message.content:e.message.content.map(ddt)}}function ddt(e){if(typeof e==`string`||!(`_geminiThoughtSignature`in e))return e;let{_geminiThoughtSignature:t,...n}=e;return n}async function X7({messages:e,systemPrompt:t,thinkingConfig:n,tools:r,signal:i,options:a}){let o;for await(let s of jit(e,async function*(){yield*vdt(e,t,n,r,i,a)}))s.type===`assistant`&&(o=s);if(!o)throw i.aborted?new nr:Error(`No assistant message found`);return o}async function*fdt({messages:e,systemPrompt:t,thinkingConfig:n,tools:r,signal:i,options:a}){return yield*jit(e,async function*(){yield*vdt(e,t,n,r,i,a)})}function pdt(){return parseInt(process.env.API_TIMEOUT_MS||``,10)||(h(process.env.CLAUDE_CODE_REMOTE)?12e4:3e5)}async function*mdt(e,t,n,r,i,a){let o=pdt(),s=wL(()=>Ao({maxRetries:0,model:e.model,fetchOverride:e.fetchOverride,source:e.source}),async(s,c,l)=>{let u=Date.now(),d=n(l);i(d),r(c,u,d.max_tokens);let f=wdt(d,Edt);try{return await s.beta.messages.create({...f,model:Wo(f.model)},{signal:t.signal,timeout:o})}catch(t){throw t instanceof nr?t:(ei(`error`,`cli_nonstreaming_fallback_error`),Y(`tengu_nonstreaming_fallback_error`,{model:e.model,error:t instanceof Error?t.name:`unknown`,attempt:c,timeout_ms:o,request_id:a??`unknown`}),t)}},{model:t.model,fallbackModel:t.fallbackModel,thinkingConfig:t.thinkingConfig,...yo()&&{fastMode:t.fastMode},signal:t.signal,initialConsecutive529Errors:t.initialConsecutive529Errors,querySource:t.querySource}),c;do c=await s.next(),!c.done&&c.value.type===`system`&&(yield c.value);while(!c.done);return c.value}function hdt(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.type===`assistant`&&n.requestId)return n.requestId}}function Z7(e){return e.type===`image`||e.type===`document`}function gdt(e){return e.type===`tool_result`}function _dt(e,t){let n=0;for(let t of e)if(Array.isArray(t.message.content)){for(let e of t.message.content)if(Z7(e)&&n++,gdt(e)&&Array.isArray(e.content))for(let t of e.content)Z7(t)&&n++}return n-=t,n<=0?e:e.map(e=>{if(n<=0)return e;let t=e.message.content;if(!Array.isArray(t))return e;let r=n,i=t.map(e=>{if(n<=0||!gdt(e)||!Array.isArray(e.content))return e;let t=e.content.filter(e=>n>0&&Z7(e)?(n--,!1):!0);return t.length===e.content.length?e:{...e,content:t}}).filter(e=>n>0&&Z7(e)?(n--,!1):!0);return r===n?e:{...e,message:{...e.message,content:i}}})}async function*vdt(e,t,n,r,i,a){let o=hdt(e),s=Fo()===`bedrock`&&a.model.includes(`application-inference-profile`)?await es(a.model)??a.model:a.model;M1(`query_tool_schema_build_start`);let c=a.querySource.startsWith(`repl_main_thread`)||a.querySource.startsWith(`agent:`)||a.querySource===`sdk`||a.querySource===`hook_agent`||a.querySource===`verification_agent`,l=Te(a.model,{isAgenticQuery:c});uv()&&l.push(Rie);let u;if(c&&uv()){let e=a.advisorModel,t=mhe();if(t!==void 0&&Wo(t.baseModel)===Wo(a.model)&&(e=t.advisorModel),e){let t=Wo(Lo(e));fv(a.model)?pv(t)?(u=t,G(`[AdvisorTool] Server-side tool enabled with ${u} as the advisor model`)):G(`[AdvisorTool] Skipping advisor - ${t} is not a valid advisor model`):G(`[AdvisorTool] Skipping advisor - base model ${a.model} does not support advisor`)}}let d=await _z(a.model,r,a.getToolPermissionContext,a.agents,`query`),f=new Set;if(d)for(let e of r)As(e)&&f.add(e.name);d&&f.size===0&&!a.hasPendingMcpServers&&(G(`Tool search disabled: no deferred tools available to search`),d=!1);let p;p=d?r.filter(e=>!!(!f.has(e.name)||Cs(e,`SearchExtraTools`))):r.filter(e=>!Cs(e,Hs));let m=Fe(),g=m&&p.some(e=>e.isMcp===!0);m&&!l.includes(`prompt-caching-scope-2026-01-05`)&&l.push(Nie);let _=m?g?`none`:`system_prompt`:`none`,v=await Promise.all(p.map(e=>V7(e,{getToolPermissionContext:a.getToolPermissionContext,tools:r,agents:a.agents,allowedAgentTypes:a.allowedAgentTypes,model:a.model})));d&&G(`Dynamic tool loading: 0/${f.size} deferred tools in API tools array (all via ExecuteExtraTool)`),M1(`query_tool_schema_build_end`),Y(`tengu_api_before_normalize`,{preNormalizedMessageCount:e.length}),M1(`query_message_normalization_start`);let y=c3(e,p);if(M1(`query_message_normalization_end`),d||(y=y.map(e=>{switch(e.type){case`user`:return Trt(e);case`assistant`:return Ert(e);default:return e}})),y=Mrt(y),l.includes(`advisor-tool-2026-03-01`)||(y=Nrt(y)),y=_dt(y,100),Fo()===`openai`){let{queryModelOpenAI:e}=await import(`./openai-
|
|
3278
|
+
IMPORTANT: this context may or may not be relevant to your tasks. You should not respond to this context unless it is highly relevant to your task.\n</system-reminder>\n`,isMeta:!0})),[...i,...e]}async function Rut(e,t){if(Zoe())return;let[{tools:n},r,i,a]=await Promise.all([HA(e),T1(t),VR(),BR()]),o=a.gitStatus?.length??0,s=i.agentsMd?.length??0,c=o+s,l=H(),u=D8(O8(t),l),d=await Foe(l,AbortSignal.timeout(1e3),u),f=0,p=0,m=0,h=0,g=0,_=r.filter(e=>!e.isMcp);f=n.length,h=_.length;let v=new Set;for(let e of n){let t=e.name.split(`__`);t.length>=3&&t[1]&&v.add(t[1])}p=v.size;for(let e of n){let t=`inputJSONSchema`in e&&e.inputJSONSchema?e.inputJSONSchema:sz(e.inputSchema);m+=b3(U(t))}for(let e of _){let t=`inputJSONSchema`in e&&e.inputJSONSchema?e.inputJSONSchema:sz(e.inputSchema);g+=b3(U(t))}Y(`tengu_context_size`,{git_status_size:o,claude_md_size:s,total_context_size:c,project_file_count_rounded:d,mcp_tools_count:f,mcp_servers_count:p,mcp_tools_tokens:m,non_mcp_tools_count:h,non_mcp_tools_tokens:g})}function zut(e,t,n){switch(e.name){case us:{let e=Pd(n),r=Nd(n);return Id(),e===null?t:{...t,plan:e,planFilePath:r}}case Rq.name:{let e=Rq.inputSchema.parse(t),{command:n,timeout:r,description:i}=e,a=H(),o=n.replace(`cd ${a} && `,``);io()===`windows`&&(o=o.replace(`cd ${Er(a)} && `,``)),o=o.replace(/\\\\;/g,`\\;`),/^echo\s+["']?[^|&;><]*["']?$/i.test(o.trim())&&Y(`tengu_bash_tool_simple_echo`,{});let s=`run_in_background`in e?e.run_in_background:void 0;return{command:o,description:i,...r!==void 0&&{timeout:r},...i!==void 0&&{description:i},...s!==void 0&&{run_in_background:s},...`dangerouslyDisableSandbox`in e&&e.dangerouslyDisableSandbox!==void 0&&{dangerouslyDisableSandbox:e.dangerouslyDisableSandbox}}}case PX.name:{let e=PX.inputSchema.parse(t),{file_path:n,edits:r}=AOe({file_path:e.file_path,edits:[{old_string:e.old_string,new_string:e.new_string,replace_all:e.replace_all}]});return{replace_all:r[0].replace_all,file_path:n,old_string:r[0].old_string,new_string:r[0].new_string}}case mK.name:{let e=mK.inputSchema.parse(t),n=/\.(md|mdx)$/i.test(e.file_path);return{file_path:e.file_path,content:n?e.content:tF(e.content)}}case kr:{let e=t,n=e.task_id??e.agentId??e.bash_id,r=e.timeout??(typeof e.wait_up_to==`number`?e.wait_up_to*1e3:void 0);return{task_id:n??``,block:e.block??!0,timeout:r??3e4}}default:return t}}function But(e,t){switch(e.name){case us:if(t&&typeof t==`object`&&(`plan`in t||`planFilePath`in t)){let{plan:e,planFilePath:n,...r}=t;return r}return t;case PX.name:if(t&&typeof t==`object`&&`edits`in t){let{old_string:e,new_string:n,replace_all:r,...i}=t;return i}return t;default:return t}}var H7,U7=n((()=>{B7(),HR(),Xoe(),oo(),cj(),zq(),FX(),sF(),hK(),E1(),ed(),T3(),zs(),Fr(),ve(),Vn(),K(),g(),h3(),Io(),R8(),zd(),ao(),nc(),mr(),Mut(),Cr(),lz(),H7=!1}));function Vut(e){let{hasThinking:t=!1,isRedactThinkingActive:n=!1,clearAllThinking:r=!1}=e??{},i=[];t&&!n&&i.push({type:`clear_thinking_20251015`,keep:r?{type:`thinking_turns`,value:1}:`all`});let a=process.env.USE_API_CLEAR_TOOL_RESULTS===void 0||h(process.env.USE_API_CLEAR_TOOL_RESULTS),o=h(process.env.USE_API_CLEAR_TOOL_USES);if(!a&&!o)return i.length>0?{edits:i}:void 0;if(a){let e=process.env.API_MAX_INPUT_TOKENS?parseInt(process.env.API_MAX_INPUT_TOKENS,10):W7,t=process.env.API_TARGET_INPUT_TOKENS?parseInt(process.env.API_TARGET_INPUT_TOKENS,10):G7,n={type:`clear_tool_uses_20250919`,trigger:{type:`input_tokens`,value:e},clear_at_least:{type:`input_tokens`,value:e-t},clear_tool_inputs:Hut};i.push(n)}if(o){let e=process.env.API_MAX_INPUT_TOKENS?parseInt(process.env.API_MAX_INPUT_TOKENS,10):W7,t=process.env.API_TARGET_INPUT_TOKENS?parseInt(process.env.API_TARGET_INPUT_TOKENS,10):G7,n={type:`clear_tool_uses_20250919`,trigger:{type:`input_tokens`,value:e},clear_at_least:{type:`input_tokens`,value:e-t},exclude_tools:Uut};i.push(n)}return i.length>0?{edits:i}:void 0}var W7,G7,Hut,Uut,Wut=n((()=>{Ls(),Us(),bs(),hs(),fs(),Ps(),Xs(),g(),W7=18e4,G7=4e4,Hut=[...poe,qs,ss,ys],Uut=[Gs,ks,Rs]})),Gut,Kut=n((()=>{Gut={providerId:`bedrock`,parseHeaders(e){let t=[],n=e.get(`x-amzn-bedrock-quota-remaining`),r=e.get(`x-amzn-bedrock-quota-reset`);if(n!==null){let e=Number(n);if(Number.isFinite(e)&&e>=0&&e<=1){let n=r===null?0:Number(r);t.push({kind:`throttle`,label:`Throttle`,utilization:1-e,...Number.isFinite(n)&&n>0?{resetsAt:n}:{}})}}return t}}}));function qut(e,t){let n=-1;for(let t=0;t<e.length;t++){let r=e[t];r&&typeof r==`object`&&`type`in r&&r.type===`tool_result`&&(n=t)}if(n>=0){let r=n+1;e.splice(r,0,t),r===e.length-1&&e.push({type:`text`,text:`.`})}else{let n=Math.max(0,e.length-1);e.splice(n,0,t)}}var Jut=n((()=>{})),Yut=n((()=>{Nv()}));function Xut(e){if(e instanceof Jn){let t=e.error;if(t?.error?.message)return t.error.message}return e instanceof Error?e.message:String(e)}function Zut({headers:e,baseUrl:t}){if(e){let t=[];e.forEach((e,n)=>t.push(n));for(let[e,{prefixes:n}]of Object.entries(rdt))if(n.some(e=>t.some(t=>t.startsWith(e))))return e}if(t)try{let e=new URL(t).hostname.toLowerCase();for(let[t,n]of Object.entries(idt))if(n.some(t=>e.endsWith(t)))return t}catch{}}function K7(){return{...process.env.ANTHROPIC_BASE_URL?{baseUrl:process.env.ANTHROPIC_BASE_URL}:{},...process.env.ANTHROPIC_MODEL?{envModel:process.env.ANTHROPIC_MODEL}:{},...process.env.ANTHROPIC_SMALL_FAST_MODEL?{envSmallFastModel:process.env.ANTHROPIC_SMALL_FAST_MODEL}:{}}}function Qut(){let e=new Date(`2026-08-26T10:41:05.156Z`).getTime();if(!isNaN(e))return Math.floor((Date.now()-e)/6e4)}function $ut({model:e,messagesLength:t,temperature:n,betas:r,permissionMode:i,querySource:a,queryTracking:o,thinkingConfig:s,fastMode:c,previousRequestId:l}){let u=s?.type??`disabled`,d=s?.type===`enabled`?s.budgetTokens:void 0;Y(`tengu_api_query`,{model:e,messagesLength:t,temperature:n,provider:Po(),buildAgeMins:Qut(),...r?.length?{betas:r.join(`,`)}:{},permissionMode:i,querySource:a,...o?{queryChainId:o.chainId,queryDepth:o.depth}:{},thinkingType:u,...d!==void 0&&{thinkingBudgetTokens:d},fastMode:c,...l?{previousRequestId:l}:{},...K7()})}function edt({error:e,model:t,messageCount:n,messageTokens:r,durationMs:i,durationMsIncludingRetries:a,attempt:o,requestId:s,clientRequestId:c,didFallBackToNonStreaming:l,promptCategory:u,headers:d,queryTracking:f,querySource:p,llmSpan:m,fastMode:h,previousRequestId:g}){let _=Zut({headers:e instanceof Jn&&e.headers?e.headers:d,baseUrl:process.env.ANTHROPIC_BASE_URL}),v=Xut(e),y=e instanceof Jn?String(e.status):void 0,b=Ske(e),x=kv(e);if(x){let e=x.isSSLError?` (SSL error)`:``;G(`Connection error details: code=${x.code}${e}, message=${x.message}`,{level:`error`})}let S=ye();c&&G(`API error x-client-request-id=${c} (give this to the API team for server-log lookup)`,{level:`error`}),J(e),Y(`tengu_api_error`,{model:t,error:v,status:y,errorType:b,messageCount:n,messageTokens:r,durationMs:i,durationMsIncludingRetries:a,attempt:o,provider:Po(),requestId:s||void 0,...S?{invokingRequestId:S.invokingRequestId,invocationKind:S.invocationKind}:{},clientRequestId:c||void 0,didFallBackToNonStreaming:l,...u?{promptCategory:u}:{},..._?{gateway:_}:{},...f?{queryChainId:f.chainId,queryDepth:f.depth}:{},...p?{querySource:p}:{},fastMode:h,...g?{previousRequestId:g}:{},...K7()}),fc(`api_error`,{model:t,error:v,status_code:String(y),duration_ms:String(i),attempt:String(o),speed:h?`fast`:`normal`}),use(m,{success:!1,statusCode:y?parseInt(y,10):void 0,error:v,attempt:o})}function tdt({model:e,preNormalizedModel:t,messageCount:n,messageTokens:r,usage:i,durationMs:a,durationMsIncludingRetries:o,attempt:s,ttftMs:c,requestId:l,stopReason:u,costUSD:d,didFallBackToNonStreaming:f,querySource:p,gateway:m,queryTracking:h,permissionMode:g,globalCacheStrategy:_,textContentLength:v,thinkingContentLength:y,toolUseContentLengths:b,connectorTextBlockCount:x,fastMode:S,previousRequestId:C,betas:w}){let T=qt(),E=tne(),D=process.argv.includes(`-p`)||process.argv.includes(`--print`),O=Date.now(),k=tn(),A=k===null?void 0:O-k,ee=ye();Y(`tengu_api_success`,{model:e,...t===e?{}:{preNormalizedModel:t},...w?.length?{betas:w.join(`,`)}:{},messageCount:n,messageTokens:r,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cache_read_input_tokens??0,uncachedInputTokens:i.cache_creation_input_tokens??0,durationMs:a,durationMsIncludingRetries:o,attempt:s,ttftMs:c??void 0,buildAgeMins:Qut(),provider:Po(),requestId:l??void 0,...ee?{invokingRequestId:ee.invokingRequestId,invocationKind:ee.invocationKind}:{},stop_reason:u??void 0,costUSD:d,didFallBackToNonStreaming:f,isNonInteractiveSession:T,print:D,isTTY:process.stdout.isTTY??!1,querySource:p,...m?{gateway:m}:{},...h?{queryChainId:h.chainId,queryDepth:h.depth}:{},permissionMode:g,..._?{globalCacheStrategy:_}:{},...v===void 0?{}:{textContentLength:v},...y===void 0?{}:{thinkingContentLength:y},...b===void 0?{}:{toolUseContentLengths:U(b)},...x===void 0?{}:{connectorTextBlockCount:x},fastMode:S,...C?{previousRequestId:C}:{},...E?{isPostCompaction:E}:{},...K7(),timeSinceLastApiCallMs:A}),yn(O)}function ndt({model:e,preNormalizedModel:t,start:n,startIncludingRetries:r,ttftMs:i,usage:a,attempt:o,messageCount:s,messageTokens:c,requestId:l,stopReason:u,didFallBackToNonStreaming:d,querySource:f,headers:p,costUSD:m,queryTracking:h,permissionMode:g,newMessages:_,llmSpan:v,globalCacheStrategy:y,requestSetupMs:b,attemptStartTimes:x,fastMode:S,previousRequestId:C,betas:w}){let T=Zut({headers:p,baseUrl:process.env.ANTHROPIC_BASE_URL}),E,D,O,k;if(_){let e=0,t=0,n=!1,r={};for(let i of _){let a=Array.isArray(i.message.content)?i.message.content:[];for(let i of a)if(typeof i!=`string`){if(i.type===`text`)e+=i.text.length;else if(i.type===`thinking`)t+=i.thinking.length;else if(i.type===`tool_use`||i.type===`server_tool_use`||i.type===`mcp_tool_use`){let e=U(i.input).length,t=Ae(i.name);r[t]=(r[t]??0)+e,n=!0}}}E=e,D=t>0?t:void 0,O=n?r:void 0,k=void 0}let A=Date.now()-n,ee=Date.now()-r;qte(ee,A),tdt({model:e,preNormalizedModel:t,messageCount:s,messageTokens:c,usage:a,durationMs:A,durationMsIncludingRetries:ee,attempt:o,ttftMs:i,requestId:l,stopReason:u,costUSD:m,didFallBackToNonStreaming:d,querySource:f,gateway:T,queryTracking:h,permissionMode:g,globalCacheStrategy:y,textContentLength:E,thinkingContentLength:D,toolUseContentLengths:O,connectorTextBlockCount:k,fastMode:S,previousRequestId:C,betas:w}),fc(`api_request`,{model:e,input_tokens:String(a.input_tokens),output_tokens:String(a.output_tokens),cache_read_tokens:String(a.cache_read_input_tokens),cache_creation_tokens:String(a.cache_creation_input_tokens),cost_usd:String(m),duration_ms:String(A),speed:S?`fast`:`normal`});let te,ne;dc()&&_&&(te=_.flatMap(e=>{let t=e.message.content;return Array.isArray(t)?t.filter(e=>typeof e!=`string`&&e.type===`text`).map(e=>e.text):[]}).join(`
|
|
3279
|
+
`)||void 0,ne=_.some(e=>{let t=e.message.content;return Array.isArray(t)?t.some(e=>typeof e!=`string`&&e.type===`tool_use`):!1})),use(v,{success:!0,inputTokens:a.input_tokens,outputTokens:a.output_tokens,cacheReadTokens:a.cache_read_input_tokens,cacheCreationTokens:a.cache_creation_input_tokens,attempt:o,modelOutput:te,thinkingOutput:void 0,hasToolCall:ne,ttftMs:i??void 0,requestSetupMs:b,attemptStartTimes:x})}var rdt,idt,adt=n((()=>{Kn(),Jt(),K(),Ga(),Io(),mr(),hc(),pc(),xe(),oo(),Se(),Yut(),xL(),eL(),rdt={litellm:{prefixes:[`x-litellm-`]},helicone:{prefixes:[`helicone-`]},portkey:{prefixes:[`x-portkey-`]},"cloudflare-ai-gateway":{prefixes:[`cf-aig-`]},kong:{prefixes:[`x-kong-`]},braintrust:{prefixes:[`x-bt-`]}},idt={databricks:[`.cloud.databricks.com`,`.azuredatabricks.net`,`.gcp.databricks.com`]}}));function q7(e){let t=process.env.CLAUDE_CODE_EXTRA_BODY,n={};if(t)try{let e=Et(t);e&&typeof e==`object`&&!Array.isArray(e)?n={...e}:G(`CLAUDE_CODE_EXTRA_BODY env var must be a JSON object, but was given ${t}`,{level:`error`})}catch(e){G(`Error parsing CLAUDE_CODE_EXTRA_BODY: ${W(e)}`,{level:`error`})}if(e&&e.length>0)if(n.anthropic_beta&&Array.isArray(n.anthropic_beta)){let t=n.anthropic_beta,r=e.filter(e=>!t.includes(e));n.anthropic_beta=[...t,...r]}else n.anthropic_beta=e;return n}function odt(e){return!(h(process.env.DISABLE_PROMPT_CACHING)||h(process.env.DISABLE_PROMPT_CACHING_HAIKU)&&e===Jo()||h(process.env.DISABLE_PROMPT_CACHING_SONNET)&&e===zo()||h(process.env.DISABLE_PROMPT_CACHING_OPUS)&&e===qie())}function J7({scope:e,querySource:t}={}){return{type:`ephemeral`,...sdt(t)&&{ttl:`1h`},...e===`global`&&{scope:e}}}function sdt(e){if(Fo()===`bedrock`&&h(process.env.ENABLE_PROMPT_CACHING_1H_BEDROCK))return!0;let t=Ite();if(t===null&&(t=!1,Xte(t)),!t)return!1;let n=Wee();return n===null&&(n={}.allowlist??[],Gee(n)),e!==void 0&&n.some(t=>t.endsWith(`*`)?e.startsWith(t.slice(0,-1)):e===t)}function cdt(e,t,n){!e||`task_budget`in t||!be()||(t.task_budget={type:`tokens`,total:e.total,...e.remaining!==void 0&&{remaining:e.remaining}},n.includes(`task-budgets-2026-03-13`)||n.push(Vie))}function Y7(){let e={},t=process.env.CLAUDE_CODE_EXTRA_METADATA;if(t){let n=Et(t,!1);n&&typeof n==`object`&&!Array.isArray(n)?e=n:G(`CLAUDE_CODE_EXTRA_METADATA env var must be a JSON object, but was given ${t}`,{level:`error`})}return{user_id:U({...e,device_id:hie(),account_uuid:``,session_id:jn()})}}function ldt(e,t=!1,n,r){return t?typeof e.message.content==`string`?{role:`user`,content:[{type:`text`,text:e.message.content,...n&&{cache_control:J7({querySource:r})}}]}:{role:`user`,content:e.message.content.map((t,i)=>({...t,...i===e.message.content.length-1&&n?{cache_control:J7({querySource:r})}:{}}))}:{role:`user`,content:Array.isArray(e.message.content)?[...e.message.content]:e.message.content}}function udt(e,t=!1,n,r){return t?typeof e.message.content==`string`?{role:`assistant`,content:[{type:`text`,text:e.message.content,...n&&{cache_control:J7({querySource:r})}}]}:{role:`assistant`,content:e.message.content.map((t,i)=>{let a=ddt(t);return{...a,...i===e.message.content.length-1&&a.type!==`thinking`&&a.type!==`redacted_thinking`&&!td(a)&&n?{cache_control:J7({querySource:r})}:{}}})}:{role:`assistant`,content:typeof e.message.content==`string`?e.message.content:e.message.content.map(ddt)}}function ddt(e){if(typeof e==`string`||!(`_geminiThoughtSignature`in e))return e;let{_geminiThoughtSignature:t,...n}=e;return n}async function X7({messages:e,systemPrompt:t,thinkingConfig:n,tools:r,signal:i,options:a}){let o;for await(let s of jit(e,async function*(){yield*vdt(e,t,n,r,i,a)}))s.type===`assistant`&&(o=s);if(!o)throw i.aborted?new nr:Error(`No assistant message found`);return o}async function*fdt({messages:e,systemPrompt:t,thinkingConfig:n,tools:r,signal:i,options:a}){return yield*jit(e,async function*(){yield*vdt(e,t,n,r,i,a)})}function pdt(){return parseInt(process.env.API_TIMEOUT_MS||``,10)||(h(process.env.CLAUDE_CODE_REMOTE)?12e4:3e5)}async function*mdt(e,t,n,r,i,a){let o=pdt(),s=wL(()=>Ao({maxRetries:0,model:e.model,fetchOverride:e.fetchOverride,source:e.source}),async(s,c,l)=>{let u=Date.now(),d=n(l);i(d),r(c,u,d.max_tokens);let f=wdt(d,Edt);try{return await s.beta.messages.create({...f,model:Wo(f.model)},{signal:t.signal,timeout:o})}catch(t){throw t instanceof nr?t:(ei(`error`,`cli_nonstreaming_fallback_error`),Y(`tengu_nonstreaming_fallback_error`,{model:e.model,error:t instanceof Error?t.name:`unknown`,attempt:c,timeout_ms:o,request_id:a??`unknown`}),t)}},{model:t.model,fallbackModel:t.fallbackModel,thinkingConfig:t.thinkingConfig,...yo()&&{fastMode:t.fastMode},signal:t.signal,initialConsecutive529Errors:t.initialConsecutive529Errors,querySource:t.querySource}),c;do c=await s.next(),!c.done&&c.value.type===`system`&&(yield c.value);while(!c.done);return c.value}function hdt(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.type===`assistant`&&n.requestId)return n.requestId}}function Z7(e){return e.type===`image`||e.type===`document`}function gdt(e){return e.type===`tool_result`}function _dt(e,t){let n=0;for(let t of e)if(Array.isArray(t.message.content)){for(let e of t.message.content)if(Z7(e)&&n++,gdt(e)&&Array.isArray(e.content))for(let t of e.content)Z7(t)&&n++}return n-=t,n<=0?e:e.map(e=>{if(n<=0)return e;let t=e.message.content;if(!Array.isArray(t))return e;let r=n,i=t.map(e=>{if(n<=0||!gdt(e)||!Array.isArray(e.content))return e;let t=e.content.filter(e=>n>0&&Z7(e)?(n--,!1):!0);return t.length===e.content.length?e:{...e,content:t}}).filter(e=>n>0&&Z7(e)?(n--,!1):!0);return r===n?e:{...e,message:{...e.message,content:i}}})}async function*vdt(e,t,n,r,i,a){let o=hdt(e),s=Fo()===`bedrock`&&a.model.includes(`application-inference-profile`)?await es(a.model)??a.model:a.model;M1(`query_tool_schema_build_start`);let c=a.querySource.startsWith(`repl_main_thread`)||a.querySource.startsWith(`agent:`)||a.querySource===`sdk`||a.querySource===`hook_agent`||a.querySource===`verification_agent`,l=Te(a.model,{isAgenticQuery:c});uv()&&l.push(Rie);let u;if(c&&uv()){let e=a.advisorModel,t=mhe();if(t!==void 0&&Wo(t.baseModel)===Wo(a.model)&&(e=t.advisorModel),e){let t=Wo(Lo(e));fv(a.model)?pv(t)?(u=t,G(`[AdvisorTool] Server-side tool enabled with ${u} as the advisor model`)):G(`[AdvisorTool] Skipping advisor - ${t} is not a valid advisor model`):G(`[AdvisorTool] Skipping advisor - base model ${a.model} does not support advisor`)}}let d=await _z(a.model,r,a.getToolPermissionContext,a.agents,`query`),f=new Set;if(d)for(let e of r)As(e)&&f.add(e.name);d&&f.size===0&&!a.hasPendingMcpServers&&(G(`Tool search disabled: no deferred tools available to search`),d=!1);let p;p=d?r.filter(e=>!!(!f.has(e.name)||Cs(e,`SearchExtraTools`))):r.filter(e=>!Cs(e,Hs));let m=Fe(),g=m&&p.some(e=>e.isMcp===!0);m&&!l.includes(`prompt-caching-scope-2026-01-05`)&&l.push(Nie);let _=m?g?`none`:`system_prompt`:`none`,v=await Promise.all(p.map(e=>V7(e,{getToolPermissionContext:a.getToolPermissionContext,tools:r,agents:a.agents,allowedAgentTypes:a.allowedAgentTypes,model:a.model})));d&&G(`Dynamic tool loading: 0/${f.size} deferred tools in API tools array (all via ExecuteExtraTool)`),M1(`query_tool_schema_build_end`),Y(`tengu_api_before_normalize`,{preNormalizedMessageCount:e.length}),M1(`query_message_normalization_start`);let y=c3(e,p);if(M1(`query_message_normalization_end`),d||(y=y.map(e=>{switch(e.type){case`user`:return Trt(e);case`assistant`:return Ert(e);default:return e}})),y=Mrt(y),l.includes(`advisor-tool-2026-03-01`)||(y=Nrt(y)),y=_dt(y,100),Fo()===`openai`){let{queryModelOpenAI:e}=await import(`./openai-D46QvESE.js`);yield*e(y,t,r,i,a);return}if(Fo()===`gemini`){let{queryModelGemini:e}=await import(`./gemini-C_ApXgwc.js`);yield*e(y,t,p,i,a,n);return}if(Fo()===`grok`){let{queryModelGrok:e}=await import(`./grok-C6WAslUT.js`);yield*e(y,t,p,i,a);return}if(Y(`tengu_api_after_normalize`,{postNormalizedMessageCount:y.length}),d&&!bz()){let e=r.filter(e=>f.has(e.name)).map(uoe).sort().join(`
|
|
3280
3280
|
`);if(e){let t=new Set(e.split(`
|
|
3281
3281
|
`));if([...t].some(e=>!t9.has(e))){t9.clear();for(let e of t)t9.add(e);y=[...y,Q({content:`<system-reminder>\n<available-deferred-tools>\n${e}\n</available-deferred-tools>\nIMPORTANT: The tools listed above are deferred-loading — they are NOT in your tool list. To use them, you MUST first discover a tool via SearchExtraTools, then invoke it with ExecuteExtraTool.\n\nSearchExtraTools and ExecuteExtraTool are core tools already in your tool list right now — call them directly, do NOT use Bash/Glob to find them.\n\nSteps:\n1. SearchExtraTools({"query": "select:<tool_name>"}) — discover the tool and its schema\n2. ExecuteExtraTool({"tool_name": "<name>", "params": {...}}) — invoke it with correct parameters\n</system-reminder>`,isMeta:!0})]}}}t=gv([Ju(),qu({isNonInteractive:a.isNonInteractiveSession,hasAppendSystemPrompt:a.hasAppendSystemPrompt}),...t,...u?[_he]:[]].filter(Boolean));{let e=woe(),n=Toe();if(Hc(e)||Hc(n)){let n=Jc();if(t=gv([...t,`<!-- cache-break nonce: ${n} -->`]),Hc(e))try{pce(e)}catch{}}}Put(t);let b=a.enablePromptCaching??odt(a.model),x=Cdt(t,b,{skipGlobalCacheForSystemPrompt:g,querySource:a.querySource}),S=l.length>0,C=[...a.extraToolSchemas??[]];u&&C.push({type:`advisor_20260301`,name:`advisor`,model:u});let w=[...v,...C],T=yo()&&jo()&&!Mo()&&Co(a.model)&&!!a.fastMode,E=Bte()===!0;!E&&c&&be()&&nI()&&(E=!0,yte(!0));let D=rte()===!0;!D&&T&&(D=!0,ane(!0));let O=kte()===!0;Vke({system:x,toolSchemas:w.filter(e=>!(`defer_loading`in e&&e.defer_loading)),querySource:a.querySource,model:a.model,agentId:a.agentId,fastMode:D,globalCacheStrategy:_,betas:l,autoModeActive:E,isUsingOverage:s0.isUsingOverage??!1,cachedMCEnabled:O,extraBodyParams:q7()});let k=dc()?{systemPrompt:t.join(`
|
|
3282
3282
|
|