@readmagic/workmate 0.0.16 → 0.0.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/{AddWorkspaceDirectory-DAtfMH4o.js → AddWorkspaceDirectory-YAhnVwyN.js} +1 -1
- package/dist/chunks/AgentsMdExternalIncludesDialog--D4BeNAN.js +1 -0
- package/dist/chunks/{AgentsMdExternalIncludesDialog-BTYgjY5c.js → AgentsMdExternalIncludesDialog-Ba4GYFl3.js} +1 -1
- package/dist/chunks/{App-HF0bvxi_.js → App-mri25OrC.js} +1 -1
- package/dist/chunks/{ApproveApiKey-BBFLw2B7.js → ApproveApiKey-DCw6d7dm.js} +1 -1
- package/dist/chunks/ApproveApiKey-lv4Sg0RR.js +1 -0
- package/dist/chunks/{BackgroundTasksDialog-Coc0ecUd.js → BackgroundTasksDialog-CZND8e_Z.js} +1 -1
- package/dist/chunks/{BypassPermissionsModeDialog--Gx9ARd4.js → BypassPermissionsModeDialog-B5QBJTB4.js} +1 -1
- package/dist/chunks/{DiffDialog-tlINuFS1.js → DiffDialog-Bd-DcTsK.js} +1 -1
- package/dist/chunks/{Doctor-Wh7z6CnF.js → Doctor-C9t7udHN.js} +1 -1
- package/dist/chunks/Doctor-V-JLC4e3.js +1 -0
- package/dist/chunks/{ExitFlow-B1zHTqQt.js → ExitFlow-CShdrKmr.js} +1 -1
- package/dist/chunks/{Grove-1Kf7xxIV.js → Grove-CClEZT2e.js} +1 -1
- package/dist/chunks/{HybridTransport-DWqWUZCH.js → HybridTransport-DyEuslQB.js} +1 -1
- package/dist/chunks/{InvalidConfigDialog-OZPFQSnC.js → InvalidConfigDialog-Wyrk_cXR.js} +1 -1
- package/dist/chunks/{InvalidSettingsDialog-BNCm-eyC.js → InvalidSettingsDialog-Cr9fmSyh.js} +1 -1
- package/dist/chunks/{MCPConnectionManager-7H84oi5n.js → MCPConnectionManager-BnUw0nYN.js} +1 -1
- package/dist/chunks/{MCPToolListView-CVgtg3Iq.js → MCPToolListView-CY2EezWF.js} +1 -1
- package/dist/chunks/{McpParsingWarnings-CN8f449l.js → McpParsingWarnings-BF4np2Y3.js} +1 -1
- package/dist/chunks/{MessageSelector-B9j6zZ5w.js → MessageSelector-Dtt2Sf65.js} +1 -1
- package/dist/chunks/{Messages-yz1m39eI.js → Messages-D5Uuapmf.js} +1 -1
- package/dist/chunks/{Onboarding-bFbgae8m.js → Onboarding-BAJXV7Ay.js} +1 -1
- package/dist/chunks/{PromptInputFooterSuggestions-CE_yVun1.js → PromptInputFooterSuggestions-Cm4WN3qd.js} +1 -1
- package/dist/chunks/{PromptInputHelpMenu-TPWuGwAy.js → PromptInputHelpMenu-ESj8sOpK.js} +1 -1
- package/dist/chunks/{QueryEngine-CRobcENE.js → QueryEngine-B79JLwG4.js} +1 -1
- package/dist/chunks/REPL-B7evbhvN.js +1 -0
- package/dist/chunks/{REPL-C33mMf_q.js → REPL-cAXdORs2.js} +5 -5
- package/dist/chunks/{RemoteSessionManager-BjVD918g.js → RemoteSessionManager-C5pAD0Lh.js} +1 -1
- package/dist/chunks/{ResumeConversation-CXd8d8po.js → ResumeConversation-NSVT3gn7.js} +1 -1
- package/dist/chunks/{SSETransport-BSilVN9e.js → SSETransport-CDGMGrxN.js} +1 -1
- package/dist/chunks/SearchExtraToolsTool-CddjJcAH.js +1 -0
- package/dist/chunks/{Settings-ClcLl0C1.js → Settings-_b5Yxt_9.js} +2 -2
- package/dist/chunks/{TeleportProgress-DonJUoPc.js → TeleportProgress-8cS6aHVO.js} +1 -1
- package/dist/chunks/{TeleportRepoMismatchDialog-ByOuSVVz.js → TeleportRepoMismatchDialog-B0epkMgp.js} +1 -1
- package/dist/chunks/{TeleportResumeWrapper-BBtELwF1.js → TeleportResumeWrapper-Bb14JeEk.js} +1 -1
- package/dist/chunks/{ThemePicker-1QQJFOEv.js → ThemePicker-CnX8faYA.js} +1 -1
- package/dist/chunks/{TrustDialog-DwJ9L_u4.js → TrustDialog-6wJF3W6K.js} +1 -1
- package/dist/chunks/{add-dir-DOKdPFT2.js → add-dir-LLAv-rGS.js} +1 -1
- package/dist/chunks/{agentDisplay-TX1bh-lX.js → agentDisplay-QqGqcHGz.js} +1 -1
- package/dist/chunks/{agents-CbRjX9Pj.js → agents-C8wRUTNV.js} +1 -1
- package/dist/chunks/{agents-C58tRxpi.js → agents-DFPEienW.js} +1 -1
- package/dist/chunks/{allErrors-DRiW7i6Y.js → allErrors-DUYYPpdH.js} +1 -1
- package/dist/chunks/{api-CazVavfB.js → api-B3Wnozaf.js} +1 -1
- package/dist/chunks/api-BAT--5sp.js +1 -0
- package/dist/chunks/{auth-CfrCl9BZ.js → auth-CQGJitIV.js} +1 -1
- package/dist/chunks/auth-DaJXqwN5.js +1 -0
- package/dist/chunks/auth-DkhPycBL.js +1 -0
- package/dist/chunks/{backgroundHousekeeping-CPLlaWcV.js → backgroundHousekeeping-Bjb_Jc7L.js} +2 -2
- package/dist/chunks/backgroundHousekeeping-V-dg2j2E.js +1 -0
- package/dist/chunks/{branch-pAa0oBaj.js → branch-BWq5ynjm.js} +1 -1
- package/dist/chunks/{bridgeConfig-DnFfCpGd.js → bridgeConfig-B3mR0kJ0.js} +1 -1
- package/dist/chunks/bridgeConfig-D31i4BRi.js +1 -0
- package/dist/chunks/{bridgeMessaging-B_hnuUHb.js → bridgeMessaging-wZ5EKxW_.js} +1 -1
- package/dist/chunks/{bridgeStatusUtil-Dwz4YHNA.js → bridgeStatusUtil-mvVQSVN-.js} +1 -1
- package/dist/chunks/{btw-CkVkYeRr.js → btw-XNgXHnNr.js} +1 -1
- package/dist/chunks/{caches-BLQUkrIG.js → caches-ByLjTvdy.js} +1 -1
- package/dist/chunks/caches-ckqJ4Qso.js +1 -0
- package/dist/chunks/{ccrClient-AfdUbWzY.js → ccrClient-EisctZbc.js} +1 -1
- package/dist/chunks/{clear-Ac3qYi_-.js → clear-BjtPf2Jb.js} +1 -1
- package/dist/chunks/client-Bl43xcRk.js +1 -0
- package/dist/chunks/commands-BDhn7EPO.js +1 -0
- package/dist/chunks/{compact-CXuDr5qM.js → compact-w8AhLkr6.js} +1 -1
- package/dist/chunks/config-CbAvTdZ7.js +1 -0
- package/dist/chunks/{context-C2plOqH4.js → context-Btn2JU2y.js} +1 -1
- package/dist/chunks/{context-noninteractive-fVQtwEkw.js → context-noninteractive-044464Vs.js} +1 -1
- package/dist/chunks/context-noninteractive-ulRLlYg5.js +1 -0
- package/dist/chunks/conversation-D08lU377.js +1 -0
- package/dist/chunks/{conversation-DQpS6nvg.js → conversation-a82khZ_n.js} +1 -1
- package/dist/chunks/{createSSHSession-CfyFuJMH.js → createSSHSession-C0KSI0fJ.js} +1 -1
- package/dist/chunks/{createSession-qk9C66lK.js → createSession-8ScCWTKb.js} +1 -1
- package/dist/chunks/createSession-CnlPXXkA.js +1 -0
- package/dist/chunks/{crossProjectResume-DY1ZBO5P.js → crossProjectResume-BCN462Wa.js} +1 -1
- package/dist/chunks/{datadog-Cr0VKbct.js → datadog-BqINRWAW.js} +1 -1
- package/dist/chunks/{diff-BNjcCXDr.js → diff-CcrSQNvQ.js} +1 -1
- package/dist/chunks/doctor-DRFDBrH1.js +1 -0
- package/dist/chunks/{entry-o9IZPS4g.js → entry-oVZ7Z59B.js} +1 -1
- package/dist/chunks/{esm-BI3tFLyy.js → esm-BZciQG9N.js} +1 -1
- package/dist/chunks/{exit-Dlyj7nY8.js → exit-jikLI2Zh.js} +1 -1
- package/dist/chunks/{extraUsage-5Ueiyw6W.js → extraUsage-BT3in1Aj.js} +1 -1
- package/dist/chunks/extractMemories-BsQU2bVO.js +1 -0
- package/dist/chunks/fast-B9vVL3sY.js +1 -0
- package/dist/chunks/{fast-ClOKONyD.js → fast-CKhtBOx7.js} +1 -1
- package/dist/chunks/fetchModelList-BeL40TyR.js +1 -0
- package/dist/chunks/{fetchModelList-gh_jFYai.js → fetchModelList-DmaMgpa2.js} +1 -1
- package/dist/chunks/{fileSuggestions-DK7W8kLF.js → fileSuggestions-BfG3sbET.js} +1 -1
- package/dist/chunks/firstPartyEventLogger-6GwZ6VLr.js +1 -0
- package/dist/chunks/{firstPartyEventLogger-BMnXb9cv.js → firstPartyEventLogger-Q3fMF0BR.js} +2 -2
- package/dist/chunks/{flushGate-n4kK6H1U.js → flushGate-COa_KO98.js} +1 -1
- package/dist/chunks/{gemini-C8-QHnsC.js → gemini-L8Gj2B4H.js} +1 -1
- package/dist/chunks/{generateSessionName-C8DnAVaa.js → generateSessionName-cAL5T7pG.js} +1 -1
- package/dist/chunks/{goal-DMmzlZOF.js → goal-D-x2WXm7.js} +1 -1
- package/dist/chunks/{grok-LLjpAwP_.js → grok-DtypRM4d.js} +1 -1
- package/dist/chunks/{grove-CQBCzeHf.js → grove-CSivzrhe.js} +1 -1
- package/dist/chunks/{help-JH7WzjZP.js → help-DKZhC0lL.js} +1 -1
- package/dist/chunks/{hooks-DD2jpRfx.js → hooks-D_afUDcs.js} +1 -1
- package/dist/chunks/hooks-DvVuNKRx.js +1 -0
- package/dist/chunks/{initReplBridge-BDaN0hpY.js → initReplBridge-sTaq4a0K.js} +1 -1
- package/dist/chunks/{install-CD4or0vj.js → install-BWe3Jz4M.js} +1 -1
- package/dist/chunks/{instrumentation-n-otwpYf.js → instrumentation-IljwxX0V.js} +3 -3
- package/dist/chunks/{job-B-pEWgXI.js → job-N25KhSUu.js} +1 -1
- package/dist/chunks/{keybindings-qed9q9tx.js → keybindings-DLEorhlY.js} +1 -1
- package/dist/chunks/{launchLocalMemory-cBovdGMT.js → launchLocalMemory-DJsuNLIf.js} +1 -1
- package/dist/chunks/{launchOnboarding-B__wtt7p.js → launchOnboarding-CVvuxeH-.js} +1 -1
- package/dist/chunks/{loadAgentsDir-PPiD2Mfq.js → loadAgentsDir-CbtNPJV3.js} +23 -23
- package/dist/chunks/loadAgentsDir-D0gl_H2S.js +1 -0
- package/dist/chunks/{loadPluginHooks-DUCuU3_8.js → loadPluginHooks-BxkDBFd6.js} +1 -1
- package/dist/chunks/{localSearch-Cvs9WfoX.js → localSearch-B5mTHBwK.js} +1 -1
- package/dist/chunks/localSearch-D3UrYUre.js +1 -0
- package/dist/chunks/{logoV2Utils-Bkj74dtY.js → logoV2Utils-D5nRpirL.js} +1 -1
- package/dist/chunks/{magicDocs-3U6peChg.js → magicDocs-C9aIo4Oe.js} +1 -1
- package/dist/chunks/{main-DkjxhBIC.js → main-DeUt_aE2.js} +9 -9
- package/dist/chunks/managedEnv-ADMKY7-G.js +1 -0
- package/dist/chunks/{managedEnv-BUrzwaD3.js → managedEnv-CDxyrUw1.js} +1 -1
- package/dist/chunks/{mappers-ZGgwqDOK.js → mappers-Del1KoA7.js} +1 -1
- package/dist/chunks/{mcp-COZxwgJZ.js → mcp-Bh3MNBIj.js} +2 -2
- package/dist/chunks/{mcp-CdyNeNzh.js → mcp-D7vMhEOV.js} +1 -1
- package/dist/chunks/{mcp-CysOyBIn.js → mcp-nnBVM5Lt.js} +1 -1
- package/dist/chunks/{memory-B5h2TTSS.js → memory-DtqQhHu8.js} +1 -1
- package/dist/chunks/{mode-D3yY1fdK.js → mode-DPbrxU32.js} +1 -1
- package/dist/chunks/{model-Bz4JHoU0.js → model-B50j-O5v.js} +1 -1
- package/dist/chunks/model-DLG1nrnf.js +1 -0
- package/dist/chunks/{model-sviY1inu.js → model-DlLO7TSx.js} +1 -1
- package/dist/chunks/{modelOptions-DYQqTLPi.js → modelOptions-SMq3one0.js} +1 -1
- package/dist/chunks/{nativeInstaller-N1xiUpCP.js → nativeInstaller-DTJ4clp-.js} +1 -1
- package/dist/chunks/{omit-BOILu8jW.js → omit-CMldTqqy.js} +1 -1
- package/dist/chunks/{onChangeAppState-COFFZAXb.js → onChangeAppState-EAnsmOuo.js} +1 -1
- package/dist/chunks/{openai-BHM5kEFo.js → openai-D9KvLMrj.js} +1 -1
- package/dist/chunks/{partition-C1SFDk_L.js → partition-B8Y4jvjW.js} +1 -1
- package/dist/chunks/{permissions-uy_NFbfy.js → permissions-cDtIZRM1.js} +1 -1
- package/dist/chunks/{pidLock-DuMVSwnN.js → pidLock-Br3_YNi_.js} +2 -2
- package/dist/chunks/{plan-DF9YSB5M.js → plan-dG2H4eQl.js} +1 -1
- package/dist/chunks/{plugin-GRPzqgTr.js → plugin-CzQHuIlP.js} +1 -1
- package/dist/chunks/{pluginAutoupdate-AMD-FvKB.js → pluginAutoupdate-B9W_vxOG.js} +1 -1
- package/dist/chunks/{pluginBlocklist-DNxkAxH6.js → pluginBlocklist-BvdBsnJG.js} +1 -1
- package/dist/chunks/{pluginCliCommands-BFoR1ZXx.js → pluginCliCommands-NKIgFTUF.js} +1 -1
- package/dist/chunks/{pluginFlagging-CW2IZWSI.js → pluginFlagging-C0PtAJEg.js} +1 -1
- package/dist/chunks/{pluginOperations-DlWE0idP.js → pluginOperations-wUUdFpu9.js} +1 -1
- package/dist/chunks/pluginStartupCheck-hDT6pEAd.js +1 -0
- package/dist/chunks/{pluginStartupCheck-AQGV0DCS.js → pluginStartupCheck-p0njap1l.js} +1 -1
- package/dist/chunks/{plugins-CwUSTE4E.js → plugins-B9WBqOAW.js} +1 -1
- package/dist/chunks/{print-9wR_ijrL.js → print-G3DgPTxy.js} +3 -3
- package/dist/chunks/{processBashCommand-Deqwq1IE.js → processBashCommand-zLWgCRws.js} +1 -1
- package/dist/chunks/{processSlashCommand-U9LJ4Keq.js → processSlashCommand-BHBnHBjj.js} +1 -1
- package/dist/chunks/{prompt-CQmEvnKN.js → prompt-BRGC5U9Y.js} +1 -1
- package/dist/chunks/prompt-Ct3Ryb3C.js +1 -0
- package/dist/chunks/prompt-TZJKyomz.js +1 -0
- package/dist/chunks/{promptEditor-Bf72KNF-.js → promptEditor-CRIw6vJS.js} +1 -1
- package/dist/chunks/{reconciler-Css9bs07.js → reconciler-DiU1RvGD.js} +1 -1
- package/dist/chunks/{refresh-B87z39Zs.js → refresh-DEXe3Lmx.js} +1 -1
- package/dist/chunks/{reload-plugins-BpmUIkfm.js → reload-plugins-Cl6wvT6V.js} +1 -1
- package/dist/chunks/{remoteBridgeCore-BCLIIygk.js → remoteBridgeCore-DnFZoXaw.js} +1 -1
- package/dist/chunks/{remoteManagedSettings-Ahgn2e80.js → remoteManagedSettings-BboLJ46D.js} +1 -1
- package/dist/chunks/{rename-BUt3PliQ.js → rename-CdzxOzN5.js} +1 -1
- package/dist/chunks/{resume-uZI9p_FE.js → resume-DgFXYWTN.js} +1 -1
- package/dist/chunks/{runtimeObserver-AKOWfdZ_.js → runtimeObserver-CwtRE2cj.js} +1 -1
- package/dist/chunks/{runtimeObserver-By59MZKJ.js → runtimeObserver-Dov-m2dl.js} +2 -2
- package/dist/chunks/sandbox-adapter-CtEngx-6.js +1 -0
- package/dist/chunks/{sandbox-toggle-BdvylnWS.js → sandbox-toggle-DWCrG9zV.js} +1 -1
- package/dist/chunks/searchExtraTools-zFMN5MqY.js +1 -0
- package/dist/chunks/{session-Tm2-rzBY.js → session-L5191BSn.js} +1 -1
- package/dist/chunks/sessionFileAccessHooks-C2VjT-PU.js +1 -0
- package/dist/chunks/sessionObserver-BuhXr3FP.js +1 -0
- package/dist/chunks/{sessionObserver-BAr8AWeL.js → sessionObserver-DpY0DOjI.js} +1 -1
- package/dist/chunks/{sessionState-BTFowSpR.js → sessionState-BlbRQ3Y6.js} +1 -1
- package/dist/chunks/sessionStorage-CiYSwyY3.js +1 -0
- package/dist/chunks/sessionTitle-k4wpUS5l.js +2 -0
- package/dist/chunks/{sessionTracing-CvY4udYI.js → sessionTracing-DqVx8aFD.js} +1 -1
- package/dist/chunks/{settingsSync-nxeaGM2-.js → settingsSync-BhlegQAU.js} +1 -1
- package/dist/chunks/{setup-D4FPeBnM.js → setup-DvnKMqDy.js} +2 -2
- package/dist/chunks/{shadowedRuleDetection-Co8m1q1D.js → shadowedRuleDetection-Gerk3t93.js} +1 -1
- package/dist/chunks/{sideQuestion-4TJYn-Az.js → sideQuestion-RndkXExy.js} +1 -1
- package/dist/chunks/sinks-Cf4vx9UX.js +1 -0
- package/dist/chunks/{sinks-Bb2i50kz.js → sinks-CfzgqLH5.js} +1 -1
- package/dist/chunks/{skillChangeDetector-BU9AFG0i.js → skillChangeDetector-BQx4xe_b.js} +1 -1
- package/dist/chunks/{skillGapStore-BcVP3ZUb.js → skillGapStore-CLxhWLyq.js} +2 -2
- package/dist/chunks/{skillLifecycle-CG2XmS8f.js → skillLifecycle-CSNX2qOH.js} +2 -2
- package/dist/chunks/{skillSearchPanel-DOJmUBXB.js → skillSearchPanel-CsQDjy_E.js} +2 -2
- package/dist/chunks/{skills-DIgCWvzX.js → skills-DM9ACPW-.js} +1 -1
- package/dist/chunks/status-C3z0CSBw.js +1 -0
- package/dist/chunks/{status-Ber2xOXc.js → status-C5v7KsX4.js} +1 -1
- package/dist/chunks/{statusNoticeHelpers-CYkrPUpN.js → statusNoticeHelpers-BY_8pK19.js} +1 -1
- package/dist/chunks/switcher-C9VsM-ip.js +1 -0
- package/dist/chunks/{switcher-BIP3rbQn.js → switcher-CnBKuiNp.js} +1 -1
- package/dist/chunks/{syncCache-AMQMQ_HR.js → syncCache-Dff4hbz4.js} +1 -1
- package/dist/chunks/{tasks-BKERIO4G.js → tasks-qVyXOLBf.js} +1 -1
- package/dist/chunks/{teleport-DOXbf2sQ.js → teleport-Deq_ecN9.js} +1 -1
- package/dist/chunks/{templateJobs-dg2F45ZJ.js → templateJobs-CntPyct-.js} +1 -1
- package/dist/chunks/{theme-BGxytGjA.js → theme-DVWYzSct.js} +1 -1
- package/dist/chunks/{toolEventObserver-CJhg_p3P.js → toolEventObserver-BZn8ZJB5.js} +1 -1
- package/dist/chunks/{toolPool-C0d7Bznl.js → toolPool-Dzp1ob3I.js} +1 -1
- package/dist/chunks/trustedDevice-1Q4FTNyX.js +1 -0
- package/dist/chunks/{trustedDevice-BtXHXu-T.js → trustedDevice-CdLAZK6m.js} +1 -1
- package/dist/chunks/{useExitOnCtrlCDWithKeybindings-C9orgrub.js → useExitOnCtrlCDWithKeybindings-YSWYVWk6.js} +1 -1
- package/dist/chunks/useMainLoopModel-C1JRp4zE.js +1 -0
- package/dist/chunks/{useManagePlugins-Bt-DYAnX.js → useManagePlugins-DfuI4Nhd.js} +1 -1
- package/dist/chunks/{useMergedTools-CZeQBdky.js → useMergedTools-B4qRVJ8b.js} +1 -1
- package/dist/chunks/{useSearchInput-DdKrVHJS.js → useSearchInput-DfUNYhqC.js} +1 -1
- package/dist/chunks/{useSettingsErrors-BR9Wws7D.js → useSettingsErrors-Bls74ocI.js} +1 -1
- package/dist/chunks/{userAgent-DUt0q-Vl.js → userAgent-CNPTS7ix.js} +1 -1
- package/dist/chunks/{util-h-Hmdke_.js → util-6aJHnBQ_.js} +1 -1
- package/dist/chunks/{validatePlugin-mWVKNtJa.js → validatePlugin-BajM6yNf.js} +1 -1
- package/dist/chunks/{workerRegistry-dlfqtySm.js → workerRegistry-BwJ54Lzk.js} +2 -2
- package/dist/chunks/worktree-BFP10vim.js +1 -0
- package/dist/cli.js +1 -1
- package/package.json +1 -1
- package/dist/chunks/AgentsMdExternalIncludesDialog-C6VH6JG6.js +0 -1
- package/dist/chunks/ApproveApiKey-B7mKgSqY.js +0 -1
- package/dist/chunks/Doctor-BJf49FWX.js +0 -1
- package/dist/chunks/REPL-BhCC0JP6.js +0 -1
- package/dist/chunks/SearchExtraToolsTool-DoiCI2uJ.js +0 -1
- package/dist/chunks/api-C8uOHD-v.js +0 -1
- package/dist/chunks/auth-BL238vgr.js +0 -1
- package/dist/chunks/auth-D3GkU6d7.js +0 -1
- package/dist/chunks/backgroundHousekeeping-Du2tN2WE.js +0 -1
- package/dist/chunks/bridgeConfig-joBqeK0j.js +0 -1
- package/dist/chunks/caches-DsFl83sh.js +0 -1
- package/dist/chunks/client-BX0r6K3I.js +0 -1
- package/dist/chunks/commands-BKLsl6gK.js +0 -1
- package/dist/chunks/config-DrY1SvhQ.js +0 -1
- package/dist/chunks/context-noninteractive-DpVlZ-wP.js +0 -1
- package/dist/chunks/conversation-C0yysXds.js +0 -1
- package/dist/chunks/createSession-CmBawnsh.js +0 -1
- package/dist/chunks/doctor-BkCtT7H1.js +0 -1
- package/dist/chunks/extractMemories-DnTBWFOW.js +0 -1
- package/dist/chunks/fast-B3fRp1xO.js +0 -1
- package/dist/chunks/fetchModelList-B8KG79EK.js +0 -1
- package/dist/chunks/firstPartyEventLogger-YYOb8aIo.js +0 -1
- package/dist/chunks/hooks-COhKt_pF.js +0 -1
- package/dist/chunks/loadAgentsDir-qvqrTVuS.js +0 -1
- package/dist/chunks/localSearch-CDk_stXJ.js +0 -1
- package/dist/chunks/managedEnv-XOUMOtEF.js +0 -1
- package/dist/chunks/model-g6XBcNAG.js +0 -1
- package/dist/chunks/pluginStartupCheck-DWpquqxx.js +0 -1
- package/dist/chunks/prompt-BBeDQXIs.js +0 -1
- package/dist/chunks/prompt-CXhdqgB7.js +0 -1
- package/dist/chunks/sandbox-adapter-D4Uho1vF.js +0 -1
- package/dist/chunks/searchExtraTools-BHMkqGBf.js +0 -1
- package/dist/chunks/sessionFileAccessHooks-BaWZ8sqn.js +0 -1
- package/dist/chunks/sessionObserver-KB1UL_n2.js +0 -1
- package/dist/chunks/sessionStorage-D6nlmaI-.js +0 -1
- package/dist/chunks/sessionTitle-SCqmSDYM.js +0 -14
- package/dist/chunks/sinks-D1opmy_x.js +0 -1
- package/dist/chunks/status-CVcXPoOZ.js +0 -1
- package/dist/chunks/switcher-zbG6T9dN.js +0 -1
- package/dist/chunks/trustedDevice-hw3iq84W.js +0 -1
- package/dist/chunks/useMainLoopModel-BigVcn2T.js +0 -1
- package/dist/chunks/worktree-IxcFe7g-.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,i as p,l as m,o as h,p as g,r as _,s as v,u as y}from"./envUtils-DcaKZlRU.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{n as ue,t as de}from"./axios-DaWTGg7G.js";import{$r as fe,Bt as pe,Ct as me,D as he,Fr as ge,Ft as _e,G as ve,Gr as ye,Gt as be,H as xe,Hr as Se,I as P,Kr as Ce,Lr as we,Lt as Te,Mr as Ee,P as F,Pr as De,Pt as Oe,Qr as ke,Rn as Ae,T as je,Tt as Me,Vr as Ne,Vt as Pe,Wt as Fe,Xn as Ie,Yt as Le,Zt as eee,_ as Re,ai as ze,bn as Be,cr as Ve,d as He,di as Ue,et as We,fi as Ge,fr as Ke,gr as qe,gt as tee,hn as Je,hr as nee,j as ree,l as iee,ln as aee,mi as oee,mr as see,mt as Ye,nt as cee,or as lee,ot as Xe,pi as uee,pr as dee,qr as Ze,rn as fee,sn as Qe,sr as pee,t as I,ui as mee,vn as hee,xr as gee,y as $e,yn as _ee,yr as vee,zr as et}from"./src-DL3w8VPk2.js";import{i as yee,r as bee}from"./isSymbol-BO6cdPI7.js";import{t as tt}from"./jsx-runtime-Bb4Xn-E0.js";import{A as L,B as xee,C as R,D as nt,H as See,I as Cee,M as rt,N as wee,O as it,R as Tee,T as at,U as Eee,a as ot,b as st,f as ct,g as lt,h as Dee,j as ut,k as dt,l as ft,m as pt,p as z,s as Oee,u as kee,v as Aee,w as B,x as mt}from"./external-CEp-aPkt.js";import{i as ht,n as gt,r as _t,t as vt}from"./lazySchema-B4D4qJVE.js";import{$t as yt,Ai as jee,At as bt,B as xt,Bn as Mee,Br as St,Bt as Nee,C as Pee,Cr as Ct,Ct as Fee,D as Iee,Dn as wt,Dt as Lee,E as Ree,En as Tt,Et,Fr as zee,Ft as Bee,G as Vee,Gr as Dt,Gt as Ot,H as kt,Hn as Hee,Hr as Uee,Ht as Wee,I as At,It as Gee,Jt as Kee,K as jt,Kr as qee,Kt as Mt,L as Jee,Ln as Nt,Lt as Yee,Mi as Xee,Mr as Pt,Mt as Zee,Ni as Qee,Nr as Ft,Nt as $ee,O as It,Oi as ete,On as Lt,Ot as Rt,Pr as tte,Q as zt,R as Bt,Rn as Vt,Rr as Ht,Rt as nte,S as rte,Sr as Ut,St as ite,T as ate,Ti as ote,Tt as ste,U as cte,Un as lte,Ur as ute,Ut as dte,V as fte,Vn as pte,Vr as mte,Wn as hte,Wr as Wt,Wt as Gt,Xt as gte,Y as _te,Yt as vte,_ as yte,_i as bte,_n as Kt,_r as qt,_t as Jt,a as xte,ai as Ste,an as Cte,at as wte,bi as Yt,br as Tte,bt as Ete,c as Dte,ci as Ote,cn as kte,cr as Ate,ct as jte,d as Mte,dn as Nte,dr as Pte,dt as Xt,et as Zt,f as Fte,fi as Ite,g as Lte,gi as Rte,gr as Qt,h as $t,ht as en,i as zte,ii as Bte,it as tn,j as Vte,ji as Hte,jt as nn,ki as Ute,kn as Wte,kt as rn,li as Gte,lr as an,lt as on,m as Kte,mn as qte,mr as Jte,n as Yte,ni as Xte,nt as sn,o as Zte,or as cn,ot as Qte,p as $te,pi as ene,pt as ln,qr as tne,qt as un,r as nne,ri as dn,rt as fn,s as rne,st as ine,t as ane,tr as one,u as pn,un as sne,ur as mn,ut as hn,vt as cne,w as lne,wi as une,wt as dne,x as fne,xi as gn,xt as _n,yt as pne,z as vn,zr as yn,zt as bn}from"./state-BPFYBqm1.js";import{i as xn,n as Sn,r as mne,t as Cn}from"./cwd-Besi3Os3.js";import{$ as hne,A as wn,B as Tn,C as V,D as gne,E as En,F as Dn,I as _ne,J as On,L as kn,M as An,N as vne,O as jn,P as H,Q as yne,R as Mn,S as Nn,T as Pn,U as Fn,V as In,W as Ln,X as Rn,Y as zn,Z as Bn,_ as Vn,a as bne,c as U,d as Hn,f as Un,g as Wn,h as xne,i as W,j as Gn,k as Kn,m as Sne,nt as qn,p as Jn,q as Cne,rt as wne,s as Yn,t as Tne,tt as Xn,u as G,v as Ene,x as Zn,y as Dne,z as One}from"./debug-BQj6h99Q.js";import{$ as kne,$t as Ane,A as jne,An as Mne,Ar as Nne,At as Pne,B as Qn,Bn as $n,Bt as er,C as Fne,Cn as tr,Cr as Ine,Ct as nr,D as Lne,Dn as Rne,Dr as zne,Dt as rr,E as Bne,Er as ir,Et as Vne,F as ar,Ft as Hne,G as Une,H as or,Ht as sr,I as cr,In as lr,J as ur,Jn as dr,Jt as Wne,K as fr,Kt as pr,L as mr,Ln as hr,Mn as gr,Mt as _r,N as Gne,Nn as Kne,On as vr,Or as yr,Ot as br,P as xr,Pn as Sr,Q as Cr,Qt as wr,R as qne,Rn as Tr,Rt as Jne,Sn as Er,Sr as Yne,St as Xne,T as Zne,Tn as Qne,Tr as Dr,U as $ne,V as Or,Vt as ere,W as kr,Wt as Ar,X as tre,Xn as jr,Xt as Mr,Y as Nr,Yn as nre,Yt as Pr,Z as Fr,Zt as Ir,_n as Lr,_t as Rr,ar as zr,at as Br,bn as Vr,br as rre,bt as Hr,c as Ur,cr as Wr,ct as Gr,dr as ire,dt as Kr,en as are,f as qr,fn as ore,fr as sre,ft as Jr,g as Yr,gn as cre,gr as lre,h as ure,hn as dre,hr as fre,ht as Xr,in as pre,ir as mre,it as Zr,j as hre,jt as Qr,kn as $r,kr as gre,kt as _re,l as ei,ln as ti,lr as vre,lt as ni,m as yre,mn as ri,mr as bre,mt as xre,n as ii,nn as ai,nr as Sre,nt as Cre,o as wre,on as Tre,or as oi,ot as si,p as Ere,pn as Dre,pr as Ore,pt as kre,q as ci,rn as Are,rr as jre,rt as Mre,s as li,sn as Nre,sr as ui,st as di,t as Pre,tn as Fre,tr as Ire,u as Lre,un as fi,ur as pi,ut as mi,v as Rre,vn as zre,vt as hi,w as Bre,wn as gi,wr as Vre,x as _i,xn as vi,xr as Hre,yn as Ure,yr as Wre,yt as yi,z as bi,zn as Gre}from"./settings-CvhsRFaT.js";import{A as xi,C as Si,F as Kre,I as qre,L as Jre,M as Ci,N as wi,O as Yre,P as Ti,R as Xre,S as Ei,c as Di,d as Zre,h as Oi,j as Qre,k as ki,l as $re,m as eie,n as tie,o as Ai,u as ji,v as Mi,y as Ni,z as nie}from"./config-BSkuQZNf.js";import{A as rie,C as iie,D as aie,E as oie,O as Pi,S as Fi,T as sie,_ as cie,a as Ii,b as lie,c as uie,h as die,i as Li,k as Ri,l as zi,m as Bi,n as Vi,o as fie,p as Hi,r as Ui,w as pie,x as mie,y as hie}from"./git-DplvjXEY.js";import{c as Wi,i as gie,l as _ie,n as Gi,o as Ki,r as qi,t as Ji}from"./execFileNoThrow-DYm1GeGn.js";import{A as vie,B as Yi,C as yie,F as bie,G as xie,H as Sie,I as Xi,K as Cie,L as Zi,N as wie,P as Qi,R as $i,T as ea,U as ta,V as na,W as Tie,_ as Eie,c as K,d as Die,f as Oie,j as kie,k as ra,l as ia,m as Aie,n as aa,o as oa,q as sa,s as q,w as ca,z as la}from"./log-BlJ7CcKG.js";import{i as ua,n as jie,r as Mie,t as Nie}from"./hash-Tu-My5Vp.js";import{a as da,i as fa,n as pa,t as ma}from"./memoize-_2f7NWDv.js";import{n as ha,t as ga}from"./which-BR8YVCCW.js";import{i as _a,o as va}from"./platform-DVeTi9mp.js";import{a as ya,i as ba,s as xa,t as Pie}from"./windowsPaths-BmXyrasP.js";import{_ as Fie,a as Sa,c as Ca,d as Iie,f as Lie,g as Rie,h as zie,i as Bie,l as wa,m as Ta,o as Ea,r as Vie,s as Da,t as Oa,u as Hie}from"./sessionStoragePortable-x0Yn02-G.js";import{a as ka,c as Uie,n as Wie,r as Aa,s as ja,t as Gie,u as Ma}from"./types-BomO8WUz.js";import{n as Na,r as J}from"./analytics-DJobLaWP.js";import{a as Kie,n as Pa,o as qie,t as Jie}from"./intl-D2kgJmX7.js";import{C as Yie,a as Fa,b as Ia,c as Xie,f as La,g as Ra,h as za,i as Zie,l as Ba,n as Qie,o as $ie,s as Va,u as Ha,v as Ua,w as eae}from"./startupProfiler-2sjXZkIP.js";import{l as Wa,o as tae,s as nae,u as Ga}from"./oauth-D38aRTUb.js";import{n as rae,r as iae,t as aae}from"./bundledMode--fG1S62b.js";import{a as Ka,c as oae,i as sae,l as qa,n as cae,o as Ja,r as Ya,s as Xa,t as Za,u as Qa}from"./stringUtils-BjnclTLB.js";import{$n as $a,$r as eo,A as to,An as no,At as ro,Bn as io,Br as ao,C as oo,Cn as so,D as lae,Dn as co,Dr as lo,Dt as uo,En as fo,F as po,Fn as mo,Gn as ho,Gr as go,Hr as uae,Ht as _o,In as dae,J as vo,Jn as yo,Jr as bo,K as fae,Kn as xo,Kr as So,Ln as Co,Mn as pae,Nn as mae,O as hae,On as wo,Or as To,P as Eo,Pt as Do,Q as Oo,Qn as ko,R as Ao,Rn as gae,S as jo,Sn as _ae,St as Mo,T as No,Tn as Po,Tt as vae,Vn as yae,Vr as bae,Wr as xae,X as Fo,Xn as Sae,Xr as Cae,Xt as wae,Y as Tae,Yr as Eae,Z as Io,Zr as Dae,_ as Lo,_n as Ro,_r as Oae,ar as kae,at as Aae,c as jae,cr as Mae,ct as zo,d as Nae,dn as Bo,dt as Pae,ei as Vo,er as Fae,fn as Ho,fr as Iae,ft as Lae,g as Rae,gn as Uo,gr as Wo,gt as Go,h as Ko,ht as zae,ir as Bae,j as Vae,jn as Hae,k as Uae,kn as qo,kt as Jo,l as Yo,ln as Wae,lr as Xo,m as Zo,ni as Qo,or as Gae,pr as Kae,q as qae,qr as Jae,r as $o,rr as Yae,s as Xae,sr as Zae,ti as es,tr as Qae,u as ts,un as $ae,ut as eoe,vn as toe,wn as ns,xt as noe,y as rs,yn as roe,z as ioe,zr as is,zt as as}from"./model-sviY1inu.js";import{$ as os,$t as aoe,A as ooe,At as soe,B as coe,Bt as ss,Ct as loe,Dt as uoe,Et as cs,Ft as doe,G as foe,Gt as ls,H as poe,Ht as us,I as moe,It as hoe,J as goe,Jt as ds,K as _oe,Kt as fs,Lt as voe,Mt as yoe,N as boe,Nt as ps,O as xoe,Ot as ms,P as Soe,Pt as Coe,Q as woe,Qt as Toe,R as Eoe,Rt as hs,S as Doe,St as gs,T as Ooe,Tt as _s,U as koe,Ut as vs,Vt as ys,W as Aoe,Wt as bs,X as joe,Xt as xs,Y as Moe,Yt as Noe,Z as Poe,Zt as Foe,_ as Ioe,_n as Ss,_t as Cs,a as ws,an as Ts,at as Es,b as Loe,bn as Ds,bt as Roe,c as Os,cn as zoe,d as Boe,dn as ks,dt as Voe,en as Hoe,et as Uoe,f as As,fn as Woe,ft as Goe,g as js,gn as Ms,gt as Koe,h as qoe,hn as Ns,ht as Ps,i as Fs,in as Is,jt as Joe,k as Yoe,kt as Ls,l as Xoe,ln as Zoe,lt as Qoe,m as $oe,mn as Rs,mt as zs,n as ese,nn as Bs,nt as Vs,o as tse,on as nse,p as rse,pt as Hs,q as ise,qt as Us,r as Ws,rn as ase,rt as ose,s as sse,sn as Gs,st as Ks,t as cse,tn as lse,tt as qs,u as use,ut as dse,vn as fse,vt as pse,w as mse,wt as Js,xn as Ys,xt as Xs,yn as Zs,yt as Qs,z as hse,zt as $s}from"./prompt-CQmEvnKN.js";import{a as ec,c as gse,h as _se,l as tc,m as vse,o as yse,s as bse,u as xse}from"./proxy-C0j74LqT.js";import{n as Sse,t as Cse}from"./userAgent-DUt0q-Vl.js";import{i as wse,m as Tse,o as Ese,p as Dse}from"./terminalSetup-JJiXmszo.js";import{B as Ose,C as kse,N as nc,O as Ase,P as jse,Q as rc,S as ic,T as ac,Y as Mse,Z as Nse,at as oc,b as sc,bt as cc,d as Pse,et as lc,h as uc,k as Fse,m as dc,n as Ise,p as Lse,q as fc,r as pc,st as mc,u as hc,ut as Rse,v as gc,vt as _c,y as vc,yt as zse,z as Bse}from"./sessionState-BTFowSpR.js";import{a as Vse,i as Hse,n as Use,o as yc,t as Wse}from"./break-cache-Cd1yQ-0h.js";import{a as bc,i as Gse,l as xc,n as Sc,o as Cc,r as Kse,s as wc,t as qse}from"./localSearch-Cvs9WfoX.js";import{a as Tc,i as Ec,n as Dc,o as Oc,r as kc,t as Ac}from"./shellQuote-D3Ocv_U-.js";import{a as jc,c as Mc,n as Jse,s as Nc}from"./ripgrep-DsLUmulz.js";import{n as Yse,r as Xse}from"./client-Bb2eZnuq.js";import{r as Pc,t as Fc}from"./store-Z8rTjDHe.js";import{n as Zse,t as Qse}from"./client-DNEVh6Wu.js";import{a as $se,n as ece,o as Ic,s as Lc,t as tce}from"./switcher-BIP3rbQn.js";import{a as Rc,i as zc,n as nce}from"./genericProcessUtils-Bbcbi11g.js";import{$ as rce,J as ice,Q as Bc,X as ace,Y as oce,at as Vc,ct as Hc,et as Uc,ft as Wc,lt as Gc,nt as Kc,ot as qc,rt as Jc,st as sce,tt as Yc,ut as Xc}from"./esm-BI3tFLyy.js";import{r as Zc,t as Qc}from"./subprocessEnv-CNBOhlDV.js";import{n as cce,t as lce}from"./sessionIdCompat-Dgp6PW_1.js";import{a as $c,o as uce,r as el,s as dce,t as tl}from"./parser-a2S_eFyE.js";import{C as nl,S as fce,T as rl,a as il,b as pce,c as al,f as mce,g as hce,h as gce,i as ol,m as _ce,n as vce,o as sl,p as yce,s as cl,t as bce,u as xce,v as Sce,w as ll,x as Cce,y as wce}from"./sessionTracing-CvY4udYI.js";import{n as ul,r as Tce,t as dl}from"./poorMode-wm2WkPF0.js";import{a as Ece,i as fl,o as Dce,r as pl}from"./detectRepository-Qy3zKoyn.js";import{a as ml,i as hl,o as gl,r as _l}from"./api-CazVavfB.js";import{f as Oce,n as kce,p as Ace,s as jce}from"./firstPartyEventLogger-BMnXb9cv.js";import{n as Mce,t as Nce}from"./datadog-Cr0VKbct.js";import{i as Pce,t as Fce}from"./src-l6_O0K-a.js";import{n as Ice,t as Lce}from"./worktreeModeEnabled-BFOYTTTr.js";import{n as Rce,t as zce}from"./featureCheck-D6FjD-nt.js";import*as vl from"os";import{homedir as yl,platform as bl,release as xl,tmpdir as Sl,type as Bce,version as Vce}from"os";import*as Cl from"path";import{basename as wl,delimiter as Hce,dirname as Tl,extname as El,isAbsolute as Dl,join as Y,normalize as Ol,parse as kl,posix as Al,relative as jl,resolve as Ml,sep as Nl,win32 as Pl}from"path";import Fl from"node:process";import*as Il from"node:path";import Ll,{basename as Rl,dirname as zl,isAbsolute as Uce,join as Bl,relative as Vl,resolve as Hl,sep as Wce}from"node:path";import*as Ul from"fs";import{accessSync as Gce,closeSync as Kce,constants as Wl,createReadStream as qce,existsSync as Jce,fstat as Yce,fstatSync as Xce,mkdirSync as Gl,openSync as Zce,readFileSync as Kl,readSync as Qce,readdirSync as $ce,rm as ele,rmSync as tle,statSync as nle,unlinkSync as rle,watch as ile,writeFileSync as ale,writeSync as ql}from"fs";import{execSync as ole,spawn as sle,spawnSync as cle}from"node:child_process";import*as Jl from"node:fs";import{closeSync as lle,existsSync as Yl,mkdirSync as ule,openSync as dle,readFileSync as fle,readSync as ple,readdirSync as Xl,renameSync as mle,rmSync as hle,stat as gle,statSync as _le,unlinkSync as vle,unwatchFile as yle,watch as ble,watchFile as xle,writeFileSync as Sle}from"node:fs";import{EOL as Zl,homedir as Cle,tmpdir as Ql,type as wle}from"node:os";import{createHash as Tle,randomBytes as Ele,randomUUID as Dle}from"node:crypto";import{createHash as $l,randomBytes as eu,randomUUID as tu}from"crypto";import*as nu from"fs/promises";import{access as Ole,appendFile as ru,chmod as iu,copyFile as au,link as ou,lstat as kle,mkdir as su,open as cu,readFile as lu,readdir as uu,readlink as Ale,realpath as du,rename as fu,rm as pu,rmdir as jle,stat as mu,symlink as hu,truncate as Mle,unlink as gu,utimes as Nle,writeFile as _u}from"fs/promises";import{isDeepStrictEqual as Ple}from"util";import{execFile as Fle,execFileSync as vu,spawn as yu,spawnSync as bu}from"child_process";import{createServer as xu}from"http";import{fileURLToPath as Ile,parse as Lle,pathToFileURL as Su}from"url";import Rle,{createConnection as zle,isIP as Ble}from"net";import{EventEmitter as Vle}from"node:events";import{setMaxListeners as Hle}from"events";import{PassThrough as Ule,Readable as Wle}from"node:stream";import{lstat as Cu,mkdir as Gle,open as Kle,readFile as wu,readdir as Tu,realpath as Eu,rename as qle,rm as Jle,stat as Du,writeFile as Yle}from"node:fs/promises";import{request as Xle}from"node:https";import{Agent as Zle,createServer as Qle,request as Ou}from"node:http";import{lookup as $le}from"dns";import{URL as ku,fileURLToPath as eue}from"node:url";import{BlockList as tue,connect as Au,isIP as ju}from"node:net";import{connect as nue}from"node:tls";import{text as rue}from"node:stream/consumers";import{join as Mu}from"path/posix";async function iue(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)!==Nu&&e.push(n);v(e)}return}p++,(async()=>{try{let r=await e.value;if(d)return;let i=await t(r,n);i===Nu&&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 Nu,aue=n((()=>{Nu=Symbol(`skip`)}));function oue(e){let t=e.slice(e.lastIndexOf(`.`)).toLowerCase();return sue.has(t)}var sue,cue=n((()=>{sue=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 lue(e,t){for(var n=-1,r=e==null?0:e.length;++n<r&&t(e[n],n,e)!==!1;);return e}var uue=n((()=>{}));function due(e,t){return e&&Dr(t,Dt(t),e)}var fue=n((()=>{ir(),Wt()}));function pue(e,t){return e&&Dr(t,Vre(t),e)}var mue=n((()=>{ir(),Ine()}));function hue(e,t){return Dr(e,Ite(e),t)}var gue=n((()=>{ir(),ene()}));function _ue(e,t){return Dr(e,Xre(e),t)}var vue=n((()=>{ir(),nie()}));function yue(e){var t=e.length,n=new e.constructor(t);return t&&typeof e[0]==`string`&&bue.call(e,`index`)&&(n.index=e.index,n.input=e.input),n}var bue,xue=n((()=>{bue=Object.prototype.hasOwnProperty}));function Sue(e,t){var n=t?fre(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.byteLength)}var Cue=n((()=>{lre()}));function wue(e){var t=new e.constructor(e.source,Tue.exec(e));return t.lastIndex=e.lastIndex,t}var Tue,Eue=n((()=>{Tue=/\w*$/}));function Due(e){return Fu?Object(Fu.call(e)):{}}var Pu,Fu,Oue=n((()=>{c(),Pu=o?o.prototype:void 0,Fu=Pu?Pu.valueOf:void 0}));function kue(e,t,n){var r=e.constructor;switch(t){case Rue:return fre(e);case Aue:case jue:return new r(+e);case zue:return Sue(e,n);case Bue:case Vue:case Hue:case Uue:case Wue:case Gue:case Kue:case que:case Jue:return Ore(e,n);case Mue:return new r;case Nue:case Iue:return new r(e);case Pue:return wue(e);case Fue:return new r;case Lue:return Due(e)}}var Aue,jue,Mue,Nue,Pue,Fue,Iue,Lue,Rue,zue,Bue,Vue,Hue,Uue,Wue,Gue,Kue,que,Jue,Yue=n((()=>{lre(),Cue(),Eue(),Oue(),bre(),Aue=`[object Boolean]`,jue=`[object Date]`,Mue=`[object Map]`,Nue=`[object Number]`,Pue=`[object RegExp]`,Fue=`[object Set]`,Iue=`[object String]`,Lue=`[object Symbol]`,Rue=`[object ArrayBuffer]`,zue=`[object DataView]`,Bue=`[object Float32Array]`,Vue=`[object Float64Array]`,Hue=`[object Int8Array]`,Uue=`[object Int16Array]`,Wue=`[object Int32Array]`,Gue=`[object Uint8Array]`,Kue=`[object Uint8ClampedArray]`,que=`[object Uint16Array]`,Jue=`[object Uint32Array]`}));function Xue(e){return yee(e)&&Ht(e)==Zue}var Zue,Que=n((()=>{yn(),bee(),Zue=`[object Map]`})),Iu,$ue,ede=n((()=>{Que(),Ste(),Xte(),Iu=dn&&dn.isMap,$ue=Iu?Bte(Iu):Xue}));function tde(e){return yee(e)&&Ht(e)==nde}var nde,rde=n((()=>{yn(),bee(),nde=`[object Set]`})),Lu,ide,ade=n((()=>{rde(),Ste(),Xte(),Lu=dn&&dn.isSet,ide=Lu?Bte(Lu):tde}));function Ru(e,t,n,r,i,a){var o,c=t&ode,l=t&sde,u=t&cde;if(n&&(o=i?n(e,r,i,a):n(e)),o!==void 0)return o;if(!s(e))return e;var d=gn(e);if(d){if(o=yue(e),!c)return Wre(e,o)}else{var f=Ht(e),p=f==Bu||f==pde;if(Gte(e))return Hre(e,c);if(f==Vu||f==zu||p&&!i){if(o=l||p?{}:ire(e),!c)return l?_ue(e,pue(o,e)):hue(e,due(o,e))}else{if(!Hu[f])return i?e:{};o=kue(e,f,c)}}a||(a=new Xee);var m=a.get(e);if(m)return m;a.set(e,o),ide(e)?e.forEach(function(r){o.add(Ru(r,t,n,r,e,a))}):$ue(e)&&e.forEach(function(r,i){o.set(i,Ru(r,t,n,i,e,a))});var h=d?void 0:(u?l?qre:Uee:l?Vre:Dt)(e);return lue(h||e,function(r,i){h&&(i=r,r=e[i]),zne(o,i,Ru(r,t,n,i,e,a))}),o}var ode,sde,cde,zu,lde,ude,dde,fde,Bu,pde,mde,hde,Vu,gde,_de,vde,yde,bde,xde,Sde,Cde,wde,Tde,Ede,Dde,Ode,kde,Ade,jde,Hu,Uu=n((()=>{Qee(),uue(),yr(),fue(),mue(),Yne(),rre(),gue(),vue(),ute(),Jre(),yn(),xue(),Yue(),sre(),Yt(),Ote(),ede(),l(),ade(),Wt(),Ine(),ode=1,sde=2,cde=4,zu=`[object Arguments]`,lde=`[object Array]`,ude=`[object Boolean]`,dde=`[object Date]`,fde=`[object Error]`,Bu=`[object Function]`,pde=`[object GeneratorFunction]`,mde=`[object Map]`,hde=`[object Number]`,Vu=`[object Object]`,gde=`[object RegExp]`,_de=`[object Set]`,vde=`[object String]`,yde=`[object Symbol]`,bde=`[object WeakMap]`,xde=`[object ArrayBuffer]`,Sde=`[object DataView]`,Cde=`[object Float32Array]`,wde=`[object Float64Array]`,Tde=`[object Int8Array]`,Ede=`[object Int16Array]`,Dde=`[object Int32Array]`,Ode=`[object Uint8Array]`,kde=`[object Uint8ClampedArray]`,Ade=`[object Uint16Array]`,jde=`[object Uint32Array]`,Hu={},Hu[zu]=Hu[lde]=Hu[xde]=Hu[Sde]=Hu[ude]=Hu[dde]=Hu[Cde]=Hu[wde]=Hu[Tde]=Hu[Ede]=Hu[Dde]=Hu[mde]=Hu[hde]=Hu[Vu]=Hu[gde]=Hu[_de]=Hu[vde]=Hu[yde]=Hu[Ode]=Hu[kde]=Hu[Ade]=Hu[jde]=!0,Hu[fde]=Hu[Bu]=Hu[bde]=!1}));function Mde(e){return Ru(e,Nde|Pde)}var Nde,Pde,Fde=n((()=>{Uu(),Nde=1,Pde=4}));function Wu(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 Ide=n((()=>{})),Gu=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})),Ku=a((e=>{var t=Gu(),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})),Lde=a((e=>{var t=Gu(),n=Ku(),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,i as p,l as m,o as h,p as g,r as _,s as v,u as y}from"./envUtils-DcaKZlRU.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{n as ue,t as de}from"./axios-DaWTGg7G.js";import{$r as fe,Bt as pe,Ct as me,D as he,Fr as ge,Ft as _e,G as ve,Gr as ye,Gt as be,H as xe,Hr as Se,I as P,Kr as Ce,Lr as we,Lt as Te,Mr as Ee,P as F,Pr as De,Pt as Oe,Qr as ke,Rn as Ae,T as je,Tt as Me,Vr as Ne,Vt as Pe,Wt as Fe,Xn as Ie,Yt as Le,Zt as eee,_ as Re,ai as ze,bn as Be,cr as Ve,d as He,di as Ue,et as We,fi as Ge,fr as Ke,gr as qe,gt as tee,hn as Je,hr as nee,j as ree,l as iee,ln as aee,mi as oee,mr as see,mt as Ye,nt as cee,or as lee,ot as Xe,pi as uee,pr as dee,qr as Ze,rn as fee,sn as Qe,sr as pee,t as I,ui as mee,vn as hee,xr as gee,y as $e,yn as _ee,yr as vee,zr as et}from"./src-DL3w8VPk2.js";import{i as yee,r as bee}from"./isSymbol-BO6cdPI7.js";import{t as tt}from"./jsx-runtime-Bb4Xn-E0.js";import{A as L,B as xee,C as R,D as nt,H as See,I as Cee,M as rt,N as wee,O as it,R as Tee,T as at,U as Eee,a as ot,b as st,f as ct,g as lt,h as Dee,j as ut,k as dt,l as ft,m as pt,p as z,s as Oee,u as kee,v as Aee,w as B,x as mt}from"./external-CEp-aPkt.js";import{i as ht,n as gt,r as _t,t as vt}from"./lazySchema-B4D4qJVE.js";import{$t as yt,Ai as jee,At as bt,B as xt,Bn as Mee,Br as St,Bt as Nee,C as Pee,Cr as Ct,Ct as Fee,D as Iee,Dn as wt,Dt as Lee,E as Ree,En as Tt,Et,Fr as zee,Ft as Bee,G as Vee,Gr as Dt,Gt as Ot,H as kt,Hn as Hee,Hr as Uee,Ht as Wee,I as At,It as Gee,Jt as Kee,K as jt,Kr as qee,Kt as Mt,L as Jee,Ln as Nt,Lt as Yee,Mi as Xee,Mr as Pt,Mt as Zee,Ni as Qee,Nr as Ft,Nt as $ee,O as It,Oi as ete,On as Lt,Ot as Rt,Pr as tte,Q as zt,R as Bt,Rn as Vt,Rr as Ht,Rt as nte,S as rte,Sr as Ut,St as ite,T as ate,Ti as ote,Tt as ste,U as cte,Un as lte,Ur as ute,Ut as dte,V as fte,Vn as pte,Vr as mte,Wn as hte,Wr as Wt,Wt as Gt,Xt as gte,Y as _te,Yt as vte,_ as yte,_i as bte,_n as Kt,_r as qt,_t as Jt,a as xte,ai as Ste,an as Cte,at as wte,bi as Yt,br as Tte,bt as Ete,c as Dte,ci as Ote,cn as kte,cr as Ate,ct as jte,d as Mte,dn as Nte,dr as Pte,dt as Xt,et as Zt,f as Fte,fi as Ite,g as Lte,gi as Rte,gr as Qt,h as $t,ht as en,i as zte,ii as Bte,it as tn,j as Vte,ji as Hte,jt as nn,ki as Ute,kn as Wte,kt as rn,li as Gte,lr as an,lt as on,m as Kte,mn as qte,mr as Jte,n as Yte,ni as Xte,nt as sn,o as Zte,or as cn,ot as Qte,p as $te,pi as ene,pt as ln,qr as tne,qt as un,r as nne,ri as dn,rt as fn,s as rne,st as ine,t as ane,tr as one,u as pn,un as sne,ur as mn,ut as hn,vt as cne,w as lne,wi as une,wt as dne,x as fne,xi as gn,xt as _n,yt as pne,z as vn,zr as yn,zt as bn}from"./state-BPFYBqm1.js";import{i as xn,n as Sn,r as mne,t as Cn}from"./cwd-Besi3Os3.js";import{$ as hne,A as wn,B as Tn,C as V,D as gne,E as En,F as Dn,I as _ne,J as On,L as kn,M as An,N as vne,O as jn,P as H,Q as yne,R as Mn,S as Nn,T as Pn,U as Fn,V as In,W as Ln,X as Rn,Y as zn,Z as Bn,_ as Vn,a as bne,c as U,d as Hn,f as Un,g as Wn,h as xne,i as W,j as Gn,k as Kn,m as Sne,nt as qn,p as Jn,q as Cne,rt as wne,s as Yn,t as Tne,tt as Xn,u as G,v as Ene,x as Zn,y as Dne,z as One}from"./debug-BQj6h99Q.js";import{$ as kne,$t as Ane,A as jne,An as Mne,Ar as Nne,At as Pne,B as Qn,Bn as $n,Bt as er,C as Fne,Cn as tr,Cr as Ine,Ct as nr,D as Lne,Dn as Rne,Dr as zne,Dt as rr,E as Bne,Er as ir,Et as Vne,F as ar,Ft as Hne,G as Une,H as or,Ht as sr,I as cr,In as lr,J as ur,Jn as dr,Jt as Wne,K as fr,Kt as pr,L as mr,Ln as hr,Mn as gr,Mt as _r,N as Gne,Nn as Kne,On as vr,Or as yr,Ot as br,P as xr,Pn as Sr,Q as Cr,Qt as wr,R as qne,Rn as Tr,Rt as Jne,Sn as Er,Sr as Yne,St as Xne,T as Zne,Tn as Qne,Tr as Dr,U as $ne,V as Or,Vt as ere,W as kr,Wt as Ar,X as tre,Xn as jr,Xt as Mr,Y as Nr,Yn as nre,Yt as Pr,Z as Fr,Zt as Ir,_n as Lr,_t as Rr,ar as zr,at as Br,bn as Vr,br as rre,bt as Hr,c as Ur,cr as Wr,ct as Gr,dr as ire,dt as Kr,en as are,f as qr,fn as ore,fr as sre,ft as Jr,g as Yr,gn as cre,gr as lre,h as ure,hn as dre,hr as fre,ht as Xr,in as pre,ir as mre,it as Zr,j as hre,jt as Qr,kn as $r,kr as gre,kt as _re,l as ei,ln as ti,lr as vre,lt as ni,m as yre,mn as ri,mr as bre,mt as xre,n as ii,nn as ai,nr as Sre,nt as Cre,o as wre,on as Tre,or as oi,ot as si,p as Ere,pn as Dre,pr as Ore,pt as kre,q as ci,rn as Are,rr as jre,rt as Mre,s as li,sn as Nre,sr as ui,st as di,t as Pre,tn as Fre,tr as Ire,u as Lre,un as fi,ur as pi,ut as mi,v as Rre,vn as zre,vt as hi,w as Bre,wn as gi,wr as Vre,x as _i,xn as vi,xr as Hre,yn as Ure,yr as Wre,yt as yi,z as bi,zn as Gre}from"./settings-CvhsRFaT.js";import{A as xi,C as Si,F as Kre,I as qre,L as Jre,M as Ci,N as wi,O as Yre,P as Ti,R as Xre,S as Ei,c as Di,d as Zre,h as Oi,j as Qre,k as ki,l as $re,m as eie,n as tie,o as Ai,u as ji,v as Mi,y as Ni,z as nie}from"./config-BSkuQZNf.js";import{A as rie,C as iie,D as aie,E as oie,O as Pi,S as Fi,T as sie,_ as cie,a as Ii,b as lie,c as uie,h as die,i as Li,k as Ri,l as zi,m as Bi,n as Vi,o as fie,p as Hi,r as Ui,w as pie,x as mie,y as hie}from"./git-DplvjXEY.js";import{c as Wi,i as gie,l as _ie,n as Gi,o as Ki,r as qi,t as Ji}from"./execFileNoThrow-DYm1GeGn.js";import{A as vie,B as Yi,C as yie,F as bie,G as xie,H as Sie,I as Xi,K as Cie,L as Zi,N as wie,P as Qi,R as $i,T as ea,U as ta,V as na,W as Tie,_ as Eie,c as K,d as Die,f as Oie,j as kie,k as ra,l as ia,m as Aie,n as aa,o as oa,q as sa,s as q,w as ca,z as la}from"./log-BlJ7CcKG.js";import{i as ua,n as jie,r as Mie,t as Nie}from"./hash-Tu-My5Vp.js";import{a as da,i as fa,n as pa,t as ma}from"./memoize-_2f7NWDv.js";import{n as ha,t as ga}from"./which-BR8YVCCW.js";import{i as _a,o as va}from"./platform-DVeTi9mp.js";import{a as ya,i as ba,s as xa,t as Pie}from"./windowsPaths-BmXyrasP.js";import{_ as Fie,a as Sa,c as Ca,d as Iie,f as Lie,g as Rie,h as zie,i as Bie,l as wa,m as Ta,o as Ea,r as Vie,s as Da,t as Oa,u as Hie}from"./sessionStoragePortable-x0Yn02-G.js";import{a as ka,c as Uie,n as Wie,r as Aa,s as ja,t as Gie,u as Ma}from"./types-BomO8WUz.js";import{n as Na,r as J}from"./analytics-DJobLaWP.js";import{a as Kie,n as Pa,o as qie,t as Jie}from"./intl-D2kgJmX7.js";import{C as Yie,a as Fa,b as Ia,c as Xie,f as La,g as Ra,h as za,i as Zie,l as Ba,n as Qie,o as $ie,s as Va,u as Ha,v as Ua,w as eae}from"./startupProfiler-2sjXZkIP.js";import{l as Wa,o as tae,s as nae,u as Ga}from"./oauth-D38aRTUb.js";import{n as rae,r as iae,t as aae}from"./bundledMode--fG1S62b.js";import{a as Ka,c as oae,i as sae,l as qa,n as cae,o as Ja,r as Ya,s as Xa,t as Za,u as Qa}from"./stringUtils-BjnclTLB.js";import{$n as $a,$r as eo,A as to,An as no,At as ro,Bn as io,Br as ao,C as oo,Cn as so,D as lae,Dn as co,Dr as lo,Dt as uo,En as fo,F as po,Fn as mo,Gn as ho,Gr as go,Hr as uae,Ht as _o,In as dae,J as vo,Jn as yo,Jr as bo,K as fae,Kn as xo,Kr as So,Ln as Co,Mn as pae,Nn as mae,O as hae,On as wo,Or as To,P as Eo,Pt as Do,Q as Oo,Qn as ko,R as Ao,Rn as gae,S as jo,Sn as _ae,St as Mo,T as No,Tn as Po,Tt as vae,Vn as yae,Vr as bae,Wr as xae,X as Fo,Xn as Sae,Xr as Cae,Xt as wae,Y as Tae,Yr as Eae,Z as Io,Zr as Dae,_ as Lo,_n as Ro,_r as Oae,ar as kae,at as Aae,c as jae,cr as Mae,ct as zo,d as Nae,dn as Bo,dt as Pae,ei as Vo,er as Fae,fn as Ho,fr as Iae,ft as Lae,g as Rae,gn as Uo,gr as Wo,gt as Go,h as Ko,ht as zae,ir as Bae,j as Vae,jn as Hae,k as Uae,kn as qo,kt as Jo,l as Yo,ln as Wae,lr as Xo,m as Zo,ni as Qo,or as Gae,pr as Kae,q as qae,qr as Jae,r as $o,rr as Yae,s as Xae,sr as Zae,ti as es,tr as Qae,u as ts,un as $ae,ut as eoe,vn as toe,wn as ns,xt as noe,y as rs,yn as roe,z as ioe,zr as is,zt as as}from"./model-DlLO7TSx.js";import{$ as os,$t as aoe,A as ooe,At as soe,B as coe,Bt as ss,Ct as loe,Dt as uoe,Et as cs,Ft as doe,G as foe,Gt as ls,H as poe,Ht as us,I as moe,It as hoe,J as goe,Jt as ds,K as _oe,Kt as fs,Lt as voe,Mt as yoe,N as boe,Nt as ps,O as xoe,Ot as ms,P as Soe,Pt as Coe,Q as woe,Qt as Toe,R as Eoe,Rt as hs,S as Doe,St as gs,T as Ooe,Tt as _s,U as koe,Ut as vs,Vt as ys,W as Aoe,Wt as bs,X as joe,Xt as xs,Y as Moe,Yt as Noe,Z as Poe,Zt as Foe,_ as Ioe,_n as Ss,_t as Cs,a as ws,an as Ts,at as Es,b as Loe,bn as Ds,bt as Roe,c as Os,cn as zoe,d as Boe,dn as ks,dt as Voe,en as Hoe,et as Uoe,f as As,fn as Woe,ft as Goe,g as js,gn as Ms,gt as Koe,h as qoe,hn as Ns,ht as Ps,i as Fs,in as Is,jt as Joe,k as Yoe,kt as Ls,l as Xoe,ln as Zoe,lt as Qoe,m as $oe,mn as Rs,mt as zs,n as ese,nn as Bs,nt as Vs,o as tse,on as nse,p as rse,pt as Hs,q as ise,qt as Us,r as Ws,rn as ase,rt as ose,s as sse,sn as Gs,st as Ks,t as cse,tn as lse,tt as qs,u as use,ut as dse,vn as fse,vt as pse,w as mse,wt as Js,xn as Ys,xt as Xs,yn as Zs,yt as Qs,z as hse,zt as $s}from"./prompt-BRGC5U9Y.js";import{a as ec,c as gse,h as _se,l as tc,m as vse,o as yse,s as bse,u as xse}from"./proxy-C0j74LqT.js";import{n as Sse,t as Cse}from"./userAgent-CNPTS7ix.js";import{i as wse,m as Tse,o as Ese,p as Dse}from"./terminalSetup-JJiXmszo.js";import{B as Ose,C as kse,N as nc,O as Ase,P as jse,Q as rc,S as ic,T as ac,Y as Mse,Z as Nse,at as oc,b as sc,bt as cc,d as Pse,et as lc,h as uc,k as Fse,m as dc,n as Ise,p as Lse,q as fc,r as pc,st as mc,u as hc,ut as Rse,v as gc,vt as _c,y as vc,yt as zse,z as Bse}from"./sessionState-BlbRQ3Y6.js";import{a as Vse,i as Hse,n as Use,o as yc,t as Wse}from"./break-cache-Cd1yQ-0h.js";import{a as bc,i as Gse,l as xc,n as Sc,o as Cc,r as Kse,s as wc,t as qse}from"./localSearch-B5mTHBwK.js";import{a as Tc,i as Ec,n as Dc,o as Oc,r as kc,t as Ac}from"./shellQuote-D3Ocv_U-.js";import{a as jc,c as Mc,n as Jse,s as Nc}from"./ripgrep-DsLUmulz.js";import{n as Yse,r as Xse}from"./client-Bb2eZnuq.js";import{r as Pc,t as Fc}from"./store-Z8rTjDHe.js";import{n as Zse,t as Qse}from"./client-DNEVh6Wu.js";import{a as $se,n as ece,o as Ic,s as Lc,t as tce}from"./switcher-CnBKuiNp.js";import{a as Rc,i as zc,n as nce}from"./genericProcessUtils-Bbcbi11g.js";import{$ as rce,J as ice,Q as Bc,X as ace,Y as oce,at as Vc,ct as Hc,et as Uc,ft as Wc,lt as Gc,nt as Kc,ot as qc,rt as Jc,st as sce,tt as Yc,ut as Xc}from"./esm-BZciQG9N.js";import{r as Zc,t as Qc}from"./subprocessEnv-CNBOhlDV.js";import{n as cce,t as lce}from"./sessionIdCompat-Dgp6PW_1.js";import{a as $c,o as uce,r as el,s as dce,t as tl}from"./parser-a2S_eFyE.js";import{C as nl,S as fce,T as rl,a as il,b as pce,c as al,f as mce,g as hce,h as gce,i as ol,m as _ce,n as vce,o as sl,p as yce,s as cl,t as bce,u as xce,v as Sce,w as ll,x as Cce,y as wce}from"./sessionTracing-DqVx8aFD.js";import{n as ul,r as Tce,t as dl}from"./poorMode-wm2WkPF0.js";import{a as Ece,i as fl,o as Dce,r as pl}from"./detectRepository-Qy3zKoyn.js";import{a as ml,i as hl,o as gl,r as _l}from"./api-B3Wnozaf.js";import{f as Oce,n as kce,p as Ace,s as jce}from"./firstPartyEventLogger-Q3fMF0BR.js";import{n as Mce,t as Nce}from"./datadog-BqINRWAW.js";import{i as Pce,t as Fce}from"./src-l6_O0K-a.js";import{n as Ice,t as Lce}from"./worktreeModeEnabled-BFOYTTTr.js";import{n as Rce,t as zce}from"./featureCheck-D6FjD-nt.js";import*as vl from"os";import{homedir as yl,platform as bl,release as xl,tmpdir as Sl,type as Bce,version as Vce}from"os";import*as Cl from"path";import{basename as wl,delimiter as Hce,dirname as Tl,extname as El,isAbsolute as Dl,join as Y,normalize as Ol,parse as kl,posix as Al,relative as jl,resolve as Ml,sep as Nl,win32 as Pl}from"path";import Fl from"node:process";import*as Il from"node:path";import Ll,{basename as Rl,dirname as zl,isAbsolute as Uce,join as Bl,relative as Vl,resolve as Hl,sep as Wce}from"node:path";import*as Ul from"fs";import{accessSync as Gce,closeSync as Kce,constants as Wl,createReadStream as qce,existsSync as Jce,fstat as Yce,fstatSync as Xce,mkdirSync as Gl,openSync as Zce,readFileSync as Kl,readSync as Qce,readdirSync as $ce,rm as ele,rmSync as tle,statSync as nle,unlinkSync as rle,watch as ile,writeFileSync as ale,writeSync as ql}from"fs";import{execSync as ole,spawn as sle,spawnSync as cle}from"node:child_process";import*as Jl from"node:fs";import{closeSync as lle,existsSync as Yl,mkdirSync as ule,openSync as dle,readFileSync as fle,readSync as ple,readdirSync as Xl,renameSync as mle,rmSync as hle,stat as gle,statSync as _le,unlinkSync as vle,unwatchFile as yle,watch as ble,watchFile as xle,writeFileSync as Sle}from"node:fs";import{EOL as Zl,homedir as Cle,tmpdir as Ql,type as wle}from"node:os";import{createHash as Tle,randomBytes as Ele,randomUUID as Dle}from"node:crypto";import{createHash as $l,randomBytes as eu,randomUUID as tu}from"crypto";import*as nu from"fs/promises";import{access as Ole,appendFile as ru,chmod as iu,copyFile as au,link as ou,lstat as kle,mkdir as su,open as cu,readFile as lu,readdir as uu,readlink as Ale,realpath as du,rename as fu,rm as pu,rmdir as jle,stat as mu,symlink as hu,truncate as Mle,unlink as gu,utimes as Nle,writeFile as _u}from"fs/promises";import{isDeepStrictEqual as Ple}from"util";import{execFile as Fle,execFileSync as vu,spawn as yu,spawnSync as bu}from"child_process";import{createServer as xu}from"http";import{fileURLToPath as Ile,parse as Lle,pathToFileURL as Su}from"url";import Rle,{createConnection as zle,isIP as Ble}from"net";import{EventEmitter as Vle}from"node:events";import{setMaxListeners as Hle}from"events";import{PassThrough as Ule,Readable as Wle}from"node:stream";import{lstat as Cu,mkdir as Gle,open as Kle,readFile as wu,readdir as Tu,realpath as Eu,rename as qle,rm as Jle,stat as Du,writeFile as Yle}from"node:fs/promises";import{request as Xle}from"node:https";import{Agent as Zle,createServer as Qle,request as Ou}from"node:http";import{lookup as $le}from"dns";import{URL as ku,fileURLToPath as eue}from"node:url";import{BlockList as tue,connect as Au,isIP as ju}from"node:net";import{connect as nue}from"node:tls";import{text as rue}from"node:stream/consumers";import{join as Mu}from"path/posix";async function iue(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)!==Nu&&e.push(n);v(e)}return}p++,(async()=>{try{let r=await e.value;if(d)return;let i=await t(r,n);i===Nu&&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 Nu,aue=n((()=>{Nu=Symbol(`skip`)}));function oue(e){let t=e.slice(e.lastIndexOf(`.`)).toLowerCase();return sue.has(t)}var sue,cue=n((()=>{sue=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 lue(e,t){for(var n=-1,r=e==null?0:e.length;++n<r&&t(e[n],n,e)!==!1;);return e}var uue=n((()=>{}));function due(e,t){return e&&Dr(t,Dt(t),e)}var fue=n((()=>{ir(),Wt()}));function pue(e,t){return e&&Dr(t,Vre(t),e)}var mue=n((()=>{ir(),Ine()}));function hue(e,t){return Dr(e,Ite(e),t)}var gue=n((()=>{ir(),ene()}));function _ue(e,t){return Dr(e,Xre(e),t)}var vue=n((()=>{ir(),nie()}));function yue(e){var t=e.length,n=new e.constructor(t);return t&&typeof e[0]==`string`&&bue.call(e,`index`)&&(n.index=e.index,n.input=e.input),n}var bue,xue=n((()=>{bue=Object.prototype.hasOwnProperty}));function Sue(e,t){var n=t?fre(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.byteLength)}var Cue=n((()=>{lre()}));function wue(e){var t=new e.constructor(e.source,Tue.exec(e));return t.lastIndex=e.lastIndex,t}var Tue,Eue=n((()=>{Tue=/\w*$/}));function Due(e){return Fu?Object(Fu.call(e)):{}}var Pu,Fu,Oue=n((()=>{c(),Pu=o?o.prototype:void 0,Fu=Pu?Pu.valueOf:void 0}));function kue(e,t,n){var r=e.constructor;switch(t){case Rue:return fre(e);case Aue:case jue:return new r(+e);case zue:return Sue(e,n);case Bue:case Vue:case Hue:case Uue:case Wue:case Gue:case Kue:case que:case Jue:return Ore(e,n);case Mue:return new r;case Nue:case Iue:return new r(e);case Pue:return wue(e);case Fue:return new r;case Lue:return Due(e)}}var Aue,jue,Mue,Nue,Pue,Fue,Iue,Lue,Rue,zue,Bue,Vue,Hue,Uue,Wue,Gue,Kue,que,Jue,Yue=n((()=>{lre(),Cue(),Eue(),Oue(),bre(),Aue=`[object Boolean]`,jue=`[object Date]`,Mue=`[object Map]`,Nue=`[object Number]`,Pue=`[object RegExp]`,Fue=`[object Set]`,Iue=`[object String]`,Lue=`[object Symbol]`,Rue=`[object ArrayBuffer]`,zue=`[object DataView]`,Bue=`[object Float32Array]`,Vue=`[object Float64Array]`,Hue=`[object Int8Array]`,Uue=`[object Int16Array]`,Wue=`[object Int32Array]`,Gue=`[object Uint8Array]`,Kue=`[object Uint8ClampedArray]`,que=`[object Uint16Array]`,Jue=`[object Uint32Array]`}));function Xue(e){return yee(e)&&Ht(e)==Zue}var Zue,Que=n((()=>{yn(),bee(),Zue=`[object Map]`})),Iu,$ue,ede=n((()=>{Que(),Ste(),Xte(),Iu=dn&&dn.isMap,$ue=Iu?Bte(Iu):Xue}));function tde(e){return yee(e)&&Ht(e)==nde}var nde,rde=n((()=>{yn(),bee(),nde=`[object Set]`})),Lu,ide,ade=n((()=>{rde(),Ste(),Xte(),Lu=dn&&dn.isSet,ide=Lu?Bte(Lu):tde}));function Ru(e,t,n,r,i,a){var o,c=t&ode,l=t&sde,u=t&cde;if(n&&(o=i?n(e,r,i,a):n(e)),o!==void 0)return o;if(!s(e))return e;var d=gn(e);if(d){if(o=yue(e),!c)return Wre(e,o)}else{var f=Ht(e),p=f==Bu||f==pde;if(Gte(e))return Hre(e,c);if(f==Vu||f==zu||p&&!i){if(o=l||p?{}:ire(e),!c)return l?_ue(e,pue(o,e)):hue(e,due(o,e))}else{if(!Hu[f])return i?e:{};o=kue(e,f,c)}}a||(a=new Xee);var m=a.get(e);if(m)return m;a.set(e,o),ide(e)?e.forEach(function(r){o.add(Ru(r,t,n,r,e,a))}):$ue(e)&&e.forEach(function(r,i){o.set(i,Ru(r,t,n,i,e,a))});var h=d?void 0:(u?l?qre:Uee:l?Vre:Dt)(e);return lue(h||e,function(r,i){h&&(i=r,r=e[i]),zne(o,i,Ru(r,t,n,i,e,a))}),o}var ode,sde,cde,zu,lde,ude,dde,fde,Bu,pde,mde,hde,Vu,gde,_de,vde,yde,bde,xde,Sde,Cde,wde,Tde,Ede,Dde,Ode,kde,Ade,jde,Hu,Uu=n((()=>{Qee(),uue(),yr(),fue(),mue(),Yne(),rre(),gue(),vue(),ute(),Jre(),yn(),xue(),Yue(),sre(),Yt(),Ote(),ede(),l(),ade(),Wt(),Ine(),ode=1,sde=2,cde=4,zu=`[object Arguments]`,lde=`[object Array]`,ude=`[object Boolean]`,dde=`[object Date]`,fde=`[object Error]`,Bu=`[object Function]`,pde=`[object GeneratorFunction]`,mde=`[object Map]`,hde=`[object Number]`,Vu=`[object Object]`,gde=`[object RegExp]`,_de=`[object Set]`,vde=`[object String]`,yde=`[object Symbol]`,bde=`[object WeakMap]`,xde=`[object ArrayBuffer]`,Sde=`[object DataView]`,Cde=`[object Float32Array]`,wde=`[object Float64Array]`,Tde=`[object Int8Array]`,Ede=`[object Int16Array]`,Dde=`[object Int32Array]`,Ode=`[object Uint8Array]`,kde=`[object Uint8ClampedArray]`,Ade=`[object Uint16Array]`,jde=`[object Uint32Array]`,Hu={},Hu[zu]=Hu[lde]=Hu[xde]=Hu[Sde]=Hu[ude]=Hu[dde]=Hu[Cde]=Hu[wde]=Hu[Tde]=Hu[Ede]=Hu[Dde]=Hu[mde]=Hu[hde]=Hu[Vu]=Hu[gde]=Hu[_de]=Hu[vde]=Hu[yde]=Hu[Ode]=Hu[kde]=Hu[Ade]=Hu[jde]=!0,Hu[fde]=Hu[Bu]=Hu[bde]=!1}));function Mde(e){return Ru(e,Nde|Pde)}var Nde,Pde,Fde=n((()=>{Uu(),Nde=1,Pde=4}));function Wu(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 Ide=n((()=>{})),Gu=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})),Ku=a((e=>{var t=Gu(),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})),Lde=a((e=>{var t=Gu(),n=Ku(),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})),qu=a((e=>{var t=Gu(),n=Ku();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})),Rde=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})),Ju=a((e=>{var t=Gu();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})),Yu=a((e=>{var t=Rde(),n=Gu(),r=Ju();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}}})),Xu=a((e=>{var t=qu(),n=Ku(),r=Gu(),i=Yu(),a=Ju(),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})),Zu=a((e=>{var t=Gu(),n=Yu(),r=Ju(),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})),Qu=a((e=>{var t=Xu(),n=Gu(),r=Zu(),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})),$u=a((e=>{var t=Qu(),n=Gu(),r=Yu();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})),ed=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())}}}})),Tfe=a((e=>{var t=vfe(),n=pd(),r=md(),i=Vde(),a=Gu(),o=Cfe(),s=wfe();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})),Efe=a((e=>{var t=vfe(),n=pd(),r=ife(),i=md(),a=Xu(),o=Gu(),s=id(),c=Zu(),l=ad(),u=sd(),d=vd(),f=Sfe(),p=Cfe(),m=wfe(),h=Tfe(),g=Ku();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 yd(e){return typeof Bun<`u`?Bun.YAML.parse(e):Efe().parse(e)}var Dfe=n((()=>{}));function Ofe(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(Mfe.test(i)){let e=i.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`);n.push(`${r}: "${e}"`);continue}}n.push(e)}return n.join(`
|
|
117
|
-
`)}function bd(e,t){let n=e.match(wd);if(!n)return{frontmatter:{},content:e};let r=n[1]||``,i=e.slice(n[0].length),a={};try{let e=yd(r);e&&typeof e==`object`&&!Array.isArray(e)&&(a=e)}catch{try{let e=yd(Ofe(r));e&&typeof e==`object`&&!Array.isArray(e)&&(a=e)}catch(e){U(`Failed to parse YAML frontmatter${t?` in ${t}`:``}: ${e instanceof Error?e.message:e}`,{level:`warn`})}}return{frontmatter:a,content:i}}function xd(e){if(Array.isArray(e))return e.flatMap(xd);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=>kfe(e))}function kfe(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=kfe(n+e+i);o.push(...t)}return o}function Afe(e){if(e==null)return;let t=typeof e==`number`?e:parseInt(String(e),10);if(Number.isInteger(t)&&t>0)return t}function Sd(e,t,n){return e==null?null:typeof e==`string`?e.trim()||null:typeof e==`number`||typeof e==`boolean`?String(e):(U(`Description invalid for ${n?`${n}:${t}`:t??`unknown`} - omitting`,{level:`warn`}),null)}function Cd(e){return e===!0||e===`true`}function jfe(e,t){if(e==null)return;let n=String(e).trim().toLowerCase();if(n!==``){if(Td.includes(n))return n;U(`Frontmatter 'shell: ${e}' in ${t} is not recognized. Valid values: ${Td.join(`, `)}. Falling back to bash.`,{level:`warn`})}}var Mfe,wd,Td,Ed=n((()=>{W(),Dfe(),Mfe=/[{}[\]*&#!|>%@`]|: /,wd=/^---\s*\n([\s\S]*?)---\s*\n?/,Td=[`bash`,`powershell`]}));function Nfe(e){return eo()===`vertex`?Dd:e?.isNonInteractive?e.hasAppendSystemPrompt?Od:kd:Dd}function Pfe(){return!f(process.env.CLAUDE_CODE_ATTRIBUTION_HEADER)}function Ffe(){if(!Pfe())return``;let e=process.env.CLAUDE_CODE_ENTRYPOINT??`unknown`,t=Cae(),n=`x-anthropic-billing-header: cc_version=0.0.
|
|
117
|
+
`)}function bd(e,t){let n=e.match(wd);if(!n)return{frontmatter:{},content:e};let r=n[1]||``,i=e.slice(n[0].length),a={};try{let e=yd(r);e&&typeof e==`object`&&!Array.isArray(e)&&(a=e)}catch{try{let e=yd(Ofe(r));e&&typeof e==`object`&&!Array.isArray(e)&&(a=e)}catch(e){U(`Failed to parse YAML frontmatter${t?` in ${t}`:``}: ${e instanceof Error?e.message:e}`,{level:`warn`})}}return{frontmatter:a,content:i}}function xd(e){if(Array.isArray(e))return e.flatMap(xd);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=>kfe(e))}function kfe(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=kfe(n+e+i);o.push(...t)}return o}function Afe(e){if(e==null)return;let t=typeof e==`number`?e:parseInt(String(e),10);if(Number.isInteger(t)&&t>0)return t}function Sd(e,t,n){return e==null?null:typeof e==`string`?e.trim()||null:typeof e==`number`||typeof e==`boolean`?String(e):(U(`Description invalid for ${n?`${n}:${t}`:t??`unknown`} - omitting`,{level:`warn`}),null)}function Cd(e){return e===!0||e===`true`}function jfe(e,t){if(e==null)return;let n=String(e).trim().toLowerCase();if(n!==``){if(Td.includes(n))return n;U(`Frontmatter 'shell: ${e}' in ${t} is not recognized. Valid values: ${Td.join(`, `)}. Falling back to bash.`,{level:`warn`})}}var Mfe,wd,Td,Ed=n((()=>{W(),Dfe(),Mfe=/[{}[\]*&#!|>%@`]|: /,wd=/^---\s*\n([\s\S]*?)---\s*\n?/,Td=[`bash`,`powershell`]}));function Nfe(e){return eo()===`vertex`?Dd:e?.isNonInteractive?e.hasAppendSystemPrompt?Od:kd:Dd}function Pfe(){return!f(process.env.CLAUDE_CODE_ATTRIBUTION_HEADER)}function Ffe(){if(!Pfe())return``;let e=process.env.CLAUDE_CODE_ENTRYPOINT??`unknown`,t=Cae(),n=`x-anthropic-billing-header: cc_version=0.0.17; cc_entrypoint=${e};${t?` cc_workload=${t};`:``}`;return U(`attribution header ${n}`),n}var Dd,Od,kd,Ife,Ad,jd=n((()=>{W(),h(),es(),Dae(),Dd=`You are Work Mate, a CLI for Work Mate.`,Od=`You are Work Mate, a CLI for Work Mate, running within the Work Mate Agent SDK.`,kd=`You are a Work Mate agent, built on the Work Mate Agent SDK.`,Ife=[Dd,Od,kd],Ad=new Set(Ife)})),Lfe,Rfe=n((()=>{Lfe=e=>!1})),zfe=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 Bfe(e){if(typeof e==`string`)return Md.find(t=>t===e)}var Md,Nd,Pd,Vfe,Hfe,Ufe,Fd,Id=n((()=>{Md=[`user`,`feedback`,`project`,`reference`],Nd=[`## 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>`,``],Pd=[`## 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.`],Vfe=`- 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.`,Hfe=[`## 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.`,Vfe],Ufe=[`## 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."],Fd=["```markdown",`---`,`name: {{memory name}}`,`description: {{one-line description — used to decide relevance in future conversations, so be specific}}`,`type: {{${Md.join(`, `)}}}`,`---`,``,`{{memory content — for feedback/project types, structure as: rule/fact, then **Why:** and **How to apply:** lines}}`,"```"]}));function Wfe(e){let t=e.trim(),n=t.split(`
|
|
118
118
|
`),r=n.length,i=t.length,a=r>200,o=i>zd;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
|
`,zd);s=s.slice(0,e>0?e:zd)}let c=o&&!a?`${Ha(i)} (limit: ${Ha(zd)}) — index entries are too long`:a&&!o?`${r} lines (limit: 200)`:`${r} lines and ${Ha(i)}`;return{content:s+`\n\n> WARNING: ${Rd} 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 Gfe(e){let t=G();try{await t.mkdir(e)}catch(t){U(`ensureMemoryDirExists failed for ${e}: ${(t instanceof Error&&`code`in t&&typeof t.code==`string`?t.code:void 0)??String(t)}`,{level:`debug`})}}function Kfe(e,t){G().readdir(e).then(e=>{let n=0,r=0;for(let t of e)t.isFile()?n++:t.isDirectory()&&r++;J(`tengu_memdir_loaded`,{...t,total_file_count:n,total_subdir_count:r})},()=>{J(`tengu_memdir_loaded`,t)})}function qfe(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:",``,...Fd,``,`- 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:",``,...Fd,``,`**Step 2** — add a pointer to that file in \`${Rd}\`. \`${Rd}\` 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 \`${Rd}\`.`,``,`- \`${Rd}\` 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}\`. ${Bd}`,``,`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.`,``,...Nd,...Pd,``,...i,``,...Hfe,``,...Ufe,``,`## 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 Jfe(e){let{displayName:t,memoryDir:n,extraGuidelines:r}=e,i=G(),a=n+Rd,o=``;try{o=i.readFileSync(a,{encoding:`utf-8`})}catch{}let s=qfe(t,n,r);if(o.trim()){let e=Wfe(o),r=t===Yfe?`auto`:`agent`;Kfe(n,{content_length:e.byteCount,line_count:e.lineCount,was_truncated:e.wasLineTruncated,was_byte_truncated:e.wasByteTruncated,memory_type:r}),s.push(`## ${Rd}`,``,e.content)}else s.push(`## ${Rd}`,``,`Your ${Rd} is currently empty. When you save new memories, they will appear here.`);return s.join(`
|
|
121
121
|
`)}async function Ld(){let e=Ti(),t=process.env.CLAUDE_COWORK_MEMORY_EXTRA_GUIDELINES,n=t&&t.trim().length>0?[t]:void 0;if(e){let e=ki();return await Gfe(e),Kfe(e,{memory_type:`auto`}),qfe(`auto memory`,e,n,!1).join(`
|
|
122
|
-
`)}return J(`tengu_memdir_disabled`,{disabled_by_env_var:m(process.env.CLAUDE_CODE_DISABLE_AUTO_MEMORY),disabled_by_setting:!m(process.env.CLAUDE_CODE_DISABLE_AUTO_MEMORY)&&ii().autoMemoryEnabled===!1}),null}var Rd,zd,Yfe,Bd,Vd=n((()=>{Un(),Ci(),Na(),W(),h(),Ua(),Yr(),Id(),Rd=`MEMORY.md`,zd=25e3,Yfe=`auto memory`,Bd=`This directory already exists — write to it directly with the Write tool (do not run mkdir or check for its existence).`}));function Xfe(e){return e.replace(/:/g,`-`)}function Zfe(e){return process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR?Y(process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR,`projects`,Ta(Vi(tn())??tn()),`agent-memory-local`,e)+Nl:Y(Cn(),`.workmate`,`agent-memory-local`,e)+Nl}function Hd(e,t){let n=Xfe(e);switch(t){case`project`:return Y(Cn(),`.workmate`,`agent-memory`,n)+Nl;case`local`:return Zfe(n);case`user`:return Y(xi(),`agent-memory`,n)+Nl}}function Ud(e){let t=Ol(e),n=xi();if(t.startsWith(Y(n,`agent-memory`)+Nl)||t.startsWith(Y(Cn(),`.workmate`,`agent-memory`)+Nl))return!0;if(process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR){if(t.includes(`${Nl}agent-memory-local${Nl}`)&&t.startsWith(Y(process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR,`projects`)+Nl))return!0}else if(t.startsWith(Y(Cn(),`.workmate`,`agent-memory-local`)+Nl))return!0;return!1}function Qfe(e){switch(e){case`user`:return`User (${Y(xi(),`agent-memory`)}/)`;case`project`:return`Project (.workmate/agent-memory/)`;case`local`:return`Local (${Zfe(`...`)})`;default:return`None`}}function Wd(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=Hd(e,t);Gfe(r);let i=process.env.CLAUDE_COWORK_MEMORY_EXTRA_GUIDELINES;return Jfe({displayName:`Persistent Agent Memory`,memoryDir:r,extraGuidelines:i&&i.trim().length>0?[n,i]:[n]})}var Gd=n((()=>{Gt(),Vd(),Ci(),Sn(),Bi(),Wr()}));function $fe(){let e=process.env.CLAUDE_CODE_ENVIRONMENT_KIND;return e===`byoc`||e===`anthropic_cloud`?e:null}var epe=n((()=>{W()}));function tpe(e){return eu(4).readUInt32BE(0)%e}function Kd(e){return e[tpe(e.length)]}function npe(){return`${Kd(qd)}-${Kd(ipe)}-${Kd(Jd)}`}function rpe(){return`${Kd(qd)}-${Kd(Jd)}`}var qd,Jd,ipe,ape=n((()=>{qd=`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(`.`),Jd=`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(`.`),ipe=`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 Yd(e){let t=e??ln(),n=sn().get(t);if(!n){let e=Qd();for(let t=0;t<mpe;t++){n=npe();let t=Y(e,`${n}.md`);if(!G().existsSync(t))break}pte(t,n)}return n}function ope(e,t){pte(e,t)}function spe(){sn().clear()}function Xd(e){let t=Yd(ln());return e?Y(Qd(),`${t}-agent-${e}.md`):Y(Qd(),`${t}.md`)}function Zd(e){let t=Xd(e);try{return G().readFileSync(t,{encoding:`utf-8`})}catch(e){return Tn(e)||q(e),null}}function cpe(e){return e.messages.find(e=>e.slug)?.slug}async function lpe(e,t){let n=cpe(e);if(!n)return!1;ope(t??ln(),n);let r=Y(Qd(),`${n}.md`);try{return await G().readFile(r,{encoding:`utf-8`}),!0}catch(t){if(!Tn(t))return q(t),!1;if($fe()===null)return!1;U(`Plan file missing during resume: ${r}. Attempting recovery.`);let n=fpe(e.messages,`plan`),i=null;if(n&&n.content.length>0?(i=n.content,U(`Plan recovered from file snapshot, ${i.length} chars`,{level:`info`})):(i=dpe(e),i&&U(`Plan recovered from message history, ${i.length} chars`,{level:`info`})),i)try{return await _u(r,i,{encoding:`utf-8`}),!0}catch(e){return q(e),!1}return U(`Plan file recovery failed: no file snapshot or plan content found in message history`),!1}}async function upe(e,t){let n=cpe(e);if(!n)return!1;let r=Qd(),i=Y(r,`${n}.md`),a=Y(r,`${Yd(t)}.md`);try{return await au(i,a),!0}catch(e){return Tn(e)||q(e),!1}}function dpe(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 fpe(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 ppe(){if($fe()!==null)try{let e=[],t=Zd();if(t&&e.push({key:`plan`,path:Xd(),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:tu(),snapshotFiles:e},{recordTranscript:r}=await import(`./sessionStorage-D6nlmaI-.js`);await r([n])}catch(e){q(e)}}var mpe,Qd,$d=n((()=>{d(),Gt(),ds(),Sn(),W(),h(),Mn(),epe(),Un(),oa(),Yr(),ape(),mpe=10,Qd=u(function(){let e=ii().plansDirectory,t;if(e){let n=Cn(),r=Ml(n,e);!r.startsWith(n+Nl)&&r!==n?(q(Error(`plansDirectory must be within project root: ${e}`)),t=Y(p(),`plans`)):t=r}else t=Y(p(),`plans`);try{G().mkdirSync(t)}catch(e){q(e)}return t})})),hpe,gpe=n((()=>{hpe={type:`local-jsx`,name:`add-dir`,description:`添加新的工作目录`,argumentHint:`<path>`,load:()=>import(`./add-dir-DOKdPFT2.js`)}})),ef,_pe=n((()=>{ef={type:`local-jsx`,name:`btw`,description:`快速问一个旁路问题,不打断主对话`,immediate:!0,argumentHint:`<question>`,load:()=>import(`./btw-CkVkYeRr.js`)}})),tf,vpe=n((()=>{tf={type:`local`,name:`clear`,description:`清空对话历史并释放上下文`,aliases:[`reset`,`new`],supportsNonInteractive:!1,load:()=>import(`./clear-Ac3qYi_-.js`)}})),ype,bpe=n((()=>{h(),ype={type:`local`,name:`compact`,description:`清空对话历史但保留摘要在上下文中。可选:/compact [摘要生成的指示]`,isEnabled:()=>!m(process.env.DISABLE_COMPACT),supportsNonInteractive:!0,argumentHint:`<optional custom summarization instructions>`,load:()=>import(`./compact-CXuDr5qM.js`)}})),xpe,Spe=n((()=>{xpe={aliases:[`settings`],type:`local-jsx`,name:`config`,description:`打开配置面板`,load:()=>import(`./config-DrY1SvhQ.js`)}})),Cpe,wpe,Tpe=n((()=>{Gt(),Cpe={name:`context`,description:`以彩色网格可视化当前上下文占用`,isEnabled:()=>!vn(),type:`local-jsx`,load:()=>import(`./context-C2plOqH4.js`)},wpe={type:`local`,name:`context`,supportsNonInteractive:!0,description:`显示当前上下文占用`,get isHidden(){return!vn()},isEnabled(){return vn()},load:()=>import(`./context-noninteractive-DpVlZ-wP.js`)}})),Epe,Dpe=n((()=>{Epe={type:`local-jsx`,name:`diff`,description:`查看未提交的改动以及每一轮的 diff`,load:()=>import(`./diff-BNjcCXDr.js`)}})),Ope,kpe=n((()=>{h(),Ope={name:`doctor`,description:`诊断并校验 Work Mate 的安装与设置`,isEnabled:()=>!m(process.env.DISABLE_DOCTOR_COMMAND),type:`local-jsx`,load:()=>import(`./doctor-BkCtT7H1.js`)}})),Ape,jpe=n((()=>{Ape={type:`local-jsx`,name:`memory`,description:`编辑 Work Mate 记忆文件`,load:()=>import(`./memory-B5h2TTSS.js`)}})),Mpe,Npe=n((()=>{Mpe={type:`local-jsx`,name:`mode`,description:`切换交互模式(default、gentle、sharp、workhorse、token-saver、super-ai)`,isEnabled:()=>!0,argumentHint:`<mode-slug>`,load:()=>import(`./mode-D3yY1fdK.js`)}})),nf,Ppe=n((()=>{nf={type:`local-jsx`,name:`help`,description:`显示帮助与可用命令`,load:()=>import(`./help-JH7WzjZP.js`)}}));function Fpe(e,t){let n=Vl(e,t);return n===``||!n.startsWith(`..`)&&!Uce(n)}function Ipe(e,t){let n=Hl(e),r=Hl(t);if(!Fpe(n,r))return[n];let i=[],a=r;for(;i.push(a),a!==n;){let e=zl(a);if(e===a)break;a=e}return i.reverse()}async function Lpe(e,t){try{let n=(await G().readFile(e,{encoding:`utf-8`})).trim();return n?{path:e,relativePath:vre(Vl(t,e))||Rl(e),content:n}:null}catch{return null}}function Rpe(e){return e.length===0?null:e.map(e=>`## ${e.relativePath}\n${e.content}`).join(`
|
|
122
|
+
`)}return J(`tengu_memdir_disabled`,{disabled_by_env_var:m(process.env.CLAUDE_CODE_DISABLE_AUTO_MEMORY),disabled_by_setting:!m(process.env.CLAUDE_CODE_DISABLE_AUTO_MEMORY)&&ii().autoMemoryEnabled===!1}),null}var Rd,zd,Yfe,Bd,Vd=n((()=>{Un(),Ci(),Na(),W(),h(),Ua(),Yr(),Id(),Rd=`MEMORY.md`,zd=25e3,Yfe=`auto memory`,Bd=`This directory already exists — write to it directly with the Write tool (do not run mkdir or check for its existence).`}));function Xfe(e){return e.replace(/:/g,`-`)}function Zfe(e){return process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR?Y(process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR,`projects`,Ta(Vi(tn())??tn()),`agent-memory-local`,e)+Nl:Y(Cn(),`.workmate`,`agent-memory-local`,e)+Nl}function Hd(e,t){let n=Xfe(e);switch(t){case`project`:return Y(Cn(),`.workmate`,`agent-memory`,n)+Nl;case`local`:return Zfe(n);case`user`:return Y(xi(),`agent-memory`,n)+Nl}}function Ud(e){let t=Ol(e),n=xi();if(t.startsWith(Y(n,`agent-memory`)+Nl)||t.startsWith(Y(Cn(),`.workmate`,`agent-memory`)+Nl))return!0;if(process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR){if(t.includes(`${Nl}agent-memory-local${Nl}`)&&t.startsWith(Y(process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR,`projects`)+Nl))return!0}else if(t.startsWith(Y(Cn(),`.workmate`,`agent-memory-local`)+Nl))return!0;return!1}function Qfe(e){switch(e){case`user`:return`User (${Y(xi(),`agent-memory`)}/)`;case`project`:return`Project (.workmate/agent-memory/)`;case`local`:return`Local (${Zfe(`...`)})`;default:return`None`}}function Wd(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=Hd(e,t);Gfe(r);let i=process.env.CLAUDE_COWORK_MEMORY_EXTRA_GUIDELINES;return Jfe({displayName:`Persistent Agent Memory`,memoryDir:r,extraGuidelines:i&&i.trim().length>0?[n,i]:[n]})}var Gd=n((()=>{Gt(),Vd(),Ci(),Sn(),Bi(),Wr()}));function $fe(){let e=process.env.CLAUDE_CODE_ENVIRONMENT_KIND;return e===`byoc`||e===`anthropic_cloud`?e:null}var epe=n((()=>{W()}));function tpe(e){return eu(4).readUInt32BE(0)%e}function Kd(e){return e[tpe(e.length)]}function npe(){return`${Kd(qd)}-${Kd(ipe)}-${Kd(Jd)}`}function rpe(){return`${Kd(qd)}-${Kd(Jd)}`}var qd,Jd,ipe,ape=n((()=>{qd=`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(`.`),Jd=`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(`.`),ipe=`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 Yd(e){let t=e??ln(),n=sn().get(t);if(!n){let e=Qd();for(let t=0;t<mpe;t++){n=npe();let t=Y(e,`${n}.md`);if(!G().existsSync(t))break}pte(t,n)}return n}function ope(e,t){pte(e,t)}function spe(){sn().clear()}function Xd(e){let t=Yd(ln());return e?Y(Qd(),`${t}-agent-${e}.md`):Y(Qd(),`${t}.md`)}function Zd(e){let t=Xd(e);try{return G().readFileSync(t,{encoding:`utf-8`})}catch(e){return Tn(e)||q(e),null}}function cpe(e){return e.messages.find(e=>e.slug)?.slug}async function lpe(e,t){let n=cpe(e);if(!n)return!1;ope(t??ln(),n);let r=Y(Qd(),`${n}.md`);try{return await G().readFile(r,{encoding:`utf-8`}),!0}catch(t){if(!Tn(t))return q(t),!1;if($fe()===null)return!1;U(`Plan file missing during resume: ${r}. Attempting recovery.`);let n=fpe(e.messages,`plan`),i=null;if(n&&n.content.length>0?(i=n.content,U(`Plan recovered from file snapshot, ${i.length} chars`,{level:`info`})):(i=dpe(e),i&&U(`Plan recovered from message history, ${i.length} chars`,{level:`info`})),i)try{return await _u(r,i,{encoding:`utf-8`}),!0}catch(e){return q(e),!1}return U(`Plan file recovery failed: no file snapshot or plan content found in message history`),!1}}async function upe(e,t){let n=cpe(e);if(!n)return!1;let r=Qd(),i=Y(r,`${n}.md`),a=Y(r,`${Yd(t)}.md`);try{return await au(i,a),!0}catch(e){return Tn(e)||q(e),!1}}function dpe(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 fpe(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 ppe(){if($fe()!==null)try{let e=[],t=Zd();if(t&&e.push({key:`plan`,path:Xd(),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:tu(),snapshotFiles:e},{recordTranscript:r}=await import(`./sessionStorage-CiYSwyY3.js`);await r([n])}catch(e){q(e)}}var mpe,Qd,$d=n((()=>{d(),Gt(),ds(),Sn(),W(),h(),Mn(),epe(),Un(),oa(),Yr(),ape(),mpe=10,Qd=u(function(){let e=ii().plansDirectory,t;if(e){let n=Cn(),r=Ml(n,e);!r.startsWith(n+Nl)&&r!==n?(q(Error(`plansDirectory must be within project root: ${e}`)),t=Y(p(),`plans`)):t=r}else t=Y(p(),`plans`);try{G().mkdirSync(t)}catch(e){q(e)}return t})})),hpe,gpe=n((()=>{hpe={type:`local-jsx`,name:`add-dir`,description:`添加新的工作目录`,argumentHint:`<path>`,load:()=>import(`./add-dir-LLAv-rGS.js`)}})),ef,_pe=n((()=>{ef={type:`local-jsx`,name:`btw`,description:`快速问一个旁路问题,不打断主对话`,immediate:!0,argumentHint:`<question>`,load:()=>import(`./btw-XNgXHnNr.js`)}})),tf,vpe=n((()=>{tf={type:`local`,name:`clear`,description:`清空对话历史并释放上下文`,aliases:[`reset`,`new`],supportsNonInteractive:!1,load:()=>import(`./clear-BjtPf2Jb.js`)}})),ype,bpe=n((()=>{h(),ype={type:`local`,name:`compact`,description:`清空对话历史但保留摘要在上下文中。可选:/compact [摘要生成的指示]`,isEnabled:()=>!m(process.env.DISABLE_COMPACT),supportsNonInteractive:!0,argumentHint:`<optional custom summarization instructions>`,load:()=>import(`./compact-w8AhLkr6.js`)}})),xpe,Spe=n((()=>{xpe={aliases:[`settings`],type:`local-jsx`,name:`config`,description:`打开配置面板`,load:()=>import(`./config-CbAvTdZ7.js`)}})),Cpe,wpe,Tpe=n((()=>{Gt(),Cpe={name:`context`,description:`以彩色网格可视化当前上下文占用`,isEnabled:()=>!vn(),type:`local-jsx`,load:()=>import(`./context-Btn2JU2y.js`)},wpe={type:`local`,name:`context`,supportsNonInteractive:!0,description:`显示当前上下文占用`,get isHidden(){return!vn()},isEnabled(){return vn()},load:()=>import(`./context-noninteractive-ulRLlYg5.js`)}})),Epe,Dpe=n((()=>{Epe={type:`local-jsx`,name:`diff`,description:`查看未提交的改动以及每一轮的 diff`,load:()=>import(`./diff-CcrSQNvQ.js`)}})),Ope,kpe=n((()=>{h(),Ope={name:`doctor`,description:`诊断并校验 Work Mate 的安装与设置`,isEnabled:()=>!m(process.env.DISABLE_DOCTOR_COMMAND),type:`local-jsx`,load:()=>import(`./doctor-DRFDBrH1.js`)}})),Ape,jpe=n((()=>{Ape={type:`local-jsx`,name:`memory`,description:`编辑 Work Mate 记忆文件`,load:()=>import(`./memory-DtqQhHu8.js`)}})),Mpe,Npe=n((()=>{Mpe={type:`local-jsx`,name:`mode`,description:`切换交互模式(default、gentle、sharp、workhorse、token-saver、super-ai)`,isEnabled:()=>!0,argumentHint:`<mode-slug>`,load:()=>import(`./mode-DPbrxU32.js`)}})),nf,Ppe=n((()=>{nf={type:`local-jsx`,name:`help`,description:`显示帮助与可用命令`,load:()=>import(`./help-DKZhC0lL.js`)}}));function Fpe(e,t){let n=Vl(e,t);return n===``||!n.startsWith(`..`)&&!Uce(n)}function Ipe(e,t){let n=Hl(e),r=Hl(t);if(!Fpe(n,r))return[n];let i=[],a=r;for(;i.push(a),a!==n;){let e=zl(a);if(e===a)break;a=e}return i.reverse()}async function Lpe(e,t){try{let n=(await G().readFile(e,{encoding:`utf-8`})).trim();return n?{path:e,relativePath:vre(Vl(t,e))||Rl(e),content:n}:null}catch{return null}}function Rpe(e){return e.length===0?null:e.map(e=>`## ${e.relativePath}\n${e.content}`).join(`
|
|
123
123
|
|
|
124
124
|
`)}function zpe(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 Bpe(e){let t=[],n=zpe(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 Vpe(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 Hpe(e,t){return`${e}::${t.name}::${t.interval}::${t.prompt}`}function Upe(e,t){let n=[];for(let r of e.heartbeatTasks){let i=Vpe(r.interval);if(i==null)continue;let a=Hpe(e.rootDir,r),o=uf.get(a);o!==void 0&&t-o<i||n.push(r)}return n}function Wpe(e,t,n){for(let r of t)uf.set(Hpe(e.rootDir,r),n)}async function Gpe(e={}){let t=Hl(e.rootDir??tn()),n=Hl(e.currentDir??Cn()),r=Ipe(t,n),[i,a]=await Promise.all([Promise.all(r.map(async e=>Lpe(Bl(e,af,sf),t))),Lpe(Bl(t,af,cf),t)]),o=i.filter(e=>e!==null);return{rootDir:t,currentDir:n,agentsFiles:o,agentsContent:Rpe(o),heartbeatFile:a,heartbeatContent:a?.content??null,heartbeatTasks:a?Bpe(a.content):[]}}async function Kpe(e){let t=await rf(e);return qpe(t),t.prompt}async function rf(e){let t=await Gpe({rootDir:e.rootDir,currentDir:e.currentDir}),n=e.nowMs??Date.now(),r=e.trigger===`proactive-tick`?Upe(t,n):[],i=r.filter(e=>e.steps.length===0),a=[];if(t.agentsContent&&a.push(`Workspace authority from ${sf}:\n${t.agentsContent}`),t.heartbeatContent&&a.push(`Workspace heartbeat guidance from ${cf}:\n${t.heartbeatContent}`),i.length>0&&a.push([`Due ${cf} 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 $pe(e,t={}){let n=t.entryType||t.type;if(n===`both`&&(n=ff.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&&!hf.includes(n))throw Error(`readdirp: Invalid type passed. Use one of ${hf.join(`, `)}`);return t.root=e,new ame(t)}var ff,pf,mf,eme,hf,tme,nme,rme,ime,gf,_f,ame,ome=n((()=>{b(),ff={FILE_TYPE:`files`,DIR_TYPE:`directories`,FILE_DIR_TYPE:`files_directories`,EVERYTHING_TYPE:`all`},pf={root:`.`,fileFilter:e=>!0,directoryFilter:e=>!0,type:ff.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096},Object.freeze(pf),mf=`READDIRP_RECURSIVE_ERROR`,eme=new Set([`ENOENT`,`EPERM`,`EACCES`,`ELOOP`,mf]),hf=[ff.DIR_TYPE,ff.EVERYTHING_TYPE,ff.FILE_DIR_TYPE,ff.FILE_TYPE],tme=new Set([ff.DIR_TYPE,ff.EVERYTHING_TYPE,ff.FILE_DIR_TYPE]),nme=new Set([ff.EVERYTHING_TYPE,ff.FILE_DIR_TYPE,ff.FILE_TYPE]),rme=e=>eme.has(e.code),ime=process.platform===`win32`,gf=e=>!0,_f=e=>{if(e===void 0)return gf;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 gf},ame=class extends Wle{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={...pf,...e},{root:n,type:r}=t;this._fileFilter=_f(t.fileFilter),this._directoryFilter=_f(t.directoryFilter);let i=t.lstat?Cu:Du;ime?this._stat=e=>i(e,{bigint:!0}):this._stat=i,this._maxDepth=t.depth!=null&&Number.isSafeInteger(t.depth)?t.depth:pf.depth,this._wantsDir=r?tme.has(r):!1,this._wantsFile=r?nme.has(r):!1,this._wantsEverything=r===ff.EVERYTHING_TYPE,this._root=Hl(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 Tu(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=Hl(Bl(t,r));n={path:Vl(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){rme(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 Eu(t),n=await Cu(e);if(n.isFile())return`file`;if(n.isDirectory()){let n=e.length;if(t.startsWith(e)&&t.substr(n,1)===Wce){let n=Error(`Circular symlink detected: "${t}" points to "${e}"`);return n.code=mf,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 sme(e,t,n,r,i){let a=(t,r)=>{n(e),i(t,r,{watchedPath:e}),r&&e!==r&&jf(Il.resolve(e,r),Cf,Il.join(e,r))};try{return ble(e,{persistent:t.persistent},a)}catch(e){r(e);return}}var cme,lme,vf,yf,bf,ume,dme,fme,pme,xf,Sf,mme,hme,Cf,wf,Tf,gme,_me,vme,Ef,Df,yme,Of,kf,Af,jf,bme,Mf,xme,Sme,Cme=n((()=>{b(),cme=`data`,lme=`close`,vf=()=>{},yf=process.platform,bf=yf===`win32`,ume=yf===`darwin`,dme=yf===`linux`,fme=yf===`freebsd`,pme=wle()===`OS400`,xf={ALL:`all`,READY:`ready`,ADD:`add`,CHANGE:`change`,ADD_DIR:`addDir`,UNLINK:`unlink`,UNLINK_DIR:`unlinkDir`,RAW:`raw`,ERROR:`error`},Sf=xf,mme=`watch`,hme={lstat:Cu,stat:Du},Cf=`listeners`,wf=`errHandlers`,Tf=`rawEmitters`,gme=[Cf,wf,Tf],_me=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(`.`)),vme=e=>_me.has(Il.extname(e).slice(1).toLowerCase()),Ef=(e,t)=>{e instanceof Set?e.forEach(t):t(e)},Df=(e,t,n)=>{let r=e[t];r instanceof Set||(e[t]=r=new Set([r])),r.add(n)},yme=e=>t=>{let n=e[t];n instanceof Set?n.clear():delete e[t]},Of=(e,t,n)=>{let r=e[t];r instanceof Set?r.delete(n):r===n&&delete e[t]},kf=e=>e instanceof Set?e.size===0:!e,Af=new Map,jf=(e,t,n,r,i)=>{let a=Af.get(e);a&&Ef(a[t],e=>{e(n,r,i)})},bme=(e,t,n,r)=>{let{listener:i,errHandler:a,rawEmitter:o}=r,s=Af.get(t),c;if(!n.persistent)return c=sme(e,n,i,a,o),c?c.close.bind(c):void 0;if(s)Df(s,Cf,i),Df(s,wf,a),Df(s,Tf,o);else{if(c=sme(e,n,jf.bind(null,t,Cf),a,jf.bind(null,t,Tf)),!c)return;c.on(Sf.ERROR,async n=>{let r=jf.bind(null,t,wf);if(s&&(s.watcherUnusable=!0),bf&&n.code===`EPERM`)try{await(await Kle(e,`r`)).close(),r(n)}catch{}else r(n)}),s={listeners:i,errHandlers:a,rawEmitters:o,watcher:c},Af.set(t,s)}return()=>{Of(s,Cf,i),Of(s,wf,a),Of(s,Tf,o),kf(s.listeners)&&(s.watcher.close(),Af.delete(t),gme.forEach(yme(s)),s.watcher=void 0,Object.freeze(s))}},Mf=new Map,xme=(e,t,n,r)=>{let{listener:i,rawEmitter:a}=r,o=Mf.get(t),s=o&&o.options;return s&&(s.persistent<n.persistent||s.interval>n.interval)&&(yle(t),o=void 0),o?(Df(o,Cf,i),Df(o,Tf,a)):(o={listeners:i,rawEmitters:a,options:n,watcher:xle(t,n,(n,r)=>{Ef(o.rawEmitters,e=>{e(Sf.CHANGE,t,{curr:n,prev:r})});let i=n.mtimeMs;(n.size!==r.size||i>r.mtimeMs||i===0)&&Ef(o.listeners,t=>t(e,n))})},Mf.set(t,o)),()=>{Of(o,Cf,i),Of(o,Tf,a),kf(o.listeners)&&(Mf.delete(t),yle(t),o.options=o.watcher=void 0,Object.freeze(o))}},Sme=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=Il.dirname(e),i=Il.basename(e);this.fsw._getWatchedDir(r).add(i);let a=Il.resolve(e),o={persistent:n.persistent};t||(t=vf);let s;return n.usePolling?(o.interval=n.interval!==n.binaryInterval&&vme(i)?n.binaryInterval:n.interval,s=xme(e,a,o,{listener:t,rawEmitter:this.fsw._emitRaw})):s=bme(e,a,o,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw}),s}_handleFile(e,t,n){if(this.fsw.closed)return;let r=Il.dirname(e),i=Il.basename(e),a=this.fsw._getWatchedDir(r),o=t;if(a.has(i))return;let s=async(t,n)=>{if(this.fsw._throttle(mme,e,5)){if(!n||n.mtimeMs===0)try{let n=await Du(e);if(this.fsw.closed)return;let r=n.atimeMs,i=n.mtimeMs;if((!r||r<=i||i!==o.mtimeMs)&&this.fsw._emit(Sf.CHANGE,e,n),(ume||dme||fme)&&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(Sf.CHANGE,e,n),o=n}}},c=this._watchWithNodeFs(e,s);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(Sf.ADD,e,0))return;this.fsw._emit(Sf.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 Eu(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(Sf.CHANGE,n,e.stats)):(a.add(r),this.fsw._symlinkPaths.set(i,t),this.fsw._emit(Sf.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=Il.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(cme,async o=>{if(this.fsw.closed){u=void 0;return}let s=o.path,d=Il.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=Il.join(i,Il.relative(i,d)),this._addToNodeFs(d,t,n,a+1))}}).on(Sf.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(Il.dirname(e)),c=s.has(Il.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!i&&!c&&this.fsw._emit(Sf.ADD_DIR,e,t),s.add(Il.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 hme[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=Il.resolve(e),l=s?await Eu(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 Eu(e):e;if(this.fsw.closed)return;let a=Il.dirname(o.watchPath);if(this.fsw._getWatchedDir(a).add(o.watchPath),this.fsw._emit(Sf.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(Il.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 Nf(e){return Array.isArray(e)?e:[e]}function wme(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=Il.relative(e.path,t);return n?!n.startsWith(`..`)&&!Il.isAbsolute(n):!1}return!1}:()=>!1}function Tme(e){if(typeof e!=`string`)throw Error(`string expected`);e=Il.normalize(e),e=e.replace(/\\/g,`/`);let t=!1;return e.startsWith(`//`)&&(t=!0),e=e.replace(If,`/`),t&&(e=`/`+e),e}function Eme(e,t,n){let r=Tme(t);for(let t=0;t<e.length;t++){let i=e[t];if(i(r,n))return!0}return!1}function Dme(e,t){if(e==null)throw TypeError(`anymatch: specify first argument`);let n=Nf(e).map(e=>wme(e));return t==null?(e,t)=>Eme(n,e,t):Eme(n,t)}function Ome(e,t={}){let n=new Hf(t);return n.add(e),n}var Pf,kme,Ff,Ame,jme,Mme,If,Nme,Pme,Lf,Rf,zf,Bf,Vf,Fme,Ime,Lme,Rme,zme,Bme,Hf,Uf,Wf=n((()=>{ome(),Cme(),b(),Pf=`/`,kme=`//`,Ff=`.`,Ame=`..`,jme=`string`,Mme=/\\/g,If=/\/\//g,Nme=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Pme=/^\.[/\\]/,Lf=e=>typeof e==`object`&&!!e&&!(e instanceof RegExp),Rf=e=>{let t=Nf(e).flat();if(!t.every(e=>typeof e===jme))throw TypeError(`Non-string provided as watch path: ${t}`);return t.map(Bf)},zf=e=>{let t=e.replace(Mme,Pf),n=!1;return t.startsWith(kme)&&(n=!0),t=t.replace(If,Pf),n&&(t=Pf+t),t},Bf=e=>zf(Il.normalize(zf(e))),Vf=(e=``)=>t=>typeof t==`string`?Bf(Il.isAbsolute(t)?t:Il.join(e,t)):t,Fme=(e,t)=>Il.isAbsolute(e)?e:Il.join(t,e),Ime=Object.freeze(new Set),Lme=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!==Ff&&e!==Ame&&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 Tu(n)}catch{this._removeWatcher&&this._removeWatcher(Il.dirname(n),Il.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=vf,this.items=Ime,Object.freeze(this)}},Rme=`stat`,zme=`lstat`,Bme=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(Pme,``),this.watchPath=r,this.fullWatchPath=Il.resolve(r),this.dirParts=[],this.dirParts.forEach(e=>{e.length>1&&e.pop()}),this.followSymlinks=t,this.statMethod=t?Rme:zme}entryPath(e){return Il.join(this.watchPath,Il.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)}},Hf=class extends Vle{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?Nf(e.ignored):Nf([]),awaitWriteFinish:t===!0?n:typeof t==`object`&&{...n,...t}};pme&&(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=vf,this._readyEmitted=!0,process.nextTick(()=>this.emit(xf.READY)))},this._emitRaw=(...e)=>this.emit(xf.RAW,...e),this._boundRemove=this._remove.bind(this),this.options=r,this._nodeFsHandler=new Sme(this),Object.freeze(r)}_addIgnoredPath(e){if(Lf(e)){for(let t of this._ignoredPaths)if(Lf(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)Lf(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=Rf(e);return r&&(i=i.map(e=>Fme(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(Il.dirname(e),Il.basename(t||e))})}),this}unwatch(e){if(this.closed)return this;let t=Rf(e),{cwd:n}=this.options;return t.forEach(e=>{!Il.isAbsolute(e)&&!this._closers.has(e)&&(n&&(e=Il.join(n,e)),e=Il.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?Il.relative(this.options.cwd,n):n)||Ff;e[r]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==xf.ERROR&&this.emit(xf.ALL,e,...t)}async _emit(e,t,n){if(this.closed)return;let r=this.options;bf&&(t=Il.normalize(t)),r.cwd&&(t=Il.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===xf.UNLINK)return this._pendingUnlinks.set(t,[e,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((e,t)=>{this.emit(...e),this.emit(xf.ALL,...e),this._pendingUnlinks.delete(t)})},typeof r.atomic==`number`?r.atomic:100),this;e===xf.ADD&&this._pendingUnlinks.has(t)&&(e=xf.CHANGE,this._pendingUnlinks.delete(t))}if(a&&(e===xf.ADD||e===xf.CHANGE)&&this._readyEmitted)return this._awaitWriteFinish(t,a.stabilityThreshold,e,(t,n)=>{t?(e=xf.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===xf.CHANGE&&!this._throttle(xf.CHANGE,t,50))return this;if(r.alwaysStat&&n===void 0&&(e===xf.ADD||e===xf.ADD_DIR||e===xf.CHANGE)){let e=r.cwd?Il.join(r.cwd,t):t,n;try{n=await Du(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(xf.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&&!Il.isAbsolute(e)&&(s=Il.join(this.options.cwd,e));let c=new Date,l=this._pendingWrites;function u(n){gle(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&&Nme.test(e))return!0;if(!this._userIgnored){let{cwd:e}=this.options,t=(this.options.ignored||[]).map(Vf(e)),n=[...[...this._ignoredPaths].map(Vf(e)),...t];this._userIgnored=Dme(n,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new Bme(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=Il.resolve(e);return this._watched.has(t)||this._watched.set(t,new Lme(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,n){let r=Il.join(e,t),i=Il.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=Il.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(s)&&this._pendingWrites.get(s).cancelWait()===xf.ADD)return;this._watched.delete(r),this._watched.delete(i);let c=n?xf.UNLINK_DIR:xf.UNLINK;o&&!this._isIgnored(r)&&this._emit(c,r),this._closePath(r)}_closePath(e){this._closeFile(e);let t=Il.dirname(e);this._getWatchedDir(t).remove(Il.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=$pe(e,{type:xf.ALL,alwaysStat:!0,lstat:!0,...t,depth:0});return this._streams.add(n),n.once(lme,()=>{n=void 0}),n.once(`end`,()=>{n&&(this._streams.delete(n),n=void 0)}),n}},Uf={watch:Ome,FSWatcher:Hf}})),Vme,Hme,Gf,Ume=n((()=>{_c(),aae(),va(),Vme=_a()===`windows`?`alt+v`:`ctrl+v`,Hme=_a()!==`windows`||(iae()?cc(process.versions.bun,`>=1.2.23`):cc(process.versions.node,`>=22.17.0 <23.0.0 || >=24.2.0`))?`shift+tab`:`meta+m`,Gf=[{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`,[Hme]:`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`,[Vme]:`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`}}]})),Wme=n((()=>{I()}));function Gme(){let e=_a(),t=[...qf,...Jf];return e===`macos`&&t.push(...Yf),t}function Kf(e){return e.trim().split(/\s+/).map(Kme).join(` `)}function Kme(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 qf,Jf,Yf,qme=n((()=>{va(),qf=[{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`}],Jf=[{key:`ctrl+z`,reason:`Unix process suspend (SIGTSTP)`,severity:`warning`},{key:`ctrl+\\`,reason:`Terminal quit signal (SIGQUIT)`,severity:`error`}],Yf=[{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 Jme(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.context==`string`&&typeof t.bindings==`object`&&t.bindings!==null}function Yme(e){return Array.isArray(e)&&e.every(Jme)}function Xme(e){return Xf.includes(e)}function Zme(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=aee(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 Qme(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`?Xme(i)?a=i:n.push({type:`invalid_context`,severity:`error`,message:`Unknown context "${i}"`,context:i,suggestion:`Valid contexts: ${Xf.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=Zme(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 $me(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 ehe(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(...Qme(e[n],n));return t}function the(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=Kf(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 nhe(e){let t=[],n=Gme();for(let r of e){let e=fee(r.chord),i=Kf(e);for(let a of n)Kf(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 rhe(e){let t=[];for(let n of e)for(let[e,r]of Object.entries(n.bindings)){let i=e.split(` `).map(e=>aee(e));t.push({chord:i,action:r,context:n.context})}return t}function ihe(e,t){let n=[];if(n.push(...ehe(e)),Yme(e)){n.push(...the(e));let t=rhe(e);n.push(...nhe(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 Xf,ahe=n((()=>{Wme(),qme(),Xf=[`Global`,`Chat`,`Autocomplete`,`Confirmation`,`Help`,`Transcript`,`HistorySearch`,`Task`,`ThemePicker`,`Settings`,`Tabs`,`Attachments`,`Footer`,`FormField`,`MessageActions`,`MessageSelector`,`DiffDialog`,`ModelPicker`,`Scroll`,`Select`,`Plugin`]}));function Zf(){return!1}function ohe(e){let t=new Date().toISOString().slice(0,10);sp!==t&&(sp=t,J(`tengu_custom_keybindings_loaded`,{user_binding_count:e}))}function she(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.context==`string`&&typeof t.bindings==`object`&&t.bindings!==null}function che(e){return Array.isArray(e)&&e.every(she)}function Qf(){return Y(p(),`keybindings.json`)}function $f(){return Qe(Gf)}async function lhe(){let e=$f();if(!Zf())return{bindings:e,warnings:[]};let t=Qf();try{let n=await lu(t,`utf-8`),r=Nn(n),i;if(typeof r==`object`&&r&&`bindings`in r)i=r.bindings;else{let t=`keybindings.json must have a "bindings" array`;return U(`[keybindings] Invalid keybindings.json: ${t}`),{bindings:e,warnings:[{type:`parse_error`,severity:`error`,message:t,suggestion:`Use format: { "bindings": [ ... ] }`}]}}if(!che(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 U(`[keybindings] Invalid keybindings.json: ${t}`),{bindings:e,warnings:[{type:`parse_error`,severity:`error`,message:t,suggestion:n}]}}let a=Qe(i);U(`[keybindings] Loaded ${a.length} user bindings from ${t}`);let o=[...e,...a];ohe(a.length);let s=[...$me(n),...ihe(i,o)];return s.length>0&&U(`[keybindings] Found ${s.length} validation issue(s)`),{bindings:o,warnings:s}}catch(n){return Tn(n)?{bindings:e,warnings:[]}:(U(`[keybindings] Error loading ${t}: ${H(n)}`),{bindings:e,warnings:[{type:`parse_error`,severity:`error`,message:`Failed to parse keybindings.json: ${H(n)}`}]})}}function uhe(){return ip||ep().bindings}function ep(){if(ip)return{bindings:ip,warnings:ap};let e=$f();if(!Zf())return ip=e,ap=[],{bindings:ip,warnings:ap};let t=Qf();try{let n=Kl(t,`utf-8`),r=Nn(n),i;if(typeof r==`object`&&r&&`bindings`in r)i=r.bindings;else return ip=e,ap=[{type:`parse_error`,severity:`error`,message:`keybindings.json must have a "bindings" array`,suggestion:`Use format: { "bindings": [ ... ] }`}],{bindings:ip,warnings:ap};if(!che(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 ip=e,ap=[{type:`parse_error`,severity:`error`,message:t,suggestion:n}],{bindings:ip,warnings:ap}}let a=Qe(i);return U(`[keybindings] Loaded ${a.length} user bindings from ${t}`),ip=[...e,...a],ohe(a.length),ap=[...$me(n),...ihe(i,ip)],ap.length>0&&U(`[keybindings] Found ${ap.length} validation issue(s)`),{bindings:ip,warnings:ap}}catch{return ip=e,ap=[],{bindings:ip,warnings:ap}}}async function dhe(){if(np||rp)return;if(!Zf()){U(`[keybindings] Skipping file watcher - user customization disabled`);return}let e=Qf(),t=Tl(e);try{if(!(await mu(t)).isDirectory()){U(`[keybindings] Not watching: ${t} is not a directory`);return}}catch{U(`[keybindings] Not watching: ${t} does not exist`);return}np=!0,U(`[keybindings] Watching for changes to ${e}`),tp=Uf.watch(e,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:ghe,pollInterval:_he},ignorePermissionErrors:!0,usePolling:!1,atomic:!0}),tp.on(`add`,phe),tp.on(`change`,phe),tp.on(`unlink`,mhe),qn(async()=>fhe())}function fhe(){rp=!0,tp&&(tp.close(),tp=null),op.clear()}async function phe(e){U(`[keybindings] Detected change to ${e}`);try{let e=await lhe();ip=e.bindings,ap=e.warnings,op.emit(e)}catch(e){U(`[keybindings] Error reloading: ${H(e)}`)}}function mhe(e){U(`[keybindings] Detected deletion of ${e}`);let t=$f();ip=t,ap=[],op.emit({bindings:t,warnings:[]})}function hhe(){return ap}var ghe,_he,tp,np,rp,ip,ap,op,sp,vhe,cp=n((()=>{Wf(),Na(),Xn(),W(),h(),Mn(),mn(),Zn(),Ume(),Wme(),ahe(),ghe=500,_he=200,tp=null,np=!1,rp=!1,ip=null,ap=[],op=an(),sp=null,vhe=op.subscribe})),lp,yhe=n((()=>{cp(),lp={name:`keybindings`,description:`打开或创建你的 keybindings 配置文件`,isEnabled:()=>Zf(),supportsNonInteractive:!1,type:`local`,load:()=>import(`./keybindings-qed9q9tx.js`)}})),bhe,xhe=n((()=>{bhe={type:`local-jsx`,name:`mcp`,description:`管理 MCP 服务器`,immediate:!0,argumentHint:`[enable|disable [server-name]]`,load:()=>import(`./mcp-CysOyBIn.js`)}})),She,Che=n((()=>{She={type:`local-jsx`,name:`onboarding`,description:`重新运行首次启动的初始化(主题、信任、模型、MCP)`,argumentHint:`[full|theme|trust|model|mcp|status]`,isEnabled:()=>!0,isHidden:!1,load:async()=>({call:(await import(`./launchOnboarding-B__wtt7p.js`)).callOnboarding})}})),whe,The=n((()=>{whe={type:`local-jsx`,name:`rename`,description:`重命名当前会话`,immediate:!0,argumentHint:`[name]`,load:()=>import(`./rename-BUt3PliQ.js`)}})),Ehe,Dhe=n((()=>{Ehe={type:`local-jsx`,name:`resume`,description:`恢复之前的会话`,aliases:[`continue`],argumentHint:`[conversation id or search term]`,load:()=>import(`./resume-uZI9p_FE.js`)}})),up,Ohe=n((()=>{Gt(),up={type:`local-jsx`,name:`session`,aliases:[`remote`],description:`显示远程会话的 URL 和二维码`,isEnabled:()=>xt(),get isHidden(){return!xt()},load:()=>import(`./session-Tm2-rzBY.js`)}})),khe,Ahe=n((()=>{khe={type:`local-jsx`,name:`skills`,description:`列出可用的 skill`,load:()=>import(`./skills-DIgCWvzX.js`)}})),jhe,Mhe=n((()=>{jhe={type:`local-jsx`,name:`status`,description:`显示 Work Mate 的状态,包括版本、模型、账号、API 连通性与工具状态`,immediate:!0,load:()=>import(`./status-CVcXPoOZ.js`)}})),Nhe,Phe=n((()=>{Nhe={type:`local-jsx`,name:`tasks`,aliases:[`bashes`],description:`列出并管理后台任务`,load:()=>import(`./tasks-BKERIO4G.js`)}})),Fhe,Ihe=n((()=>{Fhe={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-cBovdGMT.js`)).callLocalMemory})}})),Lhe,Rhe=n((()=>{Pr(),Lhe={type:`local-jsx`,name:`terminal-setup`,description:pr.terminal===`Apple_Terminal`?`启用 Option+Enter 换行键绑定和视觉响铃`:`安装 Shift+Enter 换行键绑定`,isHidden:pr.terminal!==null&&pr.terminal in{ghostty:`Ghostty`,kitty:`Kitty`,"iTerm.app":`iTerm2`,WezTerm:`WezTerm`},load:()=>import(`./terminalSetup-DDvQ0K5e.js`)}})),dp,zhe=n((()=>{dp={type:`local-jsx`,name:`theme`,description:`切换主题`,load:()=>import(`./theme-BGxytGjA.js`)}})),fp,Bhe=n((()=>{fp={name:`vim`,description:`在 Vim 与普通编辑模式之间切换`,supportsNonInteractive:!1,type:`local`,load:()=>import(`./vim-s-wmybpU.js`)}})),pp,Vhe=n((()=>{pp={type:`local-jsx`,name:`proactive`,description:`切换主动(autonomous)模式`,isEnabled:()=>!0,immediate:!0,load:()=>Promise.resolve({async call(t,n){let r=(oc(),e(Rse));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 $pe(e,t={}){let n=t.entryType||t.type;if(n===`both`&&(n=ff.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&&!hf.includes(n))throw Error(`readdirp: Invalid type passed. Use one of ${hf.join(`, `)}`);return t.root=e,new ame(t)}var ff,pf,mf,eme,hf,tme,nme,rme,ime,gf,_f,ame,ome=n((()=>{b(),ff={FILE_TYPE:`files`,DIR_TYPE:`directories`,FILE_DIR_TYPE:`files_directories`,EVERYTHING_TYPE:`all`},pf={root:`.`,fileFilter:e=>!0,directoryFilter:e=>!0,type:ff.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096},Object.freeze(pf),mf=`READDIRP_RECURSIVE_ERROR`,eme=new Set([`ENOENT`,`EPERM`,`EACCES`,`ELOOP`,mf]),hf=[ff.DIR_TYPE,ff.EVERYTHING_TYPE,ff.FILE_DIR_TYPE,ff.FILE_TYPE],tme=new Set([ff.DIR_TYPE,ff.EVERYTHING_TYPE,ff.FILE_DIR_TYPE]),nme=new Set([ff.EVERYTHING_TYPE,ff.FILE_DIR_TYPE,ff.FILE_TYPE]),rme=e=>eme.has(e.code),ime=process.platform===`win32`,gf=e=>!0,_f=e=>{if(e===void 0)return gf;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 gf},ame=class extends Wle{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={...pf,...e},{root:n,type:r}=t;this._fileFilter=_f(t.fileFilter),this._directoryFilter=_f(t.directoryFilter);let i=t.lstat?Cu:Du;ime?this._stat=e=>i(e,{bigint:!0}):this._stat=i,this._maxDepth=t.depth!=null&&Number.isSafeInteger(t.depth)?t.depth:pf.depth,this._wantsDir=r?tme.has(r):!1,this._wantsFile=r?nme.has(r):!1,this._wantsEverything=r===ff.EVERYTHING_TYPE,this._root=Hl(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 Tu(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=Hl(Bl(t,r));n={path:Vl(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){rme(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 Eu(t),n=await Cu(e);if(n.isFile())return`file`;if(n.isDirectory()){let n=e.length;if(t.startsWith(e)&&t.substr(n,1)===Wce){let n=Error(`Circular symlink detected: "${t}" points to "${e}"`);return n.code=mf,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 sme(e,t,n,r,i){let a=(t,r)=>{n(e),i(t,r,{watchedPath:e}),r&&e!==r&&jf(Il.resolve(e,r),Cf,Il.join(e,r))};try{return ble(e,{persistent:t.persistent},a)}catch(e){r(e);return}}var cme,lme,vf,yf,bf,ume,dme,fme,pme,xf,Sf,mme,hme,Cf,wf,Tf,gme,_me,vme,Ef,Df,yme,Of,kf,Af,jf,bme,Mf,xme,Sme,Cme=n((()=>{b(),cme=`data`,lme=`close`,vf=()=>{},yf=process.platform,bf=yf===`win32`,ume=yf===`darwin`,dme=yf===`linux`,fme=yf===`freebsd`,pme=wle()===`OS400`,xf={ALL:`all`,READY:`ready`,ADD:`add`,CHANGE:`change`,ADD_DIR:`addDir`,UNLINK:`unlink`,UNLINK_DIR:`unlinkDir`,RAW:`raw`,ERROR:`error`},Sf=xf,mme=`watch`,hme={lstat:Cu,stat:Du},Cf=`listeners`,wf=`errHandlers`,Tf=`rawEmitters`,gme=[Cf,wf,Tf],_me=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(`.`)),vme=e=>_me.has(Il.extname(e).slice(1).toLowerCase()),Ef=(e,t)=>{e instanceof Set?e.forEach(t):t(e)},Df=(e,t,n)=>{let r=e[t];r instanceof Set||(e[t]=r=new Set([r])),r.add(n)},yme=e=>t=>{let n=e[t];n instanceof Set?n.clear():delete e[t]},Of=(e,t,n)=>{let r=e[t];r instanceof Set?r.delete(n):r===n&&delete e[t]},kf=e=>e instanceof Set?e.size===0:!e,Af=new Map,jf=(e,t,n,r,i)=>{let a=Af.get(e);a&&Ef(a[t],e=>{e(n,r,i)})},bme=(e,t,n,r)=>{let{listener:i,errHandler:a,rawEmitter:o}=r,s=Af.get(t),c;if(!n.persistent)return c=sme(e,n,i,a,o),c?c.close.bind(c):void 0;if(s)Df(s,Cf,i),Df(s,wf,a),Df(s,Tf,o);else{if(c=sme(e,n,jf.bind(null,t,Cf),a,jf.bind(null,t,Tf)),!c)return;c.on(Sf.ERROR,async n=>{let r=jf.bind(null,t,wf);if(s&&(s.watcherUnusable=!0),bf&&n.code===`EPERM`)try{await(await Kle(e,`r`)).close(),r(n)}catch{}else r(n)}),s={listeners:i,errHandlers:a,rawEmitters:o,watcher:c},Af.set(t,s)}return()=>{Of(s,Cf,i),Of(s,wf,a),Of(s,Tf,o),kf(s.listeners)&&(s.watcher.close(),Af.delete(t),gme.forEach(yme(s)),s.watcher=void 0,Object.freeze(s))}},Mf=new Map,xme=(e,t,n,r)=>{let{listener:i,rawEmitter:a}=r,o=Mf.get(t),s=o&&o.options;return s&&(s.persistent<n.persistent||s.interval>n.interval)&&(yle(t),o=void 0),o?(Df(o,Cf,i),Df(o,Tf,a)):(o={listeners:i,rawEmitters:a,options:n,watcher:xle(t,n,(n,r)=>{Ef(o.rawEmitters,e=>{e(Sf.CHANGE,t,{curr:n,prev:r})});let i=n.mtimeMs;(n.size!==r.size||i>r.mtimeMs||i===0)&&Ef(o.listeners,t=>t(e,n))})},Mf.set(t,o)),()=>{Of(o,Cf,i),Of(o,Tf,a),kf(o.listeners)&&(Mf.delete(t),yle(t),o.options=o.watcher=void 0,Object.freeze(o))}},Sme=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=Il.dirname(e),i=Il.basename(e);this.fsw._getWatchedDir(r).add(i);let a=Il.resolve(e),o={persistent:n.persistent};t||(t=vf);let s;return n.usePolling?(o.interval=n.interval!==n.binaryInterval&&vme(i)?n.binaryInterval:n.interval,s=xme(e,a,o,{listener:t,rawEmitter:this.fsw._emitRaw})):s=bme(e,a,o,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw}),s}_handleFile(e,t,n){if(this.fsw.closed)return;let r=Il.dirname(e),i=Il.basename(e),a=this.fsw._getWatchedDir(r),o=t;if(a.has(i))return;let s=async(t,n)=>{if(this.fsw._throttle(mme,e,5)){if(!n||n.mtimeMs===0)try{let n=await Du(e);if(this.fsw.closed)return;let r=n.atimeMs,i=n.mtimeMs;if((!r||r<=i||i!==o.mtimeMs)&&this.fsw._emit(Sf.CHANGE,e,n),(ume||dme||fme)&&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(Sf.CHANGE,e,n),o=n}}},c=this._watchWithNodeFs(e,s);if(!(n&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(Sf.ADD,e,0))return;this.fsw._emit(Sf.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 Eu(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(Sf.CHANGE,n,e.stats)):(a.add(r),this.fsw._symlinkPaths.set(i,t),this.fsw._emit(Sf.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=Il.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(cme,async o=>{if(this.fsw.closed){u=void 0;return}let s=o.path,d=Il.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=Il.join(i,Il.relative(i,d)),this._addToNodeFs(d,t,n,a+1))}}).on(Sf.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(Il.dirname(e)),c=s.has(Il.basename(e));!(n&&this.fsw.options.ignoreInitial)&&!i&&!c&&this.fsw._emit(Sf.ADD_DIR,e,t),s.add(Il.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 hme[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=Il.resolve(e),l=s?await Eu(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 Eu(e):e;if(this.fsw.closed)return;let a=Il.dirname(o.watchPath);if(this.fsw._getWatchedDir(a).add(o.watchPath),this.fsw._emit(Sf.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(Il.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 Nf(e){return Array.isArray(e)?e:[e]}function wme(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=Il.relative(e.path,t);return n?!n.startsWith(`..`)&&!Il.isAbsolute(n):!1}return!1}:()=>!1}function Tme(e){if(typeof e!=`string`)throw Error(`string expected`);e=Il.normalize(e),e=e.replace(/\\/g,`/`);let t=!1;return e.startsWith(`//`)&&(t=!0),e=e.replace(If,`/`),t&&(e=`/`+e),e}function Eme(e,t,n){let r=Tme(t);for(let t=0;t<e.length;t++){let i=e[t];if(i(r,n))return!0}return!1}function Dme(e,t){if(e==null)throw TypeError(`anymatch: specify first argument`);let n=Nf(e).map(e=>wme(e));return t==null?(e,t)=>Eme(n,e,t):Eme(n,t)}function Ome(e,t={}){let n=new Hf(t);return n.add(e),n}var Pf,kme,Ff,Ame,jme,Mme,If,Nme,Pme,Lf,Rf,zf,Bf,Vf,Fme,Ime,Lme,Rme,zme,Bme,Hf,Uf,Wf=n((()=>{ome(),Cme(),b(),Pf=`/`,kme=`//`,Ff=`.`,Ame=`..`,jme=`string`,Mme=/\\/g,If=/\/\//g,Nme=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Pme=/^\.[/\\]/,Lf=e=>typeof e==`object`&&!!e&&!(e instanceof RegExp),Rf=e=>{let t=Nf(e).flat();if(!t.every(e=>typeof e===jme))throw TypeError(`Non-string provided as watch path: ${t}`);return t.map(Bf)},zf=e=>{let t=e.replace(Mme,Pf),n=!1;return t.startsWith(kme)&&(n=!0),t=t.replace(If,Pf),n&&(t=Pf+t),t},Bf=e=>zf(Il.normalize(zf(e))),Vf=(e=``)=>t=>typeof t==`string`?Bf(Il.isAbsolute(t)?t:Il.join(e,t)):t,Fme=(e,t)=>Il.isAbsolute(e)?e:Il.join(t,e),Ime=Object.freeze(new Set),Lme=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!==Ff&&e!==Ame&&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 Tu(n)}catch{this._removeWatcher&&this._removeWatcher(Il.dirname(n),Il.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=vf,this.items=Ime,Object.freeze(this)}},Rme=`stat`,zme=`lstat`,Bme=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(Pme,``),this.watchPath=r,this.fullWatchPath=Il.resolve(r),this.dirParts=[],this.dirParts.forEach(e=>{e.length>1&&e.pop()}),this.followSymlinks=t,this.statMethod=t?Rme:zme}entryPath(e){return Il.join(this.watchPath,Il.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)}},Hf=class extends Vle{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?Nf(e.ignored):Nf([]),awaitWriteFinish:t===!0?n:typeof t==`object`&&{...n,...t}};pme&&(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=vf,this._readyEmitted=!0,process.nextTick(()=>this.emit(xf.READY)))},this._emitRaw=(...e)=>this.emit(xf.RAW,...e),this._boundRemove=this._remove.bind(this),this.options=r,this._nodeFsHandler=new Sme(this),Object.freeze(r)}_addIgnoredPath(e){if(Lf(e)){for(let t of this._ignoredPaths)if(Lf(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)Lf(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=Rf(e);return r&&(i=i.map(e=>Fme(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(Il.dirname(e),Il.basename(t||e))})}),this}unwatch(e){if(this.closed)return this;let t=Rf(e),{cwd:n}=this.options;return t.forEach(e=>{!Il.isAbsolute(e)&&!this._closers.has(e)&&(n&&(e=Il.join(n,e)),e=Il.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?Il.relative(this.options.cwd,n):n)||Ff;e[r]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==xf.ERROR&&this.emit(xf.ALL,e,...t)}async _emit(e,t,n){if(this.closed)return;let r=this.options;bf&&(t=Il.normalize(t)),r.cwd&&(t=Il.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===xf.UNLINK)return this._pendingUnlinks.set(t,[e,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((e,t)=>{this.emit(...e),this.emit(xf.ALL,...e),this._pendingUnlinks.delete(t)})},typeof r.atomic==`number`?r.atomic:100),this;e===xf.ADD&&this._pendingUnlinks.has(t)&&(e=xf.CHANGE,this._pendingUnlinks.delete(t))}if(a&&(e===xf.ADD||e===xf.CHANGE)&&this._readyEmitted)return this._awaitWriteFinish(t,a.stabilityThreshold,e,(t,n)=>{t?(e=xf.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===xf.CHANGE&&!this._throttle(xf.CHANGE,t,50))return this;if(r.alwaysStat&&n===void 0&&(e===xf.ADD||e===xf.ADD_DIR||e===xf.CHANGE)){let e=r.cwd?Il.join(r.cwd,t):t,n;try{n=await Du(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(xf.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&&!Il.isAbsolute(e)&&(s=Il.join(this.options.cwd,e));let c=new Date,l=this._pendingWrites;function u(n){gle(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&&Nme.test(e))return!0;if(!this._userIgnored){let{cwd:e}=this.options,t=(this.options.ignored||[]).map(Vf(e)),n=[...[...this._ignoredPaths].map(Vf(e)),...t];this._userIgnored=Dme(n,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new Bme(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=Il.resolve(e);return this._watched.has(t)||this._watched.set(t,new Lme(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,n){let r=Il.join(e,t),i=Il.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=Il.relative(this.options.cwd,r)),this.options.awaitWriteFinish&&this._pendingWrites.has(s)&&this._pendingWrites.get(s).cancelWait()===xf.ADD)return;this._watched.delete(r),this._watched.delete(i);let c=n?xf.UNLINK_DIR:xf.UNLINK;o&&!this._isIgnored(r)&&this._emit(c,r),this._closePath(r)}_closePath(e){this._closeFile(e);let t=Il.dirname(e);this._getWatchedDir(t).remove(Il.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=$pe(e,{type:xf.ALL,alwaysStat:!0,lstat:!0,...t,depth:0});return this._streams.add(n),n.once(lme,()=>{n=void 0}),n.once(`end`,()=>{n&&(this._streams.delete(n),n=void 0)}),n}},Uf={watch:Ome,FSWatcher:Hf}})),Vme,Hme,Gf,Ume=n((()=>{_c(),aae(),va(),Vme=_a()===`windows`?`alt+v`:`ctrl+v`,Hme=_a()!==`windows`||(iae()?cc(process.versions.bun,`>=1.2.23`):cc(process.versions.node,`>=22.17.0 <23.0.0 || >=24.2.0`))?`shift+tab`:`meta+m`,Gf=[{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`,[Hme]:`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`,[Vme]:`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`}}]})),Wme=n((()=>{I()}));function Gme(){let e=_a(),t=[...qf,...Jf];return e===`macos`&&t.push(...Yf),t}function Kf(e){return e.trim().split(/\s+/).map(Kme).join(` `)}function Kme(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 qf,Jf,Yf,qme=n((()=>{va(),qf=[{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`}],Jf=[{key:`ctrl+z`,reason:`Unix process suspend (SIGTSTP)`,severity:`warning`},{key:`ctrl+\\`,reason:`Terminal quit signal (SIGQUIT)`,severity:`error`}],Yf=[{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 Jme(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.context==`string`&&typeof t.bindings==`object`&&t.bindings!==null}function Yme(e){return Array.isArray(e)&&e.every(Jme)}function Xme(e){return Xf.includes(e)}function Zme(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=aee(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 Qme(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`?Xme(i)?a=i:n.push({type:`invalid_context`,severity:`error`,message:`Unknown context "${i}"`,context:i,suggestion:`Valid contexts: ${Xf.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=Zme(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 $me(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 ehe(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(...Qme(e[n],n));return t}function the(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=Kf(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 nhe(e){let t=[],n=Gme();for(let r of e){let e=fee(r.chord),i=Kf(e);for(let a of n)Kf(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 rhe(e){let t=[];for(let n of e)for(let[e,r]of Object.entries(n.bindings)){let i=e.split(` `).map(e=>aee(e));t.push({chord:i,action:r,context:n.context})}return t}function ihe(e,t){let n=[];if(n.push(...ehe(e)),Yme(e)){n.push(...the(e));let t=rhe(e);n.push(...nhe(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 Xf,ahe=n((()=>{Wme(),qme(),Xf=[`Global`,`Chat`,`Autocomplete`,`Confirmation`,`Help`,`Transcript`,`HistorySearch`,`Task`,`ThemePicker`,`Settings`,`Tabs`,`Attachments`,`Footer`,`FormField`,`MessageActions`,`MessageSelector`,`DiffDialog`,`ModelPicker`,`Scroll`,`Select`,`Plugin`]}));function Zf(){return!1}function ohe(e){let t=new Date().toISOString().slice(0,10);sp!==t&&(sp=t,J(`tengu_custom_keybindings_loaded`,{user_binding_count:e}))}function she(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.context==`string`&&typeof t.bindings==`object`&&t.bindings!==null}function che(e){return Array.isArray(e)&&e.every(she)}function Qf(){return Y(p(),`keybindings.json`)}function $f(){return Qe(Gf)}async function lhe(){let e=$f();if(!Zf())return{bindings:e,warnings:[]};let t=Qf();try{let n=await lu(t,`utf-8`),r=Nn(n),i;if(typeof r==`object`&&r&&`bindings`in r)i=r.bindings;else{let t=`keybindings.json must have a "bindings" array`;return U(`[keybindings] Invalid keybindings.json: ${t}`),{bindings:e,warnings:[{type:`parse_error`,severity:`error`,message:t,suggestion:`Use format: { "bindings": [ ... ] }`}]}}if(!che(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 U(`[keybindings] Invalid keybindings.json: ${t}`),{bindings:e,warnings:[{type:`parse_error`,severity:`error`,message:t,suggestion:n}]}}let a=Qe(i);U(`[keybindings] Loaded ${a.length} user bindings from ${t}`);let o=[...e,...a];ohe(a.length);let s=[...$me(n),...ihe(i,o)];return s.length>0&&U(`[keybindings] Found ${s.length} validation issue(s)`),{bindings:o,warnings:s}}catch(n){return Tn(n)?{bindings:e,warnings:[]}:(U(`[keybindings] Error loading ${t}: ${H(n)}`),{bindings:e,warnings:[{type:`parse_error`,severity:`error`,message:`Failed to parse keybindings.json: ${H(n)}`}]})}}function uhe(){return ip||ep().bindings}function ep(){if(ip)return{bindings:ip,warnings:ap};let e=$f();if(!Zf())return ip=e,ap=[],{bindings:ip,warnings:ap};let t=Qf();try{let n=Kl(t,`utf-8`),r=Nn(n),i;if(typeof r==`object`&&r&&`bindings`in r)i=r.bindings;else return ip=e,ap=[{type:`parse_error`,severity:`error`,message:`keybindings.json must have a "bindings" array`,suggestion:`Use format: { "bindings": [ ... ] }`}],{bindings:ip,warnings:ap};if(!che(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 ip=e,ap=[{type:`parse_error`,severity:`error`,message:t,suggestion:n}],{bindings:ip,warnings:ap}}let a=Qe(i);return U(`[keybindings] Loaded ${a.length} user bindings from ${t}`),ip=[...e,...a],ohe(a.length),ap=[...$me(n),...ihe(i,ip)],ap.length>0&&U(`[keybindings] Found ${ap.length} validation issue(s)`),{bindings:ip,warnings:ap}}catch{return ip=e,ap=[],{bindings:ip,warnings:ap}}}async function dhe(){if(np||rp)return;if(!Zf()){U(`[keybindings] Skipping file watcher - user customization disabled`);return}let e=Qf(),t=Tl(e);try{if(!(await mu(t)).isDirectory()){U(`[keybindings] Not watching: ${t} is not a directory`);return}}catch{U(`[keybindings] Not watching: ${t} does not exist`);return}np=!0,U(`[keybindings] Watching for changes to ${e}`),tp=Uf.watch(e,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:ghe,pollInterval:_he},ignorePermissionErrors:!0,usePolling:!1,atomic:!0}),tp.on(`add`,phe),tp.on(`change`,phe),tp.on(`unlink`,mhe),qn(async()=>fhe())}function fhe(){rp=!0,tp&&(tp.close(),tp=null),op.clear()}async function phe(e){U(`[keybindings] Detected change to ${e}`);try{let e=await lhe();ip=e.bindings,ap=e.warnings,op.emit(e)}catch(e){U(`[keybindings] Error reloading: ${H(e)}`)}}function mhe(e){U(`[keybindings] Detected deletion of ${e}`);let t=$f();ip=t,ap=[],op.emit({bindings:t,warnings:[]})}function hhe(){return ap}var ghe,_he,tp,np,rp,ip,ap,op,sp,vhe,cp=n((()=>{Wf(),Na(),Xn(),W(),h(),Mn(),mn(),Zn(),Ume(),Wme(),ahe(),ghe=500,_he=200,tp=null,np=!1,rp=!1,ip=null,ap=[],op=an(),sp=null,vhe=op.subscribe})),lp,yhe=n((()=>{cp(),lp={name:`keybindings`,description:`打开或创建你的 keybindings 配置文件`,isEnabled:()=>Zf(),supportsNonInteractive:!1,type:`local`,load:()=>import(`./keybindings-DLEorhlY.js`)}})),bhe,xhe=n((()=>{bhe={type:`local-jsx`,name:`mcp`,description:`管理 MCP 服务器`,immediate:!0,argumentHint:`[enable|disable [server-name]]`,load:()=>import(`./mcp-nnBVM5Lt.js`)}})),She,Che=n((()=>{She={type:`local-jsx`,name:`onboarding`,description:`重新运行首次启动的初始化(主题、信任、模型、MCP)`,argumentHint:`[full|theme|trust|model|mcp|status]`,isEnabled:()=>!0,isHidden:!1,load:async()=>({call:(await import(`./launchOnboarding-CVvuxeH-.js`)).callOnboarding})}})),whe,The=n((()=>{whe={type:`local-jsx`,name:`rename`,description:`重命名当前会话`,immediate:!0,argumentHint:`[name]`,load:()=>import(`./rename-CdzxOzN5.js`)}})),Ehe,Dhe=n((()=>{Ehe={type:`local-jsx`,name:`resume`,description:`恢复之前的会话`,aliases:[`continue`],argumentHint:`[conversation id or search term]`,load:()=>import(`./resume-DgFXYWTN.js`)}})),up,Ohe=n((()=>{Gt(),up={type:`local-jsx`,name:`session`,aliases:[`remote`],description:`显示远程会话的 URL 和二维码`,isEnabled:()=>xt(),get isHidden(){return!xt()},load:()=>import(`./session-L5191BSn.js`)}})),khe,Ahe=n((()=>{khe={type:`local-jsx`,name:`skills`,description:`列出可用的 skill`,load:()=>import(`./skills-DM9ACPW-.js`)}})),jhe,Mhe=n((()=>{jhe={type:`local-jsx`,name:`status`,description:`显示 Work Mate 的状态,包括版本、模型、账号、API 连通性与工具状态`,immediate:!0,load:()=>import(`./status-C3z0CSBw.js`)}})),Nhe,Phe=n((()=>{Nhe={type:`local-jsx`,name:`tasks`,aliases:[`bashes`],description:`列出并管理后台任务`,load:()=>import(`./tasks-qVyXOLBf.js`)}})),Fhe,Ihe=n((()=>{Fhe={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-DJsuNLIf.js`)).callLocalMemory})}})),Lhe,Rhe=n((()=>{Pr(),Lhe={type:`local-jsx`,name:`terminal-setup`,description:pr.terminal===`Apple_Terminal`?`启用 Option+Enter 换行键绑定和视觉响铃`:`安装 Shift+Enter 换行键绑定`,isHidden:pr.terminal!==null&&pr.terminal in{ghostty:`Ghostty`,kitty:`Kitty`,"iTerm.app":`iTerm2`,WezTerm:`WezTerm`},load:()=>import(`./terminalSetup-DDvQ0K5e.js`)}})),dp,zhe=n((()=>{dp={type:`local-jsx`,name:`theme`,description:`切换主题`,load:()=>import(`./theme-DVWYzSct.js`)}})),fp,Bhe=n((()=>{fp={name:`vim`,description:`在 Vim 与普通编辑模式之间切换`,supportsNonInteractive:!1,type:`local`,load:()=>import(`./vim-s-wmybpU.js`)}})),pp,Vhe=n((()=>{pp={type:`local-jsx`,name:`proactive`,description:`切换主动(autonomous)模式`,isEnabled:()=>!0,immediate:!0,load:()=>Promise.resolve({async call(t,n){let r=(oc(),e(Rse));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}})}})),Hhe,Uhe=n((()=>{Hhe={type:`local-jsx`,name:`job`,description:`管理模板作业(job)`,argumentHint:`[list|new|reply|status]`,isEnabled:()=>!0,load:()=>import(`./job-
|
|
391
|
+
</system-reminder>`]})),null}})}})),Hhe,Uhe=n((()=>{Hhe={type:`local-jsx`,name:`job`,description:`管理模板作业(job)`,argumentHint:`[list|new|reply|status]`,isEnabled:()=>!0,load:()=>import(`./job-N25KhSUu.js`)}})),Whe,Ghe=n((()=>{Whe={type:`local-jsx`,name:`goal`,description:`设置或查看一个持久化 goal,用于驱动跨轮次的自动续作`,argumentHint:`[<objective> | status | clear | pause | resume | complete]`,load:()=>import(`./goal-D-x2WXm7.js`)}})),Khe,qhe=n((()=>{Khe={type:`local-jsx`,name:`permissions`,aliases:[`allowed-tools`],description:`管理允许 / 拒绝的工具权限规则`,load:()=>import(`./permissions-cDtIZRM1.js`)}})),mp,Jhe=n((()=>{mp={type:`local-jsx`,name:`plan`,description:`启用 plan 模式或查看当前会话的 plan`,argumentHint:`[open|<description>]`,load:()=>import(`./plan-dG2H4eQl.js`)}}));function Yhe(){return!1}var Xhe=n((()=>{})),Zhe,Qhe=n((()=>{vo(),Xhe(),Zhe={type:`local-jsx`,name:`fast`,get description(){return`Toggle fast mode (${ioe} only)`},availability:[`claude-ai`,`console`],isEnabled:()=>Io(),get isHidden(){return!Io()},argumentHint:`[on|off]`,get immediate(){return Yhe()},load:()=>import(`./fast-B9vVL3sY.js`)}})),$he,ege=n((()=>{$he={type:`local-jsx`,name:`hooks`,description:`查看工具事件的 hook 配置`,immediate:!0,load:()=>import(`./hooks-D_afUDcs.js`)}})),tge,nge=n((()=>{tge={type:`local-jsx`,name:`branch`,aliases:[`fork`],description:`从当前时间点为当前会话创建一个分支`,argumentHint:`[name]`,load:()=>import(`./branch-BWq5ynjm.js`)}})),rge,ige=n((()=>{rge={type:`local-jsx`,name:`agents`,description:`管理智能体(agent)配置`,load:()=>import(`./agents-C8wRUTNV.js`)}})),age,oge=n((()=>{age={type:`local-jsx`,name:`plugin`,aliases:[`plugins`,`marketplace`],description:`管理 Work Mate 插件`,immediate:!0,load:()=>import(`./plugin-CzQHuIlP.js`)}})),sge,cge=n((()=>{sge={type:`local`,name:`reload-plugins`,description:`在当前会话激活待生效的插件改动`,supportsNonInteractive:!1,load:()=>import(`./reload-plugins-Cl6wvT6V.js`)}})),lge,uge=n((()=>{lge={description:`把代码和/或对话恢复到之前的某个时间点`,name:`rewind`,aliases:[`checkpoint`],argumentHint:``,type:`local`,supportsNonInteractive:!1,load:()=>import(`./rewind-D12hCfZD.js`)}})),dge,fge,pge=n((()=>{dge=async()=>({type:`text`,value:`0.0.17 (built 2026-08-14T04:15:24.415Z)`}),fge={type:`local`,name:`version`,description:`打印当前会话运行的版本(不是 autoupdate 下载的版本)`,isEnabled:()=>!0,supportsNonInteractive:!0,load:()=>Promise.resolve({call:dge})}})),mge=i({isSkillSearchCompiledIn:()=>hge,isSkillSearchEnabled:()=>hp});function hge(){return!1}function hp(){return process.env.SKILL_SEARCH_ENABLED===`1`}var gp=n((()=>{})),gge,_ge=n((()=>{gp(),gge={type:`local-jsx`,name:`skill-search`,description:`控制对话过程中自动进行的 skill 匹配`,argumentHint:`[start|stop|about|status]`,isEnabled:()=>hge(),isHidden:!1,load:()=>import(`./skillSearchPanel-CsQDjy_E.js`)}}));function X(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 _p=n((()=>{}));function vge(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 ku(t);if(e.protocol!==`http:`&&e.protocol!==`https:`||!e.hostname)throw Error(`unsupported scheme or empty host`);return e}catch{X(`Invalid parent proxy URL, ignoring: ${wge(e)}`,{level:`error`});return}},a=i(t),o=i(n);if(!(!a&&!o))return{httpUrl:a,httpsUrl:o,noProxy:yge(r)}}function yge(e){let t={all:!1,suffixes:[],cidr:new tue};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=ju(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=ju(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 vp(e,t){let n=xp(t.toLowerCase().replace(/\.$/,``));if(n===`localhost`)return!0;let r=ju(n);if(r&&Oge.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 yp(e,t){return t.isHttps?e.httpsUrl??e.httpUrl:e.httpUrl}function bge(e){let{destHost:t,destPort:n}=e,r=xp(t);if(!Sp(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=ju(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??Cp,()=>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
|
|
@@ -409,7 +409,7 @@ Connection blocked by network allowlist`);return}let c=e.getMitmSocketPath?.(o),
|
|
|
409
409
|
`);return`${o} -c ${vm.quote([i])}`}else{let e=[...s,`eval ${vm.quote([n])}`].join(`
|
|
410
410
|
`);return`${o} -c ${vm.quote([e])}`}}async function bve(e,t,n={command:`rg`},r=ym,i=!1,a){let o=[],s=[],c=[];if(t){o.push(`--ro-bind`,`/`,`/`);for(let e of t.allowOnly||[]){let t=om(e);if(X(`[Sandbox Linux] Processing write path: ${e} -> ${t}`),t.startsWith(`/dev/`)){X(`[Sandbox Linux] Skipping /dev path: ${t}`);continue}if(!Ul.existsSync(t)){X(`[Sandbox Linux] Skipping non-existent write path: ${t}`);continue}try{let n=Ul.realpathSync(t);if(n!==t.replace(/\/+$/,``)&&am(t,n)){X(`[Sandbox Linux] Skipping symlink write path pointing outside expected location: ${e} -> ${n}`);continue}}catch{X(`[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 hve(n,r,i,a)],l=new Set;for(let t of e){let e=om(t);if(l.has(e)||(l.add(e),e.startsWith(`/dev/`)))continue;let n=fve(e,s);if(n){c.push(`--ro-bind`,`/dev/null`,n),X(`[Sandbox Linux] Mounted /dev/null at symlink ${n} to prevent symlink replacement attack`);continue}if(!Ul.existsSync(e)){if(pve(e)){X(`[Sandbox Linux] Skipping deny path with file ancestor (cannot create paths under a file): ${e}`);continue}let t=Ll.dirname(e);for(;t!==`/`&&!Ul.existsSync(t);)t=Ll.dirname(t);if(s.some(n=>t.startsWith(n+`/`)||t===n||e.startsWith(n+`/`))){let t=mve(e);if(t!==e){let n=Ul.mkdtempSync(Ll.join(Ql(),`claude-empty-`));c.push(`--ro-bind`,n,t),xm.add(t),_m(),X(`[Sandbox Linux] Mounted empty dir at ${t} to block creation of ${e}`)}else c.push(`--ro-bind`,`/dev/null`,t),xm.add(t),_m(),X(`[Sandbox Linux] Mounted /dev/null at ${t} to block creation of ${e}`)}else X(`[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):X(`[Sandbox Linux] Skipping deny path not within allowed paths: ${e}`)}}else o.push(`--bind`,`/`,`/`);let l=[],u=(e?.allowWithinDeny||[]).map(e=>om(e)),d=new Set([`proc`,`dev`,`sys`]);for(let t of e?.denyOnly||[])if(om(t)===`/`)for(let e of Ul.readdirSync(`/`))d.has(e)||l.push(`/`+e);else l.push(t);Ul.existsSync(`/etc/ssh/ssh_config.d`)&&l.push(`/etc/ssh/ssh_config.d`);for(let e of l){let t=om(e);if(!Ul.existsSync(t)){X(`[Sandbox Linux] Skipping non-existent read deny path: ${t}`);continue}let n=t===`/`?`/`:t+`/`;if(Ul.statSync(t).isDirectory()){o.push(`--tmpfs`,t);for(let e of s)(e.startsWith(n)||e===t)&&(o.push(`--bind`,e,e),X(`[Sandbox Linux] Re-bound write path wiped by denyRead tmpfs: ${e}`));for(let e of u)if(e.startsWith(n)||e===t){if(!Ul.existsSync(e)){X(`[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),X(`[Sandbox Linux] Re-allowed read access within denied region: ${e}`)}}else{if(u.some(e=>t===e||t.startsWith(e+`/`))){X(`[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 xve(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=ym,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)X(`[Sandbox Linux] Skipping seccomp filter - allowAllUnixSockets is enabled`);else{b=uve(h?.bpfPath)??void 0;let e=pm(h?.applyPath);!b||!e?(X(`[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/`)||(bm.add(b),_m()),X(`[Sandbox Linux] Generated seccomp BPF filter for Unix socket blocking`))}if(n&&(y.push(`--unshare-net`),r&&i)){if(!Ul.existsSync(r))throw Error(`Linux HTTP bridge socket does not exist: ${r}. The bridge process may have died. Try reinitializing the sandbox.`);if(!Ul.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=tve(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 bve(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=Dp(x);if(!S)throw Error(`Shell '${x}' not found in PATH`);if(y.push(`--`,S,`-c`),n&&r&&i){let e=yve(r,i,t,b,S,h?.applyPath);y.push(e)}else if(b){let e=pm(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=vm.quote([e,b,S,`-c`,t]);y.push(n)}else y.push(t);let C=vm.quote([`bwrap`,...y]),w=[];return n&&w.push(`network`),(_||v)&&w.push(`filesystem`),b&&w.push(`seccomp(unix-block)`),X(`[Sandbox Linux] Wrapped command with bwrap (${w.join(`, `)} restrictions)`),C}catch(e){throw b&&!b.includes(`/vendor/seccomp/`)&&bm.delete(b),e}}var vm,ym,bm,xm,Sm,Sve=n((()=>{vm=r(Oc(),1),_p(),Op(),Q_e(),dm(),dve(),ym=3,bm=new Set,xm=new Set,Sm=!1}));function Cve(e=!1){let t=process.cwd(),n=[];for(let e of um)n.push(Cl.resolve(t,e)),n.push(`**/${e}`);for(let e of $_e())n.push(Cl.resolve(t,e)),n.push(`**/${e}/**`);return n.push(Cl.resolve(t,`.git/hooks`)),n.push(`**/.git/hooks/**`),e||(n.push(Cl.resolve(t,`.git/config`)),n.push(`**/.git/config`)),[...new Set(n)]}function wve(e){return`CMD64_${nve(e)}_END_${wm}`}function Tve(e){let t=[],n=Cl.dirname(e);for(;n!==`/`&&n!==`.`;){t.push(n);let e=Cl.dirname(n);if(e===n)break;n=e}return t}function Eve(e,t){let n=[];for(let r of e){let e=om(r);if(rm(e)){let r=cm(e);n.push(`(deny file-write-unlink`,` (regex ${Cm(r)})`,` (with message "${t}"))`);let i=e.split(/[*?[\]]/)[0];if(i&&i!==`/`){let e=i.endsWith(`/`)?i.slice(0,-1):Cl.dirname(i);n.push(`(deny file-write-unlink`,` (literal ${Cm(e)})`,` (with message "${t}"))`);for(let r of Tve(e))n.push(`(deny file-write-unlink`,` (literal ${Cm(r)})`,` (with message "${t}"))`)}}else{n.push(`(deny file-write-unlink`,` (subpath ${Cm(e)})`,` (with message "${t}"))`);for(let r of Tve(e))n.push(`(deny file-write-unlink`,` (literal ${Cm(r)})`,` (with message "${t}"))`)}}return n}function Dve(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=om(i);if(e===`/`&&(r=!0),rm(e)){let r=cm(e);n.push(`(deny file-read*`,` (regex ${Cm(r)})`,` (with message "${t}"))`)}else n.push(`(deny file-read*`,` (subpath ${Cm(e)})`,` (with message "${t}"))`)}r&&n.push(`(allow file-read* (literal "/"))`);for(let r of e.allowWithinDeny||[]){let e=om(r);if(rm(e)){let r=cm(e);n.push(`(allow file-read*`,` (regex ${Cm(r)})`,` (with message "${t}"))`)}else n.push(`(allow file-read*`,` (subpath ${Cm(e)})`,` (with message "${t}"))`)}return e.denyOnly.length>0&&n.push(`(allow file-read-metadata`,` (vnode-type DIRECTORY))`),n.push(...Eve(e.denyOnly||[],t)),n}function Ove(e,t,n=!1){if(!e)return[`(allow file-write*)`];let r=[];for(let n of e.allowOnly||[]){let e=om(n);if(rm(e)){let n=cm(e);r.push(`(allow file-write*`,` (regex ${Cm(n)})`,` (with message "${t}"))`)}else r.push(`(allow file-write*`,` (subpath ${Cm(e)})`,` (with message "${t}"))`)}let i=[...e.denyWithinAllow||[],...Cve(n)];for(let e of i){let n=om(e);if(rm(n)){let e=cm(n);r.push(`(deny file-write*`,` (regex ${Cm(e)})`,` (with message "${t}"))`)}else r.push(`(deny file-write*`,` (subpath ${Cm(n)})`,` (with message "${t}"))`)}return r.push(...Eve(i,t)),r}function kve({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=om(e);f.push(`(allow network-bind (local unix-socket (subpath ${Cm(t)})))`),f.push(`(allow network-outbound (remote unix-socket (subpath ${Cm(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(...Dve(e,d)),f.push(``),f.push(`; File write`),f.push(...Ove(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(`
|
|
411
411
|
`)}function Cm(e){return JSON.stringify(e)}function Ave(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=kve({readConfig:c,writeConfig:l,httpProxyPort:r,socksProxyPort:i,needsNetworkRestriction:n,allowUnixSockets:a,allowAllUnixSockets:o,allowLocalBinding:s,allowPty:u,allowGitConfig:d,enableWeakerNetworkIsolation:f,logTag:wve(t)}),g=tve(r,i),_=p||`bash`,v=Dp(_);if(!v)throw Error(`Shell '${_}' not found in PATH`);let y=Mve.quote([`env`,...g,`sandbox-exec`,`-p`,h,v,`-c`,t]);return X(`[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 jve(e,t){let n=/CMD64_(.+?)_END/,r=/Sandbox:\s+(.+)$/,i=t?.[`*`]||[],a=t?Object.entries(t).filter(([e])=>e!==`*`):[],o=yu(`log`,[`stream`,`--predicate`,`(eventMessage ENDSWITH "${wm}")`,`--style`,`compact`]);return o.stdout?.on(`data`,o=>{let s=o.toString().split(`
|
|
412
|
-
`),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=rve(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=>{X(`[Sandbox Monitor] Log stream stderr: ${e.toString()}`)}),o.on(`error`,e=>{X(`[Sandbox Monitor] Failed to start log stream: ${e.message}`)}),o.on(`exit`,e=>{X(`[Sandbox Monitor] Log stream exited with code: ${e}`)}),()=>{X(`[Sandbox Monitor] Stopping log monitor`),o.kill(`SIGTERM`)}}var Mve,wm,Nve=n((()=>{Mve=r(Oc(),1),_p(),Op(),dm(),wm=`_${Math.random().toString(36).slice(2,11)}_SBX`})),Tm,Em=n((()=>{dm(),Tm=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=nve(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 Pve(){if(Pm)return;let e=()=>Om().catch(e=>{X(`Cleanup failed in registerCleanup ${e}`,{level:`error`})});process.once(`exit`,e),process.once(`SIGINT`,e),process.once(`SIGTERM`,e),Pm=!0}function Dm(e,t){let n=e.toLowerCase();if(t.startsWith(`*.`)){if(ju(xp(n)))return!1;let e=t.substring(2).toLowerCase();return n.endsWith(`.`+e)}return n===t.toLowerCase()}async function Fve(e,t,n){if(!km)return X(`No config available, denying network request`),!1;if(!Sp(t))return X(`Denying malformed host: ${JSON.stringify(t)}:${e}`,{level:`error`}),!1;let r=Tge(t)??t;for(let n of km.network.deniedDomains)if(Dm(r,n))return X(`Denied by config rule: ${t}:${e}`),!1;for(let n of km.network.allowedDomains)if(Dm(r,n))return X(`Allowed by config rule: ${t}:${e}`),!0;if(!n)return X(`No matching config rule, denying: ${t}:${e}`),!1;X(`No matching config rule, asking user: ${t}:${e}`);try{return await n({host:t,port:e})?(X(`User allowed: ${t}:${e}`),!0):(X(`User denied: ${t}:${e}`),!1)}catch(e){return X(`Error in permission callback: ${e}`,{level:`error`}),!1}}function Ive(e){if(!km?.network.mitmProxy)return;let{socketPath:t,domains:n}=km.network.mitmProxy;for(let r of n)if(Dm(e,r))return X(`Host ${e} matches MITM pattern ${r}`),t}async function Lve(e){return Am=kge({filter:(t,n)=>Fve(t,n,e),getMitmSocketPath:Ive,parentProxy:Im}),new Promise((e,t)=>{if(!Am){t(Error(`HTTP proxy server undefined before listen`));return}let n=Am;n.once(`error`,t),n.once(`listening`,()=>{let r=n.address();r&&typeof r==`object`?(n.unref(),X(`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 Rve(e){return jm=Lge({filter:(t,n)=>Fve(t,n,e),parentProxy:Im}),new Promise((e,t)=>{if(!jm){t(Error(`SOCKS proxy server undefined before listen`));return}jm.listen(0,`127.0.0.1`).then(t=>{jm?.unref(),e(t)}).catch(t)})}async function zve(e,t,n=!1){if(Nm){await Nm;return}km=e,Im=vge(e.network.parentProxy),Im&&X(`Parent proxy configured: http=${Cge(Im.httpUrl)} https=${Cge(Im.httpsUrl)}`);let r=Hve();if(r.errors.length>0)throw Error(`Sandbox dependencies not available: ${r.errors.join(`, `)}`);n&&tm()===`macos`&&(Fm=jve(Lm.addViolation.bind(Lm),km.ignoreViolations),X(`Started macOS sandbox log monitor`)),Pve(),Nm=(async()=>{try{let e;km.network.httpProxyPort===void 0?e=await Lve(t):(e=km.network.httpProxyPort,X(`Using external HTTP proxy on port ${e}`));let n;km.network.socksProxyPort===void 0?n=await Rve(t):(n=km.network.socksProxyPort,X(`Using external SOCKS proxy on port ${n}`));let r;tm()===`linux`&&(r=await vve(e,n));let i={httpProxyPort:e,socksProxyPort:n,linuxBridge:r};return Mm=i,X(`Network infrastructure initialized`),i}catch(e){throw Nm=void 0,Mm=void 0,Om().catch(e=>{X(`Cleanup failed in initializationPromise ${e}`,{level:`error`})}),e}})(),await Nm}function Bve(){let e=tm();return e===`linux`?X_e()!==`1`:e===`macos`}function Vve(){return km!==void 0}function Hve(e){if(!Bve())return{errors:[`Unsupported platform`],warnings:[]};let t=[],n=[],r=e??km?.ripgrep??{command:`rg`};if(Dp(r.command)===null&&t.push(`ripgrep (${r.command}) not found`),tm()===`linux`){let e=_ve(km?.seccomp);t.push(...e.errors),n.push(...e.warnings)}return{errors:t,warnings:n}}function Uve(){if(!km)return{denyOnly:[],allowWithinDeny:[]};let e=[];for(let t of km.filesystem.denyRead){let n=im(t);if(tm()===`linux`&&rm(n)){let n=lm(t);X(`[Sandbox] Expanded glob pattern "${t}" to ${n.length} paths on Linux`),e.push(...n)}else e.push(n)}let t=[];for(let e of km.filesystem.allowRead??[]){let n=im(e);if(tm()===`linux`&&rm(n)){let n=lm(e);X(`[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 Wve(){if(!km)return{allowOnly:sm(),denyWithinAllow:[]};let e=km.filesystem.allowWrite.map(e=>im(e)).filter(e=>tm()===`linux`&&rm(e)?(X(`Skipping glob pattern on Linux/WSL: ${e}`),!1):!0),t=km.filesystem.denyWrite.map(e=>im(e)).filter(e=>tm()===`linux`&&rm(e)?(X(`Skipping glob pattern on Linux/WSL: ${e}`),!1):!0);return{allowOnly:[...sm(),...e],denyWithinAllow:t}}function Gve(){if(!km)return{};let e=km.network.allowedDomains,t=km.network.deniedDomains;return{...e.length>0&&{allowedHosts:e},...t.length>0&&{deniedHosts:t}}}function Kve(){return km?.network?.allowUnixSockets}function qve(){return km?.network?.allowAllUnixSockets}function Jve(){return km?.network?.allowLocalBinding}function Yve(){return km?.ignoreViolations}function Xve(){return km?.enableWeakerNestedSandbox}function Zve(){return km?.enableWeakerNetworkIsolation}function Qve(){return km?.ripgrep??{command:`rg`}}function $ve(){return km?.mandatoryDenySearchDepth??3}function eye(){return km?.filesystem?.allowGitConfig??!1}function tye(){return km?.seccomp}function nye(){return Mm?.httpProxyPort}function rye(){return Mm?.socksProxyPort}function iye(){return Mm?.linuxBridge?.httpSocketPath}function aye(){return Mm?.linuxBridge?.socksSocketPath}async function oye(){if(!km)return!1;if(Nm)try{return await Nm,!0}catch{return!1}return Mm!==void 0}async function sye(e,t,n,r){let i=tm(),a=e=>e.map(e=>im(e)).filter(e=>tm()===`linux`&&rm(e)?(X(`[Sandbox] Skipping glob write pattern on Linux: ${e}`),!1):!0),o=a(n?.filesystem?.allowWrite??km?.filesystem.allowWrite??[]),s={allowOnly:[...sm(),...o],denyWithinAllow:a(n?.filesystem?.denyWrite??km?.filesystem.denyWrite??[])},c=n?.filesystem?.denyRead??km?.filesystem.denyRead??[],l=[];for(let e of c){let t=im(e);tm()===`linux`&&rm(t)?l.push(...lm(e)):l.push(t)}let u=n?.filesystem?.allowRead??km?.filesystem.allowRead??[],d=[];for(let e of u){let t=im(e);tm()===`linux`&&rm(t)?d.push(...lm(e)):d.push(t)}let f={denyOnly:l,allowWithinDeny:d},p=n?.network?.allowedDomains!==void 0||km?.network?.allowedDomains!==void 0,m=p,h=p;h&&await oye();let g=n?.allowPty??km?.allowPty;switch(i){case`macos`:return Ave({command:e,needsNetworkRestriction:m,httpProxyPort:h?nye():void 0,socksProxyPort:h?rye():void 0,readConfig:f,writeConfig:s,allowUnixSockets:Kve(),allowAllUnixSockets:qve(),allowLocalBinding:Jve(),ignoreViolations:Yve(),allowPty:g,allowGitConfig:eye(),enableWeakerNetworkIsolation:Zve(),binShell:t});case`linux`:return xve({command:e,needsNetworkRestriction:m,httpSocketPath:h?iye():void 0,socksSocketPath:h?aye():void 0,httpProxyPort:h?Mm?.httpProxyPort:void 0,socksProxyPort:h?Mm?.socksProxyPort:void 0,readConfig:f,writeConfig:s,enableWeakerNestedSandbox:Xve(),allowAllUnixSockets:qve(),binShell:t,ripgrepConfig:Qve(),mandatoryDenySearchDepth:$ve(),allowGitConfig:eye(),seccompConfig:tye(),abortSignal:r});default:throw Error(`Sandbox configuration is not supported on platform: ${i}`)}}function cye(){return km}function lye(e){km=Mde(e),Im=vge(e.network.parentProxy),X(`Sandbox configuration updated`)}function uye(){gve()}async function Om(){if(uye(),Fm&&(Fm(),Fm=void 0),Mm?.linuxBridge){let{httpSocketPath:e,socksSocketPath:t,httpBridgeProcess:n,socksBridgeProcess:r}=Mm.linuxBridge,i=[];if(n.pid&&!n.killed)try{process.kill(n.pid,`SIGTERM`),X(`Sent SIGTERM to HTTP bridge process`),i.push(new Promise(e=>{n.once(`exit`,()=>{X(`HTTP bridge process exited`),e()}),setTimeout(()=>{if(!n.killed){X(`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`&&X(`Error killing HTTP bridge: ${e}`,{level:`error`})}if(r.pid&&!r.killed)try{process.kill(r.pid,`SIGTERM`),X(`Sent SIGTERM to SOCKS bridge process`),i.push(new Promise(e=>{r.once(`exit`,()=>{X(`SOCKS bridge process exited`),e()}),setTimeout(()=>{if(!r.killed){X(`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`&&X(`Error killing SOCKS bridge: ${e}`,{level:`error`})}if(await Promise.all(i),e)try{Ul.rmSync(e,{force:!0}),X(`Cleaned up HTTP socket`)}catch(e){X(`HTTP socket cleanup error: ${e}`,{level:`error`})}if(t)try{Ul.rmSync(t,{force:!0}),X(`Cleaned up SOCKS socket`)}catch(e){X(`SOCKS socket cleanup error: ${e}`,{level:`error`})}}let e=[];if(Am){let t=Am,n=new Promise(e=>{t.close(t=>{t&&t.message!==`Server is not running.`&&X(`Error closing HTTP proxy server: ${t.message}`,{level:`error`}),e()})});e.push(n)}if(jm){let t=jm.close().catch(e=>{X(`Error closing SOCKS proxy server: ${e.message}`,{level:`error`})});e.push(t)}await Promise.all(e),Am=void 0,jm=void 0,Mm=void 0,Nm=void 0,Im=void 0}function dye(){return Lm}function fye(e,t){if(!km)return t;let n=Lm.getViolationsForCommand(e);if(n.length===0)return t;let r=t;r+=Zl+`<sandbox_violations>`+Zl;for(let e of n)r+=e.line+Zl;return r+=`</sandbox_violations>`,r}function pye(){if(tm()!==`linux`||!km)return[];let e=[],t=[...km.filesystem.allowWrite,...km.filesystem.denyWrite];for(let n of t)rm(im(n))&&e.push(n);return e}var km,Am,jm,Mm,Nm,Pm,Fm,Im,Lm,Rm,mye=n((()=>{jge(),Rge(),_p(),Op(),em(),nm(),Sve(),Nve(),dm(),Em(),wp(),Pm=!1,Lm=new Tm,Rm={initialize:zve,isSupportedPlatform:Bve,isSandboxingEnabled:Vve,checkDependencies:Hve,getFsReadConfig:Uve,getFsWriteConfig:Wve,getNetworkRestrictionConfig:Gve,getAllowUnixSockets:Kve,getAllowLocalBinding:Jve,getIgnoreViolations:Yve,getEnableWeakerNestedSandbox:Xve,getProxyPort:nye,getSocksProxyPort:rye,getLinuxHttpSocketPath:iye,getLinuxSocksSocketPath:aye,waitForNetworkInitialization:oye,wrapWithSandbox:sye,cleanupAfterCommand:uye,reset:Om,getSandboxViolationStore:dye,annotateStderrWithSandboxFailures:fye,getLinuxGlobPatternWarnings:pye,getConfig:cye,updateConfig:lye}})),zm,Bm,hye,gye,_ye,vye,yye,bye,xye,Sye=n((()=>{N(),zm=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.`}),Bm=j().min(1,`Path cannot be empty`),hye=se({socketPath:j().min(1).describe(`Unix socket path to the MITM proxy`),domains:M(zm).min(1).describe(`Domains to route through the MITM proxy (e.g., ["api.example.com", "*.internal.org"])`)}),gye=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.`)}),_ye=se({allowedDomains:M(zm).describe(`List of allowed domains (e.g., ["github.com", "*.npmjs.org"])`),deniedDomains:M(zm).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:hye.optional().describe(`Optional MITM proxy configuration. Routes matching domains through an upstream proxy via Unix socket while SRT still handles allow/deny filtering.`),parentProxy:gye.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.`)}),vye=se({denyRead:M(Bm).describe(`Paths denied for reading`),allowRead:M(Bm).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(Bm).describe(`Paths allowed for writing`),denyWrite:M(Bm).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.`)}),yye=le(j(),M(j())).describe(`Map of command patterns to filesystem paths to ignore violations for. Use "*" to match all commands`),bye=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])`)}),xye=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:_ye.describe(`Network restrictions configuration`),filesystem:vye.describe(`Filesystem restrictions configuration`),ignoreViolations:yye.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:bye.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:xye.optional().describe(`Custom seccomp binary paths (Linux only).`)})})),Cye=n((()=>{mye(),Em(),Sye(),dm(),nm()}));async function wye(){if(xt()||Ym||Xm)return;Ym=!0,jye(),qn(Tye);let{dirs:e,settingsFiles:t,dropInDir:n}=await Eye();Xm||e.length!==0&&(U(`Watching for changes in setting files ${[...t].join(`, `)}...${n?` and drop-in directory ${n}`:``}`),Km=Uf.watch(e,{persistent:!0,ignoreInitial:!0,depth:0,awaitWriteFinish:{stabilityThreshold:$m?.stabilityThreshold??Pye,pollInterval:$m?.pollInterval??Fye},ignored:(e,r)=>{if(r&&!r.isFile()&&!r.isDirectory()||e.split(Cl.sep).some(e=>e===`.git`))return!0;if(!r||r.isDirectory())return!1;let i=Cl.normalize(e);return!(t.has(i)||n&&i.startsWith(n+Cl.sep)&&i.endsWith(`.json`))},ignorePermissionErrors:!0,usePolling:!1,atomic:!0}),Km.on(`change`,Oye),Km.on(`unlink`,Aye),Km.on(`add`,kye))}function Tye(){Xm=!0,qm&&(clearInterval(qm),qm=null);for(let e of Zm.values())clearTimeout(e);Zm.clear(),Jm=null,Ane(),Qm.clear();let e=Km;return Km=null,e?e.close():Promise.resolve()}async function Eye(){let e=new Map,t=new Set;for(let n of ai){if(n===`flagSettings`)continue;let r=li(n);if(!r)continue;let i=Cl.dirname(r);e.has(i)||e.set(i,new Set),e.get(i).add(r);try{(await mu(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=Ir();try{(await mu(i)).isDirectory()&&(t.add(i),r=i)}catch{}return{dirs:[...t],settingsFiles:n,dropInDir:r}}function Dye(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 Oye(e){let t=Vm(e);if(!t)return;let n=Zm.get(e);n&&(clearTimeout(n),Zm.delete(e),U(`Cancelled pending deletion of ${e} — file was recreated`)),!are(e,Um)&&(U(`Detected change to ${e}`),l7(Dye(t),e).then(n=>{if(r7(n)){U(`ConfigChange hook blocked change to ${e}`);return}Hm(t)}))}function kye(e){if(!Vm(e))return;let t=Zm.get(e);t&&(clearTimeout(t),Zm.delete(e),U(`Cancelled pending deletion of ${e} — file was re-added`)),Oye(e)}function Aye(e){let t=Vm(e);if(!t||(U(`Detected deletion of ${e}`),Zm.has(e)))return;let n=setTimeout((e,t)=>{Zm.delete(e),l7(Dye(t),e).then(n=>{if(r7(n)){U(`ConfigChange hook blocked deletion of ${e}`);return}Hm(t)})},$m?.deletionGrace??Gm,e,t);Zm.set(e,n)}function Vm(e){let t=Cl.normalize(e),n=Ir();return t.startsWith(n+Cl.sep)?`policySettings`:ai.find(e=>li(e)===t)}function jye(){let e=Bre(),t=Fne();Jm=V({mdm:e.settings,hkcu:t.settings}),qm=setInterval(()=>{Xm||(async()=>{try{let{mdm:e,hkcu:t}=await Bne();if(Xm)return;let n=V({mdm:e.settings,hkcu:t.settings});n!==Jm&&(Jm=n,Lne(e,t),U(`Detected MDM settings change via poll`),Hm(`policySettings`))}catch(e){U(`MDM poll error: ${H(e)}`)}})()},$m?.mdmPollInterval??Wm),qm.unref()}function Hm(e){qt(),Qm.emit(e)}function Mye(e){U(`Programmatic settings change notification for ${e}`),Hm(e)}function Nye(e){qm&&(clearInterval(qm),qm=null);for(let e of Zm.values())clearTimeout(e);Zm.clear(),Jm=null,Ym=!1,Xm=!1,$m=e??null;let t=Km;return Km=null,t?t.close():Promise.resolve()}var Pye,Fye,Um,Wm,Gm,Km,qm,Jm,Ym,Xm,Zm,Qm,$m,Iye,eh,th=n((()=>{Wf(),Gt(),Xn(),W(),Mn(),g7(),mn(),Zn(),ti(),Fre(),wr(),Zne(),Yr(),Qt(),Pye=1e3,Fye=500,Um=5e3,Wm=1800*1e3,Gm=1700,Km=null,qm=null,Jm=null,Ym=!1,Xm=!1,Zm=new Map,Qm=an(),$m=null,Iye=Qm.subscribe,eh={initialize:wye,dispose:Tye,subscribe:Iye,notifyChange:Mye,resetForTesting:Nye}}));function nh(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 Lye(e){return e.match(/^(.+):\*$/)?.[1]??null}function rh(e,t){return e.startsWith(`//`)?e.slice(1):e.startsWith(`/`)&&!e.startsWith(`//`)?Ml(ei(t),e.slice(1)):e}function ih(e,t){return e.startsWith(`//`)?e.slice(1):oi(e,ei(t))}function ah(){return Ur(`policySettings`)?.sandbox?.network?.allowManagedDomainsOnly===!0}function Rye(){return Ur(`policySettings`)?.sandbox?.filesystem?.allowManagedReadPathsOnly===!0}function oh(e){let t=e.permissions||{},n=[],r=[];if(ah()){let e=Ur(`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=nh(e);t.ruleContent?.startsWith(`domain:`)&&r.push(t.ruleContent.substring(7))}let i=[`.`,F8()],a=[],o=[],s=[],c=ai.map(e=>li(e)).filter(e=>e!==void 0);a.push(...c),a.push(Ir());let l=It(),u=Zt();l!==u&&(a.push(Ml(l,`.workmate`,`settings.json`)),a.push(Ml(l,`.workmate`,`settings.local.json`))),a.push(Ml(u,`.workmate`,`skills`)),l!==u&&a.push(Ml(l,`.workmate`,`skills`)),ph.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=Ml(e,t);try{nle(n),a.push(n)}catch{ph.push(n)}}fh&&fh!==l&&i.push(fh);let f=new Set([...e.permissions?.additionalDirectories||[],...$t()]);i.push(...f);for(let e of ai){let t=Ur(e);if(t?.permissions){for(let n of t.permissions.allow||[]){let t=nh(n);t.toolName===`Edit`&&t.ruleContent&&i.push(rh(t.ruleContent,e))}for(let n of t.permissions.deny||[]){let t=nh(n);t.toolName===`Edit`&&t.ruleContent&&a.push(rh(t.ruleContent,e)),t.toolName===`Read`&&t.ruleContent&&o.push(rh(t.ruleContent,e))}}let n=t?.sandbox?.filesystem;if(n){for(let t of n.allowWrite||[])i.push(ih(t,e));for(let t of n.denyWrite||[])a.push(ih(t,e));for(let t of n.denyRead||[])o.push(ih(t,e));if(!Rye()||e===`policySettings`)for(let t of n.allowRead||[])s.push(ih(t,e))}}let{rgPath:p,rgArgs:m,argv0:h}=Mc(),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 zye(){for(let e of ph)try{tle(e,{recursive:!0}),U(`[Sandbox] scrubbed planted bare-repo file: ${e}`)}catch{}}async function Bye(e){let t=Y(e,`.git`);try{let n=(await lu(t,{encoding:`utf8`})).match(/^gitdir:\s*(.+)$/m);if(!n?.[1])return null;let r=Ml(e,n[1].trim()),i=`${Nl}.git${Nl}worktrees${Nl}`,a=r.lastIndexOf(i);return a>0?r.substring(0,a):null}catch{return null}}function sh(){try{return qr()?.sandbox?.enabled??!1}catch(e){return U(`Failed to get settings for sandbox check: ${e}`),!1}}function Vye(){return qr()?.sandbox?.autoAllowBashIfSandboxed??!0}function Hye(){return qr()?.sandbox?.allowUnsandboxedCommands??!0}function Uye(){let e=qr();return sh()&&(e?.sandbox?.failIfUnavailable??!1)}function ch(){try{let e=ii()?.sandbox?.enabledPlatforms;if(e===void 0)return!0;if(e.length===0)return!1;let t=_a();return e.includes(t)}catch(e){return U(`Failed to check enabledPlatforms: ${e}`),!0}}function lh(){return!hh()||mh().errors.length>0||!ch()?!1:sh()}function Wye(){if(!sh())return;if(!hh()){let e=_a();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(!ch())return`sandbox.enabled is set but ${_a()} is not in sandbox.enabledPlatforms`;let e=mh();if(e.errors.length>0){let t=_a()===`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 Gye(){let e=_a();if(e!==`linux`&&e!==`wsl`)return[];try{let e=qr();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=nh(e);(t.toolName===`Edit`||t.toolName===`Read`)&&t.ruleContent&&r(t.ruleContent)&&n.push(e)}return n}catch(e){return U(`Failed to get Linux glob pattern warnings: ${e}`),[]}}function Kye(){for(let e of[`flagSettings`,`policySettings`]){let t=Ur(e);if(t?.sandbox?.enabled!==void 0||t?.sandbox?.autoAllowBashIfSandboxed!==void 0||t?.sandbox?.allowUnsandboxedCommands!==void 0)return!0}return!1}async function qye(e){_i(`localSettings`,{sandbox:{...Ur(`localSettings`)?.sandbox,...e.enabled!==void 0&&{enabled:e.enabled},...e.autoAllowBashIfSandboxed!==void 0&&{autoAllowBashIfSandboxed:e.autoAllowBashIfSandboxed},...e.allowUnsandboxedCommands!==void 0&&{allowUnsandboxedCommands:e.allowUnsandboxedCommands}}})}function Jye(){return qr()?.sandbox?.excludedCommands??[]}async function Yye(e,t,n,r){if(lh())if(uh)await uh;else throw Error(`Sandbox failed to initialize. `);return Rm.wrapWithSandbox(e,t,n,r)}async function Xye(e){if(uh)return uh;if(!lh())return;let t=e?async t=>ah()?(U(`[sandbox] Blocked network request to ${t.host} (allowManagedDomainsOnly)`),!1):e(t):void 0;return uh=(async()=>{try{fh===void 0&&(fh=await Bye(It()));let e=oh(qr());await Rm.initialize(e,t),dh=eh.subscribe(()=>{let e=oh(qr());Rm.updateConfig(e),U(`Sandbox configuration updated from settings change`)})}catch(e){uh=void 0,U(`Failed to initialize sandbox: ${H(e)}`)}})(),uh}function Zye(){if(!lh())return;let e=oh(qr());Rm.updateConfig(e)}async function Qye(){return dh?.(),dh=void 0,fh=void 0,ph.length=0,mh.cache.clear?.(),hh.cache.clear?.(),uh=void 0,Rm.reset()}function $ye(e,t){let n=Ur(`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===Is);t?.ruleContent&&(i=Lye(t.ruleContent)||t.ruleContent)}}return r.includes(i)||_i(`localSettings`,{sandbox:{...n?.sandbox,excludedCommands:[...r,i]}}),i}var uh,dh,fh,ph,mh,hh,gh,_h=n((()=>{Cye(),em(),Gt(),W(),Wr(),va(),th(),ti(),wr(),Yr(),Ts(),Rs(),Bs(),Mn(),L8(),jc(),ph=[],mh=u(()=>{let{rgPath:e,rgArgs:t}=Mc();return Rm.checkDependencies({command:e,args:t})}),hh=u(()=>Rm.isSupportedPlatform()),gh={initialize:Xye,isSandboxingEnabled:lh,isSandboxEnabledInSettings:sh,isPlatformInEnabledList:ch,getSandboxUnavailableReason:Wye,isAutoAllowBashIfSandboxedEnabled:Vye,areUnsandboxedCommandsAllowed:Hye,isSandboxRequired:Uye,areSandboxSettingsLockedByPolicy:Kye,setSandboxSettings:qye,getExcludedCommands:Jye,wrapWithSandbox:Yye,refreshConfig:Zye,reset:Qye,checkDependencies:mh,getFsReadConfig:Rm.getFsReadConfig,getFsWriteConfig:Rm.getFsWriteConfig,getNetworkRestrictionConfig:Rm.getNetworkRestrictionConfig,getIgnoreViolations:Rm.getIgnoreViolations,getLinuxGlobPatternWarnings:Gye,isSupportedPlatform:hh,getAllowUnixSockets:Rm.getAllowUnixSockets,getAllowLocalBinding:Rm.getAllowLocalBinding,getEnableWeakerNestedSandbox:Rm.getEnableWeakerNestedSandbox,getProxyPort:Rm.getProxyPort,getSocksProxyPort:Rm.getSocksProxyPort,getLinuxHttpSocketPath:Rm.getLinuxHttpSocketPath,getLinuxSocksSocketPath:Rm.getLinuxSocksSocketPath,waitForNetworkInitialization:Rm.waitForNetworkInitialization,getSandboxViolationStore:Rm.getSandboxViolationStore,annotateStderrWithSandboxFailures:Rm.annotateStderrWithSandboxFailures,cleanupAfterCommand:()=>{Rm.cleanupAfterCommand(),zye()}}})),vh,ebe=n((()=>{ne(),_h(),vh={name:`sandbox`,get description(){let e=gh.isSandboxingEnabled(),t=gh.isAutoAllowBashIfSandboxedEnabled(),n=gh.areUnsandboxedCommandsAllowed(),r=gh.areSandboxSettingsLockedByPolicy(),i=gh.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!gh.isSupportedPlatform()||!gh.isPlatformInEnabledList()},immediate:!0,type:`local-jsx`,load:()=>import(`./sandbox-toggle-BdvylnWS.js`)}}));function yh(e){return e.type===`advisor_tool_result`||e.type===`server_tool_use`&&e.name===`advisor`}function bh(){return{}}function xh(){return m(process.env.CLAUDE_CODE_DISABLE_ADVISOR_TOOL)||!wo()?!1:bh().enabled??!1}function Sh(){return xh()&&(bh().canUserConfigure??!1)}function tbe(){let e=bh();return xh()&&!Sh()&&e.baseModel&&e.advisorModel?{baseModel:e.baseModel,advisorModel:e.advisorModel}:void 0}function Ch(e){let t=e.toLowerCase();return t.includes(`opus-4-7`)||t.includes(`opus-4-6`)||t.includes(`sonnet-4-6`)}function wh(e){let t=e.toLowerCase();return t.includes(`opus-4-7`)||t.includes(`opus-4-6`)||t.includes(`sonnet-4-6`)}function nbe(){if(xh())return ii().advisorModel}function rbe(e){let t=e.iterations;return t?t.filter(e=>e.type===`advisor_message`):[]}var Th,Eh=n((()=>{Po(),h(),Yr(),Th=`# Advisor Tool
|
|
412
|
+
`),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=rve(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=>{X(`[Sandbox Monitor] Log stream stderr: ${e.toString()}`)}),o.on(`error`,e=>{X(`[Sandbox Monitor] Failed to start log stream: ${e.message}`)}),o.on(`exit`,e=>{X(`[Sandbox Monitor] Log stream exited with code: ${e}`)}),()=>{X(`[Sandbox Monitor] Stopping log monitor`),o.kill(`SIGTERM`)}}var Mve,wm,Nve=n((()=>{Mve=r(Oc(),1),_p(),Op(),dm(),wm=`_${Math.random().toString(36).slice(2,11)}_SBX`})),Tm,Em=n((()=>{dm(),Tm=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=nve(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 Pve(){if(Pm)return;let e=()=>Om().catch(e=>{X(`Cleanup failed in registerCleanup ${e}`,{level:`error`})});process.once(`exit`,e),process.once(`SIGINT`,e),process.once(`SIGTERM`,e),Pm=!0}function Dm(e,t){let n=e.toLowerCase();if(t.startsWith(`*.`)){if(ju(xp(n)))return!1;let e=t.substring(2).toLowerCase();return n.endsWith(`.`+e)}return n===t.toLowerCase()}async function Fve(e,t,n){if(!km)return X(`No config available, denying network request`),!1;if(!Sp(t))return X(`Denying malformed host: ${JSON.stringify(t)}:${e}`,{level:`error`}),!1;let r=Tge(t)??t;for(let n of km.network.deniedDomains)if(Dm(r,n))return X(`Denied by config rule: ${t}:${e}`),!1;for(let n of km.network.allowedDomains)if(Dm(r,n))return X(`Allowed by config rule: ${t}:${e}`),!0;if(!n)return X(`No matching config rule, denying: ${t}:${e}`),!1;X(`No matching config rule, asking user: ${t}:${e}`);try{return await n({host:t,port:e})?(X(`User allowed: ${t}:${e}`),!0):(X(`User denied: ${t}:${e}`),!1)}catch(e){return X(`Error in permission callback: ${e}`,{level:`error`}),!1}}function Ive(e){if(!km?.network.mitmProxy)return;let{socketPath:t,domains:n}=km.network.mitmProxy;for(let r of n)if(Dm(e,r))return X(`Host ${e} matches MITM pattern ${r}`),t}async function Lve(e){return Am=kge({filter:(t,n)=>Fve(t,n,e),getMitmSocketPath:Ive,parentProxy:Im}),new Promise((e,t)=>{if(!Am){t(Error(`HTTP proxy server undefined before listen`));return}let n=Am;n.once(`error`,t),n.once(`listening`,()=>{let r=n.address();r&&typeof r==`object`?(n.unref(),X(`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 Rve(e){return jm=Lge({filter:(t,n)=>Fve(t,n,e),parentProxy:Im}),new Promise((e,t)=>{if(!jm){t(Error(`SOCKS proxy server undefined before listen`));return}jm.listen(0,`127.0.0.1`).then(t=>{jm?.unref(),e(t)}).catch(t)})}async function zve(e,t,n=!1){if(Nm){await Nm;return}km=e,Im=vge(e.network.parentProxy),Im&&X(`Parent proxy configured: http=${Cge(Im.httpUrl)} https=${Cge(Im.httpsUrl)}`);let r=Hve();if(r.errors.length>0)throw Error(`Sandbox dependencies not available: ${r.errors.join(`, `)}`);n&&tm()===`macos`&&(Fm=jve(Lm.addViolation.bind(Lm),km.ignoreViolations),X(`Started macOS sandbox log monitor`)),Pve(),Nm=(async()=>{try{let e;km.network.httpProxyPort===void 0?e=await Lve(t):(e=km.network.httpProxyPort,X(`Using external HTTP proxy on port ${e}`));let n;km.network.socksProxyPort===void 0?n=await Rve(t):(n=km.network.socksProxyPort,X(`Using external SOCKS proxy on port ${n}`));let r;tm()===`linux`&&(r=await vve(e,n));let i={httpProxyPort:e,socksProxyPort:n,linuxBridge:r};return Mm=i,X(`Network infrastructure initialized`),i}catch(e){throw Nm=void 0,Mm=void 0,Om().catch(e=>{X(`Cleanup failed in initializationPromise ${e}`,{level:`error`})}),e}})(),await Nm}function Bve(){let e=tm();return e===`linux`?X_e()!==`1`:e===`macos`}function Vve(){return km!==void 0}function Hve(e){if(!Bve())return{errors:[`Unsupported platform`],warnings:[]};let t=[],n=[],r=e??km?.ripgrep??{command:`rg`};if(Dp(r.command)===null&&t.push(`ripgrep (${r.command}) not found`),tm()===`linux`){let e=_ve(km?.seccomp);t.push(...e.errors),n.push(...e.warnings)}return{errors:t,warnings:n}}function Uve(){if(!km)return{denyOnly:[],allowWithinDeny:[]};let e=[];for(let t of km.filesystem.denyRead){let n=im(t);if(tm()===`linux`&&rm(n)){let n=lm(t);X(`[Sandbox] Expanded glob pattern "${t}" to ${n.length} paths on Linux`),e.push(...n)}else e.push(n)}let t=[];for(let e of km.filesystem.allowRead??[]){let n=im(e);if(tm()===`linux`&&rm(n)){let n=lm(e);X(`[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 Wve(){if(!km)return{allowOnly:sm(),denyWithinAllow:[]};let e=km.filesystem.allowWrite.map(e=>im(e)).filter(e=>tm()===`linux`&&rm(e)?(X(`Skipping glob pattern on Linux/WSL: ${e}`),!1):!0),t=km.filesystem.denyWrite.map(e=>im(e)).filter(e=>tm()===`linux`&&rm(e)?(X(`Skipping glob pattern on Linux/WSL: ${e}`),!1):!0);return{allowOnly:[...sm(),...e],denyWithinAllow:t}}function Gve(){if(!km)return{};let e=km.network.allowedDomains,t=km.network.deniedDomains;return{...e.length>0&&{allowedHosts:e},...t.length>0&&{deniedHosts:t}}}function Kve(){return km?.network?.allowUnixSockets}function qve(){return km?.network?.allowAllUnixSockets}function Jve(){return km?.network?.allowLocalBinding}function Yve(){return km?.ignoreViolations}function Xve(){return km?.enableWeakerNestedSandbox}function Zve(){return km?.enableWeakerNetworkIsolation}function Qve(){return km?.ripgrep??{command:`rg`}}function $ve(){return km?.mandatoryDenySearchDepth??3}function eye(){return km?.filesystem?.allowGitConfig??!1}function tye(){return km?.seccomp}function nye(){return Mm?.httpProxyPort}function rye(){return Mm?.socksProxyPort}function iye(){return Mm?.linuxBridge?.httpSocketPath}function aye(){return Mm?.linuxBridge?.socksSocketPath}async function oye(){if(!km)return!1;if(Nm)try{return await Nm,!0}catch{return!1}return Mm!==void 0}async function sye(e,t,n,r){let i=tm(),a=e=>e.map(e=>im(e)).filter(e=>tm()===`linux`&&rm(e)?(X(`[Sandbox] Skipping glob write pattern on Linux: ${e}`),!1):!0),o=a(n?.filesystem?.allowWrite??km?.filesystem.allowWrite??[]),s={allowOnly:[...sm(),...o],denyWithinAllow:a(n?.filesystem?.denyWrite??km?.filesystem.denyWrite??[])},c=n?.filesystem?.denyRead??km?.filesystem.denyRead??[],l=[];for(let e of c){let t=im(e);tm()===`linux`&&rm(t)?l.push(...lm(e)):l.push(t)}let u=n?.filesystem?.allowRead??km?.filesystem.allowRead??[],d=[];for(let e of u){let t=im(e);tm()===`linux`&&rm(t)?d.push(...lm(e)):d.push(t)}let f={denyOnly:l,allowWithinDeny:d},p=n?.network?.allowedDomains!==void 0||km?.network?.allowedDomains!==void 0,m=p,h=p;h&&await oye();let g=n?.allowPty??km?.allowPty;switch(i){case`macos`:return Ave({command:e,needsNetworkRestriction:m,httpProxyPort:h?nye():void 0,socksProxyPort:h?rye():void 0,readConfig:f,writeConfig:s,allowUnixSockets:Kve(),allowAllUnixSockets:qve(),allowLocalBinding:Jve(),ignoreViolations:Yve(),allowPty:g,allowGitConfig:eye(),enableWeakerNetworkIsolation:Zve(),binShell:t});case`linux`:return xve({command:e,needsNetworkRestriction:m,httpSocketPath:h?iye():void 0,socksSocketPath:h?aye():void 0,httpProxyPort:h?Mm?.httpProxyPort:void 0,socksProxyPort:h?Mm?.socksProxyPort:void 0,readConfig:f,writeConfig:s,enableWeakerNestedSandbox:Xve(),allowAllUnixSockets:qve(),binShell:t,ripgrepConfig:Qve(),mandatoryDenySearchDepth:$ve(),allowGitConfig:eye(),seccompConfig:tye(),abortSignal:r});default:throw Error(`Sandbox configuration is not supported on platform: ${i}`)}}function cye(){return km}function lye(e){km=Mde(e),Im=vge(e.network.parentProxy),X(`Sandbox configuration updated`)}function uye(){gve()}async function Om(){if(uye(),Fm&&(Fm(),Fm=void 0),Mm?.linuxBridge){let{httpSocketPath:e,socksSocketPath:t,httpBridgeProcess:n,socksBridgeProcess:r}=Mm.linuxBridge,i=[];if(n.pid&&!n.killed)try{process.kill(n.pid,`SIGTERM`),X(`Sent SIGTERM to HTTP bridge process`),i.push(new Promise(e=>{n.once(`exit`,()=>{X(`HTTP bridge process exited`),e()}),setTimeout(()=>{if(!n.killed){X(`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`&&X(`Error killing HTTP bridge: ${e}`,{level:`error`})}if(r.pid&&!r.killed)try{process.kill(r.pid,`SIGTERM`),X(`Sent SIGTERM to SOCKS bridge process`),i.push(new Promise(e=>{r.once(`exit`,()=>{X(`SOCKS bridge process exited`),e()}),setTimeout(()=>{if(!r.killed){X(`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`&&X(`Error killing SOCKS bridge: ${e}`,{level:`error`})}if(await Promise.all(i),e)try{Ul.rmSync(e,{force:!0}),X(`Cleaned up HTTP socket`)}catch(e){X(`HTTP socket cleanup error: ${e}`,{level:`error`})}if(t)try{Ul.rmSync(t,{force:!0}),X(`Cleaned up SOCKS socket`)}catch(e){X(`SOCKS socket cleanup error: ${e}`,{level:`error`})}}let e=[];if(Am){let t=Am,n=new Promise(e=>{t.close(t=>{t&&t.message!==`Server is not running.`&&X(`Error closing HTTP proxy server: ${t.message}`,{level:`error`}),e()})});e.push(n)}if(jm){let t=jm.close().catch(e=>{X(`Error closing SOCKS proxy server: ${e.message}`,{level:`error`})});e.push(t)}await Promise.all(e),Am=void 0,jm=void 0,Mm=void 0,Nm=void 0,Im=void 0}function dye(){return Lm}function fye(e,t){if(!km)return t;let n=Lm.getViolationsForCommand(e);if(n.length===0)return t;let r=t;r+=Zl+`<sandbox_violations>`+Zl;for(let e of n)r+=e.line+Zl;return r+=`</sandbox_violations>`,r}function pye(){if(tm()!==`linux`||!km)return[];let e=[],t=[...km.filesystem.allowWrite,...km.filesystem.denyWrite];for(let n of t)rm(im(n))&&e.push(n);return e}var km,Am,jm,Mm,Nm,Pm,Fm,Im,Lm,Rm,mye=n((()=>{jge(),Rge(),_p(),Op(),em(),nm(),Sve(),Nve(),dm(),Em(),wp(),Pm=!1,Lm=new Tm,Rm={initialize:zve,isSupportedPlatform:Bve,isSandboxingEnabled:Vve,checkDependencies:Hve,getFsReadConfig:Uve,getFsWriteConfig:Wve,getNetworkRestrictionConfig:Gve,getAllowUnixSockets:Kve,getAllowLocalBinding:Jve,getIgnoreViolations:Yve,getEnableWeakerNestedSandbox:Xve,getProxyPort:nye,getSocksProxyPort:rye,getLinuxHttpSocketPath:iye,getLinuxSocksSocketPath:aye,waitForNetworkInitialization:oye,wrapWithSandbox:sye,cleanupAfterCommand:uye,reset:Om,getSandboxViolationStore:dye,annotateStderrWithSandboxFailures:fye,getLinuxGlobPatternWarnings:pye,getConfig:cye,updateConfig:lye}})),zm,Bm,hye,gye,_ye,vye,yye,bye,xye,Sye=n((()=>{N(),zm=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.`}),Bm=j().min(1,`Path cannot be empty`),hye=se({socketPath:j().min(1).describe(`Unix socket path to the MITM proxy`),domains:M(zm).min(1).describe(`Domains to route through the MITM proxy (e.g., ["api.example.com", "*.internal.org"])`)}),gye=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.`)}),_ye=se({allowedDomains:M(zm).describe(`List of allowed domains (e.g., ["github.com", "*.npmjs.org"])`),deniedDomains:M(zm).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:hye.optional().describe(`Optional MITM proxy configuration. Routes matching domains through an upstream proxy via Unix socket while SRT still handles allow/deny filtering.`),parentProxy:gye.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.`)}),vye=se({denyRead:M(Bm).describe(`Paths denied for reading`),allowRead:M(Bm).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(Bm).describe(`Paths allowed for writing`),denyWrite:M(Bm).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.`)}),yye=le(j(),M(j())).describe(`Map of command patterns to filesystem paths to ignore violations for. Use "*" to match all commands`),bye=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])`)}),xye=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:_ye.describe(`Network restrictions configuration`),filesystem:vye.describe(`Filesystem restrictions configuration`),ignoreViolations:yye.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:bye.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:xye.optional().describe(`Custom seccomp binary paths (Linux only).`)})})),Cye=n((()=>{mye(),Em(),Sye(),dm(),nm()}));async function wye(){if(xt()||Ym||Xm)return;Ym=!0,jye(),qn(Tye);let{dirs:e,settingsFiles:t,dropInDir:n}=await Eye();Xm||e.length!==0&&(U(`Watching for changes in setting files ${[...t].join(`, `)}...${n?` and drop-in directory ${n}`:``}`),Km=Uf.watch(e,{persistent:!0,ignoreInitial:!0,depth:0,awaitWriteFinish:{stabilityThreshold:$m?.stabilityThreshold??Pye,pollInterval:$m?.pollInterval??Fye},ignored:(e,r)=>{if(r&&!r.isFile()&&!r.isDirectory()||e.split(Cl.sep).some(e=>e===`.git`))return!0;if(!r||r.isDirectory())return!1;let i=Cl.normalize(e);return!(t.has(i)||n&&i.startsWith(n+Cl.sep)&&i.endsWith(`.json`))},ignorePermissionErrors:!0,usePolling:!1,atomic:!0}),Km.on(`change`,Oye),Km.on(`unlink`,Aye),Km.on(`add`,kye))}function Tye(){Xm=!0,qm&&(clearInterval(qm),qm=null);for(let e of Zm.values())clearTimeout(e);Zm.clear(),Jm=null,Ane(),Qm.clear();let e=Km;return Km=null,e?e.close():Promise.resolve()}async function Eye(){let e=new Map,t=new Set;for(let n of ai){if(n===`flagSettings`)continue;let r=li(n);if(!r)continue;let i=Cl.dirname(r);e.has(i)||e.set(i,new Set),e.get(i).add(r);try{(await mu(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=Ir();try{(await mu(i)).isDirectory()&&(t.add(i),r=i)}catch{}return{dirs:[...t],settingsFiles:n,dropInDir:r}}function Dye(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 Oye(e){let t=Vm(e);if(!t)return;let n=Zm.get(e);n&&(clearTimeout(n),Zm.delete(e),U(`Cancelled pending deletion of ${e} — file was recreated`)),!are(e,Um)&&(U(`Detected change to ${e}`),l7(Dye(t),e).then(n=>{if(r7(n)){U(`ConfigChange hook blocked change to ${e}`);return}Hm(t)}))}function kye(e){if(!Vm(e))return;let t=Zm.get(e);t&&(clearTimeout(t),Zm.delete(e),U(`Cancelled pending deletion of ${e} — file was re-added`)),Oye(e)}function Aye(e){let t=Vm(e);if(!t||(U(`Detected deletion of ${e}`),Zm.has(e)))return;let n=setTimeout((e,t)=>{Zm.delete(e),l7(Dye(t),e).then(n=>{if(r7(n)){U(`ConfigChange hook blocked deletion of ${e}`);return}Hm(t)})},$m?.deletionGrace??Gm,e,t);Zm.set(e,n)}function Vm(e){let t=Cl.normalize(e),n=Ir();return t.startsWith(n+Cl.sep)?`policySettings`:ai.find(e=>li(e)===t)}function jye(){let e=Bre(),t=Fne();Jm=V({mdm:e.settings,hkcu:t.settings}),qm=setInterval(()=>{Xm||(async()=>{try{let{mdm:e,hkcu:t}=await Bne();if(Xm)return;let n=V({mdm:e.settings,hkcu:t.settings});n!==Jm&&(Jm=n,Lne(e,t),U(`Detected MDM settings change via poll`),Hm(`policySettings`))}catch(e){U(`MDM poll error: ${H(e)}`)}})()},$m?.mdmPollInterval??Wm),qm.unref()}function Hm(e){qt(),Qm.emit(e)}function Mye(e){U(`Programmatic settings change notification for ${e}`),Hm(e)}function Nye(e){qm&&(clearInterval(qm),qm=null);for(let e of Zm.values())clearTimeout(e);Zm.clear(),Jm=null,Ym=!1,Xm=!1,$m=e??null;let t=Km;return Km=null,t?t.close():Promise.resolve()}var Pye,Fye,Um,Wm,Gm,Km,qm,Jm,Ym,Xm,Zm,Qm,$m,Iye,eh,th=n((()=>{Wf(),Gt(),Xn(),W(),Mn(),g7(),mn(),Zn(),ti(),Fre(),wr(),Zne(),Yr(),Qt(),Pye=1e3,Fye=500,Um=5e3,Wm=1800*1e3,Gm=1700,Km=null,qm=null,Jm=null,Ym=!1,Xm=!1,Zm=new Map,Qm=an(),$m=null,Iye=Qm.subscribe,eh={initialize:wye,dispose:Tye,subscribe:Iye,notifyChange:Mye,resetForTesting:Nye}}));function nh(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 Lye(e){return e.match(/^(.+):\*$/)?.[1]??null}function rh(e,t){return e.startsWith(`//`)?e.slice(1):e.startsWith(`/`)&&!e.startsWith(`//`)?Ml(ei(t),e.slice(1)):e}function ih(e,t){return e.startsWith(`//`)?e.slice(1):oi(e,ei(t))}function ah(){return Ur(`policySettings`)?.sandbox?.network?.allowManagedDomainsOnly===!0}function Rye(){return Ur(`policySettings`)?.sandbox?.filesystem?.allowManagedReadPathsOnly===!0}function oh(e){let t=e.permissions||{},n=[],r=[];if(ah()){let e=Ur(`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=nh(e);t.ruleContent?.startsWith(`domain:`)&&r.push(t.ruleContent.substring(7))}let i=[`.`,F8()],a=[],o=[],s=[],c=ai.map(e=>li(e)).filter(e=>e!==void 0);a.push(...c),a.push(Ir());let l=It(),u=Zt();l!==u&&(a.push(Ml(l,`.workmate`,`settings.json`)),a.push(Ml(l,`.workmate`,`settings.local.json`))),a.push(Ml(u,`.workmate`,`skills`)),l!==u&&a.push(Ml(l,`.workmate`,`skills`)),ph.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=Ml(e,t);try{nle(n),a.push(n)}catch{ph.push(n)}}fh&&fh!==l&&i.push(fh);let f=new Set([...e.permissions?.additionalDirectories||[],...$t()]);i.push(...f);for(let e of ai){let t=Ur(e);if(t?.permissions){for(let n of t.permissions.allow||[]){let t=nh(n);t.toolName===`Edit`&&t.ruleContent&&i.push(rh(t.ruleContent,e))}for(let n of t.permissions.deny||[]){let t=nh(n);t.toolName===`Edit`&&t.ruleContent&&a.push(rh(t.ruleContent,e)),t.toolName===`Read`&&t.ruleContent&&o.push(rh(t.ruleContent,e))}}let n=t?.sandbox?.filesystem;if(n){for(let t of n.allowWrite||[])i.push(ih(t,e));for(let t of n.denyWrite||[])a.push(ih(t,e));for(let t of n.denyRead||[])o.push(ih(t,e));if(!Rye()||e===`policySettings`)for(let t of n.allowRead||[])s.push(ih(t,e))}}let{rgPath:p,rgArgs:m,argv0:h}=Mc(),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 zye(){for(let e of ph)try{tle(e,{recursive:!0}),U(`[Sandbox] scrubbed planted bare-repo file: ${e}`)}catch{}}async function Bye(e){let t=Y(e,`.git`);try{let n=(await lu(t,{encoding:`utf8`})).match(/^gitdir:\s*(.+)$/m);if(!n?.[1])return null;let r=Ml(e,n[1].trim()),i=`${Nl}.git${Nl}worktrees${Nl}`,a=r.lastIndexOf(i);return a>0?r.substring(0,a):null}catch{return null}}function sh(){try{return qr()?.sandbox?.enabled??!1}catch(e){return U(`Failed to get settings for sandbox check: ${e}`),!1}}function Vye(){return qr()?.sandbox?.autoAllowBashIfSandboxed??!0}function Hye(){return qr()?.sandbox?.allowUnsandboxedCommands??!0}function Uye(){let e=qr();return sh()&&(e?.sandbox?.failIfUnavailable??!1)}function ch(){try{let e=ii()?.sandbox?.enabledPlatforms;if(e===void 0)return!0;if(e.length===0)return!1;let t=_a();return e.includes(t)}catch(e){return U(`Failed to check enabledPlatforms: ${e}`),!0}}function lh(){return!hh()||mh().errors.length>0||!ch()?!1:sh()}function Wye(){if(!sh())return;if(!hh()){let e=_a();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(!ch())return`sandbox.enabled is set but ${_a()} is not in sandbox.enabledPlatforms`;let e=mh();if(e.errors.length>0){let t=_a()===`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 Gye(){let e=_a();if(e!==`linux`&&e!==`wsl`)return[];try{let e=qr();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=nh(e);(t.toolName===`Edit`||t.toolName===`Read`)&&t.ruleContent&&r(t.ruleContent)&&n.push(e)}return n}catch(e){return U(`Failed to get Linux glob pattern warnings: ${e}`),[]}}function Kye(){for(let e of[`flagSettings`,`policySettings`]){let t=Ur(e);if(t?.sandbox?.enabled!==void 0||t?.sandbox?.autoAllowBashIfSandboxed!==void 0||t?.sandbox?.allowUnsandboxedCommands!==void 0)return!0}return!1}async function qye(e){_i(`localSettings`,{sandbox:{...Ur(`localSettings`)?.sandbox,...e.enabled!==void 0&&{enabled:e.enabled},...e.autoAllowBashIfSandboxed!==void 0&&{autoAllowBashIfSandboxed:e.autoAllowBashIfSandboxed},...e.allowUnsandboxedCommands!==void 0&&{allowUnsandboxedCommands:e.allowUnsandboxedCommands}}})}function Jye(){return qr()?.sandbox?.excludedCommands??[]}async function Yye(e,t,n,r){if(lh())if(uh)await uh;else throw Error(`Sandbox failed to initialize. `);return Rm.wrapWithSandbox(e,t,n,r)}async function Xye(e){if(uh)return uh;if(!lh())return;let t=e?async t=>ah()?(U(`[sandbox] Blocked network request to ${t.host} (allowManagedDomainsOnly)`),!1):e(t):void 0;return uh=(async()=>{try{fh===void 0&&(fh=await Bye(It()));let e=oh(qr());await Rm.initialize(e,t),dh=eh.subscribe(()=>{let e=oh(qr());Rm.updateConfig(e),U(`Sandbox configuration updated from settings change`)})}catch(e){uh=void 0,U(`Failed to initialize sandbox: ${H(e)}`)}})(),uh}function Zye(){if(!lh())return;let e=oh(qr());Rm.updateConfig(e)}async function Qye(){return dh?.(),dh=void 0,fh=void 0,ph.length=0,mh.cache.clear?.(),hh.cache.clear?.(),uh=void 0,Rm.reset()}function $ye(e,t){let n=Ur(`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===Is);t?.ruleContent&&(i=Lye(t.ruleContent)||t.ruleContent)}}return r.includes(i)||_i(`localSettings`,{sandbox:{...n?.sandbox,excludedCommands:[...r,i]}}),i}var uh,dh,fh,ph,mh,hh,gh,_h=n((()=>{Cye(),em(),Gt(),W(),Wr(),va(),th(),ti(),wr(),Yr(),Ts(),Rs(),Bs(),Mn(),L8(),jc(),ph=[],mh=u(()=>{let{rgPath:e,rgArgs:t}=Mc();return Rm.checkDependencies({command:e,args:t})}),hh=u(()=>Rm.isSupportedPlatform()),gh={initialize:Xye,isSandboxingEnabled:lh,isSandboxEnabledInSettings:sh,isPlatformInEnabledList:ch,getSandboxUnavailableReason:Wye,isAutoAllowBashIfSandboxedEnabled:Vye,areUnsandboxedCommandsAllowed:Hye,isSandboxRequired:Uye,areSandboxSettingsLockedByPolicy:Kye,setSandboxSettings:qye,getExcludedCommands:Jye,wrapWithSandbox:Yye,refreshConfig:Zye,reset:Qye,checkDependencies:mh,getFsReadConfig:Rm.getFsReadConfig,getFsWriteConfig:Rm.getFsWriteConfig,getNetworkRestrictionConfig:Rm.getNetworkRestrictionConfig,getIgnoreViolations:Rm.getIgnoreViolations,getLinuxGlobPatternWarnings:Gye,isSupportedPlatform:hh,getAllowUnixSockets:Rm.getAllowUnixSockets,getAllowLocalBinding:Rm.getAllowLocalBinding,getEnableWeakerNestedSandbox:Rm.getEnableWeakerNestedSandbox,getProxyPort:Rm.getProxyPort,getSocksProxyPort:Rm.getSocksProxyPort,getLinuxHttpSocketPath:Rm.getLinuxHttpSocketPath,getLinuxSocksSocketPath:Rm.getLinuxSocksSocketPath,waitForNetworkInitialization:Rm.waitForNetworkInitialization,getSandboxViolationStore:Rm.getSandboxViolationStore,annotateStderrWithSandboxFailures:Rm.annotateStderrWithSandboxFailures,cleanupAfterCommand:()=>{Rm.cleanupAfterCommand(),zye()}}})),vh,ebe=n((()=>{ne(),_h(),vh={name:`sandbox`,get description(){let e=gh.isSandboxingEnabled(),t=gh.isAutoAllowBashIfSandboxedEnabled(),n=gh.areUnsandboxedCommandsAllowed(),r=gh.areSandboxSettingsLockedByPolicy(),i=gh.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!gh.isSupportedPlatform()||!gh.isPlatformInEnabledList()},immediate:!0,type:`local-jsx`,load:()=>import(`./sandbox-toggle-DWCrG9zV.js`)}}));function yh(e){return e.type===`advisor_tool_result`||e.type===`server_tool_use`&&e.name===`advisor`}function bh(){return{}}function xh(){return m(process.env.CLAUDE_CODE_DISABLE_ADVISOR_TOOL)||!wo()?!1:bh().enabled??!1}function Sh(){return xh()&&(bh().canUserConfigure??!1)}function tbe(){let e=bh();return xh()&&!Sh()&&e.baseModel&&e.advisorModel?{baseModel:e.baseModel,advisorModel:e.advisorModel}:void 0}function Ch(e){let t=e.toLowerCase();return t.includes(`opus-4-7`)||t.includes(`opus-4-6`)||t.includes(`sonnet-4-6`)}function wh(e){let t=e.toLowerCase();return t.includes(`opus-4-7`)||t.includes(`opus-4-6`)||t.includes(`sonnet-4-6`)}function nbe(){if(xh())return ii().advisorModel}function rbe(e){let t=e.iterations;return t?t.filter(e=>e.type===`advisor_message`):[]}var Th,Eh=n((()=>{Po(),h(),Yr(),Th=`# Advisor Tool
|
|
413
413
|
|
|
414
414
|
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.
|
|
415
415
|
|
|
@@ -665,8 +665,8 @@ Parameters:
|
|
|
665
665
|
if (${n}.issues.length) payload.issues = payload.issues.concat(${n}.issues.map(iss => ({
|
|
666
666
|
...iss,
|
|
667
667
|
path: iss.path ? [${qE(e)}, ...iss.path] : [${qE(e)}]
|
|
668
|
-
})));`),t.write(`newResult[${qE(e)}] = ${n}.value`)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},i,a=JE,o=!BE.jitless,s=o&&oD.value,c=t.catchall,l;e._zod.parse=(u,d)=>{l??(l=n.value);let f=u.value;if(!a(f))return u.issues.push({expected:`object`,code:`invalid_type`,input:f,inst:e}),u;let p=[];if(o&&s&&d?.async===!1&&d.jitless!==!0)i||(i=r(t.shape)),u=i(u,d);else{u.value={};let e=l.shape;for(let t of l.keys){let n=e[t],r=n._zod.run({value:f[t],issues:[]},d),i=n._zod.optin===`optional`&&n._zod.optout===`optional`;r instanceof Promise?p.push(r.then(e=>i?xO(e,u,t,f):bO(e,u,t))):i?xO(r,u,t,f):bO(r,u,t)}}if(!c)return p.length?Promise.all(p).then(()=>u):u;let m=[],h=l.keySet,g=c._zod,_=g.def.type;for(let e of Object.keys(f)){if(h.has(e))continue;if(_===`never`){m.push(e);continue}let t=g.run({value:f[e],issues:[]},d);t instanceof Promise?p.push(t.then(t=>bO(t,u,e))):bO(t,u,e)}return m.length&&u.issues.push({code:`unrecognized_keys`,keys:m,input:f,inst:e}),p.length?Promise.all(p).then(()=>u):u}}),lk=Q(`$ZodUnion`,(e,t)=>{AO.init(e,t),GE(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),GE(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),GE(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),GE(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>WE(e.source)).join(`|`)})$`)}}),e._zod.parse=(n,r)=>{let i=!1,a=[];for(let e of t.options){let t=e._zod.run({value:n.value,issues:[]},r);if(t instanceof Promise)a.push(t),i=!0;else{if(t.issues.length===0)return t;a.push(t)}}return i?Promise.all(a).then(t=>SO(t,n,e,r)):SO(a,n,e,r)}}),uk=Q(`$ZodIntersection`,(e,t)=>{AO.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>wO(e,t,n)):wO(e,i,a)}}),dk=Q(`$ZodRecord`,(e,t)=>{AO.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!YE(i))return n.issues.push({expected:`record`,code:`invalid_type`,input:i,inst:e}),n;let a=[];if(t.keyType._zod.values){let o=t.keyType._zod.values;n.value={};for(let e of o)if(typeof e==`string`||typeof e==`number`||typeof e==`symbol`){let o=t.valueType._zod.run({value:i[e],issues:[]},r);o instanceof Promise?a.push(o.then(t=>{t.issues.length&&n.issues.push(...eD(e,t.issues)),n.value[e]=t.value})):(o.issues.length&&n.issues.push(...eD(e,o.issues)),n.value[e]=o.value)}let s;for(let e in i)o.has(e)||(s=s??[],s.push(e));s&&s.length>0&&n.issues.push({code:`unrecognized_keys`,input:i,inst:e,keys:s})}else{n.value={};for(let o of Reflect.ownKeys(i)){if(o===`__proto__`)continue;let s=t.keyType._zod.run({value:o,issues:[]},r);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){n.issues.push({origin:`record`,code:`invalid_key`,issues:s.issues.map(e=>nD(e,r,RE())),input:o,path:[o],inst:e}),n.value[s.value]=s.value;continue}let c=t.valueType._zod.run({value:i[o],issues:[]},r);c instanceof Promise?a.push(c.then(e=>{e.issues.length&&n.issues.push(...eD(o,e.issues)),n.value[s.value]=e.value})):(c.issues.length&&n.issues.push(...eD(o,c.issues)),n.value[s.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),fk=Q(`$ZodEnum`,(e,t)=>{AO.init(e,t);let n=kje(t.entries);e._zod.values=new Set(n),e._zod.pattern=RegExp(`^(${n.filter(e=>sD.has(typeof e)).map(e=>typeof e==`string`?XE(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,r)=>{let i=t.value;return e._zod.values.has(i)||t.issues.push({code:`invalid_value`,values:n,input:i,inst:e}),t}}),pk=Q(`$ZodLiteral`,(e,t)=>{AO.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?XE(e):e?e.toString():String(e)).join(`|`)})$`),e._zod.parse=(n,r)=>{let i=n.value;return e._zod.values.has(i)||n.issues.push({code:`invalid_value`,values:t.values,input:i,inst:e}),n}}),mk=Q(`$ZodTransform`,(e,t)=>{AO.init(e,t),e._zod.parse=(e,n)=>{let r=t.transform(e.value,e);if(n.async)return(r instanceof Promise?r:Promise.resolve(r)).then(t=>(e.value=t,e));if(r instanceof Promise)throw new zE;return e.value=r,e}}),hk=Q(`$ZodOptional`,(e,t)=>{AO.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,GE(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),GE(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${WE(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>t.innerType._zod.optin===`optional`?t.innerType._zod.run(e,n):e.value===void 0?e:t.innerType._zod.run(e,n)}),gk=Q(`$ZodNullable`,(e,t)=>{AO.init(e,t),GE(e._zod,`optin`,()=>t.innerType._zod.optin),GE(e._zod,`optout`,()=>t.innerType._zod.optout),GE(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${WE(e.source)}|null)$`):void 0}),GE(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),_k=Q(`$ZodDefault`,(e,t)=>{AO.init(e,t),e._zod.optin=`optional`,GE(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>TO(e,t)):TO(r,t)}}),vk=Q(`$ZodPrefault`,(e,t)=>{AO.init(e,t),e._zod.optin=`optional`,GE(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),yk=Q(`$ZodNonOptional`,(e,t)=>{AO.init(e,t),GE(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>EO(t,e)):EO(i,e)}}),bk=Q(`$ZodCatch`,(e,t)=>{AO.init(e,t),e._zod.optin=`optional`,GE(e._zod,`optout`,()=>t.innerType._zod.optout),GE(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>nD(e,n,RE()))},input:e.value}),e.issues=[]),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>nD(e,n,RE()))},input:e.value}),e.issues=[]),e)}}),xk=Q(`$ZodPipe`,(e,t)=>{AO.init(e,t),GE(e._zod,`values`,()=>t.in._zod.values),GE(e._zod,`optin`,()=>t.in._zod.optin),GE(e._zod,`optout`,()=>t.out._zod.optout),e._zod.parse=(e,n)=>{let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>DO(e,t,n)):DO(r,t,n)}}),Sk=Q(`$ZodReadonly`,(e,t)=>{AO.init(e,t),GE(e._zod,`propValues`,()=>t.innerType._zod.propValues),GE(e._zod,`values`,()=>t.innerType._zod.values),GE(e._zod,`optin`,()=>t.innerType._zod.optin),GE(e._zod,`optout`,()=>t.innerType._zod.optout),e._zod.parse=(e,n)=>{let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(OO):OO(r)}}),Ck=Q(`$ZodCustom`,(e,t)=>{XD.init(e,t),AO.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>kO(t,n,r,e));kO(i,n,r,e)}})}));function qje(){return new wk}var wk,Tk,Jje=n((()=>{wk=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){let n=t[0];if(this._map.set(e,n),n&&typeof n==`object`&&`id`in n){if(this._idmap.has(n.id))throw Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}},Tk=qje()}));function Yje(e,t){return new e({type:`string`,...QE(t)})}function Xje(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...QE(t)})}function Ek(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...QE(t)})}function Zje(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...QE(t)})}function Qje(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...QE(t)})}function $je(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...QE(t)})}function eMe(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...QE(t)})}function tMe(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...QE(t)})}function nMe(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...QE(t)})}function rMe(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...QE(t)})}function iMe(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...QE(t)})}function aMe(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...QE(t)})}function oMe(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...QE(t)})}function sMe(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...QE(t)})}function cMe(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...QE(t)})}function lMe(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...QE(t)})}function uMe(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...QE(t)})}function dMe(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...QE(t)})}function fMe(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...QE(t)})}function pMe(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...QE(t)})}function mMe(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...QE(t)})}function hMe(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...QE(t)})}function gMe(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...QE(t)})}function _Me(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...QE(t)})}function vMe(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...QE(t)})}function yMe(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...QE(t)})}function bMe(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...QE(t)})}function xMe(e,t){return new e({type:`number`,checks:[],...QE(t)})}function SMe(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...QE(t)})}function CMe(e,t){return new e({type:`boolean`,...QE(t)})}function wMe(e){return new e({type:`unknown`})}function TMe(e,t){return new e({type:`never`,...QE(t)})}function Dk(e,t){return new QD({check:`less_than`,...QE(t),value:e,inclusive:!1})}function Ok(e,t){return new QD({check:`less_than`,...QE(t),value:e,inclusive:!0})}function kk(e,t){return new $D({check:`greater_than`,...QE(t),value:e,inclusive:!1})}function Ak(e,t){return new $D({check:`greater_than`,...QE(t),value:e,inclusive:!0})}function jk(e,t){return new eO({check:`multiple_of`,...QE(t),value:e})}function Mk(e,t){return new nO({check:`max_length`,...QE(t),maximum:e})}function Nk(e,t){return new rO({check:`min_length`,...QE(t),minimum:e})}function Pk(e,t){return new iO({check:`length_equals`,...QE(t),length:e})}function EMe(e,t){return new oO({check:`string_format`,format:`regex`,...QE(t),pattern:e})}function DMe(e){return new sO({check:`string_format`,format:`lowercase`,...QE(e)})}function OMe(e){return new cO({check:`string_format`,format:`uppercase`,...QE(e)})}function kMe(e,t){return new lO({check:`string_format`,format:`includes`,...QE(t),includes:e})}function AMe(e,t){return new uO({check:`string_format`,format:`starts_with`,...QE(t),prefix:e})}function jMe(e,t){return new dO({check:`string_format`,format:`ends_with`,...QE(t),suffix:e})}function Fk(e){return new fO({check:`overwrite`,tx:e})}function MMe(e){return Fk(t=>t.normalize(e))}function NMe(){return Fk(e=>e.trim())}function PMe(){return Fk(e=>e.toLowerCase())}function FMe(){return Fk(e=>e.toUpperCase())}function IMe(e,t,n){return new e({type:`array`,element:t,...QE(n)})}function LMe(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...QE(n)})}var RMe=n((()=>{pO(),lD()})),zMe=n((()=>{})),BMe=n((()=>{})),Ik=n((()=>{VE(),bD(),pD(),Kje(),pO(),_O(),lD(),YD(),Jje(),hO(),zMe(),RMe(),BMe()})),Lk=n((()=>{Ik()}));function VMe(e){return _Me(Rk,e)}function HMe(e){return vMe(zk,e)}function UMe(e){return yMe(Bk,e)}function WMe(e){return bMe(Vk,e)}var Rk,zk,Bk,Vk,Hk=n((()=>{Ik(),tj(),Rk=Q(`ZodISODateTime`,(e,t)=>{WO.init(e,t),pA.init(e,t)}),zk=Q(`ZodISODate`,(e,t)=>{GO.init(e,t),pA.init(e,t)}),Bk=Q(`ZodISOTime`,(e,t)=>{KO.init(e,t),pA.init(e,t)}),Vk=Q(`ZodISODuration`,(e,t)=>{qO.init(e,t),pA.init(e,t)})})),Uk,Wk,Gk=n((()=>{Ik(),Uk=(e,t)=>{dD.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>Bje(e,t)},flatten:{value:t=>zje(e,t)},addIssue:{value:t=>e.issues.push(t)},addIssues:{value:t=>e.issues.push(...t)},isEmpty:{get(){return e.issues.length===0}}})},Q(`ZodError`,Uk),Wk=Q(`ZodError`,Uk,{Parent:Error})})),Kk,qk,Jk,Yk,Xk=n((()=>{Ik(),Gk(),Kk=mD(Wk),qk=hD(Wk),Jk=gD(Wk),Yk=vD(Wk)}));function Zk(e){return Yje(fA,e)}function GMe(e){return xMe(NA,e)}function Qk(e){return SMe(PA,e)}function $k(e){return CMe(FA,e)}function eA(){return wMe(IA)}function KMe(e){return TMe(LA,e)}function tA(e,t){return IMe(RA,e,t)}function nA(e,t){let n={type:`object`,get shape(){return KE(this,`shape`,{...e}),this.shape},...QE(t)};return new zA(n)}function rA(e,t){return new BA({type:`union`,options:e,...QE(t)})}function qMe(e,t){return new VA({type:`intersection`,left:e,right:t})}function iA(e,t,n){return new HA({type:`record`,keyType:e,valueType:t,...QE(n)})}function aA(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new UA({type:`enum`,entries:n,...QE(t)})}function oA(e,t){return new WA({type:`literal`,values:Array.isArray(e)?e:[e],...QE(t)})}function JMe(e){return new GA({type:`transform`,transform:e})}function sA(e){return new KA({type:`optional`,innerType:e})}function cA(e){return new qA({type:`nullable`,innerType:e})}function YMe(e,t){return new JA({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():t}})}function XMe(e,t){return new YA({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():t}})}function ZMe(e,t){return new XA({type:`nonoptional`,innerType:e,...QE(t)})}function QMe(e,t){return new ZA({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}function lA(e,t){return new QA({type:`pipe`,in:e,out:t})}function $Me(e){return new $A({type:`readonly`,innerType:e})}function eNe(e){let t=new XD({check:`custom`});return t._zod.check=e,t}function tNe(e,t={}){return LMe(ej,e,t)}function nNe(e){let t=eNe(n=>(n.addIssue=e=>{if(typeof e==`string`)n.issues.push(iD(e,n.value,t._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??(r.code=`custom`),r.input??(r.input=n.value),r.inst??(r.inst=t),r.continue??(r.continue=!t._zod.def.abort),n.issues.push(iD(r))}},e(n.value,n)));return t}var uA,dA,fA,pA,mA,hA,gA,_A,vA,yA,bA,xA,SA,CA,wA,TA,EA,DA,OA,kA,AA,jA,MA,NA,PA,FA,IA,LA,RA,zA,BA,VA,HA,UA,WA,GA,KA,qA,JA,YA,XA,ZA,QA,$A,ej,tj=n((()=>{Ik(),Lk(),Hk(),Xk(),uA=Q(`ZodType`,(e,t)=>(AO.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),e.clone=(t,n)=>ZE(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.parse=(t,n)=>Kk(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Jk(e,t,n),e.parseAsync=async(t,n)=>qk(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Yk(e,t,n),e.spa=e.safeParseAsync,e.refine=(t,n)=>e.check(tNe(t,n)),e.superRefine=t=>e.check(nNe(t)),e.overwrite=t=>e.check(Fk(t)),e.optional=()=>sA(e),e.nullable=()=>cA(e),e.nullish=()=>sA(cA(e)),e.nonoptional=t=>ZMe(e,t),e.array=()=>tA(e),e.or=t=>rA([e,t]),e.and=t=>qMe(e,t),e.transform=t=>lA(e,JMe(t)),e.default=t=>YMe(e,t),e.prefault=t=>XMe(e,t),e.catch=t=>QMe(e,t),e.pipe=t=>lA(e,t),e.readonly=()=>$Me(e),e.describe=t=>{let n=e.clone();return Tk.add(n,{description:t}),n},Object.defineProperty(e,"description",{get(){return Tk.get(e)?.description},configurable:!0}),e.meta=(...t)=>{if(t.length===0)return Tk.get(e);let n=e.clone();return Tk.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),dA=Q(`_ZodString`,(e,t)=>{jO.init(e,t),uA.init(e,t);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...t)=>e.check(EMe(...t)),e.includes=(...t)=>e.check(kMe(...t)),e.startsWith=(...t)=>e.check(AMe(...t)),e.endsWith=(...t)=>e.check(jMe(...t)),e.min=(...t)=>e.check(Nk(...t)),e.max=(...t)=>e.check(Mk(...t)),e.length=(...t)=>e.check(Pk(...t)),e.nonempty=(...t)=>e.check(Nk(1,...t)),e.lowercase=t=>e.check(DMe(t)),e.uppercase=t=>e.check(OMe(t)),e.trim=()=>e.check(NMe()),e.normalize=(...t)=>e.check(MMe(...t)),e.toLowerCase=()=>e.check(PMe()),e.toUpperCase=()=>e.check(FMe())}),fA=Q(`ZodString`,(e,t)=>{jO.init(e,t),dA.init(e,t),e.email=t=>e.check(Xje(mA,t)),e.url=t=>e.check(tMe(_A,t)),e.jwt=t=>e.check(gMe(MA,t)),e.emoji=t=>e.check(nMe(vA,t)),e.guid=t=>e.check(Ek(hA,t)),e.uuid=t=>e.check(Zje(gA,t)),e.uuidv4=t=>e.check(Qje(gA,t)),e.uuidv6=t=>e.check($je(gA,t)),e.uuidv7=t=>e.check(eMe(gA,t)),e.nanoid=t=>e.check(rMe(yA,t)),e.guid=t=>e.check(Ek(hA,t)),e.cuid=t=>e.check(iMe(bA,t)),e.cuid2=t=>e.check(aMe(xA,t)),e.ulid=t=>e.check(oMe(SA,t)),e.base64=t=>e.check(pMe(kA,t)),e.base64url=t=>e.check(mMe(AA,t)),e.xid=t=>e.check(sMe(CA,t)),e.ksuid=t=>e.check(cMe(wA,t)),e.ipv4=t=>e.check(lMe(TA,t)),e.ipv6=t=>e.check(uMe(EA,t)),e.cidrv4=t=>e.check(dMe(DA,t)),e.cidrv6=t=>e.check(fMe(OA,t)),e.e164=t=>e.check(hMe(jA,t)),e.datetime=t=>e.check(VMe(t)),e.date=t=>e.check(HMe(t)),e.time=t=>e.check(UMe(t)),e.duration=t=>e.check(WMe(t))}),pA=Q(`ZodStringFormat`,(e,t)=>{MO.init(e,t),dA.init(e,t)}),mA=Q(`ZodEmail`,(e,t)=>{FO.init(e,t),pA.init(e,t)}),hA=Q(`ZodGUID`,(e,t)=>{NO.init(e,t),pA.init(e,t)}),gA=Q(`ZodUUID`,(e,t)=>{PO.init(e,t),pA.init(e,t)}),_A=Q(`ZodURL`,(e,t)=>{IO.init(e,t),pA.init(e,t)}),vA=Q(`ZodEmoji`,(e,t)=>{LO.init(e,t),pA.init(e,t)}),yA=Q(`ZodNanoID`,(e,t)=>{RO.init(e,t),pA.init(e,t)}),bA=Q(`ZodCUID`,(e,t)=>{zO.init(e,t),pA.init(e,t)}),xA=Q(`ZodCUID2`,(e,t)=>{BO.init(e,t),pA.init(e,t)}),SA=Q(`ZodULID`,(e,t)=>{VO.init(e,t),pA.init(e,t)}),CA=Q(`ZodXID`,(e,t)=>{HO.init(e,t),pA.init(e,t)}),wA=Q(`ZodKSUID`,(e,t)=>{UO.init(e,t),pA.init(e,t)}),TA=Q(`ZodIPv4`,(e,t)=>{JO.init(e,t),pA.init(e,t)}),EA=Q(`ZodIPv6`,(e,t)=>{YO.init(e,t),pA.init(e,t)}),DA=Q(`ZodCIDRv4`,(e,t)=>{XO.init(e,t),pA.init(e,t)}),OA=Q(`ZodCIDRv6`,(e,t)=>{ZO.init(e,t),pA.init(e,t)}),kA=Q(`ZodBase64`,(e,t)=>{QO.init(e,t),pA.init(e,t)}),AA=Q(`ZodBase64URL`,(e,t)=>{$O.init(e,t),pA.init(e,t)}),jA=Q(`ZodE164`,(e,t)=>{ek.init(e,t),pA.init(e,t)}),MA=Q(`ZodJWT`,(e,t)=>{tk.init(e,t),pA.init(e,t)}),NA=Q(`ZodNumber`,(e,t)=>{nk.init(e,t),uA.init(e,t),e.gt=(t,n)=>e.check(kk(t,n)),e.gte=(t,n)=>e.check(Ak(t,n)),e.min=(t,n)=>e.check(Ak(t,n)),e.lt=(t,n)=>e.check(Dk(t,n)),e.lte=(t,n)=>e.check(Ok(t,n)),e.max=(t,n)=>e.check(Ok(t,n)),e.int=t=>e.check(Qk(t)),e.safe=t=>e.check(Qk(t)),e.positive=t=>e.check(kk(0,t)),e.nonnegative=t=>e.check(Ak(0,t)),e.negative=t=>e.check(Dk(0,t)),e.nonpositive=t=>e.check(Ok(0,t)),e.multipleOf=(t,n)=>e.check(jk(t,n)),e.step=(t,n)=>e.check(jk(t,n)),e.finite=()=>e;let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null}),PA=Q(`ZodNumberFormat`,(e,t)=>{rk.init(e,t),NA.init(e,t)}),FA=Q(`ZodBoolean`,(e,t)=>{ik.init(e,t),uA.init(e,t)}),IA=Q(`ZodUnknown`,(e,t)=>{ak.init(e,t),uA.init(e,t)}),LA=Q(`ZodNever`,(e,t)=>{ok.init(e,t),uA.init(e,t)}),RA=Q(`ZodArray`,(e,t)=>{sk.init(e,t),uA.init(e,t),e.element=t.element,e.min=(t,n)=>e.check(Nk(t,n)),e.nonempty=t=>e.check(Nk(1,t)),e.max=(t,n)=>e.check(Mk(t,n)),e.length=(t,n)=>e.check(Pk(t,n)),e.unwrap=()=>e.element}),zA=Q(`ZodObject`,(e,t)=>{ck.init(e,t),uA.init(e,t),GE(e,`shape`,()=>t.shape),e.keyof=()=>aA(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:eA()}),e.loose=()=>e.clone({...e._zod.def,catchall:eA()}),e.strict=()=>e.clone({...e._zod.def,catchall:KMe()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>Fje(e,t),e.merge=t=>Ije(e,t),e.pick=t=>Nje(e,t),e.omit=t=>Pje(e,t),e.partial=(...t)=>Lje(KA,e,t[0]),e.required=(...t)=>Rje(XA,e,t[0])}),BA=Q(`ZodUnion`,(e,t)=>{lk.init(e,t),uA.init(e,t),e.options=t.options}),VA=Q(`ZodIntersection`,(e,t)=>{uk.init(e,t),uA.init(e,t)}),HA=Q(`ZodRecord`,(e,t)=>{dk.init(e,t),uA.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType}),UA=Q(`ZodEnum`,(e,t)=>{fk.init(e,t),uA.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new UA({...t,checks:[],...QE(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new UA({...t,checks:[],...QE(r),entries:i})}}),WA=Q(`ZodLiteral`,(e,t)=>{pk.init(e,t),uA.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})}),GA=Q(`ZodTransform`,(e,t)=>{mk.init(e,t),uA.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=r=>{if(typeof r==`string`)n.issues.push(iD(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??(t.code=`custom`),t.input??(t.input=n.value),t.inst??(t.inst=e),t.continue??(t.continue=!0),n.issues.push(iD(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}}),KA=Q(`ZodOptional`,(e,t)=>{hk.init(e,t),uA.init(e,t),e.unwrap=()=>e._zod.def.innerType}),qA=Q(`ZodNullable`,(e,t)=>{gk.init(e,t),uA.init(e,t),e.unwrap=()=>e._zod.def.innerType}),JA=Q(`ZodDefault`,(e,t)=>{_k.init(e,t),uA.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}),YA=Q(`ZodPrefault`,(e,t)=>{vk.init(e,t),uA.init(e,t),e.unwrap=()=>e._zod.def.innerType}),XA=Q(`ZodNonOptional`,(e,t)=>{yk.init(e,t),uA.init(e,t),e.unwrap=()=>e._zod.def.innerType}),ZA=Q(`ZodCatch`,(e,t)=>{bk.init(e,t),uA.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}),QA=Q(`ZodPipe`,(e,t)=>{xk.init(e,t),uA.init(e,t),e.in=t.in,e.out=t.out}),$A=Q(`ZodReadonly`,(e,t)=>{Sk.init(e,t),uA.init(e,t)}),ej=Q(`ZodCustom`,(e,t)=>{Ck.init(e,t),uA.init(e,t)})})),rNe=n((()=>{Ik()})),nj=n((()=>{Ik(),tj(),Lk(),Gk(),Xk(),rNe(),lD(),Hk(),tj()})),iNe=n((()=>{nj(),nj()})),aNe=n((()=>{iNe()})),rj,ij,aj,oj,sj,cj,lj,uj,dj,fj,oNe=n((()=>{aNe(),aA([`local`,`user`,`project`,`dynamic`,`enterprise`,`claudeai`,`managed`]),aA([`stdio`,`sse`,`sse-ide`,`http`,`ws`,`sdk`,`claudeai-proxy`]),rj=nA({type:oA(`stdio`).optional(),command:Zk().min(1,`Command cannot be empty`),args:tA(Zk()).default([]),env:iA(Zk(),Zk()).optional()}),ij=nA({clientId:Zk().optional(),callbackPort:GMe().int().positive().optional(),authServerMetadataUrl:Zk().url().startsWith(`https://`,{message:`authServerMetadataUrl must use https://`}).optional(),xaa:$k().optional()}),aj=nA({type:oA(`sse`),url:Zk(),headers:iA(Zk(),Zk()).optional(),headersHelper:Zk().optional(),oauth:ij.optional()}),oj=nA({type:oA(`sse-ide`),url:Zk(),ideName:Zk(),ideRunningInWindows:$k().optional()}),sj=nA({type:oA(`ws-ide`),url:Zk(),ideName:Zk(),authToken:Zk().optional(),ideRunningInWindows:$k().optional()}),cj=nA({type:oA(`http`),url:Zk(),headers:iA(Zk(),Zk()).optional(),headersHelper:Zk().optional(),oauth:ij.optional()}),lj=nA({type:oA(`ws`),url:Zk(),headers:iA(Zk(),Zk()).optional(),headersHelper:Zk().optional()}),uj=nA({type:oA(`sdk`),name:Zk()}),dj=nA({type:oA(`claudeai-proxy`),url:Zk(),id:Zk()}),fj=rA([rj,aj,oj,sj,cj,lj,uj,dj]),nA({mcpServers:iA(Zk(),fj)})}));function pj(e){if(typeof e==`string`)return e.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,``).replace(/\uFFFD/g,``).normalize(`NFC`);if(Array.isArray(e))return e.map(e=>pj(e));if(typeof e==`object`&&e){let t={};for(let[n,r]of Object.entries(e))t[n]=pj(r);return t}return e}var sNe=n((()=>{}));function cNe(e){return(`code`in e?e.code:void 0)===404?e.message.includes(`"code":-32001`)||e.message.includes(`"code": -32001`):!1}var mj,lNe=n((()=>{UDe(),hS(),mj=2048})),hj=n((()=>{hS()})),gj=n((()=>{hS()})),uNe=n((()=>{hj(),gj()})),dNe=n((()=>{oNe(),sNe(),lNe(),hj(),gj(),uNe()}));function fNe(e){return e.replace(/([a-z])([A-Z])/g,`$1_$2`).replace(/-/g,`_`).toLowerCase()}function pNe(e,t){let n=fNe(t);return{isSearch:_j.has(n),isRead:vj.has(n)}}var _j,vj,mNe=n((()=>{_j=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(`.`)),vj=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 hNe(e){return e.scope===`project`||e.scope===`local`}async function gNe(e,t){if(!t.headersHelper)return null;if(`scope`in t&&hNe(t)&&!vn()&&!tie())return Yn(`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 .`)),J(`tengu_mcp_headersHelper_missing_trust`,{}),null;try{K(e,`Executing headersHelper to get dynamic headers`);let n=await Gi(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=Nn(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 K(e,`Successfully retrieved ${Object.keys(r).length} headers from headersHelper`),r}catch(t){return ia(e,`Error getting headers from headersHelper: ${H(t)}`),q(Error(`Error getting MCP headers from headersHelper for server '${e}': ${H(t)}`)),null}}async function yj(e,t){let n=t.headers||{},r=await gNe(e,t)||{};return{...n,...r}}var _Ne=n((()=>{Gt(),Oi(),W(),Mn(),qi(),oa(),Zn(),Na()})),bj,vNe=n((()=>{b(),bj=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 yNe(){return parseInt(process.env.MCP_TOOL_TIMEOUT||``,10)||Jj}function xj(){return Y(p(),`mcp-needs-auth-cache.json`)}function Sj(){return Zj||(Zj=lu(xj(),`utf-8`).then(e=>Nn(e)).catch(()=>({}))),Zj}async function bNe(e){let t=(await Sj())[e];return t?Date.now()-t.timestamp<Xj:!1}function xNe(e){Qj=Qj.then(async()=>{let t=await Sj();t[e]={timestamp:Date.now()};let n=xj();await su(Tl(n),{recursive:!0}),await _u(n,V(t)),Zj=null}).catch(()=>{})}function Cj(){Zj=null,gu(xj()).catch(()=>{})}function wj(e){let t=gT(e);return t?{mcpServerBaseUrl:t}:{}}function Tj(e,t,n){return J(`tengu_mcp_server_needs_auth`,{transportType:n,...wj(t)}),K(e,`Authentication required for ${{sse:`SSE`,http:`HTTP`,"claudeai-proxy":`claude.ai proxy`}[n]} server`),xNe(e),{name:e,type:`needs-auth`,config:t}}function SNe(e){return async(t,n)=>{let r=async()=>{await zo();let r=Mo();if(!r)throw Error(`No claude.ai OAuth token available`);let i=new Headers(n?.headers);return i.set(`Authorization`,`Bearer ${r.accessToken}`),{response:await e(t,{...n,headers:i}),sentToken:r.accessToken}},{response:i,sentToken:a}=await r();if(i.status!==401)return i;let o=await ro(a).catch(()=>!1);if(J(`tengu_mcp_claudeai_proxy_401`,{tokenChanged:o}),!o){let e=Mo()?.accessToken;if(!e||e===a)return i}try{return(await r()).response}catch{return i}}}async function Ej(e,t){let n=(await import(`./wrapper-K8ZapJVu.js`)).default;return new n(e,[`mcp`],t)}function Dj(){return parseInt(process.env.MCP_TIMEOUT||``,10)||3e4}function Oj(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`,tM);let i=new AbortController,a=setTimeout(e=>e.abort(new DOMException(`The operation timed out.`,`TimeoutError`)),eM,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 kj(){return parseInt(process.env.MCP_SERVER_CONNECTION_BATCH_SIZE||``,10)||3}function CNe(){return parseInt(process.env.MCP_REMOTE_SERVER_CONNECTION_BATCH_SIZE||``,10)||20}function Aj(e){return!e.type||e.type===`stdio`||e.type===`sdk`}function wNe(e){return!e.name.startsWith(`mcp__ide__`)||nM.includes(e.name)}function jj(e,t){return`${e}-${V(t)}`}async function Mj(e,t){let n=jj(e,t);try{let n=await rM(e,t);n.type===`connected`&&await n.cleanup()}catch{}rM.cache.delete(n),aM.cache.delete(e),oM.cache.delete(e),sM.cache.delete(e)}async function Nj(e){if(e.config.type===`sdk`)return e;let t=await rM(e.name,e.config);if(t.type!==`connected`)throw new Gn(`MCP server "${e.name}" is not connected`,`MCP server not connected`);return t}function TNe(e,t){if(e.type!==t.type)return!1;let{scope:n,...r}=e,{scope:i,...a}=t;return V(r)===V(a)}function ENe(e,t){let n=Object.keys(e);return n.length>0?n.map(t=>`${t}=${String(e[t])}`).join(` `):t}async function Pj(e,t,n){return(await Uj({client:n,tool:e,args:t,signal:TE().signal})).content}async function Fj(e,t){try{Wo(),await Mj(e,t);let n=await rM(e,t);if(n.type!==`connected`)return{client:n,tools:[],commands:[]};t.type===`claudeai-proxy`&&jw(e);let r=!!n.capabilities?.resources,[i,a,o,s]=await Promise.all([aM(n),sM(n),Promise.resolve([]),r?oM(n):Promise.resolve([])]),c=[...a,...o],l=[];return r&&([QC,CE].some(e=>i.some(t=>Ys(t,e.name)))||l.push(QC,CE)),{client:n,tools:[...i,...l],commands:c,resources:s.length>0?s:void 0}}catch(n){return ia(e,`Error during reconnection: ${H(n)}`),{client:{name:e,type:`failed`,config:t},tools:[],commands:[]}}}async function Ij(e,t,n){await iue(e,n,{concurrency:t})}async function Lj(e,t){let n=!1,r=Object.entries(t??(await Qw()).servers),i=[];for(let t of r)nT(t[0])?e({client:{name:t[0],type:`disabled`,config:t[1]},tools:[],commands:[]}):i.push(t);let a=i.length,o=hr(i,([e,t])=>t.type===`stdio`),s=hr(i,([e,t])=>t.type===`sse`),c=hr(i,([e,t])=>t.type===`http`),l=hr(i,([e,t])=>t.type===`sse-ide`),u=hr(i,([e,t])=>t.type===`ws-ide`),d=i.filter(([e,t])=>Aj(t)),f=i.filter(([e,t])=>!Aj(t)),p={totalServers:a,stdioCount:o,sseCount:s,httpCount:c,sseIdeCount:l,wsIdeCount:u},m=async([t,r])=>{try{if(nT(t)){e({client:{name:t,type:`disabled`,config:r},tools:[],commands:[]});return}if((r.type===`claudeai-proxy`||r.type===`http`||r.type===`sse`)&&(await bNe(t)||(r.type===`http`||r.type===`sse`)&&oje(t,r))){K(t,`Skipping connection (cached needs-auth)`),e({client:{name:t,type:`needs-auth`,config:r},tools:[fE(t,r)],commands:[]});return}let i=await rM(t,r,p);if(i.type!==`connected`){e({client:i,tools:i.type===`needs-auth`?[fE(t,r)]:[],commands:[]});return}r.type===`claudeai-proxy`&&jw(t);let a=!!i.capabilities?.resources,[o,s,c,l]=await Promise.all([aM(i),sM(i),Promise.resolve([]),a?oM(i):Promise.resolve([])]),u=[...s,...c],d=[];a&&!n&&(n=!0,d.push(QC,CE)),e({client:i,tools:[...o,...d],commands:u,resources:l.length>0?l:void 0})}catch(n){ia(t,`Error fetching tools/commands/resources: ${H(n)}`),e({client:{name:t,type:`failed`,config:r},tools:[],commands:[]})}};await Promise.all([Ij(d,kj(),m),Ij(f,CNe(),m)])}function Rj(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=[];Lj(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);J(`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=>{ia(`prefetchAllMcpResources`,`Failed to get MCP resources: ${H(e)}`),t({clients:[],tools:[],commands:[]})})})}async function zj(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 Bj(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 Ug(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($j.has(r.mimeType??``)){let e=Buffer.from(r.blob,`base64`),t=r.mimeType?.split(`/`)[1]||`png`,a=await Ug(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 Bj(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 Bj(e,t,n,r){let i=await hE(e,t,`mcp-${di(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:gE(i.filepath,t,i.size,r)}]}function Vj(e,t=2){if(e===null)return`null`;if(Array.isArray(e))return e.length===0?`[]`:`[${Vj(e[0],t-1)}]`;if(typeof e==`object`){if(t<=0)return`{...}`;let n=Object.entries(e).slice(0,10).map(([e,n])=>`${e}: ${Vj(n,t-1)}`),r=Object.keys(e).length>10?`, ...`:``;return`{${n.join(`, `)}${r}}`}return typeof e}async function DNe(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:V(e.structuredContent),type:`structuredContent`,schema:Vj(e.structuredContent)};if(`content`in e&&Array.isArray(e.content)){let t=(await Promise.all(e.content.map(e=>zj(e,n,r,!0)))).flat();return{content:t,type:`contentArray`,schema:Vj(t)}}}let i=`MCP server "${n}" tool "${t}": unexpected response format`;throw ia(n,i),new Gn(i,`MCP tool unexpected response format`)}function Hj(e){return!e||typeof e==`string`?!1:e.some(e=>e.type===`image`)}async function ONe(e,t,n,r,i=!1){let{content:a,type:o,schema:s}=await DNe(e,t,n,r);if(n===`ide`||i&&!Hj(a)||!await vke(a))return a;let c=tw(a);if(f(process.env.ENABLE_MCP_LARGE_OUTPUT_FILES))return J(`tengu_mcp_large_result_handled`,{outcome:`truncated`,reason:`env_disabled`,sizeEstimateTokens:c}),await bke(a);if(!a)return a;if(Hj(a))return J(`tengu_mcp_large_result_handled`,{outcome:`truncated`,reason:`contains_images`,sizeEstimateTokens:c}),await bke(a);let l=Date.now(),u=`mcp-${di(n)}-${di(t)}-${l}`,d=ANe(a),p=typeof a==`string`?a:d??V(a,null,2),m=await ey(p,u);if(iy(m)){let e=p.length;return J(`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.`}J(`tengu_mcp_large_result_handled`,{outcome:`persisted`,reason:`file_saved`,sizeEstimateTokens:c,persistedSizeChars:m.originalSize});let h=d===void 0?mE(o,s):mE(`toolResult`);return mje(m.filepath,m.originalSize,h)}function kNe(){let e=process.env.MCP_TRUNCATION_PROMPT_OVERRIDE;return e?e!==`legacy`:!1}function ANe(e){if(!kNe()||!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 jNe({client:e,clientConnection:t,tool:n,args:r,meta:i,signal:a,setAppState:o,onProgress:s,imageLimits:c,hasResultSizeAnnotation:l=!1,callToolFn:u=Uj,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 mS)||e.code!==sx.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 K(s,`Tool '${n}' returned -32042 but no valid elicitations in error data`),e;K(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 FE(s,e,a);if(r){if(K(s,`URL elicitation ${t} resolved by hook: ${V(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 IE(s,i,a,`url`,t);if(c.action!==`accept`)return K(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.`};K(s,`Elicitation ${t} completed, retrying tool call`)}}}async function Uj({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{K(t,`Calling MCP tool: ${r}`),d=setInterval((e,t,n)=>{let r=Date.now()-e;K(t,`Tool '${n}' still running (${`${Math.floor(r/1e3)}s`} elapsed)`)},3e4,u,t,r);let n=yNe(),f,p=new Promise((e,i)=>{f=setTimeout((e,t,n,r)=>{e(new Gn(`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},$x,{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 ia(t,e),new Kj(e,`MCP tool returned error`,`_meta`in m&&m._meta?{_meta:m._meta}:void 0)}let h=Date.now()-u;K(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=wje(t);return g&&J(`tengu_code_indexing_tool_used`,{tool:g,source:`mcp`,success:!0}),{content:await ONe(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`&&K(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 zC)throw K(t,`Tool call returned 401 Unauthorized - token may have expired`),J(`tengu_mcp_tool_call_auth_error`,{}),new Wj(t,`MCP server "${t}" requires re-authorization (token expired)`);let r=qj(e),i=`code`in e&&e.code===-32e3&&e.message.includes(`Connection closed`)&&(n.type===`http`||n.type===`claudeai-proxy`);if(r||i)throw K(t,`MCP session expired during tool call (${r?`404/-32001`:`connection closed`}), clearing connection cache for re-initialization`),J(`tengu_mcp_session_expired`,{}),await Mj(t,n),new Gj(t)}if(!(e instanceof Error)||e.name!==`AbortError`)throw e;return{content:void 0}}finally{d!==void 0&&clearInterval(d)}}function MNe(e){let t=e.message.content?.[0];if(!(!t||typeof t==`string`||t.type!==`tool_use`))return t.id}async function NNe(e,t){let n=[],r=[],i=await Promise.allSettled(Object.entries(e).map(async([e,n])=>{let r=new bj(e,t),i=new bS({name:`workmate`,title:`Work Mate`,version:`0.0.16`,description:`Agentic coding tool`,websiteUrl:JC},{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 aM(a);o.push(...e)}return{client:a,tools:o}}catch(t){return ia(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 Wj,Gj,Kj,qj,Jj,Yj,Xj,Zj,Qj,$j,eM,tM,nM,rM,iM,aM,oM,sM,cM=n((()=>{UDe(),ROe(),KOe(),XOe(),iC(),hS(),qp(),d(),Y_e(),aue(),Gt(),Ga(),YC(),Zs(),$C(),Pke(),pje(),wE(),OE(),Tr(),Do(),Xn(),jE(),W(),h(),Mn(),Sae(),GM(),r_(),oa(),_E(),Ske(),Tje(),ma(),_se(),tc(),kse(),Qc(),sy(),Na(),LE(),Zr(),si(),_T(),dNe(),b(),HC(),mNe(),Oae(),Bo(),dE(),Fw(),sT(),_Ne(),vNe(),Zn(),Wj=class extends Error{constructor(e,t){super(t),x(this,`serverName`,void 0),this.name=`McpAuthError`,this.serverName=e}},Gj=class extends Error{constructor(e){super(`MCP server "${e}" session expired`),this.name=`McpSessionExpiredError`}},Kj=class extends Gn{constructor(e,t,n){super(e,t),x(this,`mcpMeta`,void 0),this.mcpMeta=n,this.name=`McpToolCallError`}},qj=cNe,Jj=1e8,Yj=mj,Xj=900*1e3,Zj=null,Qj=Promise.resolve(),$j=new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]),eM=6e4,tM=`application/json, text/event-stream`,nM=[`mcp__ide__executeCode`,`mcp__ide__getDiagnostics`],rM=u(async(e,t,n)=>{let r=Date.now();try{let i,a=ic();if(t.type===`sse`){let n=new uE(e,t),r=await yj(e,t),a={authProvider:n,fetch:Oj(tE(rC(),n)),requestInit:{headers:{"User-Agent":yo(),...r}}};a.eventSourceInit={fetch:async(e,t)=>{let i={},a=await n.tokens();a&&(i.Authorization=`Bearer ${a.access_token}`);let o=ec();return fetch(e,{...t,...o,headers:{"User-Agent":yo(),...i,...t?.headers,...r,Accept:`text/event-stream`}})}},i=new UC(new URL(t.url),a),K(e,`SSE transport initialized, awaiting connection`)}else if(t.type===`sse-ide`){K(e,`Setting up SSE-IDE transport to ${t.url}`);let n=ec(),r=n.dispatcher?{eventSourceInit:{fetch:async(e,t)=>fetch(e,{...t,...n,headers:{"User-Agent":yo(),...t?.headers}})}}:{};i=new UC(new URL(t.url),Object.keys(r).length>0?r:void 0)}else if(t.type===`ws-ide`){let e=vse(),n={"User-Agent":yo(),...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:gse(t.url),tls:e||void 0}):await Ej(t.url,{headers:n,agent:bse(t.url),...e||{}}),i=new PE(r)}else if(t.type===`ws`){K(e,`Initializing WebSocket transport to ${t.url}`);let n=await yj(e,t),r=vse(),o={"User-Agent":yo(),...a&&{Authorization:`Bearer ${a}`},...n},s=Kp(o,(e,t)=>t.toLowerCase()===`authorization`?`[REDACTED]`:e);K(e,`WebSocket transport options: ${V({url:t.url,headers:s,hasSessionAuth:!!a})}`);let c;c=typeof Bun<`u`?new globalThis.WebSocket(t.url,{protocols:[`mcp`],headers:o,proxy:gse(t.url),tls:r||void 0}):await Ej(t.url,{headers:o,agent:bse(t.url),...r||{}}),i=new PE(c)}else if(t.type===`http`){K(e,`Initializing HTTP transport to ${t.url}`),K(e,`Node version: ${process.version}, Platform: ${process.platform}`),K(e,`Environment: ${V({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=new uE(e,t),r=await yj(e,t),o=!!await n.tokens(),s=ec();K(e,`Proxy options: ${s.dispatcher?`custom dispatcher`:`default`}`);let c={authProvider:n,fetch:Oj(tE(rC(),n)),requestInit:{...s,headers:{"User-Agent":yo(),...a&&!o&&{Authorization:`Bearer ${a}`},...r}}},l=c.requestInit?.headers?Kp(c.requestInit.headers,(e,t)=>t.toLowerCase()===`authorization`?`[REDACTED]`:e):void 0;K(e,`HTTP transport options: ${V({url:t.url,headers:l,hasAuthProvider:!!n,timeoutMs:eM})}`),i=new KC(new URL(t.url),c),K(e,`HTTP transport created successfully`)}else if(t.type===`sdk`)throw Error(`SDK servers should be handled in print.ts`);else if(t.type===`claudeai-proxy`){if(K(e,`Initializing claude.ai proxy transport for server ${t.id}`),!Mo())throw Error(`No claude.ai OAuth token found`);let n=Wa(),r=`${n.MCP_PROXY_URL}${n.MCP_PROXY_PATH.replace(`{server_id}`,t.id)}`;K(e,`Using claude.ai proxy at ${r}`);let a=SNe(globalThis.fetch),o=ec(),s={fetch:Oj(a),requestInit:{...o,headers:{"User-Agent":yo(),"X-Mcp-Client-Session-Id":ln()}}};i=new KC(new URL(r),s),K(e,`claude.ai proxy transport created successfully`)}else if(t.type===`stdio`||!t.type){let e=t;i=new GOe({command:process.env.CLAUDE_CODE_SHELL_PREFIX||e.command,args:process.env.CLAUDE_CODE_SHELL_PREFIX?[[e.command,...e.args].join(` `)]:e.args,env:{...Zc(),...e.env},stderr:`pipe`})}else throw Error(`Unsupported server type: ${t.type}`);let o,s=``;if(t.type===`stdio`||!t.type){let e=i;e.stderr&&(o=e=>{if(s.length<64*1024*1024)try{s+=e.toString()}catch{}},e.stderr.on(`data`,o))}let c=new bS({name:`workmate`,title:`Work Mate`,version:`0.0.16`,description:`Agentic coding tool`,websiteUrl:JC},{capabilities:{roots:{},elicitation:{}}});if(t.type===`http`&&K(e,`Client created, setting up request handler`),c.setRequestHandler(fS,async()=>(K(e,`Received ListRoots request from server`),{roots:[{uri:`file://${Zt()}`}]})),K(e,`Starting connection with timeout of ${Dj()}ms`),t.type===`http`){K(e,`Testing basic HTTP connectivity to ${t.url}`);try{let n=new URL(t.url);K(e,`Parsed URL: host=${n.hostname}, port=${n.port||`default`}, protocol=${n.protocol}`),(n.hostname===`127.0.0.1`||n.hostname===`localhost`)&&K(e,`Using loopback address: ${n.hostname}`)}catch(t){K(e,`Failed to parse URL: ${t}`)}}let l=c.connect(i),u=new Promise((t,n)=>{let a=setTimeout(()=>{K(e,`Connection timeout triggered after ${Date.now()-r}ms (limit: ${Dj()}ms)`),i.close().catch(()=>{}),n(new Gn(`MCP server "${e}" connection timed out after ${Dj()}ms`,`MCP connection timeout`))},Dj());l.then(()=>{clearTimeout(a)},e=>{clearTimeout(a)})});try{await Promise.race([l,u]),s&&(ia(e,`Server stderr: ${s}`),s=``);let n=Date.now()-r;K(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(K(e,`SSE Connection failed after ${a}ms: ${V({url:t.url,error:n.message,errorType:n.constructor.name,stack:n.stack})}`),ia(e,n),n instanceof zC)return Tj(e,t,`sse`)}else if(t.type===`http`&&n instanceof Error){let r=n;if(K(e,`HTTP Connection failed after ${a}ms: ${n.message} (code: ${r.code||`none`}, errno: ${r.errno||`none`})`),ia(e,n),n instanceof zC)return Tj(e,t,`http`)}else if(t.type===`claudeai-proxy`&&n instanceof Error){if(K(e,`claude.ai proxy connection failed after ${a}ms: ${n.message}`),ia(e,n),n.code===401)return Tj(e,t,`claudeai-proxy`)}else(t.type===`sse-ide`||t.type===`ws-ide`)&&J(`tengu_mcp_ide_server_connection_failed`,{connectionDurationMs:a});throw i.close().catch(()=>{}),s&&ia(e,`Server stderr: ${s}`),n}let d=c.getServerCapabilities(),f=c.getServerVersion(),p=c.getInstructions(),m=p;if(p&&p.length>Yj&&(m=`${p.slice(0,Yj)}… [truncated]`,K(e,`Server instructions truncated from ${p.length} to ${Yj} chars`)),K(e,`Connection established with capabilities: ${V({hasTools:!!d?.tools,hasPrompts:!!d?.prompts,hasResources:!!d?.resources,hasResourceSubscribe:!!d?.resources?.subscribe,serverVersion:f||`unknown`})}`),U(`[MCP] Server "${e}" connected with subscribe=${!!d?.resources?.subscribe}`),c.setRequestHandler(cS,async t=>(K(e,`Elicitation request received during initialization: ${V(t)}`),{action:`cancel`})),t.type===`sse-ide`||t.type===`ws-ide`){J(`tengu_mcp_ide_server_connection_succeeded`,{connectionDurationMs:Date.now()-r,serverVersion:f});try{JNe(c)}catch(t){ia(e,`Failed to send ide_connected notification: ${t}`)}}let h=Date.now(),g=!1,_=c.onerror,v=c.onclose,y=0,b=!1,x=t=>{b||(b=!0,K(e,`Closing transport (${t})`),c.close().catch(t=>{K(e,`Error during close: ${H(t)}`)}))},S=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`);c.onerror=n=>{let r=Date.now()-h;g=!0;let i=t.type||`stdio`;if(K(e,`${i.toUpperCase()} connection dropped after ${Math.floor(r/1e3)}s uptime`),n.message&&(n.message.includes(`ECONNRESET`)?K(e,`Connection reset - server may have crashed or restarted`):n.message.includes(`ETIMEDOUT`)?K(e,`Connection timeout - network issue or server unresponsive`):n.message.includes(`ECONNREFUSED`)?K(e,`Connection refused - server may be down`):n.message.includes(`EPIPE`)?K(e,`Broken pipe - server closed connection unexpectedly`):n.message.includes(`EHOSTUNREACH`)?K(e,`Host unreachable - network connectivity issue`):n.message.includes(`ESRCH`)?K(e,`Process not found - stdio server process terminated`):n.message.includes(`spawn`)?K(e,`Failed to spawn process - check command and permissions`):K(e,`Connection error: ${n.message}`)),(i===`http`||i===`claudeai-proxy`)&&qj(n)){K(e,`MCP session expired (server returned 404 with session-not-found), triggering reconnection`),x(`session expired`),_&&_(n);return}if(i===`sse`||i===`http`||i===`claudeai-proxy`){if(n.message.includes(`Maximum reconnection attempts`)){x(`SSE reconnection exhausted`),_&&_(n);return}S(n.message)?(y++,K(e,`Terminal connection error ${y}/3`),y>=3&&(y=0,x(`max consecutive terminal errors`))):y=0}_&&_(n)},c.onclose=()=>{let n=Date.now()-h;K(e,`${(t.type??`unknown`).toUpperCase()} connection closed after ${Math.floor(n/1e3)}s (${g?`with errors`:`cleanly`})`);let r=jj(e,t);aM.cache.delete(e),oM.cache.delete(e),sM.cache.delete(e),rM.cache.delete(r),K(e,`Cleared connection cache for reconnection`),v&&v()};let C=async()=>{if(o&&(t.type===`stdio`||!t.type)&&i.stderr?.off(`data`,o),t.type===`stdio`)try{let t=i.pid;if(t){K(e,`Sending SIGINT to MCP server process`);try{process.kill(t,`SIGINT`)}catch(t){K(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),K(e,`MCP server process exited cleanly`),n())}},50),a=setTimeout(()=>{r||(r=!0,clearInterval(i),K(e,`Cleanup timeout reached, stopping process monitoring`),n())},600);try{if(await Ho(100),!r){try{process.kill(t,0),K(e,`SIGINT failed, sending SIGTERM to MCP server process`);try{process.kill(t,`SIGTERM`)}catch(t){K(e,`Error sending SIGTERM: ${t}`),r=!0,clearInterval(i),clearTimeout(a),n();return}}catch{r=!0,clearInterval(i),clearTimeout(a),n();return}if(await Ho(400),!r)try{process.kill(t,0),K(e,`SIGTERM failed, sending SIGKILL to MCP server process`);try{process.kill(t,`SIGKILL`)}catch(t){K(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){K(e,`Error terminating process: ${t}`)}try{await c.close()}catch(t){K(e,`Error closing client: ${t}`)}},w=qn(C),T=async()=>{w?.(),await C()};return J(`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,...wj(t)}),{name:e,client:c,type:`connected`,capabilities:d??{},serverInfo:f,instructions:m,config:t,cleanup:T}}catch(i){let a=Date.now()-r;return J(`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`,...wj(t)}),K(e,`Connection failed after ${a}ms: ${H(i)}`),ia(e,`Connection failed: ${H(i)}`),{name:e,type:`failed`,config:t,error:H(i)}}},jj),iM=20,aM=pa(async e=>{if(e.type!==`connected`)return[];try{if(!e.capabilities?.tools)return[];let t=pj((await e.client.request({method:`tools/list`},Qx)).tools),n=e.config.type===`sdk`&&m(process.env.CLAUDE_AGENT_SDK_MCP_NO_PREFIX);return t.map(t=>{let r=kne(e.name,t.name);return{...Nke,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>Yj?`${e.slice(0,Yj)}… [truncated]`:e},isConcurrencySafe(){return t.annotations?.readOnlyHint??!1},isReadOnly(){return t.annotations?.readOnlyHint??!1},toAutoClassifierInput(e){return ENe(e,t.name)},isDestructive(){return t.annotations?.destructiveHint??!1},isOpenWorld(){return t.annotations?.openWorldHint??!1},isSearchOrReadCommand(){return pNe(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=MNe(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 jNe({client:await Nj(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 Gj&&i<1){K(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 Gn)){let e=n.constructor.name;if(e===`Error`)throw new Gn(n.message,n.message.slice(0,200));if(e===`McpError`&&`code`in n&&typeof n.code==`number`)throw new Gn(n.message,`McpError ${n.code}`)}throw n}},userFacingName(){let n=t.annotations?.title||t.name;return`${e.name} - ${n} (MCP)`}}}).filter(wNe)}catch(t){return ia(e.name,`Failed to fetch tools: ${H(t)}`),[]}},e=>e.name,iM),oM=pa(async e=>{if(e.type!==`connected`)return[];try{if(!e.capabilities?.resources)return[];let t=await e.client.request({method:`resources/list`},Rx);return t.resources?t.resources.map(t=>({...t,server:e.name})):[]}catch(t){return ia(e.name,`Failed to fetch resources: ${H(t)}`),[]}},e=>e.name,iM),sM=pa(async e=>{if(e.type!==`connected`)return[];try{if(!e.capabilities?.prompts)return[];let t=await e.client.request({method:`prompts/list`},Ux);return t.prompts?pj(t.prompts).map(t=>{let n=Object.values(t.arguments??{}).map(e=>e.name);return{type:`prompt`,name:`mcp__${di(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 Nj(e),a=await r.client.getPrompt({name:t.name,arguments:J_e(n,i)});return(await Promise.all(a.messages.map(e=>zj(e.content,r.name)))).flat()}catch(n){throw ia(e.name,`Error running command '${t.name}': ${H(n)}`),n}}}}):[]}catch(t){return ia(e.name,`Failed to fetch commands: ${H(t)}`),[]}},e=>e.name,iM)}));function PNe(e){let t=yl(),n=[],r=uM[e.toLowerCase()];if(!r)return n;let i=process.env.APPDATA||Y(t,`AppData`,`Roaming`),a=process.env.LOCALAPPDATA||Y(t,`AppData`,`Local`);switch(bl()){case`darwin`:n.push(Y(t,`Library`,`Application Support`,`JetBrains`),Y(t,`Library`,`Application Support`)),e.toLowerCase()===`androidstudio`&&n.push(Y(t,`Library`,`Application Support`,`Google`));break;case`win32`:n.push(Y(i,`JetBrains`),Y(a,`JetBrains`),Y(i)),e.toLowerCase()===`androidstudio`&&n.push(Y(a,`Google`));break;case`linux`:n.push(Y(t,`.config`,`JetBrains`),Y(t,`.local`,`share`,`JetBrains`));for(let e of r)n.push(Y(t,`.${e}`));e.toLowerCase()===`androidstudio`&&n.push(Y(t,`.config`,`Google`));break;default:break}return n}async function FNe(e){let t=[],n=G(),r=PNe(e),i=uM[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=Y(e,a.name);if(bl()===`linux`){t.push(r);continue}let o=Y(r,`plugins`);try{await n.stat(o),t.push(o)}catch{}}}catch{}return t.filter((e,n)=>t.indexOf(e)===n)}async function INe(e){let t=await FNe(e);for(let e of t){let t=Y(e,lM);try{return await G().stat(t),!0}catch{}}return!1}async function LNe(e,t=!1){if(!t){let t=fM.get(e);if(t)return t}let n=INe(e).then(t=>(dM.set(e,t),t));return fM.set(e,n),n}async function RNe(e,t=!1){return t&&(dM.delete(e),fM.delete(e)),LNe(e,t)}var lM,uM,dM,fM,zNe=n((()=>{Un(),lM=`claude-code-jetbrains-plugin`,uM={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`]},dM=new Map,fM=new Map}));function BNe(e,t){let n=e.match(/^\\\\wsl(?:\.localhost|\$)\\([^\\]+)(.*)$/);return!n||n[1]===t}var pM,mM=n((()=>{b(),pM=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 vu(`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 vu(`wslpath`,[`-w`,e],{encoding:`utf8`,stdio:[`pipe`,`pipe`,`ignore`]}).trim()}catch{return e}}}}));function VNe({onDone:e,installationStatus:t}){UNe(),be({"confirm:yes":e,"confirm:no":e},{context:`Confirmation`});let n=t?.ideType??bM(),r=yM(n),i=MM(n),a=t?.installedVersion,o=r?`plugin`:`extension`,s=pr.platform===`darwin`?`Cmd+Option+K`:`Ctrl+Alt+K`;return(0,hM.jsxs)(hM.Fragment,{children:[(0,hM.jsx)($e,{title:(0,hM.jsxs)(hM.Fragment,{children:[(0,hM.jsx)(F,{color:`claude`,children:`✻ `}),(0,hM.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,hM.jsxs)(P,{flexDirection:`column`,gap:1,children:[(0,hM.jsxs)(F,{children:[`• Work Mate has context of `,(0,hM.jsx)(F,{color:`suggestion`,children:`⧉ open files`}),` and`,` `,(0,hM.jsx)(F,{color:`suggestion`,children:`⧉ selected lines`})]}),(0,hM.jsxs)(F,{children:[`• Review Work Mate's changes `,(0,hM.jsx)(F,{color:`diffAddedWord`,children:`+11`}),` `,(0,hM.jsx)(F,{color:`diffRemovedWord`,children:`-22`}),` in the comfort of your IDE`]}),(0,hM.jsxs)(F,{children:[`• Cmd+Esc`,(0,hM.jsx)(F,{dimColor:!0,children:` for Quick Launch`})]}),(0,hM.jsxs)(F,{children:[`• `,s,(0,hM.jsx)(F,{dimColor:!0,children:` to reference files or lines in your input`})]})]})}),(0,hM.jsx)(P,{paddingX:1,children:(0,hM.jsx)(F,{dimColor:!0,italic:!0,children:`Press Enter to continue`})})]})}function HNe(){let e=Di(),t=Xc.terminal||`unknown`;return e.hasIdeOnboardingBeenShown?.[t]===!0}function UNe(){if(HNe())return;let e=Xc.terminal||`unknown`;Ni(t=>({...t,hasIdeOnboardingBeenShown:{...t.hasIdeOnboardingBeenShown,[e]:!0}}))}var hM,gM=n((()=>{Wc(),I(),My(),Oi(),Pr(),GM(),hM=tt()}));function _M(e){try{return process.kill(e,0),!0}catch{return!1}}function WNe(){let e=null;return()=>(e||(e=nce(process.ppid,10).then(e=>new Set(e))),e)}function vM(e){if(!e)return!1;let t=FM[e];return t&&t.ideKind===`vscode`}function yM(e){if(!e)return!1;let t=FM[e];return t&&t.ideKind===`jetbrains`}function bM(){return RM()?pr.terminal:null}async function xM(){try{let e=await GNe();return(await Promise.all(e.map(async e=>{try{let t=(await G().readdir(e)).filter(e=>e.name.endsWith(`.lock`));return(await Promise.all(t.map(async t=>{let n=Y(e,t.name);try{return{path:n,mtime:(await G().stat(n)).mtime}}catch{return null}}))).filter(e=>e!==null)}catch(e){return In(e)||q(e),[]}}))).flat().sort((e,t)=>t.mtime.getTime()-e.mtime.getTime()).map(e=>e.path)}catch(e){return q(e),[]}}async function SM(e){try{let t=await G().readFile(e,{encoding:`utf-8`}),n=[],r,i,a=!1,o=!1,s;try{let e=Nn(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(`
|
|
669
|
-
`).map(e=>e.trim())}let c=e.split(Nl).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 q(e),null}}async function CM(e,t,n=500){try{return new Promise(r=>{let i=zle({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 GNe(){let e=[Y(p(),`ide`)];if(_a()!==`wsl`)return e;let t=await zM();if(t){let n=new pM(process.env.WSL_DISTRO_NAME).toLocalPath(t);e.push(Ml(n,`.workmate`,`ide`))}try{let t=`/mnt/c/Users`,n=await G().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(Y(t,r.name,`.workmate`,`ide`))}catch(e){In(e)?U(`WSL IDE lockfile path detection failed (${e.code}): ${H(e)}`):q(e)}return e}async function KNe(){try{let e=await xM();for(let t of e){let e=await SM(t);if(!e){try{await G().unlink(t)}catch(e){q(e)}continue}let n=await WM(e.runningInWindows,e.port),r=!1;if(e.pid?_M(e.pid)||_a()===`wsl`&&await CM(n,e.port)||(r=!0):await CM(n,e.port)||(r=!0),r)try{await G().unlink(t)}catch(e){q(e)}}}catch(e){q(e)}}async function qNe(e){try{let t=await XNe(e);return J(`tengu_ext_installed`,{}),Di().diffTool||Ni(e=>({...e,diffTool:`auto`})),{installed:!0,error:null,installedVersion:t,ideType:e}}catch(t){J(`tengu_ext_install_error`,{});let n=t instanceof Error?t.message:String(t);return q(t),{installed:!1,error:n,installedVersion:null,ideType:e}}}async function wM(){BM&&BM.abort(),BM=TE();let e=BM.signal;await KNe();let t=Date.now();for(;Date.now()-t<3e4&&!e.aborted;){if(fte()){await Ho(1e3,e);continue}let t=await TM(!1);if(e.aborted)return null;if(t.length===1)return t[0];await Ho(1e3,e)}return null}async function TM(e){let t=[];try{let n=process.env.CLAUDE_CODE_SSE_PORT,r=n?parseInt(n,10):null,i=Zt().normalize(`NFC`),a=await xM(),o=await Promise.all(a.map(SM)),s=WNe(),c=_a()!==`wsl`&&RM();for(let n of o){if(!n)continue;let a=!1;if(a=m(process.env.CLAUDE_CODE_IDE_SKIP_VALID_CHECK)?!0:n.port===r||n.workspaceFolders.some(e=>{if(!e)return!1;let t=e;if(_a()===`wsl`&&n.runningInWindows&&process.env.WSL_DISTRO_NAME){if(!BNe(e,process.env.WSL_DISTRO_NAME))return!1;let n=Ml(t).normalize(`NFC`);if(i===n||i.startsWith(n+Nl))return!0;t=new pM(process.env.WSL_DISTRO_NAME).toLocalPath(e)}let r=Ml(t).normalize(`NFC`);if(_a()===`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+Nl)}return i===r||i.startsWith(r+Nl)}),!a&&!e||c&&!(r!==null&&n.port===r)&&(!n.pid||!_M(n.pid)||process.ppid!==n.pid&&!(await s()).has(n.pid)))continue;let o=n.ideName??(RM()?MM(Xc.terminal):`IDE`),l=await WM(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){q(e)}return t}async function JNe(e){await e.notification({method:`ide_connected`,params:{pid:process.pid}})}function YNe(e){return e.some(e=>e.type===`connected`&&e.name===`ide`)}async function EM(e){if(vM(e)){let t=await kM(e);if(t)try{if((await Gi(t,[`--list-extensions`],{env:DM()})).stdout?.includes(VM))return!0}catch{}}else if(yM(e))return await RNe(e);return!1}async function XNe(e){if(vM(e)){let t=await kM(e);if(t){let e=await ZNe(t);if(!e||zse(e,OM())){await Ho(500);let n=await Gi(t,[`--force`,`--install-extension`,`anthropic.claude-code`],{env:DM()});if(n.code!==0)throw Error(`${n.code}: ${n.error} ${n.stderr}`);e=OM()}return e}}return null}function DM(){if(_a()===`linux`)return{...process.env,DISPLAY:``}}function OM(){return`0.0.
|
|
668
|
+
})));`),t.write(`newResult[${qE(e)}] = ${n}.value`)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},i,a=JE,o=!BE.jitless,s=o&&oD.value,c=t.catchall,l;e._zod.parse=(u,d)=>{l??(l=n.value);let f=u.value;if(!a(f))return u.issues.push({expected:`object`,code:`invalid_type`,input:f,inst:e}),u;let p=[];if(o&&s&&d?.async===!1&&d.jitless!==!0)i||(i=r(t.shape)),u=i(u,d);else{u.value={};let e=l.shape;for(let t of l.keys){let n=e[t],r=n._zod.run({value:f[t],issues:[]},d),i=n._zod.optin===`optional`&&n._zod.optout===`optional`;r instanceof Promise?p.push(r.then(e=>i?xO(e,u,t,f):bO(e,u,t))):i?xO(r,u,t,f):bO(r,u,t)}}if(!c)return p.length?Promise.all(p).then(()=>u):u;let m=[],h=l.keySet,g=c._zod,_=g.def.type;for(let e of Object.keys(f)){if(h.has(e))continue;if(_===`never`){m.push(e);continue}let t=g.run({value:f[e],issues:[]},d);t instanceof Promise?p.push(t.then(t=>bO(t,u,e))):bO(t,u,e)}return m.length&&u.issues.push({code:`unrecognized_keys`,keys:m,input:f,inst:e}),p.length?Promise.all(p).then(()=>u):u}}),lk=Q(`$ZodUnion`,(e,t)=>{AO.init(e,t),GE(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),GE(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),GE(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),GE(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>WE(e.source)).join(`|`)})$`)}}),e._zod.parse=(n,r)=>{let i=!1,a=[];for(let e of t.options){let t=e._zod.run({value:n.value,issues:[]},r);if(t instanceof Promise)a.push(t),i=!0;else{if(t.issues.length===0)return t;a.push(t)}}return i?Promise.all(a).then(t=>SO(t,n,e,r)):SO(a,n,e,r)}}),uk=Q(`$ZodIntersection`,(e,t)=>{AO.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>wO(e,t,n)):wO(e,i,a)}}),dk=Q(`$ZodRecord`,(e,t)=>{AO.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!YE(i))return n.issues.push({expected:`record`,code:`invalid_type`,input:i,inst:e}),n;let a=[];if(t.keyType._zod.values){let o=t.keyType._zod.values;n.value={};for(let e of o)if(typeof e==`string`||typeof e==`number`||typeof e==`symbol`){let o=t.valueType._zod.run({value:i[e],issues:[]},r);o instanceof Promise?a.push(o.then(t=>{t.issues.length&&n.issues.push(...eD(e,t.issues)),n.value[e]=t.value})):(o.issues.length&&n.issues.push(...eD(e,o.issues)),n.value[e]=o.value)}let s;for(let e in i)o.has(e)||(s=s??[],s.push(e));s&&s.length>0&&n.issues.push({code:`unrecognized_keys`,input:i,inst:e,keys:s})}else{n.value={};for(let o of Reflect.ownKeys(i)){if(o===`__proto__`)continue;let s=t.keyType._zod.run({value:o,issues:[]},r);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){n.issues.push({origin:`record`,code:`invalid_key`,issues:s.issues.map(e=>nD(e,r,RE())),input:o,path:[o],inst:e}),n.value[s.value]=s.value;continue}let c=t.valueType._zod.run({value:i[o],issues:[]},r);c instanceof Promise?a.push(c.then(e=>{e.issues.length&&n.issues.push(...eD(o,e.issues)),n.value[s.value]=e.value})):(c.issues.length&&n.issues.push(...eD(o,c.issues)),n.value[s.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),fk=Q(`$ZodEnum`,(e,t)=>{AO.init(e,t);let n=kje(t.entries);e._zod.values=new Set(n),e._zod.pattern=RegExp(`^(${n.filter(e=>sD.has(typeof e)).map(e=>typeof e==`string`?XE(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,r)=>{let i=t.value;return e._zod.values.has(i)||t.issues.push({code:`invalid_value`,values:n,input:i,inst:e}),t}}),pk=Q(`$ZodLiteral`,(e,t)=>{AO.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?XE(e):e?e.toString():String(e)).join(`|`)})$`),e._zod.parse=(n,r)=>{let i=n.value;return e._zod.values.has(i)||n.issues.push({code:`invalid_value`,values:t.values,input:i,inst:e}),n}}),mk=Q(`$ZodTransform`,(e,t)=>{AO.init(e,t),e._zod.parse=(e,n)=>{let r=t.transform(e.value,e);if(n.async)return(r instanceof Promise?r:Promise.resolve(r)).then(t=>(e.value=t,e));if(r instanceof Promise)throw new zE;return e.value=r,e}}),hk=Q(`$ZodOptional`,(e,t)=>{AO.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,GE(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),GE(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${WE(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>t.innerType._zod.optin===`optional`?t.innerType._zod.run(e,n):e.value===void 0?e:t.innerType._zod.run(e,n)}),gk=Q(`$ZodNullable`,(e,t)=>{AO.init(e,t),GE(e._zod,`optin`,()=>t.innerType._zod.optin),GE(e._zod,`optout`,()=>t.innerType._zod.optout),GE(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${WE(e.source)}|null)$`):void 0}),GE(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),_k=Q(`$ZodDefault`,(e,t)=>{AO.init(e,t),e._zod.optin=`optional`,GE(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>TO(e,t)):TO(r,t)}}),vk=Q(`$ZodPrefault`,(e,t)=>{AO.init(e,t),e._zod.optin=`optional`,GE(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),yk=Q(`$ZodNonOptional`,(e,t)=>{AO.init(e,t),GE(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>EO(t,e)):EO(i,e)}}),bk=Q(`$ZodCatch`,(e,t)=>{AO.init(e,t),e._zod.optin=`optional`,GE(e._zod,`optout`,()=>t.innerType._zod.optout),GE(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>nD(e,n,RE()))},input:e.value}),e.issues=[]),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>nD(e,n,RE()))},input:e.value}),e.issues=[]),e)}}),xk=Q(`$ZodPipe`,(e,t)=>{AO.init(e,t),GE(e._zod,`values`,()=>t.in._zod.values),GE(e._zod,`optin`,()=>t.in._zod.optin),GE(e._zod,`optout`,()=>t.out._zod.optout),e._zod.parse=(e,n)=>{let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>DO(e,t,n)):DO(r,t,n)}}),Sk=Q(`$ZodReadonly`,(e,t)=>{AO.init(e,t),GE(e._zod,`propValues`,()=>t.innerType._zod.propValues),GE(e._zod,`values`,()=>t.innerType._zod.values),GE(e._zod,`optin`,()=>t.innerType._zod.optin),GE(e._zod,`optout`,()=>t.innerType._zod.optout),e._zod.parse=(e,n)=>{let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(OO):OO(r)}}),Ck=Q(`$ZodCustom`,(e,t)=>{XD.init(e,t),AO.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>kO(t,n,r,e));kO(i,n,r,e)}})}));function qje(){return new wk}var wk,Tk,Jje=n((()=>{wk=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){let n=t[0];if(this._map.set(e,n),n&&typeof n==`object`&&`id`in n){if(this._idmap.has(n.id))throw Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}},Tk=qje()}));function Yje(e,t){return new e({type:`string`,...QE(t)})}function Xje(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...QE(t)})}function Ek(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...QE(t)})}function Zje(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...QE(t)})}function Qje(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...QE(t)})}function $je(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...QE(t)})}function eMe(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...QE(t)})}function tMe(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...QE(t)})}function nMe(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...QE(t)})}function rMe(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...QE(t)})}function iMe(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...QE(t)})}function aMe(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...QE(t)})}function oMe(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...QE(t)})}function sMe(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...QE(t)})}function cMe(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...QE(t)})}function lMe(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...QE(t)})}function uMe(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...QE(t)})}function dMe(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...QE(t)})}function fMe(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...QE(t)})}function pMe(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...QE(t)})}function mMe(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...QE(t)})}function hMe(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...QE(t)})}function gMe(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...QE(t)})}function _Me(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...QE(t)})}function vMe(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...QE(t)})}function yMe(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...QE(t)})}function bMe(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...QE(t)})}function xMe(e,t){return new e({type:`number`,checks:[],...QE(t)})}function SMe(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...QE(t)})}function CMe(e,t){return new e({type:`boolean`,...QE(t)})}function wMe(e){return new e({type:`unknown`})}function TMe(e,t){return new e({type:`never`,...QE(t)})}function Dk(e,t){return new QD({check:`less_than`,...QE(t),value:e,inclusive:!1})}function Ok(e,t){return new QD({check:`less_than`,...QE(t),value:e,inclusive:!0})}function kk(e,t){return new $D({check:`greater_than`,...QE(t),value:e,inclusive:!1})}function Ak(e,t){return new $D({check:`greater_than`,...QE(t),value:e,inclusive:!0})}function jk(e,t){return new eO({check:`multiple_of`,...QE(t),value:e})}function Mk(e,t){return new nO({check:`max_length`,...QE(t),maximum:e})}function Nk(e,t){return new rO({check:`min_length`,...QE(t),minimum:e})}function Pk(e,t){return new iO({check:`length_equals`,...QE(t),length:e})}function EMe(e,t){return new oO({check:`string_format`,format:`regex`,...QE(t),pattern:e})}function DMe(e){return new sO({check:`string_format`,format:`lowercase`,...QE(e)})}function OMe(e){return new cO({check:`string_format`,format:`uppercase`,...QE(e)})}function kMe(e,t){return new lO({check:`string_format`,format:`includes`,...QE(t),includes:e})}function AMe(e,t){return new uO({check:`string_format`,format:`starts_with`,...QE(t),prefix:e})}function jMe(e,t){return new dO({check:`string_format`,format:`ends_with`,...QE(t),suffix:e})}function Fk(e){return new fO({check:`overwrite`,tx:e})}function MMe(e){return Fk(t=>t.normalize(e))}function NMe(){return Fk(e=>e.trim())}function PMe(){return Fk(e=>e.toLowerCase())}function FMe(){return Fk(e=>e.toUpperCase())}function IMe(e,t,n){return new e({type:`array`,element:t,...QE(n)})}function LMe(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...QE(n)})}var RMe=n((()=>{pO(),lD()})),zMe=n((()=>{})),BMe=n((()=>{})),Ik=n((()=>{VE(),bD(),pD(),Kje(),pO(),_O(),lD(),YD(),Jje(),hO(),zMe(),RMe(),BMe()})),Lk=n((()=>{Ik()}));function VMe(e){return _Me(Rk,e)}function HMe(e){return vMe(zk,e)}function UMe(e){return yMe(Bk,e)}function WMe(e){return bMe(Vk,e)}var Rk,zk,Bk,Vk,Hk=n((()=>{Ik(),tj(),Rk=Q(`ZodISODateTime`,(e,t)=>{WO.init(e,t),pA.init(e,t)}),zk=Q(`ZodISODate`,(e,t)=>{GO.init(e,t),pA.init(e,t)}),Bk=Q(`ZodISOTime`,(e,t)=>{KO.init(e,t),pA.init(e,t)}),Vk=Q(`ZodISODuration`,(e,t)=>{qO.init(e,t),pA.init(e,t)})})),Uk,Wk,Gk=n((()=>{Ik(),Uk=(e,t)=>{dD.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>Bje(e,t)},flatten:{value:t=>zje(e,t)},addIssue:{value:t=>e.issues.push(t)},addIssues:{value:t=>e.issues.push(...t)},isEmpty:{get(){return e.issues.length===0}}})},Q(`ZodError`,Uk),Wk=Q(`ZodError`,Uk,{Parent:Error})})),Kk,qk,Jk,Yk,Xk=n((()=>{Ik(),Gk(),Kk=mD(Wk),qk=hD(Wk),Jk=gD(Wk),Yk=vD(Wk)}));function Zk(e){return Yje(fA,e)}function GMe(e){return xMe(NA,e)}function Qk(e){return SMe(PA,e)}function $k(e){return CMe(FA,e)}function eA(){return wMe(IA)}function KMe(e){return TMe(LA,e)}function tA(e,t){return IMe(RA,e,t)}function nA(e,t){let n={type:`object`,get shape(){return KE(this,`shape`,{...e}),this.shape},...QE(t)};return new zA(n)}function rA(e,t){return new BA({type:`union`,options:e,...QE(t)})}function qMe(e,t){return new VA({type:`intersection`,left:e,right:t})}function iA(e,t,n){return new HA({type:`record`,keyType:e,valueType:t,...QE(n)})}function aA(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new UA({type:`enum`,entries:n,...QE(t)})}function oA(e,t){return new WA({type:`literal`,values:Array.isArray(e)?e:[e],...QE(t)})}function JMe(e){return new GA({type:`transform`,transform:e})}function sA(e){return new KA({type:`optional`,innerType:e})}function cA(e){return new qA({type:`nullable`,innerType:e})}function YMe(e,t){return new JA({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():t}})}function XMe(e,t){return new YA({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():t}})}function ZMe(e,t){return new XA({type:`nonoptional`,innerType:e,...QE(t)})}function QMe(e,t){return new ZA({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}function lA(e,t){return new QA({type:`pipe`,in:e,out:t})}function $Me(e){return new $A({type:`readonly`,innerType:e})}function eNe(e){let t=new XD({check:`custom`});return t._zod.check=e,t}function tNe(e,t={}){return LMe(ej,e,t)}function nNe(e){let t=eNe(n=>(n.addIssue=e=>{if(typeof e==`string`)n.issues.push(iD(e,n.value,t._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??(r.code=`custom`),r.input??(r.input=n.value),r.inst??(r.inst=t),r.continue??(r.continue=!t._zod.def.abort),n.issues.push(iD(r))}},e(n.value,n)));return t}var uA,dA,fA,pA,mA,hA,gA,_A,vA,yA,bA,xA,SA,CA,wA,TA,EA,DA,OA,kA,AA,jA,MA,NA,PA,FA,IA,LA,RA,zA,BA,VA,HA,UA,WA,GA,KA,qA,JA,YA,XA,ZA,QA,$A,ej,tj=n((()=>{Ik(),Lk(),Hk(),Xk(),uA=Q(`ZodType`,(e,t)=>(AO.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),e.clone=(t,n)=>ZE(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.parse=(t,n)=>Kk(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Jk(e,t,n),e.parseAsync=async(t,n)=>qk(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Yk(e,t,n),e.spa=e.safeParseAsync,e.refine=(t,n)=>e.check(tNe(t,n)),e.superRefine=t=>e.check(nNe(t)),e.overwrite=t=>e.check(Fk(t)),e.optional=()=>sA(e),e.nullable=()=>cA(e),e.nullish=()=>sA(cA(e)),e.nonoptional=t=>ZMe(e,t),e.array=()=>tA(e),e.or=t=>rA([e,t]),e.and=t=>qMe(e,t),e.transform=t=>lA(e,JMe(t)),e.default=t=>YMe(e,t),e.prefault=t=>XMe(e,t),e.catch=t=>QMe(e,t),e.pipe=t=>lA(e,t),e.readonly=()=>$Me(e),e.describe=t=>{let n=e.clone();return Tk.add(n,{description:t}),n},Object.defineProperty(e,"description",{get(){return Tk.get(e)?.description},configurable:!0}),e.meta=(...t)=>{if(t.length===0)return Tk.get(e);let n=e.clone();return Tk.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),dA=Q(`_ZodString`,(e,t)=>{jO.init(e,t),uA.init(e,t);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...t)=>e.check(EMe(...t)),e.includes=(...t)=>e.check(kMe(...t)),e.startsWith=(...t)=>e.check(AMe(...t)),e.endsWith=(...t)=>e.check(jMe(...t)),e.min=(...t)=>e.check(Nk(...t)),e.max=(...t)=>e.check(Mk(...t)),e.length=(...t)=>e.check(Pk(...t)),e.nonempty=(...t)=>e.check(Nk(1,...t)),e.lowercase=t=>e.check(DMe(t)),e.uppercase=t=>e.check(OMe(t)),e.trim=()=>e.check(NMe()),e.normalize=(...t)=>e.check(MMe(...t)),e.toLowerCase=()=>e.check(PMe()),e.toUpperCase=()=>e.check(FMe())}),fA=Q(`ZodString`,(e,t)=>{jO.init(e,t),dA.init(e,t),e.email=t=>e.check(Xje(mA,t)),e.url=t=>e.check(tMe(_A,t)),e.jwt=t=>e.check(gMe(MA,t)),e.emoji=t=>e.check(nMe(vA,t)),e.guid=t=>e.check(Ek(hA,t)),e.uuid=t=>e.check(Zje(gA,t)),e.uuidv4=t=>e.check(Qje(gA,t)),e.uuidv6=t=>e.check($je(gA,t)),e.uuidv7=t=>e.check(eMe(gA,t)),e.nanoid=t=>e.check(rMe(yA,t)),e.guid=t=>e.check(Ek(hA,t)),e.cuid=t=>e.check(iMe(bA,t)),e.cuid2=t=>e.check(aMe(xA,t)),e.ulid=t=>e.check(oMe(SA,t)),e.base64=t=>e.check(pMe(kA,t)),e.base64url=t=>e.check(mMe(AA,t)),e.xid=t=>e.check(sMe(CA,t)),e.ksuid=t=>e.check(cMe(wA,t)),e.ipv4=t=>e.check(lMe(TA,t)),e.ipv6=t=>e.check(uMe(EA,t)),e.cidrv4=t=>e.check(dMe(DA,t)),e.cidrv6=t=>e.check(fMe(OA,t)),e.e164=t=>e.check(hMe(jA,t)),e.datetime=t=>e.check(VMe(t)),e.date=t=>e.check(HMe(t)),e.time=t=>e.check(UMe(t)),e.duration=t=>e.check(WMe(t))}),pA=Q(`ZodStringFormat`,(e,t)=>{MO.init(e,t),dA.init(e,t)}),mA=Q(`ZodEmail`,(e,t)=>{FO.init(e,t),pA.init(e,t)}),hA=Q(`ZodGUID`,(e,t)=>{NO.init(e,t),pA.init(e,t)}),gA=Q(`ZodUUID`,(e,t)=>{PO.init(e,t),pA.init(e,t)}),_A=Q(`ZodURL`,(e,t)=>{IO.init(e,t),pA.init(e,t)}),vA=Q(`ZodEmoji`,(e,t)=>{LO.init(e,t),pA.init(e,t)}),yA=Q(`ZodNanoID`,(e,t)=>{RO.init(e,t),pA.init(e,t)}),bA=Q(`ZodCUID`,(e,t)=>{zO.init(e,t),pA.init(e,t)}),xA=Q(`ZodCUID2`,(e,t)=>{BO.init(e,t),pA.init(e,t)}),SA=Q(`ZodULID`,(e,t)=>{VO.init(e,t),pA.init(e,t)}),CA=Q(`ZodXID`,(e,t)=>{HO.init(e,t),pA.init(e,t)}),wA=Q(`ZodKSUID`,(e,t)=>{UO.init(e,t),pA.init(e,t)}),TA=Q(`ZodIPv4`,(e,t)=>{JO.init(e,t),pA.init(e,t)}),EA=Q(`ZodIPv6`,(e,t)=>{YO.init(e,t),pA.init(e,t)}),DA=Q(`ZodCIDRv4`,(e,t)=>{XO.init(e,t),pA.init(e,t)}),OA=Q(`ZodCIDRv6`,(e,t)=>{ZO.init(e,t),pA.init(e,t)}),kA=Q(`ZodBase64`,(e,t)=>{QO.init(e,t),pA.init(e,t)}),AA=Q(`ZodBase64URL`,(e,t)=>{$O.init(e,t),pA.init(e,t)}),jA=Q(`ZodE164`,(e,t)=>{ek.init(e,t),pA.init(e,t)}),MA=Q(`ZodJWT`,(e,t)=>{tk.init(e,t),pA.init(e,t)}),NA=Q(`ZodNumber`,(e,t)=>{nk.init(e,t),uA.init(e,t),e.gt=(t,n)=>e.check(kk(t,n)),e.gte=(t,n)=>e.check(Ak(t,n)),e.min=(t,n)=>e.check(Ak(t,n)),e.lt=(t,n)=>e.check(Dk(t,n)),e.lte=(t,n)=>e.check(Ok(t,n)),e.max=(t,n)=>e.check(Ok(t,n)),e.int=t=>e.check(Qk(t)),e.safe=t=>e.check(Qk(t)),e.positive=t=>e.check(kk(0,t)),e.nonnegative=t=>e.check(Ak(0,t)),e.negative=t=>e.check(Dk(0,t)),e.nonpositive=t=>e.check(Ok(0,t)),e.multipleOf=(t,n)=>e.check(jk(t,n)),e.step=(t,n)=>e.check(jk(t,n)),e.finite=()=>e;let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null}),PA=Q(`ZodNumberFormat`,(e,t)=>{rk.init(e,t),NA.init(e,t)}),FA=Q(`ZodBoolean`,(e,t)=>{ik.init(e,t),uA.init(e,t)}),IA=Q(`ZodUnknown`,(e,t)=>{ak.init(e,t),uA.init(e,t)}),LA=Q(`ZodNever`,(e,t)=>{ok.init(e,t),uA.init(e,t)}),RA=Q(`ZodArray`,(e,t)=>{sk.init(e,t),uA.init(e,t),e.element=t.element,e.min=(t,n)=>e.check(Nk(t,n)),e.nonempty=t=>e.check(Nk(1,t)),e.max=(t,n)=>e.check(Mk(t,n)),e.length=(t,n)=>e.check(Pk(t,n)),e.unwrap=()=>e.element}),zA=Q(`ZodObject`,(e,t)=>{ck.init(e,t),uA.init(e,t),GE(e,`shape`,()=>t.shape),e.keyof=()=>aA(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:eA()}),e.loose=()=>e.clone({...e._zod.def,catchall:eA()}),e.strict=()=>e.clone({...e._zod.def,catchall:KMe()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>Fje(e,t),e.merge=t=>Ije(e,t),e.pick=t=>Nje(e,t),e.omit=t=>Pje(e,t),e.partial=(...t)=>Lje(KA,e,t[0]),e.required=(...t)=>Rje(XA,e,t[0])}),BA=Q(`ZodUnion`,(e,t)=>{lk.init(e,t),uA.init(e,t),e.options=t.options}),VA=Q(`ZodIntersection`,(e,t)=>{uk.init(e,t),uA.init(e,t)}),HA=Q(`ZodRecord`,(e,t)=>{dk.init(e,t),uA.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType}),UA=Q(`ZodEnum`,(e,t)=>{fk.init(e,t),uA.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new UA({...t,checks:[],...QE(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new UA({...t,checks:[],...QE(r),entries:i})}}),WA=Q(`ZodLiteral`,(e,t)=>{pk.init(e,t),uA.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})}),GA=Q(`ZodTransform`,(e,t)=>{mk.init(e,t),uA.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=r=>{if(typeof r==`string`)n.issues.push(iD(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??(t.code=`custom`),t.input??(t.input=n.value),t.inst??(t.inst=e),t.continue??(t.continue=!0),n.issues.push(iD(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}}),KA=Q(`ZodOptional`,(e,t)=>{hk.init(e,t),uA.init(e,t),e.unwrap=()=>e._zod.def.innerType}),qA=Q(`ZodNullable`,(e,t)=>{gk.init(e,t),uA.init(e,t),e.unwrap=()=>e._zod.def.innerType}),JA=Q(`ZodDefault`,(e,t)=>{_k.init(e,t),uA.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap}),YA=Q(`ZodPrefault`,(e,t)=>{vk.init(e,t),uA.init(e,t),e.unwrap=()=>e._zod.def.innerType}),XA=Q(`ZodNonOptional`,(e,t)=>{yk.init(e,t),uA.init(e,t),e.unwrap=()=>e._zod.def.innerType}),ZA=Q(`ZodCatch`,(e,t)=>{bk.init(e,t),uA.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap}),QA=Q(`ZodPipe`,(e,t)=>{xk.init(e,t),uA.init(e,t),e.in=t.in,e.out=t.out}),$A=Q(`ZodReadonly`,(e,t)=>{Sk.init(e,t),uA.init(e,t)}),ej=Q(`ZodCustom`,(e,t)=>{Ck.init(e,t),uA.init(e,t)})})),rNe=n((()=>{Ik()})),nj=n((()=>{Ik(),tj(),Lk(),Gk(),Xk(),rNe(),lD(),Hk(),tj()})),iNe=n((()=>{nj(),nj()})),aNe=n((()=>{iNe()})),rj,ij,aj,oj,sj,cj,lj,uj,dj,fj,oNe=n((()=>{aNe(),aA([`local`,`user`,`project`,`dynamic`,`enterprise`,`claudeai`,`managed`]),aA([`stdio`,`sse`,`sse-ide`,`http`,`ws`,`sdk`,`claudeai-proxy`]),rj=nA({type:oA(`stdio`).optional(),command:Zk().min(1,`Command cannot be empty`),args:tA(Zk()).default([]),env:iA(Zk(),Zk()).optional()}),ij=nA({clientId:Zk().optional(),callbackPort:GMe().int().positive().optional(),authServerMetadataUrl:Zk().url().startsWith(`https://`,{message:`authServerMetadataUrl must use https://`}).optional(),xaa:$k().optional()}),aj=nA({type:oA(`sse`),url:Zk(),headers:iA(Zk(),Zk()).optional(),headersHelper:Zk().optional(),oauth:ij.optional()}),oj=nA({type:oA(`sse-ide`),url:Zk(),ideName:Zk(),ideRunningInWindows:$k().optional()}),sj=nA({type:oA(`ws-ide`),url:Zk(),ideName:Zk(),authToken:Zk().optional(),ideRunningInWindows:$k().optional()}),cj=nA({type:oA(`http`),url:Zk(),headers:iA(Zk(),Zk()).optional(),headersHelper:Zk().optional(),oauth:ij.optional()}),lj=nA({type:oA(`ws`),url:Zk(),headers:iA(Zk(),Zk()).optional(),headersHelper:Zk().optional()}),uj=nA({type:oA(`sdk`),name:Zk()}),dj=nA({type:oA(`claudeai-proxy`),url:Zk(),id:Zk()}),fj=rA([rj,aj,oj,sj,cj,lj,uj,dj]),nA({mcpServers:iA(Zk(),fj)})}));function pj(e){if(typeof e==`string`)return e.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,``).replace(/\uFFFD/g,``).normalize(`NFC`);if(Array.isArray(e))return e.map(e=>pj(e));if(typeof e==`object`&&e){let t={};for(let[n,r]of Object.entries(e))t[n]=pj(r);return t}return e}var sNe=n((()=>{}));function cNe(e){return(`code`in e?e.code:void 0)===404?e.message.includes(`"code":-32001`)||e.message.includes(`"code": -32001`):!1}var mj,lNe=n((()=>{UDe(),hS(),mj=2048})),hj=n((()=>{hS()})),gj=n((()=>{hS()})),uNe=n((()=>{hj(),gj()})),dNe=n((()=>{oNe(),sNe(),lNe(),hj(),gj(),uNe()}));function fNe(e){return e.replace(/([a-z])([A-Z])/g,`$1_$2`).replace(/-/g,`_`).toLowerCase()}function pNe(e,t){let n=fNe(t);return{isSearch:_j.has(n),isRead:vj.has(n)}}var _j,vj,mNe=n((()=>{_j=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(`.`)),vj=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 hNe(e){return e.scope===`project`||e.scope===`local`}async function gNe(e,t){if(!t.headersHelper)return null;if(`scope`in t&&hNe(t)&&!vn()&&!tie())return Yn(`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 .`)),J(`tengu_mcp_headersHelper_missing_trust`,{}),null;try{K(e,`Executing headersHelper to get dynamic headers`);let n=await Gi(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=Nn(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 K(e,`Successfully retrieved ${Object.keys(r).length} headers from headersHelper`),r}catch(t){return ia(e,`Error getting headers from headersHelper: ${H(t)}`),q(Error(`Error getting MCP headers from headersHelper for server '${e}': ${H(t)}`)),null}}async function yj(e,t){let n=t.headers||{},r=await gNe(e,t)||{};return{...n,...r}}var _Ne=n((()=>{Gt(),Oi(),W(),Mn(),qi(),oa(),Zn(),Na()})),bj,vNe=n((()=>{b(),bj=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 yNe(){return parseInt(process.env.MCP_TOOL_TIMEOUT||``,10)||Jj}function xj(){return Y(p(),`mcp-needs-auth-cache.json`)}function Sj(){return Zj||(Zj=lu(xj(),`utf-8`).then(e=>Nn(e)).catch(()=>({}))),Zj}async function bNe(e){let t=(await Sj())[e];return t?Date.now()-t.timestamp<Xj:!1}function xNe(e){Qj=Qj.then(async()=>{let t=await Sj();t[e]={timestamp:Date.now()};let n=xj();await su(Tl(n),{recursive:!0}),await _u(n,V(t)),Zj=null}).catch(()=>{})}function Cj(){Zj=null,gu(xj()).catch(()=>{})}function wj(e){let t=gT(e);return t?{mcpServerBaseUrl:t}:{}}function Tj(e,t,n){return J(`tengu_mcp_server_needs_auth`,{transportType:n,...wj(t)}),K(e,`Authentication required for ${{sse:`SSE`,http:`HTTP`,"claudeai-proxy":`claude.ai proxy`}[n]} server`),xNe(e),{name:e,type:`needs-auth`,config:t}}function SNe(e){return async(t,n)=>{let r=async()=>{await zo();let r=Mo();if(!r)throw Error(`No claude.ai OAuth token available`);let i=new Headers(n?.headers);return i.set(`Authorization`,`Bearer ${r.accessToken}`),{response:await e(t,{...n,headers:i}),sentToken:r.accessToken}},{response:i,sentToken:a}=await r();if(i.status!==401)return i;let o=await ro(a).catch(()=>!1);if(J(`tengu_mcp_claudeai_proxy_401`,{tokenChanged:o}),!o){let e=Mo()?.accessToken;if(!e||e===a)return i}try{return(await r()).response}catch{return i}}}async function Ej(e,t){let n=(await import(`./wrapper-K8ZapJVu.js`)).default;return new n(e,[`mcp`],t)}function Dj(){return parseInt(process.env.MCP_TIMEOUT||``,10)||3e4}function Oj(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`,tM);let i=new AbortController,a=setTimeout(e=>e.abort(new DOMException(`The operation timed out.`,`TimeoutError`)),eM,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 kj(){return parseInt(process.env.MCP_SERVER_CONNECTION_BATCH_SIZE||``,10)||3}function CNe(){return parseInt(process.env.MCP_REMOTE_SERVER_CONNECTION_BATCH_SIZE||``,10)||20}function Aj(e){return!e.type||e.type===`stdio`||e.type===`sdk`}function wNe(e){return!e.name.startsWith(`mcp__ide__`)||nM.includes(e.name)}function jj(e,t){return`${e}-${V(t)}`}async function Mj(e,t){let n=jj(e,t);try{let n=await rM(e,t);n.type===`connected`&&await n.cleanup()}catch{}rM.cache.delete(n),aM.cache.delete(e),oM.cache.delete(e),sM.cache.delete(e)}async function Nj(e){if(e.config.type===`sdk`)return e;let t=await rM(e.name,e.config);if(t.type!==`connected`)throw new Gn(`MCP server "${e.name}" is not connected`,`MCP server not connected`);return t}function TNe(e,t){if(e.type!==t.type)return!1;let{scope:n,...r}=e,{scope:i,...a}=t;return V(r)===V(a)}function ENe(e,t){let n=Object.keys(e);return n.length>0?n.map(t=>`${t}=${String(e[t])}`).join(` `):t}async function Pj(e,t,n){return(await Uj({client:n,tool:e,args:t,signal:TE().signal})).content}async function Fj(e,t){try{Wo(),await Mj(e,t);let n=await rM(e,t);if(n.type!==`connected`)return{client:n,tools:[],commands:[]};t.type===`claudeai-proxy`&&jw(e);let r=!!n.capabilities?.resources,[i,a,o,s]=await Promise.all([aM(n),sM(n),Promise.resolve([]),r?oM(n):Promise.resolve([])]),c=[...a,...o],l=[];return r&&([QC,CE].some(e=>i.some(t=>Ys(t,e.name)))||l.push(QC,CE)),{client:n,tools:[...i,...l],commands:c,resources:s.length>0?s:void 0}}catch(n){return ia(e,`Error during reconnection: ${H(n)}`),{client:{name:e,type:`failed`,config:t},tools:[],commands:[]}}}async function Ij(e,t,n){await iue(e,n,{concurrency:t})}async function Lj(e,t){let n=!1,r=Object.entries(t??(await Qw()).servers),i=[];for(let t of r)nT(t[0])?e({client:{name:t[0],type:`disabled`,config:t[1]},tools:[],commands:[]}):i.push(t);let a=i.length,o=hr(i,([e,t])=>t.type===`stdio`),s=hr(i,([e,t])=>t.type===`sse`),c=hr(i,([e,t])=>t.type===`http`),l=hr(i,([e,t])=>t.type===`sse-ide`),u=hr(i,([e,t])=>t.type===`ws-ide`),d=i.filter(([e,t])=>Aj(t)),f=i.filter(([e,t])=>!Aj(t)),p={totalServers:a,stdioCount:o,sseCount:s,httpCount:c,sseIdeCount:l,wsIdeCount:u},m=async([t,r])=>{try{if(nT(t)){e({client:{name:t,type:`disabled`,config:r},tools:[],commands:[]});return}if((r.type===`claudeai-proxy`||r.type===`http`||r.type===`sse`)&&(await bNe(t)||(r.type===`http`||r.type===`sse`)&&oje(t,r))){K(t,`Skipping connection (cached needs-auth)`),e({client:{name:t,type:`needs-auth`,config:r},tools:[fE(t,r)],commands:[]});return}let i=await rM(t,r,p);if(i.type!==`connected`){e({client:i,tools:i.type===`needs-auth`?[fE(t,r)]:[],commands:[]});return}r.type===`claudeai-proxy`&&jw(t);let a=!!i.capabilities?.resources,[o,s,c,l]=await Promise.all([aM(i),sM(i),Promise.resolve([]),a?oM(i):Promise.resolve([])]),u=[...s,...c],d=[];a&&!n&&(n=!0,d.push(QC,CE)),e({client:i,tools:[...o,...d],commands:u,resources:l.length>0?l:void 0})}catch(n){ia(t,`Error fetching tools/commands/resources: ${H(n)}`),e({client:{name:t,type:`failed`,config:r},tools:[],commands:[]})}};await Promise.all([Ij(d,kj(),m),Ij(f,CNe(),m)])}function Rj(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=[];Lj(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);J(`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=>{ia(`prefetchAllMcpResources`,`Failed to get MCP resources: ${H(e)}`),t({clients:[],tools:[],commands:[]})})})}async function zj(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 Bj(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 Ug(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($j.has(r.mimeType??``)){let e=Buffer.from(r.blob,`base64`),t=r.mimeType?.split(`/`)[1]||`png`,a=await Ug(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 Bj(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 Bj(e,t,n,r){let i=await hE(e,t,`mcp-${di(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:gE(i.filepath,t,i.size,r)}]}function Vj(e,t=2){if(e===null)return`null`;if(Array.isArray(e))return e.length===0?`[]`:`[${Vj(e[0],t-1)}]`;if(typeof e==`object`){if(t<=0)return`{...}`;let n=Object.entries(e).slice(0,10).map(([e,n])=>`${e}: ${Vj(n,t-1)}`),r=Object.keys(e).length>10?`, ...`:``;return`{${n.join(`, `)}${r}}`}return typeof e}async function DNe(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:V(e.structuredContent),type:`structuredContent`,schema:Vj(e.structuredContent)};if(`content`in e&&Array.isArray(e.content)){let t=(await Promise.all(e.content.map(e=>zj(e,n,r,!0)))).flat();return{content:t,type:`contentArray`,schema:Vj(t)}}}let i=`MCP server "${n}" tool "${t}": unexpected response format`;throw ia(n,i),new Gn(i,`MCP tool unexpected response format`)}function Hj(e){return!e||typeof e==`string`?!1:e.some(e=>e.type===`image`)}async function ONe(e,t,n,r,i=!1){let{content:a,type:o,schema:s}=await DNe(e,t,n,r);if(n===`ide`||i&&!Hj(a)||!await vke(a))return a;let c=tw(a);if(f(process.env.ENABLE_MCP_LARGE_OUTPUT_FILES))return J(`tengu_mcp_large_result_handled`,{outcome:`truncated`,reason:`env_disabled`,sizeEstimateTokens:c}),await bke(a);if(!a)return a;if(Hj(a))return J(`tengu_mcp_large_result_handled`,{outcome:`truncated`,reason:`contains_images`,sizeEstimateTokens:c}),await bke(a);let l=Date.now(),u=`mcp-${di(n)}-${di(t)}-${l}`,d=ANe(a),p=typeof a==`string`?a:d??V(a,null,2),m=await ey(p,u);if(iy(m)){let e=p.length;return J(`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.`}J(`tengu_mcp_large_result_handled`,{outcome:`persisted`,reason:`file_saved`,sizeEstimateTokens:c,persistedSizeChars:m.originalSize});let h=d===void 0?mE(o,s):mE(`toolResult`);return mje(m.filepath,m.originalSize,h)}function kNe(){let e=process.env.MCP_TRUNCATION_PROMPT_OVERRIDE;return e?e!==`legacy`:!1}function ANe(e){if(!kNe()||!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 jNe({client:e,clientConnection:t,tool:n,args:r,meta:i,signal:a,setAppState:o,onProgress:s,imageLimits:c,hasResultSizeAnnotation:l=!1,callToolFn:u=Uj,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 mS)||e.code!==sx.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 K(s,`Tool '${n}' returned -32042 but no valid elicitations in error data`),e;K(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 FE(s,e,a);if(r){if(K(s,`URL elicitation ${t} resolved by hook: ${V(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 IE(s,i,a,`url`,t);if(c.action!==`accept`)return K(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.`};K(s,`Elicitation ${t} completed, retrying tool call`)}}}async function Uj({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{K(t,`Calling MCP tool: ${r}`),d=setInterval((e,t,n)=>{let r=Date.now()-e;K(t,`Tool '${n}' still running (${`${Math.floor(r/1e3)}s`} elapsed)`)},3e4,u,t,r);let n=yNe(),f,p=new Promise((e,i)=>{f=setTimeout((e,t,n,r)=>{e(new Gn(`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},$x,{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 ia(t,e),new Kj(e,`MCP tool returned error`,`_meta`in m&&m._meta?{_meta:m._meta}:void 0)}let h=Date.now()-u;K(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=wje(t);return g&&J(`tengu_code_indexing_tool_used`,{tool:g,source:`mcp`,success:!0}),{content:await ONe(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`&&K(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 zC)throw K(t,`Tool call returned 401 Unauthorized - token may have expired`),J(`tengu_mcp_tool_call_auth_error`,{}),new Wj(t,`MCP server "${t}" requires re-authorization (token expired)`);let r=qj(e),i=`code`in e&&e.code===-32e3&&e.message.includes(`Connection closed`)&&(n.type===`http`||n.type===`claudeai-proxy`);if(r||i)throw K(t,`MCP session expired during tool call (${r?`404/-32001`:`connection closed`}), clearing connection cache for re-initialization`),J(`tengu_mcp_session_expired`,{}),await Mj(t,n),new Gj(t)}if(!(e instanceof Error)||e.name!==`AbortError`)throw e;return{content:void 0}}finally{d!==void 0&&clearInterval(d)}}function MNe(e){let t=e.message.content?.[0];if(!(!t||typeof t==`string`||t.type!==`tool_use`))return t.id}async function NNe(e,t){let n=[],r=[],i=await Promise.allSettled(Object.entries(e).map(async([e,n])=>{let r=new bj(e,t),i=new bS({name:`workmate`,title:`Work Mate`,version:`0.0.17`,description:`Agentic coding tool`,websiteUrl:JC},{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 aM(a);o.push(...e)}return{client:a,tools:o}}catch(t){return ia(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 Wj,Gj,Kj,qj,Jj,Yj,Xj,Zj,Qj,$j,eM,tM,nM,rM,iM,aM,oM,sM,cM=n((()=>{UDe(),ROe(),KOe(),XOe(),iC(),hS(),qp(),d(),Y_e(),aue(),Gt(),Ga(),YC(),Zs(),$C(),Pke(),pje(),wE(),OE(),Tr(),Do(),Xn(),jE(),W(),h(),Mn(),Sae(),GM(),r_(),oa(),_E(),Ske(),Tje(),ma(),_se(),tc(),kse(),Qc(),sy(),Na(),LE(),Zr(),si(),_T(),dNe(),b(),HC(),mNe(),Oae(),Bo(),dE(),Fw(),sT(),_Ne(),vNe(),Zn(),Wj=class extends Error{constructor(e,t){super(t),x(this,`serverName`,void 0),this.name=`McpAuthError`,this.serverName=e}},Gj=class extends Error{constructor(e){super(`MCP server "${e}" session expired`),this.name=`McpSessionExpiredError`}},Kj=class extends Gn{constructor(e,t,n){super(e,t),x(this,`mcpMeta`,void 0),this.mcpMeta=n,this.name=`McpToolCallError`}},qj=cNe,Jj=1e8,Yj=mj,Xj=900*1e3,Zj=null,Qj=Promise.resolve(),$j=new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]),eM=6e4,tM=`application/json, text/event-stream`,nM=[`mcp__ide__executeCode`,`mcp__ide__getDiagnostics`],rM=u(async(e,t,n)=>{let r=Date.now();try{let i,a=ic();if(t.type===`sse`){let n=new uE(e,t),r=await yj(e,t),a={authProvider:n,fetch:Oj(tE(rC(),n)),requestInit:{headers:{"User-Agent":yo(),...r}}};a.eventSourceInit={fetch:async(e,t)=>{let i={},a=await n.tokens();a&&(i.Authorization=`Bearer ${a.access_token}`);let o=ec();return fetch(e,{...t,...o,headers:{"User-Agent":yo(),...i,...t?.headers,...r,Accept:`text/event-stream`}})}},i=new UC(new URL(t.url),a),K(e,`SSE transport initialized, awaiting connection`)}else if(t.type===`sse-ide`){K(e,`Setting up SSE-IDE transport to ${t.url}`);let n=ec(),r=n.dispatcher?{eventSourceInit:{fetch:async(e,t)=>fetch(e,{...t,...n,headers:{"User-Agent":yo(),...t?.headers}})}}:{};i=new UC(new URL(t.url),Object.keys(r).length>0?r:void 0)}else if(t.type===`ws-ide`){let e=vse(),n={"User-Agent":yo(),...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:gse(t.url),tls:e||void 0}):await Ej(t.url,{headers:n,agent:bse(t.url),...e||{}}),i=new PE(r)}else if(t.type===`ws`){K(e,`Initializing WebSocket transport to ${t.url}`);let n=await yj(e,t),r=vse(),o={"User-Agent":yo(),...a&&{Authorization:`Bearer ${a}`},...n},s=Kp(o,(e,t)=>t.toLowerCase()===`authorization`?`[REDACTED]`:e);K(e,`WebSocket transport options: ${V({url:t.url,headers:s,hasSessionAuth:!!a})}`);let c;c=typeof Bun<`u`?new globalThis.WebSocket(t.url,{protocols:[`mcp`],headers:o,proxy:gse(t.url),tls:r||void 0}):await Ej(t.url,{headers:o,agent:bse(t.url),...r||{}}),i=new PE(c)}else if(t.type===`http`){K(e,`Initializing HTTP transport to ${t.url}`),K(e,`Node version: ${process.version}, Platform: ${process.platform}`),K(e,`Environment: ${V({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=new uE(e,t),r=await yj(e,t),o=!!await n.tokens(),s=ec();K(e,`Proxy options: ${s.dispatcher?`custom dispatcher`:`default`}`);let c={authProvider:n,fetch:Oj(tE(rC(),n)),requestInit:{...s,headers:{"User-Agent":yo(),...a&&!o&&{Authorization:`Bearer ${a}`},...r}}},l=c.requestInit?.headers?Kp(c.requestInit.headers,(e,t)=>t.toLowerCase()===`authorization`?`[REDACTED]`:e):void 0;K(e,`HTTP transport options: ${V({url:t.url,headers:l,hasAuthProvider:!!n,timeoutMs:eM})}`),i=new KC(new URL(t.url),c),K(e,`HTTP transport created successfully`)}else if(t.type===`sdk`)throw Error(`SDK servers should be handled in print.ts`);else if(t.type===`claudeai-proxy`){if(K(e,`Initializing claude.ai proxy transport for server ${t.id}`),!Mo())throw Error(`No claude.ai OAuth token found`);let n=Wa(),r=`${n.MCP_PROXY_URL}${n.MCP_PROXY_PATH.replace(`{server_id}`,t.id)}`;K(e,`Using claude.ai proxy at ${r}`);let a=SNe(globalThis.fetch),o=ec(),s={fetch:Oj(a),requestInit:{...o,headers:{"User-Agent":yo(),"X-Mcp-Client-Session-Id":ln()}}};i=new KC(new URL(r),s),K(e,`claude.ai proxy transport created successfully`)}else if(t.type===`stdio`||!t.type){let e=t;i=new GOe({command:process.env.CLAUDE_CODE_SHELL_PREFIX||e.command,args:process.env.CLAUDE_CODE_SHELL_PREFIX?[[e.command,...e.args].join(` `)]:e.args,env:{...Zc(),...e.env},stderr:`pipe`})}else throw Error(`Unsupported server type: ${t.type}`);let o,s=``;if(t.type===`stdio`||!t.type){let e=i;e.stderr&&(o=e=>{if(s.length<64*1024*1024)try{s+=e.toString()}catch{}},e.stderr.on(`data`,o))}let c=new bS({name:`workmate`,title:`Work Mate`,version:`0.0.17`,description:`Agentic coding tool`,websiteUrl:JC},{capabilities:{roots:{},elicitation:{}}});if(t.type===`http`&&K(e,`Client created, setting up request handler`),c.setRequestHandler(fS,async()=>(K(e,`Received ListRoots request from server`),{roots:[{uri:`file://${Zt()}`}]})),K(e,`Starting connection with timeout of ${Dj()}ms`),t.type===`http`){K(e,`Testing basic HTTP connectivity to ${t.url}`);try{let n=new URL(t.url);K(e,`Parsed URL: host=${n.hostname}, port=${n.port||`default`}, protocol=${n.protocol}`),(n.hostname===`127.0.0.1`||n.hostname===`localhost`)&&K(e,`Using loopback address: ${n.hostname}`)}catch(t){K(e,`Failed to parse URL: ${t}`)}}let l=c.connect(i),u=new Promise((t,n)=>{let a=setTimeout(()=>{K(e,`Connection timeout triggered after ${Date.now()-r}ms (limit: ${Dj()}ms)`),i.close().catch(()=>{}),n(new Gn(`MCP server "${e}" connection timed out after ${Dj()}ms`,`MCP connection timeout`))},Dj());l.then(()=>{clearTimeout(a)},e=>{clearTimeout(a)})});try{await Promise.race([l,u]),s&&(ia(e,`Server stderr: ${s}`),s=``);let n=Date.now()-r;K(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(K(e,`SSE Connection failed after ${a}ms: ${V({url:t.url,error:n.message,errorType:n.constructor.name,stack:n.stack})}`),ia(e,n),n instanceof zC)return Tj(e,t,`sse`)}else if(t.type===`http`&&n instanceof Error){let r=n;if(K(e,`HTTP Connection failed after ${a}ms: ${n.message} (code: ${r.code||`none`}, errno: ${r.errno||`none`})`),ia(e,n),n instanceof zC)return Tj(e,t,`http`)}else if(t.type===`claudeai-proxy`&&n instanceof Error){if(K(e,`claude.ai proxy connection failed after ${a}ms: ${n.message}`),ia(e,n),n.code===401)return Tj(e,t,`claudeai-proxy`)}else(t.type===`sse-ide`||t.type===`ws-ide`)&&J(`tengu_mcp_ide_server_connection_failed`,{connectionDurationMs:a});throw i.close().catch(()=>{}),s&&ia(e,`Server stderr: ${s}`),n}let d=c.getServerCapabilities(),f=c.getServerVersion(),p=c.getInstructions(),m=p;if(p&&p.length>Yj&&(m=`${p.slice(0,Yj)}… [truncated]`,K(e,`Server instructions truncated from ${p.length} to ${Yj} chars`)),K(e,`Connection established with capabilities: ${V({hasTools:!!d?.tools,hasPrompts:!!d?.prompts,hasResources:!!d?.resources,hasResourceSubscribe:!!d?.resources?.subscribe,serverVersion:f||`unknown`})}`),U(`[MCP] Server "${e}" connected with subscribe=${!!d?.resources?.subscribe}`),c.setRequestHandler(cS,async t=>(K(e,`Elicitation request received during initialization: ${V(t)}`),{action:`cancel`})),t.type===`sse-ide`||t.type===`ws-ide`){J(`tengu_mcp_ide_server_connection_succeeded`,{connectionDurationMs:Date.now()-r,serverVersion:f});try{JNe(c)}catch(t){ia(e,`Failed to send ide_connected notification: ${t}`)}}let h=Date.now(),g=!1,_=c.onerror,v=c.onclose,y=0,b=!1,x=t=>{b||(b=!0,K(e,`Closing transport (${t})`),c.close().catch(t=>{K(e,`Error during close: ${H(t)}`)}))},S=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`);c.onerror=n=>{let r=Date.now()-h;g=!0;let i=t.type||`stdio`;if(K(e,`${i.toUpperCase()} connection dropped after ${Math.floor(r/1e3)}s uptime`),n.message&&(n.message.includes(`ECONNRESET`)?K(e,`Connection reset - server may have crashed or restarted`):n.message.includes(`ETIMEDOUT`)?K(e,`Connection timeout - network issue or server unresponsive`):n.message.includes(`ECONNREFUSED`)?K(e,`Connection refused - server may be down`):n.message.includes(`EPIPE`)?K(e,`Broken pipe - server closed connection unexpectedly`):n.message.includes(`EHOSTUNREACH`)?K(e,`Host unreachable - network connectivity issue`):n.message.includes(`ESRCH`)?K(e,`Process not found - stdio server process terminated`):n.message.includes(`spawn`)?K(e,`Failed to spawn process - check command and permissions`):K(e,`Connection error: ${n.message}`)),(i===`http`||i===`claudeai-proxy`)&&qj(n)){K(e,`MCP session expired (server returned 404 with session-not-found), triggering reconnection`),x(`session expired`),_&&_(n);return}if(i===`sse`||i===`http`||i===`claudeai-proxy`){if(n.message.includes(`Maximum reconnection attempts`)){x(`SSE reconnection exhausted`),_&&_(n);return}S(n.message)?(y++,K(e,`Terminal connection error ${y}/3`),y>=3&&(y=0,x(`max consecutive terminal errors`))):y=0}_&&_(n)},c.onclose=()=>{let n=Date.now()-h;K(e,`${(t.type??`unknown`).toUpperCase()} connection closed after ${Math.floor(n/1e3)}s (${g?`with errors`:`cleanly`})`);let r=jj(e,t);aM.cache.delete(e),oM.cache.delete(e),sM.cache.delete(e),rM.cache.delete(r),K(e,`Cleared connection cache for reconnection`),v&&v()};let C=async()=>{if(o&&(t.type===`stdio`||!t.type)&&i.stderr?.off(`data`,o),t.type===`stdio`)try{let t=i.pid;if(t){K(e,`Sending SIGINT to MCP server process`);try{process.kill(t,`SIGINT`)}catch(t){K(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),K(e,`MCP server process exited cleanly`),n())}},50),a=setTimeout(()=>{r||(r=!0,clearInterval(i),K(e,`Cleanup timeout reached, stopping process monitoring`),n())},600);try{if(await Ho(100),!r){try{process.kill(t,0),K(e,`SIGINT failed, sending SIGTERM to MCP server process`);try{process.kill(t,`SIGTERM`)}catch(t){K(e,`Error sending SIGTERM: ${t}`),r=!0,clearInterval(i),clearTimeout(a),n();return}}catch{r=!0,clearInterval(i),clearTimeout(a),n();return}if(await Ho(400),!r)try{process.kill(t,0),K(e,`SIGTERM failed, sending SIGKILL to MCP server process`);try{process.kill(t,`SIGKILL`)}catch(t){K(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){K(e,`Error terminating process: ${t}`)}try{await c.close()}catch(t){K(e,`Error closing client: ${t}`)}},w=qn(C),T=async()=>{w?.(),await C()};return J(`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,...wj(t)}),{name:e,client:c,type:`connected`,capabilities:d??{},serverInfo:f,instructions:m,config:t,cleanup:T}}catch(i){let a=Date.now()-r;return J(`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`,...wj(t)}),K(e,`Connection failed after ${a}ms: ${H(i)}`),ia(e,`Connection failed: ${H(i)}`),{name:e,type:`failed`,config:t,error:H(i)}}},jj),iM=20,aM=pa(async e=>{if(e.type!==`connected`)return[];try{if(!e.capabilities?.tools)return[];let t=pj((await e.client.request({method:`tools/list`},Qx)).tools),n=e.config.type===`sdk`&&m(process.env.CLAUDE_AGENT_SDK_MCP_NO_PREFIX);return t.map(t=>{let r=kne(e.name,t.name);return{...Nke,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>Yj?`${e.slice(0,Yj)}… [truncated]`:e},isConcurrencySafe(){return t.annotations?.readOnlyHint??!1},isReadOnly(){return t.annotations?.readOnlyHint??!1},toAutoClassifierInput(e){return ENe(e,t.name)},isDestructive(){return t.annotations?.destructiveHint??!1},isOpenWorld(){return t.annotations?.openWorldHint??!1},isSearchOrReadCommand(){return pNe(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=MNe(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 jNe({client:await Nj(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 Gj&&i<1){K(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 Gn)){let e=n.constructor.name;if(e===`Error`)throw new Gn(n.message,n.message.slice(0,200));if(e===`McpError`&&`code`in n&&typeof n.code==`number`)throw new Gn(n.message,`McpError ${n.code}`)}throw n}},userFacingName(){let n=t.annotations?.title||t.name;return`${e.name} - ${n} (MCP)`}}}).filter(wNe)}catch(t){return ia(e.name,`Failed to fetch tools: ${H(t)}`),[]}},e=>e.name,iM),oM=pa(async e=>{if(e.type!==`connected`)return[];try{if(!e.capabilities?.resources)return[];let t=await e.client.request({method:`resources/list`},Rx);return t.resources?t.resources.map(t=>({...t,server:e.name})):[]}catch(t){return ia(e.name,`Failed to fetch resources: ${H(t)}`),[]}},e=>e.name,iM),sM=pa(async e=>{if(e.type!==`connected`)return[];try{if(!e.capabilities?.prompts)return[];let t=await e.client.request({method:`prompts/list`},Ux);return t.prompts?pj(t.prompts).map(t=>{let n=Object.values(t.arguments??{}).map(e=>e.name);return{type:`prompt`,name:`mcp__${di(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 Nj(e),a=await r.client.getPrompt({name:t.name,arguments:J_e(n,i)});return(await Promise.all(a.messages.map(e=>zj(e.content,r.name)))).flat()}catch(n){throw ia(e.name,`Error running command '${t.name}': ${H(n)}`),n}}}}):[]}catch(t){return ia(e.name,`Failed to fetch commands: ${H(t)}`),[]}},e=>e.name,iM)}));function PNe(e){let t=yl(),n=[],r=uM[e.toLowerCase()];if(!r)return n;let i=process.env.APPDATA||Y(t,`AppData`,`Roaming`),a=process.env.LOCALAPPDATA||Y(t,`AppData`,`Local`);switch(bl()){case`darwin`:n.push(Y(t,`Library`,`Application Support`,`JetBrains`),Y(t,`Library`,`Application Support`)),e.toLowerCase()===`androidstudio`&&n.push(Y(t,`Library`,`Application Support`,`Google`));break;case`win32`:n.push(Y(i,`JetBrains`),Y(a,`JetBrains`),Y(i)),e.toLowerCase()===`androidstudio`&&n.push(Y(a,`Google`));break;case`linux`:n.push(Y(t,`.config`,`JetBrains`),Y(t,`.local`,`share`,`JetBrains`));for(let e of r)n.push(Y(t,`.${e}`));e.toLowerCase()===`androidstudio`&&n.push(Y(t,`.config`,`Google`));break;default:break}return n}async function FNe(e){let t=[],n=G(),r=PNe(e),i=uM[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=Y(e,a.name);if(bl()===`linux`){t.push(r);continue}let o=Y(r,`plugins`);try{await n.stat(o),t.push(o)}catch{}}}catch{}return t.filter((e,n)=>t.indexOf(e)===n)}async function INe(e){let t=await FNe(e);for(let e of t){let t=Y(e,lM);try{return await G().stat(t),!0}catch{}}return!1}async function LNe(e,t=!1){if(!t){let t=fM.get(e);if(t)return t}let n=INe(e).then(t=>(dM.set(e,t),t));return fM.set(e,n),n}async function RNe(e,t=!1){return t&&(dM.delete(e),fM.delete(e)),LNe(e,t)}var lM,uM,dM,fM,zNe=n((()=>{Un(),lM=`claude-code-jetbrains-plugin`,uM={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`]},dM=new Map,fM=new Map}));function BNe(e,t){let n=e.match(/^\\\\wsl(?:\.localhost|\$)\\([^\\]+)(.*)$/);return!n||n[1]===t}var pM,mM=n((()=>{b(),pM=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 vu(`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 vu(`wslpath`,[`-w`,e],{encoding:`utf8`,stdio:[`pipe`,`pipe`,`ignore`]}).trim()}catch{return e}}}}));function VNe({onDone:e,installationStatus:t}){UNe(),be({"confirm:yes":e,"confirm:no":e},{context:`Confirmation`});let n=t?.ideType??bM(),r=yM(n),i=MM(n),a=t?.installedVersion,o=r?`plugin`:`extension`,s=pr.platform===`darwin`?`Cmd+Option+K`:`Ctrl+Alt+K`;return(0,hM.jsxs)(hM.Fragment,{children:[(0,hM.jsx)($e,{title:(0,hM.jsxs)(hM.Fragment,{children:[(0,hM.jsx)(F,{color:`claude`,children:`✻ `}),(0,hM.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,hM.jsxs)(P,{flexDirection:`column`,gap:1,children:[(0,hM.jsxs)(F,{children:[`• Work Mate has context of `,(0,hM.jsx)(F,{color:`suggestion`,children:`⧉ open files`}),` and`,` `,(0,hM.jsx)(F,{color:`suggestion`,children:`⧉ selected lines`})]}),(0,hM.jsxs)(F,{children:[`• Review Work Mate's changes `,(0,hM.jsx)(F,{color:`diffAddedWord`,children:`+11`}),` `,(0,hM.jsx)(F,{color:`diffRemovedWord`,children:`-22`}),` in the comfort of your IDE`]}),(0,hM.jsxs)(F,{children:[`• Cmd+Esc`,(0,hM.jsx)(F,{dimColor:!0,children:` for Quick Launch`})]}),(0,hM.jsxs)(F,{children:[`• `,s,(0,hM.jsx)(F,{dimColor:!0,children:` to reference files or lines in your input`})]})]})}),(0,hM.jsx)(P,{paddingX:1,children:(0,hM.jsx)(F,{dimColor:!0,italic:!0,children:`Press Enter to continue`})})]})}function HNe(){let e=Di(),t=Xc.terminal||`unknown`;return e.hasIdeOnboardingBeenShown?.[t]===!0}function UNe(){if(HNe())return;let e=Xc.terminal||`unknown`;Ni(t=>({...t,hasIdeOnboardingBeenShown:{...t.hasIdeOnboardingBeenShown,[e]:!0}}))}var hM,gM=n((()=>{Wc(),I(),My(),Oi(),Pr(),GM(),hM=tt()}));function _M(e){try{return process.kill(e,0),!0}catch{return!1}}function WNe(){let e=null;return()=>(e||(e=nce(process.ppid,10).then(e=>new Set(e))),e)}function vM(e){if(!e)return!1;let t=FM[e];return t&&t.ideKind===`vscode`}function yM(e){if(!e)return!1;let t=FM[e];return t&&t.ideKind===`jetbrains`}function bM(){return RM()?pr.terminal:null}async function xM(){try{let e=await GNe();return(await Promise.all(e.map(async e=>{try{let t=(await G().readdir(e)).filter(e=>e.name.endsWith(`.lock`));return(await Promise.all(t.map(async t=>{let n=Y(e,t.name);try{return{path:n,mtime:(await G().stat(n)).mtime}}catch{return null}}))).filter(e=>e!==null)}catch(e){return In(e)||q(e),[]}}))).flat().sort((e,t)=>t.mtime.getTime()-e.mtime.getTime()).map(e=>e.path)}catch(e){return q(e),[]}}async function SM(e){try{let t=await G().readFile(e,{encoding:`utf-8`}),n=[],r,i,a=!1,o=!1,s;try{let e=Nn(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(`
|
|
669
|
+
`).map(e=>e.trim())}let c=e.split(Nl).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 q(e),null}}async function CM(e,t,n=500){try{return new Promise(r=>{let i=zle({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 GNe(){let e=[Y(p(),`ide`)];if(_a()!==`wsl`)return e;let t=await zM();if(t){let n=new pM(process.env.WSL_DISTRO_NAME).toLocalPath(t);e.push(Ml(n,`.workmate`,`ide`))}try{let t=`/mnt/c/Users`,n=await G().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(Y(t,r.name,`.workmate`,`ide`))}catch(e){In(e)?U(`WSL IDE lockfile path detection failed (${e.code}): ${H(e)}`):q(e)}return e}async function KNe(){try{let e=await xM();for(let t of e){let e=await SM(t);if(!e){try{await G().unlink(t)}catch(e){q(e)}continue}let n=await WM(e.runningInWindows,e.port),r=!1;if(e.pid?_M(e.pid)||_a()===`wsl`&&await CM(n,e.port)||(r=!0):await CM(n,e.port)||(r=!0),r)try{await G().unlink(t)}catch(e){q(e)}}}catch(e){q(e)}}async function qNe(e){try{let t=await XNe(e);return J(`tengu_ext_installed`,{}),Di().diffTool||Ni(e=>({...e,diffTool:`auto`})),{installed:!0,error:null,installedVersion:t,ideType:e}}catch(t){J(`tengu_ext_install_error`,{});let n=t instanceof Error?t.message:String(t);return q(t),{installed:!1,error:n,installedVersion:null,ideType:e}}}async function wM(){BM&&BM.abort(),BM=TE();let e=BM.signal;await KNe();let t=Date.now();for(;Date.now()-t<3e4&&!e.aborted;){if(fte()){await Ho(1e3,e);continue}let t=await TM(!1);if(e.aborted)return null;if(t.length===1)return t[0];await Ho(1e3,e)}return null}async function TM(e){let t=[];try{let n=process.env.CLAUDE_CODE_SSE_PORT,r=n?parseInt(n,10):null,i=Zt().normalize(`NFC`),a=await xM(),o=await Promise.all(a.map(SM)),s=WNe(),c=_a()!==`wsl`&&RM();for(let n of o){if(!n)continue;let a=!1;if(a=m(process.env.CLAUDE_CODE_IDE_SKIP_VALID_CHECK)?!0:n.port===r||n.workspaceFolders.some(e=>{if(!e)return!1;let t=e;if(_a()===`wsl`&&n.runningInWindows&&process.env.WSL_DISTRO_NAME){if(!BNe(e,process.env.WSL_DISTRO_NAME))return!1;let n=Ml(t).normalize(`NFC`);if(i===n||i.startsWith(n+Nl))return!0;t=new pM(process.env.WSL_DISTRO_NAME).toLocalPath(e)}let r=Ml(t).normalize(`NFC`);if(_a()===`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+Nl)}return i===r||i.startsWith(r+Nl)}),!a&&!e||c&&!(r!==null&&n.port===r)&&(!n.pid||!_M(n.pid)||process.ppid!==n.pid&&!(await s()).has(n.pid)))continue;let o=n.ideName??(RM()?MM(Xc.terminal):`IDE`),l=await WM(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){q(e)}return t}async function JNe(e){await e.notification({method:`ide_connected`,params:{pid:process.pid}})}function YNe(e){return e.some(e=>e.type===`connected`&&e.name===`ide`)}async function EM(e){if(vM(e)){let t=await kM(e);if(t)try{if((await Gi(t,[`--list-extensions`],{env:DM()})).stdout?.includes(VM))return!0}catch{}}else if(yM(e))return await RNe(e);return!1}async function XNe(e){if(vM(e)){let t=await kM(e);if(t){let e=await ZNe(t);if(!e||zse(e,OM())){await Ho(500);let n=await Gi(t,[`--force`,`--install-extension`,`anthropic.claude-code`],{env:DM()});if(n.code!==0)throw Error(`${n.code}: ${n.error} ${n.stderr}`);e=OM()}return e}}return null}function DM(){if(_a()===`linux`)return{...process.env,DISPLAY:``}}function OM(){return`0.0.17`}async function ZNe(e){let{stdout:t}=await Ji(e,[`--list-extensions`,`--show-versions`],{env:DM()}),n=t?.split(`
|
|
670
670
|
`)||[];for(let e of n){let[t,n]=e.split(`@`);if(t===`anthropic.claude-code`&&n)return n}return null}function QNe(){try{if(_a()!==`macos`)return null;let e=process.ppid;for(let t=0;t<10&&!(!e||e===0||e===1);t++){let t=gie(`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=gie(`ps -o ppid= -p ${e}`)?.trim();if(!n)break;e=parseInt(n.trim(),10)}return null}catch{return null}}async function kM(e){let t=QNe();if(t)try{return await G().stat(t),t}catch{}let n=_a()===`windows`?`.cmd`:``;switch(e){case`vscode`:return`code${n}`;case`cursor`:return`cursor${n}`;case`windsurf`:return`windsurf${n}`;default:break}return null}async function $Ne(){return(await Ji(`cursor`,[`--version`])).code===0}async function ePe(){return(await Ji(`windsurf`,[`--version`])).code===0}async function tPe(){let e=await Ji(`code`,[`--help`]);return e.code===0&&!!e.stdout?.includes(`Visual Studio Code`)}async function nPe(){let e=[];try{let t=_a();if(t===`macos`){let t=(await Ki(`ps aux | grep -E "Visual Studio Code|Code Helper|Cursor Helper|Windsurf Helper|IntelliJ IDEA|PyCharm|WebStorm|PhpStorm|RubyMine|CLion|GoLand|Rider|DataGrip|AppCode|DataSpell|Aqua|Gateway|Fleet|Android Studio" | grep -v grep`,{shell:!0,reject:!1})).stdout??``;for(let[n,r]of Object.entries(FM))for(let i of r.processKeywordsMac)if(t.includes(i)){e.push(n);break}}else if(t===`windows`){let t=((await Ki(`tasklist | findstr /I "Code.exe Cursor.exe Windsurf.exe idea64.exe pycharm64.exe webstorm64.exe phpstorm64.exe rubymine64.exe clion64.exe goland64.exe rider64.exe datagrip64.exe appcode.exe dataspell64.exe aqua64.exe gateway64.exe fleet.exe studio64.exe"`,{shell:!0,reject:!1})).stdout??``).toLowerCase();for(let[n,r]of Object.entries(FM))for(let i of r.processKeywordsWindows)if(t.includes(i.toLowerCase())){e.push(n);break}}else if(t===`linux`){let t=((await Ki(`ps aux | grep -E "code|cursor|windsurf|idea|pycharm|webstorm|phpstorm|rubymine|clion|goland|rider|datagrip|dataspell|aqua|gateway|fleet|android-studio" | grep -v grep`,{shell:!0,reject:!1})).stdout??``).toLowerCase();for(let[n,r]of Object.entries(FM))for(let i of r.processKeywordsLinux)if(t.includes(i)){if(n!==`vscode`){e.push(n);break}else if(!t.includes(`cursor`)&&!t.includes(`appcode`)){e.push(n);break}}}}catch(e){q(e)}return e}async function rPe(){let e=await nPe();return HM=e,e}async function iPe(){return HM===null?rPe():HM}function AM(e){return jM(e.find(e=>e.type===`connected`&&e.name===`ide`))}function jM(e){let t=e?.config;return t?.type===`sse-ide`||t?.type===`ws-ide`?t.ideName:RM()?MM(Xc.terminal):null}function MM(e){if(!e)return`IDE`;let t=FM[e];if(t)return t.displayName;let n=UM[e.toLowerCase().trim()];if(n)return n;let r=e.split(` `)[0],i=r?wl(r).toLowerCase():null;return i?UM[i]||zp(i):zp(e)}function NM(e){if(!e)return;let t=e.find(e=>e.type===`connected`&&e.name===`ide`);return t?.type===`connected`?t:void 0}async function aPe(e){try{await Pj(`closeAllDiffTabs`,{},e)}catch{}}async function oPe(e,t,n,r){wM().then(e);let i=Di().autoInstallIdeExtension??!0;if(!m(process.env.CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL)&&i){let i=t??bM();i&&(vM(i)?EM(i).then(async t=>{qNe(i).catch(e=>({installed:!1,error:e.message||`Installation failed`,installedVersion:null,ideType:i})).then(i=>{r(i),i?.installed&&wM().then(e),!t&&i?.installed===!0&&!PM().hasIdeOnboardingDialogBeenShown()&&n()})}):yM(i)&&EM(i).then(async e=>{e&&!PM().hasIdeOnboardingDialogBeenShown()&&n()}))}}var PM,FM,IM,LM,RM,zM,BM,VM,HM,UM,WM,GM=n((()=>{Wi(),Bp(),d(),Na(),Gt(),cM(),Oi(),Pr(),h(),qi(),Un(),zc(),zNe(),oa(),va(),_c(),OE(),W(),Wc(),Mn(),mM(),Bo(),Zn(),PM=()=>gM(),FM={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`]}},IM=u(()=>vM(pr.terminal)),LM=u(()=>yM(Xc.terminal)),RM=u(()=>IM()||LM()||!!process.env.FORCE_CODE_TERMINAL),zM=u(async()=>{if(process.env.USERPROFILE)return process.env.USERPROFILE;let{stdout:e,code:t}=await Ji(`powershell.exe`,[`-NoProfile`,`-NonInteractive`,`-Command`,`$env:USERPROFILE`]);if(t===0&&e.trim())return e.trim();U(`Unable to get Windows USERPROFILE via PowerShell - IDE detection may be incomplete`)}),BM=null,VM=`anthropic.claude-code`,HM=null,UM={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`},WM=u(async(e,t)=>{if(process.env.CLAUDE_CODE_IDE_HOST_OVERRIDE)return process.env.CLAUDE_CODE_IDE_HOST_OVERRIDE;if(_a()!==`wsl`||!e)return`127.0.0.1`;try{let e=await Ki(`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 CM(e,t))return e}}}catch{}return`127.0.0.1`},(e,t)=>`${e}:${t}`)}));function KM(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}function qM(e){nN=e}function JM(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(aN.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}function YM(e,t){if(t){if(aN.escapeTest.test(e))return e.replace(aN.escapeReplace,fP)}else if(aN.escapeTestNoEncode.test(e))return e.replace(aN.escapeReplaceNoEncode,fP);return e}function XM(e){try{e=encodeURI(e).replace(aN.percentDecode,`%`)}catch{return null}return e}function ZM(e,t){let n=e.replace(aN.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split(aN.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(aN.slashPipe,`|`);return n}function QM(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 sPe(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 cPe(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 $M(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 lPe(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
|
|
671
671
|
`).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(`
|
|
672
672
|
`)}function eN(e,t){return bP.parse(e,t)}var tN,nN,rN,iN,aN,oN,sN,cN,lN,uN,dN,fN,pN,mN,hN,gN,_N,vN,yN,bN,xN,SN,CN,wN,TN,EN,DN,ON,kN,AN,jN,MN,NN,PN,FN,IN,LN,RN,zN,BN,VN,HN,UN,WN,GN,KN,qN,JN,YN,XN,ZN,QN,$N,eP,tP,nP,rP,iP,aP,oP,sP,cP,lP,uP,dP,fP,pP,mP,hP,gP,_P,vP,yP,bP,xP=n((()=>{b(),nN=KM(),rN={exec:()=>null},iN=(()=>{try{return!0}catch{return!1}})(),aN={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)}}>`)},oN=/^(?:[ \t]*(?:\n|$))+/,sN=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,cN=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,lN=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,uN=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,dN=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,fN=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,pN=JM(fN).replace(/bull/g,dN).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(),mN=JM(fN).replace(/bull/g,dN).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(),hN=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,gN=/^[^\n]+/,_N=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,vN=JM(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,_N).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),yN=JM(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,dN).getRegex(),bN=`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`,xN=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,SN=JM(`^ {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`,xN).replace(`tag`,bN).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),CN=JM(hN).replace(`hr`,lN).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`,bN).getRegex(),wN={blockquote:JM(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,CN).getRegex(),code:sN,def:vN,fences:cN,heading:uN,hr:lN,html:SN,lheading:pN,list:yN,newline:oN,paragraph:CN,table:rN,text:gN},TN=JM(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,lN).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`,bN).getRegex(),EN={...wN,lheading:mN,table:TN,paragraph:JM(hN).replace(`hr`,lN).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,TN).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`,bN).getRegex()},DN={...wN,html:JM(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,xN).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:rN,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:JM(hN).replace(`hr`,lN).replace(`heading`,` *#{1,6} *[^
|
|
@@ -775,7 +775,7 @@ Examples:
|
|
|
775
775
|
- "重构这个模块的代码" -> refactor code modularize
|
|
776
776
|
- "帮我写个 Go 单元测试" -> write test golang unit
|
|
777
777
|
|
|
778
|
-
Output ONLY keywords. Nothing else.`,dI=6e3,fI=500,pI=120,mI=200,hI=150,gI=new Map})),_I=i({collectSkillDiscoveryPrefetch:()=>CI,extractQueryFromMessages:()=>yI,getTurnZeroSkillDiscovery:()=>mFe,startSkillDiscoveryPrefetch:()=>SI});function vI(e,t){if(e.add(t),e.size>wI){let t=e.size-TI,n=e.values();for(let r=0;r<t;r++){let t=n.next();if(t.done)break;e.delete(t.value)}}}function yI(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 bI(e,t,n){return{type:`skill_discovery`,skills:e,signal:t,source:`native`,gap:n}}async function xI(e,t){let n=0,r=[];for(let i of e){let e={name:i.name,description:i.description,score:i.score};if(n>=kI||i.score<OI){r.push(e);continue}let a=await dFe(i);if(!a){r.push(e);continue}n++,await fFe(i.name,a.path,a.content,t),r.push({...e,autoLoaded:!0,content:a.content,path:a.path})}return r}async function dFe(e){if(!e.skillRoot)return null;let t=[Bl(e.skillRoot,`SKILL.md`),Bl(e.skillRoot,`skill.md`)];for(let e of t)try{return{path:e,content:bd(await wu(e,`utf8`)).content.slice(0,AI)}}catch{}return null}async function fFe(e,t,n,r){try{let{addInvokedSkill:i}=await import(`./state-CsdHk8n-.js`);i(e,t,n,r.agentId??null)}catch{}}async function pFe(e,t,n,r){if(r!==`user_input`||!e.trim())return;let i=`${r}:${e.trim().toLowerCase()}`;if(!DI.has(i)){vI(DI,i);try{let[{isSkillLearningEnabled:r},{recordSkillGap:i}]=await Promise.all([import(`./featureCheck-JOur3pHb.js`),import(`./skillGapStore-
|
|
778
|
+
Output ONLY keywords. Nothing else.`,dI=6e3,fI=500,pI=120,mI=200,hI=150,gI=new Map})),_I=i({collectSkillDiscoveryPrefetch:()=>CI,extractQueryFromMessages:()=>yI,getTurnZeroSkillDiscovery:()=>mFe,startSkillDiscoveryPrefetch:()=>SI});function vI(e,t){if(e.add(t),e.size>wI){let t=e.size-TI,n=e.values();for(let r=0;r<t;r++){let t=n.next();if(t.done)break;e.delete(t.value)}}}function yI(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 bI(e,t,n){return{type:`skill_discovery`,skills:e,signal:t,source:`native`,gap:n}}async function xI(e,t){let n=0,r=[];for(let i of e){let e={name:i.name,description:i.description,score:i.score};if(n>=kI||i.score<OI){r.push(e);continue}let a=await dFe(i);if(!a){r.push(e);continue}n++,await fFe(i.name,a.path,a.content,t),r.push({...e,autoLoaded:!0,content:a.content,path:a.path})}return r}async function dFe(e){if(!e.skillRoot)return null;let t=[Bl(e.skillRoot,`SKILL.md`),Bl(e.skillRoot,`skill.md`)];for(let e of t)try{return{path:e,content:bd(await wu(e,`utf8`)).content.slice(0,AI)}}catch{}return null}async function fFe(e,t,n,r){try{let{addInvokedSkill:i}=await import(`./state-CsdHk8n-.js`);i(e,t,n,r.agentId??null)}catch{}}async function pFe(e,t,n,r){if(r!==`user_input`||!e.trim())return;let i=`${r}:${e.trim().toLowerCase()}`;if(!DI.has(i)){vI(DI,i);try{let[{isSkillLearningEnabled:r},{recordSkillGap:i}]=await Promise.all([import(`./featureCheck-JOur3pHb.js`),import(`./skillGapStore-CLxhWLyq.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){U(`[skill-search] skill gap learning error: ${e}`);return}}}async function SI(e,t,n){if(!hp())return[];let r=Date.now(),i=yI(e,t);if(!i.trim())return[];try{let e=await bc(n.cwd??process.cwd()),t=wc(i,e).filter(e=>!EI.has(e.name));if(t.length===0)return[];for(let e of t)vI(EI,e.name);let a={trigger:`assistant_turn`,queryText:i.slice(0,200),startedAt:r,durationMs:Date.now()-r,indexSize:e.length,method:`tfidf`};return U(`[skill-search] prefetch found ${t.length} skills in ${a.durationMs}ms`),[bI(await xI(t,n),a)]}catch(e){return U(`[skill-search] prefetch error: ${e}`),[]}}async function CI(e){try{return await e}catch{return[]}}async function mFe(e,t,n){if(!hp()||!e.trim())return null;let r=Date.now();try{let t=await bc(n.cwd??process.cwd()),i=wc(await aFe(e),t),a=await xI(i,n),o=a.some(e=>e.autoLoaded)?void 0:await pFe(e,i,n,`user_input`);if(i.length===0&&!o)return null;for(let e of i)vI(EI,e.name);let s={trigger:`user_input`,queryText:e.slice(0,200),startedAt:r,durationMs:Date.now()-r,indexSize:t.length,method:`tfidf`};return U(`[skill-search] turn-zero found ${i.length} skills in ${s.durationMs}ms`),bI(a,s,o)}catch(e){return U(`[skill-search] turn-zero error: ${e}`),null}}var wI,TI,EI,DI,OI,kI,AI,jI=n((()=>{gp(),Cc(),uFe(),W(),Ed(),wI=1e3,TI=750,EI=new Set,DI=new Set,OI=Number(process.env.SKILL_SEARCH_AUTOLOAD_MIN_SCORE??`0.30`),kI=Number(process.env.SKILL_SEARCH_AUTOLOAD_LIMIT??`2`),AI=Number(process.env.SKILL_SEARCH_AUTOLOAD_MAX_CHARS??`12000`)}));function MI(e){return RI.test(e)}function hFe(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 gFe(e){let t=e.filter(e=>Fs(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}=hFe(r.name),o=r.searchHint??``,s=xc(i.join(` `)),c=xc(o),l=xc(t),u=[...new Set([...s,...c,...l])],d=Kse([{tokens:s,weight:FI.name},{tokens:c,weight:FI.searchHint},{tokens:l,weight:FI.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=Sc(n);for(let e of n)for(let[t,n]of e.tfVector)e.tfVector.set(t,n*(r.get(t)??0));return U(`[search-extra-tools] indexed ${n.length} deferred tools from ${e.length} total tools`),n}function NI(e,t,n=5){if(t.length===0||!e.trim())return[];let r=xc(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=Sc(t),c=new Map;for(let[e,t]of i)c.set(e,t*(s.get(e)??0));let l=r.filter(e=>MI(e[0]??``)),u=r.filter(e=>!MI(e[0]??``)),d=e.toLowerCase().replace(/[-_]/g,` `),f=[];for(let e of t){let t=Gse(c,e.tfVector);l.length>0&&t>0&&l.filter(t=>e.tfVector.has(t)).length<LI&&(u.some(t=>e.tfVector.has(t))||(t=0)),d.includes(e.normalizedName)&&(t=Math.max(t,.75)),t>=II&&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 PI(e){let t=e.map(e=>e.name).sort().join(`,`);return zI&&BI===t?zI:(zI=await gFe(e),BI=t,zI)}var FI,II,LI,RI,zI,BI,VI=n((()=>{W(),Cc(),Ws(),FI={name:3,searchHint:2.5,description:1},II=Number(process.env.SEARCH_EXTRA_TOOLS_DISPLAY_MIN_SCORE??`0.10`),LI=2,RI=/[\u4e00-\u9fff\u3400-\u4dbf]/,zI=null,BI=null})),HI=i({buildToolDiscoveryAttachment:()=>qI,clearSearchExtraToolsPrefetchResults:()=>KI,collectSearchExtraToolsPrefetch:()=>YI,getSearchExtraToolsPrefetchSnapshot:()=>GI,getTurnZeroSearchExtraToolsPrefetch:()=>yFe,startSearchExtraToolsPrefetch:()=>JI,subscribeToSearchExtraToolsPrefetch:()=>WI});function UI(){for(let e of eL)e()}function WI(e){return eL.add(e),()=>{eL.delete(e)}}function GI(){return $I}function KI(){$I=[],UI()}function _Fe(e,t){if(e.add(t),e.size>XI){let t=e.size-ZI,n=e.values();for(let r=0;r<t;r++){let t=n.next();if(t.done)break;e.delete(t.value)}}}function vFe(e){return{name:e.name,description:e.description,searchHint:e.searchHint,score:e.score,isMcp:e.isMcp,isDeferred:e.isDeferred,inputSchema:e.inputSchema}}function qI(e,t,n,r,i){return{type:`tool_discovery`,tools:e,trigger:t,queryText:n.slice(0,200),durationMs:r,indexSize:i}}async function JI(e,t){let n=Date.now(),r=yI(null,t);if(!r.trim())return[];try{let t=await PI(e),i=NI(r,t,3).filter(e=>!QI.has(e.name));if(i.length===0)return[];for(let e of i)_Fe(QI,e.name);let a=Date.now()-n;U(`[search-extra-tools] prefetch found ${i.length} tools in ${a}ms`);let o=i.map(vFe);return $I=o,UI(),[qI(o,`assistant_turn`,r,a,t.length)]}catch(e){return U(`[search-extra-tools] prefetch error: ${e}`),[]}}async function yFe(e,t){return null}async function YI(e){try{return await e}catch{return[]}}var XI,ZI,QI,$I,eL,tL=n((()=>{VI(),W(),jI(),XI=500,ZI=400,QI=new Set,$I=[],eL=new Set}));function nL(e){iL=e}function rL(){return iL}function bFe(e){aL=e}function xFe(){return aL}function SFe(e){oL=e}function CFe(){return oL}var iL,aL,oL,sL=n((()=>{iL=!1,aL=!1,oL=!1}));function cL(){return!1}function wFe(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 TFe(e,t){let n={...t,uuid:tu(),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?(U(`No tool_use blocks found in assistant message for fork directive: ${e.slice(0,50)}...`,{level:`error`}),[$({content:[{type:`text`,text:EFe(e)}]})]):[n,$({content:[...r.map(e=>({type:`tool_result`,tool_use_id:e.id,content:[{type:`text`,text:OFe}]})),{type:`text`,text:EFe(e)}]})]}function EFe(e){return`<${ra}>
|
|
779
779
|
STOP. READ THIS FIRST.
|
|
780
780
|
|
|
781
781
|
You are a forked worker process. You are NOT the main agent.
|
|
@@ -861,7 +861,7 @@ Usage notes:
|
|
|
861
861
|
... (truncated because it exceeds 2k characters. If you need more information, run "git status" using BashTool)`:i;return Ri(`info`,`git_status_completed`,{duration_ms:Date.now()-e,truncated:i.length>KR}),[`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(`
|
|
862
862
|
|
|
863
863
|
`)}catch(t){return Ri(`error`,`git_status_failed`,{duration_ms:Date.now()-e}),q(t),null}}),JR=u(async()=>{let e=Date.now();Ri(`info`,`system_context_started`);let t=m(process.env.CLAUDE_CODE_REMOTE)||!fRe()?null:await qR();return Ri(`info`,`system_context_completed`,{duration_ms:Date.now()-e,has_git_status:t!==null,has_injection:!1}),{...t&&{gitStatus:t}}}),YR=u(async()=>{let e=Date.now();Ri(`info`,`user_context_started`);let t=m(process.env.CLAUDE_CODE_DISABLE_CLAUDE_MDS)||v()&&$t().length===0,n=t?null:QP(RP(await YP()));return kte(n||null),Ri(`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 ${UR()}.`}})}));function gRe(){return mc()}function ZR({mainThreadAgentDefinition:e,toolUseContext:t,customSystemPrompt:n,defaultSystemPrompt:r,appendSystemPrompt:i,overrideSystemPrompt:a}){if(a)return rc([a]);let o=e?K9(e)?e.getSystemPrompt({toolUseContext:{options:t.options}}):e.getSystemPrompt():void 0;return e?.memory&&J(`tengu_agent_memory_loaded`,{scope:e.memory,source:`main-thread`}),o&&gRe()?rc([...r,`\n# Custom Agent Instructions\n${o}`,...i?[i]:[]]):rc([...o?[o]:n?[n]:r,...i?[i]:[]])}var QR=n((()=>{Na(),$9(),lI(),oc()})),_Re=i({_resetCacheWarningStateForTest:()=>CRe,calculateCacheHitRate:()=>bRe,createCacheWarningMessage:()=>SRe,getCacheThreshold:()=>vRe,isCacheWarningEnabled:()=>yRe,shouldShowCacheWarning:()=>xRe});function vRe(){return ii().cacheThreshold??TRe}function yRe(){return ii().cacheWarningEnabled??!0}function bRe(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 xRe(e,t,n){let r=bRe(e);if(r===null)return null;let i=$R.get(t);if(!i){if(i={lastHitRate:null,lastTimestamp:null},$R.size>=wRe){let e=$R.keys().next().value;e!==void 0&&$R.delete(e)}$R.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 SRe(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:tu(),isMeta:!1}}function CRe(){$R.clear()}var $R,wRe,TRe,ERe=n((()=>{Yr(),$R=new Map,wRe=50,TRe=80}));async function ez(e,t){try{let n=await _3(e,t);if(n!==null)return n;U(`countTokensWithFallback: API returned null, trying haiku fallback (${t.length} tools)`)}catch(e){U(`countTokensWithFallback: API failed: ${H(e)}`),q(e)}try{let n=await qxt(e,t);return n===null&&U(`countTokensWithFallback: haiku fallback also returned null (${t.length} tools)`),n}catch(e){return U(`countTokensWithFallback: haiku fallback failed: ${H(e)}`),q(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(`, `);U(`countToolDefinitionTokens returned ${i} for ${e.length} tools: ${t.slice(0,100)}${t.length>100?`...`:``}`)}return i??0}function DRe(e){let t=e.match(/^#+\s+(.+)$/m);if(t)return t[1].trim();let n=e.split(`
|
|
864
|
-
`).find(e=>e.trim().length>0)??``;return n.length>40?`${n.slice(0,40)}…`:n}async function ORe(e){let t=await JR(),n=[...e.filter(e=>e.length>0&&e!==`__SYSTEM_PROMPT_DYNAMIC_BOUNDARY__`).map(e=>({name:DRe(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 kRe(){if(m(process.env.CLAUDE_CODE_SIMPLE))return{memoryFileDetails:[],agentsMdTokens:0};let e=RP(await YP()),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 ARe(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-BHMkqGBf.js`),{isDeferredTool:c}=await import(`./prompt-BBeDQXIs.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 jRe(e){return Ss(e,hs)}async function MRe(e,t,n){let r=await dxe(Cn()),i=jRe(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 NRe(e,t,n){try{let r=await fxe(Cn()),i=jRe(e);if(!i)return{skillTokens:0,skillInfo:{totalSkills:0,includedSkills:0,skillFrontmatter:[]}};let a=await tz([i],t,n),o=r.map(e=>({name:V3(e),source:e.type===`prompt`?e.source:`plugin`,tokens:nSt(e)}));return{skillTokens:a,skillInfo:{totalSkills:r.length,includedSkills:r.length,skillFrontmatter:o}}}catch(e){return q(Fn(e)),{skillTokens:0,skillInfo:{totalSkills:0,includedSkills:0,skillFrontmatter:[]}}}}async function PRe(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=>v3(V({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-BHMkqGBf.js`),{isDeferredTool:p}=await import(`./prompt-BBeDQXIs.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 FRe(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 IRe(e,t){let n=Array.isArray(e.message.content)?e.message.content:[];for(let e of n){let n=v3(V(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 LRe(e,t,n){if(typeof e.message.content==`string`){let n=v3(e.message.content);t.userMessageTokens+=n;return}for(let r of e.message.content??[]){let e=v3(V(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 RRe(e,t){let n=v3(V(e.attachment));t.attachmentTokens+=n;let r=e.attachment.type||`unknown`;t.attachmentsByType.set(r,(t.attachmentsByType.get(r)||0)+n)}async function zRe(e){let t=await BR(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`?IRe(e,n):e.type===`user`?LRe(e,n,r):e.type===`attachment`&&RRe(e,n);return n.totalTokens=await ez(L4(t.messages).map(e=>e.type===`assistant`?{role:`assistant`,content:e.message.content}:e.message),[])??0,n}async function BRe(t,n,r,i,a,o,s,c,l){let u=Zo({permissionMode:(await r()).mode,mainLoopModel:n}),d=mo(u,Xt()),f=await F7(i,u),p=ZR({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([ORe(p),kRe(),ARe(i,r,a,u,t),PRe(i,r,a,u,t),FRe(a),MRe(i,r,a),zRe(t)]),A=(await NRe(i,r,a)).skillInfo,ee=A.skillFrontmatter.reduce((e,t)=>e+t.tokens,0),te=k.totalTokens,ne=nG(),re=ne?$W(n)-iG: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:nz,tokens:oe,color:`inactive`})):ne||(oe=aG,ie.push({name:rz,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=_Le(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===nz||e.name===rz),_e=pe.filter(e=>e.name!==nz&&e.name!==rz&&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 P=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)),Ce=Array.from(k.attachmentsByType.entries()).map(([e,t])=>({name:e,tokens:t})).sort((e,t)=>t.tokens-e.tokens),we={toolCallTokens:k.toolCallTokens,toolResultTokens:k.toolResultTokens,attachmentTokens:k.attachmentTokens,assistantMessageTokens:k.assistantMessageTokens,userMessageTokens:k.userMessageTokens,toolCallsByType:P,attachmentsByType:Ce};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:we,apiUsage:M,...(()=>{if(!M)return{};let{calculateCacheHitRate:t,getCacheThreshold:n}=(ERe(),e(_Re)),r=t(M);return r===null?{}:{cacheHitRate:r,cacheThreshold:n()}})()}}var nz,rz,VRe=n((()=>{B7(),HR(),Gt(),$3(),XR(),sG(),C3(),L3(),Zs(),$s(),Pg(),U7(),$P(),io(),Sn(),W(),h(),Mn(),oa(),p3(),Lo(),Zn(),QR(),SR(),nz=`Autocompact buffer`,rz=`Compact buffer`}));function iz(e){let t=az.get(e);if(t)return t;let n=xee(e);return az.set(e,n),n}var az,oz=n((()=>{_t(),az=new WeakMap}));function HRe(e){if(!e.startsWith(`auto:`))return null;let t=e.slice(5),n=parseInt(t,10);return isNaN(n)?(U(`Invalid ENABLE_SEARCH_EXTRA_TOOLS value "${e}": expected auto:N where N is a number.`),null):Math.max(0,Math.min(100,n))}function URe(e){return e?e===`auto`||e.startsWith(`auto:`):!1}function sz(){let e=process.env.ENABLE_SEARCH_EXTRA_TOOLS;if(!e||e===`auto`)return hz;let t=HRe(e);return t===null?hz:t}function WRe(e){let t=mo(e,so(e)),n=sz()/100;return Math.floor(t*n)}function GRe(e){return Math.floor(WRe(e)*$Re)}function cz(){if(m(process.env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS))return`standard`;let e=process.env.ENABLE_SEARCH_EXTRA_TOOLS,t=e?HRe(e):null;return t===0?`tst`:t===100?`standard`:URe(e)?`tst-auto`:m(e)?`tst`:f(process.env.ENABLE_SEARCH_EXTRA_TOOLS)?`standard`:`tst`}function lz(){let e=cz();return e===`standard`?(gz||(gz=!0,U(`[SearchExtraTools:optimistic] mode=${e}, ENABLE_SEARCH_EXTRA_TOOLS=${process.env.ENABLE_SEARCH_EXTRA_TOOLS}, result=false`)),!1):(gz||(gz=!0,U(`[SearchExtraTools:optimistic] mode=${e}, ENABLE_SEARCH_EXTRA_TOOLS=${process.env.ENABLE_SEARCH_EXTRA_TOOLS}, result=true`)),!0)}function uz(e){return e.some(e=>Ys(e,Ks))}async function KRe(e,t,n){let r=e.filter(e=>Fs(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?V(r.inputJSONSchema):r.inputSchema?V(iz(r.inputSchema)):``;return r.name.length+i.length+a.length}))).reduce((e,t)=>e+t,0)}async function dz(e,t,n,r,i){let a=hr(t,e=>e.isMcp);function o(t,n,r,i){J(`tengu_search_extra_tools_mode_decision`,{enabled:t,mode:n,reason:r,checkedModel:e,mcpToolCount:a,userType:process.env.USER_TYPE??`external`,...i})}if(!uz(t))return U(`Tool search disabled: SearchExtraToolsTool is not available (may have been disallowed via disallowedTools).`),o(!1,`standard`,`mcp_search_unavailable`),!1;let s=cz();switch(s){case`tst`:return o(!0,s,`tst_enabled`),!0;case`tst-auto`:{let{enabled:a,debugDescription:c,metrics:l}=await QRe(t,n,r,e);return a?(U(`Auto tool search enabled: ${c}`+(i?` [source: ${i}]`:``)),o(!0,s,`auto_above_threshold`,l),!0):(U(`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 fz(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_reference`}function qRe(e){return fz(e)&&`tool_name`in e&&typeof e.tool_name==`string`}function JRe(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_result`&&`content`in e&&Array.isArray(e.content)}function YRe(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_result`&&`content`in e&&typeof e.content==`string`}function XRe(e){let t=tze.exec(e);return t?.[1]?t[1].split(`,`).map(e=>e.trim()).filter(Boolean):[]}function pz(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(JRe(n))for(let e of n.content)qRe(e)&&t.add(e.tool_name);if(YRe(n)){let e=XRe(n.content);for(let n of e)t.add(n)}}}return t.size>0&&U(`Dynamic tool loading: found ${t.size} discovered tools in message history`+(n>0?` (${n} carried from compact boundary)`:``)),t}function mz(){return!1}function ZRe(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(Fs),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:(J(`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(cse).sort(),removedNames:d.sort()})}async function QRe(e,t,n,r){let i=await eze(e,t,n,r);if(i!==null){let e=WRe(r);return{enabled:i>=e,debugDescription:`${i} tokens (threshold: ${e}, ${sz()}% of context)`,metrics:{deferredToolTokens:i,threshold:e}}}let a=await KRe(e,t,n),o=GRe(r);return{enabled:a>=o,debugDescription:`${a} chars (threshold: ${o}, ${sz()}% of context) (char fallback)`,metrics:{deferredToolDescriptionChars:a,charThreshold:o}}}var hz,$Re,eze,gz,tze,_z=n((()=>{d(),Na(),Zs(),Ws(),VRe(),Tr(),Po(),io(),W(),h(),Zn(),oz(),hz=10,$Re=2.5,eze=u(async(e,t,n,r)=>{let i=e.filter(e=>Fs(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=>Fs(e)).map(e=>e.name).join(`,`)),gz=!1,tze=/^Found \d+ deferred tool\(s\): (.+)\.$/m}));function nze(e){return e.map(e=>e.name).sort().join(`,`)}function rze(e){let t=nze(e);xz!==t&&(U(`SearchExtraToolsTool: cache invalidated - deferred tools changed`),Sz.cache.clear?.(),xz=t)}function ize(){Sz.cache.clear?.(),xz=null}function vz(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 aze(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 oze(e){let t=new Map;for(let n of e)t.has(n)||t.set(n,RegExp(`\\b${sae(n)}\\b`));return t}async function sze(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=oze(l),d=t;return s.length>0&&(d=(await Promise.all(t.map(async e=>{let t=aze(e.name),r=(await Sz(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=aze(e.name),r=(await Sz(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 cze,lze,yz,bz,xz,Sz,Cz,wz=n((()=>{d(),_t(),Na(),Zs(),W(),vt(),Ja(),_z(),Ws(),VI(),cze=Number(process.env.SEARCH_EXTRA_TOOLS_WEIGHT_KEYWORD??`0.4`),lze=Number(process.env.SEARCH_EXTRA_TOOLS_WEIGHT_TFIDF??`0.6`),yz=gt(()=>B({query:L().describe(`Query to find deferred tools. Use "select:<tool_name>" for direct selection, or keywords to search.`),max_results:R().optional().default(5).describe(`Maximum number of results to return (default: 5)`)})),bz=gt(()=>B({matches:z(L()),query:L(),total_deferred_tools:R(),pending_mcp_servers:z(L()).optional(),already_loaded:z(L()).optional()})),xz=null,Sz=u(async(e,t)=>{let n=Ss(t,e);return n?n.prompt({getToolPermissionContext:async()=>({mode:`default`,additionalWorkingDirectories:new Map,alwaysAllowRules:{},alwaysDenyRules:{},alwaysAskRules:{},isBypassPermissionsModeAvailable:!1}),tools:t,agents:[]}):``},e=>e),Cz=Ns({isEnabled(){return lz()},isConcurrencySafe(){return!0},isReadOnly(){return!0},name:Ks,maxResultSizeChars:1e5,async description(){return ese()},async prompt(){return ese()},get inputSchema(){return yz()},get outputSchema(){return bz()},async call(e,{options:{tools:t},getAppState:n}){let{query:r,max_results:i=5}=e,a=t.filter(Fs);rze(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){J(`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=Ss(a,r),o=e??Ss(t,r);o?n.includes(o.name)||(n.push(o.name),e||i.push(o.name)):l.push(r)}if(n.length===0){U(`SearchExtraToolsTool: select failed — none found: ${l.join(`, `)}`),s([],`select`);let e=o();return vz([],r,a.length,e)}return l.length>0?U(`SearchExtraToolsTool: partial select — found: ${n.join(`, `)}, missing: ${l.join(`, `)}`):U(`SearchExtraToolsTool: selected ${n.join(`, `)}`),s(n,`select`),vz(n,r,a.length,void 0,i.length>0?i:void 0)}let l=r.match(/^discover:(.+)$/i);if(l){let e=NI(l[1].trim(),await PI(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(`
|
|
864
|
+
`).find(e=>e.trim().length>0)??``;return n.length>40?`${n.slice(0,40)}…`:n}async function ORe(e){let t=await JR(),n=[...e.filter(e=>e.length>0&&e!==`__SYSTEM_PROMPT_DYNAMIC_BOUNDARY__`).map(e=>({name:DRe(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 kRe(){if(m(process.env.CLAUDE_CODE_SIMPLE))return{memoryFileDetails:[],agentsMdTokens:0};let e=RP(await YP()),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 ARe(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-zFMN5MqY.js`),{isDeferredTool:c}=await import(`./prompt-TZJKyomz.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 jRe(e){return Ss(e,hs)}async function MRe(e,t,n){let r=await dxe(Cn()),i=jRe(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 NRe(e,t,n){try{let r=await fxe(Cn()),i=jRe(e);if(!i)return{skillTokens:0,skillInfo:{totalSkills:0,includedSkills:0,skillFrontmatter:[]}};let a=await tz([i],t,n),o=r.map(e=>({name:V3(e),source:e.type===`prompt`?e.source:`plugin`,tokens:nSt(e)}));return{skillTokens:a,skillInfo:{totalSkills:r.length,includedSkills:r.length,skillFrontmatter:o}}}catch(e){return q(Fn(e)),{skillTokens:0,skillInfo:{totalSkills:0,includedSkills:0,skillFrontmatter:[]}}}}async function PRe(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=>v3(V({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-zFMN5MqY.js`),{isDeferredTool:p}=await import(`./prompt-TZJKyomz.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 FRe(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 IRe(e,t){let n=Array.isArray(e.message.content)?e.message.content:[];for(let e of n){let n=v3(V(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 LRe(e,t,n){if(typeof e.message.content==`string`){let n=v3(e.message.content);t.userMessageTokens+=n;return}for(let r of e.message.content??[]){let e=v3(V(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 RRe(e,t){let n=v3(V(e.attachment));t.attachmentTokens+=n;let r=e.attachment.type||`unknown`;t.attachmentsByType.set(r,(t.attachmentsByType.get(r)||0)+n)}async function zRe(e){let t=await BR(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`?IRe(e,n):e.type===`user`?LRe(e,n,r):e.type===`attachment`&&RRe(e,n);return n.totalTokens=await ez(L4(t.messages).map(e=>e.type===`assistant`?{role:`assistant`,content:e.message.content}:e.message),[])??0,n}async function BRe(t,n,r,i,a,o,s,c,l){let u=Zo({permissionMode:(await r()).mode,mainLoopModel:n}),d=mo(u,Xt()),f=await F7(i,u),p=ZR({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([ORe(p),kRe(),ARe(i,r,a,u,t),PRe(i,r,a,u,t),FRe(a),MRe(i,r,a),zRe(t)]),A=(await NRe(i,r,a)).skillInfo,ee=A.skillFrontmatter.reduce((e,t)=>e+t.tokens,0),te=k.totalTokens,ne=nG(),re=ne?$W(n)-iG: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:nz,tokens:oe,color:`inactive`})):ne||(oe=aG,ie.push({name:rz,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=_Le(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===nz||e.name===rz),_e=pe.filter(e=>e.name!==nz&&e.name!==rz&&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 P=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)),Ce=Array.from(k.attachmentsByType.entries()).map(([e,t])=>({name:e,tokens:t})).sort((e,t)=>t.tokens-e.tokens),we={toolCallTokens:k.toolCallTokens,toolResultTokens:k.toolResultTokens,attachmentTokens:k.attachmentTokens,assistantMessageTokens:k.assistantMessageTokens,userMessageTokens:k.userMessageTokens,toolCallsByType:P,attachmentsByType:Ce};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:we,apiUsage:M,...(()=>{if(!M)return{};let{calculateCacheHitRate:t,getCacheThreshold:n}=(ERe(),e(_Re)),r=t(M);return r===null?{}:{cacheHitRate:r,cacheThreshold:n()}})()}}var nz,rz,VRe=n((()=>{B7(),HR(),Gt(),$3(),XR(),sG(),C3(),L3(),Zs(),$s(),Pg(),U7(),$P(),io(),Sn(),W(),h(),Mn(),oa(),p3(),Lo(),Zn(),QR(),SR(),nz=`Autocompact buffer`,rz=`Compact buffer`}));function iz(e){let t=az.get(e);if(t)return t;let n=xee(e);return az.set(e,n),n}var az,oz=n((()=>{_t(),az=new WeakMap}));function HRe(e){if(!e.startsWith(`auto:`))return null;let t=e.slice(5),n=parseInt(t,10);return isNaN(n)?(U(`Invalid ENABLE_SEARCH_EXTRA_TOOLS value "${e}": expected auto:N where N is a number.`),null):Math.max(0,Math.min(100,n))}function URe(e){return e?e===`auto`||e.startsWith(`auto:`):!1}function sz(){let e=process.env.ENABLE_SEARCH_EXTRA_TOOLS;if(!e||e===`auto`)return hz;let t=HRe(e);return t===null?hz:t}function WRe(e){let t=mo(e,so(e)),n=sz()/100;return Math.floor(t*n)}function GRe(e){return Math.floor(WRe(e)*$Re)}function cz(){if(m(process.env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS))return`standard`;let e=process.env.ENABLE_SEARCH_EXTRA_TOOLS,t=e?HRe(e):null;return t===0?`tst`:t===100?`standard`:URe(e)?`tst-auto`:m(e)?`tst`:f(process.env.ENABLE_SEARCH_EXTRA_TOOLS)?`standard`:`tst`}function lz(){let e=cz();return e===`standard`?(gz||(gz=!0,U(`[SearchExtraTools:optimistic] mode=${e}, ENABLE_SEARCH_EXTRA_TOOLS=${process.env.ENABLE_SEARCH_EXTRA_TOOLS}, result=false`)),!1):(gz||(gz=!0,U(`[SearchExtraTools:optimistic] mode=${e}, ENABLE_SEARCH_EXTRA_TOOLS=${process.env.ENABLE_SEARCH_EXTRA_TOOLS}, result=true`)),!0)}function uz(e){return e.some(e=>Ys(e,Ks))}async function KRe(e,t,n){let r=e.filter(e=>Fs(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?V(r.inputJSONSchema):r.inputSchema?V(iz(r.inputSchema)):``;return r.name.length+i.length+a.length}))).reduce((e,t)=>e+t,0)}async function dz(e,t,n,r,i){let a=hr(t,e=>e.isMcp);function o(t,n,r,i){J(`tengu_search_extra_tools_mode_decision`,{enabled:t,mode:n,reason:r,checkedModel:e,mcpToolCount:a,userType:process.env.USER_TYPE??`external`,...i})}if(!uz(t))return U(`Tool search disabled: SearchExtraToolsTool is not available (may have been disallowed via disallowedTools).`),o(!1,`standard`,`mcp_search_unavailable`),!1;let s=cz();switch(s){case`tst`:return o(!0,s,`tst_enabled`),!0;case`tst-auto`:{let{enabled:a,debugDescription:c,metrics:l}=await QRe(t,n,r,e);return a?(U(`Auto tool search enabled: ${c}`+(i?` [source: ${i}]`:``)),o(!0,s,`auto_above_threshold`,l),!0):(U(`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 fz(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_reference`}function qRe(e){return fz(e)&&`tool_name`in e&&typeof e.tool_name==`string`}function JRe(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_result`&&`content`in e&&Array.isArray(e.content)}function YRe(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_result`&&`content`in e&&typeof e.content==`string`}function XRe(e){let t=tze.exec(e);return t?.[1]?t[1].split(`,`).map(e=>e.trim()).filter(Boolean):[]}function pz(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(JRe(n))for(let e of n.content)qRe(e)&&t.add(e.tool_name);if(YRe(n)){let e=XRe(n.content);for(let n of e)t.add(n)}}}return t.size>0&&U(`Dynamic tool loading: found ${t.size} discovered tools in message history`+(n>0?` (${n} carried from compact boundary)`:``)),t}function mz(){return!1}function ZRe(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(Fs),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:(J(`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(cse).sort(),removedNames:d.sort()})}async function QRe(e,t,n,r){let i=await eze(e,t,n,r);if(i!==null){let e=WRe(r);return{enabled:i>=e,debugDescription:`${i} tokens (threshold: ${e}, ${sz()}% of context)`,metrics:{deferredToolTokens:i,threshold:e}}}let a=await KRe(e,t,n),o=GRe(r);return{enabled:a>=o,debugDescription:`${a} chars (threshold: ${o}, ${sz()}% of context) (char fallback)`,metrics:{deferredToolDescriptionChars:a,charThreshold:o}}}var hz,$Re,eze,gz,tze,_z=n((()=>{d(),Na(),Zs(),Ws(),VRe(),Tr(),Po(),io(),W(),h(),Zn(),oz(),hz=10,$Re=2.5,eze=u(async(e,t,n,r)=>{let i=e.filter(e=>Fs(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=>Fs(e)).map(e=>e.name).join(`,`)),gz=!1,tze=/^Found \d+ deferred tool\(s\): (.+)\.$/m}));function nze(e){return e.map(e=>e.name).sort().join(`,`)}function rze(e){let t=nze(e);xz!==t&&(U(`SearchExtraToolsTool: cache invalidated - deferred tools changed`),Sz.cache.clear?.(),xz=t)}function ize(){Sz.cache.clear?.(),xz=null}function vz(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 aze(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 oze(e){let t=new Map;for(let n of e)t.has(n)||t.set(n,RegExp(`\\b${sae(n)}\\b`));return t}async function sze(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=oze(l),d=t;return s.length>0&&(d=(await Promise.all(t.map(async e=>{let t=aze(e.name),r=(await Sz(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=aze(e.name),r=(await Sz(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 cze,lze,yz,bz,xz,Sz,Cz,wz=n((()=>{d(),_t(),Na(),Zs(),W(),vt(),Ja(),_z(),Ws(),VI(),cze=Number(process.env.SEARCH_EXTRA_TOOLS_WEIGHT_KEYWORD??`0.4`),lze=Number(process.env.SEARCH_EXTRA_TOOLS_WEIGHT_TFIDF??`0.6`),yz=gt(()=>B({query:L().describe(`Query to find deferred tools. Use "select:<tool_name>" for direct selection, or keywords to search.`),max_results:R().optional().default(5).describe(`Maximum number of results to return (default: 5)`)})),bz=gt(()=>B({matches:z(L()),query:L(),total_deferred_tools:R(),pending_mcp_servers:z(L()).optional(),already_loaded:z(L()).optional()})),xz=null,Sz=u(async(e,t)=>{let n=Ss(t,e);return n?n.prompt({getToolPermissionContext:async()=>({mode:`default`,additionalWorkingDirectories:new Map,alwaysAllowRules:{},alwaysDenyRules:{},alwaysAskRules:{},isBypassPermissionsModeAvailable:!1}),tools:t,agents:[]}):``},e=>e),Cz=Ns({isEnabled(){return lz()},isConcurrencySafe(){return!0},isReadOnly(){return!0},name:Ks,maxResultSizeChars:1e5,async description(){return ese()},async prompt(){return ese()},get inputSchema(){return yz()},get outputSchema(){return bz()},async call(e,{options:{tools:t},getAppState:n}){let{query:r,max_results:i=5}=e,a=t.filter(Fs);rze(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){J(`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=Ss(a,r),o=e??Ss(t,r);o?n.includes(o.name)||(n.push(o.name),e||i.push(o.name)):l.push(r)}if(n.length===0){U(`SearchExtraToolsTool: select failed — none found: ${l.join(`, `)}`),s([],`select`);let e=o();return vz([],r,a.length,e)}return l.length>0?U(`SearchExtraToolsTool: partial select — found: ${n.join(`, `)}, missing: ${l.join(`, `)}`):U(`SearchExtraToolsTool: selected ${n.join(`, `)}`),s(n,`select`),vz(n,r,a.length,void 0,i.length>0?i:void 0)}let l=r.match(/^discover:(.+)$/i);if(l){let e=NI(l[1].trim(),await PI(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
865
|
|
|
866
866
|
`)}`,s(e.map(e=>e.name),`keyword`),vz(e.map(e=>e.name),r,a.length)}let u=new Set(a.map(e=>e.name)),[d,f]=await Promise.all([sze(r,a,t,i),PI(a)]),p=NI(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*cze)}),p.forEach(e=>{m.set(e.name,(m.get(e.name)??0)+e.score*lze)});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(U(`SearchExtraToolsTool: keyword search for "${r}", found ${h.length} matches`),s(h,`keyword`),h.length===0){let e=o();return vz(h,r,a.length,e)}return vz(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(`
|
|
867
867
|
`)}}})}));function uze(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)}}),L4(e).forEach(e=>{let{content:a}=e.message;if(typeof a==`string`){let n=v3(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=>dze(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 dze(e,t,n,r,i,a){let o=v3(V(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(fze(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(fze(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 fze(e,t,n){e.set(t,(e.get(t)||0)+n)}function pze(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 mze=n((()=>{C3(),p3(),Zn()})),hze,gze=n((()=>{hze=[`User`,`Project`,`Local`,`Managed`,`AutoMem`]}));function _ze(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 Tz(){kz.cache?.clear?.()}async function vze(){if(!on())return;let{enabled:e}=await l4(),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)}Mte(),yt(r)}function Ez(){let e=qr(),t=Ur(`policySettings`),n=e=>e?Object.fromEntries(Object.entries(e).sort()):{};return V({enabledPlugins:n(e.enabledPlugins),extraKnownMarketplaces:n(e.extraKnownMarketplaces),strictKnownMarketplaces:t?.strictKnownMarketplaces??[],blockedMarketplaces:t?.blockedMarketplaces??[]})}function yze(){Dz||(Dz=!0,Oz=Ez(),eh.subscribe(e=>{if(e===`policySettings`){let e=Ez();if(e===Oz){U(`Plugin hooks: skipping reload, plugin-affecting settings unchanged`);return}Oz=e,U(`Plugin hooks: reloading due to plugin-affecting settings change`),s4(`loadPluginHooks: plugin-affecting settings changed`),Tz(),kz()}}))}var Dz,Oz,kz,Az=n((()=>{d(),Gt(),W(),th(),Yr(),Zn(),u4(),Dz=!1,kz=u(async()=>{let{enabled:e}=await l4(),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;U(`Loading hooks from plugin: ${n.name}`);let e=_ze(n);for(let n of Object.keys(e))t[n].push(...e[n])}Mte(),yt(t),U(`Registered ${Object.values(t).reduce((e,t)=>e+t.reduce((e,t)=>e+t.hooks.length,0),0)} hooks from ${e.length} plugins`)})}));function bze(){let e=Mz;return Mz=void 0,e}async function jz(e,{sessionId:t,agentType:n,model:r,forceSyncExecution:i}={}){if(v())return[];let a=[],o=[],s=[];if(Q_())U(`Skipping plugin hooks - allowManagedHooksOnly is enabled`);else try{await rie(`load_plugin_hooks`,()=>kz())}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),q(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.`,U(`Warning: Failed to load plugin hooks. SessionStart hooks from plugins will not execute. Error: ${r}. ${i}`,{level:`warn`})}let c=n??_te();for await(let n of mEt(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&&(Mz=n.initialUserMessage),n.watchPaths&&n.watchPaths.length>0&&s.push(...n.watchPaths);if(s.length>0&&cv(s),o.length>0){let e=j0({type:`hook_additional_context`,content:o,hookName:`SessionStart`,toolUseID:`SessionStart`,hookEvent:`SessionStart`});a.push(e)}return a}async function xze(e,{forceSyncExecution:t}={}){if(v())return[];let n=[],r=[];if(Q_())U(`Skipping plugin hooks - allowManagedHooksOnly is enabled`);else try{await kz()}catch(e){U(`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 hEt(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=j0({type:`hook_additional_context`,content:r,hookName:`Setup`,toolUseID:`Setup`,hookEvent:`Setup`});n.push(e)}return n}var Mz,Nz=n((()=>{Gt(),H0(),W(),Pi(),h(),_v(),iv(),g7(),oa(),Az()}));async function Sze(e,t){}var Cze=n((()=>{}));function wze(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 Tze=n((()=>{}));function Eze(e,t=`from`){let n=Fz+(t===`up_to`?Mze:jze);return e&&e.trim()!==``&&(n+=`\n\nAdditional Instructions:\n${e}`),n+=Lz,n}function Dze(e){let t=Fz+Aze;return e&&e.trim()!==``&&(t+=`\n\nAdditional Instructions:\n${e}`),t+=Lz,t}function Oze(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,`
|
|
@@ -1160,7 +1160,7 @@ https://github.com/highlightjs/highlight.js/issues/2277`),i=e,r=t),n===void 0&&(
|
|
|
1160
1160
|
`),`utf8`)),p=Tqe(s,a,f),m=a.length),p!==-1)return await Dqe(e,s,c-u+p,m,n,l+uH(s,0,p));c+=d;let h=Math.min(o,f);l+=uH(s,0,f-h),u=h,s.copyWithin(0,f-u,f)}return{content:``,lineOffset:1,truncated:c>=fH}}async function wqe(e){let t=Buffer.allocUnsafe(dH),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 Eqe(t,n)}function Tqe(e,t,n){let r=e.indexOf(t);return r===-1||r+t.length>n?-1:r}function uH(e,t,n){let r=0;for(let i=t;i<n;i++)e[i]===pH&&r++;return r}function Eqe(e,t){let n=e.toString(`utf8`,0,t);return n.includes(`\r`)?n.replaceAll(`\r
|
|
1161
1161
|
`,`
|
|
1162
1162
|
`):n}async function Dqe(e,t,n,r,i,a){let o=Math.min(n,dH),{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]===pH&&(l++,l>i));e--)c--;let u=a-uH(t,s-(n-c),s)+1,d=n+r,{bytesRead:f}=await e.read(t,0,dH,d),p=d;l=0;for(let e=0;e<f&&(p++,!(t[e]===pH&&(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:Eqe(h,g),lineOffset:u,truncated:!1}}var dH,fH,pH,mH=n((()=>{Mn(),dH=8*1024,fH=10*1024*1024,pH=10}));function Oqe(e){return e?e.file_path?.startsWith(Qd())?`Updated plan`:e.edits==null&&e.old_string===``?`Create`:`Update`:`Update`}function kqe(e){return e?.file_path?vi(e.file_path):null}function Aqe({file_path:e},{verbose:t}){return e?e.startsWith(Qd())?``:(0,gH.jsx)(hb,{filePath:e,children:t?e:vi(e)}):null}function jqe({filePath:e,structuredPatch:t,originalFile:n},r,{style:i,verbose:a}){let o=e.startsWith(Qd());return(0,gH.jsx)(bqe,{filePath:e,structuredPatch:t,firstLine:n.split(`
|
|
1163
|
-
`)[0]??null,fileContent:n,style:i,verbose:a,previewHint:o?`/plan to preview`:void 0})}function Mqe(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,gH.jsx)(aH,{file_path:i,operation:`update`,firstLine:null,verbose:r}):a===``?(0,gH.jsx)(aH,{file_path:i,operation:`write`,content:o,firstLine:Ka(o),verbose:r}):(0,gH.jsx)(Pqe,{filePath:i,oldString:a,newString:o,replaceAll:s,style:n,verbose:r})}function Nqe(e,t){let{verbose:n}=t;return!n&&typeof e==`string`&&j4(e,`tool_use_error`)?j4(e,`tool_use_error`)?.includes(`Note: your current working directory is`)?(0,gH.jsx)(Z,{children:(0,gH.jsx)(F,{color:`error`,children:`File not found`})}):(0,gH.jsx)(Z,{children:(0,gH.jsx)(F,{color:`error`,children:`Error editing file`})}):(0,gH.jsx)(db,{result:e,verbose:n})}function Pqe({filePath:e,oldString:t,newString:n,replaceAll:r,style:i,verbose:a}){let[o]=(0,hH.useState)(()=>Iqe(e,t,n,r));return(0,gH.jsx)(hH.Suspense,{fallback:(0,gH.jsx)(aH,{file_path:e,operation:`update`,firstLine:null,verbose:a}),children:(0,gH.jsx)(Fqe,{promise:o,filePath:e,style:i,verbose:a})})}function Fqe({promise:e,filePath:t,style:n,verbose:r}){let{patch:i,firstLine:a,fileContent:o}=(0,hH.use)(e);return(0,gH.jsx)(aH,{file_path:t,operation:`update`,patch:i,firstLine:a,fileContent:o,style:n,verbose:r})}async function Iqe(e,t,n,r){try{let i=await Sqe(e,t,3);if(i===null||i.truncated||i.content===``){let{patch:r}=iI({filePath:e,fileContents:t,oldString:t,newString:n});return{patch:r,firstLine:null,fileContent:void 0}}let a=rI(i.content,t)||t,{patch:o}=iI({filePath:e,fileContents:i.content,oldString:a,newString:n,replaceAll:r});return{patch:KF(o,i.lineOffset-1),firstLine:i.lineOffset===1?Ka(i.content):null,fileContent:i.content}}catch(e){return q(e),{patch:[],firstLine:null,fileContent:void 0}}}var hH,gH,Lqe=n((()=>{hH=r(ze(),1),yqe(),ob(),p3(),mb(),xqe(),I(),gb(),tI(),gi(),oa(),$d(),mH(),Ja(),cI(),gH=tt()}));function _H(e,t=``){return RegExp(`\\bgit(?:\\s+-[cC]\\s+\\S+|\\s+--\\S+=\\S+)*\\s+${e}\\b${t}`)}function Rqe(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 zqe(e){let t=e.match(/https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/\d+/);return t?Rqe(t[0]):null}function Bqe(e){return e.match(/\[[\w./-]+(?: \(root-commit\))? ([0-9a-f]+)\]/)?.[1]}function Vqe(e){return e.match(/^\s*[+\-*!= ]?\s*(?:\[new branch\]|\S+\.\.+\S+)\s+\S+\s*->\s*(\S+)/m)?.[1]}function Hqe(e){let t=e.match(/[Pp]ull request (?:\S+#)?#?(\d+)/);return t?.[1]?parseInt(t[1],10):void 0}function Uqe(e,t){let n=e.split(_H(t))[1];if(n)for(let e of n.trim().split(/\s+/)){if(/^[&|;><]/.test(e))break;if(!e.startsWith(`-`))return e}}function Wqe(e,t){let n={},r=Kqe.test(e);if(vH.test(e)||r){let i=Bqe(t);i&&(n.commit={sha:i.slice(0,6),kind:r?`cherry-picked`:/--amend\b/.test(e)?`amended`:`committed`})}if(yH.test(e)){let e=Vqe(t);e&&(n.push={branch:e})}if(qqe.test(e)&&/(Fast-forward|Merge made by)/.test(t)){let t=Uqe(e,`merge`);t&&(n.branch={ref:t,action:`merged`})}if(Jqe.test(e)&&/Successfully rebased/.test(t)){let t=Uqe(e,`rebase`);t&&(n.branch={ref:t,action:`rebased`})}let i=bH.find(t=>t.re.test(e))?.action;if(i){let e=zqe(t);if(e)n.pr={number:e.prNumber,url:e.prUrl,action:i};else{let e=Hqe(t);e&&(n.pr={number:e,action:i})}}return n}function Gqe(e,t,n){if(t!==0)return;vH.test(e)&&(J(`tengu_git_operation`,{operation:`commit`}),e.match(/--amend\b/)&&J(`tengu_git_operation`,{operation:`commit_amend`}),ate()?.add(1)),yH.test(e)&&J(`tengu_git_operation`,{operation:`push`});let r=bH.find(t=>t.re.test(e));if(r&&J(`tengu_git_operation`,{operation:r.op}),r?.action===`created`&&(fn()?.add(1),n)){let e=zqe(n);e&&import(`./sessionStorage-D6nlmaI-.js`).then(({linkSessionToPR:t})=>{import(`./state-CsdHk8n-.js`).then(({getSessionId:n})=>{let r=n();r&&t(r,e.prNumber,e.prUrl,e.prRepository)})})}e.match(/\bglab\s+mr\s+create\b/)&&(J(`tengu_git_operation`,{operation:`pr_create`}),fn()?.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&&(J(`tengu_git_operation`,{operation:`pr_create`}),fn()?.add(1))}var vH,yH,Kqe,qqe,Jqe,bH,xH=n((()=>{Gt(),Na(),vH=_H(`commit`),yH=_H(`push`),Kqe=_H(`cherry-pick`),qqe=_H(`merge`,`(?!-)`),Jqe=_H(`rebase`),bH=[{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 Yqe(e){let t=Zqe(e),n=eJe.get(t);return n===void 0?$qe:n}function Xqe(e){return e.trim().split(/\s+/)[0]||``}function Zqe(e){let t=i9(e);return Xqe(t[t.length-1]||e)}function Qqe(e,t,n,r){let i=Yqe(e)(t,n,r);return{isError:i.isError,message:i.message}}var $qe,eJe,tJe=n((()=>{h9(),$qe=(e,t,n)=>({isError:e!==0,message:e===0?void 0:`Command failed with exit code ${e}`}),eJe=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 nJe(){return Ui(Cn())??Zt()}function rJe(){return process.env.CLAUDE_CODE_ENTRYPOINT??`cli`}function iJe(){return{fileStates:new Map,sessionBaselines:new Map,surface:rJe(),startingHeadSha:null,promptCount:0,promptCountAtLastCommit:0,permissionPromptCount:0,permissionPromptCountAtLastCommit:0,escapeCount:0,escapeCountAtLastCommit:0}}function aJe(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 oJe(e,t){let n={...e,promptCount:e.promptCount+1};return t(aJe(n,tu())),n}var sJe,SH,CH=n((()=>{Gt(),Sn(),W(),qi(),Un(),Fi(),Bi(),oa(),Lo(),bo(),sJe=`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(`,`),SH=null,Eae(async()=>{if(SH!==null)return SH===`internal`;let e=await mie(nJe());if(!e)return SH=`none`,!1;let t=sJe.some(t=>e.includes(t));return SH=t?`internal`:`external`,t})}));function cJe(e){let t=e.toLowerCase();for(let{keywords:e,email:n}of lJe)if(e.some(e=>t.includes(e)))return n;return`noreply@anthropic.com`}var lJe,uJe=n((()=>{lJe=[{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 dJe(e){switch(eo()){case`openai`:return Nse(e);case`gemini`:return fc(e);case`grok`:return Mse(e);default:return e}}function fJe(){return dJe(ts())}var pJe=n((()=>{ac(),Lo(),es()})),wH,TH,EH,mJe,DH=n((()=>{_t(),vt(),tV(),wH=gt(()=>dt({file_path:L().describe(`The absolute path to the file to modify`),old_string:L().describe(`The text to replace`),new_string:L().describe(`The text to replace it with (must be different from old_string)`),replace_all:eV(pt().default(!1).optional()).describe(`Replace all occurrences of old_string (default false)`)})),TH=gt(()=>B({oldStart:R(),oldLines:R(),newStart:R(),newLines:R(),lines:z(L())})),EH=gt(()=>B({filename:L(),status:ft([`modified`,`added`]),additions:R(),deletions:R(),changes:R(),patch:L(),repository:L().nullable().optional().describe(`GitHub owner/repo when available`)})),mJe=gt(()=>B({filePath:L().describe(`The file path that was edited`),oldString:L().describe(`The original string that was replaced`),newString:L().describe(`The new string that replaced it`),originalFile:L().describe(`The original file contents before editing`),structuredPatch:z(TH()).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:EH().optional()}))}));function hJe({serverName:e,files:t}){let n=tu();U(`LSP Diagnostics: Registering ${t.length} diagnostic file(s) from ${e} (ID: ${n})`),AH.set(n,{serverName:e,files:t,timestamp:Date.now(),attachmentSent:!1})}function gJe(e){switch(e){case`Error`:return 1;case`Warning`:return 2;case`Info`:return 3;case`Hint`:return 4;default:return 4}}function _Je(e){return V({message:e.message,severity:e.severity,range:e.range,source:e.source||null,code:e.code||null})}function vJe(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=jH.get(r.uri)||new Set;for(let t of r.diagnostics)try{let n=_Je(t);if(e.has(n)||a.has(n))continue;e.add(n),i.diagnostics.push(t)}catch(e){let n=Fn(e),a=t.message?.substring(0,100)||`<no message>`;q(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 yJe(){U(`LSP Diagnostics: Checking registry - ${AH.size} pending`);let e=[],t=new Set,n=[];for(let r of AH.values())r.attachmentSent||(e.push(...r.files),t.add(r.serverName),n.push(r));if(e.length===0)return[];let r;try{r=vJe(e)}catch(t){let n=Fn(t);q(Error(`Failed to deduplicate LSP diagnostics: ${n.message}`)),r=e}for(let e of n)e.attachmentSent=!0;for(let[e,t]of AH)t.attachmentSent&&AH.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&&U(`LSP Diagnostics: Deduplication removed ${i-a} duplicate diagnostic(s)`);let o=0,s=0;for(let e of r){e.diagnostics.sort((e,t)=>gJe(e.severity)-gJe(t.severity)),e.diagnostics.length>OH&&(s+=e.diagnostics.length-OH,e.diagnostics=e.diagnostics.slice(0,OH));let t=kH-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&&U(`LSP Diagnostics: Volume limiting removed ${s} diagnostic(s) (max ${OH}/file, ${kH} total)`);for(let e of r){jH.has(e.uri)||jH.set(e.uri,new Set);let t=jH.get(e.uri);for(let n of e.diagnostics)try{t.add(_Je(n))}catch(t){let r=Fn(t),i=n.message?.substring(0,100)||`<no message>`;q(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?(U(`LSP Diagnostics: No new diagnostics to deliver (all filtered by deduplication)`),[]):(U(`LSP Diagnostics: Delivering ${r.length} file(s) with ${c} diagnostic(s) from ${t.size} server(s)`),[{serverName:Array.from(t).join(`, `),files:r}])}function bJe(){U(`LSP Diagnostics: Clearing ${AH.size} pending diagnostic(s)`),AH.clear()}function xJe(){U(`LSP Diagnostics: Resetting all state (${AH.size} pending, ${jH.size} files tracked)`),AH.clear(),jH.clear()}function SJe(e){jH.has(e)&&(U(`LSP Diagnostics: Clearing delivered diagnostics for ${e}`),jH.delete(e))}var OH,kH,CJe,AH,jH,MH=n((()=>{da(),W(),Mn(),oa(),Zn(),OH=10,kH=30,CJe=500,AH=new Map,jH=new fa({max:CJe})}));function wJe(e,t){let n=Ml(e),r=Ml(e,t),i=jl(n,r);return i.startsWith(`..`)||Ml(i)===i?null:r}async function TJe(e,t=[]){let n={},r=Y(e.path,`.lsp.json`);try{let i=Nn(await lu(r,`utf-8`)),a=it(L(),Jr()).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}`;q(Error(n)),t.push({type:`lsp-config-invalid`,plugin:e.name,serverName:`.lsp.json`,validationError:a.error.message,source:`plugin`})}}catch(n){Tn(n)||(n instanceof Error?`${e.name}${n.message}`:`${e.name}`,q(Fn(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 EJe(e.manifest.lspServers,e.path,e.name,t);r&&Object.assign(n,r)}return Object.keys(n).length>0?n:void 0}async function EJe(e,t,n,r){let i={},a=Array.isArray(e)?e:[e];for(let e of a)if(typeof e==`string`){let a=wJe(t,e);if(!a){let t=`Security: Path traversal attempt blocked in plugin ${n}: ${e}`;q(Error(t)),U(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=Nn(await lu(a,`utf-8`)),o=it(L(),Jr()).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}`;q(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}`,q(Fn(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=Jr().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}`;q(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 DJe(e,t,n,r){let i=[],a=e=>{let r=Tw(e,t);n&&(r=Ew(r,n));let{expanded:a,missingVars:o}=uw(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:Og(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(`, `)}`;q(Error(e)),U(e,{level:`warn`})}return o}function OJe(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 kJe(e,t=[]){if(!e.enabled)return;let n=e.lspServers||await TJe(e,t);if(!n)return;let r=e.manifest.userConfig?Dw(Cw(e)):void 0,i={};for(let[a,o]of Object.entries(n))i[a]=DJe(o,e,r,t);return OJe(i,e.name)}var AJe=n((()=>{_t(),dw(),W(),Mn(),oa(),Zn(),kg(),Ow(),hi()}));async function jJe(){let e={};try{let{enabled:t}=await l4(),n=await Promise.all(t.map(async e=>{let t=[];try{return{plugin:e,scopedServers:await kJe(e,t),errors:t}}catch(n){return U(`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),U(`Loaded ${n} LSP server(s) from plugin: ${t.name}`)),i.length>0&&U(`${i.length} error(s) loading LSP servers from plugin: ${t.name}`)}U(`Total LSP servers loaded: ${Object.keys(e).length}`)}catch(e){q(Fn(e)),U(`Error loading LSP servers: ${H(e)}`)}return{servers:e}}var MJe=n((()=>{W(),Mn(),oa(),AJe(),u4()})),NH=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})),NJe=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=NH(),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={}))})),PJe=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))}}})),FJe=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={}))})),PH=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})),FH=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Emitter=e.Event=void 0;var t=PH(),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(){}})),IH=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CancellationTokenSource=e.CancellationToken=void 0;var t=PH(),n=NH(),r=FH(),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}}})),IJe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SharedArrayReceiverStrategy=e.SharedArraySenderStrategy=void 0;var t=IH(),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)}}})),LJe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Semaphore=void 0;var t=PH();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()}}}})),RJe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ReadableStreamMessageReader=e.AbstractMessageReader=e.MessageReader=void 0;var t=PH(),n=NH(),r=FH(),i=LJe(),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))}}})),zJe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.WriteableStreamMessageWriter=e.AbstractMessageWriter=e.MessageWriter=void 0;var t=PH(),n=NH(),r=LJe(),i=FH(),a=`Content-Length: `,o=`\r
|
|
1163
|
+
`)[0]??null,fileContent:n,style:i,verbose:a,previewHint:o?`/plan to preview`:void 0})}function Mqe(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,gH.jsx)(aH,{file_path:i,operation:`update`,firstLine:null,verbose:r}):a===``?(0,gH.jsx)(aH,{file_path:i,operation:`write`,content:o,firstLine:Ka(o),verbose:r}):(0,gH.jsx)(Pqe,{filePath:i,oldString:a,newString:o,replaceAll:s,style:n,verbose:r})}function Nqe(e,t){let{verbose:n}=t;return!n&&typeof e==`string`&&j4(e,`tool_use_error`)?j4(e,`tool_use_error`)?.includes(`Note: your current working directory is`)?(0,gH.jsx)(Z,{children:(0,gH.jsx)(F,{color:`error`,children:`File not found`})}):(0,gH.jsx)(Z,{children:(0,gH.jsx)(F,{color:`error`,children:`Error editing file`})}):(0,gH.jsx)(db,{result:e,verbose:n})}function Pqe({filePath:e,oldString:t,newString:n,replaceAll:r,style:i,verbose:a}){let[o]=(0,hH.useState)(()=>Iqe(e,t,n,r));return(0,gH.jsx)(hH.Suspense,{fallback:(0,gH.jsx)(aH,{file_path:e,operation:`update`,firstLine:null,verbose:a}),children:(0,gH.jsx)(Fqe,{promise:o,filePath:e,style:i,verbose:a})})}function Fqe({promise:e,filePath:t,style:n,verbose:r}){let{patch:i,firstLine:a,fileContent:o}=(0,hH.use)(e);return(0,gH.jsx)(aH,{file_path:t,operation:`update`,patch:i,firstLine:a,fileContent:o,style:n,verbose:r})}async function Iqe(e,t,n,r){try{let i=await Sqe(e,t,3);if(i===null||i.truncated||i.content===``){let{patch:r}=iI({filePath:e,fileContents:t,oldString:t,newString:n});return{patch:r,firstLine:null,fileContent:void 0}}let a=rI(i.content,t)||t,{patch:o}=iI({filePath:e,fileContents:i.content,oldString:a,newString:n,replaceAll:r});return{patch:KF(o,i.lineOffset-1),firstLine:i.lineOffset===1?Ka(i.content):null,fileContent:i.content}}catch(e){return q(e),{patch:[],firstLine:null,fileContent:void 0}}}var hH,gH,Lqe=n((()=>{hH=r(ze(),1),yqe(),ob(),p3(),mb(),xqe(),I(),gb(),tI(),gi(),oa(),$d(),mH(),Ja(),cI(),gH=tt()}));function _H(e,t=``){return RegExp(`\\bgit(?:\\s+-[cC]\\s+\\S+|\\s+--\\S+=\\S+)*\\s+${e}\\b${t}`)}function Rqe(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 zqe(e){let t=e.match(/https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/\d+/);return t?Rqe(t[0]):null}function Bqe(e){return e.match(/\[[\w./-]+(?: \(root-commit\))? ([0-9a-f]+)\]/)?.[1]}function Vqe(e){return e.match(/^\s*[+\-*!= ]?\s*(?:\[new branch\]|\S+\.\.+\S+)\s+\S+\s*->\s*(\S+)/m)?.[1]}function Hqe(e){let t=e.match(/[Pp]ull request (?:\S+#)?#?(\d+)/);return t?.[1]?parseInt(t[1],10):void 0}function Uqe(e,t){let n=e.split(_H(t))[1];if(n)for(let e of n.trim().split(/\s+/)){if(/^[&|;><]/.test(e))break;if(!e.startsWith(`-`))return e}}function Wqe(e,t){let n={},r=Kqe.test(e);if(vH.test(e)||r){let i=Bqe(t);i&&(n.commit={sha:i.slice(0,6),kind:r?`cherry-picked`:/--amend\b/.test(e)?`amended`:`committed`})}if(yH.test(e)){let e=Vqe(t);e&&(n.push={branch:e})}if(qqe.test(e)&&/(Fast-forward|Merge made by)/.test(t)){let t=Uqe(e,`merge`);t&&(n.branch={ref:t,action:`merged`})}if(Jqe.test(e)&&/Successfully rebased/.test(t)){let t=Uqe(e,`rebase`);t&&(n.branch={ref:t,action:`rebased`})}let i=bH.find(t=>t.re.test(e))?.action;if(i){let e=zqe(t);if(e)n.pr={number:e.prNumber,url:e.prUrl,action:i};else{let e=Hqe(t);e&&(n.pr={number:e,action:i})}}return n}function Gqe(e,t,n){if(t!==0)return;vH.test(e)&&(J(`tengu_git_operation`,{operation:`commit`}),e.match(/--amend\b/)&&J(`tengu_git_operation`,{operation:`commit_amend`}),ate()?.add(1)),yH.test(e)&&J(`tengu_git_operation`,{operation:`push`});let r=bH.find(t=>t.re.test(e));if(r&&J(`tengu_git_operation`,{operation:r.op}),r?.action===`created`&&(fn()?.add(1),n)){let e=zqe(n);e&&import(`./sessionStorage-CiYSwyY3.js`).then(({linkSessionToPR:t})=>{import(`./state-CsdHk8n-.js`).then(({getSessionId:n})=>{let r=n();r&&t(r,e.prNumber,e.prUrl,e.prRepository)})})}e.match(/\bglab\s+mr\s+create\b/)&&(J(`tengu_git_operation`,{operation:`pr_create`}),fn()?.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&&(J(`tengu_git_operation`,{operation:`pr_create`}),fn()?.add(1))}var vH,yH,Kqe,qqe,Jqe,bH,xH=n((()=>{Gt(),Na(),vH=_H(`commit`),yH=_H(`push`),Kqe=_H(`cherry-pick`),qqe=_H(`merge`,`(?!-)`),Jqe=_H(`rebase`),bH=[{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 Yqe(e){let t=Zqe(e),n=eJe.get(t);return n===void 0?$qe:n}function Xqe(e){return e.trim().split(/\s+/)[0]||``}function Zqe(e){let t=i9(e);return Xqe(t[t.length-1]||e)}function Qqe(e,t,n,r){let i=Yqe(e)(t,n,r);return{isError:i.isError,message:i.message}}var $qe,eJe,tJe=n((()=>{h9(),$qe=(e,t,n)=>({isError:e!==0,message:e===0?void 0:`Command failed with exit code ${e}`}),eJe=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 nJe(){return Ui(Cn())??Zt()}function rJe(){return process.env.CLAUDE_CODE_ENTRYPOINT??`cli`}function iJe(){return{fileStates:new Map,sessionBaselines:new Map,surface:rJe(),startingHeadSha:null,promptCount:0,promptCountAtLastCommit:0,permissionPromptCount:0,permissionPromptCountAtLastCommit:0,escapeCount:0,escapeCountAtLastCommit:0}}function aJe(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 oJe(e,t){let n={...e,promptCount:e.promptCount+1};return t(aJe(n,tu())),n}var sJe,SH,CH=n((()=>{Gt(),Sn(),W(),qi(),Un(),Fi(),Bi(),oa(),Lo(),bo(),sJe=`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(`,`),SH=null,Eae(async()=>{if(SH!==null)return SH===`internal`;let e=await mie(nJe());if(!e)return SH=`none`,!1;let t=sJe.some(t=>e.includes(t));return SH=t?`internal`:`external`,t})}));function cJe(e){let t=e.toLowerCase();for(let{keywords:e,email:n}of lJe)if(e.some(e=>t.includes(e)))return n;return`noreply@anthropic.com`}var lJe,uJe=n((()=>{lJe=[{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 dJe(e){switch(eo()){case`openai`:return Nse(e);case`gemini`:return fc(e);case`grok`:return Mse(e);default:return e}}function fJe(){return dJe(ts())}var pJe=n((()=>{ac(),Lo(),es()})),wH,TH,EH,mJe,DH=n((()=>{_t(),vt(),tV(),wH=gt(()=>dt({file_path:L().describe(`The absolute path to the file to modify`),old_string:L().describe(`The text to replace`),new_string:L().describe(`The text to replace it with (must be different from old_string)`),replace_all:eV(pt().default(!1).optional()).describe(`Replace all occurrences of old_string (default false)`)})),TH=gt(()=>B({oldStart:R(),oldLines:R(),newStart:R(),newLines:R(),lines:z(L())})),EH=gt(()=>B({filename:L(),status:ft([`modified`,`added`]),additions:R(),deletions:R(),changes:R(),patch:L(),repository:L().nullable().optional().describe(`GitHub owner/repo when available`)})),mJe=gt(()=>B({filePath:L().describe(`The file path that was edited`),oldString:L().describe(`The original string that was replaced`),newString:L().describe(`The new string that replaced it`),originalFile:L().describe(`The original file contents before editing`),structuredPatch:z(TH()).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:EH().optional()}))}));function hJe({serverName:e,files:t}){let n=tu();U(`LSP Diagnostics: Registering ${t.length} diagnostic file(s) from ${e} (ID: ${n})`),AH.set(n,{serverName:e,files:t,timestamp:Date.now(),attachmentSent:!1})}function gJe(e){switch(e){case`Error`:return 1;case`Warning`:return 2;case`Info`:return 3;case`Hint`:return 4;default:return 4}}function _Je(e){return V({message:e.message,severity:e.severity,range:e.range,source:e.source||null,code:e.code||null})}function vJe(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=jH.get(r.uri)||new Set;for(let t of r.diagnostics)try{let n=_Je(t);if(e.has(n)||a.has(n))continue;e.add(n),i.diagnostics.push(t)}catch(e){let n=Fn(e),a=t.message?.substring(0,100)||`<no message>`;q(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 yJe(){U(`LSP Diagnostics: Checking registry - ${AH.size} pending`);let e=[],t=new Set,n=[];for(let r of AH.values())r.attachmentSent||(e.push(...r.files),t.add(r.serverName),n.push(r));if(e.length===0)return[];let r;try{r=vJe(e)}catch(t){let n=Fn(t);q(Error(`Failed to deduplicate LSP diagnostics: ${n.message}`)),r=e}for(let e of n)e.attachmentSent=!0;for(let[e,t]of AH)t.attachmentSent&&AH.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&&U(`LSP Diagnostics: Deduplication removed ${i-a} duplicate diagnostic(s)`);let o=0,s=0;for(let e of r){e.diagnostics.sort((e,t)=>gJe(e.severity)-gJe(t.severity)),e.diagnostics.length>OH&&(s+=e.diagnostics.length-OH,e.diagnostics=e.diagnostics.slice(0,OH));let t=kH-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&&U(`LSP Diagnostics: Volume limiting removed ${s} diagnostic(s) (max ${OH}/file, ${kH} total)`);for(let e of r){jH.has(e.uri)||jH.set(e.uri,new Set);let t=jH.get(e.uri);for(let n of e.diagnostics)try{t.add(_Je(n))}catch(t){let r=Fn(t),i=n.message?.substring(0,100)||`<no message>`;q(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?(U(`LSP Diagnostics: No new diagnostics to deliver (all filtered by deduplication)`),[]):(U(`LSP Diagnostics: Delivering ${r.length} file(s) with ${c} diagnostic(s) from ${t.size} server(s)`),[{serverName:Array.from(t).join(`, `),files:r}])}function bJe(){U(`LSP Diagnostics: Clearing ${AH.size} pending diagnostic(s)`),AH.clear()}function xJe(){U(`LSP Diagnostics: Resetting all state (${AH.size} pending, ${jH.size} files tracked)`),AH.clear(),jH.clear()}function SJe(e){jH.has(e)&&(U(`LSP Diagnostics: Clearing delivered diagnostics for ${e}`),jH.delete(e))}var OH,kH,CJe,AH,jH,MH=n((()=>{da(),W(),Mn(),oa(),Zn(),OH=10,kH=30,CJe=500,AH=new Map,jH=new fa({max:CJe})}));function wJe(e,t){let n=Ml(e),r=Ml(e,t),i=jl(n,r);return i.startsWith(`..`)||Ml(i)===i?null:r}async function TJe(e,t=[]){let n={},r=Y(e.path,`.lsp.json`);try{let i=Nn(await lu(r,`utf-8`)),a=it(L(),Jr()).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}`;q(Error(n)),t.push({type:`lsp-config-invalid`,plugin:e.name,serverName:`.lsp.json`,validationError:a.error.message,source:`plugin`})}}catch(n){Tn(n)||(n instanceof Error?`${e.name}${n.message}`:`${e.name}`,q(Fn(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 EJe(e.manifest.lspServers,e.path,e.name,t);r&&Object.assign(n,r)}return Object.keys(n).length>0?n:void 0}async function EJe(e,t,n,r){let i={},a=Array.isArray(e)?e:[e];for(let e of a)if(typeof e==`string`){let a=wJe(t,e);if(!a){let t=`Security: Path traversal attempt blocked in plugin ${n}: ${e}`;q(Error(t)),U(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=Nn(await lu(a,`utf-8`)),o=it(L(),Jr()).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}`;q(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}`,q(Fn(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=Jr().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}`;q(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 DJe(e,t,n,r){let i=[],a=e=>{let r=Tw(e,t);n&&(r=Ew(r,n));let{expanded:a,missingVars:o}=uw(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:Og(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(`, `)}`;q(Error(e)),U(e,{level:`warn`})}return o}function OJe(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 kJe(e,t=[]){if(!e.enabled)return;let n=e.lspServers||await TJe(e,t);if(!n)return;let r=e.manifest.userConfig?Dw(Cw(e)):void 0,i={};for(let[a,o]of Object.entries(n))i[a]=DJe(o,e,r,t);return OJe(i,e.name)}var AJe=n((()=>{_t(),dw(),W(),Mn(),oa(),Zn(),kg(),Ow(),hi()}));async function jJe(){let e={};try{let{enabled:t}=await l4(),n=await Promise.all(t.map(async e=>{let t=[];try{return{plugin:e,scopedServers:await kJe(e,t),errors:t}}catch(n){return U(`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),U(`Loaded ${n} LSP server(s) from plugin: ${t.name}`)),i.length>0&&U(`${i.length} error(s) loading LSP servers from plugin: ${t.name}`)}U(`Total LSP servers loaded: ${Object.keys(e).length}`)}catch(e){q(Fn(e)),U(`Error loading LSP servers: ${H(e)}`)}return{servers:e}}var MJe=n((()=>{W(),Mn(),oa(),AJe(),u4()})),NH=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})),NJe=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=NH(),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={}))})),PJe=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))}}})),FJe=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={}))})),PH=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})),FH=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Emitter=e.Event=void 0;var t=PH(),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(){}})),IH=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CancellationTokenSource=e.CancellationToken=void 0;var t=PH(),n=NH(),r=FH(),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}}})),IJe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SharedArrayReceiverStrategy=e.SharedArraySenderStrategy=void 0;var t=IH(),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)}}})),LJe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Semaphore=void 0;var t=PH();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()}}}})),RJe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ReadableStreamMessageReader=e.AbstractMessageReader=e.MessageReader=void 0;var t=PH(),n=NH(),r=FH(),i=LJe(),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))}}})),zJe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.WriteableStreamMessageWriter=e.AbstractMessageWriter=e.MessageWriter=void 0;var t=PH(),n=NH(),r=LJe(),i=FH(),a=`Content-Length: `,o=`\r
|
|
1164
1164
|
`,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()}}})),BJe=a((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AbstractMessageBuffer=void 0;var t=13,n=10,r=`\r
|
|
1165
1165
|
`;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}}})),VJe=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=PH(),n=NH(),r=NJe(),i=PJe(),a=FH(),o=IH(),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 P(){(N===E.New||N===E.Listening)&&(N=E.Closed,ue.fire(void 0))}function Ce(e){le.fire([e,void 0,void 0])}function we(e){le.fire(e)}f.onClose(P),f.onError(Ce),v.onClose(P),v.onError(we);function Te(){re||ie.size===0||(re=(0,t.default)().timer.setImmediate(()=>{re=void 0,F()}))}function Ee(e){r.Message.isRequest(e)?Oe(e):r.Message.isNotification(e)?Ae(e):r.Message.isResponse(e)?ke(e):je(e)}function F(){if(ie.size===0)return;let e=ie.shift();try{let t=x?.messageStrategy;w.is(t)?t.handleMessage(e,Ee):Ee(e)}finally{Te()}}let De=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,Fe(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(),Le(e);return}else j.add(t)}ve(ie,e)}finally{Te()}};function Oe(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,Fe(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()};Fe(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};Fe(i,n,r),v.write(i).catch(()=>S.error(`Sending response failed.`))}Ie(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 ke(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(eee(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 Ae(e){if(Se())return;let t,n;if(e.method===s.type.method){let t=e.params.id;j.delete(t),Le(e);return}else{let r=te.get(e.method);r&&(n=r.handler,t=r.type)}if(n||ee)try{if(Le(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 je(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 Me(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 Ne(e){if(!(se===d.Off||!M))if(ce===p.Text){let t;(se===d.Verbose||se===d.Compact)&&e.params&&(t=`Params: ${Me(e.params)}\n\n`),M.log(`Sending request '${e.method} - (${e.id})'.`,t)}else Re(`send-request`,e)}function Pe(e){if(!(se===d.Off||!M))if(ce===p.Text){let t;(se===d.Verbose||se===d.Compact)&&(t=e.params?`Params: ${Me(e.params)}\n\n`:`No parameters provided.
|
|
1166
1166
|
|
|
@@ -1604,7 +1604,7 @@ Guidelines:
|
|
|
1604
1604
|
- For analysis: Start broad and narrow down. Use multiple search strategies if the first doesn't yield results.
|
|
1605
1605
|
- Be thorough: Check multiple locations, consider different naming conventions, look for related files.
|
|
1606
1606
|
- NEVER create files unless they're absolutely necessary for achieving your goal. ALWAYS prefer editing an existing file to creating a new one.
|
|
1607
|
-
- NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested.`,sK={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:s4e}}));function u4e(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 lK(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 d4e(e){let t=[];if(Ur(`policySettings`)?.allowManagedHooksOnly!==!0){let e=[`userSettings`,`projectSettings`,`localSettings`],n=new Set;for(let r of e){let e=li(r);if(e){let t=Ml(e);if(n.has(t))continue;n.add(t)}let i=Ur(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=x4e(e,ln());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 f4e(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 p4e(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 m4e(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 h4e(e,t,n){let r=Are.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 uK=n((()=>{Gt(),ti(),Yr(),Vne(),fK()}));function g4e(e,t,n,r,i,a,o){v4e(e,t,n,r,i,a,o)}function _4e(e,t,n,r,i,a,o){let s=o?.id||`function-hook-${Date.now()}-${Math.random()}`;return v4e(e,t,n,r,{type:`function`,id:s,timeout:o?.timeout||5e3,callback:i,errorMessage:a}),s}function v4e(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}),U(`Added session hook for event ${n} in session ${t}`)}function y4e(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=>!u4e(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}),U(`Removed session hook for event ${n} in session ${t}`)}function b4e(e){return e.map(e=>({matcher:e.matcher,skillRoot:e.skillRoot,hooks:e.hooks.map(e=>e.hook).filter(e=>e.type!==`function`)}))}function x4e(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,b4e(e)),i}for(let e of br){let t=r.hooks[e];t&&i.set(e,b4e(t))}return i}function S4e(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 br){let t=r.hooks[e];if(t){let n=a(t);n.length>0&&i.set(e,n)}}return i}function C4e(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=>u4e(e.hook,i));if(t)return t}}}function dK(e,t){e(e=>(e.sessionHooks.delete(t),e)),U(`Cleared all session hooks for session ${t}`)}var fK=n((()=>{rr(),W(),uK()}));function w4e(e,t,n,r,i=!1){if(!n||Object.keys(n).length===0)return;let a=0;for(let o of br){let s=n[o];if(!s||s.length===0)continue;let c=o;i&&o===`Stop`&&(c=`SubagentStop`,U(`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)g4e(e,t,c,r,n),a++}}a>0&&U(`Registered ${a} frontmatter hook(s) from ${r} for session ${t}`)}var T4e=n((()=>{rr(),W(),fK()}));async function E4e(e,t){if(!e.mcpServers?.length)return{clients:t,tools:[],cleanup:async()=>{}};let n=J_(e.source);if(q_(`mcp`)&&!n)return U(`[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=Xw(t),!n){U(`[Agent: ${e.agentType}] MCP server not found: ${t}`,{level:`warn`});continue}}else{let r=Object.entries(t);if(r.length!==1){U(`[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 rM(o,n);if(r.push(c),s&&i.push(c),c.type===`connected`){let t=await aM(c);a.push(...t),U(`[Agent: ${e.agentType}] Connected to MCP server '${o}' with ${t.length} tools`)}else U(`[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){U(`[Agent: ${e.agentType}] Error cleaning up MCP server '${t.name}': ${n}`,{level:`warn`})}};return{clients:[...t,...r],tools:a,cleanup:o}}function D4e(e){return e.type===`assistant`||e.type===`user`||e.type===`progress`||e.type===`system`&&`subtype`in e&&e.subtype===`compact_boundary`}async function*pK({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=a2e(e.model,n.options.mainLoopModel,l,S),T=c?.agentId?c.agentId:GG();if(y&&a6(T,y),Sce()){let t=n.agentId??ln();wce(T,e.agentType,t)}let E=[...o?zG(o):[],...t],D=o===void 0?wP(100):DP(n.readFileState),[O,k]=await Promise.all([c?.userContext??YR(),c?.systemContext??JR()]),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:n4e(e,f,i).resolvedTools,ce=Array.from(x.toolPermissionContext.additionalWorkingDirectories.keys()),M=c?.systemPrompt?c.systemPrompt:rc(await O4e(e,n,w,ce,se)),N=c?.abortController?c.abortController:i?new AbortController:n.abortController,le=[];for await(let t of gEt(T,e.agentType,N.signal))t.additionalContexts&&t.additionalContexts.length>0&&le.push(...t.additionalContexts);if(le.length>0){let e=j0({type:`hook_additional_context`,content:le,hookName:`SubagentStart`,toolUseID:tu(),hookEvent:`SubagentStart`});E.push(e)}let ue=!q_(`hooks`)||J_(e.source);e.hooks&&ue&&w4e(C,T,e.hooks,`agent '${e.agentType}'`,!0);let de=e.skills??[];if(de.length>0){let t=await X3(tn()),r=[];for(let n of de){let i=k4e(n,t,e);if(!i){U(`[Agent: ${e.agentType}] Warning: Skill '${n}' specified in frontmatter was not found`,{level:`warn`});continue}let a=qSt(i,t);if(a.type!==`prompt`){U(`[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-U9LJ4Keq.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){U(`[Agent: ${e.agentType}] Preloaded skill '${t}'`);let a=i(t,n.progressMessage);E.push($({content:[{type:`text`,text:a},...r],isMeta:!0}))}}let{clients:fe,tools:pe,cleanup:me}=await E4e(e,n.options.mcpClients),he=pe.length>0?Qp([...se,...pe],`name`):se,ge=F1(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}),_6(E,T).catch(e=>U(`Failed to record sidechain transcript: ${e}`)),c6(T,{agentType:e.agentType,..._&&{worktreePath:_},...v&&{description:v}}).catch(e=>U(`Failed to write agent metadata: ${e}`));let _e=E.at(-1)?.uuid??null;try{for await(let t of A1({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`){U(`[Agent
|
|
1607
|
+
- NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested.`,sK={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:s4e}}));function u4e(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 lK(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 d4e(e){let t=[];if(Ur(`policySettings`)?.allowManagedHooksOnly!==!0){let e=[`userSettings`,`projectSettings`,`localSettings`],n=new Set;for(let r of e){let e=li(r);if(e){let t=Ml(e);if(n.has(t))continue;n.add(t)}let i=Ur(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=x4e(e,ln());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 f4e(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 p4e(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 m4e(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 h4e(e,t,n){let r=Are.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 uK=n((()=>{Gt(),ti(),Yr(),Vne(),fK()}));function g4e(e,t,n,r,i,a,o){v4e(e,t,n,r,i,a,o)}function _4e(e,t,n,r,i,a,o){let s=o?.id||`function-hook-${Date.now()}-${Math.random()}`;return v4e(e,t,n,r,{type:`function`,id:s,timeout:o?.timeout||5e3,callback:i,errorMessage:a}),s}function v4e(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}),U(`Added session hook for event ${n} in session ${t}`)}function y4e(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=>!u4e(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}),U(`Removed session hook for event ${n} in session ${t}`)}function b4e(e){return e.map(e=>({matcher:e.matcher,skillRoot:e.skillRoot,hooks:e.hooks.map(e=>e.hook).filter(e=>e.type!==`function`)}))}function x4e(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,b4e(e)),i}for(let e of br){let t=r.hooks[e];t&&i.set(e,b4e(t))}return i}function S4e(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 br){let t=r.hooks[e];if(t){let n=a(t);n.length>0&&i.set(e,n)}}return i}function C4e(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=>u4e(e.hook,i));if(t)return t}}}function dK(e,t){e(e=>(e.sessionHooks.delete(t),e)),U(`Cleared all session hooks for session ${t}`)}var fK=n((()=>{rr(),W(),uK()}));function w4e(e,t,n,r,i=!1){if(!n||Object.keys(n).length===0)return;let a=0;for(let o of br){let s=n[o];if(!s||s.length===0)continue;let c=o;i&&o===`Stop`&&(c=`SubagentStop`,U(`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)g4e(e,t,c,r,n),a++}}a>0&&U(`Registered ${a} frontmatter hook(s) from ${r} for session ${t}`)}var T4e=n((()=>{rr(),W(),fK()}));async function E4e(e,t){if(!e.mcpServers?.length)return{clients:t,tools:[],cleanup:async()=>{}};let n=J_(e.source);if(q_(`mcp`)&&!n)return U(`[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=Xw(t),!n){U(`[Agent: ${e.agentType}] MCP server not found: ${t}`,{level:`warn`});continue}}else{let r=Object.entries(t);if(r.length!==1){U(`[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 rM(o,n);if(r.push(c),s&&i.push(c),c.type===`connected`){let t=await aM(c);a.push(...t),U(`[Agent: ${e.agentType}] Connected to MCP server '${o}' with ${t.length} tools`)}else U(`[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){U(`[Agent: ${e.agentType}] Error cleaning up MCP server '${t.name}': ${n}`,{level:`warn`})}};return{clients:[...t,...r],tools:a,cleanup:o}}function D4e(e){return e.type===`assistant`||e.type===`user`||e.type===`progress`||e.type===`system`&&`subtype`in e&&e.subtype===`compact_boundary`}async function*pK({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=a2e(e.model,n.options.mainLoopModel,l,S),T=c?.agentId?c.agentId:GG();if(y&&a6(T,y),Sce()){let t=n.agentId??ln();wce(T,e.agentType,t)}let E=[...o?zG(o):[],...t],D=o===void 0?wP(100):DP(n.readFileState),[O,k]=await Promise.all([c?.userContext??YR(),c?.systemContext??JR()]),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:n4e(e,f,i).resolvedTools,ce=Array.from(x.toolPermissionContext.additionalWorkingDirectories.keys()),M=c?.systemPrompt?c.systemPrompt:rc(await O4e(e,n,w,ce,se)),N=c?.abortController?c.abortController:i?new AbortController:n.abortController,le=[];for await(let t of gEt(T,e.agentType,N.signal))t.additionalContexts&&t.additionalContexts.length>0&&le.push(...t.additionalContexts);if(le.length>0){let e=j0({type:`hook_additional_context`,content:le,hookName:`SubagentStart`,toolUseID:tu(),hookEvent:`SubagentStart`});E.push(e)}let ue=!q_(`hooks`)||J_(e.source);e.hooks&&ue&&w4e(C,T,e.hooks,`agent '${e.agentType}'`,!0);let de=e.skills??[];if(de.length>0){let t=await X3(tn()),r=[];for(let n of de){let i=k4e(n,t,e);if(!i){U(`[Agent: ${e.agentType}] Warning: Skill '${n}' specified in frontmatter was not found`,{level:`warn`});continue}let a=qSt(i,t);if(a.type!==`prompt`){U(`[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-BHBnHBjj.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){U(`[Agent: ${e.agentType}] Preloaded skill '${t}'`);let a=i(t,n.progressMessage);E.push($({content:[{type:`text`,text:a},...r],isMeta:!0}))}}let{clients:fe,tools:pe,cleanup:me}=await E4e(e,n.options.mcpClients),he=pe.length>0?Qp([...se,...pe],`name`):se,ge=F1(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}),_6(E,T).catch(e=>U(`Failed to record sidechain transcript: ${e}`)),c6(T,{agentType:e.agentType,..._&&{worktreePath:_},...v&&{description:v}}).catch(e=>U(`Failed to write agent metadata: ${e}`));let _e=E.at(-1)?.uuid??null;try{for await(let t of A1({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`){U(`[Agent
|
|
1608
1608
|
: $
|
|
1609
1609
|
{
|
|
1610
1610
|
agentDefinition.agentType
|
|
@@ -1646,9 +1646,9 @@ Rejected plan:
|
|
|
1646
1646
|
`);{let e=s.getAppState(),t=await aK({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();c0({taskId:o,description:n,status:`completed`,setAppState:h,finalMessage:l,usage:{totalTokens:r0(t),toolUses:c.totalToolUseCount,durationMs:c.totalDurationMs},toolUseId:s.toolUseId,...u})}catch(e){if(e instanceof En){l0(o,h),J(`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=i4e(i);c0({taskId:o,description:n,status:`killed`,setAppState:h,toolUseId:s.toolUseId,finalMessage:t,...e});return}let t=H(e);Aht(o,t,h);let r=await re();c0({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=>Ys(e,`Read`)||Ys(e,`Bash`));return{data:{isAsync:!0,status:`async_launched`,agentId:o,description:n,prompt:e,outputFile:B8(o),canReadOutputFile:c}}}}if(S.type!==`message`)continue;let{result:C}=S;if(C.done)break;let w=C.value;if(i.push(w),i0(o,w,c,s.options.tools),f){let e=rK(w);e&&(iK(o,f,s.toolUseId,n,a,e),hn()&&u0(f,a0(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=yLe(w);e>0&&s.setResponseLength(t=>t+e)}let E=P4([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 En)throw C=!0,J(`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;U(`Sync agent error: ${H(e)}`,{level:`error`}),S=Fn(e)}finally{if(s.setToolJSX&&s.setToolJSX(null),y?.(),f&&(Pht(f,h),!_)){let e=a0(o);vc({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&&sbt(D))throw J(`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 En;if(S){if(!i.some(e=>e.type===`assistant`))throw S;U(`Sync agent recovering from error with ${i.length} messages`)}let O=nK(i,t,T);{let e=s.getAppState(),t=await aK({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:B5e,userFacingNameBackgroundColor:V5e,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 ${xs} or ${Is} 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&&tre.has(e.agentType)&&!r?Ds(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}
|
|
1647
1647
|
<usage>total_tokens: ${e.totalTokens}
|
|
1648
1648
|
tool_uses: ${e.totalToolUseCount}
|
|
1649
|
-
duration_ms: ${e.totalDurationMs}</usage>`}]}}throw Error(`Unexpected agent tool result status: ${e.status}`)},renderToolResultMessage:N5e,renderToolUseMessage:P5e,renderToolUseTag:F5e,renderToolUseProgressMessage:aJ,renderToolUseRejectedMessage:I5e,renderToolUseErrorMessage:L5e,renderGroupedToolUse:z5e})}));function $5e(e,t){let n=t?`${e}@${t.toLowerCase()}`:e;return $l(`sha256`).update(n+o7e).digest(`hex`).slice(0,16)}function e7e(e,t,n){return t===a7e?`default-bundle`:Gh(t)?`official`:n?.has(e)?`org`:`user-local`}function t7e(e,t,n){return e.isBuiltin?`default-enable`:t?.has(e.name)?`org-policy`:n.some(t=>e.path.startsWith(t.endsWith(Nl)?t:t+Nl))?`seed-mount`:`user-install`}function pJ(e,t,n=null){let r=e7e(e,t,n),i=r===`official`||r===`default-bundle`;return{plugin_id_hash:$5e(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 mJ(e,t=null){let{marketplace:n}=Wh(e.repository);return pJ(e.pluginManifest.name,n,t)}function n7e(e,t,n){for(let r of e){let{marketplace:e}=Wh(r.repository);J(`tengu_plugin_enabled_for_session`,{_PROTO_plugin_name:r.name,...e&&{_PROTO_marketplace_name:e},...pJ(r.name,e,t),enabled_via:t7e(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 r7e(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 i7e(e,t){for(let n of e){let{name:e,marketplace:r}=Wh(n.source),i=`plugin`in n&&n.plugin?n.plugin:e;J(`tengu_plugin_load_failed`,{error_category:n.type,_PROTO_plugin_name:i,...r&&{_PROTO_marketplace_name:r},...pJ(i,r,t)})}}var a7e,o7e,hJ=n((()=>{Na(),Kh(),a7e=`builtin`,o7e=`claude-plugin-telemetry-v1`}));function s7e(e){let t=Date.now(),n=gJ.get(e);n!==void 0&&t-n<l7e||(gJ.set(e,t),Ni(n=>{let r=n.skillUsage?.[e];return{...n,skillUsage:{...n.skillUsage,[e]:{usageCount:(r?.usageCount??0)+1,lastUsedAt:t}}}}))}function c7e(e){let t=Di().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 l7e,gJ,u7e=n((()=>{Oi(),l7e=6e4,gJ=new Map}));function d7e(e,t){return t?e.map(e=>e.type===`user`?{...e,sourceToolUseID:t}:e):e}function f7e(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 p7e=n((()=>{}));function m7e(e){if(`status`in e&&e.status===`forked`)return(0,vJ.jsx)(Z,{height:1,children:(0,vJ.jsx)(F,{children:(0,vJ.jsx)(je,{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} ${qa(n,`tool`)} allowed`)}return`model`in e&&e.model&&t.push(e.model),(0,vJ.jsx)(Z,{height:1,children:(0,vJ.jsx)(F,{children:(0,vJ.jsx)(je,{children:t})})})}function h7e({skill:e},{commands:t}){return e?t?.find(t=>t.name===e)?.loadedFrom===`commands_DEPRECATED`?`/${e}`:e:null}function _J(e,{tools:t,verbose:n}){if(!e.length)return(0,vJ.jsx)(Z,{height:1,children:(0,vJ.jsx)(F,{dimColor:!0,children:v7e})});let r=n?e:e.slice(-3),i=e.length-r.length,{inProgressToolUseIDs:a}=I4(e.map(e=>e.data));return(0,vJ.jsx)(Z,{children:(0,vJ.jsxs)(P,{flexDirection:`column`,children:[(0,vJ.jsx)(qy,{children:r.map(e=>(0,vJ.jsx)(P,{height:1,overflow:`hidden`,children:(0,vJ.jsx)(tJ,{message:e.data.message,lookups:u3,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,vJ.jsxs)(F,{dimColor:!0,children:[`+`,i,` more tool `,qa(i,`use`)]})]})})}function g7e(e,{progressMessagesForMessage:t,tools:n,verbose:r}){return(0,vJ.jsxs)(vJ.Fragment,{children:[_J(t,{tools:n,verbose:r}),(0,vJ.jsx)(xK,{})]})}function _7e(e,{progressMessagesForMessage:t,tools:n,verbose:r}){return(0,vJ.jsxs)(vJ.Fragment,{children:[_J(t,{tools:n,verbose:r}),(0,vJ.jsx)(db,{result:e,verbose:r})]})}var vJ,v7e,y7e=n((()=>{Qy(),mb(),CK(),I(),nJ(),ob(),p3(),Ja(),vJ=tt(),v7e=`Initializing…`})),b7e=i({getDiscoveredRemoteSkill:()=>S7e,stripCanonicalPrefix:()=>x7e});function x7e(e){return null}function S7e(e){}var C7e=n((()=>{})),w7e=i({loadRemoteSkill:()=>T7e});function T7e(e,t){return Promise.resolve({cacheHit:!1,latencyMs:0,skillPath:``,content:``})}var E7e=n((()=>{})),D7e=i({logRemoteSkillLoaded:()=>O7e});function O7e(e){}var k7e=n((()=>{}));async function yJ(e){let t=e.getAppState().mcp.commands.filter(e=>e.type===`prompt`&&e.loadedFrom===`mcp`);return t.length===0?W3(tn()):Qp([...await W3(tn()),...t],`name`)}async function A7e(e,t,n,r,i,a,o){let s=Date.now(),c=GG(),l=J3().has(t),u=M7e(e),d=e.source===`bundled`,f=l||d||u?t:`custom`,p=bJ.isSkillSearchEnabled()?{was_discovered:r.discoveredSkillNames?.has(t)??!1}:{},m=e.pluginInfo?Wh(e.pluginInfo.repository).marketplace:void 0,h=r.queryTracking?.depth??0,g=qc()?.agentId;J(`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`,...mJ(e.pluginInfo)}});let{modifiedGetAppState:_,baseAgent:v,promptMessages:y,skillContent:b}=await Imt(e,n||``,r),x=[];U(`SkillTool executing forked skill ${t} with agent ${v.agentType}`);try{for await(let t of pK({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=P4([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=Lmt(x,`Skill execution completed`);return x.length=0,U(`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 j7e(e){for(let t of Object.keys(e)){if(F7e.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 M7e(e){return e.source!==`plugin`||!e.pluginInfo?.repository?!1:Gh(Wh(e.pluginInfo.repository).marketplace)}var bJ,N7e,P7e,xJ,F7e,I7e=n((()=>{$p(),Gt(),$3(),Zs(),W(),A9(),Kh(),hJ(),_t(),sa(),Na(),Hc(),R1(),vt(),p3(),Lo(),u7e(),KG(),mK(),p7e(),$s(),Pg(),y7e(),C7e(),E7e(),k7e(),gp(),bJ={...b7e,...w7e,...D7e,...mge},N7e=gt(()=>B({skill:L().describe(`The skill name. E.g., "commit", "review-pr", or "pdf"`),args:L().optional().describe(`Optional arguments for the skill`)})),P7e=gt(()=>ut([B({success:pt().describe(`Whether the skill is valid`),commandName:L().describe(`The name of the skill`),allowedTools:z(L()).optional().describe(`Tools allowed by this skill`),model:L().optional().describe(`Model override if specified`),status:st(`inline`).optional().describe(`Execution status`)}),B({success:pt().describe(`Whether the skill completed successfully`),commandName:L().describe(`The name of the skill`),status:st(`forked`).describe(`Execution status`),agentId:L().describe(`The ID of the sub-agent that executed the skill`),result:L().describe(`The result from the forked skill execution`)})])),xJ=Ns({name:hs,searchHint:`invoke a slash-command skill`,maxResultSizeChars:1e5,get inputSchema(){return N7e()},get outputSchema(){return P7e()},description:async({skill:e})=>`Execute skill: ${e}`,prompt:async()=>Ng(tn()),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&&J(`tengu_skill_tool_slash_prefix`,{});let i=r?n.substring(1):n,a=G3(i,await yJ(t));return a?a.disableModelInvocation?{result:!1,message:`Skill ${i} cannot be used with ${hs} 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 yJ(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,xJ,`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,xJ,`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`&&j7e(o))return{behavior:`allow`,updatedInput:{skill:e,args:t},decisionReason:void 0};let u=[{type:`addRules`,rules:[{toolName:hs,ruleContent:i}],behavior:`allow`,destination:`localSettings`},{type:`addRules`,rules:[{toolName:hs,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 yJ(n),l=G3(s,c);if(s7e(s),l?.type===`prompt`&&l.context===`fork`)return A7e(l,s,t,n,r,i,a);let{processPromptSlashCommand:u}=await import(`./processSlashCommand-U9LJ4Keq.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`&&M7e(l),_=m||h||g?s:`custom`,v=bJ.isSkillSearchEnabled()?{was_discovered:n.discoveredSkillNames?.has(s)??!1}:{},y=l?.type===`prompt`&&l.pluginInfo?Wh(l.pluginInfo.repository).marketplace:void 0,b=n.queryTracking?.depth??0,x=qc()?.agentId;J(`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`,...mJ(l.pluginInfo)}});let S=f7e(i,hs),C=d7e(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 U(`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:lae(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:m7e,renderToolUseMessage:h7e,renderToolUseProgressMessage:_J,renderToolUseRejectedMessage:g7e,renderToolUseErrorMessage:_7e}),F7e=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 L7e(e,t,n){let{head:r,tail:i,mtime:a,size:o}=t,s=r.indexOf(`
|
|
1649
|
+
duration_ms: ${e.totalDurationMs}</usage>`}]}}throw Error(`Unexpected agent tool result status: ${e.status}`)},renderToolResultMessage:N5e,renderToolUseMessage:P5e,renderToolUseTag:F5e,renderToolUseProgressMessage:aJ,renderToolUseRejectedMessage:I5e,renderToolUseErrorMessage:L5e,renderGroupedToolUse:z5e})}));function $5e(e,t){let n=t?`${e}@${t.toLowerCase()}`:e;return $l(`sha256`).update(n+o7e).digest(`hex`).slice(0,16)}function e7e(e,t,n){return t===a7e?`default-bundle`:Gh(t)?`official`:n?.has(e)?`org`:`user-local`}function t7e(e,t,n){return e.isBuiltin?`default-enable`:t?.has(e.name)?`org-policy`:n.some(t=>e.path.startsWith(t.endsWith(Nl)?t:t+Nl))?`seed-mount`:`user-install`}function pJ(e,t,n=null){let r=e7e(e,t,n),i=r===`official`||r===`default-bundle`;return{plugin_id_hash:$5e(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 mJ(e,t=null){let{marketplace:n}=Wh(e.repository);return pJ(e.pluginManifest.name,n,t)}function n7e(e,t,n){for(let r of e){let{marketplace:e}=Wh(r.repository);J(`tengu_plugin_enabled_for_session`,{_PROTO_plugin_name:r.name,...e&&{_PROTO_marketplace_name:e},...pJ(r.name,e,t),enabled_via:t7e(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 r7e(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 i7e(e,t){for(let n of e){let{name:e,marketplace:r}=Wh(n.source),i=`plugin`in n&&n.plugin?n.plugin:e;J(`tengu_plugin_load_failed`,{error_category:n.type,_PROTO_plugin_name:i,...r&&{_PROTO_marketplace_name:r},...pJ(i,r,t)})}}var a7e,o7e,hJ=n((()=>{Na(),Kh(),a7e=`builtin`,o7e=`claude-plugin-telemetry-v1`}));function s7e(e){let t=Date.now(),n=gJ.get(e);n!==void 0&&t-n<l7e||(gJ.set(e,t),Ni(n=>{let r=n.skillUsage?.[e];return{...n,skillUsage:{...n.skillUsage,[e]:{usageCount:(r?.usageCount??0)+1,lastUsedAt:t}}}}))}function c7e(e){let t=Di().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 l7e,gJ,u7e=n((()=>{Oi(),l7e=6e4,gJ=new Map}));function d7e(e,t){return t?e.map(e=>e.type===`user`?{...e,sourceToolUseID:t}:e):e}function f7e(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 p7e=n((()=>{}));function m7e(e){if(`status`in e&&e.status===`forked`)return(0,vJ.jsx)(Z,{height:1,children:(0,vJ.jsx)(F,{children:(0,vJ.jsx)(je,{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} ${qa(n,`tool`)} allowed`)}return`model`in e&&e.model&&t.push(e.model),(0,vJ.jsx)(Z,{height:1,children:(0,vJ.jsx)(F,{children:(0,vJ.jsx)(je,{children:t})})})}function h7e({skill:e},{commands:t}){return e?t?.find(t=>t.name===e)?.loadedFrom===`commands_DEPRECATED`?`/${e}`:e:null}function _J(e,{tools:t,verbose:n}){if(!e.length)return(0,vJ.jsx)(Z,{height:1,children:(0,vJ.jsx)(F,{dimColor:!0,children:v7e})});let r=n?e:e.slice(-3),i=e.length-r.length,{inProgressToolUseIDs:a}=I4(e.map(e=>e.data));return(0,vJ.jsx)(Z,{children:(0,vJ.jsxs)(P,{flexDirection:`column`,children:[(0,vJ.jsx)(qy,{children:r.map(e=>(0,vJ.jsx)(P,{height:1,overflow:`hidden`,children:(0,vJ.jsx)(tJ,{message:e.data.message,lookups:u3,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,vJ.jsxs)(F,{dimColor:!0,children:[`+`,i,` more tool `,qa(i,`use`)]})]})})}function g7e(e,{progressMessagesForMessage:t,tools:n,verbose:r}){return(0,vJ.jsxs)(vJ.Fragment,{children:[_J(t,{tools:n,verbose:r}),(0,vJ.jsx)(xK,{})]})}function _7e(e,{progressMessagesForMessage:t,tools:n,verbose:r}){return(0,vJ.jsxs)(vJ.Fragment,{children:[_J(t,{tools:n,verbose:r}),(0,vJ.jsx)(db,{result:e,verbose:r})]})}var vJ,v7e,y7e=n((()=>{Qy(),mb(),CK(),I(),nJ(),ob(),p3(),Ja(),vJ=tt(),v7e=`Initializing…`})),b7e=i({getDiscoveredRemoteSkill:()=>S7e,stripCanonicalPrefix:()=>x7e});function x7e(e){return null}function S7e(e){}var C7e=n((()=>{})),w7e=i({loadRemoteSkill:()=>T7e});function T7e(e,t){return Promise.resolve({cacheHit:!1,latencyMs:0,skillPath:``,content:``})}var E7e=n((()=>{})),D7e=i({logRemoteSkillLoaded:()=>O7e});function O7e(e){}var k7e=n((()=>{}));async function yJ(e){let t=e.getAppState().mcp.commands.filter(e=>e.type===`prompt`&&e.loadedFrom===`mcp`);return t.length===0?W3(tn()):Qp([...await W3(tn()),...t],`name`)}async function A7e(e,t,n,r,i,a,o){let s=Date.now(),c=GG(),l=J3().has(t),u=M7e(e),d=e.source===`bundled`,f=l||d||u?t:`custom`,p=bJ.isSkillSearchEnabled()?{was_discovered:r.discoveredSkillNames?.has(t)??!1}:{},m=e.pluginInfo?Wh(e.pluginInfo.repository).marketplace:void 0,h=r.queryTracking?.depth??0,g=qc()?.agentId;J(`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`,...mJ(e.pluginInfo)}});let{modifiedGetAppState:_,baseAgent:v,promptMessages:y,skillContent:b}=await Imt(e,n||``,r),x=[];U(`SkillTool executing forked skill ${t} with agent ${v.agentType}`);try{for await(let t of pK({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=P4([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=Lmt(x,`Skill execution completed`);return x.length=0,U(`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 j7e(e){for(let t of Object.keys(e)){if(F7e.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 M7e(e){return e.source!==`plugin`||!e.pluginInfo?.repository?!1:Gh(Wh(e.pluginInfo.repository).marketplace)}var bJ,N7e,P7e,xJ,F7e,I7e=n((()=>{$p(),Gt(),$3(),Zs(),W(),A9(),Kh(),hJ(),_t(),sa(),Na(),Hc(),R1(),vt(),p3(),Lo(),u7e(),KG(),mK(),p7e(),$s(),Pg(),y7e(),C7e(),E7e(),k7e(),gp(),bJ={...b7e,...w7e,...D7e,...mge},N7e=gt(()=>B({skill:L().describe(`The skill name. E.g., "commit", "review-pr", or "pdf"`),args:L().optional().describe(`Optional arguments for the skill`)})),P7e=gt(()=>ut([B({success:pt().describe(`Whether the skill is valid`),commandName:L().describe(`The name of the skill`),allowedTools:z(L()).optional().describe(`Tools allowed by this skill`),model:L().optional().describe(`Model override if specified`),status:st(`inline`).optional().describe(`Execution status`)}),B({success:pt().describe(`Whether the skill completed successfully`),commandName:L().describe(`The name of the skill`),status:st(`forked`).describe(`Execution status`),agentId:L().describe(`The ID of the sub-agent that executed the skill`),result:L().describe(`The result from the forked skill execution`)})])),xJ=Ns({name:hs,searchHint:`invoke a slash-command skill`,maxResultSizeChars:1e5,get inputSchema(){return N7e()},get outputSchema(){return P7e()},description:async({skill:e})=>`Execute skill: ${e}`,prompt:async()=>Ng(tn()),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&&J(`tengu_skill_tool_slash_prefix`,{});let i=r?n.substring(1):n,a=G3(i,await yJ(t));return a?a.disableModelInvocation?{result:!1,message:`Skill ${i} cannot be used with ${hs} 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 yJ(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,xJ,`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,xJ,`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`&&j7e(o))return{behavior:`allow`,updatedInput:{skill:e,args:t},decisionReason:void 0};let u=[{type:`addRules`,rules:[{toolName:hs,ruleContent:i}],behavior:`allow`,destination:`localSettings`},{type:`addRules`,rules:[{toolName:hs,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 yJ(n),l=G3(s,c);if(s7e(s),l?.type===`prompt`&&l.context===`fork`)return A7e(l,s,t,n,r,i,a);let{processPromptSlashCommand:u}=await import(`./processSlashCommand-BHBnHBjj.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`&&M7e(l),_=m||h||g?s:`custom`,v=bJ.isSkillSearchEnabled()?{was_discovered:n.discoveredSkillNames?.has(s)??!1}:{},y=l?.type===`prompt`&&l.pluginInfo?Wh(l.pluginInfo.repository).marketplace:void 0,b=n.queryTracking?.depth??0,x=qc()?.agentId;J(`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`,...mJ(l.pluginInfo)}});let S=f7e(i,hs),C=d7e(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 U(`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:lae(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:m7e,renderToolUseMessage:h7e,renderToolUseProgressMessage:_J,renderToolUseRejectedMessage:g7e,renderToolUseErrorMessage:_7e}),F7e=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 L7e(e,t,n){let{head:r,tail:i,mtime:a,size:o}=t,s=r.indexOf(`
|
|
1650
1650
|
`),c=s>=0?r.slice(0,s):r;if(c.includes(`"isSidechain":true`)||c.includes(`"isSidechain": true`))return null;let l=Ea(i,`customTitle`)||Ea(r,`customTitle`)||Ea(i,`aiTitle`)||Ea(r,`aiTitle`)||void 0,u=Bie(r)||void 0,d=Sa(r,`timestamp`),f;if(d){let e=Date.parse(d);Number.isNaN(e)||(f=e)}let p=l||Ea(i,`lastPrompt`)||Ea(i,`summary`)||u;if(!p)return null;let m=Ea(i,`gitBranch`)||Sa(r,`gitBranch`)||void 0,h=Sa(r,`cwd`)||n||void 0,g=i.split(`
|
|
1651
|
-
`).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&&Ea(g,`tag`)||void 0,createdAt:f}}async function SJ(e,t,n){let r;try{r=await uu(e)}catch{return[]}return(await Promise.all(r.map(async r=>{if(!r.endsWith(`.jsonl`))return null;let i=zie(r.slice(0,-6));if(!i)return null;let a=Y(e,r);if(!t)return{sessionId:i,filePath:a,mtime:0,projectPath:n};try{return{sessionId:i,filePath:a,mtime:(await mu(a)).mtime.getTime(),projectPath:n}}catch{return null}}))).filter(e=>e!==null)}async function R7e(e){let t=await Iie(e.filePath);if(!t)return null;let n=L7e(e.sessionId,t,e.projectPath);return n?(e.mtime&&(n.lastModified=e.mtime),n):null}function z7e(e,t){return t.mtime===e.mtime?t.sessionId<e.sessionId?-1:+(t.sessionId>e.sessionId):t.mtime-e.mtime}async function B7e(e,t,n){e.sort(z7e);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+G7e,e.length),c=e.slice(t,s),l=await Promise.all(c.map(R7e));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 V7e(e){let t=await Promise.all(e.map(R7e)),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 H7e(e,t,n){let r=await Vie(e),i;if(t)try{i=await Rie(r)}catch{i=[]}else i=[];if(i.length<=1){let e=await Da(r);return e?SJ(e,n,r):[]}let a=Ca(),o=process.platform===`win32`,s=i.map(e=>{let t=Ta(e);return{path:e,prefix:o?t.toLowerCase():t}});s.sort((e,t)=>t.prefix.length-e.prefix.length);let c;try{c=await uu(a,{withFileTypes:!0})}catch{let e=await Da(r);return e?SJ(e,n,r):[]}let l=[],u=new Set,d=await Da(r);if(d){let e=wl(d);u.add(o?e.toLowerCase():e),l.push(...await SJ(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 SJ(Y(a,e.name),n,r));break}}}return l}async function U7e(e){let t=Ca(),n;try{n=await uu(t,{withFileTypes:!0})}catch{return[]}return(await Promise.all(n.filter(e=>e.isDirectory()).map(n=>SJ(Y(t,n.name),e)))).flat()}async function W7e(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 H7e(t,i??!0,o):await U7e(o);return o?B7e(s,n,a):V7e(s)}var G7e,K7e=n((()=>{Fie(),wa(),G7e=32}));function CJ(){return Y(ki(),Q7e)}async function q7e(){try{return(await mu(CJ())).mtimeMs}catch{return 0}}async function J7e(){let e=CJ(),t,n;try{let[r,i]=await Promise.all([mu(e),lu(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<$7e&&n!==void 0&&Rc(n))return U(`[autoDream] lock held by live PID ${n} (mtime ${Math.round((Date.now()-t)/1e3)}s ago)`),null;await su(ki(),{recursive:!0}),await _u(e,String(process.pid));let r;try{r=await lu(e,`utf8`)}catch{return null}return parseInt(r.trim(),10)===process.pid?t??0:null}async function Y7e(e){let t=CJ();try{if(e===0){await gu(t);return}await _u(t,``);let n=e/1e3;await Nle(t,n,n)}catch(e){U(`[autoDream] rollback failed: ${e.message} — next trigger delayed to minHours`)}}async function X7e(e){return(await SJ(o8(Zt()),!0)).filter(t=>t.mtime>e).map(e=>e.sessionId)}async function Z7e(){try{await su(ki(),{recursive:!0}),await _u(CJ(),String(process.pid))}catch(e){U(`[autoDream] recordConsolidation write failed: ${e.message}`)}}var Q7e,$7e,wJ=n((()=>{Gt(),Ci(),W(),zc(),K7e(),m8(),Q7e=`.consolidate-lock`,$7e=3600*1e3}));function e9e(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`dream`}function t9e(e,t){let n=o5(`dream`);return DL({...s5(n,`dream`,`dreaming`),type:`dream`,status:`running`,phase:`starting`,sessionsReviewing:t.sessionsReviewing,filesTouched:[],turns:[],abortController:t.abortController,priorMtime:t.priorMtime},e),n}function n9e(e,t,n,r){EL(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 r9e(e,t){EL(e,t,e=>({...e,status:`completed`,endTime:Date.now(),notified:!0,abortController:void 0}))}function i9e(e,t){EL(e,t,e=>({...e,status:`failed`,endTime:Date.now(),notified:!0,abortController:void 0}))}var TJ,EJ=n((()=>{wJ(),c5(),kL(),TJ={name:`DreamTask`,type:`dream`,async kill(e,t){let n;EL(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 Y7e(n)}}})),DJ,a9e=n((()=>{_t(),vt(),DJ=gt(()=>B({restrictions:it(L(),B({allowed:pt()}))}))}));function o9e(e){return e instanceof Error}function s9e(){FJ||AJ()&&(FJ=new Promise(e=>{IJ=e,setTimeout(()=>{IJ&&(U(`Policy limits: Loading promise timed out, resolving anyway`),IJ(),IJ=null)},D9e)}))}function OJ(){return Y(p(),w9e)}function c9e(){return`${Wa().BASE_API_URL}/api/claude_code/policy_limits`}function kJ(e){if(Array.isArray(e))return e.map(kJ);if(typeof e==`object`&&e){let t={};for(let[n,r]of Object.entries(e).sort(([e],[t])=>e.localeCompare(t)))t[n]=kJ(r);return t}return e}function l9e(e){let t=V(kJ(e));return`sha256:${$l(`sha256`).update(t).digest(`hex`)}`}function AJ(){if(eo()!==`firstParty`||!Qo())return!1;try{let{key:e}=Go({skipRetrievingKeyFromApiKeyHelper:!0});if(e)return!0}catch{}let e=Mo();return!(!e?.accessToken||!e.scopes?.includes(`user:inference`)||e.subscriptionType!==`enterprise`&&e.subscriptionType!==`team`)}async function u9e(){FJ&&await FJ}function d9e(){try{let{key:e}=Go({skipRetrievingKeyFromApiKeyHelper:!0});if(e)return{headers:{"x-api-key":e}}}catch{}let e=Mo();return e?.accessToken?{headers:{Authorization:`Bearer ${e.accessToken}`,"anthropic-beta":nae}}:{headers:{},error:`No authentication available`}}async function f9e(e){let t=null;for(let n=1;n<=6;n++){if(t=await p9e(e),t.success||t.skipRetry||n>MJ)return t;let r=sR(n);U(`Policy limits: Retry ${n}/${MJ} after ${r}ms`),await Ho(r)}return t}async function p9e(e){try{await zo();let t=d9e();if(t.error)return{success:!1,error:`Authentication required for policy limits`,skipRetry:!0};let n=c9e(),r={...t.headers,"User-Agent":Cse()};e&&(r[`If-None-Match`]=`"${e}"`);let i=await ue.get(n,{headers:r,timeout:T9e,validateStatus:e=>e===200||e===304||e===404});if(i.status===304)return U(`Policy limits: Using cached restrictions (304)`),{success:!0,restrictions:null,etag:e};if(i.status===404)return U(`Policy limits: No restrictions found (404)`),{success:!0,restrictions:{},etag:void 0};let a=DJ().safeParse(i.data);return a.success?(U(`Policy limits: Fetched successfully`),{success:!0,restrictions:a.data.restrictions}):(U(`Policy limits: Invalid response format - ${a.error.message}`),{success:!1,error:`Invalid policy limits format`})}catch(e){let{kind:t,message:n}=vne(e);switch(t){case`auth`:return{success:!1,error:`Not authorized for policy limits`,skipRetry:!0};case`timeout`:return{success:!1,error:`Policy limits request timeout`};case`network`:return{success:!1,error:`Cannot connect to server`};default:return{success:!1,error:n}}}}function m9e(){try{let e=Ma(Kl(OJ(),`utf-8`),!1),t=DJ().safeParse(e);return t.success?t.data.restrictions:null}catch{return null}}async function h9e(e){try{let t=OJ();await _u(t,V({restrictions:e},null,2),{encoding:`utf-8`,mode:384}),U(`Policy limits: Saved to ${t}`)}catch(e){U(`Policy limits: Failed to save - ${e instanceof Error?e.message:`unknown error`}`)}}async function jJ(){if(!AJ())return null;let e=m9e(),t=e?l9e(e):void 0;try{let n=await f9e(t);if(!n.success)return e?(U(`Policy limits: Using stale cache after fetch failure`),LJ=e,e):null;if(n.restrictions===null&&e)return U(`Policy limits: Cache still valid (304 Not Modified)`),LJ=e,e;let r=n.restrictions||{};if(Object.keys(r).length>0)return LJ=r,await h9e(r),U(`Policy limits: Applied new restrictions successfully`),r;LJ=r;try{await gu(OJ()),U(`Policy limits: Deleted cached file (404 response)`)}catch(e){o9e(e)&&e.code!==`ENOENT`&&U(`Policy limits: Failed to delete cached file - ${e.message}`)}return r}catch{return e?(U(`Policy limits: Using stale cache after error`),LJ=e,e):null}}function g9e(e){let t=_9e();if(!t)return!(Oie()&&O9e.has(e));let n=t[e];return!n||n.allowed}function _9e(){if(!AJ())return null;if(LJ)return LJ;let e=m9e();return e?(LJ=e,e):null}async function v9e(){AJ()&&!FJ&&(FJ=new Promise(e=>{IJ=e}));try{await jJ(),AJ()&&S9e()}finally{IJ&&(IJ(),IJ=null)}}async function y9e(){await b9e(),AJ()&&(await jJ(),U(`Policy limits: Refreshed after auth change`))}async function b9e(){C9e(),LJ=null,FJ=null,IJ=null;try{await gu(OJ())}catch{}}async function x9e(){if(!AJ())return;let e=LJ?V(LJ):null;try{await jJ(),(LJ?V(LJ):null)!==e&&U(`Policy limits: Changed during background poll`)}catch{}}function S9e(){NJ===null&&AJ()&&(NJ=setInterval(()=>{x9e()},E9e),NJ.unref(),PJ||(PJ=!0,qn(async()=>C9e())))}function C9e(){NJ!==null&&(clearInterval(NJ),NJ=null)}var w9e,T9e,MJ,E9e,NJ,PJ,FJ,IJ,D9e,LJ,O9e,RJ=n((()=>{de(),Ga(),Do(),Xn(),W(),h(),Mn(),ja(),es(),Die(),Bo(),Zn(),Sse(),_R(),a9e(),w9e=`policy-limits.json`,T9e=1e4,MJ=5,E9e=3600*1e3,NJ=null,PJ=!1,FJ=null,IJ=null,D9e=3e4,LJ=null,O9e=new Set([`allow_product_feedback`])}));async function k9e(){let e=Mo()?.accessToken;if(!e)throw Error(`Work Mate web sessions require authentication with a Claude.ai account. API key authentication is not sufficient.`);let t=await lo();if(!t)throw Error(`Unable to get organization UUID`);let n=`${Wa().BASE_API_URL}/v1/environment_providers`;try{let r={...ml(e),"x-organization-uuid":t},i=await ue.get(n,{headers:r,timeout:15e3});if(i.status!==200)throw Error(`Failed to fetch environments: ${i.status} ${i.statusText}`);return i.data.environments}catch(e){let t=Fn(e);throw q(t),Error(`Failed to fetch environments: ${t.message}`)}}var A9e=n((()=>{de(),Ga(),To(),Do(),Mn(),oa(),gl()}));async function j9e(){return as()?zo():!1}async function M9e(){return await uie({ignoreUntracked:!0})}async function N9e(e,t,n){try{let r=Mo()?.accessToken;if(!r)return U(`checkGithubAppInstalled: No access token found, assuming app not installed`),!1;let i=await lo();if(!i)return U(`checkGithubAppInstalled: No org UUID found, assuming app not installed`),!1;let a=`${Wa().BASE_API_URL}/api/oauth/organizations/${i}/code/repos/${e}/${t}`,o={...ml(r),"x-organization-uuid":i};U(`Checking GitHub app installation for ${e}/${t}`);let s=await ue.get(a,{headers:o,timeout:15e3,signal:n});if(s.status===200){if(s.data.status){let n=s.data.status.app_installed;return U(`GitHub app ${n?`is`:`is not`} installed on ${e}/${t}`),n}return U(`GitHub app is not installed on ${e}/${t} (status is null)`),!1}return U(`checkGithubAppInstalled: Unexpected response status ${s.status}`),!1}catch(n){if(ue.isAxiosError(n)){let r=n.response?.status;if(r&&r>=400&&r<500)return U(`checkGithubAppInstalled: Got ${r} error, app likely not installed on ${e}/${t}`),!1}return U(`checkGithubAppInstalled error: ${H(n)}`),!1}}var zJ=n((()=>{de(),Ga(),To(),Do(),Sn(),W(),fl(),Mn(),Bi(),gl(),A9e()})),P9e=n((()=>{RJ(),fl(),h(),zJ()}));function BJ(){if(process.stdout.isTTY)try{ql(1,qe);let e=Ae.get(process.stdout);if(e?.isAltScreenActive)try{e.unmount()}catch{ql(1,vee)}e?.drainStdin(),e?.detachForShutdown(),ql(1,fe),ql(1,ke),ql(1,nee),ql(1,see),ql(1,gee),ql(1,lee),Ke()&&ql(1,dee(pee)),m(process.env.CLAUDE_CODE_DISABLE_TERMINAL_TITLE)||(process.platform===`win32`?process.title=``:ql(1,Ve))}catch{}}function VJ(){if(!GJ&&process.stdout.isTTY&&Bt()&&!Ot())try{let e=ln();if(!f6(e))return;let t=F6(e),n;n=t?`"${t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`:e,ql(1,Ue.dim(`\nResume this session with:\nclaude --resume ${n}\n`)),GJ=!0}catch{}}function HJ(e){qJ!==void 0&&(clearTimeout(qJ),qJ=void 0);try{Ae.get(process.stdout)?.drainStdin()}catch{}try{process.exit(e)}catch{process.kill(process.pid,`SIGKILL`)}throw Error(`unreachable`)}function UJ(e=0,t=`other`,n){process.exitCode=e,L9e=WJ(e,t,n).catch(t=>{U(`Graceful shutdown failed: ${t}`,{level:`error`}),BJ(),VJ(),HJ(e)}).catch(()=>{})}function F9e(){return KJ}async function WJ(e=0,t=`other`,n){if(KJ)return;KJ=!0;let{executeSessionEndHooks:r,getSessionEndHookTimeoutMs:i}=await import(`./hooks-COhKt_pF.js`),a=i();qJ=setTimeout(e=>{BJ(),VJ(),HJ(e)},Math.max(5e3,a+3500),e),qJ.unref(),process.exitCode=e,BJ(),VJ();let o;try{let e=(async()=>{try{await wne()}catch{}})();await Promise.race([e,new Promise((e,t)=>{o=setTimeout(e=>e(new R9e),2e3,t)})]),clearTimeout(o)}catch{clearTimeout(o)}try{await r(t,{...n,signal:AbortSignal.timeout(a),timeoutMs:a})}catch{}try{Zie()}catch{}let s=Vee();s&&J(`tengu_cache_eviction_hint`,{scope:`session_end`,last_request_id:s});try{await Promise.race([Promise.all([jce(),Mce()]),Ho(500)])}catch{}if(n?.finalMessage)try{ql(2,`${n.finalMessage}\n`)}catch{}HJ(e)}var GJ,I9e,KJ,qJ,JJ,L9e,R9e,YJ=n((()=>{Ge(),d(),re(),Gt(),I(),Nce(),kce(),Na(),Xn(),W(),Pi(),h(),m8(),Bo(),Qie(),GJ=!1,I9e=u(()=>{te(()=>{}),process.on(`SIGINT`,()=>{process.argv.includes(`-p`)||process.argv.includes(`--print`)||(Ri(`info`,`shutdown_signal`,{signal:`SIGINT`}),WJ(0))}),process.on(`SIGTERM`,()=>{Ri(`info`,`shutdown_signal`,{signal:`SIGTERM`}),WJ(143)}),process.platform!==`win32`&&(process.on(`SIGHUP`,()=>{Ri(`info`,`shutdown_signal`,{signal:`SIGHUP`}),WJ(129)}),process.stdin.isTTY&&(JJ=setInterval(()=>{fte()||(!process.stdout.writable||!process.stdin.readable)&&(clearInterval(JJ),Ri(`info`,`shutdown_signal`,{signal:`orphan_detected`}),WJ(129))},3e4),JJ.unref())),process.on(`uncaughtException`,e=>{Ri(`error`,`uncaught_exception`,{error_name:e.name,error_message:e.message.slice(0,2e3)}),J(`tengu_uncaught_exception`,{error_name:e.name})}),process.on(`unhandledRejection`,e=>{let t=e instanceof Error?e.name:typeof e==`string`?`string`:`unknown`;Ri(`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)}),J(`tengu_unhandled_rejection`,{error_name:t})})}),KJ=!1,R9e=class extends Error{constructor(){super(`Cleanup timeout`)}}}));function XJ(){let e=cV(),t=sV(),n=(0,ZJ.useCallback)(()=>{t(e=>{let r=z9e(e.notifications.queue);return e.notifications.current!==null||!r?e:($J=setTimeout((e,t,n)=>{$J=null,e(e=>e.notifications.current?.key===t?{...e,notifications:{queue:e.notifications.queue,current:null}}:e),n()},r.timeoutMs??QJ,t,r.key,n),{...e,notifications:{queue:e.notifications.queue.filter(e=>e!==r),current:r}})})},[t]),r=(0,ZJ.useCallback)(e=>{if(e.priority===`immediate`){$J&&(clearTimeout($J),$J=null),$J=setTimeout((e,t,n)=>{$J=null,e(e=>e.notifications.current?.key===t.key?{...e,notifications:{queue:e.notifications.queue.filter(e=>!t.invalidates?.includes(e.key)),current:null}}:e),n()},e.timeoutMs??QJ,t,e,n),t(t=>({...t,notifications:{current:e,queue:[...t.notifications.current?[t.notifications.current]:[],...t.notifications.queue].filter(t=>t.priority!==`immediate`&&!e.invalidates?.includes(t.key))}}));return}t(r=>{if(e.fold){if(r.notifications.current?.key===e.key){let i=e.fold(r.notifications.current,e);return $J&&(clearTimeout($J),$J=null),$J=setTimeout((e,t,n)=>{$J=null,e(e=>e.notifications.current?.key===t?{...e,notifications:{queue:e.notifications.queue,current:null}}:e),n()},i.timeoutMs??QJ,t,i.key,n),{...r,notifications:{current:i,queue:r.notifications.queue}}}let i=r.notifications.queue.findIndex(t=>t.key===e.key);if(i!==-1){let t=e.fold(r.notifications.queue[i],e),n=[...r.notifications.queue];return n[i]=t,{...r,notifications:{current:r.notifications.current,queue:n}}}}if(!(!new Set(r.notifications.queue.map(e=>e.key)).has(e.key)&&r.notifications.current?.key!==e.key))return r;let i=r.notifications.current!==null&&e.invalidates?.includes(r.notifications.current.key);return i&&$J&&(clearTimeout($J),$J=null),{...r,notifications:{current:i?null:r.notifications.current,queue:[...r.notifications.queue.filter(t=>t.priority!==`immediate`&&!e.invalidates?.includes(t.key)),e]}}}),n()},[t,n]),i=(0,ZJ.useCallback)(e=>{t(t=>{let n=t.notifications.current?.key===e,r=t.notifications.queue.some(t=>t.key===e);return!n&&!r?t:(n&&$J&&(clearTimeout($J),$J=null),{...t,notifications:{current:n?null:t.notifications.current,queue:t.notifications.queue.filter(t=>t.key!==e)}})}),n()},[t,n]);return(0,ZJ.useEffect)(()=>{e.getState().notifications.queue.length>0&&n()},[]),{addNotification:r,removeNotification:i}}function z9e(e){if(e.length!==0)return e.reduce((e,t)=>eY[t.priority]<eY[e.priority]?t:e)}var ZJ,QJ,$J,eY,tY=n((()=>{ZJ=r(ze(),1),pV(),QJ=8e3,$J=null,eY={immediate:0,high:1,medium:2,low:3}}));function B9e(){let e=process.platform,t=process.env.CLAUDE_CODE_TMPDIR||(e===`win32`?process.env.TEMP||`C:\\Temp`:Sl()),n=`claude_cli_latest_screenshot.png`,r={darwin:Y(t,n),linux:Y(t,n),win32:Y(t,n)},i=r[e]||r.linux,a={darwin:{checkImage:`osascript -e 'the clipboard as «class PNGf»'`,saveImage:`osascript -e 'set png_data to (the clipboard as «class PNGf»)' -e 'set fp to open for access POSIX file "${i}" with write permission' -e 'write png_data to fp' -e 'close access fp'`,getPath:`osascript -e 'get POSIX path of (the clipboard as «class furl»)'`,deleteFile:`rm -f "${i}"`},linux:{checkImage:`xclip -selection clipboard -t TARGETS -o 2>/dev/null | grep -E "image/(png|jpeg|jpg|gif|webp|bmp)" || wl-paste -l 2>/dev/null | grep -E "image/(png|jpeg|jpg|gif|webp|bmp)"`,saveImage:`xclip -selection clipboard -t image/png -o > "${i}" 2>/dev/null || wl-paste --type image/png > "${i}" 2>/dev/null || xclip -selection clipboard -t image/bmp -o > "${i}" 2>/dev/null || wl-paste --type image/bmp > "${i}"`,getPath:`xclip -selection clipboard -t text/plain -o 2>/dev/null || wl-paste 2>/dev/null`,deleteFile:`rm -f "${i}"`},win32:{checkImage:`powershell -NoProfile -Command "(Get-Clipboard -Format Image) -ne $null"`,saveImage:`powershell -NoProfile -Command "$img = Get-Clipboard -Format Image; if ($img) { $img.Save('${i.replace(/\\/g,`\\\\`)}', [System.Drawing.Imaging.ImageFormat]::Png) }"`,getPath:`powershell -NoProfile -Command "Get-Clipboard"`,deleteFile:`del /f "${i}"`}};return{commands:a[e]||a.linux,screenshotPath:i}}async function V9e(){return process.platform===`darwin`&&(await Gi(`osascript`,[`-e`,`the clipboard as «class PNGf»`])).code===0}async function nY(){let{commands:e,screenshotPath:t}=B9e();try{if((await Ki(e.checkImage,{shell:!0,reject:!1})).exitCode!==0||(await Ki(e.saveImage,{shell:!0,reject:!1})).exitCode!==0)return null;let n=G().readFileBytesSync(t);n.length>=2&&n[0]===66&&n[1]===77&&(n=await(await Vg())(n).png().toBuffer());let r=await Ug(n,n.length,`png`),i=r.buffer.toString(`base64`),a=Kg(i);return Ki(e.deleteFile,{shell:!0,reject:!1}),{base64:i,mediaType:a,dimensions:r.dimensions}}catch{return null}}async function H9e(){let{commands:e}=B9e();try{let t=await Ki(e.getPath,{shell:!0,reject:!1});return t.exitCode!==0||!t.stdout?null:t.stdout.trim()}catch(e){return q(e),null}}function U9e(e){return e.startsWith(`"`)&&e.endsWith(`"`)||e.startsWith(`'`)&&e.endsWith(`'`)?e.slice(1,-1):e}function W9e(e){if(process.platform===`win32`)return e;let t=`__DOUBLE_BACKSLASH_${eu(8).toString(`hex`)}__`;return e.replace(/\\\\/g,t).replace(/\\(.)/g,`$1`).replace(new RegExp(t,`g`),`\\`)}function rY(e){let t=W9e(U9e(e.trim()));return iY.test(t)}function G9e(e){let t=W9e(U9e(e.trim()));return iY.test(t)?t:null}async function K9e(e){let t=G9e(e);if(!t)return null;let n=t,r;try{if(Dl(n))r=G().readFileBytesSync(n);else{let e=await H9e();e&&n===wl(e)&&(r=G().readFileBytesSync(e))}}catch(e){return q(e),null}if(!r)return null;if(r.length===0)return U(`Image file is empty: ${n}`,{level:`warn`}),null;r.length>=2&&r[0]===66&&r[1]===77&&(r=await(await Vg())(r).png().toBuffer());let i=El(n).slice(1).toLowerCase()||`png`,a=await Ug(r,r.length,i),o=a.buffer.toString(`base64`);return{path:n,base64:o,mediaType:Kg(o),dimensions:a.dimensions}}var iY,aY=n((()=>{Wi(),Rg(),Txe(),W(),qi(),Un(),r_(),oa(),iY=/\.(png|jpe?g|gif|webp)$/i}));function q9e(e,t){let{addNotification:n}=XJ(),r=(0,oY.useRef)(e),i=(0,oY.useRef)(0),a=(0,oY.useRef)(null);(0,oY.useEffect)(()=>{let o=r.current;if(r.current=e,!(!t||!e||o))return a.current&&clearTimeout(a.current),a.current=setTimeout(async(e,t,n)=>{e.current=null;let r=Date.now();r-t.current<X9e||await V9e()&&(t.current=r,n({key:J9e,text:`Image in clipboard · ${Ey(`chat:imagePaste`,`Chat`,`ctrl+v`)} to paste`,priority:`immediate`,timeoutMs:8e3}))},Y9e,a,i,n),()=>{a.current&&(clearTimeout(a.current),a.current=null)}},[e,t,n])}var oY,J9e,Y9e,X9e,Z9e=n((()=>{oY=r(ze(),1),tY(),Oy(),aY(),J9e=`clipboard-image-hint`,Y9e=1e3,X9e=3e4}));function Q9e(e,t){switch(t){case`bash`:return`!${e}`;default:return e}}function $9e(e){return e.startsWith(`!`)?`bash`:`prompt`}function eet(e){return $9e(e)===`prompt`?e:e.slice(1)}function tet(e){return e===`!`}var net=n((()=>{}));function sY(){return Y(p(),cet)}function ret(e){return $l(`sha256`).update(e).digest(`hex`).slice(0,16)}function iet(e){return Y(sY(),`${e}.txt`)}async function aet(e,t){try{await su(sY(),{recursive:!0});let n=iet(e);await _u(n,t,{encoding:`utf8`,mode:384}),U(`Stored paste ${e} to ${n}`)}catch(e){U(`Failed to store paste: ${e}`)}}async function oet(e){try{return await lu(iet(e),{encoding:`utf8`})}catch(t){return Tn(t)||U(`Failed to retrieve paste ${e}: ${t}`),null}}async function set(e){let t=sY(),n;try{n=await uu(t)}catch{return}let r=e.getTime();for(let e of n){if(!e.endsWith(`.txt`))continue;let n=Y(t,e);try{(await mu(n)).mtimeMs<r&&(await gu(n),U(`Cleaned up old paste: ${n}`))}catch{}}}var cet,uet=n((()=>{W(),h(),Mn(),cet=`paste-cache`}));function det(e){return(e.match(/\r\n|\r|\n/g)||[]).length}function fet(e,t){return t===0?`[Pasted text #${e}]`:`[Pasted text #${e} +${t} lines]`}function pet(e){return`[Image #${e}]`}function met(e){return[...e.matchAll(/\[(Pasted text|Image|\.\.\.Truncated text) #(\d+)(?: \+\d+ lines)?(\.)*\]/g)].map(e=>({id:parseInt(e[2]||`0`,10),match:e[0],index:e.index})).filter(e=>e.id>0)}function het(e,t){let n=met(e),r=e;for(let e=n.length-1;e>=0;e--){let i=n[e],a=t[i.id];a?.type===`text`&&(r=r.slice(0,i.index)+a.content+r.slice(i.index+i.match.length))}return r}function get(e){return Nn(e)}async function*_et(){let e=ln();for(let e=uY.length-1;e>=0;e--)yield uY[e];let t=Y(p(),`history.jsonl`);try{for await(let n of xne(t))try{let t=get(n);if(t.sessionId===e&&hY.has(t.timestamp))continue;yield t}catch(e){U(`Failed to parse history line: ${e}`)}}catch(e){if(Dn(e)===`ENOENT`)return;throw e}}async function*vet(){for await(let e of _et())yield await cY(e)}async function*yet(){let e=tn(),t=ln(),n=[],r=0;for await(let i of _et())if(!(!i||typeof i.project!=`string`)&&i.project===e&&(i.sessionId===t?(yield await cY(i),r++):n.push(i),r+n.length>=lY))break;for(let e of n){if(r>=lY)return;yield await cY(e),r++}}async function bet(e){if(e.content)return{id:e.id,type:e.type,content:e.content,mediaType:e.mediaType,filename:e.filename};if(e.contentHash){let t=await oet(e.contentHash);if(t)return{id:e.id,type:e.type,content:t,mediaType:e.mediaType,filename:e.filename}}return null}async function cY(e){let t={};for(let[n,r]of Object.entries(e.pastedContents||{})){let e=await bet(r);e&&(t[Number(n)]=e)}return{display:e.display,pastedContents:t}}async function xet(){if(uY.length===0)return;let e;try{let t=Y(p(),`history.jsonl`);await _u(t,``,{encoding:`utf8`,mode:384,flag:`a`}),e=await Si(t,{stale:1e4,retries:{retries:3,minTimeout:50}});let n=uY.map(e=>`${V(e)}\n`);uY=[],await ru(t,n.join(``),{mode:384})}catch(e){U(`Failed to write prompt history: ${e}`)}finally{e&&await e()}}async function Cet(e){if(!(dY||uY.length===0)&&!(e>5)){dY=!0;try{await xet()}finally{dY=!1,uY.length>0&&(await Ho(500),Cet(e+1))}}}async function wet(e){let t=typeof e==`string`?{display:e,pastedContents:{}}:e,n={};if(t.pastedContents){for(let[e,r]of Object.entries(t.pastedContents))if(r.type!==`image`)if(r.content.length<=Det)n[Number(e)]={id:r.id,type:r.type,content:r.content,mediaType:r.mediaType,filename:r.filename};else{let t=ret(r.content);n[Number(e)]={id:r.id,type:r.type,contentHash:t,mediaType:r.mediaType,filename:r.filename},aet(t,r.content)}}let r={...t,pastedContents:n,timestamp:Date.now(),project:tn(),sessionId:ln()};uY.push(r),mY=r,fY=Cet(0)}function Tet(e){m(process.env.CLAUDE_CODE_SKIP_PROMPT_HISTORY)||(pY||(pY=!0,qn(async()=>{fY&&await fY,uY.length>0&&await xet()})),wet(e))}function Eet(){if(!mY)return;let e=mY;mY=null;let t=uY.lastIndexOf(e);t===-1?hY.add(e.timestamp):uY.splice(t,1)}var lY,Det,uY,dY,fY,pY,mY,hY,Oet=n((()=>{Gt(),Xn(),W(),h(),Mn(),Un(),Ei(),uet(),Bo(),Zn(),lY=100,Det=1024,uY=[],dY=!1,fY=null,pY=!1,mY=null,hY=new Set}));function gY(e,t=`append`){e.length>0&&(xY&&yY.length>0?t===`prepend`?yY[0]=e+yY[0]:yY[0]+=e:(yY.unshift(e),yY.length>Net&&yY.pop()),xY=!0,wY=!1)}function ket(){return yY[0]??``}function _Y(){xY=!1}function Aet(e,t){SY=e,CY=t,wY=!0,bY=0}function jet(){return!wY||yY.length<=1?null:(bY=(bY+1)%yY.length,{text:yY[bY]??``,start:SY,length:CY})}function Met(e){CY=e}function vY(){wY=!1}var Net,yY,bY,xY,SY,CY,wY,Pet,TY,EY,DY,OY,kY,AY,Fet,Iet=n((()=>{I(),qie(),b(),Net=10,yY=[],bY=0,xY=!1,SY=0,CY=0,wY=!1,Pet=/^[\p{L}\p{N}\p{M}_]$/u,TY=/\s/,EY=e=>Pet.test(e),DY=e=>TY.test(e),OY=e=>e.length>0&&!DY(e)&&!EY(e),kY=class e{constructor(e,t=0,n=0){x(this,`measuredText`,void 0),x(this,`selection`,void 0),x(this,`offset`,void 0),this.measuredText=e,this.selection=n,this.offset=Math.max(0,Math.min(this.text.length,t))}static fromText(t,n,r=0,i=0){return new e(new Fet(t,n-1),r,i)}getViewportStartLine(e){if(e===void 0||e<=0)return 0;let{line:t}=this.getPosition(),n=this.measuredText.getWrappedText();if(n.length<=e)return 0;let r=Math.floor(e/2),i=Math.max(0,t-r),a=Math.min(n.length,i+e);return a-i<e&&(i=Math.max(0,a-e)),i}getViewportCharOffset(e){let t=this.getViewportStartLine(e);return t===0?0:this.measuredText.getWrappedLines()[t]?.startOffset??0}getViewportCharEnd(e){let t=this.getViewportStartLine(e),n=this.measuredText.getWrappedLines();if(e===void 0||e<=0)return this.text.length;let r=Math.min(n.length,t+e);return r>=n.length?this.text.length:n[r]?.startOffset??this.text.length}render(e,t,n,r,i){let{line:a,column:o}=this.getPosition(),s=this.measuredText.getWrappedText(),c=this.getViewportStartLine(i),l=i!==void 0&&i>0?Math.min(s.length,c+i):s.length;return s.slice(c,l).map((i,l)=>{let u=l+c,d=i;if(t){let e=Array.from(Pa().segment(i));if(u===s.length-1){let n=Math.min(6,e.length),r=e.length-n,a=e.length>n?e[r].index:0;d=t.repeat(r)+i.slice(a)}else d=t.repeat(e.length)}if(a!==u)return d.trimEnd();let f=``,p=e,m=``,h=0,g=!1;for(let{segment:e}of Pa().segment(d)){if(g){m+=e;continue}let t=h+ye(e);t>o?(p=e,g=!0):(h=t,f+=e)}let _,v=``;if(r&&u===s.length-1&&this.isAtEnd()&&r.text.length>0){let t=Jie(r.text)||r.text[0];_=e?n(t):t;let i=r.text.slice(t.length);i.length>0&&(v=r.dim(i))}else _=e?n(p):p;return f+_+v+m.trimEnd()}).join(`
|
|
1651
|
+
`).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&&Ea(g,`tag`)||void 0,createdAt:f}}async function SJ(e,t,n){let r;try{r=await uu(e)}catch{return[]}return(await Promise.all(r.map(async r=>{if(!r.endsWith(`.jsonl`))return null;let i=zie(r.slice(0,-6));if(!i)return null;let a=Y(e,r);if(!t)return{sessionId:i,filePath:a,mtime:0,projectPath:n};try{return{sessionId:i,filePath:a,mtime:(await mu(a)).mtime.getTime(),projectPath:n}}catch{return null}}))).filter(e=>e!==null)}async function R7e(e){let t=await Iie(e.filePath);if(!t)return null;let n=L7e(e.sessionId,t,e.projectPath);return n?(e.mtime&&(n.lastModified=e.mtime),n):null}function z7e(e,t){return t.mtime===e.mtime?t.sessionId<e.sessionId?-1:+(t.sessionId>e.sessionId):t.mtime-e.mtime}async function B7e(e,t,n){e.sort(z7e);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+G7e,e.length),c=e.slice(t,s),l=await Promise.all(c.map(R7e));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 V7e(e){let t=await Promise.all(e.map(R7e)),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 H7e(e,t,n){let r=await Vie(e),i;if(t)try{i=await Rie(r)}catch{i=[]}else i=[];if(i.length<=1){let e=await Da(r);return e?SJ(e,n,r):[]}let a=Ca(),o=process.platform===`win32`,s=i.map(e=>{let t=Ta(e);return{path:e,prefix:o?t.toLowerCase():t}});s.sort((e,t)=>t.prefix.length-e.prefix.length);let c;try{c=await uu(a,{withFileTypes:!0})}catch{let e=await Da(r);return e?SJ(e,n,r):[]}let l=[],u=new Set,d=await Da(r);if(d){let e=wl(d);u.add(o?e.toLowerCase():e),l.push(...await SJ(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 SJ(Y(a,e.name),n,r));break}}}return l}async function U7e(e){let t=Ca(),n;try{n=await uu(t,{withFileTypes:!0})}catch{return[]}return(await Promise.all(n.filter(e=>e.isDirectory()).map(n=>SJ(Y(t,n.name),e)))).flat()}async function W7e(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 H7e(t,i??!0,o):await U7e(o);return o?B7e(s,n,a):V7e(s)}var G7e,K7e=n((()=>{Fie(),wa(),G7e=32}));function CJ(){return Y(ki(),Q7e)}async function q7e(){try{return(await mu(CJ())).mtimeMs}catch{return 0}}async function J7e(){let e=CJ(),t,n;try{let[r,i]=await Promise.all([mu(e),lu(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<$7e&&n!==void 0&&Rc(n))return U(`[autoDream] lock held by live PID ${n} (mtime ${Math.round((Date.now()-t)/1e3)}s ago)`),null;await su(ki(),{recursive:!0}),await _u(e,String(process.pid));let r;try{r=await lu(e,`utf8`)}catch{return null}return parseInt(r.trim(),10)===process.pid?t??0:null}async function Y7e(e){let t=CJ();try{if(e===0){await gu(t);return}await _u(t,``);let n=e/1e3;await Nle(t,n,n)}catch(e){U(`[autoDream] rollback failed: ${e.message} — next trigger delayed to minHours`)}}async function X7e(e){return(await SJ(o8(Zt()),!0)).filter(t=>t.mtime>e).map(e=>e.sessionId)}async function Z7e(){try{await su(ki(),{recursive:!0}),await _u(CJ(),String(process.pid))}catch(e){U(`[autoDream] recordConsolidation write failed: ${e.message}`)}}var Q7e,$7e,wJ=n((()=>{Gt(),Ci(),W(),zc(),K7e(),m8(),Q7e=`.consolidate-lock`,$7e=3600*1e3}));function e9e(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`dream`}function t9e(e,t){let n=o5(`dream`);return DL({...s5(n,`dream`,`dreaming`),type:`dream`,status:`running`,phase:`starting`,sessionsReviewing:t.sessionsReviewing,filesTouched:[],turns:[],abortController:t.abortController,priorMtime:t.priorMtime},e),n}function n9e(e,t,n,r){EL(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 r9e(e,t){EL(e,t,e=>({...e,status:`completed`,endTime:Date.now(),notified:!0,abortController:void 0}))}function i9e(e,t){EL(e,t,e=>({...e,status:`failed`,endTime:Date.now(),notified:!0,abortController:void 0}))}var TJ,EJ=n((()=>{wJ(),c5(),kL(),TJ={name:`DreamTask`,type:`dream`,async kill(e,t){let n;EL(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 Y7e(n)}}})),DJ,a9e=n((()=>{_t(),vt(),DJ=gt(()=>B({restrictions:it(L(),B({allowed:pt()}))}))}));function o9e(e){return e instanceof Error}function s9e(){FJ||AJ()&&(FJ=new Promise(e=>{IJ=e,setTimeout(()=>{IJ&&(U(`Policy limits: Loading promise timed out, resolving anyway`),IJ(),IJ=null)},D9e)}))}function OJ(){return Y(p(),w9e)}function c9e(){return`${Wa().BASE_API_URL}/api/claude_code/policy_limits`}function kJ(e){if(Array.isArray(e))return e.map(kJ);if(typeof e==`object`&&e){let t={};for(let[n,r]of Object.entries(e).sort(([e],[t])=>e.localeCompare(t)))t[n]=kJ(r);return t}return e}function l9e(e){let t=V(kJ(e));return`sha256:${$l(`sha256`).update(t).digest(`hex`)}`}function AJ(){if(eo()!==`firstParty`||!Qo())return!1;try{let{key:e}=Go({skipRetrievingKeyFromApiKeyHelper:!0});if(e)return!0}catch{}let e=Mo();return!(!e?.accessToken||!e.scopes?.includes(`user:inference`)||e.subscriptionType!==`enterprise`&&e.subscriptionType!==`team`)}async function u9e(){FJ&&await FJ}function d9e(){try{let{key:e}=Go({skipRetrievingKeyFromApiKeyHelper:!0});if(e)return{headers:{"x-api-key":e}}}catch{}let e=Mo();return e?.accessToken?{headers:{Authorization:`Bearer ${e.accessToken}`,"anthropic-beta":nae}}:{headers:{},error:`No authentication available`}}async function f9e(e){let t=null;for(let n=1;n<=6;n++){if(t=await p9e(e),t.success||t.skipRetry||n>MJ)return t;let r=sR(n);U(`Policy limits: Retry ${n}/${MJ} after ${r}ms`),await Ho(r)}return t}async function p9e(e){try{await zo();let t=d9e();if(t.error)return{success:!1,error:`Authentication required for policy limits`,skipRetry:!0};let n=c9e(),r={...t.headers,"User-Agent":Cse()};e&&(r[`If-None-Match`]=`"${e}"`);let i=await ue.get(n,{headers:r,timeout:T9e,validateStatus:e=>e===200||e===304||e===404});if(i.status===304)return U(`Policy limits: Using cached restrictions (304)`),{success:!0,restrictions:null,etag:e};if(i.status===404)return U(`Policy limits: No restrictions found (404)`),{success:!0,restrictions:{},etag:void 0};let a=DJ().safeParse(i.data);return a.success?(U(`Policy limits: Fetched successfully`),{success:!0,restrictions:a.data.restrictions}):(U(`Policy limits: Invalid response format - ${a.error.message}`),{success:!1,error:`Invalid policy limits format`})}catch(e){let{kind:t,message:n}=vne(e);switch(t){case`auth`:return{success:!1,error:`Not authorized for policy limits`,skipRetry:!0};case`timeout`:return{success:!1,error:`Policy limits request timeout`};case`network`:return{success:!1,error:`Cannot connect to server`};default:return{success:!1,error:n}}}}function m9e(){try{let e=Ma(Kl(OJ(),`utf-8`),!1),t=DJ().safeParse(e);return t.success?t.data.restrictions:null}catch{return null}}async function h9e(e){try{let t=OJ();await _u(t,V({restrictions:e},null,2),{encoding:`utf-8`,mode:384}),U(`Policy limits: Saved to ${t}`)}catch(e){U(`Policy limits: Failed to save - ${e instanceof Error?e.message:`unknown error`}`)}}async function jJ(){if(!AJ())return null;let e=m9e(),t=e?l9e(e):void 0;try{let n=await f9e(t);if(!n.success)return e?(U(`Policy limits: Using stale cache after fetch failure`),LJ=e,e):null;if(n.restrictions===null&&e)return U(`Policy limits: Cache still valid (304 Not Modified)`),LJ=e,e;let r=n.restrictions||{};if(Object.keys(r).length>0)return LJ=r,await h9e(r),U(`Policy limits: Applied new restrictions successfully`),r;LJ=r;try{await gu(OJ()),U(`Policy limits: Deleted cached file (404 response)`)}catch(e){o9e(e)&&e.code!==`ENOENT`&&U(`Policy limits: Failed to delete cached file - ${e.message}`)}return r}catch{return e?(U(`Policy limits: Using stale cache after error`),LJ=e,e):null}}function g9e(e){let t=_9e();if(!t)return!(Oie()&&O9e.has(e));let n=t[e];return!n||n.allowed}function _9e(){if(!AJ())return null;if(LJ)return LJ;let e=m9e();return e?(LJ=e,e):null}async function v9e(){AJ()&&!FJ&&(FJ=new Promise(e=>{IJ=e}));try{await jJ(),AJ()&&S9e()}finally{IJ&&(IJ(),IJ=null)}}async function y9e(){await b9e(),AJ()&&(await jJ(),U(`Policy limits: Refreshed after auth change`))}async function b9e(){C9e(),LJ=null,FJ=null,IJ=null;try{await gu(OJ())}catch{}}async function x9e(){if(!AJ())return;let e=LJ?V(LJ):null;try{await jJ(),(LJ?V(LJ):null)!==e&&U(`Policy limits: Changed during background poll`)}catch{}}function S9e(){NJ===null&&AJ()&&(NJ=setInterval(()=>{x9e()},E9e),NJ.unref(),PJ||(PJ=!0,qn(async()=>C9e())))}function C9e(){NJ!==null&&(clearInterval(NJ),NJ=null)}var w9e,T9e,MJ,E9e,NJ,PJ,FJ,IJ,D9e,LJ,O9e,RJ=n((()=>{de(),Ga(),Do(),Xn(),W(),h(),Mn(),ja(),es(),Die(),Bo(),Zn(),Sse(),_R(),a9e(),w9e=`policy-limits.json`,T9e=1e4,MJ=5,E9e=3600*1e3,NJ=null,PJ=!1,FJ=null,IJ=null,D9e=3e4,LJ=null,O9e=new Set([`allow_product_feedback`])}));async function k9e(){let e=Mo()?.accessToken;if(!e)throw Error(`Work Mate web sessions require authentication with a Claude.ai account. API key authentication is not sufficient.`);let t=await lo();if(!t)throw Error(`Unable to get organization UUID`);let n=`${Wa().BASE_API_URL}/v1/environment_providers`;try{let r={...ml(e),"x-organization-uuid":t},i=await ue.get(n,{headers:r,timeout:15e3});if(i.status!==200)throw Error(`Failed to fetch environments: ${i.status} ${i.statusText}`);return i.data.environments}catch(e){let t=Fn(e);throw q(t),Error(`Failed to fetch environments: ${t.message}`)}}var A9e=n((()=>{de(),Ga(),To(),Do(),Mn(),oa(),gl()}));async function j9e(){return as()?zo():!1}async function M9e(){return await uie({ignoreUntracked:!0})}async function N9e(e,t,n){try{let r=Mo()?.accessToken;if(!r)return U(`checkGithubAppInstalled: No access token found, assuming app not installed`),!1;let i=await lo();if(!i)return U(`checkGithubAppInstalled: No org UUID found, assuming app not installed`),!1;let a=`${Wa().BASE_API_URL}/api/oauth/organizations/${i}/code/repos/${e}/${t}`,o={...ml(r),"x-organization-uuid":i};U(`Checking GitHub app installation for ${e}/${t}`);let s=await ue.get(a,{headers:o,timeout:15e3,signal:n});if(s.status===200){if(s.data.status){let n=s.data.status.app_installed;return U(`GitHub app ${n?`is`:`is not`} installed on ${e}/${t}`),n}return U(`GitHub app is not installed on ${e}/${t} (status is null)`),!1}return U(`checkGithubAppInstalled: Unexpected response status ${s.status}`),!1}catch(n){if(ue.isAxiosError(n)){let r=n.response?.status;if(r&&r>=400&&r<500)return U(`checkGithubAppInstalled: Got ${r} error, app likely not installed on ${e}/${t}`),!1}return U(`checkGithubAppInstalled error: ${H(n)}`),!1}}var zJ=n((()=>{de(),Ga(),To(),Do(),Sn(),W(),fl(),Mn(),Bi(),gl(),A9e()})),P9e=n((()=>{RJ(),fl(),h(),zJ()}));function BJ(){if(process.stdout.isTTY)try{ql(1,qe);let e=Ae.get(process.stdout);if(e?.isAltScreenActive)try{e.unmount()}catch{ql(1,vee)}e?.drainStdin(),e?.detachForShutdown(),ql(1,fe),ql(1,ke),ql(1,nee),ql(1,see),ql(1,gee),ql(1,lee),Ke()&&ql(1,dee(pee)),m(process.env.CLAUDE_CODE_DISABLE_TERMINAL_TITLE)||(process.platform===`win32`?process.title=``:ql(1,Ve))}catch{}}function VJ(){if(!GJ&&process.stdout.isTTY&&Bt()&&!Ot())try{let e=ln();if(!f6(e))return;let t=F6(e),n;n=t?`"${t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`:e,ql(1,Ue.dim(`\nResume this session with:\nclaude --resume ${n}\n`)),GJ=!0}catch{}}function HJ(e){qJ!==void 0&&(clearTimeout(qJ),qJ=void 0);try{Ae.get(process.stdout)?.drainStdin()}catch{}try{process.exit(e)}catch{process.kill(process.pid,`SIGKILL`)}throw Error(`unreachable`)}function UJ(e=0,t=`other`,n){process.exitCode=e,L9e=WJ(e,t,n).catch(t=>{U(`Graceful shutdown failed: ${t}`,{level:`error`}),BJ(),VJ(),HJ(e)}).catch(()=>{})}function F9e(){return KJ}async function WJ(e=0,t=`other`,n){if(KJ)return;KJ=!0;let{executeSessionEndHooks:r,getSessionEndHookTimeoutMs:i}=await import(`./hooks-DvVuNKRx.js`),a=i();qJ=setTimeout(e=>{BJ(),VJ(),HJ(e)},Math.max(5e3,a+3500),e),qJ.unref(),process.exitCode=e,BJ(),VJ();let o;try{let e=(async()=>{try{await wne()}catch{}})();await Promise.race([e,new Promise((e,t)=>{o=setTimeout(e=>e(new R9e),2e3,t)})]),clearTimeout(o)}catch{clearTimeout(o)}try{await r(t,{...n,signal:AbortSignal.timeout(a),timeoutMs:a})}catch{}try{Zie()}catch{}let s=Vee();s&&J(`tengu_cache_eviction_hint`,{scope:`session_end`,last_request_id:s});try{await Promise.race([Promise.all([jce(),Mce()]),Ho(500)])}catch{}if(n?.finalMessage)try{ql(2,`${n.finalMessage}\n`)}catch{}HJ(e)}var GJ,I9e,KJ,qJ,JJ,L9e,R9e,YJ=n((()=>{Ge(),d(),re(),Gt(),I(),Nce(),kce(),Na(),Xn(),W(),Pi(),h(),m8(),Bo(),Qie(),GJ=!1,I9e=u(()=>{te(()=>{}),process.on(`SIGINT`,()=>{process.argv.includes(`-p`)||process.argv.includes(`--print`)||(Ri(`info`,`shutdown_signal`,{signal:`SIGINT`}),WJ(0))}),process.on(`SIGTERM`,()=>{Ri(`info`,`shutdown_signal`,{signal:`SIGTERM`}),WJ(143)}),process.platform!==`win32`&&(process.on(`SIGHUP`,()=>{Ri(`info`,`shutdown_signal`,{signal:`SIGHUP`}),WJ(129)}),process.stdin.isTTY&&(JJ=setInterval(()=>{fte()||(!process.stdout.writable||!process.stdin.readable)&&(clearInterval(JJ),Ri(`info`,`shutdown_signal`,{signal:`orphan_detected`}),WJ(129))},3e4),JJ.unref())),process.on(`uncaughtException`,e=>{Ri(`error`,`uncaught_exception`,{error_name:e.name,error_message:e.message.slice(0,2e3)}),J(`tengu_uncaught_exception`,{error_name:e.name})}),process.on(`unhandledRejection`,e=>{let t=e instanceof Error?e.name:typeof e==`string`?`string`:`unknown`;Ri(`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)}),J(`tengu_unhandled_rejection`,{error_name:t})})}),KJ=!1,R9e=class extends Error{constructor(){super(`Cleanup timeout`)}}}));function XJ(){let e=cV(),t=sV(),n=(0,ZJ.useCallback)(()=>{t(e=>{let r=z9e(e.notifications.queue);return e.notifications.current!==null||!r?e:($J=setTimeout((e,t,n)=>{$J=null,e(e=>e.notifications.current?.key===t?{...e,notifications:{queue:e.notifications.queue,current:null}}:e),n()},r.timeoutMs??QJ,t,r.key,n),{...e,notifications:{queue:e.notifications.queue.filter(e=>e!==r),current:r}})})},[t]),r=(0,ZJ.useCallback)(e=>{if(e.priority===`immediate`){$J&&(clearTimeout($J),$J=null),$J=setTimeout((e,t,n)=>{$J=null,e(e=>e.notifications.current?.key===t.key?{...e,notifications:{queue:e.notifications.queue.filter(e=>!t.invalidates?.includes(e.key)),current:null}}:e),n()},e.timeoutMs??QJ,t,e,n),t(t=>({...t,notifications:{current:e,queue:[...t.notifications.current?[t.notifications.current]:[],...t.notifications.queue].filter(t=>t.priority!==`immediate`&&!e.invalidates?.includes(t.key))}}));return}t(r=>{if(e.fold){if(r.notifications.current?.key===e.key){let i=e.fold(r.notifications.current,e);return $J&&(clearTimeout($J),$J=null),$J=setTimeout((e,t,n)=>{$J=null,e(e=>e.notifications.current?.key===t?{...e,notifications:{queue:e.notifications.queue,current:null}}:e),n()},i.timeoutMs??QJ,t,i.key,n),{...r,notifications:{current:i,queue:r.notifications.queue}}}let i=r.notifications.queue.findIndex(t=>t.key===e.key);if(i!==-1){let t=e.fold(r.notifications.queue[i],e),n=[...r.notifications.queue];return n[i]=t,{...r,notifications:{current:r.notifications.current,queue:n}}}}if(!(!new Set(r.notifications.queue.map(e=>e.key)).has(e.key)&&r.notifications.current?.key!==e.key))return r;let i=r.notifications.current!==null&&e.invalidates?.includes(r.notifications.current.key);return i&&$J&&(clearTimeout($J),$J=null),{...r,notifications:{current:i?null:r.notifications.current,queue:[...r.notifications.queue.filter(t=>t.priority!==`immediate`&&!e.invalidates?.includes(t.key)),e]}}}),n()},[t,n]),i=(0,ZJ.useCallback)(e=>{t(t=>{let n=t.notifications.current?.key===e,r=t.notifications.queue.some(t=>t.key===e);return!n&&!r?t:(n&&$J&&(clearTimeout($J),$J=null),{...t,notifications:{current:n?null:t.notifications.current,queue:t.notifications.queue.filter(t=>t.key!==e)}})}),n()},[t,n]);return(0,ZJ.useEffect)(()=>{e.getState().notifications.queue.length>0&&n()},[]),{addNotification:r,removeNotification:i}}function z9e(e){if(e.length!==0)return e.reduce((e,t)=>eY[t.priority]<eY[e.priority]?t:e)}var ZJ,QJ,$J,eY,tY=n((()=>{ZJ=r(ze(),1),pV(),QJ=8e3,$J=null,eY={immediate:0,high:1,medium:2,low:3}}));function B9e(){let e=process.platform,t=process.env.CLAUDE_CODE_TMPDIR||(e===`win32`?process.env.TEMP||`C:\\Temp`:Sl()),n=`claude_cli_latest_screenshot.png`,r={darwin:Y(t,n),linux:Y(t,n),win32:Y(t,n)},i=r[e]||r.linux,a={darwin:{checkImage:`osascript -e 'the clipboard as «class PNGf»'`,saveImage:`osascript -e 'set png_data to (the clipboard as «class PNGf»)' -e 'set fp to open for access POSIX file "${i}" with write permission' -e 'write png_data to fp' -e 'close access fp'`,getPath:`osascript -e 'get POSIX path of (the clipboard as «class furl»)'`,deleteFile:`rm -f "${i}"`},linux:{checkImage:`xclip -selection clipboard -t TARGETS -o 2>/dev/null | grep -E "image/(png|jpeg|jpg|gif|webp|bmp)" || wl-paste -l 2>/dev/null | grep -E "image/(png|jpeg|jpg|gif|webp|bmp)"`,saveImage:`xclip -selection clipboard -t image/png -o > "${i}" 2>/dev/null || wl-paste --type image/png > "${i}" 2>/dev/null || xclip -selection clipboard -t image/bmp -o > "${i}" 2>/dev/null || wl-paste --type image/bmp > "${i}"`,getPath:`xclip -selection clipboard -t text/plain -o 2>/dev/null || wl-paste 2>/dev/null`,deleteFile:`rm -f "${i}"`},win32:{checkImage:`powershell -NoProfile -Command "(Get-Clipboard -Format Image) -ne $null"`,saveImage:`powershell -NoProfile -Command "$img = Get-Clipboard -Format Image; if ($img) { $img.Save('${i.replace(/\\/g,`\\\\`)}', [System.Drawing.Imaging.ImageFormat]::Png) }"`,getPath:`powershell -NoProfile -Command "Get-Clipboard"`,deleteFile:`del /f "${i}"`}};return{commands:a[e]||a.linux,screenshotPath:i}}async function V9e(){return process.platform===`darwin`&&(await Gi(`osascript`,[`-e`,`the clipboard as «class PNGf»`])).code===0}async function nY(){let{commands:e,screenshotPath:t}=B9e();try{if((await Ki(e.checkImage,{shell:!0,reject:!1})).exitCode!==0||(await Ki(e.saveImage,{shell:!0,reject:!1})).exitCode!==0)return null;let n=G().readFileBytesSync(t);n.length>=2&&n[0]===66&&n[1]===77&&(n=await(await Vg())(n).png().toBuffer());let r=await Ug(n,n.length,`png`),i=r.buffer.toString(`base64`),a=Kg(i);return Ki(e.deleteFile,{shell:!0,reject:!1}),{base64:i,mediaType:a,dimensions:r.dimensions}}catch{return null}}async function H9e(){let{commands:e}=B9e();try{let t=await Ki(e.getPath,{shell:!0,reject:!1});return t.exitCode!==0||!t.stdout?null:t.stdout.trim()}catch(e){return q(e),null}}function U9e(e){return e.startsWith(`"`)&&e.endsWith(`"`)||e.startsWith(`'`)&&e.endsWith(`'`)?e.slice(1,-1):e}function W9e(e){if(process.platform===`win32`)return e;let t=`__DOUBLE_BACKSLASH_${eu(8).toString(`hex`)}__`;return e.replace(/\\\\/g,t).replace(/\\(.)/g,`$1`).replace(new RegExp(t,`g`),`\\`)}function rY(e){let t=W9e(U9e(e.trim()));return iY.test(t)}function G9e(e){let t=W9e(U9e(e.trim()));return iY.test(t)?t:null}async function K9e(e){let t=G9e(e);if(!t)return null;let n=t,r;try{if(Dl(n))r=G().readFileBytesSync(n);else{let e=await H9e();e&&n===wl(e)&&(r=G().readFileBytesSync(e))}}catch(e){return q(e),null}if(!r)return null;if(r.length===0)return U(`Image file is empty: ${n}`,{level:`warn`}),null;r.length>=2&&r[0]===66&&r[1]===77&&(r=await(await Vg())(r).png().toBuffer());let i=El(n).slice(1).toLowerCase()||`png`,a=await Ug(r,r.length,i),o=a.buffer.toString(`base64`);return{path:n,base64:o,mediaType:Kg(o),dimensions:a.dimensions}}var iY,aY=n((()=>{Wi(),Rg(),Txe(),W(),qi(),Un(),r_(),oa(),iY=/\.(png|jpe?g|gif|webp)$/i}));function q9e(e,t){let{addNotification:n}=XJ(),r=(0,oY.useRef)(e),i=(0,oY.useRef)(0),a=(0,oY.useRef)(null);(0,oY.useEffect)(()=>{let o=r.current;if(r.current=e,!(!t||!e||o))return a.current&&clearTimeout(a.current),a.current=setTimeout(async(e,t,n)=>{e.current=null;let r=Date.now();r-t.current<X9e||await V9e()&&(t.current=r,n({key:J9e,text:`Image in clipboard · ${Ey(`chat:imagePaste`,`Chat`,`ctrl+v`)} to paste`,priority:`immediate`,timeoutMs:8e3}))},Y9e,a,i,n),()=>{a.current&&(clearTimeout(a.current),a.current=null)}},[e,t,n])}var oY,J9e,Y9e,X9e,Z9e=n((()=>{oY=r(ze(),1),tY(),Oy(),aY(),J9e=`clipboard-image-hint`,Y9e=1e3,X9e=3e4}));function Q9e(e,t){switch(t){case`bash`:return`!${e}`;default:return e}}function $9e(e){return e.startsWith(`!`)?`bash`:`prompt`}function eet(e){return $9e(e)===`prompt`?e:e.slice(1)}function tet(e){return e===`!`}var net=n((()=>{}));function sY(){return Y(p(),cet)}function ret(e){return $l(`sha256`).update(e).digest(`hex`).slice(0,16)}function iet(e){return Y(sY(),`${e}.txt`)}async function aet(e,t){try{await su(sY(),{recursive:!0});let n=iet(e);await _u(n,t,{encoding:`utf8`,mode:384}),U(`Stored paste ${e} to ${n}`)}catch(e){U(`Failed to store paste: ${e}`)}}async function oet(e){try{return await lu(iet(e),{encoding:`utf8`})}catch(t){return Tn(t)||U(`Failed to retrieve paste ${e}: ${t}`),null}}async function set(e){let t=sY(),n;try{n=await uu(t)}catch{return}let r=e.getTime();for(let e of n){if(!e.endsWith(`.txt`))continue;let n=Y(t,e);try{(await mu(n)).mtimeMs<r&&(await gu(n),U(`Cleaned up old paste: ${n}`))}catch{}}}var cet,uet=n((()=>{W(),h(),Mn(),cet=`paste-cache`}));function det(e){return(e.match(/\r\n|\r|\n/g)||[]).length}function fet(e,t){return t===0?`[Pasted text #${e}]`:`[Pasted text #${e} +${t} lines]`}function pet(e){return`[Image #${e}]`}function met(e){return[...e.matchAll(/\[(Pasted text|Image|\.\.\.Truncated text) #(\d+)(?: \+\d+ lines)?(\.)*\]/g)].map(e=>({id:parseInt(e[2]||`0`,10),match:e[0],index:e.index})).filter(e=>e.id>0)}function het(e,t){let n=met(e),r=e;for(let e=n.length-1;e>=0;e--){let i=n[e],a=t[i.id];a?.type===`text`&&(r=r.slice(0,i.index)+a.content+r.slice(i.index+i.match.length))}return r}function get(e){return Nn(e)}async function*_et(){let e=ln();for(let e=uY.length-1;e>=0;e--)yield uY[e];let t=Y(p(),`history.jsonl`);try{for await(let n of xne(t))try{let t=get(n);if(t.sessionId===e&&hY.has(t.timestamp))continue;yield t}catch(e){U(`Failed to parse history line: ${e}`)}}catch(e){if(Dn(e)===`ENOENT`)return;throw e}}async function*vet(){for await(let e of _et())yield await cY(e)}async function*yet(){let e=tn(),t=ln(),n=[],r=0;for await(let i of _et())if(!(!i||typeof i.project!=`string`)&&i.project===e&&(i.sessionId===t?(yield await cY(i),r++):n.push(i),r+n.length>=lY))break;for(let e of n){if(r>=lY)return;yield await cY(e),r++}}async function bet(e){if(e.content)return{id:e.id,type:e.type,content:e.content,mediaType:e.mediaType,filename:e.filename};if(e.contentHash){let t=await oet(e.contentHash);if(t)return{id:e.id,type:e.type,content:t,mediaType:e.mediaType,filename:e.filename}}return null}async function cY(e){let t={};for(let[n,r]of Object.entries(e.pastedContents||{})){let e=await bet(r);e&&(t[Number(n)]=e)}return{display:e.display,pastedContents:t}}async function xet(){if(uY.length===0)return;let e;try{let t=Y(p(),`history.jsonl`);await _u(t,``,{encoding:`utf8`,mode:384,flag:`a`}),e=await Si(t,{stale:1e4,retries:{retries:3,minTimeout:50}});let n=uY.map(e=>`${V(e)}\n`);uY=[],await ru(t,n.join(``),{mode:384})}catch(e){U(`Failed to write prompt history: ${e}`)}finally{e&&await e()}}async function Cet(e){if(!(dY||uY.length===0)&&!(e>5)){dY=!0;try{await xet()}finally{dY=!1,uY.length>0&&(await Ho(500),Cet(e+1))}}}async function wet(e){let t=typeof e==`string`?{display:e,pastedContents:{}}:e,n={};if(t.pastedContents){for(let[e,r]of Object.entries(t.pastedContents))if(r.type!==`image`)if(r.content.length<=Det)n[Number(e)]={id:r.id,type:r.type,content:r.content,mediaType:r.mediaType,filename:r.filename};else{let t=ret(r.content);n[Number(e)]={id:r.id,type:r.type,contentHash:t,mediaType:r.mediaType,filename:r.filename},aet(t,r.content)}}let r={...t,pastedContents:n,timestamp:Date.now(),project:tn(),sessionId:ln()};uY.push(r),mY=r,fY=Cet(0)}function Tet(e){m(process.env.CLAUDE_CODE_SKIP_PROMPT_HISTORY)||(pY||(pY=!0,qn(async()=>{fY&&await fY,uY.length>0&&await xet()})),wet(e))}function Eet(){if(!mY)return;let e=mY;mY=null;let t=uY.lastIndexOf(e);t===-1?hY.add(e.timestamp):uY.splice(t,1)}var lY,Det,uY,dY,fY,pY,mY,hY,Oet=n((()=>{Gt(),Xn(),W(),h(),Mn(),Un(),Ei(),uet(),Bo(),Zn(),lY=100,Det=1024,uY=[],dY=!1,fY=null,pY=!1,mY=null,hY=new Set}));function gY(e,t=`append`){e.length>0&&(xY&&yY.length>0?t===`prepend`?yY[0]=e+yY[0]:yY[0]+=e:(yY.unshift(e),yY.length>Net&&yY.pop()),xY=!0,wY=!1)}function ket(){return yY[0]??``}function _Y(){xY=!1}function Aet(e,t){SY=e,CY=t,wY=!0,bY=0}function jet(){return!wY||yY.length<=1?null:(bY=(bY+1)%yY.length,{text:yY[bY]??``,start:SY,length:CY})}function Met(e){CY=e}function vY(){wY=!1}var Net,yY,bY,xY,SY,CY,wY,Pet,TY,EY,DY,OY,kY,AY,Fet,Iet=n((()=>{I(),qie(),b(),Net=10,yY=[],bY=0,xY=!1,SY=0,CY=0,wY=!1,Pet=/^[\p{L}\p{N}\p{M}_]$/u,TY=/\s/,EY=e=>Pet.test(e),DY=e=>TY.test(e),OY=e=>e.length>0&&!DY(e)&&!EY(e),kY=class e{constructor(e,t=0,n=0){x(this,`measuredText`,void 0),x(this,`selection`,void 0),x(this,`offset`,void 0),this.measuredText=e,this.selection=n,this.offset=Math.max(0,Math.min(this.text.length,t))}static fromText(t,n,r=0,i=0){return new e(new Fet(t,n-1),r,i)}getViewportStartLine(e){if(e===void 0||e<=0)return 0;let{line:t}=this.getPosition(),n=this.measuredText.getWrappedText();if(n.length<=e)return 0;let r=Math.floor(e/2),i=Math.max(0,t-r),a=Math.min(n.length,i+e);return a-i<e&&(i=Math.max(0,a-e)),i}getViewportCharOffset(e){let t=this.getViewportStartLine(e);return t===0?0:this.measuredText.getWrappedLines()[t]?.startOffset??0}getViewportCharEnd(e){let t=this.getViewportStartLine(e),n=this.measuredText.getWrappedLines();if(e===void 0||e<=0)return this.text.length;let r=Math.min(n.length,t+e);return r>=n.length?this.text.length:n[r]?.startOffset??this.text.length}render(e,t,n,r,i){let{line:a,column:o}=this.getPosition(),s=this.measuredText.getWrappedText(),c=this.getViewportStartLine(i),l=i!==void 0&&i>0?Math.min(s.length,c+i):s.length;return s.slice(c,l).map((i,l)=>{let u=l+c,d=i;if(t){let e=Array.from(Pa().segment(i));if(u===s.length-1){let n=Math.min(6,e.length),r=e.length-n,a=e.length>n?e[r].index:0;d=t.repeat(r)+i.slice(a)}else d=t.repeat(e.length)}if(a!==u)return d.trimEnd();let f=``,p=e,m=``,h=0,g=!1;for(let{segment:e}of Pa().segment(d)){if(g){m+=e;continue}let t=h+ye(e);t>o?(p=e,g=!0):(h=t,f+=e)}let _,v=``;if(r&&u===s.length-1&&this.isAtEnd()&&r.text.length>0){let t=Jie(r.text)||r.text[0];_=e?n(t):t;let i=r.text.slice(t.length);i.length>0&&(v=r.dim(i))}else _=e?n(p):p;return f+_+v+m.trimEnd()}).join(`
|
|
1652
1652
|
`)}left(){if(this.offset===0)return this;let t=this.imageRefEndingAt(this.offset);if(t)return new e(this.measuredText,t.start);let n=this.measuredText.prevOffset(this.offset);return new e(this.measuredText,n)}right(){if(this.offset>=this.text.length)return this;let t=this.imageRefStartingAt(this.offset);if(t)return new e(this.measuredText,t.end);let n=this.measuredText.nextOffset(this.offset);return new e(this.measuredText,Math.min(n,this.text.length))}imageRefEndingAt(e){let t=this.text.slice(0,e).match(/\[Image #\d+\]$/);return t?{start:e-t[0].length,end:e}:null}imageRefStartingAt(e){let t=this.text.slice(e).match(/^\[Image #\d+\]/);return t?{start:e,end:e+t[0].length}:null}snapOutOfImageRef(e,t){let n=/\[Image #\d+\]/g,r;for(;(r=n.exec(this.text))!==null;){let n=r.index,i=n+r[0].length;if(e>n&&e<i)return t===`start`?n:i}return e}up(){let{line:t,column:n}=this.getPosition();if(t===0)return this;let r=this.measuredText.getWrappedText()[t-1];if(r===void 0)return this;let i=ye(r);if(n>i){let n=this.getOffset({line:t-1,column:i});return new e(this.measuredText,n,0)}let a=this.getOffset({line:t-1,column:n});return new e(this.measuredText,a,0)}down(){let{line:t,column:n}=this.getPosition();if(t>=this.measuredText.lineCount-1)return this;let r=this.measuredText.getWrappedText()[t+1];if(r===void 0)return this;let i=ye(r);if(n>i){let n=this.getOffset({line:t+1,column:i});return new e(this.measuredText,n,0)}let a=this.getOffset({line:t+1,column:n});return new e(this.measuredText,a,0)}startOfCurrentLine(){let{line:t}=this.getPosition();return new e(this.measuredText,this.getOffset({line:t,column:0}),0)}startOfLine(){let{line:t,column:n}=this.getPosition();return n===0&&t>0?new e(this.measuredText,this.getOffset({line:t-1,column:0}),0):this.startOfCurrentLine()}firstNonBlankInLine(){let{line:t}=this.getPosition(),n=(this.measuredText.getWrappedText()[t]||``).match(/^\s*\S/),r=n?.index?n.index+n[0].length-1:0,i=this.getOffset({line:t,column:r});return new e(this.measuredText,i,0)}endOfLine(){let{line:t}=this.getPosition(),n=this.measuredText.getLineLength(t),r=this.getOffset({line:t,column:n});return new e(this.measuredText,r,0)}findLogicalLineStart(e=this.offset){let t=this.text.lastIndexOf(`
|
|
1653
1653
|
`,e-1);return t===-1?0:t+1}findLogicalLineEnd(e=this.offset){let t=this.text.indexOf(`
|
|
1654
1654
|
`,e);return t===-1?this.text.length:t}getLogicalLineBounds(){return{start:this.findLogicalLineStart(),end:this.findLogicalLineEnd()}}createCursorWithColumn(t,n,r){let i=n-t,a=t+Math.min(r,i),o=this.measuredText.snapToGraphemeBoundary(a);return new e(this.measuredText,o,0)}endOfLogicalLine(){return new e(this.measuredText,this.findLogicalLineEnd(),0)}startOfLogicalLine(){return new e(this.measuredText,this.findLogicalLineStart(),0)}firstNonBlankInLogicalLine(){let{start:t,end:n}=this.getLogicalLineBounds(),r=t+(this.text.slice(t,n).match(/\S/)?.index??0);return new e(this.measuredText,r,0)}upLogicalLine(){let{start:t}=this.getLogicalLineBounds();if(t===0)return new e(this.measuredText,0,0);let n=this.offset-t,r=t-1,i=this.findLogicalLineStart(r);return this.createCursorWithColumn(i,r,n)}downLogicalLine(){let{start:t,end:n}=this.getLogicalLineBounds();if(n>=this.text.length)return new e(this.measuredText,this.text.length,0);let r=this.offset-t,i=n+1,a=this.findLogicalLineEnd(i);return this.createCursorWithColumn(i,a,r)}nextWord(){if(this.isAtEnd())return this;let t=this.measuredText.getWordBoundaries();for(let n of t)if(n.isWordLike&&n.start>this.offset)return new e(this.measuredText,n.start);return new e(this.measuredText,this.text.length)}endOfWord(){if(this.isAtEnd())return this;let t=this.measuredText.getWordBoundaries();for(let n of t)if(n.isWordLike){if(this.offset>=n.start&&this.offset<n.end-1)return new e(this.measuredText,n.end-1);if(this.offset===n.end-1){for(let n of t)if(n.isWordLike&&n.start>this.offset)return new e(this.measuredText,n.end-1);return this}}for(let n of t)if(n.isWordLike&&n.start>this.offset)return new e(this.measuredText,n.end-1);return this}prevWord(){if(this.isAtStart())return this;let t=this.measuredText.getWordBoundaries(),n=null;for(let r of t)if(r.isWordLike&&r.start<this.offset){if(this.offset>r.start&&this.offset<=r.end)return new e(this.measuredText,r.start);n=r.start}return n===null?new e(this.measuredText,0):new e(this.measuredText,n)}nextVimWord(){if(this.isAtEnd())return this;let t=this.offset,n=e=>this.measuredText.nextOffset(e),r=this.graphemeAt(t);if(!r)return this;if(EY(r))for(;t<this.text.length&&EY(this.graphemeAt(t));)t=n(t);else if(OY(r))for(;t<this.text.length&&OY(this.graphemeAt(t));)t=n(t);for(;t<this.text.length&&TY.test(this.graphemeAt(t));)t=n(t);return new e(this.measuredText,t)}endOfVimWord(){if(this.isAtEnd())return this;let t=this.text,n=this.offset,r=e=>this.measuredText.nextOffset(e);if(this.graphemeAt(n)===``)return this;for(n=r(n);n<t.length&&TY.test(this.graphemeAt(n));)n=r(n);if(n>=t.length)return new e(this.measuredText,t.length);let i=this.graphemeAt(n);if(EY(i))for(;n<t.length;){let e=r(n);if(e>=t.length||!EY(this.graphemeAt(e)))break;n=e}else if(OY(i))for(;n<t.length;){let e=r(n);if(e>=t.length||!OY(this.graphemeAt(e)))break;n=e}return new e(this.measuredText,n)}prevVimWord(){if(this.isAtStart())return this;let t=this.offset,n=e=>this.measuredText.prevOffset(e);for(t=n(t);t>0&&TY.test(this.graphemeAt(t));)t=n(t);if(t===0&&TY.test(this.graphemeAt(0)))return new e(this.measuredText,0);let r=this.graphemeAt(t);if(EY(r))for(;t>0;){let e=n(t);if(!EY(this.graphemeAt(e)))break;t=e}else if(OY(r))for(;t>0;){let e=n(t);if(!OY(this.graphemeAt(e)))break;t=e}return new e(this.measuredText,t)}nextWORD(){let e=this;for(;!e.isOverWhitespace()&&!e.isAtEnd();)e=e.right();for(;e.isOverWhitespace()&&!e.isAtEnd();)e=e.right();return e}endOfWORD(){if(this.isAtEnd())return this;let e=this;if(!e.isOverWhitespace()&&(e.right().isOverWhitespace()||e.right().isAtEnd()))return e=e.right(),e.endOfWORD();for(e.isOverWhitespace()&&(e=e.nextWORD());!e.right().isOverWhitespace()&&!e.isAtEnd();)e=e.right();return e}prevWORD(){let e=this;for(e.left().isOverWhitespace()&&(e=e.left());e.isOverWhitespace()&&!e.isAtStart();)e=e.left();if(!e.isOverWhitespace())for(;!e.left().isOverWhitespace()&&!e.isAtStart();)e=e.left();return e}modifyText(t,n=``){let r=this.offset,i=t.offset,a=this.text.slice(0,r)+n+this.text.slice(i);return e.fromText(a,this.columns,r+n.normalize(`NFC`).length)}insert(e){return this.modifyText(this,e)}del(){return this.isAtEnd()?this:this.modifyText(this.right())}backspace(){return this.isAtStart()?this:this.left().modifyText(this)}deleteToLineStart(){if(this.offset>0&&this.text[this.offset-1]===`
|
|
@@ -2142,7 +2142,7 @@ Use this when:
|
|
|
2142
2142
|
|
|
2143
2143
|
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.`})),zct,Bct,Vct=n((()=>{_t(),Zs(),vt(),Rct(),zct=gt(()=>dt({description:L().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:R().optional().describe(`Maximum number of results to return (default: 5)`)})),Bct=Ns({name:jQ,searchHint:`find search discover skills commands tools capabilities`,maxResultSizeChars:1e4,strict:!0,get inputSchema(){return zct()},async description(){return Ict},async prompt(){return Lct},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 Ds(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 Ds(t,`Found ${e.count} relevant skill(s):\n\n${n.join(`
|
|
2144
2144
|
|
|
2145
|
-
`)}`)},async call(e,t){let{getSkillIndex:n,searchSkills:r}=await import(`./localSearch-
|
|
2145
|
+
`)}`)},async call(e,t){let{getSkillIndex:n,searchSkills:r}=await import(`./localSearch-D3UrYUre.js`),{getCwd:i}=await import(`./cwd-DpqwaYHw.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 Hct(e,t,n){return{toolUseContext:e,canUseTool:t,...n===void 0?{}:{parentMessage:n},agentId:e.agentId}}function Uct(e){return moe(e)}function Wct(e){return Eoe(e)}var MQ=n((()=>{js()}));function Gct(e,t=Yct){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&&Jct.has(e.status)&&t(Kct(e)),n.set(e.runId,e.status)}});return()=>{r(),n.clear()}}function Kct(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`<${Yi}>
|
|
2146
2146
|
<${la}>${e.runId}</${la}>
|
|
2147
2147
|
<${na}>${qct}</${na}>
|
|
2148
2148
|
<${Zi}>${e.status}</${Zi}>
|
|
@@ -2488,7 +2488,7 @@ ${t?`${t}\n`:``}\
|
|
|
2488
2488
|
`,bft=new Set([`select-string`,`get-childitem`,`findstr`,`where.exe`]),xft=new Set([`get-content`,`get-item`,`test-path`,`resolve-path`,`get-process`,`get-service`,`get-childitem`,`get-location`,`get-filehash`,`get-acl`,`format-hex`]),Sft=new Set([`write-output`,`write-host`]),K$=2e3,Cft=1e3,wft=15e3,Tft=[`start-sleep`,`sleep`],q$=`Enterprise policy requires sandboxing, but sandboxing is not available on native Windows. Shell command execution is blocked on this platform by policy.`,J$=m(process.env.CLAUDE_CODE_DISABLE_BACKGROUND_TASKS),Y$=gt(()=>dt({command:L().describe(`The PowerShell command to execute`),timeout:yy(R().optional()).describe(`Optional timeout in milliseconds (max ${z$()})`),description:L().optional().describe(`Clear, concise description of what this command does in active voice.`),run_in_background:eV(pt().optional()).describe(`Set to true to run this command in the background. Use Read to read the output later.`),dangerouslyDisableSandbox:eV(pt().optional()).describe(`Set this to true to dangerously override sandbox mode and run commands without sandboxing.`)})),Eft=gt(()=>J$?Y$().omit({run_in_background:!0}):Y$()),Dft=gt(()=>B({stdout:L().describe(`The standard output of the command`),stderr:L().describe(`The standard error output of the command`),interrupted:pt().describe(`Whether the command was interrupted`),returnCodeInterpretation:L().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:L().optional().describe(`Path to persisted full output when too large for inline`),persistedOutputSize:R().optional().describe(`Total output size in bytes when persisted`),backgroundTaskId:L().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`)})),Oft=[`npm`,`yarn`,`pnpm`,`node`,`python`,`python3`,`go`,`cargo`,`make`,`docker`,`terraform`,`webpack`,`vite`,`jest`,`pytest`,`curl`,`Invoke-WebRequest`,`build`,`test`,`serve`,`watch`,`dev`],X$=Ns({name:Xs,searchHint:`execute Windows PowerShell commands`,maxResultSizeChars:3e4,strict:!0,async description({description:e}){return e||`Run PowerShell command`},async prompt(){return sft()},isConcurrencySafe(e){return this.isReadOnly?.(e)??!1},isSearchOrReadCommand(e){return e?.command?hft(e.command):{isSearch:!1,isRead:!1}},isReadOnly(e){return!Dut(e.command)&&Out(e.command)},toAutoClassifierInput(e){return e.command},get inputSchema(){return Eft()},get outputSchema(){return Dft()},userFacingName(){return`PowerShell`},getToolUseSummary(e){if(!e?.command)return null;let{command:t,description:n}=e;return n||Ia(t,50)},getActivityDescription(e){return e?.command?`Running ${e.description??Ia(e.command,50)}`:`Running command`},isEnabled(){return!0},async validateInput(e){return _ft()?{result:!1,message:q$,errorCode:11}:{result:!0}},async checkPermissions(e,t){return await eft(e,t)},renderToolUseMessage:lft,renderToolUseProgressMessage:uft,renderToolUseQueuedMessage:dft,renderToolResultMessage:fft,renderToolUseErrorMessage:pft,mapToolResultToToolResultBlockParam({interrupted:e,stdout:t,stderr:n,isImage:r,persistedOutputPath:i,persistedOutputSize:a,backgroundTaskId:o,backgroundedByUser:s,assistantAutoBackgrounded:c},l){if(r){let e=RSe(t,l);if(e)return e}let u=t;if(i){let e=ry(t?t.replace(/^(\s*\n)+/,``).trimEnd():``,oy);u=ty({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+=G$),d+=`<error>Command was aborted before completion</error>`);let f=``;if(o){let e=B8(o);f=c?`Command exceeded the assistant-mode blocking budget (${wft/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(`
|
|
2489
2489
|
`),is_error:e}},async call(e,t,n,r,i){if(_ft())throw Error(q$);let{abortController:a,setAppState:o,setToolJSX:s}=t,c=!t.agentId,l=0;try{let n=vft({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||Gqe(e.command,u.code,u.stdout);let d=u.interrupted&&a.signal.reason===`interrupt`,f=``;if(c&&VSe(t.getAppState().toolPermissionContext)&&(f=Gv(``)),u.backgroundTaskId){let t=zB(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(`
|
|
2490
2490
|
`),interrupted:!1,backgroundTaskId:u.backgroundTaskId,backgroundedByUser:u.backgroundedByUser,assistantAutoBackgrounded:u.assistantAutoBackgrounded}}}let p=new Za,m=(u.stdout||``).trimEnd();p.append(m+G$);let h=zlt(e.command,u.code,m,u.stderr||``),g=ISe(p.toString()),_=zB(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 wn(g,u.stderr||``,u.code,u.interrupted);let v=64*1024*1024,y,b;if(u.outputFilePath&&u.outputTaskId)try{let e=await mu(u.outputFilePath);b=e.size,await $v();let t=Qv(u.outputTaskId,!1);e.size>v&&await Mle(u.outputFilePath,v);try{await ou(u.outputFilePath,t)}catch{await au(u.outputFilePath,t)}y=t}catch{}let x=Wv(g),S=g;if(x){let e=await zSe(g,u.outputFilePath,b);e?S=e:x=!1}let C=[u.stderr||``,f].filter(Boolean).join(`
|
|
2491
|
-
`);return J(`tengu_powershell_tool_command_executed`,{command_type:W$(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 tb(e.stdout)||tb(e.stderr)}})}));function kft(e){let t=e.toLowerCase();return Mft.includes(t)?t:null}function Aft(){let e=Q$(),t=e.map(e=>e.isEnabled());return e.filter((e,n)=>t[n]).map(e=>e.name)}function Q$(){return[dJ,LZ,xW,...Sv()?[]:[dU,cU],VZ,Sb,xq,ZH,Tq,hU,jZ,JZ,xJ,cQ,oct,xst,...Db()?[pct,bct,Dct,Pct]:[],...m(process.env.ENABLE_LSP_TOOL)?[nQ]:[],...Ice()?[Fot,Kot]:[],...t1?[t1]:[],jft,jit,qit,...n1()?[n1()]:[],Bct,QC,CE,...lz()?[Cz]:[],fot]}function $$(e,t){return e.filter(e=>!C9(t,e))}function e1(e,t){let n=r1(e),r=$$(t,e),i=(e,t)=>e.name.localeCompare(t.name);return Qp([...n].sort(i).concat(r.sort(i)),`name`)}var t1,jft,n1,Mft,r1,i1=n((()=>{Zs(),fJ(),I7e(),SW(),Sq(),wb(),QH(),fU(),Eq(),wit(),Mit(),Jit(),tat(),gU(),HZ(),dat(),lU(),vat(),rot(),$C(),wE(),wz(),pot(),Dot(),Iot(),qot(),Sst(),sct(),mct(),xct(),Oct(),Fct(),$p(),_z(),Lb(),Es(),Os(),Vct(),Mlt(),A9(),Cv(),h(),Qs(),Lce(),Dq(),t1=process.env.CLAUDE_CODE_VERIFY_PLAN===`true`?(Ilt(),e(Nlt)).VerifyPlanExecutionTool:null,jft=jlt(),n1=()=>Roe()?(Z$(),e(U$)).PowerShellTool:null,Mft=[`default`],r1=e=>{if(m(process.env.CLAUDE_CODE_SIMPLE))return $$([xW,Sb,xq],e);let t=new Set([QC.name,CE.name,Vs]),n=$$(Q$().filter(e=>!t.has(e.name)),e);l8e()&&n.some(e=>Ys(e,`REPL`))&&(n=n.filter(e=>!u8e.has(e.name)));let r=n.map(e=>e.isEnabled());return n.filter((e,t)=>r[t])}})),Nft,a1,Pft=n((()=>{b(),Nft=Symbol.asyncIterator,a1=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}[Nft](){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 Fft(e){switch(e){case`allow`:return`allowed`;case`deny`:return`denied`;default:return`asked for confirmation for`}}var Ift=n((()=>{}));async function*Lft(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 sEt(t.name,n,i,u,e,c,e.abortController.signal))try{if(a.message?.type===`attachment`&&a.message.attachment.type===`hook_cancelled`){J(`tengu_post_tool_hooks_cancelled`,{toolName:Jc(t.name),queryChainId:e.queryTracking?.chainId,queryDepth:e.queryTracking?.depth}),yield{message:j0({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:j0({type:`hook_blocking_error`,hookName:`PostToolUse:${t.name}`,toolUseID:n,hookEvent:`PostToolUse`,blockingError:a.blockingError})}),a.preventContinuation){yield{message:j0({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:j0({type:`hook_additional_context`,content:a.additionalContexts,hookName:`PostToolUse:${t.name}`,toolUseID:n,hookEvent:`PostToolUse`})}),a.updatedMCPToolOutput&&pT(t)&&(u=a.updatedMCPToolOutput,yield{updatedMCPToolOutput:u})}catch(i){let a=Date.now()-l;J(`tengu_post_tool_hook_error`,{messageID:r,toolName:Jc(t.name),isMcp:t.isMcp??!1,duration:a,queryChainId:e.queryTracking?.chainId,queryDepth:e.queryTracking?.depth,...s?{mcpServerType:s}:{},...o?{requestId:o}:{}}),yield{message:j0({type:`hook_error_during_execution`,content:rQ(i),hookName:`PostToolUse:${t.name}`,toolUseID:n,hookEvent:`PostToolUse`})}}}catch(e){q(e)}}async function*Rft(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 cEt(t.name,n,i,a,e,o,l,e.abortController.signal))try{if(d.message?.type===`attachment`&&d.message.attachment.type===`hook_cancelled`){J(`tengu_post_tool_failure_hooks_cancelled`,{toolName:Jc(t.name),queryChainId:e.queryTracking?.chainId,queryDepth:e.queryTracking?.depth}),yield{message:j0({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:j0({type:`hook_blocking_error`,hookName:`PostToolUseFailure:${t.name}`,toolUseID:n,hookEvent:`PostToolUseFailure`,blockingError:d.blockingError})}),d.additionalContexts&&d.additionalContexts.length>0&&(yield{message:j0({type:`hook_additional_context`,content:d.additionalContexts,hookName:`PostToolUseFailure:${t.name}`,toolUseID:n,hookEvent:`PostToolUseFailure`})})}catch(i){let a=Date.now()-u;J(`tengu_post_tool_failure_hook_error`,{messageID:r,toolName:Jc(t.name),isMcp:t.isMcp??!1,duration:a,queryChainId:e.queryTracking?.chainId,queryDepth:e.queryTracking?.depth,...c?{mcpServerType:c}:{},...s?{requestId:s}:{}}),yield{message:j0({type:`hook_error_during_execution`,content:rQ(i),hookName:`PostToolUseFailure:${t.name}`,toolUseID:n,hookEvent:`PostToolUseFailure`})}}}catch(e){q(e)}}async function zft(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 U(`Hook approved tool use for ${t.name}, but canUseTool is required`),{decision:await i(t,l,r,a,o),input:l};let d=await ikt(t,l,r);return d===null?(U(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`?(U(`Hook approved tool use for ${t.name}, but deny rule overrides: ${d.message}`),{decision:d,input:l}):(U(`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 U(`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*Bft(e,t,n,r,i,a,o,s){let c=Date.now();try{let s=e.getAppState();for await(let l of oEt(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=tEt(`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){U(`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} ${Fft(l.permissionBehavior)} this tool`,decisionReason:e}}:yield{type:`hookPermissionResult`,hookPermissionResult:{behavior:l.permissionBehavior,message:l.hookPermissionDecisionReason||`Hook PreToolUse:${t.name} ${Fft(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:j0({type:`hook_additional_context`,content:l.additionalContexts,hookName:`PreToolUse:${t.name}`,toolUseID:r,hookEvent:`PreToolUse`})}}),e.abortController.signal.aborted){J(`tengu_pre_tool_hooks_cancelled`,{toolName:Jc(t.name),queryChainId:e.queryTracking?.chainId,queryDepth:e.queryTracking?.depth}),yield{type:`message`,message:{message:j0({type:`hook_cancelled`,hookName:`PreToolUse:${t.name}`,toolUseID:r,hookEvent:`PreToolUse`})}},yield{type:`stop`};return}}catch(n){q(n);let s=Date.now()-c;J(`tengu_pre_tool_hook_error`,{messageID:i,toolName:Jc(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:j0({type:`hook_error_during_execution`,content:rQ(n),hookName:`PreToolUse:${t.name}`,toolUseID:r,hookEvent:`PreToolUse`})}},yield{type:`stop`}}}catch(e){q(e),yield{type:`stop`};return}}var Vft=n((()=>{Na(),Uc(),H0(),W(),g7(),oa(),Ift(),A9(),iQ(),_T()}));function Hft(){return s1||(s1=import(`./toolEventObserver-CJhg_p3P.js`).catch(e=>{throw s1=void 0,e})),s1}function Uft(e){if(e instanceof Gn)return e.telemetryMessage.slice(0,200);if(e instanceof Error){let t=Dn(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 Wft(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 Gft(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 Wft(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 Kft(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 qft(e,t){if(!e.startsWith(`mcp__`))return;let n=Br(e);if(n)return t.find(e=>di(e.name)===n.serverName)}function Jft(e,t){let n=qft(e,t);if(n?.type===`connected`)return n.config.type??`stdio`}function Yft(e,t){let n=qft(e,t);if(n?.type===`connected`)return gT(n.config)}async function*o1(e,t,n,r){let i=e.name,a=Ss(r.options.tools,i);if(!a){let e=Ss(Q$(),i);e?.aliases?.includes(i)&&(a=e)}let o=t.message.id,s=t.requestId,c=Jft(i,r.options.mcpClients),l=Yft(i,r.options.mcpClients);if(!a){let n=Jc(i);U(`Unknown tool ${i}: ${e.id}`),J(`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},...Kc(i,c,l)}),yield{message:$({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){J(`tengu_tool_use_cancelled`,{toolName:Jc(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},...Kc(a.name,c,l)});let n=hbt(e.id);n.content=T4(a3),yield{message:$({content:[n],toolUseResult:a3,sourceToolAssistantUUID:t.uuid})};return}for await(let i of Xft(a,e.id,u,r,n,t,o,s,c,l))yield i}catch(n){q(n);let r=n instanceof Error?n.message:String(n),i=`Error calling tool${a?` (${a.name})`:``}: ${r}`;yield{message:$({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 Xft(e,t,n,r,i,a,o,s,c,l){let u=new a1;return Qft(e,t,n,r,i,a,o,s,c,l,n=>{J(`tengu_tool_use_progress`,{messageID:o,toolName:Jc(e.name),isMcp:e.isMcp??!1,queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Kc(e.name,c,l)}),u.enqueue({message:mbt({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 Zft(e,t,n){if(!lz()||!uz(n)||!Fs(e)||pz(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: ${Ks}("select:${e.name}")\n2. Then call ${r} tool\n\nExample:\n${Ks}("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: ${Ks}("select:TaskGet,TaskCreate,TaskUpdate,TaskList")\n\nSee docs/openai-task-tools.md for detailed guide.`}async function Qft(e,t,n,r,i,a,o,s,c,l,u){let d=e.inputSchema.safeParse(n);if(!d.success){let n=oot(e.name,d.error),i=Zft(e,r.messages,r.options.tools);return i&&(J(`tengu_deferred_tool_schema_not_sent`,{toolName:Jc(e.name),isMcp:e.isMcp??!1}),n+=i),U(`${e.name} tool input error: ${n.slice(0,200)}`),J(`tengu_tool_use_error`,{error:`InputValidationError`,errorDetails:n.slice(0,2e3),messageID:o,toolName:Jc(e.name),isMcp:e.isMcp??!1,queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Kc(e.name,c,l)}),[{message:$({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 U(`${e.name} tool validation error: ${f.message?.slice(0,200)}`),J(`tengu_tool_use_error`,{messageID:o,toolName:Jc(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},...Kc(e.name,c,l)}),[{message:$({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();p$e(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 Bft(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 Jt()?.observe(`pre_tool_hook_duration_ms`,Date.now()-x),p.push({message:$({content:[hbt(t)],toolUseResult:`Error: ${v}`,sourceToolAssistantUUID:a.uuid})}),p}let S=Date.now()-x;Jt()?.observe(`pre_tool_hook_duration_ms`,S),S>=c1&&U(`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)),gce(e.name,C,nl()?V(m):void 0),yce();let w=r.getAppState().toolPermissionContext.mode,T=Date.now(),E=await zft(y,e,m,r,i,a,t),D=E.decision;m=E.input;let O=Date.now()-T;if(O>=c1&&w===`auto`&&U(`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=Gft(D.decisionReason,D.behavior);rl(`tool_decision`,{decision:t,source:n,tool_name:Jc(e.name)}),j0e(e.name)&&M0e(e,m,t,n).then(e=>lne()?.add(1,e))}if(D.decisionReason?.type===`hook`&&D.decisionReason.hookName===`PermissionRequest`&&D.behavior!==`ask`&&p.push({message:j0({type:`hook_permission_decision`,decision:D.behavior,toolUseID:t,hookEvent:`PermissionRequest`})}),D.behavior!==`allow`){U(`${e.name} tool permission denied`);let n=r.toolDecisions?.get(t);il(`reject`,n?.source||`unknown`),cl(),J(`tengu_tool_use_can_use_tool_rejected`,{messageID:o,toolName:Jc(e.name),queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Kc(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=hr(d,e=>e.type===`image`);if(e>0){let t=Kft(r.messages);f=Array.from({length:e},(e,n)=>t+n)}}return p.push({message:$({content:u,imagePasteIds:f,toolUseResult:`Error: ${i}`,sourceToolAssistantUUID:a.uuid})}),p}J(`tengu_tool_use_can_use_tool_allowed`,{messageID:o,toolName:Jc(e.name),queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Kc(e.name,c,l)}),D.updatedInput!==void 0&&(m=D.updatedInput);let k=ace(m),A={};if(Yc()){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=ice(e.name);t&&(A.mcp_server_name=t.serverName,A.mcp_tool_name=t.mcpToolName);let n=oce(e.name,m);n&&(A.skill_name=n)}let ee=r.toolDecisions?.get(t);il(ee?.decision||`unknown`,ee?.source||`unknown`),_ce();let te=Date.now();dc(`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=Rce()?await(async()=>{let{runToolCallWithSkillLearningHooks:t}=await Hft();return t(e.name,h,{sessionId:r.sessionId},n)})():await n(),f=Date.now()-te;if(Yte(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&&bce(`tool.output`,t)}typeof d==`object`&&`structured_output`in d&&p.push({message:j0({type:`structured_output`,data:d.structured_output})}),sl({success:!0}),cl(d.data&&typeof d.data==`object`?V(d.data):String(d.data??``));let g=e.mapToolResultToToolResultBlockParam(d.data,t),y=g.content,b=y?typeof y==`string`?y.length:V(y).length:0,x;if(m&&typeof m==`object`){if((e.name===`Read`||e.name===`Edit`||e.name===`Write`)&&`file_path`in m)x=Bc(String(m.file_path));else if(e.name===`NotebookEdit`&&`notebook_path`in m)x=Bc(String(m.notebook_path));else if(e.name===`Bash`&&`command`in m){let e=m;x=rce(e.command,e._simulatedSedEdit?.filePath)}}if(J(`tengu_tool_use_success`,{messageID:o,toolName:Jc(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},...Kc(e.name,c,l)}),Yc()&&(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=Bqe(String(d.data.stdout));e&&(A.git_commit_id=e)}let C=pT(e)?hT(e.name):null;rl(`tool_result`,{tool_name:Jc(e.name),success:`true`,duration_ms:String(f),...Object.keys(A).length>0&&{tool_parameters:V(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 aCe(i,e.name,e.maxResultSizeChars):await ny(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=hr(s,e=>e.type===`image`);if(e>0){let t=Kft(r.messages);c=Array.from({length:e},(e,n)=>t+n)}}p.push({message:$({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})}pT(e)||await ne(w,g);let re=[],ie=Date.now();for await(let n of Lft(r,e,t,a.message.id,m,w,s,c,l))if(`updatedMCPToolOutput`in n)pT(e)&&(w=n.updatedMCPToolOutput);else if(pT(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>=c1&&U(`Slow PostToolUse hooks: ${ae}ms for ${e.name} (${re.length} hooks)`,{level:`info`}),pT(e)&&await ne(w),d.newMessages&&d.newMessages.length>0)for(let e of d.newMessages)p.push({message:e});_&&p.push({message:j0({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(Yte(i),sl({success:!1,error:H(n)}),cl(),n instanceof Wj&&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 En)){let a=H(n);U(`${e.name} tool error (${i}ms): ${a.slice(0,200)}`),n instanceof wn||q(n),J(`tengu_tool_use_error`,{messageID:o,toolName:Jc(e.name),error:Uft(n),isMcp:e.isMcp??!1,queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Kc(e.name,c,l)});let u=pT(e)?hT(e.name):null;rl(`tool_result`,{tool_name:Jc(e.name),use_id:t,success:`false`,duration_ms:String(i),error:H(n),...Object.keys(A).length>0&&{tool_parameters:V(A)},...k&&{tool_input:k},...ee&&{decision_source:ee.source,decision_type:ee.decision},...u&&{mcp_server_scope:u}})}let u=rQ(n),d=n instanceof En,f=[];for await(let n of Rft(r,e,t,o,m,u,d,s,c,l))f.push(n);return[{message:$({content:[{type:`tool_result`,content:u,is_error:!0,tool_use_id:t}],toolUseResult:`Error: ${u}`,mcpMeta:r.agentId?void 0:n instanceof Kj?n.mcpMeta:void 0,sourceToolAssistantUUID:a.uuid})},...f]}finally{uc(`tool_exec`),ee&&r.toolDecisions?.delete(t)}}var s1,c1,$ft=n((()=>{Na(),Uc(),Gt(),R0e(),Zs(),HW(),Ts(),Rs(),Bs(),Cs(),zs(),gs(),xH(),Ws(),i1(),Tr(),H0(),W(),Mn(),g7(),oa(),p3(),hc(),Zn(),Pft(),ll(),al(),iQ(),sy(),_z(),cM(),Zr(),si(),_T(),Vft(),zce(),c1=2e3}));function ept(e,t){e.setInProgressToolUseIDs(e=>{let n=new Set(e);return n.delete(t),n})}var l1,tpt=n((()=>{p3(),Zs(),Ts(),OE(),$ft(),b(),l1=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=EE(n.abortController)}discard(){this.discarded=!0,this.siblingAbortController.abort(`streaming_fallback`),this.tools.length=0,this.progressAvailableResolve=void 0}addTool(e,t){let n=Ss(this.toolDefinitions,e.name);if(!n){this.tools.push({id:e.id,block:e,assistantMessage:t,status:`completed`,isConcurrencySafe:!0,pendingProgress:[],results:[$({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 $({content:[{type:`tool_result`,content:T4(o3),is_error:!0,tool_use_id:e}],toolUseResult:`User rejected tool use`,sourceToolAssistantUUID:n.uuid});if(t===`streaming_fallback`)return $({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 $({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=Ss(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=EE(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};ept(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 npt(){d1&&(Va().clearMarks(),f1.clear(),m1=null,p1++,u1(`query_user_input_received`))}function u1(e){if(!d1)return;let t=Va();if(t.mark(e),f1.set(e,process.memoryUsage()),e===`query_first_chunk_received`&&m1===null){let e=t.getEntriesByType(`mark`);e.length>0&&(m1=e[e.length-1]?.startTime??0)}}function rpt(){d1&&u1(`query_profile_end`)}function ipt(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 apt(){if(!d1)return`Query profiling not enabled (set CLAUDE_CODE_PROFILE_QUERY=1)`;let e=Va().getEntriesByType(`mark`);if(e.length===0)return`No query profiling checkpoints recorded`;let t=[];t.push(`=`.repeat(80)),t.push(`QUERY PROFILING REPORT - Query #${p1}`),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($ie(e,s,o.name,f1.get(o.name),10,9,ipt(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: ${Fa(a)}ms`),t.push(` - Pre-request overhead: ${Fa(e)}ms (${r}%)`),t.push(` - Network latency: ${Fa(n)}ms (${o}%)`)}else t.push(`Total time: ${Fa(s)}ms`);return t.push(opt(e,n)),t.push(`=`.repeat(80)),t.join(`
|
|
2491
|
+
`);return J(`tengu_powershell_tool_command_executed`,{command_type:W$(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 tb(e.stdout)||tb(e.stderr)}})}));function kft(e){let t=e.toLowerCase();return Mft.includes(t)?t:null}function Aft(){let e=Q$(),t=e.map(e=>e.isEnabled());return e.filter((e,n)=>t[n]).map(e=>e.name)}function Q$(){return[dJ,LZ,xW,...Sv()?[]:[dU,cU],VZ,Sb,xq,ZH,Tq,hU,jZ,JZ,xJ,cQ,oct,xst,...Db()?[pct,bct,Dct,Pct]:[],...m(process.env.ENABLE_LSP_TOOL)?[nQ]:[],...Ice()?[Fot,Kot]:[],...t1?[t1]:[],jft,jit,qit,...n1()?[n1()]:[],Bct,QC,CE,...lz()?[Cz]:[],fot]}function $$(e,t){return e.filter(e=>!C9(t,e))}function e1(e,t){let n=r1(e),r=$$(t,e),i=(e,t)=>e.name.localeCompare(t.name);return Qp([...n].sort(i).concat(r.sort(i)),`name`)}var t1,jft,n1,Mft,r1,i1=n((()=>{Zs(),fJ(),I7e(),SW(),Sq(),wb(),QH(),fU(),Eq(),wit(),Mit(),Jit(),tat(),gU(),HZ(),dat(),lU(),vat(),rot(),$C(),wE(),wz(),pot(),Dot(),Iot(),qot(),Sst(),sct(),mct(),xct(),Oct(),Fct(),$p(),_z(),Lb(),Es(),Os(),Vct(),Mlt(),A9(),Cv(),h(),Qs(),Lce(),Dq(),t1=process.env.CLAUDE_CODE_VERIFY_PLAN===`true`?(Ilt(),e(Nlt)).VerifyPlanExecutionTool:null,jft=jlt(),n1=()=>Roe()?(Z$(),e(U$)).PowerShellTool:null,Mft=[`default`],r1=e=>{if(m(process.env.CLAUDE_CODE_SIMPLE))return $$([xW,Sb,xq],e);let t=new Set([QC.name,CE.name,Vs]),n=$$(Q$().filter(e=>!t.has(e.name)),e);l8e()&&n.some(e=>Ys(e,`REPL`))&&(n=n.filter(e=>!u8e.has(e.name)));let r=n.map(e=>e.isEnabled());return n.filter((e,t)=>r[t])}})),Nft,a1,Pft=n((()=>{b(),Nft=Symbol.asyncIterator,a1=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}[Nft](){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 Fft(e){switch(e){case`allow`:return`allowed`;case`deny`:return`denied`;default:return`asked for confirmation for`}}var Ift=n((()=>{}));async function*Lft(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 sEt(t.name,n,i,u,e,c,e.abortController.signal))try{if(a.message?.type===`attachment`&&a.message.attachment.type===`hook_cancelled`){J(`tengu_post_tool_hooks_cancelled`,{toolName:Jc(t.name),queryChainId:e.queryTracking?.chainId,queryDepth:e.queryTracking?.depth}),yield{message:j0({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:j0({type:`hook_blocking_error`,hookName:`PostToolUse:${t.name}`,toolUseID:n,hookEvent:`PostToolUse`,blockingError:a.blockingError})}),a.preventContinuation){yield{message:j0({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:j0({type:`hook_additional_context`,content:a.additionalContexts,hookName:`PostToolUse:${t.name}`,toolUseID:n,hookEvent:`PostToolUse`})}),a.updatedMCPToolOutput&&pT(t)&&(u=a.updatedMCPToolOutput,yield{updatedMCPToolOutput:u})}catch(i){let a=Date.now()-l;J(`tengu_post_tool_hook_error`,{messageID:r,toolName:Jc(t.name),isMcp:t.isMcp??!1,duration:a,queryChainId:e.queryTracking?.chainId,queryDepth:e.queryTracking?.depth,...s?{mcpServerType:s}:{},...o?{requestId:o}:{}}),yield{message:j0({type:`hook_error_during_execution`,content:rQ(i),hookName:`PostToolUse:${t.name}`,toolUseID:n,hookEvent:`PostToolUse`})}}}catch(e){q(e)}}async function*Rft(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 cEt(t.name,n,i,a,e,o,l,e.abortController.signal))try{if(d.message?.type===`attachment`&&d.message.attachment.type===`hook_cancelled`){J(`tengu_post_tool_failure_hooks_cancelled`,{toolName:Jc(t.name),queryChainId:e.queryTracking?.chainId,queryDepth:e.queryTracking?.depth}),yield{message:j0({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:j0({type:`hook_blocking_error`,hookName:`PostToolUseFailure:${t.name}`,toolUseID:n,hookEvent:`PostToolUseFailure`,blockingError:d.blockingError})}),d.additionalContexts&&d.additionalContexts.length>0&&(yield{message:j0({type:`hook_additional_context`,content:d.additionalContexts,hookName:`PostToolUseFailure:${t.name}`,toolUseID:n,hookEvent:`PostToolUseFailure`})})}catch(i){let a=Date.now()-u;J(`tengu_post_tool_failure_hook_error`,{messageID:r,toolName:Jc(t.name),isMcp:t.isMcp??!1,duration:a,queryChainId:e.queryTracking?.chainId,queryDepth:e.queryTracking?.depth,...c?{mcpServerType:c}:{},...s?{requestId:s}:{}}),yield{message:j0({type:`hook_error_during_execution`,content:rQ(i),hookName:`PostToolUseFailure:${t.name}`,toolUseID:n,hookEvent:`PostToolUseFailure`})}}}catch(e){q(e)}}async function zft(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 U(`Hook approved tool use for ${t.name}, but canUseTool is required`),{decision:await i(t,l,r,a,o),input:l};let d=await ikt(t,l,r);return d===null?(U(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`?(U(`Hook approved tool use for ${t.name}, but deny rule overrides: ${d.message}`),{decision:d,input:l}):(U(`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 U(`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*Bft(e,t,n,r,i,a,o,s){let c=Date.now();try{let s=e.getAppState();for await(let l of oEt(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=tEt(`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){U(`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} ${Fft(l.permissionBehavior)} this tool`,decisionReason:e}}:yield{type:`hookPermissionResult`,hookPermissionResult:{behavior:l.permissionBehavior,message:l.hookPermissionDecisionReason||`Hook PreToolUse:${t.name} ${Fft(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:j0({type:`hook_additional_context`,content:l.additionalContexts,hookName:`PreToolUse:${t.name}`,toolUseID:r,hookEvent:`PreToolUse`})}}),e.abortController.signal.aborted){J(`tengu_pre_tool_hooks_cancelled`,{toolName:Jc(t.name),queryChainId:e.queryTracking?.chainId,queryDepth:e.queryTracking?.depth}),yield{type:`message`,message:{message:j0({type:`hook_cancelled`,hookName:`PreToolUse:${t.name}`,toolUseID:r,hookEvent:`PreToolUse`})}},yield{type:`stop`};return}}catch(n){q(n);let s=Date.now()-c;J(`tengu_pre_tool_hook_error`,{messageID:i,toolName:Jc(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:j0({type:`hook_error_during_execution`,content:rQ(n),hookName:`PreToolUse:${t.name}`,toolUseID:r,hookEvent:`PreToolUse`})}},yield{type:`stop`}}}catch(e){q(e),yield{type:`stop`};return}}var Vft=n((()=>{Na(),Uc(),H0(),W(),g7(),oa(),Ift(),A9(),iQ(),_T()}));function Hft(){return s1||(s1=import(`./toolEventObserver-BZn8ZJB5.js`).catch(e=>{throw s1=void 0,e})),s1}function Uft(e){if(e instanceof Gn)return e.telemetryMessage.slice(0,200);if(e instanceof Error){let t=Dn(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 Wft(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 Gft(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 Wft(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 Kft(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 qft(e,t){if(!e.startsWith(`mcp__`))return;let n=Br(e);if(n)return t.find(e=>di(e.name)===n.serverName)}function Jft(e,t){let n=qft(e,t);if(n?.type===`connected`)return n.config.type??`stdio`}function Yft(e,t){let n=qft(e,t);if(n?.type===`connected`)return gT(n.config)}async function*o1(e,t,n,r){let i=e.name,a=Ss(r.options.tools,i);if(!a){let e=Ss(Q$(),i);e?.aliases?.includes(i)&&(a=e)}let o=t.message.id,s=t.requestId,c=Jft(i,r.options.mcpClients),l=Yft(i,r.options.mcpClients);if(!a){let n=Jc(i);U(`Unknown tool ${i}: ${e.id}`),J(`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},...Kc(i,c,l)}),yield{message:$({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){J(`tengu_tool_use_cancelled`,{toolName:Jc(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},...Kc(a.name,c,l)});let n=hbt(e.id);n.content=T4(a3),yield{message:$({content:[n],toolUseResult:a3,sourceToolAssistantUUID:t.uuid})};return}for await(let i of Xft(a,e.id,u,r,n,t,o,s,c,l))yield i}catch(n){q(n);let r=n instanceof Error?n.message:String(n),i=`Error calling tool${a?` (${a.name})`:``}: ${r}`;yield{message:$({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 Xft(e,t,n,r,i,a,o,s,c,l){let u=new a1;return Qft(e,t,n,r,i,a,o,s,c,l,n=>{J(`tengu_tool_use_progress`,{messageID:o,toolName:Jc(e.name),isMcp:e.isMcp??!1,queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Kc(e.name,c,l)}),u.enqueue({message:mbt({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 Zft(e,t,n){if(!lz()||!uz(n)||!Fs(e)||pz(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: ${Ks}("select:${e.name}")\n2. Then call ${r} tool\n\nExample:\n${Ks}("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: ${Ks}("select:TaskGet,TaskCreate,TaskUpdate,TaskList")\n\nSee docs/openai-task-tools.md for detailed guide.`}async function Qft(e,t,n,r,i,a,o,s,c,l,u){let d=e.inputSchema.safeParse(n);if(!d.success){let n=oot(e.name,d.error),i=Zft(e,r.messages,r.options.tools);return i&&(J(`tengu_deferred_tool_schema_not_sent`,{toolName:Jc(e.name),isMcp:e.isMcp??!1}),n+=i),U(`${e.name} tool input error: ${n.slice(0,200)}`),J(`tengu_tool_use_error`,{error:`InputValidationError`,errorDetails:n.slice(0,2e3),messageID:o,toolName:Jc(e.name),isMcp:e.isMcp??!1,queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Kc(e.name,c,l)}),[{message:$({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 U(`${e.name} tool validation error: ${f.message?.slice(0,200)}`),J(`tengu_tool_use_error`,{messageID:o,toolName:Jc(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},...Kc(e.name,c,l)}),[{message:$({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();p$e(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 Bft(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 Jt()?.observe(`pre_tool_hook_duration_ms`,Date.now()-x),p.push({message:$({content:[hbt(t)],toolUseResult:`Error: ${v}`,sourceToolAssistantUUID:a.uuid})}),p}let S=Date.now()-x;Jt()?.observe(`pre_tool_hook_duration_ms`,S),S>=c1&&U(`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)),gce(e.name,C,nl()?V(m):void 0),yce();let w=r.getAppState().toolPermissionContext.mode,T=Date.now(),E=await zft(y,e,m,r,i,a,t),D=E.decision;m=E.input;let O=Date.now()-T;if(O>=c1&&w===`auto`&&U(`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=Gft(D.decisionReason,D.behavior);rl(`tool_decision`,{decision:t,source:n,tool_name:Jc(e.name)}),j0e(e.name)&&M0e(e,m,t,n).then(e=>lne()?.add(1,e))}if(D.decisionReason?.type===`hook`&&D.decisionReason.hookName===`PermissionRequest`&&D.behavior!==`ask`&&p.push({message:j0({type:`hook_permission_decision`,decision:D.behavior,toolUseID:t,hookEvent:`PermissionRequest`})}),D.behavior!==`allow`){U(`${e.name} tool permission denied`);let n=r.toolDecisions?.get(t);il(`reject`,n?.source||`unknown`),cl(),J(`tengu_tool_use_can_use_tool_rejected`,{messageID:o,toolName:Jc(e.name),queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Kc(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=hr(d,e=>e.type===`image`);if(e>0){let t=Kft(r.messages);f=Array.from({length:e},(e,n)=>t+n)}}return p.push({message:$({content:u,imagePasteIds:f,toolUseResult:`Error: ${i}`,sourceToolAssistantUUID:a.uuid})}),p}J(`tengu_tool_use_can_use_tool_allowed`,{messageID:o,toolName:Jc(e.name),queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Kc(e.name,c,l)}),D.updatedInput!==void 0&&(m=D.updatedInput);let k=ace(m),A={};if(Yc()){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=ice(e.name);t&&(A.mcp_server_name=t.serverName,A.mcp_tool_name=t.mcpToolName);let n=oce(e.name,m);n&&(A.skill_name=n)}let ee=r.toolDecisions?.get(t);il(ee?.decision||`unknown`,ee?.source||`unknown`),_ce();let te=Date.now();dc(`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=Rce()?await(async()=>{let{runToolCallWithSkillLearningHooks:t}=await Hft();return t(e.name,h,{sessionId:r.sessionId},n)})():await n(),f=Date.now()-te;if(Yte(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&&bce(`tool.output`,t)}typeof d==`object`&&`structured_output`in d&&p.push({message:j0({type:`structured_output`,data:d.structured_output})}),sl({success:!0}),cl(d.data&&typeof d.data==`object`?V(d.data):String(d.data??``));let g=e.mapToolResultToToolResultBlockParam(d.data,t),y=g.content,b=y?typeof y==`string`?y.length:V(y).length:0,x;if(m&&typeof m==`object`){if((e.name===`Read`||e.name===`Edit`||e.name===`Write`)&&`file_path`in m)x=Bc(String(m.file_path));else if(e.name===`NotebookEdit`&&`notebook_path`in m)x=Bc(String(m.notebook_path));else if(e.name===`Bash`&&`command`in m){let e=m;x=rce(e.command,e._simulatedSedEdit?.filePath)}}if(J(`tengu_tool_use_success`,{messageID:o,toolName:Jc(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},...Kc(e.name,c,l)}),Yc()&&(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=Bqe(String(d.data.stdout));e&&(A.git_commit_id=e)}let C=pT(e)?hT(e.name):null;rl(`tool_result`,{tool_name:Jc(e.name),success:`true`,duration_ms:String(f),...Object.keys(A).length>0&&{tool_parameters:V(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 aCe(i,e.name,e.maxResultSizeChars):await ny(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=hr(s,e=>e.type===`image`);if(e>0){let t=Kft(r.messages);c=Array.from({length:e},(e,n)=>t+n)}}p.push({message:$({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})}pT(e)||await ne(w,g);let re=[],ie=Date.now();for await(let n of Lft(r,e,t,a.message.id,m,w,s,c,l))if(`updatedMCPToolOutput`in n)pT(e)&&(w=n.updatedMCPToolOutput);else if(pT(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>=c1&&U(`Slow PostToolUse hooks: ${ae}ms for ${e.name} (${re.length} hooks)`,{level:`info`}),pT(e)&&await ne(w),d.newMessages&&d.newMessages.length>0)for(let e of d.newMessages)p.push({message:e});_&&p.push({message:j0({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(Yte(i),sl({success:!1,error:H(n)}),cl(),n instanceof Wj&&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 En)){let a=H(n);U(`${e.name} tool error (${i}ms): ${a.slice(0,200)}`),n instanceof wn||q(n),J(`tengu_tool_use_error`,{messageID:o,toolName:Jc(e.name),error:Uft(n),isMcp:e.isMcp??!1,queryChainId:r.queryTracking?.chainId,queryDepth:r.queryTracking?.depth,...c&&{mcpServerType:c},...l&&{mcpServerBaseUrl:l},...s&&{requestId:s},...Kc(e.name,c,l)});let u=pT(e)?hT(e.name):null;rl(`tool_result`,{tool_name:Jc(e.name),use_id:t,success:`false`,duration_ms:String(i),error:H(n),...Object.keys(A).length>0&&{tool_parameters:V(A)},...k&&{tool_input:k},...ee&&{decision_source:ee.source,decision_type:ee.decision},...u&&{mcp_server_scope:u}})}let u=rQ(n),d=n instanceof En,f=[];for await(let n of Rft(r,e,t,o,m,u,d,s,c,l))f.push(n);return[{message:$({content:[{type:`tool_result`,content:u,is_error:!0,tool_use_id:t}],toolUseResult:`Error: ${u}`,mcpMeta:r.agentId?void 0:n instanceof Kj?n.mcpMeta:void 0,sourceToolAssistantUUID:a.uuid})},...f]}finally{uc(`tool_exec`),ee&&r.toolDecisions?.delete(t)}}var s1,c1,$ft=n((()=>{Na(),Uc(),Gt(),R0e(),Zs(),HW(),Ts(),Rs(),Bs(),Cs(),zs(),gs(),xH(),Ws(),i1(),Tr(),H0(),W(),Mn(),g7(),oa(),p3(),hc(),Zn(),Pft(),ll(),al(),iQ(),sy(),_z(),cM(),Zr(),si(),_T(),Vft(),zce(),c1=2e3}));function ept(e,t){e.setInProgressToolUseIDs(e=>{let n=new Set(e);return n.delete(t),n})}var l1,tpt=n((()=>{p3(),Zs(),Ts(),OE(),$ft(),b(),l1=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=EE(n.abortController)}discard(){this.discarded=!0,this.siblingAbortController.abort(`streaming_fallback`),this.tools.length=0,this.progressAvailableResolve=void 0}addTool(e,t){let n=Ss(this.toolDefinitions,e.name);if(!n){this.tools.push({id:e.id,block:e,assistantMessage:t,status:`completed`,isConcurrencySafe:!0,pendingProgress:[],results:[$({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 $({content:[{type:`tool_result`,content:T4(o3),is_error:!0,tool_use_id:e}],toolUseResult:`User rejected tool use`,sourceToolAssistantUUID:n.uuid});if(t===`streaming_fallback`)return $({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 $({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=Ss(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=EE(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};ept(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 npt(){d1&&(Va().clearMarks(),f1.clear(),m1=null,p1++,u1(`query_user_input_received`))}function u1(e){if(!d1)return;let t=Va();if(t.mark(e),f1.set(e,process.memoryUsage()),e===`query_first_chunk_received`&&m1===null){let e=t.getEntriesByType(`mark`);e.length>0&&(m1=e[e.length-1]?.startTime??0)}}function rpt(){d1&&u1(`query_profile_end`)}function ipt(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 apt(){if(!d1)return`Query profiling not enabled (set CLAUDE_CODE_PROFILE_QUERY=1)`;let e=Va().getEntriesByType(`mark`);if(e.length===0)return`No query profiling checkpoints recorded`;let t=[];t.push(`=`.repeat(80)),t.push(`QUERY PROFILING REPORT - Query #${p1}`),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($ie(e,s,o.name,f1.get(o.name),10,9,ipt(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: ${Fa(a)}ms`),t.push(` - Pre-request overhead: ${Fa(e)}ms (${r}%)`),t.push(` - Network latency: ${Fa(n)}ms (${o}%)`)}else t.push(`Total time: ${Fa(s)}ms`);return t.push(opt(e,n)),t.push(`=`.repeat(80)),t.join(`
|
|
2492
2492
|
`)}function opt(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)} ${Fa(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)} ${Fa(a).padStart(10)}ms`)),i.join(`
|
|
2493
2493
|
`)}function spt(){d1&&U(apt())}var d1,f1,p1,m1,h1=n((()=>{W(),h(),Xie(),d1=m(process.env.CLAUDE_CODE_PROFILE_QUERY),f1=new Map,p1=0,m1=null}));async function cpt(e){let t;do t=await e.next();while(!t.done);return t.value}async function*lpt(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 upt(e){let t=[];for await(let n of e)t.push(n);return t}async function*dpt(e){for(let t of e)yield t}var g1=n((()=>{}));function fpt(){return parseInt(process.env.CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY||``,10)||10}async function*ppt(e,t,n,r){let i=r;for(let{isConcurrencySafe:r,blocks:a}of mpt(e,i))if(r){let e={};for await(let r of gpt(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 hpt(a,t,n,i))e.newContext&&(i=e.newContext),yield{message:e.message,newContext:i}}function mpt(e,t){return e.reduce((e,n)=>{let r=Ss(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*hpt(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};_pt(r,a.id)}}async function*gpt(e,t,n,r){yield*lpt(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),_pt(r,e.id)}),fpt())}function _pt(e,t){e.setInProgressToolUseIDs(e=>{let n=new Set(e);return n.delete(t),n})}var vpt=n((()=>{Zs(),g1(),$ft()}));async function ypt(e,t){let n=Y(e,`state.json`),r;try{r=JSON.parse(Kl(n,`utf-8`))}catch{return}let i=bpt(t);r.status=i,r.updatedAt=new Date().toISOString(),ale(n,JSON.stringify(r,null,2),`utf-8`)}function bpt(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 xpt=n((()=>{}));function Spt(){let e=ii().autoDreamEnabled;return e!==void 0&&e}var Cpt=n((()=>{Yr()}));async function wpt(e,t){try{let n=(await uu(e,{recursive:!0})).filter(e=>e.endsWith(`.md`)&&wl(e)!==`MEMORY.md`);return(await Promise.allSettled(n.map(async n=>{let r=Y(e,n),{content:i,mtimeMs:a}=await hy(r,0,Dpt,void 0,t),{frontmatter:o}=bd(i,r);return{filename:n,filePath:r,mtimeMs:a,description:o.description||null,type:Bfe(o.type)}}))).filter(e=>e.status===`fulfilled`).map(e=>e.value).sort((e,t)=>t.mtimeMs-e.mtimeMs).slice(0,Ept)}catch{return[]}}function Tpt(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(`
|
|
2494
2494
|
`)}var Ept,Dpt,Opt=n((()=>{Ed(),vy(),Id(),Ept=200,Dpt=30}));function kpt(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: ${xs}, ${cs}, ${Js}, read-only ${Is} (ls/find/cat/stat/wc/head/tail and similar), and ${ks}/${Ps} for paths inside the memory directory only. ${Is} rm is not permitted. All other tools — MCP, Agent, write-capable ${Is}, etc — will be denied.`,``,`You have a limited turn budget. ${ks} requires a prior ${xs} of the same file, so the efficient strategy is: turn 1 — issue all ${xs} calls in parallel for every file you might update; turn 2 — issue all ${Ps}/${ks} 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(`
|
|
@@ -2548,7 +2548,7 @@ Return a brief summary of what you consolidated, updated, or pruned. If nothing
|
|
|
2548
2548
|
|
|
2549
2549
|
Sessions since last consolidation (${c.length}):
|
|
2550
2550
|
${c.map(e=>`- ${e}`).join(`
|
|
2551
|
-
`)}`)})],cacheSafeParams:P1(t),canUseTool:v1(e),querySource:`auto_dream`,forkLabel:`auto_dream`,maxTurns:20,skipTranscript:!0,overrides:{abortController:f},onMessage:qpt(p,d)});r9e(p,d);let i=t.toolUseContext.getAppState().tasks?.[p];n&&e9e(i)&&i.filesTouched.length>0&&n({...nxt(i.filesTouched),verb:`Improved`}),U(`[autoDream] completed — cache: read=${r.totalUsage.cache_read_input_tokens} created=${r.totalUsage.cache_creation_input_tokens}`),J(`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){U(`[autoDream] aborted by user`);return}U(`[autoDream] fork failed: ${e.message}`),J(`tengu_auto_dream_failed`,{}),i9e(p,d),await Y7e(u)}}}function qpt(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)}n9e(e,{text:r.trim(),toolUseCount:i},a,t)}}async function Jpt(e,t){await x1?.(e,t)}var Ypt,Xpt,x1,Zpt=n((()=>{R1(),p3(),W(),Na(),Ci(),Cpt(),m8(),Gt(),Bpt(),Hpt(),wJ(),EJ(),Rs(),Cs(),Ypt=600*1e3,Xpt={minHours:24,minSessions:5},x1=null}));async function*Qpt(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`)&&Nmt(P1(l)),process.env.CLAUDE_JOB_DIR&&o.startsWith(`repl_main_thread`)&&!a.agentId){let e=l.messages.filter(e=>e.type===`assistant`),t=ypt(process.env.CLAUDE_JOB_DIR,e).catch(e=>{U(`[job] classifier error: ${H(e)}`,{level:`error`})});await Promise.race([t,new Promise(e=>setTimeout(e,6e4).unref())])}let u=(await import(`./poorMode-DD88nPJ4.js`)).isPoorModeActive();v()||(!f(process.env.CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION)&&!u&&Wmt(l),!a.agentId&&Kre()&&!u&&import(`./extractMemories-DnTBWFOW.js`).then(({executeExtractMemories:e})=>e(l,a.appendSystemMessage)).catch(()=>{}),!a.agentId&&!u&&Jpt(l,a.appendSystemMessage));try{let n=[],r=a.getAppState().toolPermissionContext.mode,i=uEt(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=$({content:nEt(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 j0({type:`hook_stopped_continuation`,message:u,hookName:`Stop`,toolUseID:o,hookEvent:`Stop`})),a.abortController.signal.aborted)return J(`tengu_pre_stop_hooks_cancelled`,{queryChainId:a.queryTracking?.chainId,queryDepth:a.queryTracking?.depth}),yield A4({toolUse:!1}),{blockingErrors:[],preventContinuation:!0}}if(c>0&&(yield ext(c,p,f,l,u,d,`suggestion`,o),f.length>0)){let e=Ey(`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 J(`tengu_stop_hook_error`,{duration:Date.now()-c,queryChainId:a.queryTracking?.chainId,queryDepth:a.queryTracking?.depth}),yield Q4(`Stop hook failed: ${H(e)}`,`warning`),{blockingErrors:[],preventContinuation:!1}}}var $pt=n((()=>{Oy(),Ci(),Na(),H0(),W(),Mn(),g7(),p3(),xpt(),Zpt(),U1(),h(),R1()}));function emt(){return{sessionId:ln(),gates:{streamingToolExecution:!1,emitToolUseSummaries:m(process.env.CLAUDE_CODE_EMIT_TOOL_USE_SUMMARIES),fastModeEnabled:!m(process.env.CLAUDE_CODE_DISABLE_FAST_MODE)}}}var tmt=n((()=>{Gt(),h()}));function nmt(){return{callModel:hOt,microcompact:BR,autocompact:Q$e,uuid:tu}}var rmt=n((()=>{n9(),sG(),HR()}));function S1(e,t){return parseFloat(e)*cmt[t.toLowerCase()]}function imt(e){let t=e.match(omt);if(t)return S1(t[1],t[2]);let n=e.match(smt);if(n)return S1(n[1],n[2]);let r=e.match(C1);return r?S1(r[1],r[2]):null}function amt(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 omt,smt,C1,cmt,lmt=n((()=>{omt=/^\s*\+(\d+(?:\.\d+)?)\s*(k|m|b)\b/i,smt=/\s\+(\d+(?:\.\d+)?)\s*(k|m|b)\s*[.!?]?\s*$/i,C1=/\b(?:use|spend)\s+(\d+(?:\.\d+)?)\s*(k|m|b)\s*tokens?\b/i,new RegExp(C1.source,`gi`),cmt={k:1e3,m:1e6,b:1e9}}));function umt(){return{continuationCount:0,lastDeltaTokens:0,lastGlobalTurnTokens:0,startedAt:Date.now()}}function dmt(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<w1&&e.lastDeltaTokens<w1;return!s&&i<n*fmt?(e.continuationCount++,e.lastDeltaTokens=o,e.lastGlobalTurnTokens=r,{action:`continue`,nudgeMessage:amt(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 fmt,w1,pmt=n((()=>{lmt(),fmt=.9,w1=500}));function T1(){return Y(p(),`sessions`)}function mmt(){let e=process.env.CLAUDE_CODE_SESSION_KIND;if(e===`bg`||e===`daemon`||e===`daemon-worker`)return e}function hmt(){return mmt()===`bg`}async function gmt(){let e=mmt()??`interactive`,t=T1(),n=Y(t,`${process.pid}.json`);qn(async()=>{try{await gu(n)}catch{}});try{return await su(t,{recursive:!0,mode:448}),await iu(t,448),await _u(n,V({pid:process.pid,sessionId:ln(),cwd:Zt(),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=>{E1({sessionId:e})}),!0}catch(e){return U(`[concurrentSessions] register failed: ${H(e)}`),!1}}async function E1(e){let t=Y(T1(),`${process.pid}.json`);try{await _u(t,V({...Nn(await lu(t,`utf8`)),...e}))}catch(e){U(`[concurrentSessions] updatePidFile failed: ${H(e)}`)}}async function _mt(e){e&&await E1({name:e})}async function vmt(e){await E1({bridgeSessionId:e})}async function ymt(e){await E1({...e,updatedAt:Date.now()})}async function bmt(){let e=T1(),t;try{t=await uu(e)}catch(e){return In(e)||U(`[concurrentSessions] readdir failed: ${H(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}Rc(t)?n++:_a()!==`wsl`&&gu(Y(e,r)).catch(()=>{})}return n}var D1=n((()=>{Gt(),Xn(),W(),h(),Mn(),zc(),va(),Zn()}));function xmt(){return hmt()?Date.now()-O1>=Cmt:!1}function Smt(e){O1=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`}`)}}ymt({status:r,waitingFor:i}).catch(e=>{U(`[taskSummary] updateSessionActivity failed: ${e}`)})}catch(e){U(`[taskSummary] error: ${e}`)}}var Cmt,O1,wmt=n((()=>{D1(),W(),Cmt=3e4,O1=0}));function*k1(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 $({content:[{type:`tool_result`,content:t,is_error:!0,tool_use_id:r.id}],toolUseResult:t,sourceToolAssistantUUID:n.uuid})}}function Tmt(e){return e?.type===`assistant`&&e.apiError===`max_output_tokens`}function Emt(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*A1(e){let t=[],n=[],r,i=!1,a;try{r=yield*Dmt(e,t,n)}catch(e){throw i=!0,a=e,e}finally{await x0e({commands:n,outcome:Emt({terminal:r,...i?{thrownError:a}:{}}),priority:`later`}).then(e=>{for(let t of e)mL(t)}).catch(q);let e=globalThis.performance;if(e&&typeof e.clearMarks==`function`)try{e.clearMarks(),e.clearMeasures?.(),e.clearResourceTimings?.()}catch{}}for(let e of t)OG(e,`completed`);return r}async function*Dmt(e,t,n){try{var r=Ene();let{systemPrompt:i,userContext:a,systemContext:o,canUseTool:s,fallbackModel:c,querySource:l,maxTurns:u,skipCacheWrite:d}=e,f=e.deps??nmt(),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=umt(),h,g=emt(),_=r.u(kgt(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=SI(null,v,r),D=JI(r.options.tools??[],v);yield{type:`stream_request_start`},u1(`query_fn_entry`),r.agentId||AG(`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=t3(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 CCe(A,r.contentReplacementState,te?e=>void b6(e,r.agentId).catch(q):void 0,new Set(r.options.tools.filter(e=>!Number.isFinite(e.maxResultSizeChars)).map(e=>e.name)));let ne=0;u1(`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)}u1(`query_microcompact_end`);let ie=rc(RDt(i,o));u1(`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(u1(`query_autocompact_end`),ae){let{preCompactTokenCount:t,postCompactTokenCount:n,truePostCompactTokenCount:r,compactionUsage:i}=ae;if(J(`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=gLe(A);h=Math.max(0,(h??e.taskBudget.total)-t)}ee={compacted:!0,turnId:f.uuid(),turnCounter:0,consecutiveFailures:0};let a=Rz(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;u1(`query_setup_start`);let N=g.gates.streamingToolExecution?new l1(r.options.tools,s,r):null,le=r.getAppState(),ue=le.toolPermissionContext.mode,de=Zo({permissionMode:ue,mainLoopModel:r.options.mainLoopModel,exceeds200kTokens:ue===`plan`&&vLe(A)});if(u1(`query_setup_end`),!ae&&l!==`compact`&&l!==`session_memory`){let{isAtBlockingLimit:e}=tG(xR(A)-ne,r.options.mainLoopModel);if(e)return yield k4({content:JL,error:`invalid_request`}),{reason:`blocking_limit`}}if(!ae&&nG()){let e=r.options.mainLoopModel,t=xR(A)-ne,n=X$e(e);if(t>$W(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=Rz(e.compactionResult),ne=0,ee=ee&&{...ee,compacted:!0,consecutiveFailures:e.consecutiveFailures??0})}}let fe=!0;u1(`query_api_loop_start`);try{for(;fe;){fe=!1;try{let t=!1;u1(`query_api_streaming_start`);for await(let n of f.callModel({messages:zDt(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};J(`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 l1(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=Ss(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(Tmt(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(...L4([e.message],r.options.tools).filter(e=>e.type===`user`)))}u1(`query_api_streaming_end`)}catch(e){if(e instanceof gR&&c){de=c,fe=!0,yield*k1(oe,`Model fallback triggered`),oe.length=0,se.length=0,ce.length=0,M=!1,N&&(N.discard(),N=new l1(r.options.tools,s,r)),r.options.mainLoopModel=c,J(`tengu_model_fallback_triggered`,{original_model:e.originalModel,fallback_model:c,entrypoint:`cli`,queryChainId:k,queryDepth:O.depth}),yield Q4(`Switched to ${No(e.fallbackModel)} due to high demand for ${No(e.originalModel)}`,`warning`);continue}throw e}}}catch(e){q(e);let t=e instanceof Error?e.message:String(e);return J(`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 AL||e instanceof n_?(yield k4({content:e.message}),{reason:`image_error`}):(yield*k1(oe,t),yield k4({content:t}),Yn(`Query error`,e),{reason:`model_error`,error:e})}if(oe.length>0&&!r.options.isNonInteractiveSession){let e=oe.at(-1)?.message?.usage;if(e&&yRe()){let t=xRe(e,l,vRe());t&&(yield SRe(t))}}if(oe.length>0&&k0e(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*k1(oe,`Interrupted by user`);return r.abortController.signal.reason!==`interrupt`&&(yield A4({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&&AIe(e),Tmt(e)){if(b<Omt){let e=$({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 lEt(e,r),{reason:`model_error`,error:e.error??e.apiError??`api_error`};let t=yield*Qpt(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=dmt(m,r.agentId,Iee(),Bee());if(e.action===`continue`){dte(),U(`Token budget continuation #${e.continuationCount}: ${e.pct}% (${e.turnTokens.toLocaleString()} / ${e.budget.toLocaleString()})`),p={messages:[...A,...oe,$({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&&U(`Token budget early stop: diminishing returns at ${e.completionEvent.pct}%`),J(`tengu_token_budget_completed`,{...e.completionEvent,queryChainId:k,queryDepth:O.depth}))}return{reason:`completed`}}let pe=!1,me=r;u1(`query_tool_execution_start`),J(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():ppt(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(...L4([e.message],r.options.tools).filter(e=>e.type===`user`))),e.newContext&&(me={...e.newContext,queryTracking:O});u1(`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=r1e({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?_xt(e,n):null).catch(()=>null)}if(r.abortController.signal.aborted){r.abortController.signal.reason!==`interrupt`&&(yield A4({toolUse:!0}));let e=T+1;return u&&e>u&&(yield j0({type:`max_turns_reached`,maxTurns:u,turnCount:e})),{reason:`aborted_tools`}}if(pe)return{reason:`hook_stopped`};ee?.compacted&&(ee.turnCounter++,J(`tengu_post_autocompact_turn`,{turnId:ee.turnId,turnCounter:ee.turnCounter,queryChainId:k,queryDepth:O.depth})),J(`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===os),ve=l.startsWith(`repl_main_thread`)||l===`sdk`,ye=r.agentId,be=await _0e(yL(_e?`later`:`next`).filter(e=>$Fe(e)?!1:ve?e.agentId===void 0:e.mode===`task-notification`&&e.agentId===ye));be.staleCommands.length>0&&_L(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),OG(e.uuid,`started`));_L(xe)}for await(let e of Kgt(null,me,null,be.attachmentCommands,A.concat(oe,se),l))yield e,se.push(e);if(_&&_.settledAt!==null&&_.consumedOnIteration===-1){let e=Ngt(await _.promise,r.readFileState);for(let t of e){let e=j0(t);yield e,se.push(e)}_.consumedOnIteration=T-1}if(_I&&E){let e=await CI(E);for(let t of e){let e=j0(t);yield e,se.push(e)}}if(HI&&D){let e=await YI(D);for(let t of e){let e=j0(t);yield e,se.push(e)}}let Se=new Set(xe),P=be.attachmentCommands.filter(e=>(e.mode===`prompt`||e.mode===`task-notification`)&&!Se.has(e));if(P.length>0){for(let e of P)e.uuid&&(t.push(e.uuid),OG(e.uuid,`started`));_L(P)}let Ce=hr(se,e=>e.type===`attachment`&&e.attachment.type===`edited_text_file`);if(J(`tengu_query_after_attachments`,{totalToolResultsCount:se.length,fileChangeAttachmentCount:Ce,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 we={...me,queryTracking:O},Te=T+1;if(!r.agentId&&xmt()&&Smt({systemPrompt:i,userContext:a,systemContext:o,toolUseContext:r,forkContextMessages:A.concat(oe,se)}),u&&Te>u)return yield j0({type:`max_turns_reached`,maxTurns:u,turnCount:Te}),{reason:`max_turns`,turnCount:Te};u1(`query_recursive_call`),p={messages:A.concat(oe,se),toolUseContext:we,autoCompactTracking:ee,turnCount:Te,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,pendingToolUseSummary:ge,maxOutputTokensOverride:void 0,stopHookActive:w,transition:{reason:`next_turn`}}}}catch(e){r.e=e}finally{r.d()}}var Omt,j1=n((()=>{_R(),sG(),Gz(),Dne(),Na(),jL(),r_(),Zs(),lI(),oa(),iR(),W(),p3(),o1e(),U7(),H0(),jI(),tL(),TL(),S0e(),w0e(),IG(),Lo(),SR(),io(),qs(),A0e(),g7(),tpt(),h1(),vpt(),sy(),m8(),$pt(),tmt(),rmt(),Gt(),pmt(),Tr(),ERe(),wmt(),Omt=3}));function kmt(){return{consecutiveDenials:0,totalDenials:0}}function Amt(e){return{...e,consecutiveDenials:e.consecutiveDenials+1,totalDenials:e.totalDenials+1}}function M1(e){return e.consecutiveDenials===0?e:{...e,consecutiveDenials:0}}function jmt(e){return e.consecutiveDenials>=N1.maxConsecutive||e.totalDenials>=N1.maxTotal}var N1,Mmt=n((()=>{N1={maxConsecutive:3,maxTotal:20}}));function Nmt(e){L1=e}function Pmt(){return L1}function P1(e){return{systemPrompt:e.systemPrompt,userContext:e.userContext,systemContext:e.systemContext,toolUseContext:e.toolUseContext,forkContextMessages:e.messages}}function Fmt(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 Imt(e,t,n){let r=(await e.getPromptForCommand(t,n)).map(e=>e.type===`text`?e.text:``).join(`
|
|
2551
|
+
`)}`)})],cacheSafeParams:P1(t),canUseTool:v1(e),querySource:`auto_dream`,forkLabel:`auto_dream`,maxTurns:20,skipTranscript:!0,overrides:{abortController:f},onMessage:qpt(p,d)});r9e(p,d);let i=t.toolUseContext.getAppState().tasks?.[p];n&&e9e(i)&&i.filesTouched.length>0&&n({...nxt(i.filesTouched),verb:`Improved`}),U(`[autoDream] completed — cache: read=${r.totalUsage.cache_read_input_tokens} created=${r.totalUsage.cache_creation_input_tokens}`),J(`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){U(`[autoDream] aborted by user`);return}U(`[autoDream] fork failed: ${e.message}`),J(`tengu_auto_dream_failed`,{}),i9e(p,d),await Y7e(u)}}}function qpt(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)}n9e(e,{text:r.trim(),toolUseCount:i},a,t)}}async function Jpt(e,t){await x1?.(e,t)}var Ypt,Xpt,x1,Zpt=n((()=>{R1(),p3(),W(),Na(),Ci(),Cpt(),m8(),Gt(),Bpt(),Hpt(),wJ(),EJ(),Rs(),Cs(),Ypt=600*1e3,Xpt={minHours:24,minSessions:5},x1=null}));async function*Qpt(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`)&&Nmt(P1(l)),process.env.CLAUDE_JOB_DIR&&o.startsWith(`repl_main_thread`)&&!a.agentId){let e=l.messages.filter(e=>e.type===`assistant`),t=ypt(process.env.CLAUDE_JOB_DIR,e).catch(e=>{U(`[job] classifier error: ${H(e)}`,{level:`error`})});await Promise.race([t,new Promise(e=>setTimeout(e,6e4).unref())])}let u=(await import(`./poorMode-DD88nPJ4.js`)).isPoorModeActive();v()||(!f(process.env.CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION)&&!u&&Wmt(l),!a.agentId&&Kre()&&!u&&import(`./extractMemories-BsQU2bVO.js`).then(({executeExtractMemories:e})=>e(l,a.appendSystemMessage)).catch(()=>{}),!a.agentId&&!u&&Jpt(l,a.appendSystemMessage));try{let n=[],r=a.getAppState().toolPermissionContext.mode,i=uEt(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=$({content:nEt(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 j0({type:`hook_stopped_continuation`,message:u,hookName:`Stop`,toolUseID:o,hookEvent:`Stop`})),a.abortController.signal.aborted)return J(`tengu_pre_stop_hooks_cancelled`,{queryChainId:a.queryTracking?.chainId,queryDepth:a.queryTracking?.depth}),yield A4({toolUse:!1}),{blockingErrors:[],preventContinuation:!0}}if(c>0&&(yield ext(c,p,f,l,u,d,`suggestion`,o),f.length>0)){let e=Ey(`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 J(`tengu_stop_hook_error`,{duration:Date.now()-c,queryChainId:a.queryTracking?.chainId,queryDepth:a.queryTracking?.depth}),yield Q4(`Stop hook failed: ${H(e)}`,`warning`),{blockingErrors:[],preventContinuation:!1}}}var $pt=n((()=>{Oy(),Ci(),Na(),H0(),W(),Mn(),g7(),p3(),xpt(),Zpt(),U1(),h(),R1()}));function emt(){return{sessionId:ln(),gates:{streamingToolExecution:!1,emitToolUseSummaries:m(process.env.CLAUDE_CODE_EMIT_TOOL_USE_SUMMARIES),fastModeEnabled:!m(process.env.CLAUDE_CODE_DISABLE_FAST_MODE)}}}var tmt=n((()=>{Gt(),h()}));function nmt(){return{callModel:hOt,microcompact:BR,autocompact:Q$e,uuid:tu}}var rmt=n((()=>{n9(),sG(),HR()}));function S1(e,t){return parseFloat(e)*cmt[t.toLowerCase()]}function imt(e){let t=e.match(omt);if(t)return S1(t[1],t[2]);let n=e.match(smt);if(n)return S1(n[1],n[2]);let r=e.match(C1);return r?S1(r[1],r[2]):null}function amt(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 omt,smt,C1,cmt,lmt=n((()=>{omt=/^\s*\+(\d+(?:\.\d+)?)\s*(k|m|b)\b/i,smt=/\s\+(\d+(?:\.\d+)?)\s*(k|m|b)\s*[.!?]?\s*$/i,C1=/\b(?:use|spend)\s+(\d+(?:\.\d+)?)\s*(k|m|b)\s*tokens?\b/i,new RegExp(C1.source,`gi`),cmt={k:1e3,m:1e6,b:1e9}}));function umt(){return{continuationCount:0,lastDeltaTokens:0,lastGlobalTurnTokens:0,startedAt:Date.now()}}function dmt(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<w1&&e.lastDeltaTokens<w1;return!s&&i<n*fmt?(e.continuationCount++,e.lastDeltaTokens=o,e.lastGlobalTurnTokens=r,{action:`continue`,nudgeMessage:amt(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 fmt,w1,pmt=n((()=>{lmt(),fmt=.9,w1=500}));function T1(){return Y(p(),`sessions`)}function mmt(){let e=process.env.CLAUDE_CODE_SESSION_KIND;if(e===`bg`||e===`daemon`||e===`daemon-worker`)return e}function hmt(){return mmt()===`bg`}async function gmt(){let e=mmt()??`interactive`,t=T1(),n=Y(t,`${process.pid}.json`);qn(async()=>{try{await gu(n)}catch{}});try{return await su(t,{recursive:!0,mode:448}),await iu(t,448),await _u(n,V({pid:process.pid,sessionId:ln(),cwd:Zt(),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=>{E1({sessionId:e})}),!0}catch(e){return U(`[concurrentSessions] register failed: ${H(e)}`),!1}}async function E1(e){let t=Y(T1(),`${process.pid}.json`);try{await _u(t,V({...Nn(await lu(t,`utf8`)),...e}))}catch(e){U(`[concurrentSessions] updatePidFile failed: ${H(e)}`)}}async function _mt(e){e&&await E1({name:e})}async function vmt(e){await E1({bridgeSessionId:e})}async function ymt(e){await E1({...e,updatedAt:Date.now()})}async function bmt(){let e=T1(),t;try{t=await uu(e)}catch(e){return In(e)||U(`[concurrentSessions] readdir failed: ${H(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}Rc(t)?n++:_a()!==`wsl`&&gu(Y(e,r)).catch(()=>{})}return n}var D1=n((()=>{Gt(),Xn(),W(),h(),Mn(),zc(),va(),Zn()}));function xmt(){return hmt()?Date.now()-O1>=Cmt:!1}function Smt(e){O1=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`}`)}}ymt({status:r,waitingFor:i}).catch(e=>{U(`[taskSummary] updateSessionActivity failed: ${e}`)})}catch(e){U(`[taskSummary] error: ${e}`)}}var Cmt,O1,wmt=n((()=>{D1(),W(),Cmt=3e4,O1=0}));function*k1(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 $({content:[{type:`tool_result`,content:t,is_error:!0,tool_use_id:r.id}],toolUseResult:t,sourceToolAssistantUUID:n.uuid})}}function Tmt(e){return e?.type===`assistant`&&e.apiError===`max_output_tokens`}function Emt(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*A1(e){let t=[],n=[],r,i=!1,a;try{r=yield*Dmt(e,t,n)}catch(e){throw i=!0,a=e,e}finally{await x0e({commands:n,outcome:Emt({terminal:r,...i?{thrownError:a}:{}}),priority:`later`}).then(e=>{for(let t of e)mL(t)}).catch(q);let e=globalThis.performance;if(e&&typeof e.clearMarks==`function`)try{e.clearMarks(),e.clearMeasures?.(),e.clearResourceTimings?.()}catch{}}for(let e of t)OG(e,`completed`);return r}async function*Dmt(e,t,n){try{var r=Ene();let{systemPrompt:i,userContext:a,systemContext:o,canUseTool:s,fallbackModel:c,querySource:l,maxTurns:u,skipCacheWrite:d}=e,f=e.deps??nmt(),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=umt(),h,g=emt(),_=r.u(kgt(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=SI(null,v,r),D=JI(r.options.tools??[],v);yield{type:`stream_request_start`},u1(`query_fn_entry`),r.agentId||AG(`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=t3(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 CCe(A,r.contentReplacementState,te?e=>void b6(e,r.agentId).catch(q):void 0,new Set(r.options.tools.filter(e=>!Number.isFinite(e.maxResultSizeChars)).map(e=>e.name)));let ne=0;u1(`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)}u1(`query_microcompact_end`);let ie=rc(RDt(i,o));u1(`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(u1(`query_autocompact_end`),ae){let{preCompactTokenCount:t,postCompactTokenCount:n,truePostCompactTokenCount:r,compactionUsage:i}=ae;if(J(`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=gLe(A);h=Math.max(0,(h??e.taskBudget.total)-t)}ee={compacted:!0,turnId:f.uuid(),turnCounter:0,consecutiveFailures:0};let a=Rz(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;u1(`query_setup_start`);let N=g.gates.streamingToolExecution?new l1(r.options.tools,s,r):null,le=r.getAppState(),ue=le.toolPermissionContext.mode,de=Zo({permissionMode:ue,mainLoopModel:r.options.mainLoopModel,exceeds200kTokens:ue===`plan`&&vLe(A)});if(u1(`query_setup_end`),!ae&&l!==`compact`&&l!==`session_memory`){let{isAtBlockingLimit:e}=tG(xR(A)-ne,r.options.mainLoopModel);if(e)return yield k4({content:JL,error:`invalid_request`}),{reason:`blocking_limit`}}if(!ae&&nG()){let e=r.options.mainLoopModel,t=xR(A)-ne,n=X$e(e);if(t>$W(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=Rz(e.compactionResult),ne=0,ee=ee&&{...ee,compacted:!0,consecutiveFailures:e.consecutiveFailures??0})}}let fe=!0;u1(`query_api_loop_start`);try{for(;fe;){fe=!1;try{let t=!1;u1(`query_api_streaming_start`);for await(let n of f.callModel({messages:zDt(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};J(`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 l1(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=Ss(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(Tmt(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(...L4([e.message],r.options.tools).filter(e=>e.type===`user`)))}u1(`query_api_streaming_end`)}catch(e){if(e instanceof gR&&c){de=c,fe=!0,yield*k1(oe,`Model fallback triggered`),oe.length=0,se.length=0,ce.length=0,M=!1,N&&(N.discard(),N=new l1(r.options.tools,s,r)),r.options.mainLoopModel=c,J(`tengu_model_fallback_triggered`,{original_model:e.originalModel,fallback_model:c,entrypoint:`cli`,queryChainId:k,queryDepth:O.depth}),yield Q4(`Switched to ${No(e.fallbackModel)} due to high demand for ${No(e.originalModel)}`,`warning`);continue}throw e}}}catch(e){q(e);let t=e instanceof Error?e.message:String(e);return J(`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 AL||e instanceof n_?(yield k4({content:e.message}),{reason:`image_error`}):(yield*k1(oe,t),yield k4({content:t}),Yn(`Query error`,e),{reason:`model_error`,error:e})}if(oe.length>0&&!r.options.isNonInteractiveSession){let e=oe.at(-1)?.message?.usage;if(e&&yRe()){let t=xRe(e,l,vRe());t&&(yield SRe(t))}}if(oe.length>0&&k0e(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*k1(oe,`Interrupted by user`);return r.abortController.signal.reason!==`interrupt`&&(yield A4({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&&AIe(e),Tmt(e)){if(b<Omt){let e=$({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 lEt(e,r),{reason:`model_error`,error:e.error??e.apiError??`api_error`};let t=yield*Qpt(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=dmt(m,r.agentId,Iee(),Bee());if(e.action===`continue`){dte(),U(`Token budget continuation #${e.continuationCount}: ${e.pct}% (${e.turnTokens.toLocaleString()} / ${e.budget.toLocaleString()})`),p={messages:[...A,...oe,$({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&&U(`Token budget early stop: diminishing returns at ${e.completionEvent.pct}%`),J(`tengu_token_budget_completed`,{...e.completionEvent,queryChainId:k,queryDepth:O.depth}))}return{reason:`completed`}}let pe=!1,me=r;u1(`query_tool_execution_start`),J(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():ppt(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(...L4([e.message],r.options.tools).filter(e=>e.type===`user`))),e.newContext&&(me={...e.newContext,queryTracking:O});u1(`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=r1e({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?_xt(e,n):null).catch(()=>null)}if(r.abortController.signal.aborted){r.abortController.signal.reason!==`interrupt`&&(yield A4({toolUse:!0}));let e=T+1;return u&&e>u&&(yield j0({type:`max_turns_reached`,maxTurns:u,turnCount:e})),{reason:`aborted_tools`}}if(pe)return{reason:`hook_stopped`};ee?.compacted&&(ee.turnCounter++,J(`tengu_post_autocompact_turn`,{turnId:ee.turnId,turnCounter:ee.turnCounter,queryChainId:k,queryDepth:O.depth})),J(`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===os),ve=l.startsWith(`repl_main_thread`)||l===`sdk`,ye=r.agentId,be=await _0e(yL(_e?`later`:`next`).filter(e=>$Fe(e)?!1:ve?e.agentId===void 0:e.mode===`task-notification`&&e.agentId===ye));be.staleCommands.length>0&&_L(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),OG(e.uuid,`started`));_L(xe)}for await(let e of Kgt(null,me,null,be.attachmentCommands,A.concat(oe,se),l))yield e,se.push(e);if(_&&_.settledAt!==null&&_.consumedOnIteration===-1){let e=Ngt(await _.promise,r.readFileState);for(let t of e){let e=j0(t);yield e,se.push(e)}_.consumedOnIteration=T-1}if(_I&&E){let e=await CI(E);for(let t of e){let e=j0(t);yield e,se.push(e)}}if(HI&&D){let e=await YI(D);for(let t of e){let e=j0(t);yield e,se.push(e)}}let Se=new Set(xe),P=be.attachmentCommands.filter(e=>(e.mode===`prompt`||e.mode===`task-notification`)&&!Se.has(e));if(P.length>0){for(let e of P)e.uuid&&(t.push(e.uuid),OG(e.uuid,`started`));_L(P)}let Ce=hr(se,e=>e.type===`attachment`&&e.attachment.type===`edited_text_file`);if(J(`tengu_query_after_attachments`,{totalToolResultsCount:se.length,fileChangeAttachmentCount:Ce,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 we={...me,queryTracking:O},Te=T+1;if(!r.agentId&&xmt()&&Smt({systemPrompt:i,userContext:a,systemContext:o,toolUseContext:r,forkContextMessages:A.concat(oe,se)}),u&&Te>u)return yield j0({type:`max_turns_reached`,maxTurns:u,turnCount:Te}),{reason:`max_turns`,turnCount:Te};u1(`query_recursive_call`),p={messages:A.concat(oe,se),toolUseContext:we,autoCompactTracking:ee,turnCount:Te,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,pendingToolUseSummary:ge,maxOutputTokensOverride:void 0,stopHookActive:w,transition:{reason:`next_turn`}}}}catch(e){r.e=e}finally{r.d()}}var Omt,j1=n((()=>{_R(),sG(),Gz(),Dne(),Na(),jL(),r_(),Zs(),lI(),oa(),iR(),W(),p3(),o1e(),U7(),H0(),jI(),tL(),TL(),S0e(),w0e(),IG(),Lo(),SR(),io(),qs(),A0e(),g7(),tpt(),h1(),vpt(),sy(),m8(),$pt(),tmt(),rmt(),Gt(),pmt(),Tr(),ERe(),wmt(),Omt=3}));function kmt(){return{consecutiveDenials:0,totalDenials:0}}function Amt(e){return{...e,consecutiveDenials:e.consecutiveDenials+1,totalDenials:e.totalDenials+1}}function M1(e){return e.consecutiveDenials===0?e:{...e,consecutiveDenials:0}}function jmt(e){return e.consecutiveDenials>=N1.maxConsecutive||e.totalDenials>=N1.maxTotal}var N1,Mmt=n((()=>{N1={maxConsecutive:3,maxTotal:20}}));function Nmt(e){L1=e}function Pmt(){return L1}function P1(e){return{systemPrompt:e.systemPrompt,userContext:e.userContext,systemContext:e.systemContext,toolUseContext:e.toolUseContext,forkContextMessages:e.messages}}function Fmt(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 Imt(e,t,n){let r=(await e.getPromptForCommand(t,n)).map(e=>e.type===`text`?e.text:``).join(`
|
|
2552
2552
|
`),i=N9(e.allowedTools??[]),a=Fmt(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:[$({content:r})]}}function Lmt(e,t=`Execution completed`){let n=D4(e);return n&&K4(Array.isArray(n.message.content)?n.message.content:[],`
|
|
2553
2553
|
`)||t}function F1(e,t){let n=t?.abortController??(t?.shareAbortController?e.abortController:EE(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:DP(t?.readFileState??e.readFileState),nestedMemoryAttachmentTriggers:new Set,loadedNestedMemoryPaths:new Set,dynamicSkillDirTriggers:new Set,discoveredSkillNames:new Set,toolDecisions:void 0,contentReplacementState:t?.contentReplacementState??(e.contentReplacementState?lCe(e.contentReplacementState):void 0),abortController:n,getAppState:r,setAppState:t?.shareSetAppState?e.setAppState:()=>{},setAppStateForTasks:e.setAppStateForTasks??e.setAppState,localDenialTracking:t?.shareSetAppState?e.localDenialTracking:kmt(),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??GG(),agentType:t?.agentType,queryTracking:{chainId:tu(),depth:(e.queryTracking?.depth??-1)+1},fileReadingLimits:e.fileReadingLimits,userModified:e.userModified,criticalSystemReminder_EXPERIMENTAL:t?.criticalSystemReminder_EXPERIMENTAL,requireCanUseTool:t?.requireCanUseTool}}function Rmt(e){return e.type===`stream_event`&&typeof e.event==`object`&&e.event!==null&&`type`in e.event&&e.event.type===`message_delta`}async function I1({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={...lc},{systemPrompt:m,userContext:h,systemContext:g,toolUseContext:_,forkContextMessages:v}=t,y=F1(_,a),b=[...v,...e],x=l?void 0:GG(i),S=null;x&&(await _6(b,x).catch(e=>U(`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 A1({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(Rmt(e)){let t=Q7({...lc},e.event.usage);p=COt(p,t)}continue}if(e.type===`stream_request_start`)continue;U(`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 _6([t],x,S).catch(e=>U(`Forked agent [${i}] failed to record transcript: ${e}`)),t.type!==`progress`&&(S=t.uuid))}}finally{y.readFileState.clear(),b.length=0}return U(`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}`),zmt({forkLabel:i,querySource:r,durationMs:Date.now()-d,messageCount:f.length,totalUsage:p,queryTracking:_.queryTracking}),{messages:f,totalUsage:p}}function zmt({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;J(`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 L1,R1=n((()=>{j1(),Na(),n9(),ac(),OE(),W(),jP(),p3(),Mmt(),R9(),m8(),sy(),KG(),L1=null}));function z1(){return`user_intent`}function Bmt(){let e=process.env.CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION;return f(e)?(J(`tengu_prompt_suggestion_init`,{enabled:!1,source:`env`}),!1):m(e)?(J(`tengu_prompt_suggestion_init`,{enabled:!0,source:`env`}),!0):(J(`tengu_prompt_suggestion_init`,{enabled:!1,source:`growthbook`}),!1)}function Vmt(){V1&&(V1.abort(),V1=null)}function Hmt(e){return e.promptSuggestionEnabled?e.elicitation.queue.length>0?`elicitation_active`:e.toolPermissionContext.mode===`plan`?`plan_mode`:zL.status===`allowed`?null:`rate_limit`:`disabled`}async function Umt(e,t,n,r,i){if(e.signal.aborted)return B1(`aborted`,void 0,void 0,i),null;if(hr(t,e=>e.type===`assistant`)<2)return B1(`early_conversation`,void 0,void 0,i),null;let a=D4(t);if(a?.isApiErrorMessage)return B1(`last_response_error`,void 0,void 0,i),null;let o=Gmt(a);if(o)return B1(o,void 0,void 0,i),null;let s=Hmt(n());if(s)return B1(s,void 0,void 0,i),null;let c=z1(),{suggestion:l,generationRequestId:u}=await Kmt(e,c,r);return e.signal.aborted?(B1(`aborted`,void 0,void 0,i),null):l?qmt(l,c,i)?null:{suggestion:l,promptId:c,generationRequestId:u}:(B1(`empty`,void 0,c,i),null)}async function Wmt(e){if(e.querySource!==`repl_main_thread`)return;V1=new AbortController;let t=V1,n=P1(e);try{let r=await Umt(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}})),ght()&&r.suggestion&&vht(r.suggestion,e,e.toolUseContext.setAppState,!1,n)}catch(e){if(e instanceof Error&&(e.name===`AbortError`||e.name===`APIUserAbortError`)){B1(`aborted`,void 0,void 0,`cli`);return}q(Fn(e))}finally{V1===t&&(V1=null)}}function Gmt(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>Ymt?`cache_cold`:null}async function Kmt(e,t,n){let r=Xmt[t],i=await I1({promptMessages:[$({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 qmt(e,t,n){if(!e)return B1(`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 B1(r,e,t,n),!0;return!1}function Jmt(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);J(`tengu_prompt_suggestion`,{source:`sdk`,outcome:o?`accepted`:`ignored`,prompt_id:r,...i&&{generationRequestId:i},...o&&{timeToAcceptMs:s},...!o&&{timeToIgnoreMs:s},similarity:a})}function B1(e,t,n,r){let i=n??z1();J(`tengu_prompt_suggestion`,{...r&&{source:r},outcome:`suppressed`,reason:e,prompt_id:i})}var V1,Ymt,H1,Xmt,U1=n((()=>{Gt(),Tr(),h(),Mn(),R1(),oa(),p3(),Yr(),Na(),HL(),t0(),V1=null,Ymt=1e4,H1=`[SUGGESTION MODE: Suggest what the user might naturally type next into Work Mate.]
|
|
2554
2554
|
|
|
@@ -3167,13 +3167,13 @@ Goal: Write your final plan to the plan file (the only file you can edit).
|
|
|
3167
3167
|
- **Hard limit: 40 lines.** If the plan is longer, delete prose — not file paths.`}));function m3(){return!1}async function Mxt(e,t,n){if(!m3())return await n();let r=$l(`sha1`).update(V(e)).digest(`hex`).slice(0,12),i=Y(process.env.CLAUDE_CODE_TEST_FIXTURES_ROOT??Cn(),`fixtures/${t}-${r}.json`);try{return Nn(await lu(i,{encoding:`utf8`}))}catch(e){if(Dn(e)!==`ENOENT`)throw e}if((pr.isCI||process.env.CI)&&!m(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 su(Tl(i),{recursive:!0}),await _u(i,V(a,null,2),{encoding:`utf8`}),a}async function Nxt(e,t){if(!m3())return await t();let n=Fxt(L4(e.filter(e=>e.type!==`user`||!e.isMeta)).map(e=>e.message.content),g3),r=Y(process.env.CLAUDE_CODE_TEST_FIXTURES_ROOT??Cn(),`fixtures/${n.map(e=>$l(`sha1`).update(V(e)).digest(`hex`).slice(0,6)).join(`-`)}.json`);try{let e=Nn(await lu(r,{encoding:`utf8`}));return e.output.forEach(Pxt),e.output.map((e,t)=>Lxt(e,Rxt,t,tu()))}catch(e){if(Dn(e)!==`ENOENT`)throw e}if(pr.isCI&&!m(process.env.VCR_RECORD))throw Error(`API fixture missing: ${r}. Re-run tests with VCR_RECORD=1, then commit the result. Input messages:\n${V(n,null,2)}`);let i=await t();return pr.isCI&&!m(process.env.VCR_RECORD)?i:(await su(Tl(r),{recursive:!0}),await _u(r,V({input:n,output:i.map((e,t)=>Lxt(e,g3,t))},null,2),{encoding:`utf8`}),i)}function Pxt(e){if(e.type===`stream_event`)return;let t=e.message.model,n=e.message.usage;WF(po(t,n),n,t)}function Fxt(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:h3(e.input,t)};case`image`:return e;default:return}}))}function h3(e,t){return Kp(e,(n,r)=>Array.isArray(n)?n.map(e=>h3(e,t)):Sre(n)?h3(n,t):t(n,r,e))}function Ixt(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:h3(e.input,t)};default:return e}}).filter(Boolean)},type:`assistant`}}function Lxt(e,t,n,r){return e.type===`assistant`?Ixt(e,t,n,r):e}function g3(e){if(typeof e!=`string`)return e;let t=Cn(),n=p(),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=V(t).slice(1,-1),o=V(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 Rxt(e){return typeof e==`string`?e.replaceAll(`[NUM]`,`1`).replaceAll(`[DURATION]`,`100`).replaceAll(`[CONFIG_HOME]`,p()).replaceAll(`[CWD]`,Cn()):e}async function*zxt(e,t){if(!m3())return yield*t();let n=[],r=await Nxt(e,async()=>{for await(let e of t())n.push(e);return n});if(r.length>0){yield*r;return}yield*n}async function Bxt(e,t,n){let r=Cn().replace(/[^a-zA-Z0-9]/g,`-`);return(await Mxt(g3(V({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 Vxt=n((()=>{Ire(),qp(),GF(),Ao(),Sn(),Pr(),h(),Mn(),p3(),Zn()}));function Hxt(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 Uxt(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=>!fz(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 Wxt(e){return e?_3([{role:`user`,content:e}],[]):0}async function _3(e,t){return Bxt(e,t,async()=>{try{let n=eo();if(n===`gemini`)return Yxt(e,t);let r=ts(),i=ns(r),a=Hxt(e);if(n===`bedrock`)return Zxt({model:jo(r),messages:e,tools:t,betas:i,containsThinking:a});let o=await ho({maxRetries:1,model:r,source:`count_tokens`}),s=eo()===`vertex`?i.filter(e=>Mae.has(e)):i,c=await o.beta.messages.countTokens({model:jo(r),messages:e.length>0?e:[{role:`user`,content:`foo`}],tools:t,...s.length>0&&{betas:s},...a&&{thinking:{type:`enabled`,budget_tokens:x3}}});return typeof c.input_tokens==`number`?c.input_tokens:null}catch(e){return q(e),null}})}function v3(e,t=4){return Math.round(e.length/t)}function Gxt(e){switch(e){case`json`:case`jsonl`:case`jsonc`:return 2;default:return 4}}function Kxt(e,t){return v3(e,Gxt(t))}async function qxt(e,t){if(eo()===`gemini`)return Yxt(e,t);let n=Hxt(e),r=m(process.env.CLAUDE_CODE_USE_VERTEX)&&_(Ko())===`global`,i=m(process.env.CLAUDE_CODE_USE_BEDROCK)&&n,a=m(process.env.CLAUDE_CODE_USE_VERTEX)&&n,o=r||i||a?Yo():Ko(),s=await ho({maxRetries:1,model:o,source:`count_tokens`}),c=Uxt(e),l=c.length>0?c:[{role:`user`,content:`count`}],u=ns(o),d=eo()===`vertex`?u.filter(e=>Mae.has(e)):u,f=(await s.beta.messages.create({model:jo(o),max_tokens:n?S3:1,messages:l,tools:t.length>0?t:void 0,...d.length>0&&{betas:d},metadata:Y7(),...q7(),...n&&{thinking:{type:`enabled`,budget_tokens:x3}}})).usage,p=f.input_tokens,h=f.cache_creation_input_tokens||0,g=f.cache_read_input_tokens||0;return p+h+g}function y3(e){let t=0;for(let n of e)t+=Jxt(n);return t}function Jxt(e){if((e.type===`assistant`||e.type===`user`)&&e.message?.content)return b3(e.message?.content);if(e.type===`attachment`&&e.attachment){let t=Qbt(e.attachment),n=0;for(let e of t)n+=b3(e.message.content);return n}return 0}function b3(e){if(!e)return 0;if(typeof e==`string`)return v3(e);let t=0;for(let n of e)t+=Xxt(n);return t}function Yxt(e,t){let n=0;for(let t of e)n+=b3(t.content);return t.length>0&&(n+=v3(V(t))),n}function Xxt(e){return typeof e==`string`?v3(e):e.type===`text`?v3(e.text):e.type===`image`||e.type===`document`?2e3:e.type===`tool_result`?b3(e.content):e.type===`tool_use`?v3(e.name+V(e.input??{})):e.type===`thinking`?v3(e.thinking):e.type===`redacted_thinking`?v3(e.data):v3(V(e))}async function Zxt({model:e,messages:t,tools:n,betas:r,containsThinking:i}){try{let a=await uae(),o=Jae(e)?e:await go(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?S3:1,...n.length>0&&{tools:n},...r.length>0&&{anthropic_beta:r},...i&&{thinking:{type:`enabled`,budget_tokens:x3}}},{CountTokensCommand:c}=await import(`./dist-es-Gt_DpXlP.js`),l={modelId:o,input:{invokeModel:{body:new TextEncoder().encode(V(s))}}};return(await a.send(new c(l))).inputTokens??null}catch(e){return q(e),null}}var x3,S3,C3=n((()=>{es(),Xo(),Po(),h(),oa(),p3(),So(),Lo(),Zn(),_z(),n9(),xo(),Vxt(),x3=1024,S3=2048}));function Qxt(e){$xt=e}var $xt,eSt=n((()=>{}));function tSt(e,t){switch(e){case`policySettings`:return Y(Mr(),`.workmate`,t);case`userSettings`:return Y(p(),t);case`projectSettings`:return`.workmate/${t}`;case`plugin`:return`plugin`;default:return``}}function nSt(e){return v3([e.name,e.description,e.whenToUse].filter(Boolean).join(` `))}async function rSt(e){try{return await du(e)}catch{return null}}function iSt(e,t){if(!e.hooks)return;let n=nr().safeParse(e.hooks);if(!n.success){U(`Invalid hooks in skill '${t}': ${n.error.message}`);return}return n.data}function aSt(e){if(!e.paths)return;let t=xd(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 w3(e,t,n,r=`Skill`){let i=Sd(e.description,n),a=i??z9(t,r),o=e[`user-invocable`]===void 0||Cd(e[`user-invocable`]),s=e.model===`inherit`?void 0:e.model?oo(e.model):void 0;return{displayName:e.name==null?void 0:String(e.name),description:a,hasUserSpecifiedDescription:i!==null,allowedTools:V9(e[`allowed-tools`]),argumentHint:e[`argument-hint`]==null?void 0:String(e[`argument-hint`]),argumentNames:m_t(e.arguments),whenToUse:e.when_to_use,version:e.version,model:s,disableModelInvocation:Cd(e[`disable-model-invocation`]),userInvocable:o,hooks:iSt(e,n),executionContext:e.context===`fork`?`fork`:void 0,agent:e.agent,shell:jfe(e.shell,n)}}function T3({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=J0(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,ln()),h!==`mcp`&&(r=await g_t(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 E3(e,t){let n=G(),r;try{r=await n.readdir(e)}catch(e){return In(e)||q(e),[]}return(await Promise.all(r.map(async r=>{try{if(!r.isDirectory()&&!r.isSymbolicLink())return null;let i=Y(e,r.name),a=Y(i,`SKILL.md`),o;try{o=await n.readFile(a,{encoding:`utf-8`})}catch(e){return Tn(e)||U(`[skills] failed to read ${a}: ${e}`,{level:`warn`}),null}let{frontmatter:s,content:c}=bd(o,a),l=r.name,u=w3(s,c,l),d=aSt(s);return{skill:T3({...u,skillName:l,markdownContent:c,source:t,baseDir:i,loadedFrom:`skills`,paths:d}),filePath:a}}catch(e){return q(e),null}}))).filter(e=>e!==null)}function D3(e){return/^skill\.md$/i.test(wl(e))}function oSt(e){let t=new Map;for(let n of e){let e=Tl(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=>D3(e.filePath));if(t.length>0){let r=t[0];t.length>1&&U(`Multiple skill files found in ${e}, using ${wl(r.filePath)}`),n.push(r)}else n.push(...r)}return n}function sSt(e,t){let n=t.endsWith(Nl)?t.slice(0,-1):t;if(e===n)return``;let r=e.slice(n.length+1);return r?r.split(Nl).join(`:`):``}function cSt(e,t){let n=Tl(e),r=Tl(n),i=wl(n),a=sSt(r,t);return a?`${a}:${i}`:i}function lSt(e,t){let n=wl(e),r=Tl(e),i=n.replace(/\.md$/,``),a=sSt(r,t);return a?`${a}:${i}`:i}function uSt(e){return D3(e.filePath)?cSt(e.filePath,e.baseDir):lSt(e.filePath,e.baseDir)}async function dSt(e){try{let t=oSt(await W9(`commands`,e)),n=[];for(let{baseDir:e,filePath:r,frontmatter:i,content:a,source:o}of t)try{let t=D3(r)?Tl(r):void 0,s=uSt({baseDir:e,filePath:r,frontmatter:i,content:a,source:o}),c=w3(i,a,s,`Custom command`);n.push({skill:T3({...c,skillName:s,displayName:void 0,markdownContent:a,source:o,baseDir:t,loadedFrom:`commands_DEPRECATED`,paths:void 0}),filePath:r})}catch(e){q(e)}return n}catch(e){return q(e),[]}}function fSt(){j3.cache?.clear?.(),W9.cache?.clear?.(),P3.clear(),F3.clear()}function pSt(e){return I3.subscribe(()=>{try{e()}catch(e){q(e)}})}async function O3(e,t){let n=G(),r=t.endsWith(Nl)?t.slice(0,-1):t,i=[];for(let t of e){let e=Tl(t);for(;e.startsWith(r+Nl);){let t=Y(e,`.workmate`,`skills`);if(!M3.has(t)){M3.add(t);try{if(await n.stat(t),await Dre(e,r)){U(`[skills] Skipped gitignored skills dir: ${t}`);continue}i.push(t)}catch{}}let a=Tl(e);if(a===e)break;e=a}}return i.sort((e,t)=>t.split(Nl).length-e.split(Nl).length)}async function k3(e){if(!fi(`projectSettings`)||q_(`skills`)){U(`[skills] Dynamic skill discovery skipped: projectSettings disabled or plugin-only policy`);return}if(e.length===0)return;let t=new Set(N3.keys()),n=await Promise.all(e.map(e=>E3(e,`projectSettings`)));for(let e=n.length-1;e>=0;e--)for(let{skill:t}of n[e]??[])t.type===`prompt`&&N3.set(t.name,t);let r=n.flat().length;if(r>0){let n=[...N3.keys()].filter(e=>!t.has(e));U(`[skills] Dynamically discovered ${r} skills from ${e.length} directories`),n.length>0&&J(`tengu_dynamic_skills_changed`,{source:`file_operation`,previousCount:t.size,newCount:N3.size,addedCount:n.length,directoryCount:e.length})}I3.emit()}function mSt(){return Array.from(N3.values())}function A3(e,t){if(P3.size===0)return[];let n=[];for(let[r,i]of P3){if(i.type!==`prompt`||!i.paths||i.paths.length===0)continue;let a=(0,gSt.default)().add(i.paths);for(let o of e){let e=Dl(o)?jl(t,o):o;if(!(!e||e.startsWith(`..`)||Dl(e))&&a.ignores(e)){N3.set(r,i),P3.delete(r),F3.add(r),n.push(r),U(`[skills] Activated conditional skill '${r}' (matched path: ${e})`);break}}}return n.length>0&&(J(`tengu_dynamic_skills_changed`,{source:`conditional_paths`,previousCount:N3.size-n.length,newCount:N3.size,addedCount:n.length,directoryCount:0}),I3.emit()),n}function hSt(){M3.clear(),N3.clear(),P3.clear(),F3.clear()}var gSt,j3,M3,N3,P3,F3,I3,L3=n((()=>{gSt=r(ce(),1),d(),Gt(),Na(),C3(),Y0(),W(),h(),Mn(),Ed(),Un(),ore(),oa(),G9(),Lo(),S_t(),ti(),wr(),X_(),xr(),mn(),eSt(),j3=u(async e=>{let t=Y(p(),`skills`),n=Y(Mr(),`.workmate`,`skills`),r=H9(`skills`,e);U(`Loading skills from: managed=${n}, user=${t}, project=[${r.join(`, `)}]`);let i=$t(),a=q_(`skills`),o=fi(`projectSettings`)&&!a;if(v())return i.length===0||!o?(U(`[bare] Skipping skill dir discovery (${i.length===0?`no --add-dir`:`projectSettings disabled or skillsLocked`})`),[]):(await Promise.all(i.map(e=>E3(Y(e,`.workmate`,`skills`),`projectSettings`)))).flat().map(e=>e.skill);let[s,c,l,u,d]=await Promise.all([m(process.env.CLAUDE_CODE_DISABLE_POLICY_SKILLS)?Promise.resolve([]):E3(n,`policySettings`),fi(`userSettings`)&&!a?E3(t,`userSettings`):Promise.resolve([]),o?Promise.all(r.map(e=>E3(e,`projectSettings`))):Promise.resolve([]),o?Promise.all(i.map(e=>E3(Y(e,`.workmate`,`skills`),`projectSettings`))):Promise.resolve([]),a?Promise.resolve([]):dSt(e)]),f=[...s,...c,...l.flat(),...u.flat(),...d],h=await Promise.all(f.map(({skill:e,filePath:t})=>e.type===`prompt`?rSt(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=h[e];if(r==null){_.push(n);continue}let i=g.get(r);if(i!==void 0){U(`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&&U(`Deduplicated ${y} skills (same file)`);let b=[],x=[];for(let e of _)e.type===`prompt`&&e.paths&&e.paths.length>0&&!F3.has(e.name)?x.push(e):b.push(e);for(let e of x)P3.set(e.name,e);return x.length>0&&U(`[skills] ${x.length} conditional skills stored (activated when matching files are touched)`),U(`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}),M3=new Set,N3=new Map,P3=new Map,F3=new Set,I3=an(),Qxt({createSkillCommand:T3,parseSkillFrontmatterFields:w3})}));function _St(e){let{files:t}=e,n,r=e.getPromptForCommand;if(t&&Object.keys(t).length>0){n=ySt(e.name);let i,a=e.getPromptForCommand;r=async(n,r)=>{i??(i=bSt(e.name,t));let o=await i,s=await a(n,r);return o===null?s:wSt(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};R3.push(i)}function vSt(){return[...R3]}function ySt(e){return Y(I8(),e)}async function bSt(e,t){let n=ySt(e);try{return await xSt(n,t),n}catch(t){return U(`Failed to extract bundled skill '${e}' to ${n}: ${t instanceof Error?t.message:String(t)}`),null}}async function xSt(e,t){let n=new Map;for(let[r,i]of Object.entries(t)){let t=CSt(e,r),a=Tl(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 su(e,{recursive:!0,mode:448}),await Promise.all(t.map(([e,t])=>SSt(e,t)))}))}async function SSt(e,t){let n=await cu(e,ESt,384);try{await n.writeFile(t,`utf8`)}finally{await n.close()}}function CSt(e,t){let n=Ol(t);if(Dl(n)||n.split(Nl).includes(`..`)||n.split(`/`).includes(`..`))throw Error(`bundled skill file path escapes skill dir: ${t}`);return Y(e,n)}function wSt(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 R3,TSt,ESt,DSt=n((()=>{W(),L8(),R3=[],TSt=Wl.O_NOFOLLOW??0,ESt=process.platform===`win32`?`wx`:Wl.O_WRONLY|Wl.O_CREAT|Wl.O_EXCL|TSt}));function OSt(e){return NSt.some(t=>t.test(e))}function kSt(e){return e.length<=8?`***`:`${e.slice(0,4)}…${e.slice(-2)} (${e.length} chars)`}function ASt(e){return PSt.some(t=>e.startsWith(t))}function jSt(){let e=Object.entries(process.env).filter(([e])=>ASt(e)).map(([e,t])=>[e,OSt(e)&&t?kSt(t):t??``]).sort(([e],[t])=>e.localeCompare(t));return e.length===0?` (no recognized env vars set)`:e.map(([e,t])=>` ${e}=${t}`).join(`
|
|
3168
3168
|
`)}function MSt(){return[` platform: ${process.platform} ${process.arch}`,` cwd: ${process.cwd()}`,` pid: ${process.pid}`,` bun: ${typeof Bun<`u`?Bun.version:`n/a`}`,` node: ${process.version}`,` session: ${ln()}`].join(`
|
|
3169
3169
|
`)}var NSt,PSt,FSt,ISt=n((()=>{Gt(),NSt=[/token/i,/secret/i,/password/i,/api[_-]?key/i,/auth/i,/private/i,/credential/i,/jwt/i,/session[_-]?id$/i],PSt=[`CLAUDE_`,`FEATURE_`,`ANTHROPIC_`,`BUN_`,`NODE_`,`GEMINI_`,`OPENAI_`,`GROK_`,`CCR_`,`BUGHUNTER_`],FSt={type:`local`,name:`env`,description:`显示当前环境、运行时与 feature flag`,isHidden:!1,isEnabled:()=>!0,supportsNonInteractive:!0,load:async()=>({call:async()=>({type:`text`,value:[`## Runtime`,MSt(),``,`## Environment Variables (allowlisted prefixes)`,jSt(),``,"_Secrets matching token/password/auth/api_key are masked. Set additional `CLAUDE_*` / `FEATURE_*` env vars to see them here._"].join(`
|
|
3170
|
-
`)})})}})),z3,LSt=n((()=>{z3={type:`local-jsx`,name:`exit`,aliases:[`quit`],description:`退出 REPL`,immediate:!0,load:()=>import(`./exit-
|
|
3170
|
+
`)})})}})),z3,LSt=n((()=>{z3={type:`local-jsx`,name:`exit`,aliases:[`quit`],description:`退出 REPL`,immediate:!0,load:()=>import(`./exit-jikLI2Zh.js`)}})),RSt,zSt=n((()=>{Xhe(),Lo(),RSt={type:`local-jsx`,name:`model`,get description(){return`Set the AI model for Work Mate (currently ${No(ts())})`},argumentHint:`[model]`,get immediate(){return Yhe()},load:()=>import(`./model-B50j-O5v.js`)}})),B3,BSt=n((()=>{Cr(),B3={type:`prompt`,description:`设置 Work Mate 的状态栏 UI`,contentLength:0,aliases:[],name:`statusline`,progressMessage:`setting up statusLine`,allowedTools:[ur,`Read(~/**)`,`Edit(~/.workmate/settings.json)`],source:`builtin`,disableNonInteractive:!0,async getPromptForCommand(e){return[{type:`text`,text:`Create an ${ur} with subagent_type "statusline-setup" and the prompt "${e.trim()||`Configure my statusLine from my shell PS1 configuration`}"`}]}}}));function V3(e){return(e.userFacingName?.()??e.name)||``}function H3(e){return e.isEnabled?.()??!0}var VSt=n((()=>{}));async function HSt(e){try{let[t,n]=await Promise.all([j3(e).catch(e=>(q(Fn(e)),U(`Skill directory commands failed to load, continuing without them`),[])),$0().catch(e=>(q(Fn(e)),U(`Plugin skills failed to load, continuing without them`),[]))]),r=vSt(),i=Ebe();return U(`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 q(Fn(e)),U(`Unexpected error in getSkills, returning empty`),{skillDirCommands:[],pluginSkills:[],bundledSkills:[],builtinPluginSkills:[]}}}function U3(e){if(!e.availability||e.availability.length===0)return!0;for(let t of e.availability)switch(t){case`claude-ai`:if(as())return!0;break;case`console`:if(!as()&&!wae()&&Qo())return!0;break;default:break}return!1}async function W3(e){let t=await Y3(e),n=mSt(),r=t.filter(e=>U3(e)&&H3(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)&&H3(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 USt(){Y3.cache?.clear?.(),X3.cache?.clear?.(),Z3.cache?.clear?.(),qse()}function WSt(){USt(),D_t(),k_t(),fSt()}function GSt(e){return[]}function KSt(e){return e.filter(e=>Q3.has(e))}function G3(e,t){return t.find(t=>t.name===e||V3(t)===e||t.aliases?.includes(e))}function K3(e,t){return G3(e,t)!==void 0}function qSt(e,t){let n=G3(e,t);if(!n)throw ReferenceError(`Command ${e} not found. Available commands: ${t.map(e=>{let t=V3(e);return e.aliases?`${t} (aliases: ${e.aliases.join(`, `)})`:t}).sort((e,t)=>e.localeCompare(t)).join(`, `)}`);return n}function JSt(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} (${Nre(e.source)})`}var q3,J3,Y3,X3,Z3,Q3,$3=n((()=>{gpe(),_pe(),vpe(),bpe(),Spe(),Tpe(),Dpe(),kpe(),jpe(),Npe(),Ppe(),Xpe(),Qpe(),yhe(),yc(),xhe(),Che(),The(),Dhe(),Ohe(),Ahe(),Mhe(),Phe(),Ihe(),Rhe(),zhe(),Bhe(),Vhe(),Cc(),Uhe(),Ghe(),qhe(),Jhe(),Qhe(),ege(),nge(),ige(),oge(),cge(),uge(),pge(),_ge(),ebe(),pbe(),Sbe(),oa(),Mn(),W(),L3(),DSt(),Bh(),e2(),d(),Do(),es(),ISt(),LSt(),zSt(),BSt(),ti(),VSt(),q3=u(()=>[hpe,fbe,Fhe,xbe,rge,tge,ef,tf,ype,xpe,Cpe,wpe,Epe,Ope,z3,Zhe,nf,Ype,lp,bhe,Ape,Mpe,RSt,age,sge,whe,Ehe,up,khe,jhe,B3,dp,lge,Lhe,fp,Whe,pp,Khe,mp,$he,vh,Nhe,Hhe,gge,fge,Zpe,FSt,Wse,Use,She]),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([HSt(e),Q0()]);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 q(Fn(e)),U(`Returning empty skills array due to load failure`),[]}}),Q3=new Set([up,z3,tf,nf,dp,fp,ef,mp,pp,lp,B3])}));async function YSt(e){let t=Date.now(),{stdout:n,code:r}=await Gi(Hi(),[`worktree`,`list`,`--porcelain`],{cwd:e,preserveOutputOnError:!1}),i=Date.now()-t;if(r!==0)return J(`tengu_worktree_detection`,{duration_ms:i,worktree_count:0,success:!1}),[];let a=n.split(`
|
|
3171
3171
|
`).filter(e=>e.startsWith(`worktree `)).map(e=>e.slice(9).normalize(`NFC`));J(`tengu_worktree_detection`,{duration_ms:i,worktree_count:a.length,success:!0});let o=a.find(t=>e===t||e.startsWith(t+Nl)),s=a.filter(e=>e!==o).sort((e,t)=>e.localeCompare(t));return o?[o,...s]:s}var XSt=n((()=>{Na(),qi(),Bi()})),ZSt=i({MAX_TRANSCRIPT_READ_BYTES:()=>i8,adoptResumedSessionFile:()=>gCt,buildConversationChain:()=>T6,cacheSessionTitle:()=>BCt,checkResumeConsistency:()=>E6,cleanMessagesForLogging:()=>Q6,clearAgentTranscriptSubdir:()=>o6,clearGoalEntry:()=>P6,clearSessionMessagesCache:()=>W6,clearSessionMetadata:()=>LCt,deleteRemoteAgentMetadata:()=>u6,doesMessageExistInSession:()=>JCt,enrichLogs:()=>n8,extractAgentIdsFromMessages:()=>$Ct,fetchLogs:()=>j6,findUnresolvedToolUse:()=>iwt,flushSessionStorage:()=>yCt,getAgentTranscript:()=>Y6,getAgentTranscriptPath:()=>s6,getCurrentSessionTag:()=>FCt,getCurrentSessionTitle:()=>F6,getFirstMeaningfulUserMessageTextContent:()=>S6,getLastSessionLog:()=>G6,getLogByIndex:()=>rwt,getNodeEnv:()=>p6,getProjectDir:()=>o8,getProjectsDir:()=>n6,getSessionFilesLite:()=>t8,getSessionFilesWithMtime:()=>$6,getSessionIdFromLog:()=>R6,getSessionMessages:()=>H6,getSessionMessagesCache:()=>U6,getTranscriptPath:()=>r6,getTranscriptPathForSession:()=>i6,getUserType:()=>m6,hydrateFromCCRv2InternalEvents:()=>xCt,hydrateRemoteSession:()=>bCt,isChainParticipant:()=>t6,isCustomTitleEnabled:()=>oCt,isEphemeralToolProgress:()=>$St,isLiteLog:()=>z6,isLoggableMessage:()=>Z6,isTranscriptMessage:()=>e6,linkSessionToPR:()=>PCt,listRemoteAgentMetadata:()=>d6,loadAllLogsFromSessionFile:()=>e8,loadAllProjectsMessageLogs:()=>YCt,loadAllProjectsMessageLogsProgressive:()=>q6,loadAllSubagentTranscriptsFromDisk:()=>ewt,loadFullLog:()=>B6,loadMessageLogs:()=>K6,loadSameRepoMessageLogs:()=>ZCt,loadSameRepoMessageLogsProgressive:()=>J6,loadSubagentTranscripts:()=>X6,loadTranscriptFile:()=>V6,loadTranscriptFromFile:()=>TCt,reAppendSessionMetadata:()=>I6,readAgentMetadata:()=>tCt,readRemoteAgentMetadata:()=>iCt,recordAttributionSnapshot:()=>mCt,recordContentReplacement:()=>b6,recordContextCollapseCommit:()=>_Ct,recordContextCollapseSnapshot:()=>vCt,recordFileHistorySnapshot:()=>y6,recordQueueOperation:()=>v6,recordSidechainTranscript:()=>_6,recordTranscript:()=>g6,removeExtraFields:()=>C6,removeTranscriptMessage:()=>pCt,resetProjectFlushStateForTesting:()=>sCt,resetProjectForTesting:()=>cCt,resetSessionFilePointer:()=>hCt,restoreSessionMetadata:()=>ICt,saveAgentName:()=>RCt,saveAgentSetting:()=>zCt,saveAiGeneratedTitle:()=>jCt,saveCustomTitle:()=>ACt,saveGoal:()=>N6,saveMode:()=>VCt,saveTag:()=>NCt,saveTaskSummary:()=>MCt,saveWorktreeState:()=>L6,searchSessionsByCustomTitle:()=>HCt,sessionIdExists:()=>f6,setAgentTranscriptSubdir:()=>a6,setInternalEventReader:()=>dCt,setInternalEventWriter:()=>uCt,setRemoteIngressUrlForTesting:()=>fCt,setSessionFileForTesting:()=>lCt,writeAgentMetadata:()=>c6,writeRemoteAgentMetadata:()=>rCt});function e6(e){return e.type===`user`||e.type===`assistant`||e.type===`attachment`||e.type===`system`}function t6(e){return e.type!==`progress`}function QSt(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`progress`&&`uuid`in e&&typeof e.uuid==`string`}function $St(e){return typeof e==`string`&&pwt.has(e)}function n6(){return Y(p(),`projects`)}function r6(){return Y(en()??o8(Zt()),`${ln()}.jsonl`)}function i6(e){return e===ln()?r6():Y(o8(Zt()),`${e}.jsonl`)}function a6(e,t){a8.set(e,t)}function o6(e){a8.delete(e)}function s6(e){let t=en()??o8(Zt()),n=ln(),r=a8.get(e);return Y(r?Y(t,n,`subagents`,r):Y(t,n,`subagents`),`agent-${e}.jsonl`)}function eCt(e){return s6(e).replace(/\.jsonl$/,`.meta.json`)}async function c6(e,t){let n=eCt(e);await su(Tl(n),{recursive:!0}),await _u(n,JSON.stringify(t))}async function tCt(e){let t=eCt(e);try{let e=await lu(t,`utf-8`);return JSON.parse(e)}catch(e){if(In(e))return null;throw e}}function nCt(){return Y(en()??o8(Zt()),ln(),`remote-agents`)}function l6(e){return Y(nCt(),`remote-agent-${e}.meta.json`)}async function rCt(e,t){let n=l6(e);await su(Tl(n),{recursive:!0}),await _u(n,JSON.stringify(t))}async function iCt(e){let t=l6(e);try{let e=await lu(t,`utf-8`);return JSON.parse(e)}catch(e){if(In(e))return null;throw e}}async function u6(e){let t=l6(e);try{await gu(t)}catch(e){if(In(e))return;throw e}}async function d6(){let e=nCt(),t;try{t=await uu(e,{withFileTypes:!0})}catch(e){if(In(e))return[];throw e}let n=[];for(let r of t)if(!(!r.isFile()||!r.name.endsWith(`.meta.json`)))try{let t=await lu(Y(e,r.name),`utf-8`);n.push(JSON.parse(t))}catch(e){U(`listRemoteAgentMetadata: skipping ${r.name}: ${String(e)}`)}return n}function f6(e){let t=Y(o8(Zt()),`${e}.jsonl`),n=G();try{return n.statSync(t),!0}catch{return!1}}function p6(){return`production`}function m6(){return`external`}function aCt(){return process.env.CLAUDE_CODE_ENTRYPOINT}function oCt(){return!0}function h6(){return s8||(s8=new mwt,c8||(qn(async()=>{await s8?.flush();try{s8?.reAppendSessionMetadata()}catch{}}),c8=!0)),s8}function sCt(){s8?._resetFlushState()}function cCt(){s8=null}function lCt(e){h6().sessionFile=e}function uCt(e){h6().setInternalEventWriter(e)}function dCt(e,t){h6().setInternalEventReader(e),h6().setInternalSubagentEventReader(t)}function fCt(e){h6().setRemoteIngressUrl(e)}async function g6(e,t,n,r){let i=Q6(e,r),a=await H6(ln()),o=[],s=n,c=!1;for(let e of i)a.has(e.uuid)?!c&&t6(e)&&(s=e.uuid):(o.push(e),c=!0);return o.length>0&&await h6().insertMessageChain(o,!1,void 0,s,t),o.findLast(t6)?.uuid??s??null}async function _6(e,t,n){await h6().insertMessageChain(Q6(e),!0,t,n)}async function v6(e){await h6().insertQueueOperation(e)}async function pCt(e){await h6().removeMessageByUuid(e)}async function y6(e,t,n){await h6().insertFileHistorySnapshot(e,t,n)}async function mCt(e){await h6().insertAttributionSnapshot(e)}async function b6(e,t){await h6().insertContentReplacement(e,t)}async function hCt(){h6().resetSessionFile()}function gCt(){let e=h6();e.sessionFile=r6(),e.reAppendSessionMetadata(!0)}async function _Ct(e){let t=ln();t&&await h6().appendEntry({type:`marble-origami-commit`,sessionId:t,...e})}async function vCt(e){let t=ln();t&&await h6().appendEntry({type:`marble-origami-snapshot`,sessionId:t,...e})}async function yCt(){await h6().flush()}async function bCt(e,t){cn(DB(e));let n=h6();try{let n=await Znt(e,t)||[];return await su(o8(Zt()),{recursive:!0,mode:448}),await _u(i6(e),n.map(e=>`${V(e)}\n`).join(``),{encoding:`utf8`,mode:384}),U(`Hydrated ${n.length} entries from remote`),n.length>0}catch(e){return U(`Error hydrating session from remote: ${e}`),Ri(`error`,`hydrate_remote_session_fail`),!1}finally{n.setRemoteIngressUrl(t)}}async function xCt(e){let t=Date.now();cn(DB(e));let n=h6(),r=n.getInternalEventReader();if(!r)return U(`No internal event reader registered for CCR v2 resume`),!1;try{let i=await r();if(!i)return U(`Failed to read internal events for resume`),Ri(`error`,`hydrate_ccr_v2_read_fail`),!1;await su(o8(Zt()),{recursive:!0,mode:448}),await _u(i6(e),i.map(e=>`${V(e.payload)}\n`).join(``),{encoding:`utf8`,mode:384}),U(`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=s6(OB(e));await su(Tl(t),{recursive:!0,mode:448}),await _u(t,n.map(e=>`${V(e)}\n`).join(``),{encoding:`utf8`,mode:384})}U(`Hydrated ${e.length} subagent entries across ${t.size} agents`)}}return Ri(`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 U(`Error hydrating session from CCR v2: ${e}`),Ri(`error`,`hydrate_ccr_v2_fail`),!1}}function x6(e){let t=S6(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 S6(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=j4(e,ea);if(t){let n=t.replace(/^\//,``);if(J3().has(n))continue;{let n=j4(e,`command-args`)?.trim();if(!n)continue;return`${t} ${n}`}}let n=j4(e,`bash-input`);if(n)return`! ${n}`;if(!r8.test(e))return e}}}function C6(e){return e.map(e=>{let{isSidechain:t,parentUuid:n,...r}=e;return r})}function SCt(e){let t,n=-1,r=-1,i=new Map,a=0;for(let o of e.values()){if(i.set(o.uuid,a),e3(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){J(`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 CCt(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++);J(`tengu_snip_resume_filtered`,{removed_count:r,relinked_count:a})}function w6(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 T6(e,t){let n=[],r=new Set,i=t;for(;i;){if(r.has(i.uuid)){q(Error(`Cycle detected in parentUuid chain at message ${i.uuid}. Returning partial transcript.`)),J(`tengu_chain_parent_cycle`,{});break}r.add(i.uuid),n.push(i),i=i.parentUuid?e.get(i.parentUuid):void 0}return n.reverse(),wCt(e,n,r)}function wCt(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;J(`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 E6(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;J(`tengu_resume_consistency_delta`,{expected:r,actual:i,delta:i-r,chain_length:e.length,checkpoint_age_entries:e.length-1-t});return}}function D6(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 O6(e,t){return Array.from(e.values())}async function TCt(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 V6(e);if(t.size===0)throw Error(`No messages found in JSONL file`);let f=w6(t.values(),e=>l.has(e.uuid));if(!f)throw Error(`No valid conversation chain found in JSONL file`);let p=T6(t,f),m=n.get(f.uuid),h=r.get(f.sessionId),g=i.get(f.sessionId),_=f.sessionId;return{...A6(p,0,m,h,D6(a,p),g,e,O6(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 lu(e,{encoding:`utf-8`}),n;try{n=Nn(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 A6(r,0,void 0,void 0,void 0,void 0,e)}function ECt(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 DCt(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 k6(e){let t=0;for(let n of e)switch(n.type){case`user`:ECt(n)&&t++;break;case`assistant`:DCt(n)&&t++;break;case`attachment`:case`system`:case`progress`:break}return t}function A6(e,t=0,n,r,i,a,o,s,c,l){let u=e.at(-1),d=e[0],f=x6(e),p=new Date(d.timestamp),m=new Date(u.timestamp);return{date:u.timestamp,messages:C6(e),fullPath:o,value:t,created:p,modified:m,firstPrompt:f,messageCount:k6(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 OCt(e){let t=new Map,n=0;for(let r of e){let e=R6(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);J(`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 j6(e){let t=await t8(o8(Zt()),e,Zt());return await OCt(t),t}function M6(e,t){let n=G(),r=`${V(t)}\n`;try{n.appendFileSync(e,r,{mode:384})}catch{n.mkdirSync(Tl(e),{mode:448}),n.appendFileSync(e,r,{mode:384})}}function kCt(e){let t;try{t=Zce(e,`r`);let n=Xce(t),r=Math.max(0,n.size-Oa),i=Buffer.allocUnsafe(Math.min(Oa,n.size-r)),a=Qce(t,i,0,i.length,r);return i.toString(`utf8`,0,a)}catch{return``}finally{if(t!==void 0)try{Kce(t)}catch{}}}async function ACt(e,t,n,r=`user`){M6(n??i6(e),{type:`custom-title`,customTitle:t,sessionId:e}),e===ln()&&(h6().currentSessionTitle=t),J(`tengu_session_renamed`,{source:r})}function jCt(e,t){M6(i6(e),{type:`ai-title`,aiTitle:t,sessionId:e})}function MCt(e,t){M6(i6(e),{type:`task-summary`,summary:t,sessionId:e,timestamp:new Date().toISOString()})}async function NCt(e,t,n){M6(n??i6(e),{type:`tag`,tag:t,sessionId:e}),e===ln()&&(h6().currentSessionTag=t),J(`tengu_session_tagged`,{})}function N6(e,t,n){M6(n??i6(e),{type:`goal`,sessionId:e,state:t,timestamp:new Date().toISOString()}),e===ln()&&(h6().currentSessionGoal=t)}function P6(e,t){M6(t??i6(e),{type:`goal-cleared`,sessionId:e,timestamp:new Date().toISOString()}),e===ln()&&(h6().currentSessionGoal=void 0)}async function PCt(e,t,n,r,i){if(M6(i??i6(e),{type:`pr-link`,sessionId:e,prNumber:t,prUrl:n,prRepository:r,timestamp:new Date().toISOString()}),e===ln()){let e=h6();e.currentSessionPrNumber=t,e.currentSessionPrUrl=n,e.currentSessionPrRepository=r}J(`tengu_session_linked_to_pr`,{prNumber:t})}function FCt(e){if(e===ln())return h6().currentSessionTag}function F6(e){if(e===ln())return h6().currentSessionTitle}function ICt(e){let t=h6();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 LCt(){let e=h6();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 I6(){h6().reAppendSessionMetadata()}async function RCt(e,t,n,r=`user`){M6(n??i6(e),{type:`agent-name`,agentName:t,sessionId:e}),e===ln()&&(h6().currentSessionAgentName=t,_mt(t)),J(`tengu_agent_name_set`,{source:r})}function zCt(e){h6().currentSessionAgentSetting=e}function BCt(e){h6().currentSessionTitle=e}function VCt(e){h6().currentSessionMode=e}function L6(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=h6();n.currentSessionWorktree=t,n.sessionFile&&M6(n.sessionFile,{type:`worktree-state`,worktreeSession:t,sessionId:ln()})}function R6(e){return e.sessionId?e.sessionId:e.messages[0]?.sessionId}function z6(e){return e.messages.length===0&&e.sessionId!==void 0}async function B6(e){if(!z6(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 V6(t);if(n.size===0){let t=e.sessionId?m.get(e.sessionId):void 0;return t?{...e,goal:t}:e}let x=w6(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=T6(n,x),C=x.sessionId;return{...e,messages:C6(S),firstPrompt:x6(S),messageCount:k6(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:D6(h,S),attributionSnapshots:O6(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 HCt(e,t){let{limit:n,exact:r}=t||{},i=await QCt(await YSt(Zt())),{logs:a}=await n8(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=R6(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 UCt(e,t){if(e===null||e.length===0)return t;if(e.length<hwt)return Buffer.concat([e,t]);if(e[0]===123){for(let n of d8)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 WCt(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=UCt(a,e);if(t===null){a=null;continue}let n=!1;for(let e of d8)if(t.includes(e)){n=!0;break}if(n){let e=0,n=t.indexOf(10);for(;n!==-1;){for(let r of d8){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 d8)if(a.includes(e)){i.push(a.toString(`utf-8`));break}}return i}function GCt(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 KCt(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?GCt(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 V6(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,h=new Map,g=new Map,_=new Map,v=new Map,y=new Map,b=[],x;try{let S=null,C=null,w=!1;if(!m(process.env.CLAUDE_CODE_DISABLE_PRECOMPACT_SKIP)){let{size:t}=await mu(e);if(t>5242880){let n=await Lie(e,t);S=n.postBoundaryBuf,w=n.hasPreservedSegment,n.boundaryStartOffset>0&&(C=await WCt(e,n.boundaryStartOffset))}}if(S??(S=await lu(e)),!t?.keepAllLeaves&&!w&&!m(process.env.CLAUDE_CODE_DISABLE_PRECOMPACT_SKIP)&&S.length>5242880&&(S=KCt(S)),C&&C.length>0){let e=Uie(Buffer.from(C.join(`
|
|
3172
3172
|
`)));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?h.set(t.sessionId,t.state):t.type===`goal-cleared`&&t.sessionId?h.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=Uie(S),E=new Map;for(let e of T){if(QSt(e)){let t=e.parentUuid;E.set(e.uuid,t&&E.has(t)?E.get(t)??null:t);continue}if(e6(e))e.parentUuid&&E.has(e.parentUuid)&&(e.parentUuid=E.get(e.parentUuid)??null),n.set(e.uuid,e),e3(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)h.set(e.sessionId,e.state);else if(e.type===`goal-cleared`&&e.sessionId)h.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{}SCt(n),CCt(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&&J(`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:h,fileHistorySnapshots:g,attributionSnapshots:_,contentReplacements:v,agentContentReplacements:y,contextCollapseCommits:b,contextCollapseSnapshot:x,leafUuids:T}}async function qCt(e){return V6(Y(en()??o8(Zt()),`${e}.jsonl`))}async function H6(e){let t=f8.get(e);if(t!==void 0)return t;if(f8.size>=u8){let e=f8.keys().next().value;e!==void 0&&f8.delete(e)}let n=(async()=>{let{messages:t}=await qCt(e);return new Set(t.keys())})();return f8.set(e,n),n}function U6(){return f8}function W6(){f8.clear()}async function JCt(e,t){return(await H6(e)).has(t)}async function G6(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 qCt(e);if(t.size===0)return null;let p=U6();p.has(e)||p.set(e,Promise.resolve(new Set(t.keys())));let m=w6(t.values(),e=>!e.isSidechain);if(!m)return null;let h=T6(t,m),g=n.get(m.uuid),_=r.get(m.sessionId),v=i.get(m.sessionId),y=a.get(e);return{...A6(h,0,g,_,D6(s,h),v,i6(e),O6(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 K6(e){let t=await j6(e),{logs:n}=await n8(t,0,t.length),r=Wu(n);return r.forEach((e,t)=>{e.value=t}),r}async function YCt(e,t){return t?.skipIndex?XCt(e):(await q6(e,t?.initialEnrichCount??p8)).logs}async function XCt(e){let t=n6(),n;try{n=await uu(t,{withFileTypes:!0})}catch{return[]}let r=n.filter(e=>e.isDirectory()).map(e=>Y(t,e.name)),i=(await Promise.all(r.map(t=>awt(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=Wu([...a.values()]);return o.forEach((e,t)=>{e.value=t}),o}async function q6(e,t=p8){let n=n6(),r;try{r=await uu(n,{withFileTypes:!0})}catch{return{logs:[],allStatLogs:[],nextIndex:0}}let i=r.filter(e=>e.isDirectory()).map(e=>Y(n,e.name)),a=[];for(let t of i)a.push(...await t8(t,e));let o=lwt(a),{logs:s,nextIndex:c}=await n8(o,0,t);return s.forEach((e,t)=>{e.value=t}),{logs:s,allStatLogs:o,nextIndex:c}}async function ZCt(e,t,n=p8){return(await J6(e,t,n)).logs}async function J6(e,t,n=p8){U(`/resume: loading sessions for cwd=${Zt()}, worktrees=[${e.join(`, `)}]`);let r=await QCt(e,t);U(`/resume: found ${r.length} session files on disk`);let{logs:i,nextIndex:a}=await n8(r,0,n);return i.forEach((e,t)=>{e.value=t}),{logs:i,allStatLogs:r,nextIndex:a}}async function QCt(e,t){let n=n6();if(e.length<=1){let e=Zt();return t8(o8(e),void 0,e)}let r=process.platform===`win32`,i=e.map(e=>{let t=Ta(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 uu(n,{withFileTypes:!0})}catch(e){return U(`Failed to read projects dir ${n}, falling back to current project: ${e}`),t8(o8(Zt()),t,Zt())}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 t8(Y(n,e.name),void 0,r));break}}}return lwt(a)}async function Y6(e){let t=s6(e);try{let{messages:n,agentContentReplacements:r}=await V6(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=w6(i,e=>!a.has(e.uuid));return o?{messages:T6(n,o).filter(t=>t.agentId===e).map(({isSidechain:e,parentUuid:t,...n})=>n),contentReplacements:r.get(e)??[]}:null}catch{return null}}function $Ct(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 $n(t)}async function X6(e){let t=await Promise.all(e.map(async e=>{try{let t=await Y6(OB(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 ewt(){let e=Y(en()??o8(Zt()),ln(),`subagents`),t;try{t=await uu(e,{withFileTypes:!0})}catch{return{}}return X6(t.filter(e=>e.isFile()&&e.name.startsWith(`agent-`)&&e.name.endsWith(`.jsonl`)).map(e=>e.name.slice(6,-6)))}function Z6(e){return e.type===`progress`?!1:e.type===`attachment`&&m6()!==`ant`?!!(e.attachment.type===`hook_additional_context`&&m(process.env.CLAUDE_CODE_SAVE_HOOK_ADDITIONAL_CONTEXT)):!0}function twt(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 nwt(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 Q6(e,t=e){let n=e.filter(Z6);return m6()===`ant`?n:nwt(n,twt(t))}async function rwt(e){return(await K6())[e]||null}async function iwt(e){try{let{messages:t}=await V6(r6()),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 $6(e){let t=new Map,n;try{n=await uu(e,{withFileTypes:!0})}catch{return t}let r=[];for(let t of n){if(!t.isFile()||!t.name.endsWith(`.jsonl`))continue;let n=l2e(wl(t.name,`.jsonl`));n&&r.push({sessionId:n,filePath:Y(e,t.name)})}return await Promise.all(r.map(async({sessionId:e,filePath:n})=>{try{let r=await mu(n);t.set(e,{path:n,mtime:r.mtime.getTime(),ctime:r.birthtime.getTime(),size:r.size})}catch{U(`Failed to stat session file: ${n}`)}})),t}async function e8(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 V6(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 _=T6(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:C6(_),fullPath:e,value:0,created:new Date(x.timestamp),modified:new Date(g.timestamp),firstPrompt:x6(_),messageCount:k6(_),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:D6(p,_),attributionSnapshots:O6(m,_),contentReplacements:h.get(S)??[]})}return y}async function awt(e,t){let n=await $6(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 e8(e.path);i.push(...t)}catch{U(`Failed to load session file: ${e.path}`)}return i}async function owt(e,t,n){let{head:r,tail:i}=await Hie(e,t,n);if(!r)return{firstPrompt:``,isSidechain:!1};let a=r.includes(`"isSidechain":true`)||r.includes(`"isSidechain": true`),o=Sa(r,`cwd`),s=Sa(r,`agentSetting`),c=Ea(i,`lastPrompt`)||swt(r)||cwt(r,`content`,200)||cwt(r,`text`,200)||``,l=Ea(i,`customTitle`)??Ea(r,`customTitle`)??Ea(i,`aiTitle`)??Ea(r,`aiTitle`),u=Ea(i,`summary`),d=Ea(i,`tag`),f=Ea(i,`gitBranch`)??Sa(r,`gitBranch`),p=Ea(i,`prUrl`),m=Ea(i,`prRepository`),h,g=Ea(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 swt(e){let t=0,n=!1,r=``;for(;t<e.length;){let i=e.indexOf(`
|
|
3173
|
-
`,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=Nn(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=j4(t,ea);if(i){let e=i.replace(/^\//,``),n=j4(t,`command-args`)?.trim()||``;if(J3().has(e)||!n){r||(r=i);continue}return n?`${i} ${n}`:i}let a=j4(t,`bash-input`);if(a)return`! ${a}`;if(r8.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 cwt(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 lwt(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 Wu([...t.values()]).map((e,t)=>({...e,value:t}))}async function t8(e,t,n){let r=[...(await $6(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=Wu(i);return a.forEach((e,t)=>{e.value=t}),a}async function uwt(e,t){if(!e.isLite||!e.fullPath)return e;let n=await owt(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?(U(`Session ${e.sessionId} filtered from /resume: isSidechain=true`),null):r}async function n8(e,t,n){let r=[],i=Buffer.alloc(Oa),a=t;for(;a<e.length&&r.length<n;){let t=e[a];a++;let n=await uwt(t,i);n&&r.push(n)}let o=a-t,s=o-r.length;return s>0&&U(`/resume: enriched ${o} sessions, ${s} filtered out, ${r.length} visible (${e.length-a} remaining on disk)`),{logs:r,nextIndex:a}}var dwt,fwt,r8,pwt,i8,a8,o8,s8,c8,l8,u8,mwt,d8,hwt,f8,p8,m8=n((()=>{d(),Na(),Gt(),$3(),sa(),cZ(),Dq(),kB(),Ide(),Tr(),Xn(),D1(),Sn(),W(),Pi(),h(),Mn(),Ua(),Un(),XSt(),Bi(),YJ(),ja(),oa(),p3(),Wr(),wa(),Yr(),Zn(),KG(),b(),dwt=typeof MACRO<`u`?`0.0.
|
|
3173
|
+
`,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=Nn(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=j4(t,ea);if(i){let e=i.replace(/^\//,``),n=j4(t,`command-args`)?.trim()||``;if(J3().has(e)||!n){r||(r=i);continue}return n?`${i} ${n}`:i}let a=j4(t,`bash-input`);if(a)return`! ${a}`;if(r8.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 cwt(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 lwt(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 Wu([...t.values()]).map((e,t)=>({...e,value:t}))}async function t8(e,t,n){let r=[...(await $6(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=Wu(i);return a.forEach((e,t)=>{e.value=t}),a}async function uwt(e,t){if(!e.isLite||!e.fullPath)return e;let n=await owt(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?(U(`Session ${e.sessionId} filtered from /resume: isSidechain=true`),null):r}async function n8(e,t,n){let r=[],i=Buffer.alloc(Oa),a=t;for(;a<e.length&&r.length<n;){let t=e[a];a++;let n=await uwt(t,i);n&&r.push(n)}let o=a-t,s=o-r.length;return s>0&&U(`/resume: enriched ${o} sessions, ${s} filtered out, ${r.length} visible (${e.length-a} remaining on disk)`),{logs:r,nextIndex:a}}var dwt,fwt,r8,pwt,i8,a8,o8,s8,c8,l8,u8,mwt,d8,hwt,f8,p8,m8=n((()=>{d(),Na(),Gt(),$3(),sa(),cZ(),Dq(),kB(),Ide(),Tr(),Xn(),D1(),Sn(),W(),Pi(),h(),Mn(),Ua(),Un(),XSt(),Bi(),YJ(),ja(),oa(),p3(),Wr(),wa(),Yr(),Zn(),KG(),b(),dwt=typeof MACRO<`u`?`0.0.17`:`unknown`,fwt=50*1024*1024,r8=/^(?:\s*<[a-z][\w-]*[\s>]|\[Request interrupted by user[^\]]*\])/,pwt=new Set([`bash_progress`,`powershell_progress`,`mcp_progress`,`sleep_progress`]),i8=50*1024*1024,a8=new Map,o8=u(e=>Y(n6(),Ta(e))),s8=null,c8=!1,l8=10,u8=200,mwt=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,`remoteIngressUrl`,null),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 ru(e,t,{mode:384})}catch{await su(Tl(e),{recursive:!0,mode:448}),await ru(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=`${V(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=ln();if(!t)return;let n=kCt(this.sessionFile).split(`
|
|
3174
3174
|
`);if(!e){let e=n.findLast(e=>e.startsWith(`{"type":"custom-title"`));if(e){let t=Ea(e,`customTitle`);t!==void 0&&(this.currentSessionTitle=t||void 0)}}let r=n.findLast(e=>e.startsWith(`{"type":"tag"`));if(r){let e=Ea(r,`tag`);e!==void 0&&(this.currentSessionTag=e||void 0)}this.currentSessionLastPrompt&&M6(this.sessionFile,{type:`last-prompt`,lastPrompt:this.currentSessionLastPrompt,sessionId:t}),this.currentSessionTitle&&M6(this.sessionFile,{type:`custom-title`,customTitle:this.currentSessionTitle,sessionId:t}),this.currentSessionTag&&M6(this.sessionFile,{type:`tag`,tag:this.currentSessionTag,sessionId:t}),this.currentSessionAgentName&&M6(this.sessionFile,{type:`agent-name`,agentName:this.currentSessionAgentName,sessionId:t}),this.currentSessionAgentColor&&M6(this.sessionFile,{type:`agent-color`,agentColor:this.currentSessionAgentColor,sessionId:t}),this.currentSessionAgentSetting&&M6(this.sessionFile,{type:`agent-setting`,agentSetting:this.currentSessionAgentSetting,sessionId:t}),this.currentSessionMode&&M6(this.sessionFile,{type:`mode`,mode:this.currentSessionMode,sessionId:t}),this.currentSessionGoal&&M6(this.sessionFile,{type:`goal`,sessionId:t,state:this.currentSessionGoal,timestamp:new Date().toISOString()}),this.currentSessionWorktree!==void 0&&M6(this.sessionFile,{type:`worktree-state`,worktreeSession:this.currentSessionWorktree,sessionId:t}),this.currentSessionPrNumber!==void 0&&this.currentSessionPrUrl&&this.currentSessionPrRepository&&M6(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 cu(this.sessionFile,`r+`);try{let{size:r}=await n.stat();if(t=r,r===0)return;let i=Math.min(r,Oa),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>fwt){U(`Skipping tombstone removal: session file too large (${Ha(t)})`,{level:`warn`});return}let r=(await lu(this.sessionFile,{encoding:`utf-8`})).split(`
|
|
3175
3175
|
`).filter(t=>{if(!t.trim())return!0;try{return Nn(t).uuid!==e}catch{return!0}});await _u(this.sessionFile,r.join(`
|
|
3176
|
-
`),{encoding:`utf8`})}catch{}})}shouldSkipPersistence(){let e=m(process.env.TEST_ENABLE_SESSION_PERSISTENCE);return p6()===`test`&&!e||qr()?.cleanupPeriodDays===0||Ot()||m(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 Li()}catch{o=void 0}let s=ln(),c=sn().get(s);for(let r of e){let e=e3(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`?ine()??void 0:void 0,agentId:n,...r,userType:m6(),entrypoint:aCt(),cwd:Cn(),sessionId:s,timestamp:new Date().toISOString(),version:dwt,gitBranch:o,slug:c};await this.appendEntry(u),t6(r)&&(a=r.uuid)}if(!t){let t=S6(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:ln(),agentId:t,replacements:e};await this.appendEntry(n)})}async appendEntry(e,t=ln()){if(this.shouldSkipPersistence())return;let n=t===ln(),r;if(n){if(this.sessionFile===null){this.pendingEntries.push(e);return}r=this.sessionFile}else{let e=await this.getExistingSessionFile(t);if(!e){q(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?s6(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 H6(t);if(e.type===`queue-operation`)this.enqueueWrite(r,e);else{let i=e.isSidechain&&e.agentId!==void 0,a=i?s6(OB(e.agentId)):r,o=!n.has(e.uuid);(i||o)&&(this.enqueueWrite(a,e),i||(n.add(e.uuid),e6(e)&&await this.persistToRemote(t,e)))}}}ensureCurrentSessionFile(){return this.sessionFile===null&&(this.sessionFile=r6()),this.sessionFile}async getExistingSessionFile(e){let t=this.existingSessionFiles.get(e);if(t)return t;let n=i6(e);try{if(await mu(n),this.existingSessionFiles.size>=u8){let e=this.existingSessionFiles.keys().next().value;e!==void 0&&this.existingSessionFiles.delete(e)}return this.existingSessionFiles.set(e,n),n}catch(e){if(In(e))return null;throw e}}async persistToRemote(e,t){if(!F9e()){if(this.internalEventWriter){try{await this.internalEventWriter(`transcript`,t,{...e3(t)&&{isCompaction:!0},...t.agentId&&{agentId:t.agentId}})}catch{J(`tengu_session_persistence_failed`,{}),U(`Failed to write transcript as internal event`)}return}!m(process.env.ENABLE_SESSION_PERSISTENCE)||!this.remoteIngressUrl||await Xnt(e,t,this.remoteIngressUrl)||(J(`tengu_session_persistence_failed`,{}),UJ(1,`other`))}}setRemoteIngressUrl(e){this.remoteIngressUrl=e,U(`Remote persistence enabled with URL: ${e}`),e&&(this.FLUSH_INTERVAL_MS=l8)}setInternalEventWriter(e){this.internalEventWriter=e,U(`CCR v2 internal event writer registered for transcript persistence`),this.FLUSH_INTERVAL_MS=l8}setInternalEventReader(e){this.internalEventReader=e,U(`CCR v2 internal event reader registered for session resume`)}setInternalSubagentEventReader(e){this.internalSubagentEventReader=e,U(`CCR v2 subagent event reader registered for session resume`)}getInternalEventReader(){return this.internalEventReader}getInternalSubagentEventReader(){return this.internalSubagentEventReader}},d8=[`"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)),hwt=25,f8=new Map,p8=50}));function h8(e){return e.toLowerCase()}function gwt(e){let t=oi(e),n=h8(t),r=[{dir:oi(Y(Zt(),`.workmate`,`skills`)),prefix:`/.workmate/skills/`},{dir:oi(Y(yl(),`.workmate`,`skills`)),prefix:`~/.workmate/skills/`}];for(let{dir:e,prefix:i}of r){let r=h8(e);for(let a of[Nl,`/`])if(n.startsWith(r+a.toLowerCase())){let n=t.slice(e.length+a.length),r=n.indexOf(`/`),o=Nl===`\\`?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 _wt(e,t){if(_a()===`windows`){let n=xa(e),r=xa(t);return Al.relative(n,r)}return Al.relative(e,t)}function vwt(e){return _a()===`windows`?xa(e):e}function ywt(){return ai.map(e=>li(e)).filter(e=>e!==void 0)}function bwt(e){let t=h8(oi(e));return t.endsWith(`${Nl}.workmate${Nl}settings.json`)||t.endsWith(`${Nl}.workmate${Nl}settings.local.json`)?!0:ywt().some(e=>h8(e)===t)}function xwt(e){if(bwt(e))return!0;let t=Y(Zt(),`.workmate`,`commands`),n=Y(Zt(),`.workmate`,`agents`),r=Y(Zt(),`.workmate`,`skills`);return w8(e,t)||w8(e,n)||w8(e,r)}function Swt(e){let t=Y(Qd(),Yd()),n=Ol(e);return n.startsWith(t)&&n.endsWith(`.md`)}function g8(){return Y(o8(Cn()),ln(),`session-memory`)+Nl}function _8(){return Y(g8(),`summary.md`)}function Cwt(e){return Ol(e).startsWith(g8())}function wwt(e){let t=o8(Cn()),n=Ol(e);return n===t||n.startsWith(t+Nl)}function v8(){return!1}function Twt(){return _a()===`windows`?`claude`:`claude-${process.getuid?.()??0}`}function y8(){return Y(F8(),Ta(Zt()))+Nl}function b8(){return Y(y8(),ln(),`scratchpad`)}async function Ewt(){if(!v8())throw Error(`Scratchpad directory feature is not enabled`);let e=G(),t=b8();return await e.mkdir(t,{mode:448}),t}function Dwt(e){if(!v8())return!1;let t=b8(),n=Ol(e);return n===t||n.startsWith(t+Nl)}function Owt(e){let t=oi(e).split(Nl),n=t.at(-1);if(e.startsWith(`\\\\`)||e.startsWith(`//`))return!0;for(let e=0;e<t.length;e++){let n=t[e],r=h8(n);for(let n of Iwt)if(r===h8(n)){if(n===`.workmate`){let n=t[e+1];if(n&&h8(n)===`worktrees`)break}return!0}}if(n){let e=h8(n);if(Fwt.some(t=>h8(t)===e))return!0}return!1}function kwt(e){return!!((_a()===`windows`||_a()===`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)||rg(e))}function x8(e,t){let n=t??Hn(e);for(let t of n)if(kwt(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(xwt(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(Owt(t))return{safe:!1,message:`Work Mate requested permissions to edit ${e} which is a sensitive file.`,classifierApprovable:!0};return{safe:!0}}function S8(e){return new Set([Zt(),...e.additionalWorkingDirectories.keys()])}function C8(e,t,n){let r=n??Hn(e),i=Array.from(S8(t)).flatMap(e=>Lwt(e));return r.every(e=>i.some(t=>w8(e,t)))}function w8(e,t){let n=oi(e),r=oi(t),i=n.replace(/^\/private\/var\//,`/var/`).replace(/^\/private\/tmp(\/|$)/,`/tmp$1`),a=r.replace(/^\/private\/var\//,`/var/`).replace(/^\/private\/tmp(\/|$)/,`/tmp$1`),o=h8(i),s=_wt(h8(a),o);return s===``||!zr(s)&&!Al.isAbsolute(s)}function Awt(e){switch(e){case`cliArg`:case`command`:case`session`:return oi(Zt());case`userSettings`:case`policySettings`:case`projectSettings`:case`localSettings`:case`flagSettings`:return ei(e)}}function T8(e){return Al.join(P8,e)}function jwt({patternRoot:e,pattern:t,rootPath:n}){let r=Al.join(e,t);if(e===n)return T8(t);if(r.startsWith(`${n}${P8}`))return T8(r.slice(n.length));{let r=Al.relative(n,e);return!r||r.startsWith(`..${P8}`)||r===`..`?null:T8(Al.join(r,t))}}function E8(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=jwt({patternRoot:r,pattern:e,rootPath:t});i&&n.add(i)}return Array.from(n)}function D8(e){let t=Nwt(e,`read`,`deny`),n=new Map;for(let[e,r]of t.entries())n.set(e,Array.from(r.keys()));return n}function Mwt(e,t){if(e.startsWith(`${P8}${P8}`)){let t=e.slice(1);if(_a()===`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:P8}}else if(e.startsWith(`~${P8}`))return{relativePattern:e.slice(1),root:yl().normalize(`NFC`)};else if(e.startsWith(P8))return{relativePattern:e,root:Awt(t)};let n=e;return e.startsWith(`.${P8}`)&&(n=e.slice(2)),{relativePattern:n,root:null}}function Nwt(e,t,n){let r=E9(e,(()=>{switch(t){case`edit`:return ks;case`read`:return xs}})(),n),i=new Map;for(let[e,t]of r.entries()){let{relativePattern:n,root:r}=Mwt(e,t.source),a=i.get(r);a===void 0&&(a=new Map,i.set(r,a)),a.set(n,t)}return i}function O8(e,t,n,r){let i=oi(e);_a()===`windows`&&i.includes(`\\`)&&(i=xa(i));let a=Nwt(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,Pwt.default)().add(n),a=_wt(e??Cn(),i??Cn());if(a.startsWith(`..${P8}`)||!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 k8(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=Hn(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(kwt(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=O8(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=O8(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=A8(e,t,n,i);if(a.behavior===`allow`)return a;if(C8(r,n,i))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`mode`,mode:`default`}};let o=N8(oi(r),t);if(o.behavior!==`passthrough`)return o;let s=O8(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:j8(r,`read`,n,i),decisionReason:{type:`workingDir`,reason:`Path is outside allowed working directories`}}}function A8(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??Hn(i);for(let e of a){let t=O8(e,n,`edit`,`deny`);if(t)return{behavior:`deny`,message:`Permission to edit ${i} has been denied.`,decisionReason:{type:`rule`,rule:t}}}let o=M8(oi(i),t);if(o.behavior!==`passthrough`)return o;let s=O8(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=x8(i,a);if(!c.safe){let e=gwt(i),t=e?[{type:`addRules`,rules:[{toolName:ks,ruleContent:e.pattern}],behavior:`allow`,destination:`session`}]:j8(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=O8(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=C8(i,n,a);if(n.mode===`acceptEdits`&&l)return{behavior:`allow`,updatedInput:t,decisionReason:{type:`mode`,mode:n.mode}};let u=O8(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:j8(i,`write`,n,a),decisionReason:l?void 0:{type:`workingDir`,reason:`Path is outside allowed working directories`}}}function j8(e,t,n,r){let i=!C8(e,n,r);if(t===`read`&&i)return Hn(ui(e)).map(e=>xB(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=Hn(ui(e));t.push({type:`addDirectories`,directories:n,destination:`session`})}return t}return a?[{type:`setMode`,mode:`acceptEdits`,destination:`session`}]:[]}function M8(e,t){let n=Ol(e);if(Swt(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Plan files for current session are allowed for writing`}};if(Dwt(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=Y(p(),`jobs`),i=Hn(r).map(Ol),a=Hn(n).map(Ol);if(i.every(e=>a.some(t=>e.startsWith(t+Nl)))&&Hn(e).every(e=>{let t=Ol(e);return i.some(e=>t===e||t.startsWith(e+Nl))}))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Job directory files for current job are allowed for writing`}}}return Ud(n)?{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Agent memory files are allowed for writing`}}:!Qre()&&wi(n)?{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`auto memory files are allowed for writing`}}:h8(n)===h8(Y(Zt(),`.workmate`,`launch.json`))?{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Preview launch config is allowed for writing`}}:{behavior:`passthrough`,message:``}}function N8(e,t){let n=Ol(e);if(Cwt(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Session memory files are allowed for reading`}};if(wwt(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Project directory files are allowed for reading`}};if(Swt(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Plan files for current session are allowed for reading`}};let r=Zv(),i=r.endsWith(Nl)?r:r+Nl;if(n===r||n.startsWith(i))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Tool result files are allowed for reading`}};if(Dwt(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Scratchpad files for current session are allowed for reading`}};let a=y8();if(n.startsWith(a))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Project temp directory files are allowed for reading`}};if(Ud(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Agent memory files are allowed for reading`}};if(wi(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`auto memory files are allowed for reading`}};let o=Y(p(),`tasks`)+Nl;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=Y(p(),`teams`)+Nl;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=I8()+Nl;return n.startsWith(c)?{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Bundled skill reference files are allowed for reading`}}:{behavior:`passthrough`,message:``}}var Pwt,Fwt,Iwt,P8,F8,I8,Lwt,L8=n((()=>{Pwt=r(ce(),1),d(),Ci(),Gd(),Rs(),Gt(),Bs(),Sn(),h(),Un(),Wr(),$d(),va(),m8(),ti(),Yr(),_g(),sy(),ba(),SB(),A9(),Fwt=[`.gitconfig`,`.gitmodules`,`.bashrc`,`.bash_profile`,`.zshrc`,`.zprofile`,`.profile`,`.ripgreprc`,`.mcp.json`,`.workmate.json`],Iwt=[`.git`,`.vscode`,`.idea`,`.workmate`],P8=Al.sep,F8=u(function(){let e=process.env.CLAUDE_CODE_TMPDIR||Sl(),t=G(),n=e;try{n=t.realpathSync(e)}catch{}return Y(n,Twt())+Nl}),I8=u(function(){let e=eu(16).toString(`hex`);return Y(F8(),`bundled-skills`,`0.0.16`,e)}),Lwt=u(Hn)}));function R8(){return q8===void 0&&(q8=Y(y8(),ln(),`tasks`)),q8}async function z8(){await su(R8(),{recursive:!0})}function B8(e){return Y(R8(),`${e}.output`)}function V8(e){return J8.add(e),e.finally(()=>J8.delete(e)).catch(()=>{}),e}async function Rwt(){for(;;){try{for(D(X8,this)||(await z8(),k(X8,this,await cu(D(Y8,this),process.platform===`win32`?`a`:Wl.O_WRONLY|Wl.O_APPEND|Wl.O_CREAT|W8)));await S(n5,this,zwt).call(this),D(Z8,this).length!==0;);}finally{if(D(X8,this)){let e=D(X8,this);k(X8,this,null),await e.close()}}if(!D(Z8,this).length)break}}function zwt(){return D(X8,this).appendFile(S(n5,this,Bwt).call(this))}function Bwt(){let e=D(Z8,this).splice(0,D(Z8,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 Vwt(){try{await S(n5,this,Rwt).call(this)}catch(e){if(q(e),D(Z8,this).length>0)try{await S(n5,this,Rwt).call(this)}catch(e){q(e)}}finally{let e=D(t5,this);k(e5,this,null),k(t5,this,null),e()}}function Hwt(e){let t=i5.get(e);return t||(t=new r5(e),i5.set(e,t)),t}function Uwt(e,t){Hwt(e).append(t)}function H8(e){return V8((async()=>{let t=i5.get(e);t&&(await t.flush(),i5.delete(e))})())}async function Wwt(e,t,n=G8){try{let r=await Sne(B8(e),t,n);return r?{content:r.content,newOffset:t+r.bytesRead}:{content:``,newOffset:t}}catch(e){return Dn(e)===`ENOENT`||q(e),{content:``,newOffset:t}}}async function Gwt(e,t=G8){try{let{content:n,bytesTotal:r,bytesRead:i}=await Vn(B8(e),t);return r>i?`[${Math.round((r-i)/1024)}KB of earlier output omitted]\n${n}`:n}catch(e){return Dn(e)===`ENOENT`||q(e),``}}function Kwt(e){return V8((async()=>{await z8();let t=B8(e);return await(await cu(t,process.platform===`win32`?`wx`:Wl.O_WRONLY|Wl.O_CREAT|Wl.O_EXCL|W8)).close(),t})())}function U8(e,t){return V8((async()=>{try{await z8();let n=B8(e);try{await hu(t,n)}catch{await gu(n),await hu(t,n)}return n}catch(t){return q(t),Kwt(e)}})())}var W8,G8,K8,q8,J8,Y8,X8,Z8,Q8,$8,e5,t5,n5,r5,i5,a5=n((()=>{Gt(),Mn(),Un(),oa(),L8(),A(),C(),T(),w(),E(),W8=Wl.O_NOFOLLOW??0,G8=8*1024*1024,K8=5*1024*1024*1024,J8=new Set,Y8=new WeakMap,X8=new WeakMap,Z8=new WeakMap,Q8=new WeakMap,$8=new WeakMap,e5=new WeakMap,t5=new WeakMap,n5=new WeakSet,r5=class{constructor(e){ee(this,n5),O(this,Y8,void 0),O(this,X8,null),O(this,Z8,[]),O(this,Q8,0),O(this,$8,!1),O(this,e5,null),O(this,t5,null),k(Y8,this,B8(e))}append(e){D($8,this)||(k(Q8,this,D(Q8,this)+e.length),D(Q8,this)>5368709120?(k($8,this,!0),D(Z8,this).push(`
|
|
3176
|
+
`),{encoding:`utf8`})}catch{}})}shouldSkipPersistence(){let e=m(process.env.TEST_ENABLE_SESSION_PERSISTENCE);return p6()===`test`&&!e||qr()?.cleanupPeriodDays===0||Ot()||m(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 Li()}catch{o=void 0}let s=ln(),c=sn().get(s);for(let r of e){let e=e3(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`?ine()??void 0:void 0,agentId:n,...r,userType:m6(),entrypoint:aCt(),cwd:Cn(),sessionId:s,timestamp:new Date().toISOString(),version:dwt,gitBranch:o,slug:c};await this.appendEntry(u),t6(r)&&(a=r.uuid)}if(!t){let t=S6(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:ln(),agentId:t,replacements:e};await this.appendEntry(n)})}async appendEntry(e,t=ln()){if(this.shouldSkipPersistence())return;let n=t===ln(),r;if(n){if(this.sessionFile===null){this.pendingEntries.push(e);return}r=this.sessionFile}else{let e=await this.getExistingSessionFile(t);if(!e){q(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?s6(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 H6(t);if(e.type===`queue-operation`)this.enqueueWrite(r,e);else{let i=e.isSidechain&&e.agentId!==void 0,a=i?s6(OB(e.agentId)):r,o=!n.has(e.uuid);(i||o)&&(this.enqueueWrite(a,e),i||(n.add(e.uuid),e6(e)&&await this.persistToRemote(t,e)))}}}ensureCurrentSessionFile(){return this.sessionFile===null&&(this.sessionFile=r6()),this.sessionFile}async getExistingSessionFile(e){let t=this.existingSessionFiles.get(e);if(t)return t;let n=i6(e);try{if(await mu(n),this.existingSessionFiles.size>=u8){let e=this.existingSessionFiles.keys().next().value;e!==void 0&&this.existingSessionFiles.delete(e)}return this.existingSessionFiles.set(e,n),n}catch(e){if(In(e))return null;throw e}}async persistToRemote(e,t){if(!F9e()){if(this.internalEventWriter){try{await this.internalEventWriter(`transcript`,t,{...e3(t)&&{isCompaction:!0},...t.agentId&&{agentId:t.agentId}})}catch{J(`tengu_session_persistence_failed`,{}),U(`Failed to write transcript as internal event`)}return}!m(process.env.ENABLE_SESSION_PERSISTENCE)||!this.remoteIngressUrl||await Xnt(e,t,this.remoteIngressUrl)||(J(`tengu_session_persistence_failed`,{}),UJ(1,`other`))}}setRemoteIngressUrl(e){this.remoteIngressUrl=e,U(`Remote persistence enabled with URL: ${e}`),e&&(this.FLUSH_INTERVAL_MS=l8)}setInternalEventWriter(e){this.internalEventWriter=e,U(`CCR v2 internal event writer registered for transcript persistence`),this.FLUSH_INTERVAL_MS=l8}setInternalEventReader(e){this.internalEventReader=e,U(`CCR v2 internal event reader registered for session resume`)}setInternalSubagentEventReader(e){this.internalSubagentEventReader=e,U(`CCR v2 subagent event reader registered for session resume`)}getInternalEventReader(){return this.internalEventReader}getInternalSubagentEventReader(){return this.internalSubagentEventReader}},d8=[`"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)),hwt=25,f8=new Map,p8=50}));function h8(e){return e.toLowerCase()}function gwt(e){let t=oi(e),n=h8(t),r=[{dir:oi(Y(Zt(),`.workmate`,`skills`)),prefix:`/.workmate/skills/`},{dir:oi(Y(yl(),`.workmate`,`skills`)),prefix:`~/.workmate/skills/`}];for(let{dir:e,prefix:i}of r){let r=h8(e);for(let a of[Nl,`/`])if(n.startsWith(r+a.toLowerCase())){let n=t.slice(e.length+a.length),r=n.indexOf(`/`),o=Nl===`\\`?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 _wt(e,t){if(_a()===`windows`){let n=xa(e),r=xa(t);return Al.relative(n,r)}return Al.relative(e,t)}function vwt(e){return _a()===`windows`?xa(e):e}function ywt(){return ai.map(e=>li(e)).filter(e=>e!==void 0)}function bwt(e){let t=h8(oi(e));return t.endsWith(`${Nl}.workmate${Nl}settings.json`)||t.endsWith(`${Nl}.workmate${Nl}settings.local.json`)?!0:ywt().some(e=>h8(e)===t)}function xwt(e){if(bwt(e))return!0;let t=Y(Zt(),`.workmate`,`commands`),n=Y(Zt(),`.workmate`,`agents`),r=Y(Zt(),`.workmate`,`skills`);return w8(e,t)||w8(e,n)||w8(e,r)}function Swt(e){let t=Y(Qd(),Yd()),n=Ol(e);return n.startsWith(t)&&n.endsWith(`.md`)}function g8(){return Y(o8(Cn()),ln(),`session-memory`)+Nl}function _8(){return Y(g8(),`summary.md`)}function Cwt(e){return Ol(e).startsWith(g8())}function wwt(e){let t=o8(Cn()),n=Ol(e);return n===t||n.startsWith(t+Nl)}function v8(){return!1}function Twt(){return _a()===`windows`?`claude`:`claude-${process.getuid?.()??0}`}function y8(){return Y(F8(),Ta(Zt()))+Nl}function b8(){return Y(y8(),ln(),`scratchpad`)}async function Ewt(){if(!v8())throw Error(`Scratchpad directory feature is not enabled`);let e=G(),t=b8();return await e.mkdir(t,{mode:448}),t}function Dwt(e){if(!v8())return!1;let t=b8(),n=Ol(e);return n===t||n.startsWith(t+Nl)}function Owt(e){let t=oi(e).split(Nl),n=t.at(-1);if(e.startsWith(`\\\\`)||e.startsWith(`//`))return!0;for(let e=0;e<t.length;e++){let n=t[e],r=h8(n);for(let n of Iwt)if(r===h8(n)){if(n===`.workmate`){let n=t[e+1];if(n&&h8(n)===`worktrees`)break}return!0}}if(n){let e=h8(n);if(Fwt.some(t=>h8(t)===e))return!0}return!1}function kwt(e){return!!((_a()===`windows`||_a()===`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)||rg(e))}function x8(e,t){let n=t??Hn(e);for(let t of n)if(kwt(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(xwt(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(Owt(t))return{safe:!1,message:`Work Mate requested permissions to edit ${e} which is a sensitive file.`,classifierApprovable:!0};return{safe:!0}}function S8(e){return new Set([Zt(),...e.additionalWorkingDirectories.keys()])}function C8(e,t,n){let r=n??Hn(e),i=Array.from(S8(t)).flatMap(e=>Lwt(e));return r.every(e=>i.some(t=>w8(e,t)))}function w8(e,t){let n=oi(e),r=oi(t),i=n.replace(/^\/private\/var\//,`/var/`).replace(/^\/private\/tmp(\/|$)/,`/tmp$1`),a=r.replace(/^\/private\/var\//,`/var/`).replace(/^\/private\/tmp(\/|$)/,`/tmp$1`),o=h8(i),s=_wt(h8(a),o);return s===``||!zr(s)&&!Al.isAbsolute(s)}function Awt(e){switch(e){case`cliArg`:case`command`:case`session`:return oi(Zt());case`userSettings`:case`policySettings`:case`projectSettings`:case`localSettings`:case`flagSettings`:return ei(e)}}function T8(e){return Al.join(P8,e)}function jwt({patternRoot:e,pattern:t,rootPath:n}){let r=Al.join(e,t);if(e===n)return T8(t);if(r.startsWith(`${n}${P8}`))return T8(r.slice(n.length));{let r=Al.relative(n,e);return!r||r.startsWith(`..${P8}`)||r===`..`?null:T8(Al.join(r,t))}}function E8(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=jwt({patternRoot:r,pattern:e,rootPath:t});i&&n.add(i)}return Array.from(n)}function D8(e){let t=Nwt(e,`read`,`deny`),n=new Map;for(let[e,r]of t.entries())n.set(e,Array.from(r.keys()));return n}function Mwt(e,t){if(e.startsWith(`${P8}${P8}`)){let t=e.slice(1);if(_a()===`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:P8}}else if(e.startsWith(`~${P8}`))return{relativePattern:e.slice(1),root:yl().normalize(`NFC`)};else if(e.startsWith(P8))return{relativePattern:e,root:Awt(t)};let n=e;return e.startsWith(`.${P8}`)&&(n=e.slice(2)),{relativePattern:n,root:null}}function Nwt(e,t,n){let r=E9(e,(()=>{switch(t){case`edit`:return ks;case`read`:return xs}})(),n),i=new Map;for(let[e,t]of r.entries()){let{relativePattern:n,root:r}=Mwt(e,t.source),a=i.get(r);a===void 0&&(a=new Map,i.set(r,a)),a.set(n,t)}return i}function O8(e,t,n,r){let i=oi(e);_a()===`windows`&&i.includes(`\\`)&&(i=xa(i));let a=Nwt(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,Pwt.default)().add(n),a=_wt(e??Cn(),i??Cn());if(a.startsWith(`..${P8}`)||!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 k8(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=Hn(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(kwt(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=O8(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=O8(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=A8(e,t,n,i);if(a.behavior===`allow`)return a;if(C8(r,n,i))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`mode`,mode:`default`}};let o=N8(oi(r),t);if(o.behavior!==`passthrough`)return o;let s=O8(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:j8(r,`read`,n,i),decisionReason:{type:`workingDir`,reason:`Path is outside allowed working directories`}}}function A8(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??Hn(i);for(let e of a){let t=O8(e,n,`edit`,`deny`);if(t)return{behavior:`deny`,message:`Permission to edit ${i} has been denied.`,decisionReason:{type:`rule`,rule:t}}}let o=M8(oi(i),t);if(o.behavior!==`passthrough`)return o;let s=O8(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=x8(i,a);if(!c.safe){let e=gwt(i),t=e?[{type:`addRules`,rules:[{toolName:ks,ruleContent:e.pattern}],behavior:`allow`,destination:`session`}]:j8(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=O8(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=C8(i,n,a);if(n.mode===`acceptEdits`&&l)return{behavior:`allow`,updatedInput:t,decisionReason:{type:`mode`,mode:n.mode}};let u=O8(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:j8(i,`write`,n,a),decisionReason:l?void 0:{type:`workingDir`,reason:`Path is outside allowed working directories`}}}function j8(e,t,n,r){let i=!C8(e,n,r);if(t===`read`&&i)return Hn(ui(e)).map(e=>xB(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=Hn(ui(e));t.push({type:`addDirectories`,directories:n,destination:`session`})}return t}return a?[{type:`setMode`,mode:`acceptEdits`,destination:`session`}]:[]}function M8(e,t){let n=Ol(e);if(Swt(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Plan files for current session are allowed for writing`}};if(Dwt(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=Y(p(),`jobs`),i=Hn(r).map(Ol),a=Hn(n).map(Ol);if(i.every(e=>a.some(t=>e.startsWith(t+Nl)))&&Hn(e).every(e=>{let t=Ol(e);return i.some(e=>t===e||t.startsWith(e+Nl))}))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Job directory files for current job are allowed for writing`}}}return Ud(n)?{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Agent memory files are allowed for writing`}}:!Qre()&&wi(n)?{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`auto memory files are allowed for writing`}}:h8(n)===h8(Y(Zt(),`.workmate`,`launch.json`))?{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Preview launch config is allowed for writing`}}:{behavior:`passthrough`,message:``}}function N8(e,t){let n=Ol(e);if(Cwt(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Session memory files are allowed for reading`}};if(wwt(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Project directory files are allowed for reading`}};if(Swt(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Plan files for current session are allowed for reading`}};let r=Zv(),i=r.endsWith(Nl)?r:r+Nl;if(n===r||n.startsWith(i))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Tool result files are allowed for reading`}};if(Dwt(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Scratchpad files for current session are allowed for reading`}};let a=y8();if(n.startsWith(a))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Project temp directory files are allowed for reading`}};if(Ud(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Agent memory files are allowed for reading`}};if(wi(n))return{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`auto memory files are allowed for reading`}};let o=Y(p(),`tasks`)+Nl;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=Y(p(),`teams`)+Nl;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=I8()+Nl;return n.startsWith(c)?{behavior:`allow`,updatedInput:t,decisionReason:{type:`other`,reason:`Bundled skill reference files are allowed for reading`}}:{behavior:`passthrough`,message:``}}var Pwt,Fwt,Iwt,P8,F8,I8,Lwt,L8=n((()=>{Pwt=r(ce(),1),d(),Ci(),Gd(),Rs(),Gt(),Bs(),Sn(),h(),Un(),Wr(),$d(),va(),m8(),ti(),Yr(),_g(),sy(),ba(),SB(),A9(),Fwt=[`.gitconfig`,`.gitmodules`,`.bashrc`,`.bash_profile`,`.zshrc`,`.zprofile`,`.profile`,`.ripgreprc`,`.mcp.json`,`.workmate.json`],Iwt=[`.git`,`.vscode`,`.idea`,`.workmate`],P8=Al.sep,F8=u(function(){let e=process.env.CLAUDE_CODE_TMPDIR||Sl(),t=G(),n=e;try{n=t.realpathSync(e)}catch{}return Y(n,Twt())+Nl}),I8=u(function(){let e=eu(16).toString(`hex`);return Y(F8(),`bundled-skills`,`0.0.17`,e)}),Lwt=u(Hn)}));function R8(){return q8===void 0&&(q8=Y(y8(),ln(),`tasks`)),q8}async function z8(){await su(R8(),{recursive:!0})}function B8(e){return Y(R8(),`${e}.output`)}function V8(e){return J8.add(e),e.finally(()=>J8.delete(e)).catch(()=>{}),e}async function Rwt(){for(;;){try{for(D(X8,this)||(await z8(),k(X8,this,await cu(D(Y8,this),process.platform===`win32`?`a`:Wl.O_WRONLY|Wl.O_APPEND|Wl.O_CREAT|W8)));await S(n5,this,zwt).call(this),D(Z8,this).length!==0;);}finally{if(D(X8,this)){let e=D(X8,this);k(X8,this,null),await e.close()}}if(!D(Z8,this).length)break}}function zwt(){return D(X8,this).appendFile(S(n5,this,Bwt).call(this))}function Bwt(){let e=D(Z8,this).splice(0,D(Z8,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 Vwt(){try{await S(n5,this,Rwt).call(this)}catch(e){if(q(e),D(Z8,this).length>0)try{await S(n5,this,Rwt).call(this)}catch(e){q(e)}}finally{let e=D(t5,this);k(e5,this,null),k(t5,this,null),e()}}function Hwt(e){let t=i5.get(e);return t||(t=new r5(e),i5.set(e,t)),t}function Uwt(e,t){Hwt(e).append(t)}function H8(e){return V8((async()=>{let t=i5.get(e);t&&(await t.flush(),i5.delete(e))})())}async function Wwt(e,t,n=G8){try{let r=await Sne(B8(e),t,n);return r?{content:r.content,newOffset:t+r.bytesRead}:{content:``,newOffset:t}}catch(e){return Dn(e)===`ENOENT`||q(e),{content:``,newOffset:t}}}async function Gwt(e,t=G8){try{let{content:n,bytesTotal:r,bytesRead:i}=await Vn(B8(e),t);return r>i?`[${Math.round((r-i)/1024)}KB of earlier output omitted]\n${n}`:n}catch(e){return Dn(e)===`ENOENT`||q(e),``}}function Kwt(e){return V8((async()=>{await z8();let t=B8(e);return await(await cu(t,process.platform===`win32`?`wx`:Wl.O_WRONLY|Wl.O_CREAT|Wl.O_EXCL|W8)).close(),t})())}function U8(e,t){return V8((async()=>{try{await z8();let n=B8(e);try{await hu(t,n)}catch{await gu(n),await hu(t,n)}return n}catch(t){return q(t),Kwt(e)}})())}var W8,G8,K8,q8,J8,Y8,X8,Z8,Q8,$8,e5,t5,n5,r5,i5,a5=n((()=>{Gt(),Mn(),Un(),oa(),L8(),A(),C(),T(),w(),E(),W8=Wl.O_NOFOLLOW??0,G8=8*1024*1024,K8=5*1024*1024*1024,J8=new Set,Y8=new WeakMap,X8=new WeakMap,Z8=new WeakMap,Q8=new WeakMap,$8=new WeakMap,e5=new WeakMap,t5=new WeakMap,n5=new WeakSet,r5=class{constructor(e){ee(this,n5),O(this,Y8,void 0),O(this,X8,null),O(this,Z8,[]),O(this,Q8,0),O(this,$8,!1),O(this,e5,null),O(this,t5,null),k(Y8,this,B8(e))}append(e){D($8,this)||(k(Q8,this,D(Q8,this)+e.length),D(Q8,this)>5368709120?(k($8,this,!0),D(Z8,this).push(`
|
|
3177
3177
|
[output truncated: exceeded 5GB disk cap]
|
|
3178
3178
|
`)):D(Z8,this).push(e),D(e5,this)||(k(e5,this,new Promise(e=>{k(t5,this,e)})),V8(S(n5,this,Vwt).call(this))))}flush(){return D(e5,this)??Promise.resolve()}cancel(){D(Z8,this).length=0}},i5=new Map}));function qwt(e){return e===`completed`||e===`failed`||e===`killed`}function Jwt(e){return Ywt[e]??`x`}function o5(e){let t=Jwt(e),n=eu(8),r=t;for(let e=0;e<8;e++)r+=Xwt[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:B8(e),outputOffset:0,notified:!1}}var Ywt,Xwt,c5=n((()=>{a5(),Ywt={local_bash:`b`,local_agent:`a`,remote_agent:`r`,local_workflow:`w`,dream:`d`},Xwt=`0123456789abcdefghijklmnopqrstuvwxyz`}));function Zwt(e,t){return t?`${e} ${t}`:e}function Qwt(e){let t=typeof e==`string`?e:e.toString();D(_5,this)?D(g5,this).writeStderr(t):D(g5,this).writeStdout(t)}function $wt(e){D(N5,e)&&D(j5,e)?D(j5,e).call(e,e.background.bind(e)):S(L5,e,d5).call(e,p5)}function eTt(){D(A5,this).reason!==`interrupt`&&this.kill()}function tTt(e,t){let n=e??(t===`SIGTERM`?144:1);S(L5,this,l5).call(this,n)}function nTt(){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,rTt).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 rTt(){D(D5,this)&&(clearInterval(D(D5,this)),k(D5,this,null))}function iTt(){k(D5,this,setInterval(()=>{mu(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,rTt).call(this),S(L5,this,d5).call(this,f5))},()=>{})},dTt)),D(D5,this).unref()}function aTt(){k(I5,this,S(L5,this,eTt).bind(this)),D(A5,this).addEventListener(`abort`,D(I5,this),{once:!0}),D(T5,this).once(`exit`,S(L5,this,tTt).bind(this)),D(T5,this).once(`error`,S(L5,this,nTt).bind(this)),k(E5,this,setTimeout($wt,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,oTt).bind(this))})}async function oTt(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=Zwt(`Background command killed: output file exceeded 5GB`,t.stderr):e===p5&&(t.stderr=Zwt(`Command timed out after ${Ba(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,uTt.default)(D(T5,this).pid,`SIGKILL`),S(L5,this,l5).call(this,e??f5)}function sTt(e,t,n,r,i=!1,a=K8){return new fTt(e,t,n,r,i,a)}function cTt(e,t){return new pTt({backgroundTaskId:e,...t})}function lTt(e){let t=new I_(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 uTt,f5,p5,dTt,m5,h5,g5,_5,v5,y5,b5,x5,S5,C5,w5,T5,E5,D5,O5,k5,A5,j5,M5,N5,P5,F5,I5,L5,fTt,pTt,mTt=n((()=>{uTt=r(zfe(),1),c5(),Ua(),a5(),B_(),A(),C(),E(),T(),w(),b(),f5=137,p5=143,dTt=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,Qwt).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,fTt=class{constructor(e,t,n,r,i=!1,a=K8){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,aTt).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,iTt).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)}},pTt=class{constructor(e){x(this,`status`,`killed`),x(this,`result`,void 0),x(this,`taskOutput`,void 0),this.taskOutput=new I_(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,hTt=n((()=>{_t(),vt(),R5=gt(()=>ht.enum([`allow`,`deny`,`ask`])),z5=gt(()=>ht.object({toolName:ht.string(),ruleContent:ht.string().optional()}))})),B5,V5,gTt=n((()=>{_t(),vt(),_r(),hTt(),B5=gt(()=>ht.enum([`userSettings`,`projectSettings`,`localSettings`,`session`,`cliArg`])),V5=gt(()=>ht.discriminatedUnion(`type`,[ht.object({type:ht.literal(`addRules`),rules:ht.array(z5()),behavior:R5(),destination:B5()}),ht.object({type:ht.literal(`replaceRules`),rules:ht.array(z5()),behavior:R5(),destination:B5()}),ht.object({type:ht.literal(`removeRules`),rules:ht.array(z5()),behavior:R5(),destination:B5()}),ht.object({type:ht.literal(`setMode`),mode:Pne(),destination:B5()}),ht.object({type:ht.literal(`addDirectories`),directories:ht.array(ht.string()),destination:B5()}),ht.object({type:ht.literal(`removeDirectories`),directories:ht.array(ht.string()),destination:B5()})]))}));function H5(e){return!(`async`in e&&e.async===!0)}function U5(e){return`async`in e&&e.async===!0}var _Tt,vTt,W5,yTt=n((()=>{_t(),vt(),rr(),hTt(),gTt(),_Tt=gt(()=>B({prompt:L(),message:L(),options:z(B({key:L(),label:L(),description:L().optional()}))})),vTt=gt(()=>B({continue:pt().describe(`Whether Work Mate should continue after hook (default: true)`).optional(),suppressOutput:pt().describe(`Hide stdout from transcript (default: false)`).optional(),stopReason:L().describe(`Message shown when continue is false`).optional(),decision:ft([`approve`,`block`]).optional(),reason:L().describe(`Explanation for the decision`).optional(),systemMessage:L().describe(`Warning message shown to the user`).optional(),hookSpecificOutput:ut([B({hookEventName:st(`PreToolUse`),permissionDecision:R5().optional(),permissionDecisionReason:L().optional(),updatedInput:it(L(),rt()).optional(),additionalContext:L().optional()}),B({hookEventName:st(`UserPromptSubmit`),additionalContext:L().optional()}),B({hookEventName:st(`SessionStart`),additionalContext:L().optional(),initialUserMessage:L().optional(),watchPaths:z(L()).describe(`Absolute paths to watch for FileChanged hooks`).optional()}),B({hookEventName:st(`Setup`),additionalContext:L().optional()}),B({hookEventName:st(`SubagentStart`),additionalContext:L().optional()}),B({hookEventName:st(`PostToolUse`),additionalContext:L().optional(),updatedMCPToolOutput:rt().describe(`Updates the output for MCP tools`).optional()}),B({hookEventName:st(`PostToolUseFailure`),additionalContext:L().optional()}),B({hookEventName:st(`PermissionDenied`),retry:pt().optional()}),B({hookEventName:st(`Notification`),additionalContext:L().optional()}),B({hookEventName:st(`PermissionRequest`),decision:ut([B({behavior:st(`allow`),updatedInput:it(L(),rt()).optional(),updatedPermissions:z(V5()).optional()}),B({behavior:st(`deny`),message:L().optional(),interrupt:pt().optional()})])}),B({hookEventName:st(`Elicitation`),action:ft([`accept`,`decline`,`cancel`]).optional(),content:it(L(),rt()).optional()}),B({hookEventName:st(`ElicitationResult`),action:ft([`accept`,`decline`,`cancel`]).optional(),content:it(L(),rt()).optional()}),B({hookEventName:st(`CwdChanged`),watchPaths:z(L()).describe(`Absolute paths to watch for FileChanged hooks`).optional()}),B({hookEventName:st(`FileChanged`),watchPaths:z(L()).describe(`Absolute paths to watch for FileChanged hooks`).optional()}),B({hookEventName:st(`WorktreeCreate`),worktreePath:L()})]).optional()})),W5=gt(()=>ut([B({async:st(!0),asyncTimeout:R().optional()}),vTt()]))}));function G5(e,t){let{signalB:n,timeoutMs:r}=t??{},i=TE();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((()=>{OE()}));function bTt(e,t){return J0(e,t)}function xTt(){return{...ose,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 STt(e,t){_4e(e,t,`Stop`,``,e=>uxt(e,Vs),`You MUST call the ${Vs} tool to complete this request. Call this tool now.`,{timeout:5e3})}var q5,J5=n((()=>{_t(),Es(),Y0(),vt(),p3(),fK(),q5=gt(()=>B({ok:pt().describe(`Whether the condition was met`),reason:L().describe(`Reason, if the condition was not met`).optional()}))}));async function CTt(e,t,n,r,i,a,o,s){let c=s||`hook-${tu()}`;try{let s=bTt(e.prompt,r);U(`Hooks: Processing prompt hook with prompt: ${s}`);let l=$({content:s}),u=o&&o.length>0?[...o,l]:[l];U(`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:rc([`You are evaluating a hook in Work Mate.
|
|
3179
3179
|
|
|
@@ -3186,7 +3186,7 @@ Use as few steps as possible - be efficient and direct.
|
|
|
3186
3186
|
|
|
3187
3187
|
When done, return your result using the ${Vs} tool with:
|
|
3188
3188
|
- ok: true if the condition is met
|
|
3189
|
-
- ok: false with reason if the condition is not met`]),f=e.model??Ko(),_=OB(`hook-agent-${tu()}`),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})`]}}}}};STt(a.setAppState,_);let y=null,b=0,x=!1;for await(let e of A1({messages:s,systemPrompt:o,userContext:{},systemContext:{},canUseTool:k9,toolUseContext:v,querySource:`hook_agent`}))if(Vbt(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,U(`Hooks: Agent turn ${b} hit max turns, aborting`),p.abort();break}if(TTt(e)){let t=q5().safeParse(e.attachment.data);if(t.success){y=t.data,U(`Hooks: Got structured output: ${V(y)}`),p.abort();break}}}return m.removeEventListener(`abort`,g),h(),dK(a.setAppState,_),y?y.ok?(U(`Hooks: Agent hook condition was met`),J(`tengu_agent_stop_hook_success`,{durationMs:Date.now()-d,turnCount:b,agentName:c}),{hook:e,outcome:`success`,message:j0({type:`hook_success`,hookName:t,toolUseID:l,hookEvent:n,content:``})}):(U(`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?(U(`Hooks: Agent hook did not complete within 50 turns`),J(`tengu_agent_stop_hook_max_turns`,{durationMs:Date.now()-d,turnCount:b,agentName:c}),{hook:e,outcome:`cancelled`}):(U(`Hooks: Agent hook did not return structured output`),J(`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=H(r);return U(`Hooks: Agent hook error: ${i}`),J(`tengu_agent_stop_hook_error`,{durationMs:Date.now()-d,errorType:2,agentName:c}),{hook:e,outcome:`non_blocking_error`,message:j0({type:`hook_non_blocking_error`,hookName:t,toolUseID:l,hookEvent:n,stderr:`Error executing agent hook: ${i}`,stdout:``,exitCode:1})}}}var DTt=n((()=>{j1(),Na(),Zs(),Es(),i1(),kB(),OE(),H0(),K5(),W(),Mn(),p3(),Lo(),A9(),m8(),Zn(),lI(),J5(),fK()}));function OTt(e){let t=Ble(e);return t===4?kTt(e):t===6&&ATt(e)}function kTt(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 ATt(e){let t=e.toLowerCase();if(t===`::1`)return!1;if(t===`::`)return!0;let n=MTt(t);if(n!==null)return kTt(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 jTt(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 MTt(e){let t=jTt(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 NTt(e,t,n){let r=`all`in t&&t.all===!0,i=Ble(e);if(i!==0){if(OTt(e)){n(PTt(e,e),``);return}let t=i===6?6:4;r?n(null,[{address:e,family:t}]):n(null,e,t);return}$le(e,{all:!0},(t,i)=>{if(t){n(t,``);return}for(let{address:t}of i)if(OTt(t)){n(PTt(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 PTt(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 FTt=n((()=>{}));async function ITt(){let{SandboxManager:e}=await import(`./sandbox-adapter-
|
|
3189
|
+
- ok: false with reason if the condition is not met`]),f=e.model??Ko(),_=OB(`hook-agent-${tu()}`),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})`]}}}}};STt(a.setAppState,_);let y=null,b=0,x=!1;for await(let e of A1({messages:s,systemPrompt:o,userContext:{},systemContext:{},canUseTool:k9,toolUseContext:v,querySource:`hook_agent`}))if(Vbt(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,U(`Hooks: Agent turn ${b} hit max turns, aborting`),p.abort();break}if(TTt(e)){let t=q5().safeParse(e.attachment.data);if(t.success){y=t.data,U(`Hooks: Got structured output: ${V(y)}`),p.abort();break}}}return m.removeEventListener(`abort`,g),h(),dK(a.setAppState,_),y?y.ok?(U(`Hooks: Agent hook condition was met`),J(`tengu_agent_stop_hook_success`,{durationMs:Date.now()-d,turnCount:b,agentName:c}),{hook:e,outcome:`success`,message:j0({type:`hook_success`,hookName:t,toolUseID:l,hookEvent:n,content:``})}):(U(`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?(U(`Hooks: Agent hook did not complete within 50 turns`),J(`tengu_agent_stop_hook_max_turns`,{durationMs:Date.now()-d,turnCount:b,agentName:c}),{hook:e,outcome:`cancelled`}):(U(`Hooks: Agent hook did not return structured output`),J(`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=H(r);return U(`Hooks: Agent hook error: ${i}`),J(`tengu_agent_stop_hook_error`,{durationMs:Date.now()-d,errorType:2,agentName:c}),{hook:e,outcome:`non_blocking_error`,message:j0({type:`hook_non_blocking_error`,hookName:t,toolUseID:l,hookEvent:n,stderr:`Error executing agent hook: ${i}`,stdout:``,exitCode:1})}}}var DTt=n((()=>{j1(),Na(),Zs(),Es(),i1(),kB(),OE(),H0(),K5(),W(),Mn(),p3(),Lo(),A9(),m8(),Zn(),lI(),J5(),fK()}));function OTt(e){let t=Ble(e);return t===4?kTt(e):t===6&&ATt(e)}function kTt(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 ATt(e){let t=e.toLowerCase();if(t===`::1`)return!1;if(t===`::`)return!0;let n=MTt(t);if(n!==null)return kTt(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 jTt(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 MTt(e){let t=jTt(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 NTt(e,t,n){let r=`all`in t&&t.all===!0,i=Ble(e);if(i!==0){if(OTt(e)){n(PTt(e,e),``);return}let t=i===6?6:4;r?n(null,[{address:e,family:t}]):n(null,e,t);return}$le(e,{all:!0},(t,i)=>{if(t){n(t,``);return}for(let{address:t}of i)if(OTt(t)){n(PTt(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 PTt(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 FTt=n((()=>{}));async function ITt(){let{SandboxManager:e}=await import(`./sandbox-adapter-CtEngx-6.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 LTt(){let e=ii();return{allowedUrls:e.allowedHttpHookUrls,allowedEnvVars:e.httpHookAllowedEnvVars}}function RTt(e,t){let n=t.replace(/[.+?^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`.*`);return RegExp(`^${n}$`).test(e)}function zTt(e){return e.replace(/[\r\n\x00]/g,``)}function BTt(e,t){return zTt(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]??``:(U(`Hooks: env var $${i} not in allowedEnvVars, skipping interpolation`,{level:`warn`}),``)}))}async function VTt(e,t,n,r){let i=LTt();if(i.allowedUrls!==void 0&&!i.allowedUrls.some(t=>RTt(e.url,t))){let t=`HTTP hook blocked: ${e.url} does not match any pattern in allowedHttpHookUrls`;return U(t,{level:`warn`}),{ok:!1,body:``,error:t}}let{signal:a,cleanup:o}=G5(r,{timeoutMs:e.timeout?e.timeout*1e3:HTt});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]=BTt(r,a)}let r=await ITt(),s=!r&&yse()!==void 0&&!xse(e.url);U(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 ue.post(e.url,n,{headers:t,signal:a,responseType:`text`,validateStatus:()=>!0,maxRedirects:0,proxy:r??!1,lookup:r||s?void 0:NTt});o();let l=c.data??``;return U(`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=H(e);return U(`Hooks: HTTP hook error: ${t}`,{level:`error`}),{ok:!1,body:``,error:t}}}var HTt,UTt=n((()=>{de(),K5(),W(),Mn(),tc(),Yr(),FTt(),HTt=600*1e3}));function WTt(){let e=process.env.CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS,t=e?parseInt(e,10):NaN;return Number.isFinite(t)&&t>0?t:AEt}function GTt({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(),_0({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&&hL({value:J4(`Stop hook blocking error from command "${a}": ${o||r}`),mode:`task-notification`})}),!0):n.background(e)?(Ght({processId:e,hookId:t,asyncResponse:r,hookEvent:i,hookName:a,command:o,shellCommand:n,pluginId:c}),!0):!1}function Y5(){return!vn()&&!tie()}function X5(e,t,n){let r=t??ln(),i=n?.agentType??_te();return{session_id:r,transcript_path:i6(r),cwd:Cn(),permission_mode:e,agent_id:n?.agentId,agent_type:i}}function KTt(e){let t=Nn(e),n=W5().safeParse(t);return n.success?(U(`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(`
|
|
3190
3190
|
`)}\n\nThe hook's output was: ${V(t,null,2)}`}}function qTt(e){let t=e.trim();if(!t.startsWith(`{`))return U(`Hook output does not start with {, treating as plain text`),{plainText:e};try{let n=KTt(t);if(`json`in n)return n;let r=`${n.validationError}\n\nExpected schema:\n${V({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 U(r),{plainText:e,validationError:r}}catch(t){return U(`Failed to parse hook output as JSON: ${t}`),{plainText:e}}}function JTt(e){let t=e.trim();if(t===``){let e=W5().safeParse({});if(e.success)return U(`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 U(e),{validationError:e}}try{let e=KTt(t);return`json`in e||U(e.validationError),e}catch(e){let t=`HTTP hook must return valid JSON, but parsing failed: ${e}`;return U(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: ${V(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?j0({type:`hook_blocking_error`,hookName:n,toolUseID:r,hookEvent:i,blockingError:u.blockingError}):j0({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=_a()===`windows`,_=e.shell??`bash`,v=_===`powershell`,y=g&&!v?e=>xa(e):e=>e,b=tn(),x=e.command,S;if(s){if(!await $r(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(Og(c));x=x.replace(/\$\{CLAUDE_PLUGIN_DATA\}/g,()=>e)}c&&(S=Dw(c),x=Ew(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?Av(process.env.CLAUDE_CODE_SHELL_PREFIX,x):x,w=e.timeout?e.timeout*1e3:h7,T={...Zc(),CLAUDE_PROJECT_DIR:y(b)};if(s&&(T.CLAUDE_PLUGIN_ROOT=y(s),c&&(T.CLAUDE_PLUGIN_DATA=y(Og(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 Wxe(t,o));let E=Cn(),D=await $r(E)?E:Zt();D!==E&&U(`Hooks: cwd ${E} not found, falling back to original cwd`,{level:`warn`});let O=C;if(!v&&gh.isSandboxingEnabled())try{O=await gh.wrapWithSandbox(C,void 0,{network:{allowedDomains:[],deniedDomains:[]},filesystem:{allowWrite:[`/`],denyWrite:[],allowRead:[],denyRead:[]}},i),U(`Hook command sandboxed (network-only): ${e.command}`,{level:`verbose`})}catch(e){U(`Failed to sandbox hook command, running unsandboxed: ${H(e)}`,{level:`warn`})}let k;if(_===`powershell`){let t=await Lv();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=yu(t,ESe(C),{env:T,cwd:D,windowsHide:!0})}else{let e=!g||Pie();k=yu(O,[],{env:T,cwd:D,shell:e,windowsHide:!0})}let A=new I_(`hook_${k.pid}`,null),ee=sTt(k,i,w,A),te=!1,ne=!1;if((e.async||e.asyncRewake)&&!u){let i=`async_hook_${k.pid}`;if(U(`Hooks: Config-based async hook, backgrounding process ${i}`),k.stdin.write(`${r}\n`,`utf8`),k.stdin.end(),ne=!0,GTt({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(`
|
|
3191
3191
|
`);N=e.pop()??``;for(let t of e){let e=t.trim();if(e)try{let t=Nn(e),n=_Tt().safeParse(t);if(n.success){ce.add(e),U(`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(`${V(e)}\n`,`utf8`)}catch(e){U(`Hooks: Prompt request handling failed: ${e}`),k.stdin.destroy()}})}}catch{}}}if(!j){let r=Ka(re).trim();if(!r.includes(`}`))return;j=!0,U(`Hooks: Checking first line for async: ${r}`);try{let i=Nn(r);if(U(`Hooks: Parsed initial response: ${V(i)}`),U5(i)&&!u){let r=`async_hook_${k.pid}`;U(`Hooks: Detected async hook, backgrounding process ${r}`),GTt({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?U(`Hooks: Detected async hook but forceSyncExecution is true, waiting for completion`):U(`Hooks: Initial response is not async, continuing normal processing`)}catch(e){U(`Hooks: Failed to parse initial response as JSON: ${e}`)}}}),k.stderr.on(`data`,e=>{ie+=e,ae+=e});let le=Vht({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?U(`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(`
|
|
3192
3192
|
`).filter(e=>!ce.has(e.trim())).join(`
|
|
@@ -3383,8 +3383,8 @@ The user context may include a \`terminalFocus\` field indicating whether the us
|
|
|
3383
3383
|
`)].filter(Boolean)}function zDt(e,t){if(Object.entries(t).length===0)return e;let{agentsMd:n,...r}=t,i=[];n&&i.push($({content:`<project-instructions>\n${n}\n</project-instructions>\n`,isMeta:!0}));let a=Object.entries(r);return a.length>0&&i.push($({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(`
|
|
3384
3384
|
`)}
|
|
3385
3385
|
|
|
3386
|
-
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 BDt(e,t){if(Ace())return;let[{tools:n},r,i,a]=await Promise.all([Rj(e),r1(t),YR(),JR()]),o=a.gitStatus?.length??0,s=i.agentsMd?.length??0,c=o+s,l=Cn(),u=E8(D8(t),l),d=await Jse(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:iz(e.inputSchema);m+=v3(V(t))}for(let e of _){let t=`inputJSONSchema`in e&&e.inputJSONSchema?e.inputJSONSchema:iz(e.inputSchema);g+=v3(V(t))}J(`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 VDt(e,t,n){switch(e.name){case Us:{let e=Zd(n),r=Xd(n);return ppe(),e===null?t:{...t,plan:e,planFilePath:r}}case xW.name:{let e=xW.inputSchema.parse(t),{command:n,timeout:r,description:i}=e,a=Cn(),o=n.replace(`cd ${a} && `,``);_a()===`windows`&&(o=o.replace(`cd ${xa(a)} && `,``)),o=o.replace(/\\\\;/g,`\\;`),/^echo\s+["']?[^|&;><]*["']?$/i.test(o.trim())&&J(`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 xq.name:{let e=xq.inputSchema.parse(t),{file_path:n,edits:r}=eFe({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 ZH.name:{let e=ZH.inputSchema.parse(t),n=/\.(md|mdx)$/i.test(e.file_path);return{file_path:e.file_path,content:n?e.content:nI(e.content)}}case fr:{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 HDt(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 xq.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(),XR(),Oce(),Na(),cM(),SW(),Sq(),cI(),QH(),i1(),jd(),C3(),ds(),ci(),Po(),Sn(),W(),h(),p3(),es(),L8(),$d(),va(),jc(),Zn(),$ae(),ba(),oz(),H7=!1}));function UDt(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||m(process.env.USE_API_CLEAR_TOOL_RESULTS),o=m(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:WDt};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:GDt};i.push(n)}return i.length>0?{edits:i}:void 0}var W7,G7,WDt,GDt,KDt=n((()=>{Rs(),Bs(),Cs(),_s(),ms(),zs(),Qs(),h(),W7=18e4,G7=4e4,WDt=[...pse,Js,cs,xs],GDt=[ks,Ps,Hs]})),qDt,JDt=n((()=>{qDt={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 YDt(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 XDt=n((()=>{})),ZDt=n((()=>{ac()}));function QDt(e){if(e instanceof Rn){let t=e.error;if(t?.error?.message)return t.error.message}return e instanceof Error?e.message:String(e)}function $Dt({headers:e,baseUrl:t}){if(e){let t=[];e.forEach((e,n)=>t.push(n));for(let[e,{prefixes:n}]of Object.entries(aOt))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(oOt))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 eOt(){let e=new Date(`2026-08-14T04:05:02.242Z`).getTime();if(!isNaN(e))return Math.floor((Date.now()-e)/6e4)}function tOt({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;J(`tengu_api_query`,{model:e,messagesLength:t,temperature:n,provider:Vo(),buildAgeMins:eOt(),...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 nOt({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 _=$Dt({headers:e instanceof Rn&&e.headers?e.headers:d,baseUrl:process.env.ANTHROPIC_BASE_URL}),v=QDt(e),y=e instanceof Rn?String(e.status):void 0,b=HIe(e),x=nc(e);if(x){let e=x.isSSLError?` (SSL error)`:``;U(`Connection error details: code=${x.code}${e}, message=${x.message}`,{level:`error`})}let S=Vc();c&&U(`API error x-client-request-id=${c} (give this to the API team for server-log lookup)`,{level:`error`}),q(e),J(`tengu_api_error`,{model:t,error:v,status:y,errorType:b,messageCount:n,messageTokens:r,durationMs:i,durationMsIncludingRetries:a,attempt:o,provider:Vo(),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()}),rl(`api_error`,{model:t,error:v,status_code:String(y),duration_ms:String(i),attempt:String(o),speed:h?`fast`:`normal`}),ol(m,{success:!1,statusCode:y?parseInt(y,10):void 0,error:v,attempt:o});let C=Ete();C?.isTeleported&&!C.hasLoggedFirstMessage&&(J(`tengu_teleport_first_message_error`,{session_id:C.sessionId,error_type:b}),Mt())}function rOt({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=vn(),E=$te(),D=process.argv.includes(`-p`)||process.argv.includes(`--print`),O=Date.now(),k=kt(),A=k===null?void 0:O-k,ee=Vc();J(`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:eOt(),provider:Vo(),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:V(b)},...x===void 0?{}:{connectorTextBlockCount:x},fastMode:S,...C?{previousRequestId:C}:{},...E?{isPostCompaction:E}:{},...K7(),timeSinceLastApiCallMs:A}),Tt(O)}function iOt({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=$Dt({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=V(i.input).length,t=Jc(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;zte(ee,A),rOt({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}),rl(`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;nl()&&_&&(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(`
|
|
3387
|
-
`)||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})),ol(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});let re=Ete();re?.isTeleported&&!re.hasLoggedFirstMessage&&(J(`tengu_teleport_first_message_success`,{session_id:re.sessionId}),Mt())}var aOt,oOt,sOt=n((()=>{Ln(),Gt(),W(),oa(),es(),Zn(),ll(),al(),Hc(),Na(),Uc(),ZDt(),iR(),UL(),aOt={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-`]}},oOt={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=Ma(t);e&&typeof e==`object`&&!Array.isArray(e)?n={...e}:U(`CLAUDE_CODE_EXTRA_BODY env var must be a JSON object, but was given ${t}`,{level:`error`})}catch(e){U(`Error parsing CLAUDE_CODE_EXTRA_BODY: ${H(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 cOt(e){return!(m(process.env.DISABLE_PROMPT_CACHING)||m(process.env.DISABLE_PROMPT_CACHING_HAIKU)&&e===Ko()||m(process.env.DISABLE_PROMPT_CACHING_SONNET)&&e===Yo()||m(process.env.DISABLE_PROMPT_CACHING_OPUS)&&e===jae())}function J7({scope:e,querySource:t}={}){return{type:`ephemeral`,...lOt(t)&&{ttl:`1h`},...e===`global`&&{scope:e}}}function lOt(e){if(eo()===`bedrock`&&m(process.env.ENABLE_PROMPT_CACHING_1H_BEDROCK))return!0;let t=Qte();if(t===null&&(t=as()&&!zL.isUsingOverage,hte(t)),!t)return!1;let n=wte();return n===null&&(n={}.allowlist??[],lte(n)),e!==void 0&&n.some(t=>t.endsWith(`*`)?e.startsWith(t.slice(0,-1)):e===t)}function uOt(e,t,n){!e||`task_budget`in t||!wo()||(t.task_budget={type:`tokens`,total:e.total,...e.remaining!==void 0&&{remaining:e.remaining}},n.includes(`task-budgets-2026-03-13`)||n.push(Zae))}function Y7(){let e={},t=process.env.CLAUDE_CODE_EXTRA_METADATA;if(t){let n=Ma(t,!1);n&&typeof n==`object`&&!Array.isArray(n)?e=n:U(`CLAUDE_CODE_EXTRA_METADATA env var must be a JSON object, but was given ${t}`,{level:`error`})}return{user_id:V({...e,device_id:Zre(),account_uuid:vae()?.accountUuid??``,session_id:ln()})}}async function dOt(e,t){if(t)return!0;try{let t=Ko(),n=ns(t);return await cpt(oR(()=>ho({apiKey:e,maxRetries:3,model:t,source:`verify_api_key`}),async e=>(await e.beta.messages.create({model:t,max_tokens:1,messages:[{role:`user`,content:`test`}],temperature:1,...n.length>0&&{betas:n.filter(Boolean)},metadata:Y7(),...q7()}),!0),{maxRetries:2,model:t,thinkingConfig:{type:`disabled`}}))}catch(e){let t=e;if(e instanceof hR&&(t=e.originalError),q(t),t instanceof Error&&t.message.includes(`{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}`))return!1;throw t}}function fOt(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 pOt(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=mOt(t);return{...a,...i===e.message.content.length-1&&a.type!==`thinking`&&a.type!==`redacted_thinking`&&!Lfe(a)&&n?{cache_control:J7({querySource:r})}:{}}})}:{role:`assistant`,content:typeof e.message.content==`string`?e.message.content:e.message.content.map(mOt)}}function mOt(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 zxt(e,async function*(){yield*xOt(e,t,n,r,i,a)}))s.type===`assistant`&&(o=s);if(!o)throw i.aborted?new Bn:Error(`No assistant message found`);return o}async function*hOt({messages:e,systemPrompt:t,thinkingConfig:n,tools:r,signal:i,options:a}){return yield*zxt(e,async function*(){yield*xOt(e,t,n,r,i,a)})}function gOt(){return parseInt(process.env.API_TIMEOUT_MS||``,10)||(m(process.env.CLAUDE_CODE_REMOTE)?12e4:3e5)}async function*_Ot(e,t,n,r,i,a){let o=gOt(),s=oR(()=>ho({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=DOt(d,kOt);try{return await s.beta.messages.create({...f,model:jo(f.model)},{signal:t.signal,timeout:o})}catch(t){throw t instanceof Bn?t:(Ri(`error`,`cli_nonstreaming_fallback_error`),J(`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,...Io()&&{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 vOt(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 yOt(e){return e.type===`tool_result`}function bOt(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++,yOt(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||!yOt(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*xOt(e,t,n,r,i,a){if(!as()&&rs(a.model)&&{activated:!1}.activated){J(`tengu_off_switch_query`,{}),yield KL(Error(nR),a.model);return}let o=vOt(e),s=eo()===`bedrock`&&a.model.includes(`application-inference-profile`)?await go(a.model)??a.model:a.model;u1(`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=so(a.model,{isAgenticQuery:c});xh()&&l.push(Fae);let u;if(c&&xh()){let e=a.advisorModel,t=tbe();if(t!==void 0&&jo(t.baseModel)===jo(a.model)&&(e=t.advisorModel),e){let t=jo(oo(e));Ch(a.model)?wh(t)?(u=t,U(`[AdvisorTool] Server-side tool enabled with ${u} as the advisor model`)):U(`[AdvisorTool] Skipping advisor - ${t} is not a valid advisor model`):U(`[AdvisorTool] Skipping advisor - base model ${a.model} does not support advisor`)}}let d=await dz(a.model,r,a.getToolPermissionContext,a.agents,`query`),f=new Set;if(d)for(let e of r)Fs(e)&&f.add(e.name);d&&f.size===0&&!a.hasPendingMcpServers&&(U(`Tool search disabled: no deferred tools available to search`),d=!1);let p;p=d?r.filter(e=>!!(!f.has(e.name)||Ys(e,`SearchExtraTools`))):r.filter(e=>!Ys(e,Ks));let h=qo(),g=h&&p.some(e=>e.isMcp===!0);h&&!l.includes(`prompt-caching-scope-2026-01-05`)&&l.push(Bae);let _=h?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&&U(`Dynamic tool loading: 0/${f.size} deferred tools in API tools array (all via ExecuteExtraTool)`),u1(`query_tool_schema_build_end`),J(`tengu_api_before_normalize`,{preNormalizedMessageCount:e.length}),u1(`query_message_normalization_start`);let y=L4(e,p);if(u1(`query_message_normalization_end`),d||(y=y.map(e=>{switch(e.type){case`user`:return kbt(e);case`assistant`:return Abt(e);default:return e}})),y=vxt(y),l.includes(`advisor-tool-2026-03-01`)||(y=yxt(y)),y=bOt(y,100),eo()===`openai`){let{queryModelOpenAI:e}=await import(`./openai-
|
|
3386
|
+
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 BDt(e,t){if(Ace())return;let[{tools:n},r,i,a]=await Promise.all([Rj(e),r1(t),YR(),JR()]),o=a.gitStatus?.length??0,s=i.agentsMd?.length??0,c=o+s,l=Cn(),u=E8(D8(t),l),d=await Jse(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:iz(e.inputSchema);m+=v3(V(t))}for(let e of _){let t=`inputJSONSchema`in e&&e.inputJSONSchema?e.inputJSONSchema:iz(e.inputSchema);g+=v3(V(t))}J(`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 VDt(e,t,n){switch(e.name){case Us:{let e=Zd(n),r=Xd(n);return ppe(),e===null?t:{...t,plan:e,planFilePath:r}}case xW.name:{let e=xW.inputSchema.parse(t),{command:n,timeout:r,description:i}=e,a=Cn(),o=n.replace(`cd ${a} && `,``);_a()===`windows`&&(o=o.replace(`cd ${xa(a)} && `,``)),o=o.replace(/\\\\;/g,`\\;`),/^echo\s+["']?[^|&;><]*["']?$/i.test(o.trim())&&J(`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 xq.name:{let e=xq.inputSchema.parse(t),{file_path:n,edits:r}=eFe({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 ZH.name:{let e=ZH.inputSchema.parse(t),n=/\.(md|mdx)$/i.test(e.file_path);return{file_path:e.file_path,content:n?e.content:nI(e.content)}}case fr:{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 HDt(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 xq.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(),XR(),Oce(),Na(),cM(),SW(),Sq(),cI(),QH(),i1(),jd(),C3(),ds(),ci(),Po(),Sn(),W(),h(),p3(),es(),L8(),$d(),va(),jc(),Zn(),$ae(),ba(),oz(),H7=!1}));function UDt(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||m(process.env.USE_API_CLEAR_TOOL_RESULTS),o=m(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:WDt};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:GDt};i.push(n)}return i.length>0?{edits:i}:void 0}var W7,G7,WDt,GDt,KDt=n((()=>{Rs(),Bs(),Cs(),_s(),ms(),zs(),Qs(),h(),W7=18e4,G7=4e4,WDt=[...pse,Js,cs,xs],GDt=[ks,Ps,Hs]})),qDt,JDt=n((()=>{qDt={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 YDt(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 XDt=n((()=>{})),ZDt=n((()=>{ac()}));function QDt(e){if(e instanceof Rn){let t=e.error;if(t?.error?.message)return t.error.message}return e instanceof Error?e.message:String(e)}function $Dt({headers:e,baseUrl:t}){if(e){let t=[];e.forEach((e,n)=>t.push(n));for(let[e,{prefixes:n}]of Object.entries(aOt))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(oOt))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 eOt(){let e=new Date(`2026-08-14T04:15:24.415Z`).getTime();if(!isNaN(e))return Math.floor((Date.now()-e)/6e4)}function tOt({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;J(`tengu_api_query`,{model:e,messagesLength:t,temperature:n,provider:Vo(),buildAgeMins:eOt(),...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 nOt({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 _=$Dt({headers:e instanceof Rn&&e.headers?e.headers:d,baseUrl:process.env.ANTHROPIC_BASE_URL}),v=QDt(e),y=e instanceof Rn?String(e.status):void 0,b=HIe(e),x=nc(e);if(x){let e=x.isSSLError?` (SSL error)`:``;U(`Connection error details: code=${x.code}${e}, message=${x.message}`,{level:`error`})}let S=Vc();c&&U(`API error x-client-request-id=${c} (give this to the API team for server-log lookup)`,{level:`error`}),q(e),J(`tengu_api_error`,{model:t,error:v,status:y,errorType:b,messageCount:n,messageTokens:r,durationMs:i,durationMsIncludingRetries:a,attempt:o,provider:Vo(),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()}),rl(`api_error`,{model:t,error:v,status_code:String(y),duration_ms:String(i),attempt:String(o),speed:h?`fast`:`normal`}),ol(m,{success:!1,statusCode:y?parseInt(y,10):void 0,error:v,attempt:o});let C=Ete();C?.isTeleported&&!C.hasLoggedFirstMessage&&(J(`tengu_teleport_first_message_error`,{session_id:C.sessionId,error_type:b}),Mt())}function rOt({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=vn(),E=$te(),D=process.argv.includes(`-p`)||process.argv.includes(`--print`),O=Date.now(),k=kt(),A=k===null?void 0:O-k,ee=Vc();J(`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:eOt(),provider:Vo(),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:V(b)},...x===void 0?{}:{connectorTextBlockCount:x},fastMode:S,...C?{previousRequestId:C}:{},...E?{isPostCompaction:E}:{},...K7(),timeSinceLastApiCallMs:A}),Tt(O)}function iOt({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=$Dt({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=V(i.input).length,t=Jc(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;zte(ee,A),rOt({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}),rl(`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;nl()&&_&&(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(`
|
|
3387
|
+
`)||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})),ol(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});let re=Ete();re?.isTeleported&&!re.hasLoggedFirstMessage&&(J(`tengu_teleport_first_message_success`,{session_id:re.sessionId}),Mt())}var aOt,oOt,sOt=n((()=>{Ln(),Gt(),W(),oa(),es(),Zn(),ll(),al(),Hc(),Na(),Uc(),ZDt(),iR(),UL(),aOt={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-`]}},oOt={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=Ma(t);e&&typeof e==`object`&&!Array.isArray(e)?n={...e}:U(`CLAUDE_CODE_EXTRA_BODY env var must be a JSON object, but was given ${t}`,{level:`error`})}catch(e){U(`Error parsing CLAUDE_CODE_EXTRA_BODY: ${H(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 cOt(e){return!(m(process.env.DISABLE_PROMPT_CACHING)||m(process.env.DISABLE_PROMPT_CACHING_HAIKU)&&e===Ko()||m(process.env.DISABLE_PROMPT_CACHING_SONNET)&&e===Yo()||m(process.env.DISABLE_PROMPT_CACHING_OPUS)&&e===jae())}function J7({scope:e,querySource:t}={}){return{type:`ephemeral`,...lOt(t)&&{ttl:`1h`},...e===`global`&&{scope:e}}}function lOt(e){if(eo()===`bedrock`&&m(process.env.ENABLE_PROMPT_CACHING_1H_BEDROCK))return!0;let t=Qte();if(t===null&&(t=as()&&!zL.isUsingOverage,hte(t)),!t)return!1;let n=wte();return n===null&&(n={}.allowlist??[],lte(n)),e!==void 0&&n.some(t=>t.endsWith(`*`)?e.startsWith(t.slice(0,-1)):e===t)}function uOt(e,t,n){!e||`task_budget`in t||!wo()||(t.task_budget={type:`tokens`,total:e.total,...e.remaining!==void 0&&{remaining:e.remaining}},n.includes(`task-budgets-2026-03-13`)||n.push(Zae))}function Y7(){let e={},t=process.env.CLAUDE_CODE_EXTRA_METADATA;if(t){let n=Ma(t,!1);n&&typeof n==`object`&&!Array.isArray(n)?e=n:U(`CLAUDE_CODE_EXTRA_METADATA env var must be a JSON object, but was given ${t}`,{level:`error`})}return{user_id:V({...e,device_id:Zre(),account_uuid:vae()?.accountUuid??``,session_id:ln()})}}async function dOt(e,t){if(t)return!0;try{let t=Ko(),n=ns(t);return await cpt(oR(()=>ho({apiKey:e,maxRetries:3,model:t,source:`verify_api_key`}),async e=>(await e.beta.messages.create({model:t,max_tokens:1,messages:[{role:`user`,content:`test`}],temperature:1,...n.length>0&&{betas:n.filter(Boolean)},metadata:Y7(),...q7()}),!0),{maxRetries:2,model:t,thinkingConfig:{type:`disabled`}}))}catch(e){let t=e;if(e instanceof hR&&(t=e.originalError),q(t),t instanceof Error&&t.message.includes(`{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}`))return!1;throw t}}function fOt(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 pOt(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=mOt(t);return{...a,...i===e.message.content.length-1&&a.type!==`thinking`&&a.type!==`redacted_thinking`&&!Lfe(a)&&n?{cache_control:J7({querySource:r})}:{}}})}:{role:`assistant`,content:typeof e.message.content==`string`?e.message.content:e.message.content.map(mOt)}}function mOt(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 zxt(e,async function*(){yield*xOt(e,t,n,r,i,a)}))s.type===`assistant`&&(o=s);if(!o)throw i.aborted?new Bn:Error(`No assistant message found`);return o}async function*hOt({messages:e,systemPrompt:t,thinkingConfig:n,tools:r,signal:i,options:a}){return yield*zxt(e,async function*(){yield*xOt(e,t,n,r,i,a)})}function gOt(){return parseInt(process.env.API_TIMEOUT_MS||``,10)||(m(process.env.CLAUDE_CODE_REMOTE)?12e4:3e5)}async function*_Ot(e,t,n,r,i,a){let o=gOt(),s=oR(()=>ho({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=DOt(d,kOt);try{return await s.beta.messages.create({...f,model:jo(f.model)},{signal:t.signal,timeout:o})}catch(t){throw t instanceof Bn?t:(Ri(`error`,`cli_nonstreaming_fallback_error`),J(`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,...Io()&&{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 vOt(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 yOt(e){return e.type===`tool_result`}function bOt(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++,yOt(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||!yOt(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*xOt(e,t,n,r,i,a){if(!as()&&rs(a.model)&&{activated:!1}.activated){J(`tengu_off_switch_query`,{}),yield KL(Error(nR),a.model);return}let o=vOt(e),s=eo()===`bedrock`&&a.model.includes(`application-inference-profile`)?await go(a.model)??a.model:a.model;u1(`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=so(a.model,{isAgenticQuery:c});xh()&&l.push(Fae);let u;if(c&&xh()){let e=a.advisorModel,t=tbe();if(t!==void 0&&jo(t.baseModel)===jo(a.model)&&(e=t.advisorModel),e){let t=jo(oo(e));Ch(a.model)?wh(t)?(u=t,U(`[AdvisorTool] Server-side tool enabled with ${u} as the advisor model`)):U(`[AdvisorTool] Skipping advisor - ${t} is not a valid advisor model`):U(`[AdvisorTool] Skipping advisor - base model ${a.model} does not support advisor`)}}let d=await dz(a.model,r,a.getToolPermissionContext,a.agents,`query`),f=new Set;if(d)for(let e of r)Fs(e)&&f.add(e.name);d&&f.size===0&&!a.hasPendingMcpServers&&(U(`Tool search disabled: no deferred tools available to search`),d=!1);let p;p=d?r.filter(e=>!!(!f.has(e.name)||Ys(e,`SearchExtraTools`))):r.filter(e=>!Ys(e,Ks));let h=qo(),g=h&&p.some(e=>e.isMcp===!0);h&&!l.includes(`prompt-caching-scope-2026-01-05`)&&l.push(Bae);let _=h?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&&U(`Dynamic tool loading: 0/${f.size} deferred tools in API tools array (all via ExecuteExtraTool)`),u1(`query_tool_schema_build_end`),J(`tengu_api_before_normalize`,{preNormalizedMessageCount:e.length}),u1(`query_message_normalization_start`);let y=L4(e,p);if(u1(`query_message_normalization_end`),d||(y=y.map(e=>{switch(e.type){case`user`:return kbt(e);case`assistant`:return Abt(e);default:return e}})),y=vxt(y),l.includes(`advisor-tool-2026-03-01`)||(y=yxt(y)),y=bOt(y,100),eo()===`openai`){let{queryModelOpenAI:e}=await import(`./openai-D9KvLMrj.js`);yield*e(y,t,r,i,a);return}if(eo()===`gemini`){let{queryModelGemini:e}=await import(`./gemini-L8Gj2B4H.js`);yield*e(y,t,p,i,a,n);return}if(eo()===`grok`){let{queryModelGrok:e}=await import(`./grok-DtypRM4d.js`);yield*e(y,t,p,i,a);return}if(J(`tengu_api_after_normalize`,{postNormalizedMessageCount:y.length}),d&&!mz()){let e=r.filter(e=>f.has(e.name)).map(cse).sort().join(`
|
|
3388
3388
|
`);if(e){let t=new Set(e.split(`
|
|
3389
3389
|
`));if([...t].some(e=>!t9.has(e))){t9.clear();for(let e of t)t9.add(e);y=[...y,$({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=rc([Ffe(),Nfe({isNonInteractive:a.isNonInteractiveSession,hasAppendSystemPrompt:a.hasAppendSystemPrompt}),...t,...u?[Th]:[]].filter(Boolean));{let e=Vse(),n=Hse();if(Yl(e)||Yl(n)){let n=tu();if(t=rc([...t,`<!-- cache-break nonce: ${n} -->`]),Yl(e))try{vle(e)}catch{}}}IDt(t);let b=a.enablePromptCaching??cOt(a.model),x=EOt(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=Io()&&Tae()&&!Fo()&&Oo(a.model)&&!!a.fastMode,E=Lte()===!0;!E&&c&&wo()&&rL()&&(E=!0,Cte(!0));let D=Vte()===!0;!D&&T&&(D=!0,qte(!0));let O=fne()===!0;ELe({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:zL.isUsingOverage??!1,cachedMCEnabled:O,extraBodyParams:q7()});let k=nl()?{systemPrompt:t.join(`
|
|
3390
3390
|
|