@shareai-lab/kode 2.1.0 → 2.1.2
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/{Doctor-AES5ON33.js → Doctor-TWRIVOVW.js} +13 -13
- package/dist/chunks/{LogList-PQJEJHHE.js → LogList-PUTPM24L.js} +10 -10
- package/dist/chunks/REPL-YGIR5VXC.js +78 -0
- package/dist/chunks/{ResumeConversation-OWQ3DB4M.js → ResumeConversation-IJMKQXBU.js} +44 -44
- package/dist/chunks/{ScreenFrame-AGLR6B4D.js → ScreenFrame-PQJRZ5DQ.js} +2 -2
- package/dist/chunks/{agentLoader-BMWB4UKI.js → agentLoader-GOYNJTAO.js} +5 -5
- package/dist/chunks/{agentsValidate-LSMJSFYW.js → agentsValidate-R26AKPAA.js} +6 -6
- package/dist/chunks/{ask-3TSZR6AJ.js → ask-6SYVJONJ.js} +18 -18
- package/dist/chunks/{autoUpdater-MEPC7LJF.js → autoUpdater-SDLJ5QSH.js} +4 -4
- package/dist/chunks/{chunk-NC3RX5AB.js → chunk-2B2TR2S3.js} +4 -4
- package/dist/chunks/{chunk-HDEYMVIJ.js → chunk-437YGKVA.js} +2 -2
- package/dist/chunks/{chunk-WGMKKKS2.js → chunk-4BBWDSDC.js} +1 -1
- package/dist/chunks/{chunk-KKOES3YK.js → chunk-4T5LR4P5.js} +55 -116
- package/dist/chunks/chunk-4T5LR4P5.js.map +7 -0
- package/dist/chunks/{chunk-PMC3BZ3M.js → chunk-5HZWM4JB.js} +1 -1
- package/dist/chunks/{chunk-REQTXUXO.js → chunk-5LBRVQT5.js} +1 -1
- package/dist/chunks/{chunk-BEDQTC44.js → chunk-5LL33G6X.js} +2 -2
- package/dist/chunks/{chunk-YUXYJB45.js → chunk-5RCVEFJS.js} +19 -8
- package/dist/chunks/chunk-5RCVEFJS.js.map +7 -0
- package/dist/chunks/{chunk-MDCOIZVX.js → chunk-6C6VNA2D.js} +2 -2
- package/dist/chunks/{chunk-P77NF36M.js → chunk-6CAQXUDY.js} +1 -1
- package/dist/chunks/{chunk-DPQE5NA4.js → chunk-7SRIFZDJ.js} +1 -1
- package/dist/chunks/{chunk-TI2CTTMA.js → chunk-7ZC22R33.js} +1 -1
- package/dist/chunks/{chunk-EV56PDOI.js → chunk-AX3VXMUS.js} +1 -1
- package/dist/chunks/{chunk-5MVUCX6O.js → chunk-AZHJLRRP.js} +1 -1
- package/dist/chunks/{chunk-LIBZWJEW.js → chunk-BNSPVA24.js} +11 -10
- package/dist/chunks/chunk-BNSPVA24.js.map +7 -0
- package/dist/chunks/{chunk-Z3J3WJ2K.js → chunk-BPMYW5DT.js} +415 -414
- package/dist/chunks/chunk-BPMYW5DT.js.map +7 -0
- package/dist/chunks/{chunk-QBW7VU7C.js → chunk-DWKF6SQH.js} +3 -3
- package/dist/chunks/{chunk-4RVYYLN7.js → chunk-E4C4N7OV.js} +1 -1
- package/dist/chunks/{chunk-4RVYYLN7.js.map → chunk-E4C4N7OV.js.map} +1 -1
- package/dist/chunks/chunk-ESRGV7DC.js +34 -0
- package/dist/chunks/chunk-ESRGV7DC.js.map +7 -0
- package/dist/chunks/{chunk-VSKGDU73.js → chunk-FKWFR23G.js} +2 -2
- package/dist/chunks/{chunk-E6BU32L2.js → chunk-H5F7M5D3.js} +2 -2
- package/dist/chunks/{chunk-DZPD6H7A.js → chunk-JXYXMP2Q.js} +2 -2
- package/dist/chunks/{chunk-65FLXXMH.js → chunk-KA543BHH.js} +8 -8
- package/dist/chunks/{chunk-MEQ7TAT7.js → chunk-KHMXPPO7.js} +4 -4
- package/dist/chunks/{chunk-G5ET7GFB.js → chunk-KQV5FGSS.js} +5 -5
- package/dist/chunks/{chunk-DPVCHIF7.js → chunk-KRBZO255.js} +1 -1
- package/dist/chunks/{chunk-Y33AS3MY.js → chunk-L2LWCVUF.js} +21 -7
- package/dist/chunks/chunk-L2LWCVUF.js.map +7 -0
- package/dist/chunks/{chunk-EKXQ7ZWV.js → chunk-L5ZJIOEF.js} +4 -4
- package/dist/chunks/{chunk-UUJN5ZCN.js → chunk-LBHVWSUP.js} +2 -2
- package/dist/chunks/{chunk-GL6HUBBX.js → chunk-LKDMUCWA.js} +6 -6
- package/dist/chunks/{chunk-HJCYE2AS.js → chunk-LUZMHHQF.js} +10 -10
- package/dist/chunks/{chunk-MXFN7OSL.js → chunk-MOGUUWKG.js} +1 -1
- package/dist/chunks/{chunk-4UDKRYWZ.js → chunk-N4772IDQ.js} +3 -3
- package/dist/chunks/{chunk-TJMA65RL.js → chunk-N5AH66UG.js} +168 -23
- package/dist/chunks/chunk-N5AH66UG.js.map +7 -0
- package/dist/chunks/{chunk-JJ67KF6A.js → chunk-PTIAF6KF.js} +4 -4
- package/dist/chunks/{chunk-YUJB4WDK.js → chunk-PVMCLI36.js} +1 -1
- package/dist/chunks/{chunk-3TLVYEGW.js → chunk-RTGKCKD3.js} +1 -1
- package/dist/chunks/{chunk-AKC4BUW5.js → chunk-SOBWNYOW.js} +7 -6
- package/dist/chunks/chunk-SOBWNYOW.js.map +7 -0
- package/dist/chunks/{chunk-3DBNJOZI.js → chunk-SUNG5KP5.js} +1 -1
- package/dist/chunks/{chunk-VBGSHKHX.js → chunk-SVRXO73D.js} +16 -13
- package/dist/chunks/chunk-SVRXO73D.js.map +7 -0
- package/dist/chunks/{chunk-Q55CB4Y4.js → chunk-WE7CQGRG.js} +2 -2
- package/dist/chunks/{chunk-V3IXG64X.js → chunk-WOMV4RCI.js} +404 -446
- package/dist/chunks/chunk-WOMV4RCI.js.map +7 -0
- package/dist/chunks/{chunk-ZAT5BSQI.js → chunk-WVJMXIKQ.js} +12 -12
- package/dist/chunks/{chunk-ZAT5BSQI.js.map → chunk-WVJMXIKQ.js.map} +1 -1
- package/dist/chunks/{chunk-DELUVYKS.js → chunk-XVNEJVZC.js} +2 -2
- package/dist/chunks/{chunk-KDY7XYYS.js → chunk-YQ3YJSMI.js} +1 -1
- package/dist/chunks/{chunk-6CNJ3CYQ.js → chunk-YUZBVKVH.js} +3 -3
- package/dist/chunks/{chunk-VJ2QSQ3E.js → chunk-ZXOTOID7.js} +2 -2
- package/dist/chunks/{client-OWTJ7TPE.js → client-QUCHWMEW.js} +5 -5
- package/dist/chunks/{customCommands-FA6HRXXV.js → customCommands-S6YGRUED.js} +5 -5
- package/dist/chunks/{engine-UBCAVO7E.js → engine-FRDEQVDF.js} +17 -17
- package/dist/chunks/{env-JIMGBRE2.js → env-YH77MILU.js} +3 -3
- package/dist/chunks/{kodeAgentSessionLoad-BZRTCPMB.js → kodeAgentSessionLoad-TBPU4TWU.js} +3 -3
- package/dist/chunks/{kodeAgentSessionResume-V3WB3OWQ.js → kodeAgentSessionResume-3CNE5T6N.js} +3 -3
- package/dist/chunks/{kodeHooks-R3YHG4ZI.js → kodeHooks-6SWQE5W7.js} +4 -4
- package/dist/chunks/{llm-C4F2Q7I2.js → llm-PONI6QWH.js} +47 -20
- package/dist/chunks/llm-PONI6QWH.js.map +7 -0
- package/dist/chunks/{llmLazy-IBED5LIH.js → llmLazy-O4T62IIT.js} +1 -1
- package/dist/chunks/{mcpCli-A744Z3FL.js → mcpCli-HIA4I4GG.js} +5 -5
- package/dist/chunks/{mentionProcessor-VV6DN2LJ.js → mentionProcessor-HH4EF7BE.js} +6 -6
- package/dist/chunks/{messages-ZR64JVON.js → messages-WKWCZBGM.js} +1 -1
- package/dist/chunks/{model-NPMMYL2U.js → model-4EIFU5QN.js} +5 -5
- package/dist/chunks/{openai-FEBNBOGM.js → openai-KTBJ2KNZ.js} +5 -5
- package/dist/chunks/{permissions-34CRWMCH.js → permissions-C3N4DKS2.js} +7 -7
- package/dist/chunks/{pluginRuntime-7YBUMVFI.js → pluginRuntime-2FKZLVA5.js} +3 -3
- package/dist/chunks/{pluginValidation-NZ4LOT3Q.js → pluginValidation-X5NZZCFA.js} +7 -7
- package/dist/chunks/registry-3UVW32YF.js +68 -0
- package/dist/chunks/{responsesStreaming-JNGE2P3D.js → responsesStreaming-LB4THIUM.js} +2 -2
- package/dist/chunks/{ripgrep-KGHLK4RO.js → ripgrep-N7O6M4IE.js} +4 -4
- package/dist/chunks/{runNonTextPrintMode-U3TKEYYN.js → runNonTextPrintMode-YFWCUTWZ.js} +12 -12
- package/dist/chunks/server-3CICV7EL.js +59 -0
- package/dist/chunks/server-FRP7OT4H.js +61 -0
- package/dist/chunks/{skillMarketplace-PPPUBC4N.js → skillMarketplace-4Y2H4JFK.js} +4 -4
- package/dist/chunks/{src-TVS6YABL.js → src-IETAWKYR.js} +30 -30
- package/dist/chunks/{src-QST7UD2A.js → src-OB2HE3RX.js} +27 -27
- package/dist/chunks/{src-DB7GKD4L.js → src-Y2IM2VKU.js} +78 -78
- package/dist/chunks/{thinking-O7LIIMFW.js → thinking-XG3FB4HO.js} +6 -6
- package/dist/chunks/{toolPermissionContext-UWGATCUZ.js → toolPermissionContext-RFYFDINH.js} +1 -1
- package/dist/chunks/{toolPermissionSettings-WD7CB37T.js → toolPermissionSettings-EEFURGBO.js} +5 -5
- package/dist/chunks/{useScreenLayout-PKLCMNZD.js → useScreenLayout-OUGQRR4I.js} +2 -2
- package/dist/chunks/{webOnlyMode-GJ6PQCPU.js → webOnlyMode-FRQBIAXG.js} +1 -1
- package/dist/entrypoints/cli.js +1 -1
- package/dist/entrypoints/daemon.js +1 -1
- package/dist/entrypoints/mcp.js +28 -28
- package/dist/index.js +5 -5
- package/dist/sdk/core.cjs +93 -34
- package/dist/sdk/core.cjs.map +3 -3
- package/dist/sdk/core.js +96 -37
- package/dist/sdk/core.js.map +4 -4
- package/dist/sdk/tools.cjs +1787 -1748
- package/dist/sdk/tools.cjs.map +4 -4
- package/dist/sdk/tools.js +1611 -1572
- package/dist/sdk/tools.js.map +4 -4
- package/package.json +1 -1
- package/dist/chunks/REPL-KD7YOSI5.js +0 -78
- package/dist/chunks/chunk-AKC4BUW5.js.map +0 -7
- package/dist/chunks/chunk-KKOES3YK.js.map +0 -7
- package/dist/chunks/chunk-LIBZWJEW.js.map +0 -7
- package/dist/chunks/chunk-LOCXPQNJ.js +0 -20
- package/dist/chunks/chunk-LOCXPQNJ.js.map +0 -7
- package/dist/chunks/chunk-TJMA65RL.js.map +0 -7
- package/dist/chunks/chunk-V3IXG64X.js.map +0 -7
- package/dist/chunks/chunk-VBGSHKHX.js.map +0 -7
- package/dist/chunks/chunk-Y33AS3MY.js.map +0 -7
- package/dist/chunks/chunk-YUXYJB45.js.map +0 -7
- package/dist/chunks/chunk-Z3J3WJ2K.js.map +0 -7
- package/dist/chunks/llm-C4F2Q7I2.js.map +0 -7
- package/dist/chunks/registry-FHPZ36EO.js +0 -68
- package/dist/chunks/server-Y42VR6YJ.js +0 -59
- package/dist/chunks/server-ZSC5G3TU.js +0 -61
- /package/dist/chunks/{Doctor-AES5ON33.js.map → Doctor-TWRIVOVW.js.map} +0 -0
- /package/dist/chunks/{LogList-PQJEJHHE.js.map → LogList-PUTPM24L.js.map} +0 -0
- /package/dist/chunks/{REPL-KD7YOSI5.js.map → REPL-YGIR5VXC.js.map} +0 -0
- /package/dist/chunks/{ResumeConversation-OWQ3DB4M.js.map → ResumeConversation-IJMKQXBU.js.map} +0 -0
- /package/dist/chunks/{ScreenFrame-AGLR6B4D.js.map → ScreenFrame-PQJRZ5DQ.js.map} +0 -0
- /package/dist/chunks/{agentLoader-BMWB4UKI.js.map → agentLoader-GOYNJTAO.js.map} +0 -0
- /package/dist/chunks/{agentsValidate-LSMJSFYW.js.map → agentsValidate-R26AKPAA.js.map} +0 -0
- /package/dist/chunks/{ask-3TSZR6AJ.js.map → ask-6SYVJONJ.js.map} +0 -0
- /package/dist/chunks/{autoUpdater-MEPC7LJF.js.map → autoUpdater-SDLJ5QSH.js.map} +0 -0
- /package/dist/chunks/{chunk-NC3RX5AB.js.map → chunk-2B2TR2S3.js.map} +0 -0
- /package/dist/chunks/{chunk-HDEYMVIJ.js.map → chunk-437YGKVA.js.map} +0 -0
- /package/dist/chunks/{chunk-WGMKKKS2.js.map → chunk-4BBWDSDC.js.map} +0 -0
- /package/dist/chunks/{chunk-PMC3BZ3M.js.map → chunk-5HZWM4JB.js.map} +0 -0
- /package/dist/chunks/{chunk-REQTXUXO.js.map → chunk-5LBRVQT5.js.map} +0 -0
- /package/dist/chunks/{chunk-BEDQTC44.js.map → chunk-5LL33G6X.js.map} +0 -0
- /package/dist/chunks/{chunk-MDCOIZVX.js.map → chunk-6C6VNA2D.js.map} +0 -0
- /package/dist/chunks/{chunk-P77NF36M.js.map → chunk-6CAQXUDY.js.map} +0 -0
- /package/dist/chunks/{chunk-DPQE5NA4.js.map → chunk-7SRIFZDJ.js.map} +0 -0
- /package/dist/chunks/{chunk-TI2CTTMA.js.map → chunk-7ZC22R33.js.map} +0 -0
- /package/dist/chunks/{chunk-EV56PDOI.js.map → chunk-AX3VXMUS.js.map} +0 -0
- /package/dist/chunks/{chunk-5MVUCX6O.js.map → chunk-AZHJLRRP.js.map} +0 -0
- /package/dist/chunks/{chunk-QBW7VU7C.js.map → chunk-DWKF6SQH.js.map} +0 -0
- /package/dist/chunks/{chunk-VSKGDU73.js.map → chunk-FKWFR23G.js.map} +0 -0
- /package/dist/chunks/{chunk-E6BU32L2.js.map → chunk-H5F7M5D3.js.map} +0 -0
- /package/dist/chunks/{chunk-DZPD6H7A.js.map → chunk-JXYXMP2Q.js.map} +0 -0
- /package/dist/chunks/{chunk-65FLXXMH.js.map → chunk-KA543BHH.js.map} +0 -0
- /package/dist/chunks/{chunk-MEQ7TAT7.js.map → chunk-KHMXPPO7.js.map} +0 -0
- /package/dist/chunks/{chunk-G5ET7GFB.js.map → chunk-KQV5FGSS.js.map} +0 -0
- /package/dist/chunks/{chunk-DPVCHIF7.js.map → chunk-KRBZO255.js.map} +0 -0
- /package/dist/chunks/{chunk-EKXQ7ZWV.js.map → chunk-L5ZJIOEF.js.map} +0 -0
- /package/dist/chunks/{chunk-UUJN5ZCN.js.map → chunk-LBHVWSUP.js.map} +0 -0
- /package/dist/chunks/{chunk-GL6HUBBX.js.map → chunk-LKDMUCWA.js.map} +0 -0
- /package/dist/chunks/{chunk-HJCYE2AS.js.map → chunk-LUZMHHQF.js.map} +0 -0
- /package/dist/chunks/{chunk-MXFN7OSL.js.map → chunk-MOGUUWKG.js.map} +0 -0
- /package/dist/chunks/{chunk-4UDKRYWZ.js.map → chunk-N4772IDQ.js.map} +0 -0
- /package/dist/chunks/{chunk-JJ67KF6A.js.map → chunk-PTIAF6KF.js.map} +0 -0
- /package/dist/chunks/{chunk-YUJB4WDK.js.map → chunk-PVMCLI36.js.map} +0 -0
- /package/dist/chunks/{chunk-3TLVYEGW.js.map → chunk-RTGKCKD3.js.map} +0 -0
- /package/dist/chunks/{chunk-3DBNJOZI.js.map → chunk-SUNG5KP5.js.map} +0 -0
- /package/dist/chunks/{chunk-Q55CB4Y4.js.map → chunk-WE7CQGRG.js.map} +0 -0
- /package/dist/chunks/{chunk-DELUVYKS.js.map → chunk-XVNEJVZC.js.map} +0 -0
- /package/dist/chunks/{chunk-KDY7XYYS.js.map → chunk-YQ3YJSMI.js.map} +0 -0
- /package/dist/chunks/{chunk-6CNJ3CYQ.js.map → chunk-YUZBVKVH.js.map} +0 -0
- /package/dist/chunks/{chunk-VJ2QSQ3E.js.map → chunk-ZXOTOID7.js.map} +0 -0
- /package/dist/chunks/{client-OWTJ7TPE.js.map → client-QUCHWMEW.js.map} +0 -0
- /package/dist/chunks/{customCommands-FA6HRXXV.js.map → customCommands-S6YGRUED.js.map} +0 -0
- /package/dist/chunks/{engine-UBCAVO7E.js.map → engine-FRDEQVDF.js.map} +0 -0
- /package/dist/chunks/{env-JIMGBRE2.js.map → env-YH77MILU.js.map} +0 -0
- /package/dist/chunks/{kodeAgentSessionLoad-BZRTCPMB.js.map → kodeAgentSessionLoad-TBPU4TWU.js.map} +0 -0
- /package/dist/chunks/{kodeAgentSessionResume-V3WB3OWQ.js.map → kodeAgentSessionResume-3CNE5T6N.js.map} +0 -0
- /package/dist/chunks/{kodeHooks-R3YHG4ZI.js.map → kodeHooks-6SWQE5W7.js.map} +0 -0
- /package/dist/chunks/{llmLazy-IBED5LIH.js.map → llmLazy-O4T62IIT.js.map} +0 -0
- /package/dist/chunks/{mcpCli-A744Z3FL.js.map → mcpCli-HIA4I4GG.js.map} +0 -0
- /package/dist/chunks/{mentionProcessor-VV6DN2LJ.js.map → mentionProcessor-HH4EF7BE.js.map} +0 -0
- /package/dist/chunks/{messages-ZR64JVON.js.map → messages-WKWCZBGM.js.map} +0 -0
- /package/dist/chunks/{model-NPMMYL2U.js.map → model-4EIFU5QN.js.map} +0 -0
- /package/dist/chunks/{openai-FEBNBOGM.js.map → openai-KTBJ2KNZ.js.map} +0 -0
- /package/dist/chunks/{permissions-34CRWMCH.js.map → permissions-C3N4DKS2.js.map} +0 -0
- /package/dist/chunks/{pluginRuntime-7YBUMVFI.js.map → pluginRuntime-2FKZLVA5.js.map} +0 -0
- /package/dist/chunks/{pluginValidation-NZ4LOT3Q.js.map → pluginValidation-X5NZZCFA.js.map} +0 -0
- /package/dist/chunks/{registry-FHPZ36EO.js.map → registry-3UVW32YF.js.map} +0 -0
- /package/dist/chunks/{responsesStreaming-JNGE2P3D.js.map → responsesStreaming-LB4THIUM.js.map} +0 -0
- /package/dist/chunks/{ripgrep-KGHLK4RO.js.map → ripgrep-N7O6M4IE.js.map} +0 -0
- /package/dist/chunks/{runNonTextPrintMode-U3TKEYYN.js.map → runNonTextPrintMode-YFWCUTWZ.js.map} +0 -0
- /package/dist/chunks/{server-Y42VR6YJ.js.map → server-3CICV7EL.js.map} +0 -0
- /package/dist/chunks/{server-ZSC5G3TU.js.map → server-FRP7OT4H.js.map} +0 -0
- /package/dist/chunks/{skillMarketplace-PPPUBC4N.js.map → skillMarketplace-4Y2H4JFK.js.map} +0 -0
- /package/dist/chunks/{src-TVS6YABL.js.map → src-IETAWKYR.js.map} +0 -0
- /package/dist/chunks/{src-QST7UD2A.js.map → src-OB2HE3RX.js.map} +0 -0
- /package/dist/chunks/{src-DB7GKD4L.js.map → src-Y2IM2VKU.js.map} +0 -0
- /package/dist/chunks/{thinking-O7LIIMFW.js.map → thinking-XG3FB4HO.js.map} +0 -0
- /package/dist/chunks/{toolPermissionContext-UWGATCUZ.js.map → toolPermissionContext-RFYFDINH.js.map} +0 -0
- /package/dist/chunks/{toolPermissionSettings-WD7CB37T.js.map → toolPermissionSettings-EEFURGBO.js.map} +0 -0
- /package/dist/chunks/{useScreenLayout-PKLCMNZD.js.map → useScreenLayout-OUGQRR4I.js.map} +0 -0
- /package/dist/chunks/{webOnlyMode-GJ6PQCPU.js.map → webOnlyMode-FRQBIAXG.js.map} +0 -0
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../packages/tools/src/registry.ts", "../../packages/tools/src/tools/ai/AskExpertModelTool/AskExpertModelTool.tsx", "../../packages/core/src/utils/markdown.ts", "../../packages/core/src/utils/expertChatStorage.ts", "../../packages/tools/src/tools/ai/AskExpertModelTool/call.ts", "../../packages/tools/src/tools/ai/AskExpertModelTool/prompt.ts", "../../packages/tools/src/tools/interaction/AskUserQuestionTool/AskUserQuestionTool.tsx", "../../packages/core/src/constants/figures.ts", "../../packages/tools/src/tools/interaction/AskUserQuestionTool/prompt.ts", "../../packages/tools/src/tools/system/BashTool/BashTool.tsx", "../../packages/core/src/permissions/bashReadOnly.ts", "../../packages/tools/src/tools/system/BashTool/BashToolResultMessage.tsx", "../../packages/tools/src/tools/system/BashTool/OutputLine.tsx", "../../packages/tools/src/tools/system/BashTool/prompt.ts", "../../apps/cli/src/ui/components/MaxSizedText.tsx", "../../packages/tools/src/tools/system/BashTool/text.ts", "../../packages/core/src/sandbox/systemSandbox.ts", "../../packages/core/src/sandbox/destructiveCommandGuard.ts", "../../packages/tools/src/tools/system/BashTool/bashGateSimpleRules.ts", "../../packages/tools/src/tools/system/BashTool/bashGateRules.ts", "../../packages/tools/src/tools/system/BashTool/llmSafetyGateDump.ts", "../../packages/tools/src/tools/system/BashTool/llmSafetyGatePrompt.ts", "../../packages/tools/src/tools/system/BashTool/llmSafetyGateVerdict.ts", "../../packages/tools/src/tools/system/BashTool/llmSafetyGate.ts", "../../packages/protocol/src/commandSource.ts", "../../packages/tools/src/tools/system/BashTool/executeForeground.tsx", "../../packages/tools/src/tools/system/BashTool/BashToolRunInBackgroundOverlay.tsx", "../../packages/tools/src/tools/system/BashTool/utils.ts", "../../packages/tools/src/tools/system/BashTool/summarizeOutput.ts", "../../packages/core/src/sandbox/sandboxNetworkInfrastructure/httpProxy.ts", "../../packages/core/src/sandbox/sandboxNetworkInfrastructure/socks5Proxy.ts", "../../packages/core/src/sandbox/sandboxNetworkInfrastructure/linuxBridge.ts", "../../packages/core/src/sandbox/sandboxNetworkInfrastructure.ts", "../../packages/tools/src/tools/network/WebFetchTool/WebFetchTool.tsx", "../../packages/tools/src/tools/network/WebFetchTool/prompt.ts", "../../packages/tools/src/tools/network/WebFetchTool/htmlToMarkdown.ts", "../../packages/tools/src/tools/network/WebFetchTool/cache.ts", "../../packages/tools/src/tools/network/WebFetchTool/utils.ts", "../../packages/tools/src/tools/system/BashTool/sandboxNetwork.ts", "../../packages/tools/src/tools/system/BashTool/call.ts", "../../packages/tools/src/tools/system/TaskOutputTool/TaskOutputTool.tsx", "../../packages/tools/src/tools/system/TaskOutputTool/prompt.ts", "../../packages/tools/src/tools/interaction/PlanModeTool/EnterPlanModeTool.tsx", "../../packages/tools/src/tools/interaction/PlanModeTool/prompt.ts", "../../packages/tools/src/tools/interaction/PlanModeTool/ExitPlanModeTool.tsx", "../../packages/tools/src/tools/filesystem/FileEditTool/FileEditTool.tsx", "../../packages/tools/src/tools/filesystem/NotebookEditTool/NotebookEditTool.tsx", "../../packages/tools/src/tools/filesystem/NotebookEditTool/prompt.ts", "../../packages/tools/src/tools/filesystem/NotebookEditTool/cells.ts", "../../packages/tools/src/tools/filesystem/NotebookEditTool/editor.ts", "../../packages/tools/src/tools/filesystem/FileEditTool/prompt.ts", "../../packages/tools/src/tools/filesystem/FileEditTool/utils.ts", "../../packages/tools/src/tools/filesystem/GlobTool/GlobTool.tsx", "../../packages/tools/src/tools/filesystem/GlobTool/prompt.ts", "../../packages/tools/src/tools/filesystem/LSTool/LSTool.tsx", "../../packages/tools/src/tools/filesystem/LSTool/prompt.ts", "../../packages/tools/src/tools/search/GrepTool/GrepTool.tsx", "../../packages/tools/src/tools/search/GrepTool/prompt.ts", "../../packages/tools/src/tools/search/GrepTool/helpers.ts", "../../packages/tools/src/tools/search/GrepTool/execute.ts", "../../packages/tools/src/tools/system/KillShellTool/KillShellTool.tsx", "../../packages/tools/src/tools/system/KillShellTool/prompt.ts", "../../packages/tools/src/tools/mcp/ListMcpResourcesTool/ListMcpResourcesTool.tsx", "../../packages/tools/src/tools/mcp/ListMcpResourcesTool/prompt.ts", "../../packages/core/src/utils/toolOutputDisplay.ts", "../../packages/tools/src/tools/system/LspTool/LspTool.tsx", "../../packages/tools/src/tools/system/LspTool/constants.ts", "../../packages/tools/src/tools/system/LspTool/summary.tsx", "../../packages/tools/src/tools/system/LspTool/prompt.ts", "../../packages/tools/src/tools/mcp/MCPTool/MCPTool.tsx", "../../packages/tools/src/tools/mcp/MCPTool/prompt.ts", "../../packages/tools/src/tools/mcp/MCPSearchTool/MCPSearchTool.tsx", "../../packages/tools/src/tools/mcp/MCPSearchTool/prompt.ts", "../../packages/tools/src/tools/mcp/ReadMcpResourceTool/ReadMcpResourceTool.tsx", "../../packages/tools/src/tools/mcp/ReadMcpResourceTool/prompt.ts", "../../packages/tools/src/tools/interaction/SlashCommandTool/SlashCommandTool.tsx", "../../packages/core/src/utils/agentTranscripts.ts", "../../packages/tools/src/tools/ai/TaskTool/prompt.ts", "../../packages/tools/src/tools/ai/TaskTool/forkContext.ts", "../../packages/tools/src/tools/ai/TaskTool/models.ts", "../../packages/tools/src/tools/ai/TaskTool/toolSpec.ts", "../../packages/tools/src/tools/ai/TaskTool/permissions.ts", "../../packages/tools/src/tools/ai/TaskTool/callBackground.ts", "../../packages/tools/src/tools/ai/TaskTool/assistantText.ts", "../../packages/tools/src/tools/ai/TaskTool/callForeground.ts", "../../packages/tools/src/tools/ai/TaskTool/call.ts", "../../packages/tools/src/tools/interaction/SlashCommandTool/prompt.ts", "../../packages/tools/src/tools/interaction/SlashCommandTool/utils.ts", "../../packages/tools/src/tools/interaction/SkillTool/SkillTool.tsx", "../../packages/tools/src/tools/interaction/SkillTool/prompt.ts", "../../packages/tools/src/tools/ai/TaskTool/constants.ts", "../../packages/tools/src/tools/ai/TaskTool/schema.ts", "../../packages/tools/src/tools/ai/TaskTool/render.tsx", "../../packages/tools/src/tools/ai/TaskTool/TaskTool.tsx", "../../packages/tools/src/tools/interaction/TodoWriteTool/TodoWriteTool.tsx", "../../packages/tools/src/tools/interaction/TodoWriteTool/prompt.ts", "../../packages/tools/src/tools/search/WebSearchTool/WebSearchTool.tsx", "../../packages/tools/src/tools/search/WebSearchTool/prompt.ts", "../../packages/tools/src/tools/search/WebSearchTool/searchProviders.ts"],
|
|
4
|
-
"sourcesContent": ["import { memoize } from 'lodash-es'\nimport { resolveToolDescription, type Tool } from '#core/tooling/Tool'\n\nimport { AskExpertModelTool } from '#tools/tools/ai/AskExpertModelTool/AskExpertModelTool'\nimport { AskUserQuestionTool } from '#tools/tools/interaction/AskUserQuestionTool/AskUserQuestionTool'\nimport { BashTool } from '#tools/tools/system/BashTool/BashTool'\nimport { TaskOutputTool } from '#tools/tools/system/TaskOutputTool/TaskOutputTool'\nimport { EnterPlanModeTool } from '#tools/tools/interaction/PlanModeTool/EnterPlanModeTool'\nimport { ExitPlanModeTool } from '#tools/tools/interaction/PlanModeTool/ExitPlanModeTool'\nimport { FileEditTool } from '#tools/tools/filesystem/FileEditTool/FileEditTool'\nimport { FileReadTool } from '#tools/tools/filesystem/FileReadTool/FileReadTool'\nimport { FileWriteTool } from '#tools/tools/filesystem/FileWriteTool/FileWriteTool'\nimport { GlobTool } from '#tools/tools/filesystem/GlobTool/GlobTool'\nimport { LSTool } from '#tools/tools/filesystem/LSTool/LSTool'\nimport { GrepTool } from '#tools/tools/search/GrepTool/GrepTool'\nimport { KillShellTool } from '#tools/tools/system/KillShellTool/KillShellTool'\nimport { ListMcpResourcesTool } from '#tools/tools/mcp/ListMcpResourcesTool/ListMcpResourcesTool'\nimport { LspTool } from '#tools/tools/system/LspTool/LspTool'\nimport { MCPTool } from '#tools/tools/mcp/MCPTool/MCPTool'\nimport { MCPSearchTool } from '#tools/tools/mcp/MCPSearchTool/MCPSearchTool'\nimport { NotebookEditTool } from '#tools/tools/filesystem/NotebookEditTool/NotebookEditTool'\nimport { ReadMcpResourceTool } from '#tools/tools/mcp/ReadMcpResourceTool/ReadMcpResourceTool'\nimport { SlashCommandTool } from '#tools/tools/interaction/SlashCommandTool/SlashCommandTool'\nimport { SkillTool } from '#tools/tools/interaction/SkillTool/SkillTool'\nimport { TaskTool } from '#tools/tools/ai/TaskTool/TaskTool'\nimport { TodoWriteTool } from '#tools/tools/interaction/TodoWriteTool/TodoWriteTool'\nimport { WebFetchTool } from '#tools/tools/network/WebFetchTool/WebFetchTool'\nimport { WebSearchTool } from '#tools/tools/search/WebSearchTool/WebSearchTool'\n\nimport { getMCPTools, getMcpListChangedVersion } from '#core/mcp/client'\n\n// Base tool list for the CLI toolset\nexport const getAllTools = (): Tool[] => [\n TaskTool as unknown as Tool,\n AskExpertModelTool as unknown as Tool,\n BashTool as unknown as Tool,\n TaskOutputTool as unknown as Tool,\n KillShellTool as unknown as Tool,\n LSTool as unknown as Tool,\n GlobTool as unknown as Tool,\n GrepTool as unknown as Tool,\n LspTool as unknown as Tool,\n FileReadTool as unknown as Tool,\n FileEditTool as unknown as Tool,\n FileWriteTool as unknown as Tool,\n NotebookEditTool as unknown as Tool,\n TodoWriteTool as unknown as Tool,\n WebSearchTool as unknown as Tool,\n WebFetchTool as unknown as Tool,\n AskUserQuestionTool as unknown as Tool,\n EnterPlanModeTool as unknown as Tool,\n ExitPlanModeTool as unknown as Tool,\n SlashCommandTool as unknown as Tool,\n SkillTool as unknown as Tool,\n ListMcpResourcesTool as unknown as Tool,\n ReadMcpResourceTool as unknown as Tool,\n MCPSearchTool as unknown as Tool,\n MCPTool as unknown as Tool,\n]\n\nexport const getTools = memoize(\n async (_includeOptional?: boolean): Promise<Tool[]> => {\n const tools = [...getAllTools(), ...(await getMCPTools())]\n\n const isEnabled = await Promise.all(tools.map(tool => tool.isEnabled()))\n const enabledTools = tools.filter((_, i) => isEnabled[i])\n\n // Populate cachedDescription for adapters that require synchronous access.\n await Promise.all(enabledTools.map(tool => resolveToolDescription(tool)))\n\n return enabledTools\n },\n (_includeOptional?: boolean) =>\n `${_includeOptional ?? ''}:mcp-tools@${getMcpListChangedVersion('tools')}`,\n)\n\nexport const getReadOnlyTools = memoize(async (): Promise<Tool[]> => {\n const tools = getAllTools().filter(tool => tool.isReadOnly())\n const isEnabled = await Promise.all(tools.map(tool => tool.isEnabled()))\n const enabledTools = tools.filter((_, index) => isEnabled[index])\n\n // Populate cachedDescription for adapters that require synchronous access.\n await Promise.all(enabledTools.map(tool => resolveToolDescription(tool)))\n\n return enabledTools\n})\n", "import { Box, Text } from 'ink'\nimport React from 'react'\nimport { z } from 'zod'\nimport type { ToolUseContext, ValidationResult } from '#core/tooling/Tool'\nimport { Tool } from '#core/tooling/Tool'\nimport { applyMarkdown } from '#core/utils/markdown'\nimport { getModelManager } from '#core/utils/model'\nimport { getTheme } from '#core/utils/theme'\nimport { callAskExpertModelTool } from './call'\nimport { DESCRIPTION, PROMPT } from './prompt'\n\nexport const inputSchema = z.strictObject({\n question: z\n .string()\n .describe(\n 'A fully self-contained question (include all background context, constraints, and a clear ask).',\n ),\n expert_model: z\n .string()\n .describe(\n 'The expert model to use (e.g., gpt-5, claude-3-5-sonnet-20241022)',\n ),\n chat_session_id: z\n .string()\n .describe('Use \"new\" for a new session, or an existing session ID.'),\n})\n\ntype Input = z.infer<typeof inputSchema>\n\nexport type Out = {\n chatSessionId: string\n expertModelName: string\n expertAnswer: string\n}\n\nfunction normalizeModelName(modelName: string): string {\n return modelName.toLowerCase().replace(/[^a-z0-9]/g, '')\n}\n\nfunction getCurrentModelName(context?: ToolUseContext): string {\n if (typeof context?.options?.model === 'string') return context.options.model\n const modelName = getModelManager().getModelName('main')\n return modelName ?? ''\n}\n\nasync function validateInput(\n input: Input,\n context?: ToolUseContext,\n): Promise<ValidationResult> {\n const question = input.question.trim()\n const expertModel = input.expert_model.trim()\n const sessionId = input.chat_session_id.trim()\n\n if (!question) return { result: false, message: 'Question cannot be empty' }\n if (!expertModel)\n return { result: false, message: 'Expert model must be specified' }\n if (!sessionId) {\n return {\n result: false,\n message: 'Chat session ID must be specified (use \"new\" for new session)',\n }\n }\n\n const currentModel = getCurrentModelName(context)\n if (\n currentModel &&\n normalizeModelName(currentModel) === normalizeModelName(expertModel)\n ) {\n return {\n result: false,\n message: `You are already running as ${currentModel}. Please choose a different model to consult.`,\n }\n }\n\n const modelManager = getModelManager()\n const resolved = modelManager.resolveModelWithInfo(expertModel)\n if (!resolved.success) {\n const available = modelManager.getAllAvailableModelNames()\n return {\n result: false,\n message:\n available.length > 0\n ? `Model '${expertModel}' is not configured. Available models: ${available.join(', ')}. Configure it via /model.`\n : `Model '${expertModel}' is not configured and no models are currently available. Configure a model via /model first.`,\n }\n }\n\n return { result: true }\n}\n\nexport const AskExpertModelTool = {\n name: 'AskExpertModel',\n async description() {\n return DESCRIPTION\n },\n async prompt() {\n return PROMPT\n },\n inputSchema,\n userFacingName() {\n return 'AskExpertModel'\n },\n async isEnabled() {\n return true\n },\n isReadOnly() {\n return true\n },\n isConcurrencySafe() {\n return true\n },\n needsPermissions() {\n return false\n },\n validateInput,\n renderToolUseMessage(\n { question, expert_model, chat_session_id },\n { verbose },\n ) {\n if (!expert_model) return null\n\n const isNewSession = chat_session_id === 'new'\n const sessionLabel = isNewSession\n ? 'new session'\n : `session ${chat_session_id.slice(0, 8)}\u2026`\n const theme = getTheme()\n\n if (!verbose) {\n return (\n <Box flexDirection=\"column\">\n <Text bold color=\"yellow\">\n {expert_model}{' '}\n </Text>\n <Text color={theme.secondaryText} dimColor>\n ({sessionLabel})\n </Text>\n </Box>\n )\n }\n\n const preview =\n question.length > 300 ? `${question.slice(0, 300)}\u2026` : question\n return (\n <Box flexDirection=\"column\">\n <Text bold color=\"yellow\">\n {expert_model}\n </Text>\n <Text color={theme.secondaryText}>{sessionLabel}</Text>\n <Box marginTop={1}>\n <Text color={theme.text}>{preview}</Text>\n </Box>\n </Box>\n )\n },\n renderToolResultMessage(output: Out, { verbose }) {\n const theme = getTheme()\n const answer = (output.expertAnswer ?? '').trim()\n const shown = verbose\n ? answer\n : answer.length > 800\n ? `${answer.slice(0, 800)}\u2026`\n : answer\n\n return (\n <Box flexDirection=\"column\">\n <Text bold color={theme.text}>\n Response from {output.expertModelName}:\n </Text>\n <Box marginTop={1}>\n <Text color={theme.text}>{applyMarkdown(shown)}</Text>\n </Box>\n <Box marginTop={1}>\n <Text color={theme.secondaryText} dimColor>\n Session: {output.chatSessionId.slice(0, 8)}\n </Text>\n </Box>\n </Box>\n )\n },\n renderToolUseRejectedMessage() {\n const theme = getTheme()\n return (\n <Box flexDirection=\"row\">\n <Text color={theme.secondaryText} dimColor>\n Expert consultation cancelled\n </Text>\n </Box>\n )\n },\n renderResultForAssistant(output: Out): string {\n return `[Expert consultation completed]\nExpert Model: ${output.expertModelName}\nSession ID: ${output.chatSessionId}\nTo continue this conversation, reuse this Session ID in the next AskExpertModel call.\n\n${output.expertAnswer}`\n },\n async *call(\n input: Input,\n { abortController, readFileTimestamps }: ToolUseContext,\n ) {\n const normalizedInput = {\n question: String(input.question ?? ''),\n expert_model: String(input.expert_model ?? ''),\n chat_session_id: String(input.chat_session_id ?? ''),\n }\n yield* callAskExpertModelTool(\n normalizedInput,\n { abortController, readFileTimestamps },\n output => this.renderResultForAssistant(output),\n )\n },\n} satisfies Tool<typeof inputSchema, Out>\n", "import { marked, Token } from 'marked'\nimport { stripSystemMessages } from './messages'\nimport chalk from 'chalk'\nimport { EOL } from 'os'\nimport { highlight, supportsLanguage } from 'cli-highlight'\nimport { logError } from './log'\n\nexport function applyMarkdown(content: string): string {\n return marked\n .lexer(stripSystemMessages(content))\n .map(_ => format(_))\n .join('')\n .trim()\n}\n\nfunction format(\n token: Token,\n listDepth = 0,\n orderedListNumber: number | null = null,\n parent: Token | null = null,\n): string {\n switch (token.type) {\n case 'blockquote':\n return chalk.dim.italic((token.tokens ?? []).map(_ => format(_)).join(''))\n case 'code':\n if (token.lang && supportsLanguage(token.lang)) {\n return highlight(token.text, { language: token.lang }) + EOL\n } else {\n logError(\n `Language not supported while highlighting code, falling back to markdown: ${token.lang}`,\n )\n return highlight(token.text, { language: 'markdown' }) + EOL\n }\n case 'codespan':\n // inline code\n return chalk.blue(token.text)\n case 'em':\n return chalk.italic((token.tokens ?? []).map(_ => format(_)).join(''))\n case 'strong':\n return chalk.bold((token.tokens ?? []).map(_ => format(_)).join(''))\n case 'heading':\n switch (token.depth) {\n case 1: // h1\n return (\n chalk.bold.italic.underline(\n (token.tokens ?? []).map(_ => format(_)).join(''),\n ) +\n EOL +\n EOL\n )\n case 2: // h2\n return (\n chalk.bold((token.tokens ?? []).map(_ => format(_)).join('')) +\n EOL +\n EOL\n )\n default: // h3+\n return (\n chalk.bold.dim((token.tokens ?? []).map(_ => format(_)).join('')) +\n EOL +\n EOL\n )\n }\n case 'hr':\n return '---'\n case 'image':\n return `[Image: ${token.title}: ${token.href}]`\n case 'link':\n return chalk.blue(token.href)\n case 'list': {\n return token.items\n .map((_: Token, index: number) =>\n format(\n _,\n listDepth,\n token.ordered ? token.start + index : null,\n token,\n ),\n )\n .join('')\n }\n case 'list_item':\n return (token.tokens ?? [])\n .map(\n _ =>\n `${' '.repeat(listDepth)}${format(_, listDepth + 1, orderedListNumber, token)}`,\n )\n .join('')\n case 'paragraph':\n return (token.tokens ?? []).map(_ => format(_)).join('') + EOL\n case 'space':\n return EOL\n case 'text':\n if (parent?.type === 'list_item') {\n return `${orderedListNumber === null ? '-' : getListNumber(listDepth, orderedListNumber) + '.'} ${token.tokens ? token.tokens.map(_ => format(_, listDepth, orderedListNumber, token)).join('') : token.text}${EOL}`\n } else {\n return token.text\n }\n }\n // NOTE: tables are intentionally not handled by this formatter.\n return ''\n}\n\nconst DEPTH_1_LIST_NUMBERS = [\n 'a',\n 'b',\n 'c',\n 'd',\n 'e',\n 'f',\n 'g',\n 'h',\n 'i',\n 'j',\n 'k',\n 'l',\n 'm',\n 'n',\n 'o',\n 'p',\n 'q',\n 'r',\n 's',\n 't',\n 'u',\n 'v',\n 'w',\n 'x',\n 'y',\n 'z',\n 'aa',\n 'ab',\n 'ac',\n 'ad',\n 'ae',\n 'af',\n 'ag',\n 'ah',\n 'ai',\n 'aj',\n 'ak',\n 'al',\n 'am',\n 'an',\n 'ao',\n 'ap',\n 'aq',\n 'ar',\n 'as',\n 'at',\n 'au',\n 'av',\n 'aw',\n 'ax',\n 'ay',\n 'az',\n]\nconst DEPTH_2_LIST_NUMBERS = [\n 'i',\n 'ii',\n 'iii',\n 'iv',\n 'v',\n 'vi',\n 'vii',\n 'viii',\n 'ix',\n 'x',\n 'xi',\n 'xii',\n 'xiii',\n 'xiv',\n 'xv',\n 'xvi',\n 'xvii',\n 'xviii',\n 'xix',\n 'xx',\n 'xxi',\n 'xxii',\n 'xxiii',\n 'xxiv',\n 'xxv',\n 'xxvi',\n 'xxvii',\n 'xxviii',\n 'xxix',\n 'xxx',\n 'xxxi',\n 'xxxii',\n 'xxxiii',\n 'xxxiv',\n 'xxxv',\n 'xxxvi',\n 'xxxvii',\n 'xxxviii',\n 'xxxix',\n 'xl',\n]\n\nfunction getListNumber(listDepth: number, orderedListNumber: number): string {\n switch (listDepth) {\n case 0:\n case 1:\n return orderedListNumber.toString()\n case 2:\n return DEPTH_1_LIST_NUMBERS[orderedListNumber - 1]! // NOTE: list markers are intentionally fixed.\n case 3:\n return DEPTH_2_LIST_NUMBERS[orderedListNumber - 1]! // NOTE: list markers are intentionally fixed.\n default:\n return orderedListNumber.toString()\n }\n}\n", "import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs'\nimport { join } from 'path'\nimport { randomUUID } from 'crypto'\nimport { debug as debugLogger } from '#core/utils/debugLogger'\nimport { logError } from '#core/utils/log'\nimport { getKodeRoot } from '#config/dataRoots'\n\n/**\n * Expert Chat Session Storage - \u6781\u7B80\u7248\n * \u5B58\u50A8\u7B26\u5408OpenAI\u683C\u5F0F\u7684messages\u5386\u53F2\n */\n\nexport interface ChatMessage {\n role: 'user' | 'assistant'\n content: string\n}\n\nexport interface ExpertChatSession {\n sessionId: string\n expertModel: string\n messages: ChatMessage[]\n createdAt: number\n lastUpdated: number\n}\n\n/**\n * \u83B7\u53D6\u4E13\u5BB6\u804A\u5929\u5B58\u50A8\u76EE\u5F55\n */\nfunction getExpertChatDirectory(): string {\n const configDir = getKodeRoot()\n const expertChatDir = join(configDir, 'expert-chats')\n\n if (!existsSync(expertChatDir)) {\n mkdirSync(expertChatDir, { recursive: true })\n }\n\n return expertChatDir\n}\n\n/**\n * \u83B7\u53D6\u4F1A\u8BDD\u6587\u4EF6\u8DEF\u5F84 - \u4F7F\u7528 sessionId.json \u683C\u5F0F\n */\nfunction getSessionFilePath(sessionId: string): string {\n return join(getExpertChatDirectory(), `${sessionId}.json`)\n}\n\n/**\n * \u521B\u5EFA\u65B0\u7684\u4E13\u5BB6\u804A\u5929\u4F1A\u8BDD\n */\nexport function createExpertChatSession(\n expertModel: string,\n): ExpertChatSession {\n const sessionId = randomUUID().slice(0, 5)\n const session: ExpertChatSession = {\n sessionId,\n expertModel,\n messages: [],\n createdAt: Date.now(),\n lastUpdated: Date.now(),\n }\n\n saveExpertChatSession(session)\n return session\n}\n\n/**\n * \u52A0\u8F7D\u73B0\u6709\u4E13\u5BB6\u804A\u5929\u4F1A\u8BDD\n */\nexport function loadExpertChatSession(\n sessionId: string,\n): ExpertChatSession | null {\n const filePath = getSessionFilePath(sessionId)\n\n if (!existsSync(filePath)) {\n return null\n }\n\n try {\n const content = readFileSync(filePath, 'utf-8')\n return JSON.parse(content) as ExpertChatSession\n } catch (error) {\n logError(error)\n debugLogger.warn('EXPERT_CHAT_SESSION_LOAD_FAILED', {\n sessionId,\n error: error instanceof Error ? error.message : String(error),\n })\n return null\n }\n}\n\n/**\n * \u4FDD\u5B58\u4E13\u5BB6\u804A\u5929\u4F1A\u8BDD\n */\nexport function saveExpertChatSession(session: ExpertChatSession): void {\n const filePath = getSessionFilePath(session.sessionId)\n\n try {\n session.lastUpdated = Date.now()\n writeFileSync(filePath, JSON.stringify(session, null, 2), 'utf-8')\n } catch (error) {\n logError(error)\n debugLogger.warn('EXPERT_CHAT_SESSION_SAVE_FAILED', {\n sessionId: session.sessionId,\n error: error instanceof Error ? error.message : String(error),\n })\n throw error\n }\n}\n\n/**\n * \u6DFB\u52A0\u6D88\u606F\u5230\u4F1A\u8BDD\n */\nexport function addMessageToSession(\n sessionId: string,\n role: 'user' | 'assistant',\n content: string,\n): ExpertChatSession | null {\n const session = loadExpertChatSession(sessionId)\n if (!session) {\n return null\n }\n\n session.messages.push({ role, content })\n saveExpertChatSession(session)\n\n return session\n}\n\n/**\n * \u83B7\u53D6\u4F1A\u8BDD\u7684\u6D88\u606F\u5386\u53F2 - \u8FD4\u56DEOpenAI\u683C\u5F0F\n */\nexport function getSessionMessages(sessionId: string): ChatMessage[] {\n const session = loadExpertChatSession(sessionId)\n return session?.messages || []\n}\n\n/**\n * \u751F\u6210\u65B0\u7684\u4F1A\u8BDDID\n */\nexport function generateSessionId(): string {\n return randomUUID().slice(0, 5)\n}\n", "import { logError } from '#core/utils/log'\nimport { debug as debugLogger } from '#core/utils/debugLogger'\nimport { getModelManager } from '#core/utils/model'\nimport type { AssistantMessage } from '#core/query'\nimport {\n addMessageToSession,\n createExpertChatSession,\n getSessionMessages,\n loadExpertChatSession,\n} from '#core/utils/expertChatStorage'\nimport {\n createAssistantMessage,\n createUserMessage,\n INTERRUPT_MESSAGE,\n} from '#core/utils/messages'\nimport { queryLLM } from '#core/ai/llmLazy'\nimport type { Out } from './AskExpertModelTool'\n\ntype Input = {\n question: string\n expert_model: string\n chat_session_id: string\n}\n\ntype Context = {\n abortController: AbortController\n readFileTimestamps: Record<string, number>\n}\n\ntype ToolYield =\n | { type: 'progress'; content: AssistantMessage }\n | { type: 'result'; data: Out; resultForAssistant: string }\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === 'object'\n}\n\nfunction extractAssistantText(message: AssistantMessage): string {\n const content = message?.message?.content as unknown\n\n if (typeof content === 'string') return content\n if (!Array.isArray(content)) return ''\n\n const parts: string[] = []\n for (const block of content) {\n if (!isRecord(block)) continue\n if (block.type === 'text' && typeof block.text === 'string') {\n parts.push(block.text)\n }\n }\n return parts.join('\\n')\n}\n\nfunction isInterrupted(\n error: unknown,\n abortController: AbortController,\n interruptedFlag: boolean,\n): boolean {\n if (interruptedFlag) return true\n if (abortController.signal.aborted) return true\n if (!isRecord(error)) return false\n return error.name === 'AbortError'\n}\n\nasync function withTimeout<T>(\n promise: Promise<T>,\n timeoutMs: number,\n): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n reject(new Error(`Expert model query timed out after ${timeoutMs}ms`))\n }, timeoutMs)\n\n promise\n .then(value => resolve(value))\n .catch(err => reject(err))\n .finally(() => clearTimeout(timeoutId))\n })\n}\n\nfunction interruptResult(expertModelName: string): ToolYield {\n return {\n type: 'result',\n data: {\n chatSessionId: 'interrupted',\n expertModelName,\n expertAnswer: INTERRUPT_MESSAGE,\n },\n resultForAssistant: INTERRUPT_MESSAGE,\n }\n}\n\nexport async function* callAskExpertModelTool(\n input: Input,\n context: Context,\n renderResultForAssistant: (output: Out) => string,\n): AsyncGenerator<ToolYield> {\n const { question, expert_model, chat_session_id } = input\n const { abortController } = context\n\n const expertModel = expert_model\n let sessionId = ''\n let interrupted = false\n\n const abortListener = () => {\n interrupted = true\n }\n abortController.signal.addEventListener('abort', abortListener)\n\n try {\n if (abortController.signal.aborted) {\n yield interruptResult(expertModel)\n return\n }\n\n if (chat_session_id === 'new') {\n sessionId = createExpertChatSession(expertModel).sessionId\n } else {\n sessionId = chat_session_id\n const session = loadExpertChatSession(sessionId)\n if (!session) {\n sessionId = createExpertChatSession(expertModel).sessionId\n }\n }\n\n if (interrupted || abortController.signal.aborted) {\n yield interruptResult(expertModel)\n return\n }\n\n const history = (() => {\n try {\n return getSessionMessages(sessionId)\n } catch (error) {\n logError(error)\n return []\n }\n })()\n\n const conversation = [...history, { role: 'user', content: question }]\n const llmMessages = conversation.map(msg =>\n msg.role === 'user'\n ? createUserMessage(msg.content)\n : createAssistantMessage(msg.content),\n )\n\n if (interrupted || abortController.signal.aborted) {\n yield interruptResult(expertModel)\n return\n }\n\n yield {\n type: 'progress',\n content: createAssistantMessage(\n `Connecting to ${expertModel}... (timeout: 5 minutes)`,\n ),\n }\n\n const modelManager = getModelManager()\n const modelResolution = modelManager.resolveModelWithInfo(expertModel)\n debugLogger.api('EXPERT_MODEL_RESOLUTION', {\n requestedModel: expertModel,\n success: modelResolution.success,\n profileName: modelResolution.profile?.name,\n profileModelName: modelResolution.profile?.modelName,\n provider: modelResolution.profile?.provider,\n isActive: modelResolution.profile?.isActive,\n error: modelResolution.error,\n })\n\n const timeoutMs = 300_000\n const response = await withTimeout(\n queryLLM(llmMessages, [], 0, [], abortController.signal, {\n safeMode: false,\n model: expertModel,\n prependCLISysprompt: false,\n }),\n timeoutMs,\n )\n\n if (interrupted || abortController.signal.aborted) {\n yield interruptResult(expertModel)\n return\n }\n\n const expertAnswer = extractAssistantText(response).trim()\n if (!expertAnswer) {\n throw new Error('Expert response was empty')\n }\n\n try {\n addMessageToSession(sessionId, 'user', question)\n addMessageToSession(sessionId, 'assistant', expertAnswer)\n } catch (error) {\n logError(error)\n }\n\n const result: Out = {\n chatSessionId: sessionId,\n expertModelName: expertModel,\n expertAnswer,\n }\n\n yield {\n type: 'result',\n data: result,\n resultForAssistant: renderResultForAssistant(result),\n }\n } catch (error) {\n if (isInterrupted(error, abortController, interrupted)) {\n yield interruptResult(expertModel)\n return\n }\n\n logError(error)\n const errorMessage = error instanceof Error ? error.message : String(error)\n const result: Out = {\n chatSessionId: sessionId || 'error-session',\n expertModelName: expertModel,\n expertAnswer: `\u274C ${errorMessage || 'Expert consultation failed with unknown error'}`,\n }\n yield {\n type: 'result',\n data: result,\n resultForAssistant: renderResultForAssistant(result),\n }\n } finally {\n abortController.signal.removeEventListener('abort', abortListener)\n }\n}\n", "export const DESCRIPTION =\n 'Consult an external AI model for a second opinion or specialized analysis.'\n\nexport const PROMPT = `Ask a question to a specific external AI model for expert analysis.\n\nCRITICAL: The expert model receives ONLY your \\`question\\` (plus the prior messages in the same \\`chat_session_id\\`).\nIt does NOT have access to the user\u2019s current repository context unless you include it in the question.\n\nThe \\`question\\` MUST be self-contained:\n1) Background / context\n2) Current situation / constraints\n3) A clear, independent question\n\nUse this tool when you want a different model\u2019s perspective, not for task execution.`\n", "import { Box, Text } from 'ink'\nimport React from 'react'\nimport { z } from 'zod'\nimport { BLACK_CIRCLE } from '#core/constants/figures'\nimport { PRODUCT_NAME } from '#core/constants/product'\nimport { Tool, ToolUseContext } from '#core/tooling/Tool'\nimport { getTheme } from '#core/utils/theme'\nimport { DESCRIPTION, PROMPT, TOOL_NAME_FOR_PROMPT } from './prompt'\n\nconst optionSchema = z.object({\n label: z.string(),\n description: z.string(),\n})\n\nconst questionSchema = z.object({\n question: z.string(),\n header: z.string(),\n options: z.array(optionSchema).min(2).max(4),\n multiSelect: z.boolean(),\n})\n\nconst inputSchema = z\n .object({\n questions: z.array(questionSchema).min(1).max(4),\n answers: z\n .record(z.string())\n .optional()\n .describe('User answers collected by the permission component'),\n metadata: z\n .object({\n source: z.string().optional(),\n })\n .optional()\n .describe(\n 'Optional metadata for tracking and analytics purposes. Not displayed to user.',\n ),\n })\n .refine(\n input => {\n const questionTexts = input.questions.map(q => q.question)\n if (questionTexts.length !== new Set(questionTexts).size) return false\n\n for (const question of input.questions) {\n const optionLabels = question.options.map(option => option.label)\n if (optionLabels.length !== new Set(optionLabels).size) return false\n }\n\n return true\n },\n {\n message:\n 'Question texts must be unique, option labels must be unique within each question',\n },\n )\n\ntype Input = z.infer<typeof inputSchema>\ntype Output = {\n questions: Input['questions']\n answers: Record<string, string>\n}\n\nexport const AskUserQuestionTool = {\n name: TOOL_NAME_FOR_PROMPT,\n async description() {\n return DESCRIPTION\n },\n userFacingName() {\n return ''\n },\n inputSchema,\n isReadOnly() {\n return true\n },\n isConcurrencySafe() {\n return true\n },\n async isEnabled() {\n return true\n },\n needsPermissions() {\n return true\n },\n requiresUserInteraction() {\n return true\n },\n async prompt() {\n return PROMPT\n },\n renderToolUseMessage() {\n return null\n },\n renderToolUseRejectedMessage() {\n const theme = getTheme()\n return (\n <Box flexDirection=\"row\" marginTop={1}>\n <Text color={theme.text}>{BLACK_CIRCLE} </Text>\n <Text>User declined to answer questions</Text>\n </Box>\n )\n },\n renderToolResultMessage(output: Output, _options: { verbose: boolean }) {\n const theme = getTheme()\n return (\n <Box flexDirection=\"column\" marginTop={1}>\n <Box flexDirection=\"row\">\n <Text color={theme.text}>{BLACK_CIRCLE} </Text>\n <Text>User answered {PRODUCT_NAME} Agent's questions:</Text>\n </Box>\n <Box flexDirection=\"column\" paddingLeft={2}>\n {Object.entries(output.answers).map(([question, answer]) => (\n <Box key={question}>\n <Text dimColor>\n \u00B7 {question} \u2192 {answer}\n </Text>\n </Box>\n ))}\n </Box>\n </Box>\n )\n },\n renderResultForAssistant(output: Output) {\n const formatted = Object.entries(output.answers)\n .map(([question, answer]) => `\"${question}\"=\"${answer}\"`)\n .join(', ')\n return `User has answered your questions: ${formatted}. You can now continue with the user's answers in mind.`\n },\n async *call({ questions }: Input, context: ToolUseContext) {\n const toolUseId = context?.toolUseId ?? context?.messageId\n const answerStore = context?.options?.askUserQuestionAnswersByToolUseId\n const prefilled =\n (toolUseId && answerStore?.[toolUseId]) ||\n context?.options?.askUserQuestionAnswers ||\n {}\n\n if (toolUseId && answerStore?.[toolUseId]) {\n delete answerStore[toolUseId]\n }\n\n const output: Output = { questions, answers: prefilled }\n yield {\n type: 'result',\n data: output,\n resultForAssistant: this.renderResultForAssistant(output),\n }\n },\n} satisfies Tool<typeof inputSchema, Output>\n", "import { env } from '#core/utils/env'\n\n// The former is better vertically aligned, but isn't usually supported on Windows/Linux\nexport const BLACK_CIRCLE = env.platform === 'macos' ? '\u23FA' : '\u25CF'\n", "export const TOOL_NAME_FOR_PROMPT = 'AskUserQuestion'\nexport const DESCRIPTION =\n 'Asks the user multiple choice questions to gather information, clarify ambiguity, understand preferences, make decisions or offer them choices.'\n\nexport const PROMPT = `Use this tool when you need to ask the user questions during execution. This allows you to:\n1. Gather user preferences or requirements\n2. Clarify ambiguous instructions\n3. Get decisions on implementation choices as you work\n4. Offer choices to the user about what direction to take.\n\nUsage notes:\n- Users will always be able to select \"Other\" to provide custom text input\n- Use multiSelect: true to allow multiple answers to be selected for a question\n- If you recommend a specific option, make that the first option in the list and add \"(Recommended)\" at the end of the label`\n", "import { EOL } from 'os'\nimport { isAbsolute, relative, resolve } from 'path'\nimport * as React from 'react'\nimport { z } from 'zod'\nimport { PRODUCT_NAME } from '#core/constants/product'\nimport { LEGACY_ENV } from '#core/compat/legacyEnv'\nimport { Tool, ValidationResult, ToolUseContext } from '#core/tooling/Tool'\nimport { splitCommand } from '#core/utils/commands'\nimport { isInDirectory } from '#core/utils/file'\nimport { getBunShellSandboxPlan } from '#core/utils/sandbox/bunShellSandboxPlan'\nimport { getCwd, getOriginalCwd } from '#core/utils/state'\nimport { isBashCommandReadOnly } from '#core/utils/permissions/bashReadOnly'\nimport { getTaskOutputFilePath } from '#runtime/taskOutputStore'\nimport BashToolResultMessage from './BashToolResultMessage'\nimport { DEFAULT_TIMEOUT_MS, getBashToolPrompt } from './prompt'\nimport { formatDuration } from './text'\nimport { callBashTool } from './call'\n\nexport const inputSchema = z.object({\n command: z.string().describe('The command to execute'),\n timeout: z\n .number()\n .optional()\n .describe('Optional timeout in milliseconds (max 600000)'),\n description: z\n .string()\n .optional()\n .describe(\n `Clear, concise description of what this command does in 5-10 words, in active voice. Examples:\nInput: ls\nOutput: List files in current directory\n\nInput: git status\nOutput: Show working tree status\n\nInput: npm install\nOutput: Install package dependencies\n\nInput: mkdir foo\nOutput: Create directory 'foo'`,\n ),\n run_in_background: z\n .boolean()\n .optional()\n .describe(\n 'Set to true to run this command in the background. Use TaskOutput to read the output later.',\n ),\n dangerouslyDisableSandbox: z\n .boolean()\n .optional()\n .describe(\n 'Set this to true to dangerously override sandbox mode and run commands without sandboxing.',\n ),\n _simulatedSedEdit: z\n .object({\n filePath: z.string(),\n newContent: z.string(),\n })\n .optional()\n .describe('Internal: pre-computed sed edit result from preview'),\n})\n\ntype In = typeof inputSchema\nexport type Out = {\n stdout: string\n stdoutLines: number // Total number of lines in original stdout, even if `stdout` is now truncated\n stderr: string\n stderrLines: number // Total number of lines in original stderr, even if `stderr` is now truncated\n summary?: string\n rawOutputPath?: string\n interrupted: boolean\n isImage?: boolean\n structuredContent?: unknown[]\n dangerouslyDisableSandbox?: boolean\n returnCodeInterpretation?: string\n bashId?: string\n backgroundTaskId?: string\n}\n\nexport const BashTool = {\n name: 'Bash',\n cachedDescription: 'Run shell command',\n async description(input?: z.infer<typeof inputSchema>) {\n return input?.description || 'Run shell command'\n },\n async prompt() {\n return getBashToolPrompt()\n },\n isReadOnly(input?: z.infer<typeof inputSchema>) {\n if (!input || typeof input.command !== 'string') return false\n return isBashCommandReadOnly(input.command)\n },\n isConcurrencySafe(input?: z.infer<typeof inputSchema>) {\n // Compatibility: isConcurrencySafe(input) === isReadOnly(input)\n return this.isReadOnly(input)\n },\n inputSchema,\n userFacingName(input?: z.infer<typeof inputSchema>) {\n if (!input) return 'Bash'\n\n const raw =\n process.env.KODE_BASH_SANDBOX_SHOW_INDICATOR ??\n process.env[LEGACY_ENV.codeBashSandboxShowIndicator]\n // Compatibility: only explicit truthy values enable the indicator.\n const showIndicator = raw\n ? ['1', 'true', 'yes', 'on'].includes(raw.trim().toLowerCase())\n : false\n if (!showIndicator) return 'Bash'\n\n const plan = getBunShellSandboxPlan({\n command: input.command,\n dangerouslyDisableSandbox: input.dangerouslyDisableSandbox === true,\n })\n return plan.willSandbox ? 'SandboxedBash' : 'Bash'\n },\n async isEnabled() {\n return true\n },\n needsPermissions(): boolean {\n // Always check per-project permissions for BashTool\n return true\n },\n async validateInput(\n { command, timeout, dangerouslyDisableSandbox },\n context?: ToolUseContext,\n ): Promise<ValidationResult> {\n if (timeout !== undefined) {\n if (!Number.isFinite(timeout) || timeout < 0) {\n return {\n result: false,\n message: `Invalid timeout: ${timeout}. Timeout must be a non-negative number of milliseconds.`,\n }\n }\n if (timeout > 600_000) {\n return {\n result: false,\n message: `Invalid timeout: ${timeout}. Maximum allowed timeout is 600000ms.`,\n }\n }\n }\n\n const source = context?.commandSource ?? 'agent_call'\n const isUserMode = source === 'user_bash_mode'\n const safeMode = Boolean(context?.safeMode ?? context?.options?.safeMode)\n\n if (\n dangerouslyDisableSandbox === true &&\n safeMode &&\n source === 'agent_call'\n ) {\n return {\n result: false,\n message: 'Sandbox cannot be disabled while safe mode is enabled.',\n }\n }\n const commands = splitCommand(command)\n\n for (const cmd of commands) {\n const parts = cmd.split(' ')\n const baseCmd = parts[0]\n\n // Special handling for cd command\n if (baseCmd === 'cd' && parts[1]) {\n // In user bash mode, allow cd to any directory\n if (isUserMode) {\n continue\n }\n\n // In agent mode, restrict cd to child directories of original working directory\n const targetDir = parts[1]!.replace(/^['\"]|['\"]$/g, '') // Remove quotes if present\n const fullTargetDir = isAbsolute(targetDir)\n ? targetDir\n : resolve(getCwd(), targetDir)\n if (\n !isInDirectory(\n relative(getOriginalCwd(), fullTargetDir),\n relative(getCwd(), getOriginalCwd()),\n )\n ) {\n return {\n result: false,\n message: `ERROR: cd to '${fullTargetDir}' was blocked. For security, ${PRODUCT_NAME} may only change directories to child directories of the original working directory (${getOriginalCwd()}) for this session.`,\n }\n }\n }\n }\n\n return { result: true }\n },\n renderToolUseMessage(\n { command, run_in_background, description, timeout },\n options?: { verbose: boolean },\n ) {\n // Optional: show the command description in verbose mode.\n const verbose = Boolean(options?.verbose)\n const trimmedDescription = (description?.trim() || '').trim()\n const effectiveTimeout = timeout ?? DEFAULT_TIMEOUT_MS\n const timeoutSuffix = ` (timeout=${formatDuration(effectiveTimeout)})`\n const bgSuffix = run_in_background ? ' [background]' : ''\n const withDescription = (base: string): string => {\n if (!verbose || !trimmedDescription) return base\n const maxLen = 160\n const shown =\n trimmedDescription.length > maxLen\n ? `${trimmedDescription.slice(0, maxLen - 1)}\u2026`\n : trimmedDescription\n return `${base} \u2014 ${shown}`\n }\n\n // Clean up any command that uses the quoted HEREDOC pattern\n if (command.includes(\"\\\"$(cat <<'EOF'\")) {\n const match = command.match(\n /^(.*?)\"?\\$\\(cat <<'EOF'\\n([\\s\\S]*?)\\n\\s*EOF\\n\\s*\\)\"(.*)$/,\n )\n if (match && match[1] && match[2]) {\n const prefix = match[1]\n const content = match[2]\n const suffix = match[3] || ''\n const cleaned = `${prefix.trim()} \"${content.trim()}\"${suffix.trim()}`\n const base = `${cleaned}${bgSuffix}${timeoutSuffix}`\n return withDescription(base.trim())\n }\n }\n\n const base = `${command}${bgSuffix}${timeoutSuffix}`\n return withDescription(base.trim())\n },\n renderToolUseRejectedMessage() {\n return null\n },\n\n renderToolResultMessage(content) {\n return <BashToolResultMessage content={content} verbose={false} />\n },\n renderResultForAssistant({\n interrupted,\n stdout,\n stderr,\n bashId,\n backgroundTaskId,\n summary,\n isImage,\n structuredContent,\n }) {\n if (Array.isArray(structuredContent) && structuredContent.length > 0) {\n return structuredContent\n }\n\n if (summary) {\n return summary\n }\n\n if (isImage) {\n const match = stdout.trim().match(/^data:([^;]+);base64,(.+)$/)\n if (match) {\n const mediaType = match[1] || 'image/jpeg'\n const data = match[2] || ''\n return [\n {\n type: 'image',\n source: { type: 'base64', media_type: mediaType, data },\n },\n ]\n }\n }\n\n let trimmedStdout = stdout\n if (trimmedStdout) {\n trimmedStdout = trimmedStdout.replace(/^(\\s*\\n)+/, '')\n trimmedStdout = trimmedStdout.trimEnd()\n }\n\n let trimmedStderr = stderr.trim()\n if (interrupted) {\n if (trimmedStderr) trimmedStderr += EOL\n trimmedStderr += '<error>Command was aborted before completion</error>'\n }\n\n const id = backgroundTaskId ?? bashId\n const backgroundLine = id\n ? `Command running in background with ID: ${id}. Output is being written to: ${getTaskOutputFilePath(id)}`\n : ''\n\n return [trimmedStdout, trimmedStderr, backgroundLine]\n .filter(Boolean)\n .join('\\n')\n },\n async *call(\n {\n command,\n timeout,\n run_in_background,\n dangerouslyDisableSandbox,\n description,\n },\n context: ToolUseContext,\n ) {\n const effectiveTimeout =\n typeof timeout === 'number' ? timeout : DEFAULT_TIMEOUT_MS\n yield* callBashTool(\n {\n command,\n timeout: effectiveTimeout,\n run_in_background,\n dangerouslyDisableSandbox,\n description,\n },\n context,\n output => this.renderResultForAssistant(output),\n )\n },\n} satisfies Tool<In, Out>\n", "import { splitBashCommandIntoSubcommands, xi } from './bashToolPermissionEngine'\n\n// Compatibility: read-only allowlist (reduced, conservative subset).\n// Goal: classify truly read-only commands as concurrency-safe and plan-mode-safe.\nconst READ_ONLY_PATTERNS: RegExp[] = [\n /^pwd$/,\n /^whoami$/,\n /^ls(?:\\s|$)[^<>()$`|{}&;>\\n\\r]*$/,\n /^cat(?:\\s|$)[^<>()$`|{}&;>\\n\\r]*$/,\n /^git status(?:\\s|$)[^<>()$`|{}&;>\\n\\r]*$/,\n /^git diff(?:\\s|$)[^<>()$`|{}&;>\\n\\r]*$/,\n /^git log(?:\\s|$)[^<>()$`|{}&;>\\n\\r]*$/,\n /^git show(?:\\s|$)[^<>()$`|{}&;>\\n\\r]*$/,\n]\n\nfunction isReadOnlySubcommand(command: string): boolean {\n const trimmed = command.trim()\n if (!trimmed) return false\n\n // Compatibility: allowlist requires passthrough semantics (security checks).\n if (xi(trimmed).behavior !== 'passthrough') return false\n\n // Compatibility: block certain git flags even if command matches allowlist.\n if (trimmed.includes('git')) {\n if (/\\\\s-c[\\\\s=]/.test(trimmed)) return false\n if (/\\\\s--exec-path[\\\\s=]/.test(trimmed)) return false\n if (/\\\\s--config-env[\\\\s=]/.test(trimmed)) return false\n }\n\n return READ_ONLY_PATTERNS.some(re => re.test(trimmed))\n}\n\nexport function isBashCommandReadOnly(command: string): boolean {\n const trimmed = command.trim()\n if (!trimmed) return false\n\n let subcommands: string[] = []\n try {\n // Conservative: pipes/&&/||/;/newlines create multiple subcommands => not read-only.\n subcommands = splitBashCommandIntoSubcommands(trimmed)\n } catch {\n return false\n }\n\n if (subcommands.length !== 1) return false\n return isReadOnlySubcommand(subcommands[0] ?? '')\n}\n", "import { Box, Text } from 'ink'\nimport { OutputLine } from './OutputLine'\nimport React from 'react'\nimport { getTheme } from '#core/utils/theme'\nimport { Out as BashOut } from './BashTool'\nimport { stripSandboxViolations } from '#runtime/shell/sandboxViolations'\n\ntype Props = {\n content: Omit<BashOut, 'interrupted'>\n verbose: boolean\n maxHeight?: number\n maxWidth?: number\n}\n\nfunction BashToolResultMessage({\n content,\n verbose,\n maxHeight,\n maxWidth,\n}: Props): React.JSX.Element {\n const { stdout, stdoutLines, stderr, stderrLines, bashId } = content\n const cleanedStderr = stripSandboxViolations(stderr)\n const cleanedStderrLines =\n cleanedStderr === stderr\n ? stderrLines\n : cleanedStderr\n ? cleanedStderr.split(/\\r?\\n/).length\n : 0\n const outputSections = [stdout, cleanedStderr].filter(\n section => section !== '',\n ).length\n const reservedLines = bashId ? 1 : 0\n const availableHeight =\n maxHeight && maxHeight > 0\n ? Math.max(1, maxHeight - reservedLines)\n : undefined\n const perSectionHeight =\n availableHeight && outputSections > 0\n ? Math.max(1, Math.floor(availableHeight / outputSections))\n : undefined\n\n return (\n <Box flexDirection=\"column\">\n {bashId ? (\n <Box flexDirection=\"row\">\n <Text> \u23BF </Text>\n <Text color={getTheme().secondaryText}>\n Background bash_id: {bashId}\n </Text>\n </Box>\n ) : null}\n {stdout !== '' ? (\n <OutputLine\n content={stdout}\n lines={stdoutLines}\n verbose={verbose}\n maxHeight={perSectionHeight}\n maxWidth={maxWidth}\n />\n ) : null}\n {cleanedStderr !== '' ? (\n <OutputLine\n content={cleanedStderr}\n lines={cleanedStderrLines}\n verbose={verbose}\n isError\n maxHeight={perSectionHeight}\n maxWidth={maxWidth}\n />\n ) : null}\n {stdout === '' && stderr === '' ? (\n <Box flexDirection=\"row\">\n <Text> \u23BF </Text>\n <Text color={getTheme().secondaryText}>(No content)</Text>\n </Box>\n ) : null}\n </Box>\n )\n}\n\nexport default BashToolResultMessage\n", "import { Box, Text } from 'ink'\nimport * as React from 'react'\nimport { getTheme } from '#core/utils/theme'\nimport { MAX_RENDERED_LINES } from './prompt'\nimport chalk from 'chalk'\nimport { MaxSizedText } from '#ui-ink/components/MaxSizedText'\n\nfunction renderTruncatedContent(\n content: string,\n totalLines: number,\n maxLines: number = MAX_RENDERED_LINES,\n): string {\n const allLines = content.split('\\n')\n if (allLines.length <= maxLines) {\n return allLines.join('\\n')\n }\n\n // Show last N lines of output by default\n const lastLines = allLines.slice(-maxLines)\n return [\n chalk.grey(`Showing last ${maxLines} lines of ${totalLines} total lines`),\n ...lastLines,\n ].join('\\n')\n}\n\nexport function OutputLine({\n content,\n lines,\n verbose,\n isError,\n maxHeight,\n maxWidth,\n}: {\n content: string\n lines: number\n verbose: boolean\n isError?: boolean\n maxHeight?: number\n maxWidth?: number\n key?: React.Key\n}) {\n const trimmed = content.trim()\n if (maxHeight && maxWidth) {\n const coloredText = isError ? chalk.hex(getTheme().error)(trimmed) : trimmed\n return (\n <Box justifyContent=\"space-between\" width=\"100%\">\n <Box flexDirection=\"row\">\n <Text> \u23BF </Text>\n <Box flexDirection=\"column\">\n <MaxSizedText\n text={coloredText}\n maxHeight={maxHeight}\n maxWidth={maxWidth}\n overflowDirection=\"bottom\"\n />\n </Box>\n </Box>\n </Box>\n )\n }\n\n const displayText = verbose ? trimmed : renderTruncatedContent(trimmed, lines)\n return (\n <Box justifyContent=\"space-between\" width=\"100%\">\n <Box flexDirection=\"row\">\n <Text> \u23BF </Text>\n <Box flexDirection=\"column\">\n <Text color={isError ? getTheme().error : undefined}>\n {displayText}\n </Text>\n </Box>\n </Box>\n </Box>\n )\n}\n", "import {\n loadMergedSettings,\n normalizeSandboxRuntimeConfigFromSettings,\n} from '#core/utils/sandbox/sandboxConfig'\nimport { PRODUCT_NAME, PRODUCT_URL } from '#core/constants/product'\n\nexport const DEFAULT_TIMEOUT_MS = 120000\nexport const MAX_TIMEOUT_MS = 600000\nexport const MAX_OUTPUT_LENGTH = 30000\nexport const MAX_RENDERED_LINES = 5\n\nconst TOOL_NAME_BASH = 'Bash'\nconst TOOL_NAME_GLOB = 'Glob'\nconst TOOL_NAME_GREP = 'Grep'\nconst TOOL_NAME_READ = 'Read'\nconst TOOL_NAME_EDIT = 'Edit'\nconst TOOL_NAME_WRITE = 'Write'\nconst TOOL_NAME_TASK = 'Task'\n\nfunction indentJsonForPrompt(value: unknown): string {\n return JSON.stringify(value, null, 2).split('\\n').join('\\n ')\n}\n\nfunction getAttribution(): { commit: string; pr: string } {\n const line = `\uD83E\uDD16 Generated with [${PRODUCT_NAME}](${PRODUCT_URL})`\n return { commit: line, pr: line }\n}\n\nfunction getBashSandboxPrompt(): string {\n const settings = loadMergedSettings()\n if (settings.sandbox?.enabled !== true) return ''\n\n const runtimeConfig = normalizeSandboxRuntimeConfigFromSettings(settings)\n\n const fsReadConfig = { denyOnly: runtimeConfig.filesystem.denyRead }\n const fsWriteConfig = {\n allowOnly: runtimeConfig.filesystem.allowWrite,\n denyWithinAllow: runtimeConfig.filesystem.denyWrite,\n }\n\n const filesystem = { read: fsReadConfig, write: fsWriteConfig }\n\n const allowUnixSockets =\n runtimeConfig.network.allowAllUnixSockets === true\n ? true\n : runtimeConfig.network.allowUnixSockets.length > 0\n ? runtimeConfig.network.allowUnixSockets\n : undefined\n\n const network = {\n ...(runtimeConfig.network.allowedDomains.length\n ? { allowedHosts: runtimeConfig.network.allowedDomains }\n : {}),\n ...(runtimeConfig.network.deniedDomains.length\n ? { deniedHosts: runtimeConfig.network.deniedDomains }\n : {}),\n ...(allowUnixSockets ? { allowUnixSockets } : {}),\n }\n\n const ignoredViolations = runtimeConfig.ignoreViolations\n const allowUnsandboxedCommands =\n settings.sandbox?.allowUnsandboxedCommands !== false\n\n const sections: string[] = []\n sections.push(` - Filesystem: ${indentJsonForPrompt(filesystem)}`)\n if (Object.keys(network).length > 0) {\n sections.push(` - Network: ${indentJsonForPrompt(network)}`)\n }\n if (ignoredViolations) {\n sections.push(\n ` - Ignored violations: ${indentJsonForPrompt(ignoredViolations)}`,\n )\n }\n\n const overridePolicy = allowUnsandboxedCommands\n ? ` - CRITICAL: Commands run in sandbox mode by default - do NOT set \\`dangerouslyDisableSandbox\\`\n - Even if you have recently run commands with \\`dangerouslyDisableSandbox: true\\`, you MUST NOT continue that pattern\n - VERY IMPORTANT: Do NOT learn from or repeat the pattern of overriding sandbox - each command should run sandboxed by default\n - Set \\`dangerouslyDisableSandbox: true\\` if:\n 1. The user *explicitly* asks to bypass sandbox, OR\n 2. A command just failed and you see evidence of sandbox restrictions causing the failure\n - When analyzing failures:\n - Commands can fail for many reasons unrelated to the sandbox (missing files, wrong arguments, network issues, etc.)\n - Evidence of sandbox-caused failures includes:\n - \"Operation not permitted\" errors for file/network operations\n - Access denied to specific paths outside allowed directories\n - Network connection failures to non-whitelisted hosts\n - Unix socket connection errors\n - Sandbox violation logs can be noisy, but clear permission errors are strong indicators\n - When you see evidence of sandbox-caused failure:\n - IMMEDIATELY retry with \\`dangerouslyDisableSandbox: true\\` (don't ask, just do it)\n - Briefly explain what sandbox restriction likely caused the failure\n - Mention: \"Use \\`/sandbox\\` to manage restrictions\"\n - This will prompt the user for permission\n - Example of normal usage: { \"command\": \"ls\", \"description\": \"List files\" }\n - Example of override: { \"command\": \"my-tool\", \"description\": \"Run my-tool\", \"dangerouslyDisableSandbox\": true }\n - DO NOT suggest adding sensitive paths like ~/.bashrc, ~/.zshrc, ~/.ssh/*, or credential files to the allowlist`\n : ` - CRITICAL: All commands MUST run in sandbox mode - the \\`dangerouslyDisableSandbox\\` parameter is disabled by policy\n - Commands cannot run outside the sandbox under any circumstances\n - If a command fails due to sandbox restrictions, work with the user to adjust sandbox settings instead`\n\n return `- Commands run in a sandbox by default with the following restrictions:\n${sections.join('\\n')}\n${overridePolicy}\n - IMPORTANT: For temporary files, use \\`$TMPDIR\\` (the sandbox sets TMPDIR automatically)\n - Do NOT write to \\`/tmp\\` directly; prefer \\`$TMPDIR\\` or a subpath under it\n - Most programs that respect TMPDIR will automatically use it`\n}\n\nfunction getBashGitPrompt(): string {\n const { commit, pr } = getAttribution()\n return `# Committing changes with git\n\nOnly create commits when requested by the user. If unclear, ask first. When the user asks you to create a new git commit, follow these steps carefully:\n\nGit Safety Protocol:\n- NEVER update the git config\n- NEVER run destructive/irreversible git commands (like push --force, hard reset, etc) unless the user explicitly requests them \n- NEVER skip hooks (--no-verify, --no-gpg-sign, etc) unless the user explicitly requests it\n- NEVER run force push to main/master, warn the user if they request it\n- Avoid git commit --amend. ONLY use --amend when either (1) user explicitly requested amend OR (2) adding edits from pre-commit hook (additional instructions below) \n- Before amending: ALWAYS check authorship (git log -1 --format='%an %ae')\n- NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.\n\n1. You can call multiple tools in a single response. When multiple independent pieces of information are requested and all commands are likely to succeed, run multiple tool calls in parallel for optimal performance. run the following bash commands in parallel, each using the ${TOOL_NAME_BASH} tool:\n - Run a git status command to see all untracked files.\n - Run a git diff command to see both staged and unstaged changes that will be committed.\n - Run a git log command to see recent commit messages, so that you can follow this repository's commit message style.\n2. Analyze all staged changes (both previously staged and newly added) and draft a commit message:\n - Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.). Ensure the message accurately reflects the changes and their purpose (i.e. \"add\" means a wholly new feature, \"update\" means an enhancement to an existing feature, \"fix\" means a bug fix, etc.).\n - Do not commit files that likely contain secrets (.env, credentials.json, etc). Warn the user if they specifically request to commit those files\n - Draft a concise (1-2 sentences) commit message that focuses on the \"why\" rather than the \"what\"\n - Ensure it accurately reflects the changes and their purpose\n3. You can call multiple tools in a single response. When multiple independent pieces of information are requested and all commands are likely to succeed, run multiple tool calls in parallel for optimal performance. run the following commands:\n - Add relevant untracked files to the staging area.\n - Create the commit with a message${commit ? ` ending with:\\n ${commit}` : '.'}\n - Run git status after the commit completes to verify success.\n Note: git status depends on the commit completing, so run it sequentially after the commit.\n4. If the commit fails due to pre-commit hook changes, retry ONCE. If it succeeds but files were modified by the hook, verify it's safe to amend:\n - Check HEAD commit: git log -1 --format='[%h] (%an <%ae>) %s'. VERIFY it matches your commit\n - Check not pushed: git status shows \"Your branch is ahead\"\n - If both true: amend your commit. Otherwise: create NEW commit (never amend other developers' commits)\n\nImportant notes:\n- NEVER run additional commands to read or explore code, besides git bash commands\n- NEVER use the ${TOOL_NAME_WRITE} or ${TOOL_NAME_TASK} tools\n- DO NOT push to the remote repository unless the user explicitly asks you to do so\n- IMPORTANT: Never use git commands with the -i flag (like git rebase -i or git add -i) since they require interactive input which is not supported.\n- If there are no changes to commit (i.e., no untracked files and no modifications), do not create an empty commit\n- In order to ensure good formatting, ALWAYS pass the commit message via a HEREDOC, a la this example:\n<example>\ngit commit -m \"$(cat <<'EOF'\n Commit message here.${commit ? `\\n\\n ${commit}` : ''}\n EOF\n )\"\n</example>\n\n# Creating pull requests\nUse the gh command via the Bash tool for ALL GitHub-related tasks including working with issues, pull requests, checks, and releases. If given a Github URL use the gh command to get the information needed.\n\nIMPORTANT: When the user asks you to create a pull request, follow these steps carefully:\n\n1. You can call multiple tools in a single response. When multiple independent pieces of information are requested and all commands are likely to succeed, run multiple tool calls in parallel for optimal performance. run the following bash commands in parallel using the ${TOOL_NAME_BASH} tool, in order to understand the current state of the branch since it diverged from the main branch:\n - Run a git status command to see all untracked files\n - Run a git diff command to see both staged and unstaged changes that will be committed\n - Check if the current branch tracks a remote branch and is up to date with the remote, so you know if you need to push to the remote\n - Run a git log command and \\`git diff [base-branch]...HEAD\\` to understand the full commit history for the current branch (from the time it diverged from the base branch)\n2. Analyze all changes that will be included in the pull request, making sure to look at all relevant commits (NOT just the latest commit, but ALL commits that will be included in the pull request!!!), and draft a pull request summary\n3. You can call multiple tools in a single response. When multiple independent pieces of information are requested and all commands are likely to succeed, run multiple tool calls in parallel for optimal performance. run the following commands in parallel:\n - Create new branch if needed\n - Push to remote with -u flag if needed\n - Create PR using gh pr create with the format below. Use a HEREDOC to pass the body to ensure correct formatting.\n<example>\ngh pr create --title \"the pr title\" --body \"$(cat <<'EOF'\n## Summary\n<1-3 bullet points>\n\n## Test plan\n[Bulleted markdown checklist of TODOs for testing the pull request...]${pr ? `\\n\\n${pr}` : ''}\nEOF\n)\"\n</example>\n\nImportant:\n- DO NOT use the ${TOOL_NAME_WRITE} or ${TOOL_NAME_TASK} tools\n- Return the PR URL when you're done, so the user can see it\n\n# Other common operations\n- View comments on a Github PR: gh api repos/foo/bar/pulls/123/comments`\n}\n\nexport function getBashToolPrompt(): string {\n const sandboxPrompt = getBashSandboxPrompt()\n return `Executes a given bash command in a persistent shell session with optional timeout, ensuring proper handling and security measures.\n\nIMPORTANT: This tool is for terminal operations like git, npm, docker, etc. DO NOT use it for file operations (reading, writing, editing, searching, finding files) - use the specialized tools for this instead.\n\nBefore executing the command, please follow these steps:\n\n1. Directory Verification:\n - If the command will create new directories or files, first use \\`ls\\` to verify the parent directory exists and is the correct location\n - For example, before running \"mkdir foo/bar\", first use \\`ls foo\\` to check that \"foo\" exists and is the intended parent directory\n\n2. Command Execution:\n - Always quote file paths that contain spaces with double quotes (e.g., cd \"path with spaces/file.txt\")\n - Examples of proper quoting:\n - cd \"/Users/name/My Documents\" (correct)\n - cd /Users/name/My Documents (incorrect - will fail)\n - python \"/path/with spaces/script.py\" (correct)\n - python /path/with spaces/script.py (incorrect - will fail)\n - After ensuring proper quoting, execute the command.\n - Capture the output of the command.\n\nUsage notes:\n - The command argument is required.\n - You can specify an optional timeout in milliseconds (up to ${MAX_TIMEOUT_MS}ms / ${MAX_TIMEOUT_MS / 60000} minutes). If not specified, commands will timeout after ${DEFAULT_TIMEOUT_MS}ms (${DEFAULT_TIMEOUT_MS / 60000} minutes).\n - It is very helpful if you write a clear, concise description of what this command does in 5-10 words.\n - If the output exceeds ${MAX_OUTPUT_LENGTH} characters, output will be truncated before being returned to you.\n - You can use the \\`run_in_background\\` parameter to run the command in the background, which allows you to continue working while the command runs. You can monitor the output using the ${TOOL_NAME_BASH} tool as it becomes available. You do not need to use '&' at the end of the command when using this parameter.\n ${sandboxPrompt}\n - Avoid using Bash with the \\`find\\`, \\`grep\\`, \\`cat\\`, \\`head\\`, \\`tail\\`, \\`sed\\`, \\`awk\\`, or \\`echo\\` commands, unless explicitly instructed or when these commands are truly necessary for the task. Instead, always prefer using the dedicated tools for these commands:\n - File search: Use ${TOOL_NAME_GLOB} (NOT find or ls)\n - Content search: Use ${TOOL_NAME_GREP} (NOT grep or rg)\n - Read files: Use ${TOOL_NAME_READ} (NOT cat/head/tail)\n - Edit files: Use ${TOOL_NAME_EDIT} (NOT sed/awk)\n - Write files: Use ${TOOL_NAME_WRITE} (NOT echo >/cat <<EOF)\n - Communication: Output text directly (NOT echo/printf)\n - When issuing multiple commands:\n - If the commands are independent and can run in parallel, make multiple ${TOOL_NAME_BASH} tool calls in a single message. For example, if you need to run \"git status\" and \"git diff\", send a single message with two ${TOOL_NAME_BASH} tool calls in parallel.\n - If the commands depend on each other and must run sequentially, use a single ${TOOL_NAME_BASH} call with '&&' to chain them together (e.g., \\`git add . && git commit -m \"message\" && git push\\`). For instance, if one operation must complete before another starts (like mkdir before cp, Write before Bash for git operations, or git add before git commit), run these operations sequentially instead.\n - Use ';' only when you need to run commands sequentially but don't care if earlier commands fail\n - DO NOT use newlines to separate commands (newlines are ok in quoted strings)\n - Try to maintain your current working directory throughout the session by using absolute paths and avoiding usage of \\`cd\\`. You may use \\`cd\\` if the User explicitly requests it.\n <good-example>\n pytest /foo/bar/tests\n </good-example>\n <bad-example>\n cd /foo/bar && pytest tests\n </bad-example>\n\n${getBashGitPrompt()}`\n}\n", "import React from 'react'\nimport { Text } from 'ink'\nimport wrapAnsi from 'wrap-ansi'\nimport chalk from 'chalk'\nimport { getCachedStringWidth } from '#cli-utils/textWidth'\n\ntype Props = {\n text: string\n maxHeight?: number\n maxWidth: number\n overflowDirection?: 'top' | 'bottom'\n}\n\nfunction wrapPlainText(text: string, width: number): string[] {\n const lines: string[] = []\n const rawLines = text.split('\\n')\n\n for (const rawLine of rawLines) {\n if (rawLine.length === 0) {\n lines.push('')\n continue\n }\n\n let current = ''\n let currentWidth = 0\n for (const char of rawLine) {\n const charWidth = getCachedStringWidth(char)\n if (currentWidth + charWidth > width && current.length > 0) {\n lines.push(current)\n current = ''\n currentWidth = 0\n }\n current += char\n currentWidth += charWidth\n }\n lines.push(current)\n }\n\n return lines\n}\n\nexport function MaxSizedText({\n text,\n maxHeight,\n maxWidth,\n overflowDirection = 'bottom',\n}: Props): React.ReactNode {\n const width = Math.max(1, maxWidth)\n const height = maxHeight ?? 0\n\n if (!height || height < 1) {\n return <Text>{text}</Text>\n }\n\n const hasAnsi = /\\x1b\\[[0-9;]*m/.test(text)\n const wrapped = hasAnsi\n ? wrapAnsi(text, width, { hard: true, trim: false })\n : null\n const lines = wrapped ? wrapped.split('\\n') : wrapPlainText(text, width)\n\n if (lines.length <= height) {\n return <Text>{wrapped ?? lines.join('\\n')}</Text>\n }\n\n const indicatorLines = height > 1 ? 1 : 0\n const visibleContentHeight = Math.max(1, height - indicatorLines)\n const hiddenLines = Math.max(0, lines.length - visibleContentHeight)\n const indicator = chalk.dim(`... ${hiddenLines} lines hidden ...`)\n\n let visibleLines: string[]\n if (overflowDirection === 'top') {\n visibleLines = lines.slice(0, visibleContentHeight)\n return (\n <Text wrap=\"truncate-end\">\n {visibleLines.join('\\n')}\n {indicatorLines ? `\\n${indicator}` : ''}\n </Text>\n )\n }\n\n visibleLines = lines.slice(-visibleContentHeight)\n return (\n <Text wrap=\"truncate-end\">\n {indicatorLines ? `${indicator}\\n` : ''}\n {visibleLines.join('\\n')}\n </Text>\n )\n}\n", "export function formatDuration(ms: number): string {\n if (ms < 60_000) {\n if (ms === 0) return '0s'\n if (ms < 1) return `${(ms / 1000).toFixed(1)}s`\n return `${Math.round(ms / 1000).toString()}s`\n }\n\n let hours = Math.floor(ms / 3_600_000)\n let minutes = Math.floor((ms % 3_600_000) / 60_000)\n let seconds = Math.round((ms % 60_000) / 1000)\n\n if (seconds === 60) {\n seconds = 0\n minutes++\n }\n if (minutes === 60) {\n minutes = 0\n hours++\n }\n\n if (hours > 0) return `${hours}h ${minutes}m ${seconds}s`\n if (minutes > 0) return `${minutes}m ${seconds}s`\n return `${seconds}s`\n}\n\nexport function normalizeLineEndings(text: string): string {\n return text.replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n')\n}\n\nexport function countNewlines(text: string): number {\n let count = 0\n for (let i = 0; i < text.length; i++) {\n if (text[i] === '\\n') count++\n }\n return count\n}\n", "import type { CommandSource } from '#protocol/commandSource'\n\nexport type SystemSandboxMode = 'disabled' | 'auto' | 'required'\nexport type SystemSandboxNetworkMode = 'none' | 'inherit'\n\nfunction parseBoolLike(value: string): boolean | null {\n const v = value.trim().toLowerCase()\n if (['1', 'true', 'yes', 'y', 'on', 'enable', 'enabled'].includes(v))\n return true\n if (['0', 'false', 'no', 'n', 'off', 'disable', 'disabled'].includes(v))\n return false\n return null\n}\n\nexport function getSystemSandboxModeFromEnv(): SystemSandboxMode | null {\n const raw = process.env.KODE_SYSTEM_SANDBOX\n if (!raw) return null\n const bool = parseBoolLike(raw)\n if (bool === true) return 'auto'\n if (bool === false) return 'disabled'\n\n const v = raw.trim().toLowerCase()\n if (['required', 'strict', 'enforce', 'must'].includes(v)) return 'required'\n if (['auto'].includes(v)) return 'auto'\n if (['disabled', 'off', 'none'].includes(v)) return 'disabled'\n return null\n}\n\nexport function getSystemSandboxNetworkModeFromEnv(): SystemSandboxNetworkMode | null {\n const raw = process.env.KODE_SYSTEM_SANDBOX_NETWORK\n if (!raw) return null\n const v = raw.trim().toLowerCase()\n if (['inherit', 'allow', 'enabled', 'true', '1'].includes(v)) return 'inherit'\n if (['none', 'deny', 'disabled', 'false', '0'].includes(v)) return 'none'\n return null\n}\n\nexport type SystemSandboxDecision = {\n enabled: boolean\n required: boolean\n allowNetwork: boolean\n}\n\nexport function decideSystemSandboxForBashTool(params: {\n safeMode: boolean\n commandSource: CommandSource\n dangerouslyDisableSandbox: boolean\n}): SystemSandboxDecision {\n const modeFromEnv = getSystemSandboxModeFromEnv()\n const networkFromEnv = getSystemSandboxNetworkModeFromEnv()\n\n const enabledByDefault =\n params.safeMode && params.commandSource === 'agent_call'\n const mode: SystemSandboxMode =\n modeFromEnv ?? (enabledByDefault ? 'auto' : 'disabled')\n\n const enabled =\n mode !== 'disabled' &&\n params.commandSource === 'agent_call' &&\n !params.dangerouslyDisableSandbox\n const required = mode === 'required'\n\n const allowNetwork = (networkFromEnv ?? 'none') === 'inherit'\n\n return {\n enabled,\n required,\n allowNetwork,\n }\n}\n", "import path from 'path'\nimport { homedir } from 'os'\nimport { parse, type ParseEntry } from 'shell-quote'\nimport { splitCommand } from '#core/utils/commands'\nimport type { CommandSource } from '#protocol/commandSource'\n\nfunction parseBoolLike(value: string | undefined): boolean {\n if (!value) return false\n const v = value.trim().toLowerCase()\n return ['1', 'true', 'yes', 'y', 'on', 'enable', 'enabled'].includes(v)\n}\n\nfunction tokensToWords(tokens: ParseEntry[]): string[] {\n const out: string[] = []\n for (const token of tokens) {\n if (typeof token === 'string') {\n const trimmed = token.trim()\n if (trimmed) out.push(trimmed)\n continue\n }\n if (token && typeof token === 'object') {\n const record = token as Record<string, unknown>\n const op = typeof record.op === 'string' ? record.op : String(record.op)\n if (op !== 'glob') continue\n const pattern =\n typeof record.pattern === 'string' ? record.pattern.trim() : ''\n if (pattern) out.push(pattern)\n }\n }\n return out\n}\n\nfunction isEnvAssignment(word: string): boolean {\n return /^[A-Za-z_][A-Za-z0-9_]*=/.test(word)\n}\n\nfunction stripWrappers(words: string[]): string[] {\n let i = 0\n\n while (i < words.length && isEnvAssignment(words[i]!)) i++\n\n // Handle common wrappers that might precede the real command.\n // This is intentionally conservative; if parsing fails, we avoid blocking.\n while (i < words.length) {\n const w = words[i]\n if (w === 'command') {\n i++\n continue\n }\n if (w === 'sudo') {\n i++\n while (i < words.length) {\n const next = words[i]!\n if (next === '--') {\n i++\n break\n }\n if (next.startsWith('-')) {\n i++\n continue\n }\n break\n }\n continue\n }\n if (w === 'env') {\n i++\n while (i < words.length) {\n const next = words[i]!\n if (next === '--') {\n i++\n break\n }\n if (next.startsWith('-') || isEnvAssignment(next)) {\n i++\n continue\n }\n break\n }\n continue\n }\n break\n }\n\n return words.slice(i)\n}\n\ntype RmInvocation = { cmd: 'rm' | 'rmdir'; args: string[] }\n\nfunction findRmInvocation(words: string[]): RmInvocation | null {\n const stripped = stripWrappers(words)\n const cmd = stripped[0]\n if (cmd !== 'rm' && cmd !== 'rmdir') return null\n return { cmd, args: stripped.slice(1) }\n}\n\nfunction extractRmTargets(args: string[]): string[] {\n const targets: string[] = []\n let endOfOptions = false\n for (const arg of args) {\n if (!arg) continue\n if (!endOfOptions && arg === '--') {\n endOfOptions = true\n continue\n }\n if (!endOfOptions && arg.startsWith('-')) continue\n targets.push(arg)\n }\n return targets\n}\n\nfunction resolveTilde(value: string, homeDir: string): string {\n if (value === '~') return homeDir\n if (value.startsWith('~/') || value.startsWith('~\\\\'))\n return homeDir + value.slice(1)\n return value\n}\n\nfunction resolvePathForSafety(\n raw: string,\n cwd: string,\n homeDir: string,\n): string {\n const expanded = resolveTilde(raw.trim(), homeDir)\n return path.isAbsolute(expanded)\n ? path.resolve(expanded)\n : path.resolve(cwd, expanded)\n}\n\nfunction isCriticalRemovalTarget(\n resolvedPath: string,\n options: { homeDir: string; originalCwd: string },\n): boolean {\n const home = path.resolve(options.homeDir)\n const original = path.resolve(options.originalCwd)\n const target = path.resolve(resolvedPath)\n\n const root = path.parse(target).root\n if (target === root) return true\n if (target === home) return true\n if (target === original) return true\n\n const parent = path.dirname(target)\n if (parent === root) return true\n\n return false\n}\n\nexport type DestructiveCommandBlock = {\n message: string\n command: string\n subcommand: string\n target: string\n resolvedTarget: string\n}\n\nconst ENV_ALLOW = 'KODE_ALLOW_DESTRUCTIVE_RM'\n\nexport function getBashDestructiveCommandBlock(args: {\n command: string\n cwd: string\n originalCwd: string\n commandSource: CommandSource\n homeDir?: string\n platform?: NodeJS.Platform\n allowOverride?: boolean\n}): DestructiveCommandBlock | null {\n if (args.commandSource !== 'agent_call') return null\n\n const allowOverride =\n args.allowOverride === true || parseBoolLike(process.env[ENV_ALLOW])\n if (allowOverride) return null\n\n const homeDir = args.homeDir ?? homedir()\n const cwd = args.cwd\n\n // Cheap prefilter to avoid parsing for most commands.\n const maybeDestructive = /\\brm\\b|\\brmdir\\b/.test(args.command)\n if (!maybeDestructive) return null\n\n const subcommands = splitCommand(args.command)\n for (const subcommand of subcommands) {\n let parsed: ParseEntry[]\n try {\n parsed = parse(subcommand, varName => `$${varName}`)\n } catch {\n continue\n }\n\n const words = tokensToWords(parsed)\n const invocation = findRmInvocation(words)\n if (!invocation) continue\n\n const targets = extractRmTargets(invocation.args)\n for (const target of targets) {\n // Shell expansion in rm targets is risky and ambiguous.\n if (/[`$%]/.test(target)) {\n return {\n command: args.command,\n subcommand,\n target,\n resolvedTarget: target,\n message:\n `Blocked destructive command: ${invocation.cmd} target contains shell expansion (${JSON.stringify(target)}).\\n\\n` +\n `Specify an explicit path (avoid $VARS, backticks, or %VAR%), or run this command manually.\\n` +\n `To override (not recommended), set ${ENV_ALLOW}=1 in the ${args.platform ?? process.platform} environment and rerun.`,\n }\n }\n\n const resolvedTarget = resolvePathForSafety(target, cwd, homeDir)\n if (\n isCriticalRemovalTarget(resolvedTarget, {\n homeDir,\n originalCwd: args.originalCwd,\n })\n ) {\n return {\n command: args.command,\n subcommand,\n target,\n resolvedTarget,\n message:\n `Blocked destructive command: ${invocation.cmd} target resolves to a critical directory (${JSON.stringify(resolvedTarget)}).\\n\\n` +\n `This guard prevents accidental deletion of system/home/project roots in non-interactive agent runs.\\n` +\n `To override (not recommended), set ${ENV_ALLOW}=1 in the ${args.platform ?? process.platform} environment and rerun.`,\n }\n }\n }\n }\n\n return null\n}\n", "import type { SimpleRule } from './bashGateRules'\n\nexport const SIMPLE_RULES: SimpleRule[] = [\n // Privilege escalation / identity\n {\n code: 'PRIV_SUDO',\n severity: 'high',\n category: 'privilege',\n title: 'sudo escalates privileges',\n patterns: [/\\bsudo\\b/i],\n },\n {\n code: 'PRIV_SU',\n severity: 'high',\n category: 'privilege',\n title: 'su changes user identity',\n patterns: [/\\bsu\\b(\\s|$)/i],\n },\n {\n code: 'PRIV_SUDOERS',\n severity: 'high',\n category: 'privilege',\n title: 'modifies sudoers policy',\n patterns: [/\\/etc\\/sudoers(\\.d\\/[^\\s]+)?/i],\n },\n\n // System power / service management\n {\n code: 'SYS_SHUTDOWN',\n severity: 'high',\n category: 'system',\n title: 'shutdown/reboot/poweroff',\n patterns: [/\\b(shutdown|reboot|poweroff|halt|init\\s+0)\\b/i],\n },\n {\n code: 'SYS_SYSTEMCTL_STOP',\n severity: 'high',\n category: 'system',\n title: 'systemctl stop/disable/mask can break services',\n patterns: [/\\bsystemctl\\b[^\\n]*\\b(stop|disable|mask)\\b/i],\n },\n\n // Filesystem / disk destructive operations\n {\n code: 'FS_MKFS',\n severity: 'high',\n category: 'fs_delete',\n title: 'mkfs formats filesystems',\n patterns: [/\\bmkfs(\\.[a-z0-9]+)?\\b/i],\n },\n {\n code: 'FS_PARTITION',\n severity: 'high',\n category: 'fs_delete',\n title: 'disk partitioning tools',\n patterns: [/\\b(fdisk|parted|sfdisk|gdisk)\\b/i],\n },\n {\n code: 'FS_WIPE',\n severity: 'high',\n category: 'fs_delete',\n title: 'secure wipe/destructive disk ops',\n patterns: [/\\b(shred|wipefs|blkdiscard)\\b/i],\n },\n {\n code: 'FS_DD_OF',\n severity: 'high',\n category: 'fs_delete',\n title: 'dd writes to output target (of=...)',\n patterns: [/\\bdd\\b[^\\n]*\\bof=\\S+/i],\n },\n\n // Remote fetch + exec / code execution\n {\n code: 'RCE_PIPE_TO_SHELL',\n severity: 'high',\n category: 'remote_exec',\n title: 'pipe remote content into shell',\n patterns: [/\\b(curl|wget)\\b[^\\n]*\\|\\s*(bash|sh)\\b/i],\n },\n {\n code: 'RCE_EVAL',\n severity: 'high',\n category: 'remote_exec',\n title: 'eval executes arbitrary code',\n patterns: [/\\beval\\b/i],\n },\n {\n code: 'RCE_SOURCE_SUBSTITUTION',\n severity: 'high',\n category: 'remote_exec',\n title: 'source of process substitution executes command output',\n patterns: [/\\b(source|\\.)\\b[^\\n]*<\\(/i],\n },\n {\n code: 'EXEC_SOURCE_FILE',\n severity: 'medium',\n category: 'remote_exec',\n title: 'sources a file into the current shell',\n patterns: [/\\bsource\\b\\s+(?!<\\()\\S+/i, /(^|[;&|()\\s])\\.\\s+(?!<\\()\\S+/i],\n },\n {\n code: 'RCE_BASE64',\n severity: 'high',\n category: 'remote_exec',\n title: 'decode then execute',\n patterns: [/\\bbase64\\b[^\\n]*\\s+-d\\b[^\\n]*\\|\\s*(bash|sh)\\b/i],\n },\n {\n code: 'RCE_ONE_LINER',\n severity: 'medium',\n category: 'remote_exec',\n title: 'interpreter one-liner execution',\n patterns: [\n /\\bpython3?\\b\\s+-c\\b/i,\n /\\bperl\\b\\s+-e\\b/i,\n /\\bruby\\b\\s+-e\\b/i,\n /\\bnode\\b\\s+-e\\b/i,\n ],\n },\n\n // Persistence / startup modification\n {\n code: 'PERSIST_RC',\n severity: 'high',\n category: 'persistence',\n title: 'modifies shell startup files',\n patterns: [/~\\/\\.(bashrc|zshrc|profile|bash_profile)\\b/i],\n },\n {\n code: 'PERSIST_CRON',\n severity: 'high',\n category: 'persistence',\n title: 'modifies cron jobs',\n patterns: [/\\bcrontab\\b/i, /\\/etc\\/cron\\./i, /cron\\.d/i],\n },\n {\n code: 'PERSIST_SYSTEMD',\n severity: 'high',\n category: 'persistence',\n title: 'modifies systemd units',\n patterns: [/\\/etc\\/systemd\\/system\\//i, /\\bsystemctl\\b[^\\n]*\\benable\\b/i],\n },\n\n // Credentials / secrets access\n {\n code: 'CRED_SSH',\n severity: 'high',\n category: 'credentials',\n title: 'SSH key material access',\n patterns: [/~\\/\\.ssh\\//i, /\\/etc\\/ssh\\//i],\n },\n {\n code: 'CRED_SHADOW',\n severity: 'high',\n category: 'credentials',\n title: 'reads /etc/shadow',\n patterns: [/\\/etc\\/shadow\\b/i],\n },\n {\n code: 'CRED_ENV_FILE',\n severity: 'high',\n category: 'credentials',\n title: 'reads .env secrets file',\n patterns: [\n /(\\s|^)(cat|sed|awk|perl|python3?)\\b[^\\n]*\\s+(\\.\\/)?\\.env(\\s|$)/i,\n /(^|\\/)\\.env(\\.|$)/i,\n ],\n },\n\n // Infra destroy\n {\n code: 'INFRA_KUBECTL_DELETE',\n severity: 'high',\n category: 'infra_destroy',\n title: 'kubectl delete can destroy cluster resources',\n patterns: [/\\bkubectl\\b[^\\n]*\\bdelete\\b/i],\n },\n {\n code: 'INFRA_TERRAFORM_DESTROY',\n severity: 'high',\n category: 'infra_destroy',\n title: 'terraform destroy destroys infrastructure',\n patterns: [/\\bterraform\\b[^\\n]*\\bdestroy\\b/i],\n },\n {\n code: 'INFRA_PULUMI_DESTROY',\n severity: 'high',\n category: 'infra_destroy',\n title: 'pulumi destroy destroys infrastructure',\n patterns: [/\\bpulumi\\b[^\\n]*\\bdestroy\\b/i],\n },\n\n // Containers / data loss\n {\n code: 'DOCKER_PRUNE',\n severity: 'medium',\n category: 'container',\n title: 'docker prune can delete data',\n patterns: [/\\bdocker\\b[^\\n]*\\b(system\\s+prune|volume\\s+rm)\\b/i],\n },\n\n // Package removal\n {\n code: 'PKG_REMOVE',\n severity: 'medium',\n category: 'pkg',\n title: 'package removal/purge can break environment',\n patterns: [\n /\\bapt(-get)?\\b[^\\n]*\\b(remove|purge)\\b/i,\n /\\byum\\b[^\\n]*\\bremove\\b/i,\n /\\bdnf\\b[^\\n]*\\bremove\\b/i,\n /\\bpacman\\b[^\\n]*\\b-R(ns)?\\b/i,\n /\\bnpm\\b[^\\n]*\\buninstall\\b/i,\n /\\bpnpm\\b[^\\n]*\\bremove\\b/i,\n /\\byarn\\b[^\\n]*\\bremove\\b/i,\n ],\n },\n\n // Obfuscation / shell bomb\n {\n code: 'OBF_FORK_BOMB',\n severity: 'high',\n category: 'obfuscation',\n title: 'fork bomb pattern',\n patterns: [/:\\(\\)\\s*\\{\\s*:\\s*\\|\\s*:\\s*&\\s*\\}\\s*;:/],\n },\n]\n", "export type BashGateFindingSeverity = 'high' | 'medium'\n\nexport type BashGateFindingCategory =\n | 'fs_delete'\n | 'fs_write'\n | 'privilege'\n | 'remote_exec'\n | 'persistence'\n | 'credentials'\n | 'git_data_loss'\n | 'infra_destroy'\n | 'container'\n | 'system'\n | 'process'\n | 'network'\n | 'pkg'\n | 'obfuscation'\n\nexport type BashGateFinding = {\n code: string\n severity: BashGateFindingSeverity\n category: BashGateFindingCategory\n title: string\n evidence?: string\n}\n\nexport type SimpleRule = {\n code: string\n severity: BashGateFindingSeverity\n category: BashGateFindingCategory\n title: string\n patterns: RegExp[]\n evidence?: (m: RegExpMatchArray) => string\n}\n\nfunction addUnique(\n findings: BashGateFinding[],\n finding: BashGateFinding,\n): void {\n if (findings.some(f => f.code === finding.code)) return\n findings.push(finding)\n}\n\nfunction applySimpleRules(\n command: string,\n rules: SimpleRule[],\n): BashGateFinding[] {\n const findings: BashGateFinding[] = []\n for (const rule of rules) {\n for (const re of rule.patterns) {\n const m = command.match(re)\n if (!m) continue\n addUnique(findings, {\n code: rule.code,\n severity: rule.severity,\n category: rule.category,\n title: rule.title,\n ...(rule.evidence ? { evidence: rule.evidence(m).slice(0, 200) } : {}),\n })\n break\n }\n }\n return findings\n}\n\nfunction analyzeRm(command: string): BashGateFinding[] {\n const findings: BashGateFinding[] = []\n if (!/(^|[;&|()\\s])rm(\\s|$)/.test(command)) return findings\n\n addUnique(findings, {\n code: 'FS_RM_ANY',\n severity: 'medium',\n category: 'fs_delete',\n title: 'rm deletes files/directories',\n })\n\n if (/\\s-rf(\\s|$)/i.test(command) || /\\s-fR(\\s|$)/i.test(command)) {\n addUnique(findings, {\n code: 'FS_RM_FORCE_RECURSIVE',\n severity: 'medium',\n category: 'fs_delete',\n title: 'rm uses force+recursive flags (high data-loss risk)',\n })\n }\n\n const criticalTargets = [\n { re: /(^|\\s)\\/(\\s|$)/, label: '/' },\n { re: /(^|\\s)~(\\/|\\s|$)/, label: '~' },\n { re: /(^|\\s)\\.(\\s|$)/, label: '.' },\n { re: /(^|\\s)\\.\\.(\\s|$)/, label: '..' },\n {\n re: /(^|\\s)\\/(etc|bin|sbin|usr|var|lib|proc|sys)(\\/|\\s|$)/,\n label: '/(etc|bin|sbin|usr|var|lib|proc|sys)',\n },\n ]\n for (const t of criticalTargets) {\n if (t.re.test(command)) {\n addUnique(findings, {\n code: 'FS_RM_CRITICAL_TARGET',\n severity: 'high',\n category: 'fs_delete',\n title: 'rm targets a critical path',\n evidence: t.label,\n })\n break\n }\n }\n\n if (\n /[^\\n]*\\*/.test(command) ||\n /[^\\n]*\\?/.test(command) ||\n /[^\\n]*\\{/.test(command)\n ) {\n addUnique(findings, {\n code: 'FS_RM_GLOB',\n severity: 'medium',\n category: 'fs_delete',\n title: 'rm uses glob/expansion patterns (wider blast radius)',\n })\n }\n\n return findings\n}\n\nfunction analyzeGit(command: string): BashGateFinding[] {\n const findings: BashGateFinding[] = []\n if (!/(^|[;&|()\\s])git(\\s|$)/.test(command)) return findings\n\n const dataLossOps: Array<{ code: string; title: string; re: RegExp }> = [\n {\n code: 'GIT_CHECKOUT',\n title: 'git checkout can discard working changes',\n re: /\\bgit\\b[^\\n]*\\bcheckout\\b/i,\n },\n {\n code: 'GIT_RESTORE',\n title: 'git restore can discard working changes',\n re: /\\bgit\\b[^\\n]*\\brestore\\b/i,\n },\n {\n code: 'GIT_RESET',\n title: 'git reset can discard commits/changes',\n re: /\\bgit\\b[^\\n]*\\breset\\b/i,\n },\n {\n code: 'GIT_RESET_HARD',\n title: 'git reset --hard discards local changes',\n re: /\\bgit\\b[^\\n]*\\breset\\b[^\\n]*--hard\\b/i,\n },\n {\n code: 'GIT_CLEAN',\n title: 'git clean deletes untracked files',\n re: /\\bgit\\b[^\\n]*\\bclean\\b/i,\n },\n {\n code: 'GIT_CLEAN_FDX',\n title: 'git clean -fdx deletes untracked + ignored files',\n re: /\\bgit\\b[^\\n]*\\bclean\\b[^\\n]*-(?:[^\\n]*f[^\\n]*d|[^\\n]*d[^\\n]*f)[^\\n]*x/i,\n },\n {\n code: 'GIT_PUSH_FORCE',\n title: 'git push --force rewrites remote history',\n re: /\\bgit\\b[^\\n]*\\bpush\\b[^\\n]*(--force|--force-with-lease|\\s-f(\\s|$))/i,\n },\n {\n code: 'GIT_PUSH_DELETE',\n title: 'git push --delete deletes remote refs',\n re: /\\bgit\\b[^\\n]*\\bpush\\b[^\\n]*(--delete|:\\S+)/i,\n },\n {\n code: 'GIT_FILTER_REWRITE',\n title: 'history rewrite (filter-branch/filter-repo/rebase/amend)',\n re: /\\bgit\\b[^\\n]*\\b(filter-branch|filter-repo|rebase|commit\\b[^\\n]*--amend)\\b/i,\n },\n {\n code: 'GIT_RECOVERY_REDUCE',\n title: 'reduces recoverability (reflog expire / gc --prune=now)',\n re: /\\bgit\\b[^\\n]*\\b(reflog\\b[^\\n]*expire|gc\\b[^\\n]*--prune=now)\\b/i,\n },\n {\n code: 'GIT_STASH_DROP',\n title: 'stash drop/clear removes saved work',\n re: /\\bgit\\b[^\\n]*\\bstash\\b[^\\n]*\\b(drop|clear)\\b/i,\n },\n ]\n\n for (const op of dataLossOps) {\n if (!op.re.test(command)) continue\n addUnique(findings, {\n code: op.code,\n severity: 'medium',\n category: 'git_data_loss',\n title: op.title,\n })\n }\n\n return findings\n}\n\nimport { SIMPLE_RULES } from './bashGateSimpleRules'\n\nexport function getBashGateFindings(command: string): BashGateFinding[] {\n const c = command.trim()\n if (!c) return []\n const findings = [\n ...analyzeRm(c),\n ...analyzeGit(c),\n ...applySimpleRules(c, SIMPLE_RULES),\n ]\n\n // Deterministic ordering (stable prompts/dumps).\n findings.sort((a, b) => a.code.localeCompare(b.code))\n return findings\n}\n\nexport function shouldReviewBashCommand(findings: BashGateFinding[]): boolean {\n // Unified policy: any high-severity signal requires LLM review.\n return findings.some(f => f.severity === 'high')\n}\n", "import { randomUUID } from 'crypto'\nimport { mkdirSync, writeFileSync } from 'fs'\nimport { join } from 'path'\nimport { CACHE_PATHS, dateToFilename } from '#core/utils/log'\nimport type { BashGateFinding } from './bashGateRules'\n\nexport function writeGateFailureDump(args: {\n command: string\n userPrompt: string\n description: string\n findings: BashGateFinding[]\n input: string\n output?: string\n error: string\n errorType?: string\n}): void {\n try {\n const dir = join(CACHE_PATHS.errors(), 'bash-llm-gate')\n mkdirSync(dir, { recursive: true })\n const filename = `${dateToFilename(new Date())}-${randomUUID()}.txt`\n const path = join(dir, filename)\n const body = [\n '=== Bash LLM gate failure ===',\n '',\n `error: ${args.error}`,\n args.errorType ? `errorType: ${args.errorType}` : '',\n '',\n '--- command ---',\n args.command,\n '',\n '--- description ---',\n args.description,\n '',\n '--- userPrompt ---',\n args.userPrompt,\n '',\n '--- findings ---',\n args.findings.length\n ? args.findings\n .map(\n f =>\n `[${f.code}] (${f.severity}/${f.category}) ${f.title}${f.evidence ? ` \u2014 ${f.evidence}` : ''}`,\n )\n .join('\\n')\n : '(none)',\n '',\n '--- gate input ---',\n args.input,\n '',\n args.output !== undefined ? '--- gate output ---' : '',\n args.output ?? '',\n '',\n ]\n .filter(Boolean)\n .join('\\n')\n writeFileSync(path, body, 'utf8')\n } catch {\n // Best-effort diagnostics only.\n }\n}\n", "import type { CommandSource } from './commandSource'\nimport type { BashGateFinding } from './bashGateRules'\n\nexport function buildGateSystemPrompt(): string[] {\n return [\n [\n 'You are a safety + intent-alignment reviewer for a coding agent about to run a shell command on the user machine.',\n 'A local rule pool produced one or more risk findings. Your job is to decide whether to ALLOW or BLOCK executing the command now.',\n '',\n 'You must evaluate BOTH:',\n '1) Safety of the behavior (risk of data loss, irreversible changes, privilege escalation, remote code execution, infra destruction).',\n '2) Alignment: does the command match the user request (USER_PROMPT) and the initiator description (DESCRIPTION)?',\n '',\n 'Output (required): EXACTLY ONE LINE of XML and nothing else:',\n '<final><decision>allow|block</decision><reason>...</reason></final>',\n '- If allow: <reason> may be empty.',\n '- If block: <reason> is required (<=140 chars).',\n '',\n 'No analysis. No markdown. No numbered lists.',\n '',\n 'Few-shot examples (follow the output format strictly):',\n '',\n 'Example A (rm, user asked to delete a temp file):',\n 'USER_PROMPT: Remove the generated temp file',\n 'DESCRIPTION: Delete temp output',\n 'COMMAND: rm -f ./tmp/output.log',\n '<final><decision>allow</decision><reason></reason></final>',\n '',\n 'Example B (rm -rf ., mismatch):',\n 'USER_PROMPT: Check git status',\n 'DESCRIPTION: Check repo state',\n 'COMMAND: rm -rf .',\n '<final><decision>block</decision><reason>Destructive delete does not match the request</reason></final>',\n '',\n 'Example C (git reset --hard, explicitly requested):',\n 'USER_PROMPT: Discard my local changes and go back to HEAD',\n 'DESCRIPTION: Reset working tree to HEAD',\n 'COMMAND: git reset --hard',\n '<final><decision>allow</decision><reason></reason></final>',\n '',\n 'Example D (git clean -fdx, unclear intent):',\n 'USER_PROMPT: Run tests',\n 'DESCRIPTION: Clean repository',\n 'COMMAND: git clean -fdx',\n '<final><decision>block</decision><reason>Deletes untracked/ignored files; user did not request cleanup</reason></final>',\n ].join('\\n'),\n ]\n}\n\nexport function buildGateUserInput(params: {\n command: string\n userPrompt: string\n description: string\n findings: BashGateFinding[]\n platform: NodeJS.Platform\n commandSource: CommandSource\n safeMode: boolean\n runInBackground: boolean\n willSandbox: boolean\n sandboxRequired: boolean\n cwd: string\n originalCwd: string\n}): string {\n // Keep this plain text (no JSON) for maximum model compatibility.\n const lines: string[] = []\n lines.push(\n 'OUTPUT_FORMAT: <final><decision>allow|block</decision><reason>...</reason></final>',\n )\n lines.push('')\n lines.push('FINDINGS:')\n if (params.findings.length === 0) {\n lines.push('- (none)')\n } else {\n for (const f of params.findings.slice(0, 20)) {\n lines.push(\n `- [${f.code}] (${f.severity}/${f.category}) ${f.title}${f.evidence ? ` \u2014 ${f.evidence}` : ''}`,\n )\n }\n if (params.findings.length > 20) {\n lines.push(`- ... (${params.findings.length - 20} more)`)\n }\n }\n lines.push('')\n lines.push('USER_PROMPT:')\n lines.push(params.userPrompt.trim() ? params.userPrompt.trim() : '(none)')\n lines.push('')\n lines.push('DESCRIPTION:')\n lines.push(params.description.trim() ? params.description.trim() : '(none)')\n lines.push('')\n lines.push('COMMAND:')\n lines.push(params.command)\n lines.push('')\n lines.push('CONTEXT:')\n lines.push(`- commandSource: ${params.commandSource}`)\n lines.push(`- platform: ${params.platform}`)\n lines.push(`- safeMode: ${params.safeMode ? 'true' : 'false'}`)\n lines.push(`- runInBackground: ${params.runInBackground ? 'true' : 'false'}`)\n lines.push(`- sandbox.willSandbox: ${params.willSandbox ? 'true' : 'false'}`)\n lines.push(`- sandbox.required: ${params.sandboxRequired ? 'true' : 'false'}`)\n lines.push(`- cwd: ${params.cwd}`)\n lines.push(`- originalCwd: ${params.originalCwd}`)\n return lines.join('\\n')\n}\n", "export type BashLlmGateVerdict = {\n action: 'allow' | 'block'\n summary: string\n}\n\nexport function parseVerdictFromText(text: string): BashLlmGateVerdict {\n const trimmed = text.trim()\n if (!trimmed) throw new Error('LLM gate produced empty output')\n\n if (/^allow$/i.test(trimmed)) return { action: 'allow', summary: '' }\n if (/^block$/i.test(trimmed)) return { action: 'block', summary: '' }\n\n const finals = Array.from(\n trimmed.matchAll(/<final\\b[^>]*>[\\s\\S]*?<\\/final>/gi),\n )\n const xml = finals.length > 0 ? finals[finals.length - 1]![0]! : trimmed\n const decisionTag = xml.match(/<decision>\\s*(allow|block)\\s*<\\/decision>/i)\n if (decisionTag) {\n const action = decisionTag[1]!.trim().toLowerCase() as 'allow' | 'block'\n const reasonTag = xml.match(/<reason>\\s*([^<]{0,180})\\s*<\\/reason>/i)\n return { action, summary: (reasonTag?.[1] ?? '').trim() }\n }\n\n const nonEmptyLines = trimmed\n .split(/\\r?\\n/)\n .map(l => l.trim())\n .filter(Boolean)\n for (let i = nonEmptyLines.length - 1; i >= 0; i--) {\n const line = nonEmptyLines[i]!\n const m = line.match(\n /^(?:[-*\u2022]|\\d+\\.)?\\s*(allow|block)\\s*(?:(?:[:-]\\s*)(.{0,200}))?\\s*$/i,\n )\n if (!m) continue\n const action = m[1]!.toLowerCase() as 'allow' | 'block'\n const summary = (m[2] ?? '').trim().slice(0, 140)\n return { action, summary }\n }\n\n const bareDecisionTag = trimmed.match(\n /<decision>\\s*(allow|block)\\s*<\\/decision>/i,\n )\n if (bareDecisionTag) {\n const action = bareDecisionTag[1]!.trim().toLowerCase() as 'allow' | 'block'\n const reasonTag = trimmed.match(/<reason>\\s*([^<]{0,180})\\s*<\\/reason>/i)\n const summary = (reasonTag?.[1] ?? '').trim()\n return { action, summary }\n }\n\n const preview = trimmed.length > 240 ? `${trimmed.slice(0, 240)}\u2026` : trimmed\n throw new Error(\n `Unable to parse LLM gate verdict. Output preview: ${preview}`,\n )\n}\n\nexport function formatBashLlmGateBlockMessage(\n verdict: BashLlmGateVerdict,\n): string {\n const summary = verdict.summary?.trim()\n return `Blocked by LLM intent gate: ${summary ? summary : 'No reason provided by gate model'}`\n}\n", "import { logError } from '#core/utils/log'\nimport { createUserMessage } from '#core/utils/messages'\nimport type { CommandSource } from './commandSource'\nimport {\n getBashGateFindings,\n shouldReviewBashCommand,\n type BashGateFinding,\n} from './bashGateRules'\nimport { writeGateFailureDump } from './llmSafetyGateDump'\nimport {\n buildGateSystemPrompt,\n buildGateUserInput,\n} from './llmSafetyGatePrompt'\nimport {\n parseVerdictFromText,\n type BashLlmGateVerdict,\n} from './llmSafetyGateVerdict'\nexport {\n formatBashLlmGateBlockMessage,\n type BashLlmGateVerdict,\n} from './llmSafetyGateVerdict'\n\n// Gate calls must be fast in the common case, but some reasoning models can be slow.\n// Keep this generous enough to avoid spurious timeouts, while still bounded.\nconst DEFAULT_GATE_TIMEOUT_MS = 300_000\nconst DEFAULT_GATE_STOP_SEQUENCES = ['</final>']\n\nexport type BashLlmGateErrorType =\n | 'api'\n | 'timeout'\n | 'invalid_output'\n | 'unknown'\n\ntype GateQueryFn = (args: {\n systemPrompt: string[]\n userInput: string\n signal: AbortSignal\n model?: 'quick' | 'main'\n}) => Promise<string>\n\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n if (!value || typeof value !== 'object') return null\n return value as Record<string, unknown>\n}\n\nfunction collectTextBlocks(content: unknown): string {\n if (typeof content === 'string') return content\n if (!Array.isArray(content)) return ''\n return content\n .flatMap(block => {\n const record = asRecord(block)\n if (!record) return []\n if (record.type === 'text' && typeof record.text === 'string')\n return [record.text]\n if (record.type === 'thinking' && typeof record.thinking === 'string')\n return [record.thinking]\n // Some providers return plain objects without `type`; tolerate those.\n if (\n (record.type === undefined || record.type === null) &&\n typeof record.text === 'string'\n )\n return [record.text]\n if (\n (record.type === undefined || record.type === null) &&\n typeof record.thinking === 'string'\n )\n return [record.thinking]\n return []\n })\n .join('\\n')\n}\n\nfunction formatParseError(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\nasync function defaultGateQuery(args: {\n systemPrompt: string[]\n userInput: string\n signal: AbortSignal\n model?: 'quick' | 'main'\n}): Promise<string> {\n const { API_ERROR_MESSAGE_PREFIX, queryLLM } = await import('#core/ai/llm')\n const messages = [createUserMessage(args.userInput)]\n\n // Use the normal model-pointer config but *without* the CLI sysprompt.\n // The gate needs a single, purpose-built system prompt to stay deterministic.\n const assistant = await queryLLM(\n messages,\n args.systemPrompt,\n 0,\n [],\n args.signal,\n {\n safeMode: false,\n model: args.model ?? 'quick',\n prependCLISysprompt: false,\n stopSequences: DEFAULT_GATE_STOP_SEQUENCES,\n },\n )\n\n const text = collectTextBlocks(assistant.message.content as unknown)\n const trimmed = text.trim()\n if (assistant.isApiErrorMessage) {\n const preview = trimmed.length > 240 ? `${trimmed.slice(0, 240)}\u2026` : trimmed\n throw new Error(`LLM gate model error: ${preview}`)\n }\n if (trimmed.startsWith(API_ERROR_MESSAGE_PREFIX)) {\n const preview = trimmed.length > 240 ? `${trimmed.slice(0, 240)}\u2026` : trimmed\n throw new Error(`LLM gate model error: ${preview}`)\n }\n return text\n}\n\ntype GateAttemptOutput = {\n model: 'quick' | 'main'\n output: string\n error?: string\n}\n\nexport async function runBashLlmSafetyGate(params: {\n command: string\n userPrompt: string\n description: string\n platform: NodeJS.Platform\n commandSource: CommandSource\n safeMode: boolean\n runInBackground: boolean\n willSandbox: boolean\n sandboxRequired: boolean\n cwd: string\n originalCwd: string\n parentAbortSignal?: AbortSignal\n query?: GateQueryFn\n}): Promise<\n | { decision: 'allow'; verdict: BashLlmGateVerdict; fromCache: boolean }\n | { decision: 'block'; verdict: BashLlmGateVerdict; fromCache: boolean }\n | {\n decision: 'error'\n error: string\n errorType: BashLlmGateErrorType\n willSandbox: boolean\n canFailOpen: boolean\n }\n | { decision: 'disabled' }\n> {\n const trimmedUserPrompt = params.userPrompt.trim()\n const trimmedDescription = params.description.trim()\n const findings = getBashGateFindings(params.command)\n const attemptOutputs: GateAttemptOutput[] = []\n\n // Only run the LLM gate when unified policy says review is needed.\n if (!shouldReviewBashCommand(findings)) {\n return {\n decision: 'allow',\n verdict: { action: 'allow', summary: '' },\n fromCache: false,\n }\n }\n\n const abortController = new AbortController()\n const timeout = setTimeout(\n () => abortController.abort(),\n DEFAULT_GATE_TIMEOUT_MS,\n )\n const onAbort = () => abortController.abort()\n params.parentAbortSignal?.addEventListener('abort', onAbort, { once: true })\n\n try {\n const baseInput = buildGateUserInput({\n command: params.command,\n userPrompt: trimmedUserPrompt,\n description: trimmedDescription,\n findings,\n platform: params.platform,\n commandSource: params.commandSource,\n safeMode: params.safeMode,\n runInBackground: params.runInBackground,\n willSandbox: params.willSandbox,\n sandboxRequired: params.sandboxRequired,\n cwd: params.cwd,\n originalCwd: params.originalCwd,\n })\n const query = params.query ?? defaultGateQuery\n const attempts: Array<{ model: 'quick' | 'main' }> = [\n { model: 'quick' },\n { model: 'main' },\n { model: 'main' },\n ]\n\n let lastError: unknown = null\n for (const attempt of attempts) {\n try {\n const output = await query({\n systemPrompt: buildGateSystemPrompt(),\n userInput: baseInput,\n signal: abortController.signal,\n model: attempt.model,\n })\n attemptOutputs.push({ model: attempt.model, output })\n const verdict = parseVerdictFromText(output)\n return {\n decision: verdict.action === 'allow' ? 'allow' : 'block',\n verdict,\n fromCache: false,\n }\n } catch (e) {\n lastError = e\n attemptOutputs.push({\n model: attempt.model,\n output: '',\n error: formatParseError(e),\n })\n }\n }\n throw lastError ?? new Error('LLM gate produced no verdict')\n } catch (error) {\n const errorStr = formatParseError(error)\n const errorType: BashLlmGateErrorType = abortController.signal.aborted\n ? 'timeout'\n : errorStr.startsWith('LLM gate model error:')\n ? 'api'\n : errorStr.startsWith('LLM gate produced empty output') ||\n errorStr.startsWith('Unable to parse LLM gate verdict')\n ? 'invalid_output'\n : 'unknown'\n logError(`Bash LLM gate error: ${errorStr}`)\n const input = buildGateUserInput({\n command: params.command,\n userPrompt: trimmedUserPrompt,\n description: trimmedDescription,\n findings,\n platform: params.platform,\n commandSource: params.commandSource,\n safeMode: params.safeMode,\n runInBackground: params.runInBackground,\n willSandbox: params.willSandbox,\n sandboxRequired: params.sandboxRequired,\n cwd: params.cwd,\n originalCwd: params.originalCwd,\n })\n const output =\n attemptOutputs.length > 0\n ? attemptOutputs\n .map(o => {\n const header = `--- model: ${o.model} ---`\n const body = o.error ? `error: ${o.error}` : o.output\n return `${header}\\n${body}`\n })\n .join('\\n\\n')\n : undefined\n writeGateFailureDump({\n command: params.command,\n userPrompt: trimmedUserPrompt,\n description: trimmedDescription,\n findings,\n input,\n ...(output ? { output } : {}),\n error: errorStr,\n errorType,\n })\n return {\n decision: 'error',\n error: errorStr,\n errorType,\n willSandbox: params.willSandbox,\n canFailOpen: false,\n }\n } finally {\n clearTimeout(timeout)\n params.parentAbortSignal?.removeEventListener('abort', onAbort)\n }\n}\n", "/**\n * Command source tracking for dual-mode security.\n *\n * - user_bash_mode: User-initiated `!` commands (relaxed)\n * - agent_call: Tool use via the LLM (strict)\n */\nexport type CommandSource = 'user_bash_mode' | 'agent_call'\n\n/**\n * Context for bash command validation.\n */\nexport interface BashValidationContext {\n source: CommandSource\n}\n\n/**\n * Get validation context from a tool context object.\n */\nexport function getCommandSource(context: any): CommandSource {\n if (context?.commandSource === 'user_bash_mode') {\n return 'user_bash_mode'\n }\n return 'agent_call'\n}\n", "import { statSync } from 'fs'\nimport { EOL } from 'os'\nimport { isAbsolute, resolve } from 'path'\nimport * as React from 'react'\nimport { createAssistantMessage } from '#core/utils/messages'\nimport { isInDirectory } from '#core/utils/file'\nimport { logError } from '#core/utils/log'\nimport { getCwd, getOriginalCwd } from '#core/utils/state'\nimport { BunShell } from '#runtime/shell'\nimport type { BunShellSandboxOptions } from '#runtime/shell'\nimport { BashToolRunInBackgroundOverlay } from './BashToolRunInBackgroundOverlay'\nimport { formatOutput, getCommandFilePaths } from './utils'\nimport { countNewlines, formatDuration, normalizeLineEndings } from './text'\nimport type { Out } from './BashTool'\nimport { maybeSummarizeBashOutput } from './summarizeOutput'\n\ntype SetToolJSX = (\n value: {\n jsx: React.ReactNode | null\n shouldHidePromptInput: boolean\n } | null,\n) => void\n\nexport async function* executeForegroundBash(options: {\n command: string\n timeout: number\n abortController: AbortController\n readFileTimestamps: Record<string, number>\n sandboxOptions: BunShellSandboxOptions | undefined\n dangerouslyDisableSandbox?: boolean\n setToolJSX?: SetToolJSX\n renderResultForAssistant: (output: Out) => string\n conversationKey: string\n}): AsyncGenerator<\n | { type: 'progress'; content: unknown }\n | { type: 'result'; resultForAssistant: string; data: Out }\n> {\n const { command, timeout, abortController, readFileTimestamps } = options\n const setToolJSX = options.setToolJSX\n let stdout = ''\n let stderr = ''\n\n try {\n const startedAt = Date.now()\n const PROGRESS_INITIAL_DELAY_MS = 2000 // Reference CLI: XJ2=2000\n const PROGRESS_INTERVAL_MS = 1000 // Reference CLI: SH5=1000\n const PROGRESS_MAX_LINES = 5\n const PROGRESS_TAIL_MAX_CHARS = 100_000\n\n let combinedTail = ''\n let totalNewlines = 0\n let sawAnyOutput = false\n\n const onChunk = (chunk: string) => {\n if (!chunk) return\n sawAnyOutput = true\n totalNewlines += countNewlines(chunk)\n combinedTail += chunk\n if (combinedTail.length > PROGRESS_TAIL_MAX_CHARS) {\n combinedTail = combinedTail.slice(-PROGRESS_TAIL_MAX_CHARS)\n }\n }\n\n const exec = BunShell.getInstance().execPromotable(\n command,\n abortController.signal,\n timeout,\n {\n sandbox: options.sandboxOptions,\n onStdoutChunk: onChunk,\n onStderrChunk: onChunk,\n },\n )\n\n let backgroundRequested = false\n let resolveBackground: ((bashId: string) => void) | null = null\n const backgroundPromise = new Promise<string>(resolve => {\n resolveBackground = resolve\n })\n\n const requestBackground = () => {\n if (backgroundRequested) return\n backgroundRequested = true\n const promoted = exec.background()\n if (!promoted) return\n resolveBackground?.(promoted.bashId)\n }\n\n const resultPromise = exec.result\n\n const buildProgressText = (): string => {\n const elapsedMs = Date.now() - startedAt\n const time = `(${formatDuration(elapsedMs)})`\n\n const normalized = normalizeLineEndings(combinedTail).trim()\n const lines = normalized.length\n ? normalized.split('\\n').filter(line => line.length > 0)\n : []\n\n if (lines.length === 0) {\n return `Running\u2026 ${time}`\n }\n\n const shownLines = lines.slice(-PROGRESS_MAX_LINES)\n const totalLines = sawAnyOutput ? totalNewlines + 1 : 0\n const extraLines = Math.max(0, totalLines - PROGRESS_MAX_LINES)\n\n const footerParts: string[] = []\n if (extraLines > 0) {\n footerParts.push(\n `+${extraLines} more line${extraLines === 1 ? '' : 's'}`,\n )\n }\n footerParts.push(time)\n\n return `${shownLines.join('\\n')}\\n${footerParts.join(' ')}`\n }\n\n // Compatibility: delay first progress paint to avoid flicker.\n let nextTickAt = startedAt + PROGRESS_INITIAL_DELAY_MS\n let overlayShown = false\n while (true) {\n const now = Date.now()\n const waitMs = Math.max(0, nextTickAt - now)\n const race = await Promise.race([\n resultPromise.then(r => ({ kind: 'done' as const, r })),\n backgroundPromise.then(bashId => ({\n kind: 'background' as const,\n bashId,\n })),\n new Promise<{ kind: 'tick' }>(resolve =>\n setTimeout(() => resolve({ kind: 'tick' }), waitMs),\n ),\n ])\n\n if (race.kind === 'background') {\n const data: Out = {\n stdout: '',\n stdoutLines: 0,\n stderr: '',\n stderrLines: 0,\n interrupted: false,\n bashId: race.bashId,\n backgroundTaskId: race.bashId,\n }\n\n yield {\n type: 'result',\n resultForAssistant: options.renderResultForAssistant(data),\n data,\n }\n return\n }\n\n if (race.kind === 'done') {\n const result = race.r\n\n stdout += (result.stdout || '').trim() + EOL\n stderr += (result.stderr || '').trim() + EOL\n if (result.code !== 0) {\n stderr += `Exit code ${result.code}`\n }\n\n if (!isInDirectory(getCwd(), getOriginalCwd())) {\n // Shell directory is outside original working directory, reset it\n await BunShell.getInstance().setCwd(getOriginalCwd())\n stderr = `${stderr.trim()}${EOL}Shell cwd was reset to ${getOriginalCwd()}`\n }\n\n // Update read timestamps for any files referenced by the command\n // Don't block the main thread!\n // Skip this in tests because it makes fixtures non-deterministic (they might not always get written),\n // so will be missing in CI.\n if (process.env.NODE_ENV !== 'test') {\n getCommandFilePaths(command, stdout).then(filePaths => {\n for (const filePath of filePaths) {\n const fullFilePath = isAbsolute(filePath)\n ? filePath\n : resolve(getCwd(), filePath)\n\n // Try/catch in case the file doesn't exist (because Haiku didn't properly extract it)\n try {\n readFileTimestamps[fullFilePath] =\n statSync(fullFilePath).mtimeMs\n } catch (e) {\n logError(e)\n }\n }\n })\n }\n\n const { totalLines: stdoutLines, truncatedContent: stdoutContent } =\n formatOutput(stdout.trim())\n const { totalLines: stderrLines, truncatedContent: stderrContent } =\n formatOutput(stderr.trim())\n\n const data: Out = {\n stdout: stdoutContent,\n stdoutLines,\n stderr: stderrContent,\n stderrLines,\n interrupted: result.interrupted,\n dangerouslyDisableSandbox: options.dangerouslyDisableSandbox,\n isImage: /^data:image\\/[^;]+;base64,/i.test(stdoutContent.trim()),\n }\n\n const outputForAnalysis = [stdoutContent, stderrContent]\n .filter(Boolean)\n .join('\\n')\n\n if (!data.isImage) {\n const summary = await maybeSummarizeBashOutput({\n command,\n stdout: stdout.trimEnd(),\n stderr: stderr.trimEnd(),\n outputForAnalysis,\n conversationKey: options.conversationKey,\n signal: abortController.signal,\n })\n if (summary) {\n data.summary = summary.summary\n data.rawOutputPath = summary.rawOutputPath\n }\n }\n\n yield {\n type: 'result',\n resultForAssistant: options.renderResultForAssistant(data),\n data,\n }\n return\n }\n\n if (\n !overlayShown &&\n setToolJSX &&\n Date.now() - startedAt >= PROGRESS_INITIAL_DELAY_MS\n ) {\n overlayShown = true\n setToolJSX({\n jsx: (\n <BashToolRunInBackgroundOverlay onBackground={requestBackground} />\n ),\n shouldHidePromptInput: false,\n })\n }\n\n const text = buildProgressText()\n yield {\n type: 'progress',\n content: createAssistantMessage(\n `<tool-progress>${text}</tool-progress>`,\n ),\n }\n\n nextTickAt = Date.now() + PROGRESS_INTERVAL_MS\n }\n } catch (error) {\n // \uD83D\uDD27 Handle cancellation or other errors properly\n const isAborted = abortController.signal.aborted\n const errorMessage = isAborted\n ? 'Command was cancelled by user'\n : `Command failed: ${error instanceof Error ? error.message : String(error)}`\n\n const data: Out = {\n stdout: stdout.trim(),\n stdoutLines: stdout.split('\\n').length,\n stderr: errorMessage,\n stderrLines: 1,\n interrupted: isAborted,\n }\n\n yield {\n type: 'result',\n resultForAssistant: options.renderResultForAssistant(data),\n data,\n }\n } finally {\n setToolJSX?.(null)\n }\n}\n", "import { Box, Text, useInput } from 'ink'\nimport React, { useEffect, useMemo, useRef, useState } from 'react'\nimport { getTheme } from '#core/utils/theme'\nimport {\n getRequestStatus,\n subscribeRequestStatus,\n type RequestStatus,\n} from '#core/utils/requestStatus'\n\nconst CHARACTERS =\n process.platform === 'darwin'\n ? ['\u00B7', '\u2722', '\u2733', '\u2217', '\u273B', '\u273D']\n : ['\u00B7', '\u2722', '*', '\u2217', '\u273B', '\u273D']\n\nfunction getLabel(status: RequestStatus): string {\n switch (status.kind) {\n case 'thinking':\n return 'Thinking'\n case 'streaming':\n return 'Streaming'\n case 'tool':\n return status.detail ? `Running tool: ${status.detail}` : 'Running tool'\n case 'idle':\n return 'Working'\n }\n}\n\nfunction RequestStatusIndicator(): React.ReactNode {\n const frames = useMemo(\n () => [...CHARACTERS, ...[...CHARACTERS].reverse()],\n [],\n )\n const theme = getTheme()\n\n const [frame, setFrame] = useState(0)\n const [elapsedTime, setElapsedTime] = useState(0)\n const [status, setStatus] = useState<RequestStatus>(() => getRequestStatus())\n\n const requestStartTime = useRef<number | null>(null)\n\n useEffect(() => {\n return subscribeRequestStatus(next => {\n setStatus(next)\n if (next.kind !== 'idle' && requestStartTime.current === null) {\n requestStartTime.current = Date.now()\n }\n if (next.kind === 'idle') {\n requestStartTime.current = null\n setElapsedTime(0)\n }\n })\n }, [])\n\n useEffect(() => {\n const timer = setInterval(() => {\n setFrame(f => (f + 1) % frames.length)\n }, 120)\n return () => clearInterval(timer)\n }, [frames.length])\n\n useEffect(() => {\n const timer = setInterval(() => {\n if (requestStartTime.current === null) {\n setElapsedTime(0)\n return\n }\n setElapsedTime(Math.floor((Date.now() - requestStartTime.current) / 1000))\n }, 250)\n return () => clearInterval(timer)\n }, [])\n\n return (\n <Box flexDirection=\"row\" marginTop={1}>\n <Box flexWrap=\"nowrap\" height={1} width={2}>\n <Text color={theme.kode}>{frames[frame]}</Text>\n </Box>\n <Text color={theme.kode}>{getLabel(status)}\u2026 </Text>\n <Text color={theme.secondaryText}>\n ({elapsedTime}s \u00B7 <Text bold>esc</Text> to interrupt)\n </Text>\n </Box>\n )\n}\n\nexport function BashToolRunInBackgroundOverlay({\n onBackground,\n}: {\n onBackground: () => void\n}): React.ReactNode {\n useInput((input, key) => {\n if (input === 'b' && key.ctrl) {\n onBackground()\n return true\n }\n return false\n })\n\n const shortcut = process.env.TMUX ? 'ctrl+b ctrl+b' : 'ctrl+b'\n\n return (\n <Box flexDirection=\"column\">\n <RequestStatusIndicator />\n <Box paddingLeft={5}>\n <Text dimColor>{`${shortcut} run in background`}</Text>\n </Box>\n </Box>\n )\n}\n", "import { queryQuick } from '#core/ai/llmLazy'\nimport { extractTag } from '#core/utils/messages'\nimport { MAX_OUTPUT_LENGTH } from './prompt'\n\nexport function formatOutput(content: string): {\n totalLines: number\n truncatedContent: string\n} {\n if (content.length <= MAX_OUTPUT_LENGTH) {\n return {\n totalLines: content.split('\\n').length,\n truncatedContent: content,\n }\n }\n const halfLength = MAX_OUTPUT_LENGTH / 2\n const start = content.slice(0, halfLength)\n const end = content.slice(-halfLength)\n const truncated = `${start}\\n\\n... [${content.slice(halfLength, -halfLength).split('\\n').length} lines truncated] ...\\n\\n${end}`\n\n return {\n totalLines: content.split('\\n').length,\n truncatedContent: truncated,\n }\n}\n\nexport async function getCommandFilePaths(\n command: string,\n output: string,\n): Promise<string[]> {\n const response = await queryQuick({\n systemPrompt: [\n `Extract any file paths that this command reads or modifies. For commands like \"git diff\" and \"cat\", include the paths of files being shown. Use paths verbatim -- don't add any slashes or try to resolve them. Do not try to infer paths that were not explicitly listed in the command output.\nFormat your response as:\n<filepaths>\npath/to/file1\npath/to/file2\n</filepaths>\n\nIf no files are read or modified, return empty filepaths tags:\n<filepaths>\n</filepaths>\n\nDo not include any other text in your response.`,\n ],\n userPrompt: `Command: ${command}\\nOutput: ${output}`,\n enablePromptCaching: true,\n })\n const content = response.message.content\n .filter(_ => _.type === 'text')\n .map(_ => _.text)\n .join('')\n\n return (\n extractTag(content, 'filepaths')?.trim().split('\\n').filter(Boolean) || []\n )\n}\n", "import { createHash, randomUUID } from 'crypto'\nimport { mkdirSync, writeFileSync } from 'fs'\nimport path from 'path'\n\nimport type { AssistantMessage, UserMessage } from '#core/query'\nimport { queryLLM } from '#core/ai/llmLazy'\nimport { getKodeBaseDir } from '#core/utils/env'\nimport { extractTag } from '#core/utils/messages'\n\nconst SUMMARY_THRESHOLD_CHARS = 5000 // Reference CLI: W97=5000\nconst OUTPUT_DIR_NAME = 'bash-outputs' // Reference CLI: V97=\"bash-outputs\"\n\nconst SUMMARY_SYSTEM_PROMPT = `You are analyzing output from a bash command to determine if it should be summarized.\n\nYour task is to:\n1. Determine if the output contains mostly repetitive logs, verbose build output, or other \"log spew\"\n2. If it does, extract only the relevant information (errors, test results, completion status, etc.)\n3. Consider the conversation context - if the user specifically asked to see detailed output, preserve it\n\nYou MUST output your response using XML tags in the following format:\n<should_summarize>true/false</should_summarize>\n<reason>reason for why you decided to summarize or not summarize the output</reason>\n<summary>markdown summary as described below (only if should_summarize is true)</summary>\n\nIf should_summarize is true, include all three tags with a comprehensive summary.\nIf should_summarize is false, include only the first two tags and omit the summary tag.\n\nSummary: The summary should be extremely comprehensive and detailed in markdown format. Especially consider the converstion context to determine what to focus on.\nFreely copy parts of the output verbatim into the summary if you think it is relevant to the conversation context or what the user is asking for.\nIt's fine if the summary is verbose. The summary should contain the following sections: (Make sure to include all of these sections)\n1. Overview: An overview of the output including the most interesting information summarized.\n2. Detailed summary: An extremely detailed summary of the output.\n3. Errors: List of relevant errors that were encountered. Include snippets of the output wherever possible.\n4. Verbatim output: Copy any parts of the provided output verbatim that are relevant to the conversation context. This is critical. Make sure to include ATLEAST 3 snippets of the output verbatim. \n5. DO NOT provide a recommendation. Just summarize the facts.\n\nReason: If providing a reason, it should comprehensively explain why you decided not to summarize the output.\n\nExamples of when to summarize:\n- Verbose build logs with only the final status being important. Eg. if we are running npm run build to test if our code changes build.\n- Test output where only the pass/fail results matter\n- Repetitive debug logs with a few key errors\n\nExamples of when NOT to summarize:\n- User explicitly asked to see the full output\n- Output contains unique, non-repetitive information\n- Error messages that need full stack traces for debugging\n\n\nCRITICAL: You MUST start your response with the <should_summarize> tag as the very first thing. Do not include any other text before the first tag. The summary tag can contain markdown format, but ensure all XML tags are properly closed.`\n\nfunction buildSummaryUserPrompt(args: {\n command: string\n output: string\n recentConversationContextJson?: string | null\n}): string {\n return `Command executed: \\`${args.command}\\`\n\nRecent conversation context:\n${args.recentConversationContextJson || 'No recent conversation context'}\n\nBash output to analyze:\n${args.output}\n\nShould this output be summarized? If yes, provide a summary focusing on the most relevant information.`\n}\n\nfunction buildBashOutputFilename(command: string): string {\n const timestamp = new Date().toISOString().replace(/[:.]/g, '-')\n const hash = createHash('sha256').update(command).digest('hex').slice(0, 8)\n return `${timestamp}-${hash}.txt`\n}\n\nfunction formatPersistedBashOutput(args: {\n command: string\n stdout: string\n stderr: string\n}): string {\n return `COMMAND: ${args.command}\n\nSTDOUT:\n${args.stdout}\n\nSTDERR:\n${args.stderr}`\n}\n\nfunction persistBashOutput(args: {\n conversationKey: string\n command: string\n stdout: string\n stderr: string\n}): string {\n const dir = path.join(getKodeBaseDir(), OUTPUT_DIR_NAME, args.conversationKey)\n try {\n mkdirSync(dir, { recursive: true })\n } catch {\n return ''\n }\n\n const filename = buildBashOutputFilename(args.command)\n const filePath = path.join(dir, filename)\n\n try {\n writeFileSync(\n filePath,\n formatPersistedBashOutput({\n command: args.command,\n stdout: args.stdout,\n stderr: args.stderr,\n }),\n { encoding: 'utf-8' },\n )\n return filePath\n } catch {\n return ''\n }\n}\n\nfunction wrapSummarizedOutput(summary: string, rawOutputPath: string): string {\n const note = rawOutputPath\n ? `\\n\\nNote: The complete bash output is available at ${rawOutputPath}. You can use Read or Grep tools to search for specific information not included in this summary.`\n : ''\n return `[Summarized output]\n${summary}${note}`\n}\n\nfunction extractTextFromAssistantMessage(message: AssistantMessage): string {\n const content = message.message.content\n if (!Array.isArray(content)) return ''\n return content\n .filter(block => block.type === 'text')\n .map(block => block.text)\n .join('')\n}\n\nexport async function maybeSummarizeBashOutput(args: {\n command: string\n stdout: string\n stderr: string\n outputForAnalysis: string\n conversationKey: string\n signal: AbortSignal\n}): Promise<{ summary: string; rawOutputPath: string } | null> {\n if (process.env.NODE_ENV === 'test') return null\n if (args.outputForAnalysis.length < SUMMARY_THRESHOLD_CHARS) return null\n\n const messages = [\n {\n type: 'user',\n uuid: randomUUID(),\n message: {\n role: 'user',\n content: buildSummaryUserPrompt({\n command: args.command,\n output: args.outputForAnalysis,\n recentConversationContextJson: null,\n }),\n },\n },\n ] as (UserMessage | AssistantMessage)[]\n\n let response: AssistantMessage\n try {\n response = await queryLLM(\n messages,\n [SUMMARY_SYSTEM_PROMPT],\n 0,\n [],\n args.signal,\n {\n safeMode: false,\n model: 'main',\n prependCLISysprompt: false,\n temperature: 0,\n maxTokens: 4096,\n },\n )\n } catch {\n return null\n }\n\n const text = extractTextFromAssistantMessage(response)\n const shouldSummarize = extractTag(text, 'should_summarize')?.trim()\n const summary = extractTag(text, 'summary')?.trim() || ''\n\n if (shouldSummarize !== 'true' || !summary) return null\n\n const rawOutputPath = persistBashOutput({\n conversationKey: args.conversationKey,\n command: args.command,\n stdout: args.stdout,\n stderr: args.stderr,\n })\n\n return {\n summary: wrapSummarizedOutput(summary, rawOutputPath),\n rawOutputPath,\n }\n}\n", "import net from 'node:net'\nimport type { AddressInfo } from 'node:net'\nimport { URL } from 'node:url'\n\ntype NetworkQuery = { host: string; port: number }\n\nfunction parseConnectTarget(value: string): NetworkQuery | null {\n const trimmed = value.trim()\n const firstToken = trimmed.split(/\\s+/)[0]\n const withoutLeadingSlash = firstToken.startsWith('/')\n ? firstToken.slice(1)\n : firstToken\n const authority = withoutLeadingSlash.startsWith('//')\n ? withoutLeadingSlash.slice(2)\n : withoutLeadingSlash\n\n try {\n const url = new URL(`http://${authority}`)\n if (!url.hostname) return null\n const port = Number(url.port) || 443\n return { host: url.hostname, port }\n } catch {\n return null\n }\n}\n\nfunction writeHttpErrorResponse(socket: net.Socket, statusLine: string): void {\n try {\n socket.write(\n `HTTP/1.1 ${statusLine}\\r\\nConnection: close\\r\\nContent-Length: 0\\r\\n\\r\\n`,\n )\n } catch {}\n try {\n socket.destroy()\n } catch {}\n}\n\nexport async function startHttpProxy(args: {\n shouldAllowNetworkRequest: (query: NetworkQuery) => Promise<boolean>\n onServer: (server: net.Server) => void\n}): Promise<number> {\n const server = net.createServer(clientSocket => {\n let buffered: Buffer<ArrayBufferLike> = Buffer.alloc(0)\n\n const onData = (chunk: Buffer<ArrayBufferLike>) => {\n buffered = buffered.length ? Buffer.concat([buffered, chunk]) : chunk\n\n const headerEnd = buffered.indexOf('\\r\\n\\r\\n')\n if (headerEnd === -1) return\n\n const headerText = buffered.slice(0, headerEnd).toString('latin1')\n const remainder = buffered.slice(headerEnd + 4)\n buffered = Buffer.alloc(0)\n clientSocket.off('data', onData)\n\n const lines = headerText.split('\\r\\n')\n const requestLine = lines.shift() ?? ''\n const [methodRaw, targetRaw, versionRaw] = requestLine.split(' ')\n const method = (methodRaw ?? '').trim().toUpperCase()\n const target = (targetRaw ?? '').trim()\n const version = (versionRaw ?? 'HTTP/1.1').trim() || 'HTTP/1.1'\n\n if (!method || !target) {\n writeHttpErrorResponse(clientSocket, '400 Bad Request')\n return\n }\n\n const headers: Record<string, string> = {}\n for (const line of lines) {\n const idx = line.indexOf(':')\n if (idx === -1) continue\n const key = line.slice(0, idx).trim().toLowerCase()\n const value = line.slice(idx + 1).trim()\n if (!key) continue\n headers[key] = value\n }\n\n if (method === 'CONNECT') {\n void (async () => {\n const targetValue = target || headers['host'] || ''\n const parsed = targetValue ? parseConnectTarget(targetValue) : null\n if (!parsed) {\n writeHttpErrorResponse(clientSocket, '400 Bad Request')\n return\n }\n\n const allowed = await args.shouldAllowNetworkRequest({\n host: parsed.host,\n port: parsed.port,\n })\n if (!allowed) {\n writeHttpErrorResponse(clientSocket, '403 Forbidden')\n return\n }\n\n const upstream = net.connect(parsed.port, parsed.host)\n upstream.once('error', () => {\n writeHttpErrorResponse(clientSocket, '502 Bad Gateway')\n })\n\n upstream.once('connect', () => {\n try {\n clientSocket.write('HTTP/1.1 200 Connection Established\\r\\n\\r\\n')\n } catch {\n try {\n upstream.destroy()\n } catch {}\n return\n }\n\n if (remainder.length > 0) {\n try {\n upstream.write(remainder)\n } catch {}\n }\n\n clientSocket.pipe(upstream)\n upstream.pipe(clientSocket)\n })\n })()\n return\n }\n\n void (async () => {\n const hostHeader = headers['host'] ?? ''\n let targetUrl: URL | null = null\n if (target.startsWith('http://') || target.startsWith('https://')) {\n try {\n targetUrl = new URL(target)\n } catch {\n targetUrl = null\n }\n } else if (hostHeader) {\n try {\n targetUrl = new URL(\n `http://${hostHeader}${target.startsWith('/') ? target : '/' + target}`,\n )\n } catch {\n targetUrl = null\n }\n }\n\n if (!targetUrl) {\n writeHttpErrorResponse(clientSocket, '400 Bad Request')\n return\n }\n\n const port =\n targetUrl.port !== ''\n ? Number(targetUrl.port)\n : targetUrl.protocol === 'https:'\n ? 443\n : 80\n\n const allowed = await args.shouldAllowNetworkRequest({\n host: targetUrl.hostname,\n port,\n })\n if (!allowed) {\n writeHttpErrorResponse(clientSocket, '403 Forbidden')\n return\n }\n\n if (targetUrl.protocol === 'https:') {\n // Non-CONNECT HTTPS proxy requests are not supported; clients should use CONNECT.\n writeHttpErrorResponse(clientSocket, '400 Bad Request')\n return\n }\n\n delete headers['proxy-connection']\n delete headers['proxy-authorization']\n headers['connection'] = 'close'\n headers['host'] = targetUrl.host\n\n const upstream = net.connect(port, targetUrl.hostname)\n upstream.once('error', () => {\n writeHttpErrorResponse(clientSocket, '502 Bad Gateway')\n })\n\n upstream.once('connect', () => {\n const path = `${targetUrl.pathname}${targetUrl.search}`\n try {\n upstream.write(`${method} ${path} ${version}\\r\\n`)\n for (const [k, v] of Object.entries(headers)) {\n upstream.write(`${k}: ${v}\\r\\n`)\n }\n upstream.write('\\r\\n')\n } catch {\n writeHttpErrorResponse(clientSocket, '502 Bad Gateway')\n try {\n upstream.destroy()\n } catch {}\n return\n }\n\n if (remainder.length > 0) {\n try {\n upstream.write(remainder)\n } catch {}\n }\n\n clientSocket.pipe(upstream)\n upstream.pipe(clientSocket)\n upstream.once('end', () => {\n try {\n clientSocket.end()\n } catch {}\n })\n })\n })()\n }\n\n clientSocket.on('data', onData)\n })\n\n args.onServer(server)\n\n return new Promise<number>((resolve, reject) => {\n server.once('error', reject)\n server.once('listening', () => {\n const addr = server.address()\n if (!addr || typeof addr === 'string') {\n reject(new Error('Failed to get HTTP proxy address'))\n return\n }\n server.unref()\n resolve((addr as AddressInfo).port)\n })\n server.listen(0, '127.0.0.1')\n })\n}\n", "import net from 'node:net'\nimport type { AddressInfo } from 'node:net'\n\ntype NetworkQuery = { host: string; port: number }\n\nfunction buildSocks5Reply(rep: number): Buffer {\n // VER, REP, RSV, ATYP, BND.ADDR, BND.PORT (0.0.0.0:0)\n return Buffer.from([0x05, rep, 0x00, 0x01, 0, 0, 0, 0, 0, 0])\n}\n\nfunction parseSocks5Request(\n buffer: Buffer,\n): { host: string; port: number; remaining: Buffer } | null {\n if (buffer.length < 4) return null\n if (buffer[0] !== 0x05) return null\n const cmd = buffer[1]\n const atyp = buffer[3]\n if (cmd !== 0x01) return null\n\n let offset = 4\n let host = ''\n\n if (atyp === 0x01) {\n if (buffer.length < offset + 4 + 2) return null\n host = `${buffer[offset]}.${buffer[offset + 1]}.${buffer[offset + 2]}.${buffer[offset + 3]}`\n offset += 4\n } else if (atyp === 0x03) {\n if (buffer.length < offset + 1) return null\n const len = buffer[offset]\n offset += 1\n if (buffer.length < offset + len + 2) return null\n host = buffer.slice(offset, offset + len).toString('utf8')\n offset += len\n } else if (atyp === 0x04) {\n if (buffer.length < offset + 16 + 2) return null\n const parts: string[] = []\n for (let i = 0; i < 16; i += 2) {\n parts.push(buffer.readUInt16BE(offset + i).toString(16))\n }\n host = parts.join(':')\n offset += 16\n } else {\n return null\n }\n\n const port = buffer.readUInt16BE(offset)\n offset += 2\n return { host, port, remaining: buffer.slice(offset) }\n}\n\nexport async function startSocks5Proxy(args: {\n shouldAllowNetworkRequest: (query: NetworkQuery) => Promise<boolean>\n onServer: (server: net.Server) => void\n}): Promise<number> {\n const server = net.createServer(socket => {\n let buffered: Buffer<ArrayBufferLike> = Buffer.alloc(0)\n let stage: 'greeting' | 'request' = 'greeting'\n\n const onData = (chunk: Buffer<ArrayBufferLike>) => {\n buffered = buffered.length ? Buffer.concat([buffered, chunk]) : chunk\n\n if (stage === 'greeting') {\n if (buffered.length < 2) return\n if (buffered[0] !== 0x05) {\n socket.end()\n return\n }\n\n const nMethods = buffered[1]\n if (buffered.length < 2 + nMethods) return\n const methods = buffered.slice(2, 2 + nMethods)\n const supportsNoAuth = methods.includes(0x00)\n socket.write(Buffer.from([0x05, supportsNoAuth ? 0x00 : 0xff]))\n buffered = buffered.slice(2 + nMethods)\n if (!supportsNoAuth) {\n socket.end()\n return\n }\n stage = 'request'\n }\n\n if (stage === 'request') {\n const parsed = parseSocks5Request(buffered)\n if (!parsed) return\n buffered = parsed.remaining\n\n void (async () => {\n const allowed = await args.shouldAllowNetworkRequest({\n host: parsed.host,\n port: parsed.port,\n })\n if (!allowed) {\n socket.write(buildSocks5Reply(0x02))\n socket.end()\n return\n }\n\n const upstream = net.connect(parsed.port, parsed.host)\n upstream.once('error', () => {\n try {\n socket.write(buildSocks5Reply(0x05))\n } catch {}\n socket.end()\n })\n upstream.once('connect', () => {\n try {\n socket.write(buildSocks5Reply(0x00))\n } catch {\n try {\n upstream.destroy()\n } catch {}\n socket.end()\n return\n }\n socket.pipe(upstream)\n upstream.pipe(socket)\n })\n })()\n }\n }\n\n socket.on('data', onData)\n })\n\n args.onServer(server)\n\n return new Promise<number>((resolve, reject) => {\n server.once('error', reject)\n server.once('listening', () => {\n const addr = server.address()\n if (!addr || typeof addr === 'string') {\n reject(new Error('Failed to get SOCKS proxy address'))\n return\n }\n server.unref()\n resolve((addr as AddressInfo).port)\n })\n server.listen(0, '127.0.0.1')\n })\n}\n", "import { spawn } from 'node:child_process'\nimport { randomBytes } from 'node:crypto'\nimport { existsSync, rmSync } from 'node:fs'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\nimport type { ChildProcess } from 'node:child_process'\n\nexport type LinuxSandboxBridge = {\n httpSocketPath: string\n socksSocketPath: string\n}\n\nexport type LinuxSandboxBridgeState = LinuxSandboxBridge & {\n httpBridgeProcess: ChildProcess\n socksBridgeProcess: ChildProcess\n}\n\nfunction safeUnlink(path: string): void {\n try {\n rmSync(path, { force: true })\n } catch {\n // ignore\n }\n}\n\nfunction safeKill(\n proc: ChildProcess,\n signal: NodeJS.Signals = 'SIGTERM',\n): void {\n try {\n if (proc.pid) process.kill(proc.pid, signal)\n } catch {\n // ignore\n }\n}\n\nexport async function startLinuxSandboxBridge(args: {\n hostHttpProxyPort: number\n hostSocksProxyPort: number\n}): Promise<LinuxSandboxBridgeState> {\n const suffix = randomBytes(8).toString('hex')\n const base = tmpdir()\n const httpSocketPath = join(base, `kode-http-${suffix}.sock`)\n const socksSocketPath = join(base, `kode-socks-${suffix}.sock`)\n\n safeUnlink(httpSocketPath)\n safeUnlink(socksSocketPath)\n\n const httpArgs = [\n `UNIX-LISTEN:${httpSocketPath},fork,reuseaddr`,\n `TCP:localhost:${args.hostHttpProxyPort},keepalive,keepidle=10,keepintvl=5,keepcnt=3`,\n ]\n const httpBridgeProcess = spawn('socat', httpArgs, { stdio: 'ignore' })\n if (!httpBridgeProcess.pid) {\n throw new Error('Failed to start Linux HTTP bridge process (socat)')\n }\n\n const socksArgs = [\n `UNIX-LISTEN:${socksSocketPath},fork,reuseaddr`,\n `TCP:localhost:${args.hostSocksProxyPort},keepalive,keepidle=10,keepintvl=5,keepcnt=3`,\n ]\n const socksBridgeProcess = spawn('socat', socksArgs, { stdio: 'ignore' })\n if (!socksBridgeProcess.pid) {\n safeKill(httpBridgeProcess)\n throw new Error('Failed to start Linux SOCKS bridge process (socat)')\n }\n\n const attempts = 5\n for (let i = 0; i < attempts; i++) {\n if (!httpBridgeProcess.pid || httpBridgeProcess.killed) break\n if (!socksBridgeProcess.pid || socksBridgeProcess.killed) break\n\n if (existsSync(httpSocketPath) && existsSync(socksSocketPath)) {\n return {\n httpSocketPath,\n socksSocketPath,\n httpBridgeProcess,\n socksBridgeProcess,\n }\n }\n\n await new Promise(resolve => setTimeout(resolve, i * 100))\n }\n\n safeKill(httpBridgeProcess)\n safeKill(socksBridgeProcess)\n safeUnlink(httpSocketPath)\n safeUnlink(socksSocketPath)\n throw new Error('Failed to create Linux sandbox bridge sockets (socat)')\n}\n\nexport function stopLinuxSandboxBridge(state: LinuxSandboxBridgeState): void {\n safeKill(state.httpBridgeProcess)\n safeKill(state.socksBridgeProcess)\n safeUnlink(state.httpSocketPath)\n safeUnlink(state.socksSocketPath)\n}\n", "import net from 'node:net'\nimport { logError } from '#core/utils/log'\nimport type { SandboxRuntimeConfig } from './sandboxConfig'\nimport { startHttpProxy } from './sandboxNetworkInfrastructure/httpProxy'\nimport { startSocks5Proxy } from './sandboxNetworkInfrastructure/socks5Proxy'\nimport {\n startLinuxSandboxBridge,\n stopLinuxSandboxBridge,\n type LinuxSandboxBridge,\n type LinuxSandboxBridgeState,\n} from './sandboxNetworkInfrastructure/linuxBridge'\n\nexport type SandboxNetworkPermissionQuery = { host: string; port: number }\nexport type SandboxNetworkPermissionCallback = (\n query: SandboxNetworkPermissionQuery,\n) => Promise<boolean>\n\nexport type SandboxNetworkInfrastructurePorts = {\n httpProxyPort: number\n socksProxyPort: number\n linuxBridge?: LinuxSandboxBridge\n}\n\ntype ActiveState = {\n config: SandboxRuntimeConfig | null\n permissionCallback: SandboxNetworkPermissionCallback | null\n httpProxyServer: net.Server | null\n socksProxyServer: net.Server | null\n httpProxyPort: number | null\n socksProxyPort: number | null\n linuxBridge: LinuxSandboxBridgeState | null\n initializationPromise: Promise<SandboxNetworkInfrastructurePorts> | null\n cleanupRegistered: boolean\n sessionAllowedHosts: Set<string>\n sessionDeniedHosts: Set<string>\n inflightPermissionRequests: Map<string, Promise<boolean>>\n permissionPromptChain: Promise<void>\n}\n\nconst active: ActiveState = {\n config: null,\n permissionCallback: null,\n httpProxyServer: null,\n socksProxyServer: null,\n httpProxyPort: null,\n socksProxyPort: null,\n linuxBridge: null,\n initializationPromise: null,\n cleanupRegistered: false,\n sessionAllowedHosts: new Set(),\n sessionDeniedHosts: new Set(),\n inflightPermissionRequests: new Map(),\n permissionPromptChain: Promise.resolve(),\n}\n\n// Compatibility: host/pattern matching supports \"*.domain\" and exact matches (case-insensitive).\nexport function matchesSandboxDomainPattern(\n host: string,\n pattern: string,\n): boolean {\n if (pattern.startsWith('*.')) {\n const suffix = pattern.substring(2)\n return host.toLowerCase().endsWith('.' + suffix.toLowerCase())\n }\n return host.toLowerCase() === pattern.toLowerCase()\n}\n\nasync function shouldAllowNetworkRequest(\n query: SandboxNetworkPermissionQuery,\n): Promise<boolean> {\n const config = active.config\n if (!config) return false\n\n const hostKey = query.host.toLowerCase()\n if (active.sessionAllowedHosts.has(hostKey)) return true\n if (active.sessionDeniedHosts.has(hostKey)) return false\n\n for (const denied of config.network.deniedDomains) {\n if (matchesSandboxDomainPattern(query.host, denied)) return false\n }\n for (const allowed of config.network.allowedDomains) {\n if (matchesSandboxDomainPattern(query.host, allowed)) return true\n }\n\n const permissionCallback = active.permissionCallback\n if (!permissionCallback) return false\n\n const existing = active.inflightPermissionRequests.get(hostKey)\n if (existing) return existing\n\n const requestPromise = (async () => {\n const decision = await serializePermissionPrompt(async () => {\n try {\n return await permissionCallback(query)\n } catch (error) {\n logError(error)\n return false\n }\n })\n\n if (decision) active.sessionAllowedHosts.add(hostKey)\n else active.sessionDeniedHosts.add(hostKey)\n\n return decision\n })().finally(() => {\n active.inflightPermissionRequests.delete(hostKey)\n })\n\n active.inflightPermissionRequests.set(hostKey, requestPromise)\n return requestPromise\n}\n\nasync function serializePermissionPrompt<T>(\n task: () => Promise<T>,\n): Promise<T> {\n let release: (() => void) | null = null\n const next = new Promise<void>(resolve => {\n release = resolve\n })\n const prev = active.permissionPromptChain\n active.permissionPromptChain = prev.then(() => next)\n\n try {\n await prev\n return await task()\n } finally {\n release?.()\n }\n}\n\nfunction registerCleanupOnce(): void {\n if (active.cleanupRegistered) return\n active.cleanupRegistered = true\n\n const cleanup = () => {\n void cleanupSandboxNetworkInfrastructure()\n }\n\n process.once('exit', cleanup)\n process.once('SIGINT', cleanup)\n process.once('SIGTERM', cleanup)\n}\n\nasync function cleanupSandboxNetworkInfrastructure(): Promise<void> {\n const httpServer = active.httpProxyServer\n const socksServer = active.socksProxyServer\n const linuxBridge = active.linuxBridge\n active.httpProxyServer = null\n active.socksProxyServer = null\n active.httpProxyPort = null\n active.socksProxyPort = null\n active.linuxBridge = null\n active.initializationPromise = null\n\n active.sessionAllowedHosts.clear()\n active.sessionDeniedHosts.clear()\n active.inflightPermissionRequests.clear()\n\n if (linuxBridge) {\n try {\n stopLinuxSandboxBridge(linuxBridge)\n } catch (error) {\n logError(error)\n }\n }\n\n await Promise.allSettled([\n httpServer\n ? new Promise<void>(resolve => {\n try {\n httpServer.close(() => resolve())\n } catch {\n resolve()\n }\n })\n : Promise.resolve(),\n socksServer\n ? new Promise<void>(resolve => {\n try {\n socksServer.close(() => resolve())\n } catch {\n resolve()\n }\n })\n : Promise.resolve(),\n ])\n}\n\nexport async function ensureSandboxNetworkInfrastructure(options: {\n runtimeConfig: SandboxRuntimeConfig\n permissionCallback?: SandboxNetworkPermissionCallback | null\n platform?: NodeJS.Platform\n}): Promise<SandboxNetworkInfrastructurePorts> {\n active.config = options.runtimeConfig\n active.permissionCallback = options.permissionCallback ?? null\n\n if (active.initializationPromise) return active.initializationPromise\n\n registerCleanupOnce()\n\n active.initializationPromise = (async () => {\n const platform = options.platform ?? process.platform\n\n const httpProxyPort =\n options.runtimeConfig.network.httpProxyPort !== undefined\n ? options.runtimeConfig.network.httpProxyPort\n : await startHttpProxy({\n shouldAllowNetworkRequest,\n onServer: server => {\n active.httpProxyServer = server\n },\n })\n\n const socksProxyPort =\n options.runtimeConfig.network.socksProxyPort !== undefined\n ? options.runtimeConfig.network.socksProxyPort\n : await startSocks5Proxy({\n shouldAllowNetworkRequest,\n onServer: server => {\n active.socksProxyServer = server\n },\n })\n\n active.httpProxyPort = httpProxyPort\n active.socksProxyPort = socksProxyPort\n\n let linuxBridge: LinuxSandboxBridge | undefined\n if (platform === 'linux') {\n const bridge = await startLinuxSandboxBridge({\n hostHttpProxyPort: httpProxyPort,\n hostSocksProxyPort: socksProxyPort,\n })\n active.linuxBridge = bridge\n linuxBridge = {\n httpSocketPath: bridge.httpSocketPath,\n socksSocketPath: bridge.socksSocketPath,\n }\n }\n\n return { httpProxyPort, socksProxyPort, linuxBridge }\n })().catch(async error => {\n active.initializationPromise = null\n await cleanupSandboxNetworkInfrastructure()\n throw error\n })\n\n return active.initializationPromise\n}\n\nexport function getSandboxNetworkInfrastructurePorts(): SandboxNetworkInfrastructurePorts | null {\n if (active.httpProxyPort === null || active.socksProxyPort === null)\n return null\n const ports: SandboxNetworkInfrastructurePorts = {\n httpProxyPort: active.httpProxyPort,\n socksProxyPort: active.socksProxyPort,\n }\n if (active.linuxBridge) {\n ports.linuxBridge = {\n httpSocketPath: active.linuxBridge.httpSocketPath,\n socksSocketPath: active.linuxBridge.socksSocketPath,\n }\n }\n return ports\n}\n\nexport async function __resetSandboxNetworkInfrastructureForTests(): Promise<void> {\n await cleanupSandboxNetworkInfrastructure()\n active.permissionCallback = null\n active.config = null\n active.permissionPromptChain = Promise.resolve()\n}\n", "import { Box, Text } from 'ink'\nimport React from 'react'\nimport { z } from 'zod'\nimport { Tool, ToolUseContext } from '#core/tooling/Tool'\nimport type { AssistantMessage, UserMessage } from '#core/query'\nimport { queryLLM } from '#core/ai/llmLazy'\nimport { randomUUID } from 'crypto'\nimport { isIP } from 'node:net'\nimport { PROMPT, TOOL_NAME_FOR_PROMPT } from './prompt'\nimport { convertHtmlToMarkdown } from './htmlToMarkdown'\nimport { urlCache } from './cache'\nimport {\n buildWebFetchApplyPrompt,\n createTimeoutSignal,\n extractTextFromMessageContent,\n fetchWithRedirectDetection,\n formatBytes,\n isMarkdownHost,\n normalizeUrl,\n readResponseTextLimited,\n truncateFetchedContent,\n} from './utils'\n\nconst inputSchema = z.object({\n url: z.string().describe('The URL to fetch content from'),\n prompt: z.string().describe('The prompt to run on the fetched content'),\n})\n\ntype Input = z.infer<typeof inputSchema>\ntype Output = {\n bytes: number\n code: number\n codeText: string\n result: string\n durationMs: number\n url: string\n}\n\nconst FETCH_TIMEOUT_MS = 30_000\nconst MAX_URL_LENGTH = 2000\nconst MAX_RESPONSE_BYTES = 10 * 1024 * 1024 // 10485760\n\nfunction isPrivateIpv4(hostname: string): boolean {\n if (isIP(hostname) !== 4) return false\n const parts = hostname.split('.').map(Number)\n if (parts.length !== 4) return false\n if (parts.some(part => !Number.isInteger(part) || part < 0 || part > 255)) {\n return false\n }\n const [a, b] = parts\n if (a === 0) return true\n if (a === 10) return true\n if (a === 127) return true\n if (a === 169 && b === 254) return true\n if (a === 172 && b >= 16 && b <= 31) return true\n if (a === 192 && b === 168) return true\n if (a === 100 && b >= 64 && b <= 127) return true\n return false\n}\n\nfunction isValidWebFetchUrl(url: string): boolean {\n if (url.length > MAX_URL_LENGTH) return false\n let parsed: URL\n try {\n parsed = new URL(url)\n } catch {\n return false\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false\n if (parsed.username || parsed.password) return false\n if (isPrivateIpv4(parsed.hostname)) return false\n if (parsed.hostname.split('.').length < 2) return false\n return true\n}\n\nexport const WebFetchTool = {\n name: TOOL_NAME_FOR_PROMPT,\n async description(input?: Input) {\n const url = input?.url\n try {\n return `The assistant wants to fetch content from ${new URL(url || '').hostname}`\n } catch {\n return 'The assistant wants to fetch content from this URL'\n }\n },\n userFacingName: () => 'Fetch',\n inputSchema,\n isReadOnly: () => true,\n isConcurrencySafe: () => true,\n async isEnabled() {\n return true\n },\n needsPermissions() {\n return true\n },\n async prompt() {\n return PROMPT\n },\n async validateInput({ url }: Input) {\n try {\n new URL(url)\n } catch {\n return {\n result: false,\n message: `Error: Invalid URL \"${url}\". The URL provided could not be parsed.`,\n meta: { reason: 'invalid_url' },\n errorCode: 1,\n }\n }\n return { result: true }\n },\n renderToolUseMessage(\n { url, prompt }: Input,\n { verbose }: { verbose: boolean },\n ) {\n if (verbose) {\n return `url: \"${url}\"${prompt ? `, prompt: \"${prompt}\"` : ''}`\n }\n return url\n },\n renderToolResultMessage(output: Output) {\n return (\n <Box flexDirection=\"row\">\n <Text> \u23BF Received </Text>\n <Text bold>{formatBytes(output.bytes)} </Text>\n <Text>\n ({output.code} {output.codeText})\n </Text>\n </Box>\n )\n },\n renderResultForAssistant(output: Output) {\n return output.result\n },\n async *call({ url, prompt }: Input, context: ToolUseContext) {\n const normalizedUrl = normalizeUrl(url)\n const start = Date.now()\n\n const timeoutSignal = createTimeoutSignal(\n context.abortController.signal,\n FETCH_TIMEOUT_MS,\n )\n\n try {\n if (!isValidWebFetchUrl(normalizedUrl)) {\n throw new Error('Invalid URL')\n }\n\n const cached = urlCache.get(normalizedUrl)\n\n const fetched = cached\n ? null\n : await fetchWithRedirectDetection(normalizedUrl, timeoutSignal.signal)\n\n if (fetched && fetched.type === 'redirect') {\n const codeText =\n fetched.statusCode === 301\n ? 'Moved Permanently'\n : fetched.statusCode === 308\n ? 'Permanent Redirect'\n : fetched.statusCode === 307\n ? 'Temporary Redirect'\n : 'Found'\n\n const result = `REDIRECT DETECTED: The URL redirects to a different host.\n\nOriginal URL: ${fetched.originalUrl}\nRedirect URL: ${fetched.redirectUrl}\nStatus: ${fetched.statusCode} ${codeText}\n\nTo complete your request, I need to fetch content from the redirected URL. Please use WebFetch again with these parameters:\n- url: \"${fetched.redirectUrl}\"\n- prompt: \"${prompt}\"`\n\n const output: Output = {\n bytes: Buffer.byteLength(result, 'utf8'),\n code: fetched.statusCode,\n codeText,\n result,\n durationMs: Date.now() - start,\n url: normalizedUrl,\n }\n yield {\n type: 'result' as const,\n resultForAssistant: this.renderResultForAssistant(output),\n data: output,\n }\n return\n }\n\n let bytes = cached ? cached.bytes : 0\n let code = cached ? cached.code : 200\n let codeText = cached ? cached.codeText : 'OK'\n let markdown = cached ? cached.content : ''\n let contentType = cached ? cached.contentType : ''\n\n if (fetched && fetched.type === 'response') {\n const response = fetched.response\n\n code = response.status\n codeText = response.statusText || 'OK'\n\n contentType = response.headers.get('content-type') || ''\n\n const { text: raw, bytes: responseBytes } =\n await readResponseTextLimited(response, MAX_RESPONSE_BYTES)\n bytes = responseBytes\n\n const converted = contentType.toLowerCase().includes('text/html')\n ? convertHtmlToMarkdown(raw)\n : raw\n markdown = truncateFetchedContent(converted)\n urlCache.set(normalizedUrl, {\n bytes,\n code,\n codeText,\n content: markdown,\n contentType,\n })\n }\n\n const allowBroaderQuoting = isMarkdownHost(normalizedUrl, contentType)\n const userPrompt = buildWebFetchApplyPrompt(\n markdown,\n prompt,\n allowBroaderQuoting,\n )\n const messages = [\n {\n type: 'user',\n uuid: randomUUID(),\n message: { role: 'user', content: userPrompt },\n },\n ] as (UserMessage | AssistantMessage)[]\n\n const aiResponse = await queryLLM(\n messages,\n [],\n 0,\n [],\n timeoutSignal.signal,\n {\n safeMode: false,\n model: 'main',\n prependCLISysprompt: false,\n temperature: 0,\n maxTokens: 2048,\n },\n )\n\n const extracted = extractTextFromMessageContent(\n aiResponse.message.content as unknown,\n )\n const result = extracted ?? 'No response from model'\n\n const output: Output = {\n bytes,\n code,\n codeText,\n result,\n durationMs: Date.now() - start,\n url: normalizedUrl,\n }\n\n yield {\n type: 'result' as const,\n resultForAssistant: this.renderResultForAssistant(output),\n data: output,\n }\n } finally {\n timeoutSignal.cleanup()\n }\n },\n} satisfies Tool<typeof inputSchema, Output>\n", "export const TOOL_NAME_FOR_PROMPT = 'WebFetch'\nexport const PROMPT = `\n- Fetches content from a specified URL and processes it using an AI model\n- Takes a URL and a prompt as input\n- Fetches the URL content, converts HTML to markdown\n- Processes the content with the prompt using a small, fast model\n- Returns the model's response about the content\n- Use this tool when you need to retrieve and analyze web content\n\nUsage notes:\n - IMPORTANT: If an MCP-provided web fetch tool is available, prefer using that tool instead of this one, as it may have fewer restrictions.\n - The URL must be a fully-formed valid URL\n - HTTP URLs will be automatically upgraded to HTTPS\n - The prompt should describe what information you want to extract from the page\n - This tool is read-only and does not modify any files\n - Results may be summarized if the content is very large\n - Includes a self-cleaning 15-minute cache for faster responses when repeatedly accessing the same URL\n - When a URL redirects to a different host, the tool will inform you and provide the redirect URL in a special format. You should then make a new WebFetch request with the redirect URL to fetch the content.\n`.trim()\n", "import TurndownService from 'turndown'\n\nconst turndownService = new TurndownService({\n headingStyle: 'atx',\n hr: '---',\n bulletListMarker: '-',\n codeBlockStyle: 'fenced',\n fence: '```',\n emDelimiter: '_',\n strongDelimiter: '**',\n})\n\n// Configure rules to handle common HTML elements\nturndownService.addRule('removeScripts', {\n filter: ['script', 'style', 'noscript'],\n replacement: () => '',\n})\n\nturndownService.addRule('removeComments', {\n filter: node => node.nodeType === 8, // Comment nodes\n replacement: () => '',\n})\n\nturndownService.addRule('cleanLinks', {\n filter: 'a',\n replacement: (content, node) => {\n const href = node.getAttribute('href')\n if (!href || href.startsWith('javascript:') || href.startsWith('#')) {\n return content\n }\n return `[${content}](${href})`\n },\n})\n\nexport function convertHtmlToMarkdown(html: string): string {\n try {\n // Clean up the HTML before conversion\n const cleanHtml = html\n .replace(/<script[^>]*>[\\s\\S]*?<\\/script>/gi, '') // Remove script tags\n .replace(/<style[^>]*>[\\s\\S]*?<\\/style>/gi, '') // Remove style tags\n .replace(/<!--[\\s\\S]*?-->/g, '') // Remove HTML comments\n .replace(/\\s+/g, ' ') // Normalize whitespace\n .trim()\n\n const markdown = turndownService.turndown(cleanHtml)\n\n // Clean up the resulting markdown\n return markdown\n .replace(/\\n{3,}/g, '\\n\\n') // Remove excessive line breaks\n .replace(/^\\s+|\\s+$/gm, '') // Remove leading/trailing spaces on each line\n .trim()\n } catch (error) {\n throw new Error(\n `Failed to convert HTML to markdown: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n}\n", "interface CacheEntry {\n bytes: number\n code: number\n codeText: string\n content: string\n contentType: string\n timestamp: number\n}\n\nclass URLCache {\n private cache = new Map<string, CacheEntry>()\n private readonly CACHE_DURATION = 15 * 60 * 1000 // 15 minutes in milliseconds\n\n set(url: string, entry: Omit<CacheEntry, 'timestamp'>): void {\n this.cache.set(url, {\n ...entry,\n timestamp: Date.now(),\n })\n }\n\n get(url: string): CacheEntry | null {\n const entry = this.cache.get(url)\n if (!entry) {\n return null\n }\n\n // Check if entry has expired\n if (Date.now() - entry.timestamp > this.CACHE_DURATION) {\n this.cache.delete(url)\n return null\n }\n\n return entry\n }\n\n clear(): void {\n this.cache.clear()\n }\n\n // Clean expired entries\n private cleanExpired(): void {\n const now = Date.now()\n for (const [url, entry] of this.cache.entries()) {\n if (now - entry.timestamp > this.CACHE_DURATION) {\n this.cache.delete(url)\n }\n }\n }\n\n // Auto-clean expired entries every 5 minutes\n constructor() {\n setInterval(\n () => {\n this.cleanExpired()\n },\n 5 * 60 * 1000,\n ) // 5 minutes\n }\n}\n\n// Export singleton instance\nexport const urlCache = new URLCache()\n", "const MAX_CONTENT_CHARS = 100_000\n\ntype TextContentBlock = { type: 'text'; text: string }\n\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n if (!value || typeof value !== 'object') return null\n return value as Record<string, unknown>\n}\n\nfunction isTextContentBlock(block: unknown): block is TextContentBlock {\n const record = asRecord(block)\n if (!record) return false\n return record.type === 'text' && typeof record.text === 'string'\n}\n\nexport function extractTextFromMessageContent(content: unknown): string | null {\n if (typeof content === 'string') return content\n if (!Array.isArray(content)) return null\n const textBlock = content.find(isTextContentBlock)\n return textBlock ? textBlock.text : null\n}\n\nexport function formatBytes(bytes: number): string {\n if (!Number.isFinite(bytes)) return `${bytes}B`\n if (bytes < 1024) return `${Math.max(0, Math.round(bytes))}B`\n const units = ['KB', 'MB', 'GB', 'TB'] as const\n let value = bytes / 1024\n let unitIndex = 0\n while (value >= 1024 && unitIndex < units.length - 1) {\n value /= 1024\n unitIndex++\n }\n const rounded = Math.round(value * 10) / 10\n return `${rounded}${units[unitIndex]}`\n}\n\nexport function normalizeUrl(url: string): string {\n if (url.startsWith('http://')) {\n return url.replace('http://', 'https://')\n }\n return url\n}\n\nfunction normalizeHostname(hostname: string): string {\n return hostname.replace(/^www\\./i, '').toLowerCase()\n}\n\nfunction isSameHost(originalUrl: string, redirectUrl: string): boolean {\n try {\n const original = new URL(originalUrl)\n const redirect = new URL(redirectUrl)\n if (redirect.protocol !== original.protocol) return false\n if (redirect.port !== original.port) return false\n if (redirect.username || redirect.password) return false\n return (\n normalizeHostname(original.hostname) ===\n normalizeHostname(redirect.hostname)\n )\n } catch {\n return false\n }\n}\n\nexport function createTimeoutSignal(\n parent: AbortSignal,\n timeoutMs: number,\n): {\n signal: AbortSignal\n cleanup: () => void\n} {\n const controller = new AbortController()\n const onAbort = () => controller.abort()\n if (parent.aborted) {\n controller.abort()\n } else {\n parent.addEventListener('abort', onAbort, { once: true })\n }\n const timeout = setTimeout(() => controller.abort(), timeoutMs)\n return {\n signal: controller.signal,\n cleanup: () => {\n clearTimeout(timeout)\n parent.removeEventListener('abort', onAbort)\n },\n }\n}\n\nexport async function readResponseTextLimited(\n response: Response,\n maxBytes: number,\n): Promise<{ text: string; bytes: number }> {\n if (!response.body) return { text: '', bytes: 0 }\n const reader = response.body.getReader()\n const chunks: Uint8Array[] = []\n let bytes = 0\n try {\n while (true) {\n const { value, done } = await reader.read()\n if (done) break\n if (!value) continue\n bytes += value.byteLength\n if (bytes > maxBytes) {\n try {\n await reader.cancel()\n } catch {\n // ignore\n }\n throw new Error(\n `Response exceeded maximum allowed size (${maxBytes} bytes)`,\n )\n }\n chunks.push(value)\n }\n } finally {\n try {\n reader.releaseLock()\n } catch {\n // ignore\n }\n }\n\n const buffer = Buffer.concat(chunks.map(chunk => Buffer.from(chunk)))\n return { text: buffer.toString('utf-8'), bytes }\n}\n\nexport function truncateFetchedContent(content: string): string {\n if (content.length <= MAX_CONTENT_CHARS) return content\n return `${content.substring(0, MAX_CONTENT_CHARS)}...[content truncated]`\n}\n\nexport function isMarkdownHost(url: string, contentType: string): boolean {\n const lowerContentType = contentType.toLowerCase()\n if (lowerContentType.includes('text/markdown')) return true\n try {\n const parsed = new URL(url)\n const host = parsed.hostname.toLowerCase()\n if (\n host === 'raw.githubusercontent.com' ||\n host === 'gist.githubusercontent.com' ||\n host === 'modelcontextprotocol.io' ||\n host === 'github.com'\n ) {\n return true\n }\n const pathname = parsed.pathname.toLowerCase()\n return pathname.endsWith('.md') || pathname.endsWith('.markdown')\n } catch {\n return false\n }\n}\n\nexport function buildWebFetchApplyPrompt(\n content: string,\n prompt: string,\n allowBroaderQuoting: boolean,\n): string {\n return `\nWeb page content:\n---\n${content}\n---\n\n${prompt}\n\n${\n allowBroaderQuoting\n ? 'Provide a concise response based on the content above. Include relevant details, code examples, and documentation excerpts as needed.'\n : `Provide a concise response based only on the content above. In your response:\n - Enforce a strict 125-character maximum for quotes from any source document. Open Source Software is ok as long as we respect the license.\n - Use quotation marks for exact language from articles; any language outside of the quotation should never be word-for-word the same.\n - You are not a lawyer and never comment on the legality of your own prompts and responses.\n - Never produce or reproduce exact song lyrics.`\n}\n`\n}\n\nfunction getChromeLikeHeaders(): Record<string, string> {\n const platformHint =\n process.platform === 'darwin'\n ? 'macOS'\n : process.platform === 'win32'\n ? 'Windows'\n : 'Linux'\n const userAgent =\n process.platform === 'darwin'\n ? 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36'\n : process.platform === 'win32'\n ? 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36'\n : 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36'\n\n return {\n 'User-Agent': userAgent,\n Accept:\n 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8',\n 'Accept-Language': 'en-US,en;q=0.9',\n 'Cache-Control': 'no-cache',\n Pragma: 'no-cache',\n 'Upgrade-Insecure-Requests': '1',\n 'Sec-Fetch-Dest': 'document',\n 'Sec-Fetch-Mode': 'navigate',\n 'Sec-Fetch-Site': 'none',\n 'Sec-Fetch-User': '?1',\n 'sec-ch-ua':\n '\"Chromium\";v=\"121\", \"Not A(Brand\";v=\"99\", \"Google Chrome\";v=\"121\"',\n 'sec-ch-ua-mobile': '?0',\n 'sec-ch-ua-platform': `\"${platformHint}\"`,\n }\n}\n\nexport async function fetchWithRedirectDetection(\n url: string,\n signal: AbortSignal,\n): Promise<\n | {\n type: 'redirect'\n originalUrl: string\n redirectUrl: string\n statusCode: number\n }\n | { type: 'response'; response: Response; finalUrl: string }\n> {\n let current = url\n const headers = getChromeLikeHeaders()\n for (let i = 0; i < 10; i++) {\n const response = await fetch(current, {\n method: 'GET',\n headers,\n signal,\n redirect: 'manual',\n })\n\n if ([301, 302, 307, 308].includes(response.status)) {\n const location = response.headers.get('location')\n if (!location) {\n return { type: 'response', response, finalUrl: current }\n }\n const redirectUrl = new URL(location, current).toString()\n if (isSameHost(current, redirectUrl)) {\n current = redirectUrl\n continue\n }\n return {\n type: 'redirect',\n originalUrl: url,\n redirectUrl,\n statusCode: response.status,\n }\n }\n\n return { type: 'response', response, finalUrl: current }\n }\n\n const response = await fetch(current, {\n method: 'GET',\n headers,\n signal,\n redirect: 'manual',\n })\n return { type: 'response', response, finalUrl: current }\n}\n", "import type { ToolUseContext } from '#core/tooling/Tool'\nimport type { BunShellSandboxPlan } from '#core/utils/sandbox/bunShellSandboxPlan'\nimport { ensureSandboxNetworkInfrastructure } from '#core/utils/sandbox/sandboxNetworkInfrastructure'\nimport type { BunShellSandboxOptions } from '#runtime/shell'\nimport { WebFetchTool } from '#tools/tools/network/WebFetchTool/WebFetchTool'\n\nexport async function maybeAttachSandboxNetworkPorts(args: {\n sandboxPlan: BunShellSandboxPlan\n sandboxOptions: BunShellSandboxOptions | undefined\n context: ToolUseContext\n}): Promise<BunShellSandboxOptions | undefined> {\n const { sandboxPlan, sandboxOptions, context } = args\n if (!sandboxPlan.willSandbox) return sandboxOptions\n if (!sandboxOptions || sandboxOptions.enabled !== true) return sandboxOptions\n\n const platform = sandboxOptions.__platformOverride ?? process.platform\n if (platform !== 'darwin' && platform !== 'linux') return sandboxOptions\n\n const needsRestriction =\n sandboxOptions.needsNetworkRestriction !== undefined\n ? sandboxOptions.needsNetworkRestriction === true\n : sandboxOptions.allowNetwork === true\n ? false\n : true\n if (!needsRestriction) return sandboxOptions\n\n const { abortController } = context\n const mode = context?.options?.toolPermissionContext?.mode ?? 'default'\n const shouldAvoidPermissionPrompts = Boolean(\n context?.options?.shouldAvoidPermissionPrompts,\n )\n const requestToolUsePermission =\n typeof context?.options?.requestToolUsePermission === 'function'\n ? context.options.requestToolUsePermission\n : undefined\n\n const ports = await ensureSandboxNetworkInfrastructure({\n runtimeConfig: sandboxPlan.runtimeConfig,\n platform,\n permissionCallback: async ({ host, port }) => {\n if (mode === 'acceptEdits' || mode === 'bypassPermissions') return true\n if (mode === 'dontAsk' || shouldAvoidPermissionPrompts) return false\n if (!requestToolUsePermission) return false\n if (abortController.signal.aborted) return false\n\n const hostForUrl =\n host.includes(':') && !host.startsWith('[') ? `[${host}]` : host\n const url = `http://${hostForUrl}:${port}/`\n\n const result = await requestToolUsePermission(\n {\n tool: WebFetchTool,\n description: 'Network request outside of sandbox',\n input: { url },\n commandPrefix: null,\n suggestions: undefined,\n riskScore: null,\n },\n context,\n )\n\n return result.result === true\n },\n })\n\n if (platform === 'linux') {\n if (!ports.linuxBridge) return sandboxOptions\n return {\n ...sandboxOptions,\n linuxBridge: ports.linuxBridge,\n // Compatibility: inside a Linux net namespace we expose proxy bridges on fixed ports.\n httpProxyPort: 3128,\n socksProxyPort: 1080,\n }\n }\n\n return {\n ...sandboxOptions,\n httpProxyPort: ports.httpProxyPort,\n socksProxyPort: ports.socksProxyPort,\n }\n}\n", "import type { ToolUseContext } from '#core/tooling/Tool'\nimport { createAssistantMessage } from '#core/utils/messages'\nimport { BunShell } from '#runtime/shell'\nimport { getBunShellSandboxPlan } from '#core/utils/sandbox/bunShellSandboxPlan'\nimport { getCwd, getOriginalCwd } from '#core/utils/state'\nimport { decideSystemSandboxForBashTool } from '#core/utils/sandbox/systemSandbox'\nimport { getBashDestructiveCommandBlock } from '#core/utils/sandbox/destructiveCommandGuard'\nimport { getPlanConversationKey } from '#core/utils/planMode'\nimport {\n formatBashLlmGateBlockMessage,\n runBashLlmSafetyGate,\n} from './llmSafetyGate'\nimport { getCommandSource } from './commandSource'\nimport type { Out } from './BashTool'\nimport { executeForegroundBash } from './executeForeground'\nimport { maybeAttachSandboxNetworkPorts } from './sandboxNetwork'\n\ntype SetToolJSX = (\n value: {\n jsx: unknown\n shouldHidePromptInput: boolean\n } | null,\n) => void\n\ntype Input = {\n command: string\n timeout: number\n run_in_background?: boolean\n dangerouslyDisableSandbox?: boolean\n description?: string\n}\n\nexport async function* callBashTool(\n input: Input,\n context: ToolUseContext,\n renderResultForAssistant: (output: Out) => string,\n): AsyncGenerator<\n | { type: 'progress'; content: unknown }\n | { type: 'result'; resultForAssistant: string; data: Out }\n> {\n const { abortController, readFileTimestamps } = context\n const hasSetToolJSX = (\n value: ToolUseContext,\n ): value is ToolUseContext & { setToolJSX: SetToolJSX } => {\n return typeof (value as { setToolJSX?: unknown }).setToolJSX === 'function'\n }\n const setToolJSX = hasSetToolJSX(context) ? context.setToolJSX : undefined\n\n const commandSource = getCommandSource(context)\n const safeMode = Boolean(context?.safeMode ?? context?.options?.safeMode)\n const userPrompt =\n typeof context?.options?.lastUserPrompt === 'string'\n ? context.options.lastUserPrompt.trim()\n : ''\n const commandDescription =\n typeof input.description === 'string' ? input.description.trim() : ''\n const sandboxDisabled = input.dangerouslyDisableSandbox === true\n\n const destructiveBlock = getBashDestructiveCommandBlock({\n command: input.command,\n cwd: getCwd(),\n originalCwd: getOriginalCwd(),\n commandSource,\n platform: process.platform,\n })\n if (destructiveBlock) {\n const data: Out = {\n stdout: '',\n stdoutLines: 0,\n stderr: destructiveBlock.message,\n stderrLines: destructiveBlock.message.split(/\\r?\\n/).length,\n interrupted: false,\n dangerouslyDisableSandbox: sandboxDisabled,\n }\n yield {\n type: 'result',\n resultForAssistant: renderResultForAssistant(data),\n data,\n }\n return\n }\n\n const systemSandboxDecision = decideSystemSandboxForBashTool({\n safeMode,\n commandSource,\n dangerouslyDisableSandbox: input.dangerouslyDisableSandbox === true,\n })\n\n const systemSandboxOptions = systemSandboxDecision.enabled\n ? {\n enabled: true,\n require: systemSandboxDecision.required,\n allowNetwork: systemSandboxDecision.allowNetwork,\n writableRoots: [getOriginalCwd()],\n chdir: getCwd(),\n }\n : undefined\n\n const sandboxPlan = getBunShellSandboxPlan({\n command: input.command,\n dangerouslyDisableSandbox: input.dangerouslyDisableSandbox === true,\n toolUseContext: context,\n })\n\n if (sandboxPlan.shouldBlockUnsandboxedCommand) {\n const data: Out = {\n stdout: '',\n stdoutLines: 0,\n stderr:\n 'This command must run in the sandbox, but sandboxed execution is not available.',\n stderrLines: 1,\n interrupted: false,\n dangerouslyDisableSandbox: sandboxDisabled,\n }\n yield {\n type: 'result',\n resultForAssistant: renderResultForAssistant(data),\n data,\n }\n return\n }\n\n let sandboxOptions =\n sandboxPlan.settings.enabled === true\n ? sandboxPlan.bunShellSandboxOptions\n : systemSandboxOptions\n\n const bashLlmGateQuery = context.options?.bashLlmGateQuery\n\n const llmGateResult = await runBashLlmSafetyGate({\n command: input.command,\n userPrompt,\n description: commandDescription,\n platform: process.platform,\n commandSource,\n safeMode,\n runInBackground: input.run_in_background === true,\n willSandbox: Boolean(sandboxOptions?.enabled),\n sandboxRequired: Boolean(sandboxOptions?.enabled && sandboxOptions.require),\n cwd: getCwd(),\n originalCwd: getOriginalCwd(),\n parentAbortSignal: abortController.signal,\n query: bashLlmGateQuery,\n })\n\n if (llmGateResult.decision === 'block') {\n const message = formatBashLlmGateBlockMessage(llmGateResult.verdict)\n const data: Out = {\n stdout: '',\n stdoutLines: 0,\n stderr: message,\n stderrLines: message.split(/\\r?\\n/).length,\n interrupted: false,\n dangerouslyDisableSandbox: sandboxDisabled,\n }\n yield {\n type: 'result',\n resultForAssistant: renderResultForAssistant(data),\n data,\n }\n return\n }\n\n if (llmGateResult.decision === 'error' && !llmGateResult.canFailOpen) {\n const userHint =\n llmGateResult.errorType === 'api'\n ? 'Fix your model connection (API key / network) and retry.'\n : llmGateResult.errorType === 'timeout'\n ? 'LLM intent gate timed out. Retry.'\n : 'LLM intent gate returned invalid output. Retry.'\n const userMessage = [\n llmGateResult.willSandbox\n ? 'Blocked: LLM intent gate failed (cannot verify command intent).'\n : 'Blocked: LLM intent gate failed and command would run unsandboxed.',\n `Error: ${llmGateResult.error}`,\n '',\n userHint,\n ]\n .filter(Boolean)\n .join('\\n')\n\n // Keep user-only bypass instructions out of the model-facing tool result to avoid\n // encouraging the assistant to \"solve\" the problem by bypassing safety.\n const assistantMessage = [\n llmGateResult.willSandbox\n ? 'Blocked: LLM intent gate unavailable.'\n : 'Blocked: LLM intent gate unavailable (command would run unsandboxed).',\n `Error: ${llmGateResult.error}`,\n llmGateResult.errorType === 'invalid_output'\n ? 'Hint: Retry and include a short `description` for the Bash command.'\n : llmGateResult.errorType === 'timeout'\n ? 'Hint: Retry (or switch to a faster main model).'\n : '',\n ]\n .filter(Boolean)\n .join('\\n')\n const data: Out = {\n stdout: '',\n stdoutLines: 0,\n stderr: userMessage,\n stderrLines: userMessage.split(/\\r?\\n/).length,\n interrupted: false,\n dangerouslyDisableSandbox: sandboxDisabled,\n }\n yield {\n type: 'result',\n resultForAssistant: assistantMessage,\n data,\n }\n return\n }\n\n sandboxOptions = await maybeAttachSandboxNetworkPorts({\n sandboxPlan,\n sandboxOptions,\n context,\n })\n\n // \uD83D\uDD27 Check if already cancelled before starting execution\n if (abortController.signal.aborted) {\n const data: Out = {\n stdout: '',\n stdoutLines: 0,\n stderr: 'Command cancelled before execution',\n stderrLines: 1,\n interrupted: true,\n dangerouslyDisableSandbox: sandboxDisabled,\n }\n\n yield {\n type: 'result',\n resultForAssistant: renderResultForAssistant(data),\n data,\n }\n return\n }\n\n try {\n if (input.run_in_background) {\n const { bashId } = BunShell.getInstance().execInBackground(\n input.command,\n input.timeout,\n {\n sandbox: sandboxOptions,\n },\n )\n const data: Out = {\n stdout: '',\n stdoutLines: 0,\n stderr: '',\n stderrLines: 0,\n interrupted: false,\n bashId,\n backgroundTaskId: bashId,\n dangerouslyDisableSandbox: sandboxDisabled,\n }\n yield {\n type: 'result',\n resultForAssistant: renderResultForAssistant(data),\n data,\n }\n return\n }\n\n yield* executeForegroundBash({\n command: input.command,\n timeout: input.timeout,\n abortController,\n readFileTimestamps,\n sandboxOptions,\n dangerouslyDisableSandbox: sandboxDisabled,\n setToolJSX,\n renderResultForAssistant,\n conversationKey: getPlanConversationKey(context),\n })\n } catch (error) {\n const isAborted = abortController.signal.aborted\n const errorMessage = isAborted\n ? 'Command was cancelled by user'\n : `Command failed: ${error instanceof Error ? error.message : String(error)}`\n\n const data: Out = {\n stdout: '',\n stdoutLines: 0,\n stderr: errorMessage,\n stderrLines: 1,\n interrupted: isAborted,\n dangerouslyDisableSandbox: sandboxDisabled,\n }\n\n yield {\n type: 'result',\n resultForAssistant: renderResultForAssistant(data),\n data,\n }\n } finally {\n setToolJSX?.(null)\n }\n}\n", "import { z } from 'zod'\nimport type { Tool, ToolUseContext, ValidationResult } from '#core/tooling/Tool'\nimport { BunShell } from '#runtime/shell'\nimport {\n getBackgroundAgentTaskSnapshot,\n waitForBackgroundAgentTask,\n} from '#core/utils/backgroundTasks'\nimport { createAssistantMessage } from '#core/utils/messages'\nimport { DESCRIPTION, PROMPT, TOOL_NAME_FOR_PROMPT } from './prompt'\nimport { readTaskOutput } from '#runtime/taskOutputStore'\n\nconst inputSchema = z.strictObject({\n task_id: z.string().describe('The task ID to get output from'),\n block: z\n .boolean()\n .optional()\n .default(true)\n .describe('Whether to wait for completion'),\n timeout: z\n .number()\n .min(0)\n .max(600000)\n .optional()\n .default(30000)\n .describe('Max wait time in ms'),\n})\n\ntype Input = z.infer<typeof inputSchema>\n\ntype TaskType = 'local_bash' | 'local_agent' | 'remote_agent'\ntype TaskStatus = 'running' | 'pending' | 'completed' | 'failed' | 'killed'\n\ntype TaskSummary = {\n task_id: string\n task_type: TaskType\n status: TaskStatus\n description: string\n output?: string\n exitCode?: number | null\n prompt?: string\n result?: string\n error?: string\n}\n\ntype Output = {\n retrieval_status: 'success' | 'timeout' | 'not_ready'\n task: TaskSummary | null\n}\n\nfunction normalizeTaskOutputInput(input: Input): Input {\n return input\n}\n\nfunction taskStatusFromBash(\n bg: ReturnType<BunShell['getBackgroundOutput']>,\n): TaskStatus {\n if (!bg) return 'failed'\n if (bg.killed) return 'killed'\n if (bg.code === null) return 'running'\n return bg.code === 0 ? 'completed' : 'failed'\n}\n\nfunction buildTaskSummary(taskId: string): TaskSummary | null {\n const bg = BunShell.getInstance().getBackgroundOutput(taskId)\n if (bg) {\n return {\n task_id: taskId,\n task_type: 'local_bash',\n status: taskStatusFromBash(bg),\n description: bg.command,\n output: readTaskOutput(taskId),\n exitCode: bg.code,\n }\n }\n\n const agent = getBackgroundAgentTaskSnapshot(taskId)\n if (agent) {\n const output = readTaskOutput(taskId) || agent.resultText || ''\n return {\n task_id: taskId,\n task_type: 'local_agent',\n status: agent.status,\n description: agent.description,\n output,\n prompt: agent.prompt,\n result: output,\n error: agent.error,\n }\n }\n\n return null\n}\n\nasync function waitForBashTaskCompletion(args: {\n taskId: string\n timeoutMs: number\n signal: AbortSignal\n}): Promise<TaskSummary | null> {\n const { taskId, timeoutMs, signal } = args\n const startedAt = Date.now()\n\n while (Date.now() - startedAt < timeoutMs) {\n if (signal.aborted) return null\n const summary = buildTaskSummary(taskId)\n if (!summary) return null\n if (summary.status !== 'running' && summary.status !== 'pending')\n return summary\n await new Promise(resolve => setTimeout(resolve, 100))\n }\n\n return buildTaskSummary(taskId)\n}\n\nexport const TaskOutputTool = {\n name: TOOL_NAME_FOR_PROMPT,\n async description() {\n return DESCRIPTION\n },\n userFacingName() {\n return 'Task Output'\n },\n inputSchema,\n isReadOnly() {\n return true\n },\n isConcurrencySafe() {\n return true\n },\n async isEnabled() {\n return true\n },\n needsPermissions() {\n return false\n },\n async prompt() {\n return PROMPT\n },\n renderToolUseMessage(input: Input) {\n if (input.block === false) return 'non-blocking'\n return ''\n },\n renderToolUseRejectedMessage() {\n return null\n },\n renderResultForAssistant(output: Output) {\n const parts: string[] = []\n parts.push(\n `<retrieval_status>${output.retrieval_status}</retrieval_status>`,\n )\n\n if (output.task) {\n parts.push(`<task_id>${output.task.task_id}</task_id>`)\n parts.push(`<task_type>${output.task.task_type}</task_type>`)\n parts.push(`<status>${output.task.status}</status>`)\n if (output.task.exitCode !== undefined && output.task.exitCode !== null) {\n parts.push(`<exit_code>${output.task.exitCode}</exit_code>`)\n }\n if (output.task.output?.trim()) {\n parts.push(`<output>\\n${output.task.output.trimEnd()}\\n</output>`)\n }\n if (output.task.error) {\n parts.push(`<error>${output.task.error}</error>`)\n }\n }\n\n return parts.join('\\n\\n')\n },\n async validateInput(input: Input): Promise<ValidationResult> {\n if (!input.task_id) {\n return { result: false, message: 'Task ID is required', errorCode: 1 }\n }\n\n const task = buildTaskSummary(input.task_id)\n if (!task) {\n return {\n result: false,\n message: `No task found with ID: ${input.task_id}`,\n errorCode: 2,\n }\n }\n\n return { result: true }\n },\n async *call(input: Input, context: ToolUseContext) {\n const normalized = normalizeTaskOutputInput(input)\n const taskId = normalized.task_id\n const block = normalized.block\n const timeoutMs = normalized.timeout\n\n const initial = buildTaskSummary(taskId)\n if (!initial) {\n throw new Error(`No task found with ID: ${taskId}`)\n }\n\n if (!block) {\n const isDone =\n initial.status !== 'running' && initial.status !== 'pending'\n const out: Output = {\n retrieval_status: isDone ? 'success' : 'not_ready',\n task: initial,\n }\n yield {\n type: 'result',\n data: out,\n resultForAssistant: this.renderResultForAssistant(out),\n }\n return\n }\n\n yield {\n type: 'progress',\n content: createAssistantMessage(\n `<tool-progress>${initial.description ? ` ${initial.description}\\n` : ''} Waiting for task (esc to give additional instructions)</tool-progress>`,\n ),\n }\n\n let finalTask: TaskSummary | null = null\n\n if (initial.task_type === 'local_agent') {\n try {\n const task = await waitForBackgroundAgentTask(\n taskId,\n timeoutMs,\n context.abortController.signal,\n )\n finalTask = task ? buildTaskSummary(taskId) : null\n } catch {\n finalTask = buildTaskSummary(taskId)\n }\n } else {\n finalTask = await waitForBashTaskCompletion({\n taskId,\n timeoutMs,\n signal: context.abortController.signal,\n })\n }\n\n if (!finalTask) {\n const out: Output = { retrieval_status: 'timeout', task: null }\n yield {\n type: 'result',\n data: out,\n resultForAssistant: this.renderResultForAssistant(out),\n }\n return\n }\n\n if (finalTask.status === 'running' || finalTask.status === 'pending') {\n const out: Output = { retrieval_status: 'timeout', task: finalTask }\n yield {\n type: 'result',\n data: out,\n resultForAssistant: this.renderResultForAssistant(out),\n }\n return\n }\n\n const out: Output = { retrieval_status: 'success', task: finalTask }\n yield {\n type: 'result',\n data: out,\n resultForAssistant: this.renderResultForAssistant(out),\n }\n },\n} satisfies Tool<typeof inputSchema, Output>\n", "export const TOOL_NAME_FOR_PROMPT = 'TaskOutput'\n\nexport const DESCRIPTION = 'Retrieves output from a running or completed task'\n\nexport const PROMPT = `- Retrieves output from a running or completed task (background shell, agent, or remote session)\n- Takes a task_id parameter identifying the task\n- Returns the task output along with status information\n- Use block=true (default) to wait for task completion\n- Use block=false for non-blocking check of current status\n- Task IDs can be found using the /tasks command\n- Works with all task types: background shells, async agents, and remote sessions`\n", "import { Box, Text } from 'ink'\nimport React from 'react'\nimport { z } from 'zod'\nimport { Tool } from '#core/tooling/Tool'\nimport { enterPlanMode, getPlanConversationKey } from '#core/utils/planMode'\nimport { ENTER_DESCRIPTION, ENTER_PROMPT, ENTER_TOOL_NAME } from './prompt'\nimport { getTheme } from '#core/utils/theme'\nimport { BLACK_CIRCLE } from '#core/constants/figures'\nimport { setPermissionMode } from '#core/utils/permissionModeState'\nimport { applyToolPermissionContextUpdateForConversationKey } from '#core/utils/toolPermissionContextState'\n\nconst inputSchema = z.strictObject({})\n\ntype Output = {\n message: string\n}\n\nexport const EnterPlanModeTool = {\n name: ENTER_TOOL_NAME,\n async description() {\n return ENTER_DESCRIPTION\n },\n userFacingName() {\n return ''\n },\n inputSchema,\n isReadOnly() {\n return true\n },\n isConcurrencySafe() {\n return true\n },\n async isEnabled() {\n return true\n },\n needsPermissions() {\n // Entering plan mode is a safe, local state transition (no side effects).\n // Official behavior: entering plan mode does not require a permission prompt.\n return false\n },\n requiresUserInteraction() {\n return false\n },\n async prompt() {\n return ENTER_PROMPT\n },\n renderToolUseMessage() {\n return ''\n },\n renderToolUseRejectedMessage() {\n const theme = getTheme()\n return (\n <Box flexDirection=\"row\" marginTop={1}>\n <Text color={theme.text}>{BLACK_CIRCLE}</Text>\n <Text> User declined to enter plan mode</Text>\n </Box>\n )\n },\n renderToolResultMessage(_output: Output) {\n const theme = getTheme()\n return (\n <Box flexDirection=\"column\" marginTop={1}>\n <Box flexDirection=\"row\">\n <Text color={theme.planMode}>{BLACK_CIRCLE}</Text>\n <Text> Entered plan mode</Text>\n </Box>\n <Box paddingLeft={2}>\n <Text dimColor>\n Kode Agent is now exploring and designing an implementation\n approach.\n </Text>\n </Box>\n </Box>\n )\n },\n renderResultForAssistant(output: Output) {\n return `${output.message}\n\nIn plan mode, you should:\n1. Thoroughly explore the codebase to understand existing patterns\n2. Identify similar features and architectural approaches\n3. Consider multiple approaches and their trade-offs\n4. Use AskUserQuestion if you need to clarify the approach\n5. Design a concrete implementation strategy\n6. When ready, use ExitPlanMode to present your plan for approval\n\nRemember: DO NOT write or edit any files yet. This is a read-only exploration and planning phase.`\n },\n async *call(_input: z.infer<typeof inputSchema>, context: any) {\n if (context?.agentId) {\n throw new Error('EnterPlanMode tool cannot be used in agent contexts')\n }\n\n const safeMode = Boolean(context?.options?.safeMode ?? context?.safeMode)\n const conversationKey = getPlanConversationKey(context)\n const updatedToolPermissionContext =\n applyToolPermissionContextUpdateForConversationKey({\n conversationKey,\n isBypassPermissionsModeAvailable: !safeMode,\n update: { type: 'setMode', mode: 'plan', destination: 'session' },\n })\n\n if (context) {\n context.options ??= {}\n context.options.toolPermissionContext = updatedToolPermissionContext\n }\n\n setPermissionMode(context, 'plan')\n enterPlanMode(context)\n\n const output: Output = {\n message:\n 'Entered plan mode. You should now focus on exploring the codebase and designing an implementation approach.',\n }\n yield {\n type: 'result',\n data: output,\n resultForAssistant: this.renderResultForAssistant(output),\n }\n },\n} satisfies Tool<typeof inputSchema, Output>\n", "export const ENTER_TOOL_NAME = 'EnterPlanMode'\nexport const EXIT_TOOL_NAME = 'ExitPlanMode'\n\nexport const ENTER_DESCRIPTION =\n 'Enters plan mode for complex tasks requiring exploration and design'\n\nexport const ENTER_PROMPT = `Use this tool proactively when you're about to start a non-trivial implementation task. Getting user sign-off on your approach before writing code prevents wasted effort and ensures alignment. This tool transitions you into plan mode where you can explore the codebase and design an implementation approach for user approval.\n\n## When to Use This Tool\n\n**Prefer using EnterPlanMode** for implementation tasks unless they're simple. Use it when ANY of these conditions apply:\n\n1. **New Feature Implementation**: Adding meaningful new functionality\n - Example: \"Add a logout button\" - where should it go? What should happen on click?\n - Example: \"Add form validation\" - what rules? What error messages?\n\n2. **Multiple Valid Approaches**: The task can be solved in several different ways\n - Example: \"Add caching to the API\" - could use Redis, in-memory, file-based, etc.\n - Example: \"Improve performance\" - many optimization strategies possible\n\n3. **Code Modifications**: Changes that affect existing behavior or structure\n - Example: \"Update the login flow\" - what exactly should change?\n - Example: \"Refactor this component\" - what's the target architecture?\n\n4. **Architectural Decisions**: The task requires choosing between patterns or technologies\n - Example: \"Add real-time updates\" - WebSockets vs SSE vs polling\n - Example: \"Implement state management\" - Redux vs Context vs custom solution\n\n5. **Multi-File Changes**: The task will likely touch more than 2-3 files\n - Example: \"Refactor the authentication system\"\n - Example: \"Add a new API endpoint with tests\"\n\n6. **Unclear Requirements**: You need to explore before understanding the full scope\n - Example: \"Make the app faster\" - need to profile and identify bottlenecks\n - Example: \"Fix the bug in checkout\" - need to investigate root cause\n\n7. **User Preferences Matter**: The implementation could reasonably go multiple ways\n - If you would use AskUserQuestion to clarify the approach, use EnterPlanMode instead\n - Plan mode lets you explore first, then present options with context\n\n## When NOT to Use This Tool\n\nOnly skip EnterPlanMode for simple tasks:\n- Single-line or few-line fixes (typos, obvious bugs, small tweaks)\n- Adding a single function with clear requirements\n- Tasks where the user has given very specific, detailed instructions\n- Pure research/exploration tasks (use the Task tool with explore agent instead)\n\n## What Happens in Plan Mode\n\nIn plan mode, you'll:\n1. Thoroughly explore the codebase using Glob, Grep, and Read tools\n2. Understand existing patterns and architecture\n3. Design an implementation approach\n4. Present your plan to the user for approval\n5. Use AskUserQuestion if you need to clarify approaches\n6. Exit plan mode with ExitPlanMode when ready to implement\n\n## Examples\n\n### GOOD - Use EnterPlanMode:\nUser: \"Add user authentication to the app\"\n- Requires architectural decisions (session vs JWT, where to store tokens, middleware structure)\n\nUser: \"Optimize the database queries\"\n- Multiple approaches possible, need to profile first, significant impact\n\nUser: \"Implement dark mode\"\n- Architectural decision on theme system, affects many components\n\nUser: \"Add a delete button to the user profile\"\n- Seems simple but involves: where to place it, confirmation dialog, API call, error handling, state updates\n\nUser: \"Update the error handling in the API\"\n- Affects multiple files, user should approve the approach\n\n### BAD - Don't use EnterPlanMode:\nUser: \"Fix the typo in the README\"\n- Straightforward, no planning needed\n\nUser: \"Add a console.log to debug this function\"\n- Simple, obvious implementation\n\nUser: \"What files handle routing?\"\n- Research task, not implementation planning\n\n## Important Notes\n\n- Entering plan mode is a safe, local state transition (no code changes)\n- If unsure whether to use it, err on the side of planning - it's better to get alignment upfront than to redo work\n- Users appreciate being consulted before significant changes are made to their codebase`\n\nexport const EXIT_DESCRIPTION =\n 'Prompts the user to exit plan mode and start coding'\n\nexport const EXIT_PROMPT = `Use this tool when you are in plan mode and have finished writing your plan to the plan file and are ready for user approval.\n\n## How This Tool Works\n- You should have already written your plan to the plan file specified in the plan mode system message\n- This tool does NOT take the plan content as a parameter - it will read the plan from the file you wrote\n- This tool simply signals that you're done planning and ready for the user to review and approve\n- The user will see the contents of your plan file when they review it\n\n## When to Use This Tool\nIMPORTANT: Only use this tool when the task requires planning the implementation steps of a task that requires writing code. For research tasks where you're gathering information, searching files, reading files or in general trying to understand the codebase - do NOT use this tool.\n\n## Handling Ambiguity in Plans\nBefore using this tool, ensure your plan is clear and unambiguous. If there are multiple valid approaches or unclear requirements:\n1. Use the AskUserQuestion tool to clarify with the user\n2. Ask about specific implementation choices (e.g., architectural patterns, which library to use)\n3. Clarify any assumptions that could affect the implementation\n4. Edit your plan file to incorporate user feedback\n5. Only proceed with ExitPlanMode after resolving ambiguities and updating the plan file\n\n## Examples\n\n1. Initial task: \"Search for and understand the implementation of vim mode in the codebase\" - Do not use the exit plan mode tool because you are not planning the implementation steps of the task.\n2. Initial task: \"Help me implement yank mode for vim\" - Use the exit plan mode tool after you have finished planning the implementation steps of the task.\n3. Initial task: \"Add a new feature to handle user authentication\" - If unsure about auth method (OAuth, JWT, etc.), use AskUserQuestion first, then use exit plan mode tool after clarifying the approach.`\n", "import { Box, Text } from 'ink'\nimport React from 'react'\nimport { z } from 'zod'\nimport { Tool } from '#core/tooling/Tool'\nimport {\n exitPlanMode,\n getPlanConversationKey,\n getPlanFilePath,\n readPlanFile,\n} from '#core/utils/planMode'\nimport { EXIT_DESCRIPTION, EXIT_PROMPT, EXIT_TOOL_NAME } from './prompt'\nimport { getTheme } from '#core/utils/theme'\nimport { BLACK_CIRCLE } from '#core/constants/figures'\nimport {\n getPermissionMode,\n setPermissionMode,\n} from '#core/utils/permissionModeState'\nimport { applyToolPermissionContextUpdateForConversationKey } from '#core/utils/toolPermissionContextState'\n\nfunction getExitPlanModePlanText(conversationKey?: string): string {\n const { content } = readPlanFile(undefined, conversationKey)\n return (\n content || 'No plan found. Please write your plan to the plan file first.'\n )\n}\n\nexport function __getExitPlanModePlanTextForTests(\n conversationKey?: string,\n): string {\n return getExitPlanModePlanText(conversationKey)\n}\n\nconst inputSchema = z\n .object({\n allowedPrompts: z\n .array(\n z.object({\n tool: z.literal('Bash'),\n prompt: z.string(),\n }),\n )\n .optional()\n .describe(\n 'Prompt-based permissions needed to implement the plan. These describe categories of actions rather than specific commands.',\n ),\n })\n .passthrough()\n\ntype Output = {\n plan: string\n isAgent: boolean\n filePath?: string\n}\n\nexport const ExitPlanModeTool = {\n name: EXIT_TOOL_NAME,\n async description() {\n return EXIT_DESCRIPTION\n },\n userFacingName() {\n return ''\n },\n inputSchema,\n isReadOnly() {\n return false\n },\n isConcurrencySafe() {\n return true\n },\n async isEnabled() {\n return true\n },\n needsPermissions() {\n return true\n },\n requiresUserInteraction() {\n return true\n },\n async prompt() {\n return EXIT_PROMPT\n },\n renderToolUseMessage() {\n return ''\n },\n renderToolUseRejectedMessage(\n _input: z.infer<typeof inputSchema>,\n options: { conversationKey?: string } = {},\n ) {\n const theme = getTheme()\n const conversationKey =\n typeof options.conversationKey === 'string' &&\n options.conversationKey.trim()\n ? options.conversationKey.trim()\n : undefined\n\n const { content } = readPlanFile(undefined, conversationKey)\n const plan = getExitPlanModePlanText(conversationKey)\n\n return (\n <Box flexDirection=\"column\" marginTop={1} width=\"100%\">\n <Box flexDirection=\"row\">\n <Text> \u23BF </Text>\n <Box flexDirection=\"column\" width=\"100%\">\n <Text color={theme.error}>User rejected the plan:</Text>\n <Box\n borderStyle=\"round\"\n borderColor={theme.planMode}\n borderDimColor\n paddingX={1}\n overflow=\"hidden\"\n >\n <Text dimColor>{plan}</Text>\n </Box>\n </Box>\n </Box>\n </Box>\n )\n },\n renderToolResultMessage(output: Output) {\n const theme = getTheme()\n const planPath =\n typeof output.filePath === 'string' ? output.filePath : null\n const plan = output.plan || 'No plan found'\n\n return (\n <Box flexDirection=\"column\" marginTop={1} width=\"100%\">\n <Box flexDirection=\"row\">\n <Text color={theme.planMode}>{BLACK_CIRCLE}</Text>\n <Text> User approved the plan</Text>\n </Box>\n <Box flexDirection=\"row\">\n <Text> \u23BF </Text>\n <Box flexDirection=\"column\">\n {planPath ? (\n <Text dimColor>Plan file: {planPath} \u00B7 /plan to edit</Text>\n ) : null}\n <Text dimColor>{plan}</Text>\n </Box>\n </Box>\n </Box>\n )\n },\n renderResultForAssistant(output: Output) {\n if (output.isAgent) {\n return 'User has approved the plan. There is nothing else needed from you now. Please respond with \"ok\"'\n }\n\n return `User has approved your plan. You can now start coding. Start with updating your todo list if applicable\n\nYour plan file is: ${output.filePath}\nYou can refer back to it if needed during implementation.\n\n## Approved Plan:\n${output.plan}`\n },\n async *call(input: z.infer<typeof inputSchema>, context: any) {\n exitPlanMode(context)\n\n const safeMode = Boolean(context?.options?.safeMode ?? context?.safeMode)\n const permissionMode = getPermissionMode(context)\n const nextPermissionMode =\n permissionMode === 'plan' ? 'default' : permissionMode\n const conversationKey = getPlanConversationKey(context)\n const updatedToolPermissionContext =\n applyToolPermissionContextUpdateForConversationKey({\n conversationKey,\n isBypassPermissionsModeAvailable: !safeMode,\n update: {\n type: 'setMode',\n mode: nextPermissionMode,\n destination: 'session',\n },\n })\n\n if (context) {\n context.options ??= {}\n context.options.toolPermissionContext = updatedToolPermissionContext\n }\n\n if (context) {\n setPermissionMode(context, nextPermissionMode)\n }\n\n const planFilePath = getPlanFilePath(context?.agentId, conversationKey)\n const { content } = readPlanFile(context?.agentId, conversationKey)\n const plan = content.trim()\n ? content\n : getExitPlanModePlanText(conversationKey)\n\n const isAgent = !!context?.agentId\n const output: Output = {\n plan,\n isAgent,\n filePath: planFilePath,\n }\n yield {\n type: 'result',\n data: output,\n resultForAssistant: this.renderResultForAssistant(output),\n }\n },\n} satisfies Tool<typeof inputSchema, Output>\n", "import { Hunk } from 'diff'\nimport { mkdirSync, readFileSync, statSync } from 'fs'\nimport { dirname, isAbsolute, relative, resolve, sep } from 'path'\nimport { z } from 'zod'\nimport { Tool, ValidationResult } from '#core/tooling/Tool'\nimport {\n addLineNumbers,\n detectFileEncoding,\n detectLineEndings,\n findSimilarFile,\n writeTextContent,\n} from '#core/utils/file'\nimport { readFileBun, fileExistsBun } from '#runtime/file'\nimport { getCwd } from '#core/utils/state'\nimport { emitReminderEvent } from '#core/services/systemReminder'\nimport { recordFileEdit } from '#core/services/fileFreshness'\nimport { NotebookEditTool } from '#tools/tools/filesystem/NotebookEditTool/NotebookEditTool'\nimport { DESCRIPTION } from './prompt'\nimport { applyEdit } from './utils'\nimport { hasWritePermission } from '#core/utils/permissions/filesystem'\nimport { PROJECT_FILE } from '#core/constants/product'\nimport { normalizeLineEndings } from '#core/utils/paste'\nimport { sha256File } from '#core/utils/sha256'\n\nconst inputSchema = z.strictObject({\n file_path: z.string().describe('The absolute path to the file to modify'),\n old_string: z.string().describe('The text to replace'),\n new_string: z.string().describe('The text to replace it with'),\n replace_all: z\n .boolean()\n .optional()\n .describe('Replace all occurences of old_string (default false)'),\n})\n\nexport type In = typeof inputSchema\n\n// Number of lines of context to include before/after the change in our result message\nconst N_LINES_SNIPPET = 4\n\nexport const FileEditTool = {\n name: 'Edit',\n async description() {\n return 'A tool for editing files'\n },\n async prompt() {\n return DESCRIPTION\n },\n inputSchema,\n userFacingName() {\n return 'Edit'\n },\n async isEnabled() {\n return true\n },\n isReadOnly() {\n return false\n },\n isConcurrencySafe() {\n return false // FileEdit modifies files, not safe for concurrent execution\n },\n needsPermissions({ file_path }) {\n return !hasWritePermission(file_path)\n },\n renderToolUseMessage(input, { verbose }) {\n return `file_path: ${verbose ? input.file_path : relative(getCwd(), input.file_path)}`\n },\n async validateInput(\n { file_path, old_string, new_string, replace_all },\n { readFileTimestamps, readFileHashes },\n ) {\n if (old_string === new_string) {\n return {\n result: false,\n message:\n 'No changes to make: old_string and new_string are exactly the same.',\n meta: {\n old_string,\n },\n } as ValidationResult\n }\n\n const fullFilePath = isAbsolute(file_path)\n ? file_path\n : resolve(getCwd(), file_path)\n\n if (old_string === '') {\n if (!fileExistsBun(fullFilePath)) return { result: true }\n const existingContent = await readFileBun(fullFilePath)\n if (normalizeLineEndings(existingContent ?? '').trim() !== '') {\n return {\n result: false,\n message: 'Cannot create new file - file already exists.',\n }\n }\n return { result: true }\n }\n\n if (!fileExistsBun(fullFilePath)) {\n // Try to find a similar file with a different extension\n const similarFilename = findSimilarFile(fullFilePath)\n let message = 'File does not exist.'\n\n // If we found a similar file, suggest it to the assistant\n if (similarFilename) {\n message += ` Did you mean ${similarFilename}?`\n }\n\n return {\n result: false,\n message,\n }\n }\n\n if (fullFilePath.endsWith('.ipynb')) {\n return {\n result: false,\n message: `File is a Jupyter Notebook. Use the ${NotebookEditTool.name} to edit this file.`,\n }\n }\n\n const readTimestamp = readFileTimestamps[fullFilePath]\n if (!readTimestamp) {\n return {\n result: false,\n message:\n 'File has not been read yet. Read it first before writing to it.',\n meta: {\n isFilePathAbsolute: String(isAbsolute(file_path)),\n },\n }\n }\n\n // Check if file exists and get its last modified time\n const stats = statSync(fullFilePath)\n const lastWriteTime = stats.mtimeMs\n if (lastWriteTime > readTimestamp) {\n const lastReadHash = readFileHashes?.[fullFilePath]\n if (!lastReadHash) {\n return {\n result: false,\n message:\n 'File has been modified since read, either by the user or by a linter. Read it again before attempting to write it.',\n }\n }\n\n let currentHash: string\n try {\n currentHash = await sha256File(fullFilePath)\n } catch {\n return {\n result: false,\n message:\n 'File has been modified since read, either by the user or by a linter. Read it again before attempting to write it.',\n }\n }\n if (currentHash !== lastReadHash) {\n return {\n result: false,\n message:\n 'File has been modified since read, either by the user or by a linter. Read it again before attempting to write it.',\n }\n }\n\n // The file was touched (mtime changed) without content changes. Treat as fresh.\n readFileTimestamps[fullFilePath] = lastWriteTime\n }\n\n const file = await readFileBun(fullFilePath)\n const normalizedFile = normalizeLineEndings(file ?? '')\n const normalizedOldString = normalizeLineEndings(old_string)\n if (!file) {\n return {\n result: false,\n message: 'Could not read file.',\n meta: {\n isFilePathAbsolute: String(isAbsolute(file_path)),\n },\n }\n }\n if (!normalizedFile.includes(normalizedOldString)) {\n return {\n result: false,\n message: `String to replace not found in file.\\nString: ${old_string}`,\n meta: {\n isFilePathAbsolute: String(isAbsolute(file_path)),\n },\n }\n }\n\n const matches = normalizedFile.split(normalizedOldString).length - 1\n if (matches > 1 && !replace_all) {\n return {\n result: false,\n message: `Found ${matches} matches of the string to replace, but replace_all is false. To replace all occurrences, set replace_all to true. To replace only one occurrence, please provide more context to uniquely identify the instance.\\nString: ${old_string}`,\n meta: {\n isFilePathAbsolute: String(isAbsolute(file_path)),\n },\n }\n }\n\n return { result: true }\n },\n async *call(\n { file_path, old_string, new_string, replace_all },\n { readFileTimestamps, readFileHashes },\n ) {\n const fullFilePath = isAbsolute(file_path)\n ? file_path\n : resolve(getCwd(), file_path)\n\n if (fileExistsBun(fullFilePath)) {\n const readTimestamp = readFileTimestamps[fullFilePath]\n const lastWriteTime = statSync(fullFilePath).mtimeMs\n if (!readTimestamp) {\n throw new Error(\n 'File has been unexpectedly modified. Read it again before attempting to write it.',\n )\n }\n if (lastWriteTime > readTimestamp) {\n const lastReadHash = readFileHashes?.[fullFilePath]\n if (lastReadHash) {\n let currentHash: string\n try {\n currentHash = await sha256File(fullFilePath)\n } catch {\n throw new Error(\n 'File has been unexpectedly modified. Read it again before attempting to write it.',\n )\n }\n if (currentHash === lastReadHash) {\n readFileTimestamps[fullFilePath] = lastWriteTime\n } else {\n throw new Error(\n 'File has been unexpectedly modified. Read it again before attempting to write it.',\n )\n }\n } else {\n throw new Error(\n 'File has been unexpectedly modified. Read it again before attempting to write it.',\n )\n }\n }\n }\n\n const { patch, updatedFile } = await applyEdit(\n file_path,\n old_string,\n new_string,\n replace_all ?? false,\n )\n\n const dir = dirname(fullFilePath)\n mkdirSync(dir, { recursive: true })\n const enc = fileExistsBun(fullFilePath)\n ? detectFileEncoding(fullFilePath)\n : 'utf8'\n const endings = fileExistsBun(fullFilePath)\n ? detectLineEndings(fullFilePath)\n : 'LF'\n const originalFile = fileExistsBun(fullFilePath)\n ? normalizeLineEndings((await readFileBun(fullFilePath)) ?? '')\n : ''\n writeTextContent(fullFilePath, updatedFile, enc, endings)\n\n // Record Agent edit operation for file freshness tracking\n recordFileEdit(fullFilePath, updatedFile)\n\n // Update read timestamp, to invalidate stale writes\n readFileTimestamps[fullFilePath] = statSync(fullFilePath).mtimeMs\n\n if (readFileHashes) {\n try {\n readFileHashes[fullFilePath] = await sha256File(fullFilePath)\n } catch {\n // ignore\n }\n }\n\n // Emit file edited event for system reminders\n emitReminderEvent('file:edited', {\n filePath: fullFilePath,\n oldString: old_string,\n newString: new_string,\n timestamp: Date.now(),\n operation:\n old_string === '' ? 'create' : new_string === '' ? 'delete' : 'update',\n })\n\n const data = {\n filePath: file_path,\n oldString: old_string,\n newString: new_string,\n originalFile,\n structuredPatch: patch,\n userModified: false,\n replaceAll: replace_all ?? false,\n }\n yield {\n type: 'result',\n data,\n resultForAssistant: this.renderResultForAssistant(data),\n }\n },\n renderResultForAssistant({ filePath, originalFile, oldString, newString }) {\n const { snippet, startLine } = getSnippet(\n normalizeLineEndings(originalFile || ''),\n normalizeLineEndings(oldString),\n normalizeLineEndings(newString),\n )\n return `The file ${filePath} has been updated. Here's the result of running \\`cat -n\\` on a snippet of the edited file:\n${addLineNumbers({\n content: snippet,\n startLine,\n})}`\n },\n} satisfies Tool<\n typeof inputSchema,\n {\n filePath: string\n oldString: string\n newString: string\n originalFile: string\n structuredPatch: Hunk[]\n userModified: boolean\n replaceAll: boolean\n }\n>\n\nexport function getSnippet(\n initialText: string,\n oldStr: string,\n newStr: string,\n): { snippet: string; startLine: number } {\n const before = initialText.split(oldStr)[0] ?? ''\n const replacementLine = before.split(/\\r?\\n/).length - 1\n const newFileLines = initialText.replace(oldStr, newStr).split(/\\r?\\n/)\n // Calculate the start and end line numbers for the snippet\n const startLine = Math.max(0, replacementLine - N_LINES_SNIPPET)\n const endLine =\n replacementLine + N_LINES_SNIPPET + newStr.split(/\\r?\\n/).length\n // Get snippet\n const snippetLines = newFileLines.slice(startLine, endLine + 1)\n const snippet = snippetLines.join('\\n')\n return { snippet, startLine: startLine + 1 }\n}\n", "import { Box, Text } from 'ink'\nimport { extname, relative } from 'path'\nimport * as React from 'react'\nimport { z } from 'zod'\nimport { highlight, supportsLanguage } from 'cli-highlight'\nimport type { Tool } from '#core/tooling/Tool'\nimport { NotebookCellType, NotebookContent } from '#core/types/notebook'\nimport { readFileBun, fileExistsBun } from '#runtime/file'\nimport { safeParseJSON } from '#core/utils/json'\nimport { getCwd } from '#core/utils/state'\nimport { DESCRIPTION, PROMPT } from './prompt'\nimport { hasWritePermission } from '#core/utils/permissions/filesystem'\nimport { findCellIndex } from './cells'\nimport { editNotebookFile, resolveNotebookPath } from './editor'\n\nfunction highlightCode(code: string, language: string): string {\n try {\n if (supportsLanguage(language)) {\n return highlight(code, { language })\n }\n return highlight(code, { language: 'markdown' })\n } catch {\n return highlight(code, { language: 'markdown' })\n }\n}\n\nconst inputSchema = z.strictObject({\n notebook_path: z\n .string()\n .describe(\n 'The absolute path to the Jupyter notebook file to edit (must be absolute, not relative)',\n ),\n cell_id: z\n .string()\n .optional()\n .describe(\n 'The ID of the cell to edit. When inserting a new cell, the new cell will be inserted after the cell with this ID, or at the beginning if not specified.',\n ),\n new_source: z.string().describe('The new source for the cell'),\n cell_type: z\n .enum(['code', 'markdown'])\n .optional()\n .describe(\n 'The type of the cell (code or markdown). If not specified, it defaults to the current cell type. If using edit_mode=insert, this is required.',\n ),\n edit_mode: z\n .enum(['replace', 'insert', 'delete'])\n .optional()\n .describe(\n 'The type of edit to make (replace, insert, delete). Defaults to replace.',\n ),\n})\n\nexport const NotebookEditTool = {\n name: 'NotebookEdit',\n async description() {\n return DESCRIPTION\n },\n async prompt() {\n return PROMPT\n },\n inputSchema,\n userFacingName() {\n return 'Edit Notebook'\n },\n async isEnabled() {\n return true\n },\n isReadOnly() {\n return false\n },\n isConcurrencySafe() {\n return false // NotebookEditTool modifies state/files, not safe for concurrent execution\n },\n needsPermissions({ notebook_path }) {\n return !hasWritePermission(notebook_path)\n },\n renderResultForAssistant({ cell_id, edit_mode, new_source, error }) {\n if (error) {\n return error\n }\n switch (edit_mode) {\n case 'replace':\n return `Updated cell ${cell_id} with ${new_source}`\n case 'insert':\n return `Inserted cell after ${cell_id ?? 'beginning'} with ${new_source}`\n case 'delete':\n return `Deleted cell ${cell_id}`\n }\n },\n renderToolUseMessage(input, { verbose }) {\n const cellRef = input.cell_id ?? '(none)'\n return `notebook_path: ${verbose ? input.notebook_path : relative(getCwd(), input.notebook_path)}, cell_id: ${cellRef}, content: ${input.new_source.slice(0, 30)}\u2026, cell_type: ${input.cell_type}, edit_mode: ${input.edit_mode ?? 'replace'}`\n },\n renderToolResultMessage({ cell_id, new_source, language, error }) {\n if (error) {\n return (\n <Box flexDirection=\"column\">\n <Text color=\"red\">{error}</Text>\n </Box>\n )\n }\n\n return (\n <Box flexDirection=\"column\">\n <Text>Updated cell {cell_id}:</Text>\n <Box marginLeft={2}>\n <Text>{highlightCode(new_source, language)}</Text>\n </Box>\n </Box>\n )\n },\n async validateInput({\n notebook_path,\n cell_id,\n cell_type,\n edit_mode = 'replace',\n }) {\n const fullPath = resolveNotebookPath(notebook_path)\n\n if (!fileExistsBun(fullPath)) {\n return {\n result: false,\n message: 'Notebook file does not exist.',\n }\n }\n\n if (extname(fullPath) !== '.ipynb') {\n return {\n result: false,\n message:\n 'File must be a Jupyter notebook (.ipynb file). For editing other file types, use the FileEdit tool.',\n }\n }\n\n if (edit_mode === 'insert' && !cell_type) {\n return {\n result: false,\n message: 'Cell type is required when using edit_mode=insert.',\n }\n }\n\n const content = await readFileBun(fullPath)\n if (!content) {\n return {\n result: false,\n message: 'Could not read notebook file.',\n }\n }\n const notebook = safeParseJSON(content) as NotebookContent | null\n if (!notebook) {\n return {\n result: false,\n message: 'Notebook is not valid JSON.',\n }\n }\n\n if ((edit_mode === 'replace' || edit_mode === 'delete') && !cell_id) {\n return {\n result: false,\n message: 'cell_id is required for replace/delete edits.',\n }\n }\n\n if (cell_id) {\n const index = findCellIndex(notebook, cell_id)\n if (index === null || index < 0 || index >= notebook.cells.length) {\n return {\n result: false,\n message: `Cell ID is out of bounds or not found. Notebook has ${notebook.cells.length} cells.`,\n }\n }\n }\n\n return { result: true }\n },\n async *call({ notebook_path, cell_id, new_source, cell_type, edit_mode }) {\n const data = await editNotebookFile({\n notebook_path,\n cell_id,\n new_source,\n cell_type,\n edit_mode,\n })\n yield {\n type: 'result',\n data,\n resultForAssistant: this.renderResultForAssistant(data),\n }\n },\n} satisfies Tool<\n typeof inputSchema,\n {\n cell_id?: string\n new_source: string\n cell_type: NotebookCellType\n language: string\n edit_mode: string\n error?: string\n }\n>\n", "export const DESCRIPTION =\n 'Replace the contents of a specific cell in a Jupyter notebook.'\nexport const PROMPT = `Completely replaces the contents of a specific cell in a Jupyter notebook (.ipynb file) with new source. Jupyter notebooks are interactive documents that combine code, text, and visualizations, commonly used for data analysis and scientific computing. The notebook_path parameter must be an absolute path, not a relative path. The cell_number is 0-indexed. Use edit_mode=insert to add a new cell at the index specified by cell_number. Use edit_mode=delete to delete the cell at the index specified by cell_number.`\n", "import type { NotebookContent } from '#core/types/notebook'\n\nexport function getDerivedCellId(index: number): string {\n return `cell-${index}`\n}\n\nexport function getCellId(\n cell: NotebookContent['cells'][number],\n index: number,\n): string {\n return cell.id ?? getDerivedCellId(index)\n}\n\nfunction parseCellIdAsIndex(cellId: string): number | undefined {\n const trimmed = cellId.trim()\n if (/^\\d+$/.test(trimmed)) return Number(trimmed)\n const match = trimmed.match(/^cell-(\\d+)$/)\n if (match) return Number(match[1])\n return undefined\n}\n\nexport function findCellIndex(\n notebook: NotebookContent,\n cellId: string,\n): number | null {\n const numericIndex = parseCellIdAsIndex(cellId)\n if (numericIndex !== undefined) return numericIndex\n\n const index = notebook.cells.findIndex(\n (cell, idx) => getCellId(cell, idx) === cellId,\n )\n return index >= 0 ? index : null\n}\n", "import { randomUUID } from 'crypto'\nimport { isAbsolute, resolve } from 'path'\n\nimport type { NotebookCellType } from '#core/types/notebook'\nimport { NotebookContent } from '#core/types/notebook'\nimport {\n detectFileEncoding,\n detectLineEndings,\n writeTextContent,\n} from '#core/utils/file'\nimport { readFileBun } from '#runtime/file'\nimport { getCwd } from '#core/utils/state'\nimport { emitReminderEvent } from '#core/services/systemReminder'\nimport { recordFileEdit } from '#core/services/fileFreshness'\n\nimport { findCellIndex, getCellId, getDerivedCellId } from './cells'\n\nexport type NotebookEditResult = {\n cell_id?: string\n new_source: string\n cell_type: NotebookCellType\n language: string\n edit_mode: string\n error?: string\n}\n\nexport function resolveNotebookPath(input: string): string {\n return isAbsolute(input) ? input : resolve(getCwd(), input)\n}\n\nexport async function editNotebookFile(args: {\n notebook_path: string\n cell_id?: string\n new_source: string\n cell_type?: NotebookCellType\n edit_mode?: 'replace' | 'insert' | 'delete'\n}): Promise<NotebookEditResult> {\n const fullPath = resolveNotebookPath(args.notebook_path)\n const mode = args.edit_mode ?? 'replace'\n let editedCellId: string | undefined = args.cell_id\n\n try {\n const enc = detectFileEncoding(fullPath)\n const content = await readFileBun(fullPath)\n if (!content) {\n throw new Error('Could not read notebook file')\n }\n\n const notebook = JSON.parse(content) as NotebookContent\n const language = notebook.metadata.language_info?.name ?? 'python'\n\n const resolveIndexOrThrow = (): number => {\n if (!args.cell_id) {\n throw new Error('cell_id is required for this edit')\n }\n const idx = findCellIndex(notebook, args.cell_id)\n if (idx === null || idx < 0 || idx >= notebook.cells.length) {\n throw new Error(`Cell not found: ${args.cell_id}`)\n }\n return idx\n }\n\n if (mode === 'delete') {\n const idx = resolveIndexOrThrow()\n editedCellId = getCellId(notebook.cells[idx]!, idx)\n notebook.cells.splice(idx, 1)\n } else if (mode === 'insert') {\n if (!args.cell_type) {\n throw new Error('cell_type is required for insert edits')\n }\n\n const afterIndex =\n args.cell_id === undefined ? -1 : findCellIndex(notebook, args.cell_id)\n if (afterIndex === null) {\n throw new Error(`Cell not found: ${args.cell_id}`)\n }\n\n const insertIndex = afterIndex === -1 ? 0 : afterIndex + 1\n\n const newCell: NotebookContent['cells'][number] = {\n cell_type: args.cell_type,\n source: args.new_source,\n metadata: {},\n ...(args.cell_type === 'code' ? { outputs: [] } : {}),\n }\n\n if (notebook.nbformat === 4 && notebook.nbformat_minor >= 5) {\n newCell.id = randomUUID()\n }\n\n notebook.cells.splice(insertIndex, 0, newCell)\n editedCellId = newCell.id ?? getDerivedCellId(insertIndex)\n } else {\n const idx = resolveIndexOrThrow()\n const targetCell = notebook.cells[idx]!\n targetCell.source = args.new_source\n targetCell.execution_count = undefined\n targetCell.outputs = []\n if (args.cell_type && args.cell_type !== targetCell.cell_type) {\n targetCell.cell_type = args.cell_type\n }\n editedCellId = getCellId(targetCell, idx)\n }\n\n const endings = detectLineEndings(fullPath)\n const updatedNotebook = JSON.stringify(notebook, null, 1)\n writeTextContent(fullPath, updatedNotebook, enc, endings!)\n\n recordFileEdit(fullPath, updatedNotebook)\n emitReminderEvent('file:edited', {\n filePath: fullPath,\n cellId: editedCellId,\n newSource: args.new_source,\n cellType: args.cell_type,\n editMode: mode,\n timestamp: Date.now(),\n operation: 'notebook_edit',\n })\n\n return {\n cell_id: editedCellId,\n new_source: args.new_source,\n cell_type: args.cell_type ?? 'code',\n language,\n edit_mode: mode,\n error: '',\n }\n } catch (error) {\n return {\n cell_id: args.cell_id,\n new_source: args.new_source,\n cell_type: args.cell_type ?? 'code',\n language: 'python',\n edit_mode: mode,\n error:\n error instanceof Error\n ? error.message\n : 'Unknown error occurred while editing notebook',\n }\n }\n}\n", "export const DESCRIPTION = `Performs exact string replacements in files. \n\nUsage:\n- You must use your \\`Read\\` tool at least once in the conversation before editing. This tool will error if you attempt an edit without reading the file. \n- When editing text from Read tool output, ensure you preserve the exact indentation (tabs/spaces) as it appears AFTER the line number prefix. The line number prefix format is: spaces + line number + tab. Everything after that tab is the actual file content to match. Never include any part of the line number prefix in the old_string or new_string.\n- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.\n- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.\n- The edit will FAIL if \\`old_string\\` is not unique in the file. Either provide a larger string with more surrounding context to make it unique or use \\`replace_all\\` to change every instance of \\`old_string\\`. \n- Use \\`replace_all\\` for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance.`.trim()\n", "import { isAbsolute, resolve } from 'path'\nimport { getCwd } from '#core/utils/state'\nimport { readFileBun } from '#runtime/file'\nimport { type Hunk } from 'diff'\nimport { getPatch } from '#core/utils/diff'\nimport { normalizeLineEndings } from '#core/utils/paste'\n\n/**\n * Applies an edit to a file and returns the patch and updated file.\n * Does not write the file to disk.\n */\nexport async function applyEdit(\n file_path: string,\n old_string: string,\n new_string: string,\n replace_all = false,\n): Promise<{ patch: Hunk[]; updatedFile: string }> {\n const fullFilePath = isAbsolute(file_path)\n ? file_path\n : resolve(getCwd(), file_path)\n\n let originalFile\n let updatedFile\n if (old_string === '') {\n // Create new file\n originalFile = ''\n updatedFile = normalizeLineEndings(new_string)\n } else {\n // Edit existing file\n const fileContent = await readFileBun(fullFilePath)\n if (!fileContent) {\n throw new Error('Could not read file')\n }\n originalFile = normalizeLineEndings(fileContent)\n const normalizedOldString = normalizeLineEndings(old_string)\n const normalizedNewString = normalizeLineEndings(new_string)\n const oldStringForReplace =\n normalizedNewString === '' &&\n !normalizedOldString.endsWith('\\n') &&\n originalFile.includes(normalizedOldString + '\\n')\n ? normalizedOldString + '\\n'\n : normalizedOldString\n updatedFile = replace_all\n ? originalFile.split(oldStringForReplace).join(normalizedNewString)\n : originalFile.replace(oldStringForReplace, () => normalizedNewString)\n if (updatedFile === originalFile) {\n throw new Error(\n 'Original and edited file match exactly. Failed to apply edit.',\n )\n }\n }\n\n const patch = getPatch({\n filePath: file_path,\n fileContents: originalFile,\n oldStr: originalFile,\n newStr: updatedFile,\n })\n\n return { patch, updatedFile }\n}\n", "import { z } from 'zod'\nimport { Tool } from '#core/tooling/Tool'\nimport { getCwd } from '#core/utils/state'\nimport { ripGrep } from '#core/utils/ripgrep'\nimport { DESCRIPTION, TOOL_NAME_FOR_PROMPT } from './prompt'\nimport { existsSync, statSync } from 'fs'\nimport { isAbsolute, join, relative, resolve } from 'path'\nimport { hasReadPermission } from '#core/utils/permissions/filesystem'\n\nconst inputSchema = z.strictObject({\n pattern: z.string().describe('The glob pattern to match files against'),\n path: z\n .string()\n .optional()\n .describe(\n 'The directory to search in. If not specified, the current working directory will be used. IMPORTANT: Omit this field to use the default directory. DO NOT enter \"undefined\" or \"null\" - simply omit it for the default behavior. Must be a valid directory path if provided.',\n ),\n})\n\ntype Output = {\n durationMs: number\n numFiles: number\n filenames: string[]\n truncated: boolean\n}\n\nconst DEFAULT_LIMIT = 100\n\nexport const GlobTool = {\n name: TOOL_NAME_FOR_PROMPT,\n async description() {\n return DESCRIPTION\n },\n userFacingName() {\n return 'Search'\n },\n inputSchema,\n async isEnabled() {\n return true\n },\n isReadOnly() {\n return true\n },\n isConcurrencySafe() {\n return true // GlobTool is read-only, safe for concurrent execution\n },\n needsPermissions({ path }) {\n return !hasReadPermission(path || getCwd())\n },\n async prompt() {\n return DESCRIPTION\n },\n async validateInput({ path }) {\n if (!path) return { result: true }\n const absolute = isAbsolute(path) ? path : resolve(getCwd(), path)\n if (!existsSync(absolute)) {\n return {\n result: false,\n message: `Directory does not exist: ${path}`,\n errorCode: 1,\n }\n }\n if (!statSync(absolute).isDirectory()) {\n return {\n result: false,\n message: `Path is not a directory: ${path}`,\n errorCode: 2,\n }\n }\n return { result: true }\n },\n renderToolUseMessage({ pattern, path }, { verbose }) {\n const absolutePath = path\n ? isAbsolute(path)\n ? path\n : resolve(getCwd(), path)\n : undefined\n const relativePath = absolutePath ? relative(getCwd(), absolutePath) : ''\n return `pattern: \"${pattern}\"${\n relativePath || verbose\n ? `, path: \"${verbose ? absolutePath : relativePath}\"`\n : ''\n }`\n },\n async *call({ pattern, path }, { abortController }) {\n const start = Date.now()\n const searchPath = path\n ? isAbsolute(path)\n ? path\n : resolve(getCwd(), path)\n : getCwd()\n\n // Default semantics: use ripgrep file listing with no-ignore + hidden,\n // sorted by modified time, filtered by --glob pattern.\n const raw = await ripGrep(\n [\n '--files',\n '--no-ignore',\n '--hidden',\n '--sort=modified',\n '--glob',\n pattern,\n ],\n searchPath,\n abortController.signal,\n )\n\n const files = raw.map(p => (isAbsolute(p) ? p : join(searchPath, p)))\n const truncated = files.length > DEFAULT_LIMIT\n const limitedFiles = files.slice(0, DEFAULT_LIMIT)\n const output: Output = {\n filenames: limitedFiles,\n durationMs: Date.now() - start,\n numFiles: limitedFiles.length,\n truncated,\n }\n yield {\n type: 'result',\n resultForAssistant: this.renderResultForAssistant(output),\n data: output,\n }\n },\n renderResultForAssistant(output) {\n let result = output.filenames.join('\\n')\n if (output.filenames.length === 0) {\n result = 'No files found'\n }\n // Only add truncation message if results were actually truncated\n else if (output.truncated) {\n result +=\n '\\n(Results are truncated. Consider using a more specific path or pattern.)'\n }\n return result\n },\n} satisfies Tool<typeof inputSchema, Output>\n", "export const TOOL_NAME_FOR_PROMPT = 'Glob'\n\nexport const DESCRIPTION = `- Fast file pattern matching tool that works with any codebase size\n- Supports glob patterns like \"**/*.js\" or \"src/**/*.ts\"\n- Returns matching file paths sorted by modification time\n- Use this tool when you need to find files by name patterns\n- When you are doing an open ended search that may require multiple rounds of globbing and grepping, use the Agent tool instead\n- You can call multiple tools in a single response. It is always better to speculatively perform multiple searches in parallel if they are potentially useful.\n`\n", "import { z } from 'zod'\nimport { Tool } from '#core/tooling/Tool'\nimport { getCwd } from '#core/utils/state'\nimport { readdir } from 'fs/promises'\nimport { existsSync, statSync } from 'fs'\nimport { isAbsolute, relative, resolve } from 'path'\nimport { hasReadPermission } from '#core/utils/permissions/filesystem'\nimport { DESCRIPTION, TOOL_NAME_FOR_PROMPT } from './prompt'\n\nconst inputSchema = z.strictObject({\n path: z\n .string()\n .optional()\n .describe(\n 'Directory path to list. If omitted, uses the current working directory.',\n ),\n all: z\n .boolean()\n .optional()\n .describe('Include dotfiles (equivalent to ls -a).'),\n limit: z\n .number()\n .int()\n .min(1)\n .max(5000)\n .optional()\n .describe('Maximum number of entries to return (default: 200).'),\n})\n\ntype Output = {\n path: string\n entries: string[]\n total: number\n truncated: boolean\n}\n\nconst DEFAULT_LIMIT = 200\n\nfunction resolveDirPath(path: string | undefined): string {\n if (!path) return getCwd()\n return isAbsolute(path) ? resolve(path) : resolve(getCwd(), path)\n}\n\nexport const LSTool = {\n name: TOOL_NAME_FOR_PROMPT,\n async description() {\n return DESCRIPTION\n },\n inputSchema,\n async isEnabled() {\n return true\n },\n isReadOnly() {\n return true\n },\n isConcurrencySafe() {\n return true\n },\n needsPermissions({ path }) {\n return !hasReadPermission(resolveDirPath(path))\n },\n async prompt() {\n return DESCRIPTION\n },\n async validateInput({ path }) {\n const dir = resolveDirPath(path)\n if (!existsSync(dir)) {\n return {\n result: false,\n message: `Directory does not exist: ${path ?? dir}`,\n errorCode: 1,\n }\n }\n if (!statSync(dir).isDirectory()) {\n return {\n result: false,\n message: `Path is not a directory: ${path ?? dir}`,\n errorCode: 2,\n }\n }\n return { result: true }\n },\n renderToolUseMessage({ path, all, limit }, { verbose }) {\n const absolute = resolveDirPath(path)\n const display =\n verbose || !path ? absolute : relative(getCwd(), absolute) || '.'\n const flags: string[] = []\n if (all) flags.push('all')\n if (limit !== undefined) flags.push(`limit=${limit}`)\n return `path: \"${display}\"${flags.length > 0 ? ` (${flags.join(', ')})` : ''}`\n },\n async *call(\n { path, all, limit },\n { abortController },\n ): AsyncGenerator<\n { type: 'result'; resultForAssistant: string; data: Output },\n void\n > {\n const dir = resolveDirPath(path)\n const includeHidden = all === true\n const max = limit ?? DEFAULT_LIMIT\n\n if (abortController.signal.aborted) {\n const output: Output = {\n path: dir,\n entries: [],\n total: 0,\n truncated: false,\n }\n yield {\n type: 'result',\n resultForAssistant: this.renderResultForAssistant(output),\n data: output,\n }\n return\n }\n\n const dirents = await readdir(dir, { withFileTypes: true })\n const entries = dirents\n .filter(d => includeHidden || !d.name.startsWith('.'))\n .map(d => {\n if (d.isDirectory()) return `${d.name}/`\n if (d.isSymbolicLink()) return `${d.name}@`\n return d.name\n })\n .sort((a, b) => a.localeCompare(b))\n\n const truncated = entries.length > max\n const limited = entries.slice(0, max)\n\n const output: Output = {\n path: dir,\n entries: limited,\n total: entries.length,\n truncated,\n }\n\n yield {\n type: 'result',\n resultForAssistant: this.renderResultForAssistant(output),\n data: output,\n }\n },\n renderResultForAssistant(output) {\n if (output.entries.length === 0) return 'No entries found'\n const suffix = output.truncated\n ? `\\n(Results are truncated. Showing ${output.entries.length}/${output.total}.)`\n : ''\n return `${output.entries.join('\\n')}${suffix}`\n },\n} satisfies Tool<typeof inputSchema, Output>\n", "export const TOOL_NAME_FOR_PROMPT = 'LS'\n\nexport const DESCRIPTION = `List directory contents.\n\nUsage:\n- Use LS to quickly inspect the contents of a directory.\n- Prefer LS over running \\`ls\\` via Bash when you only need a directory listing.\n- Set \\`all: true\\` to include dotfiles (like \\`ls -a\\`).\n`\n", "import { Box, Text } from 'ink'\nimport React from 'react'\nimport { existsSync } from 'fs'\nimport { z } from 'zod'\nimport { Tool } from '#core/tooling/Tool'\nimport { getCwd } from '#core/utils/state'\nimport { getAbsoluteAndRelativePaths, getAbsolutePath } from '#core/utils/file'\nimport { DESCRIPTION, TOOL_NAME_FOR_PROMPT } from './prompt'\nimport { hasReadPermission } from '#core/utils/permissions/filesystem'\nimport { relative } from 'path'\nimport { formatPagination, truncateToCharBudget } from './helpers'\nimport type { GrepToolOutput } from './types'\nimport { runGrepTool } from './execute'\n\nconst inputSchema = z.strictObject({\n pattern: z\n .string()\n .describe('The regular expression pattern to search for in file contents'),\n path: z\n .string()\n .optional()\n .describe(\n 'File or directory to search in (rg PATH). Defaults to current working directory.',\n ),\n glob: z\n .string()\n .optional()\n .describe(\n 'Glob pattern to filter files (e.g. \"*.js\", \"*.{ts,tsx}\") - maps to rg --glob',\n ),\n output_mode: z\n .enum(['content', 'files_with_matches', 'count'])\n .optional()\n .describe(\n 'Output mode: \"content\" shows matching lines (supports -A/-B/-C context, -n line numbers, head_limit), \"files_with_matches\" shows file paths (supports head_limit), \"count\" shows match counts (supports head_limit). Defaults to \"files_with_matches\".',\n ),\n '-B': z\n .number()\n .optional()\n .describe(\n 'Number of lines to show before each match (rg -B). Requires output_mode: \"content\", ignored otherwise.',\n ),\n '-A': z\n .number()\n .optional()\n .describe(\n 'Number of lines to show after each match (rg -A). Requires output_mode: \"content\", ignored otherwise.',\n ),\n '-C': z\n .number()\n .optional()\n .describe(\n 'Number of lines to show before and after each match (rg -C). Requires output_mode: \"content\", ignored otherwise.',\n ),\n '-n': z\n .boolean()\n .optional()\n .describe(\n 'Show line numbers in output (rg -n). Requires output_mode: \"content\", ignored otherwise. Defaults to true.',\n ),\n '-i': z.boolean().optional().describe('Case insensitive search (rg -i)'),\n type: z\n .string()\n .optional()\n .describe(\n 'File type to search (rg --type). Common types: js, py, rust, go, java, etc. More efficient than include for standard file types.',\n ),\n head_limit: z\n .number()\n .optional()\n .describe(\n 'Limit output to first N lines/entries, equivalent to \"| head -N\". Works across all output modes: content (limits output lines), files_with_matches (limits file paths), count (limits count entries). Defaults based on \"cap\" experiment value: 0 (unlimited), 20, or 100.',\n ),\n offset: z\n .number()\n .optional()\n .describe(\n 'Skip first N lines/entries before applying head_limit, equivalent to \"| tail -n +N | head -N\". Works across all output modes. Defaults to 0.',\n ),\n multiline: z\n .boolean()\n .optional()\n .describe(\n 'Enable multiline mode where . matches newlines and patterns can span lines (rg -U --multiline-dotall). Default: false.',\n ),\n})\n\ntype Input = typeof inputSchema\ntype Output = GrepToolOutput\n\nexport const GrepTool = {\n name: TOOL_NAME_FOR_PROMPT,\n async description() {\n return DESCRIPTION\n },\n userFacingName() {\n return 'Search'\n },\n inputSchema,\n isReadOnly() {\n return true\n },\n isConcurrencySafe() {\n return true // GrepTool is read-only, safe for concurrent execution\n },\n async isEnabled() {\n return true\n },\n needsPermissions({ path }) {\n return !hasReadPermission(path || getCwd())\n },\n async prompt() {\n return DESCRIPTION\n },\n renderToolUseMessage(input: any, { verbose }: { verbose: boolean }) {\n const {\n pattern,\n path,\n glob,\n type,\n output_mode = 'files_with_matches',\n head_limit,\n } = input\n if (!pattern) return ''\n const parts = [`pattern: \"${pattern}\"`]\n if (path) {\n const { absolutePath, relativePath } = getAbsoluteAndRelativePaths(path)\n parts.push(`path: \"${verbose ? absolutePath : relativePath}\"`)\n }\n if (glob) parts.push(`glob: \"${glob}\"`)\n if (type) parts.push(`type: \"${type}\"`)\n if (output_mode !== 'files_with_matches') {\n parts.push(`output_mode: \"${output_mode}\"`)\n }\n if (head_limit !== undefined) parts.push(`head_limit: ${head_limit}`)\n return parts.join(', ')\n },\n renderToolUseRejectedMessage() {\n return null\n },\n renderToolResultMessage(output) {\n // Handle string content for backward compatibility\n if (typeof output === 'string') {\n // Convert string to Output type using tmpDeserializeOldLogResult if needed\n output = output as unknown as Output\n }\n\n return (\n <Box flexDirection=\"row\">\n <Text> \u23BF Found </Text>\n <Text bold>\n {output.mode === 'content'\n ? (output.numLines ?? 0)\n : output.mode === 'count'\n ? (output.numMatches ?? 0)\n : output.numFiles}{' '}\n </Text>\n <Text>\n {output.mode === 'content'\n ? (output.numLines ?? 0) === 1\n ? 'line'\n : 'lines'\n : output.mode === 'count'\n ? (output.numMatches ?? 0) === 1\n ? 'match'\n : 'matches'\n : output.numFiles === 1\n ? 'file'\n : 'files'}\n </Text>\n </Box>\n )\n },\n renderResultForAssistant(result: Output) {\n const pagination = formatPagination(\n result.appliedLimit,\n result.appliedOffset,\n )\n\n if (result.mode === 'content') {\n const base = truncateToCharBudget(result.content || 'No matches found')\n return pagination\n ? `${base}\\n\\n[Showing results with pagination = ${pagination}]`\n : base\n }\n\n if (result.mode === 'count') {\n const base = truncateToCharBudget(result.content || 'No matches found')\n const numMatches = result.numMatches ?? 0\n const numFiles = result.numFiles ?? 0\n return (\n base +\n `\\n\\nFound ${numMatches} total ${numMatches === 1 ? 'occurrence' : 'occurrences'} across ${numFiles} ${numFiles === 1 ? 'file' : 'files'}.` +\n (pagination ? ` with pagination = ${pagination}` : '')\n )\n }\n\n // files_with_matches\n if (result.numFiles === 0) return 'No files found'\n const header = `Found ${result.numFiles} file${result.numFiles === 1 ? '' : 's'}${pagination ? ` ${pagination}` : ''}\\n${result.filenames.join('\\n')}`\n return truncateToCharBudget(header)\n },\n async validateInput({ path }: any) {\n if (path) {\n const abs = getAbsolutePath(path)\n if (!abs || !existsSync(abs)) {\n return {\n result: false,\n message: `Path does not exist: ${path}`,\n errorCode: 1,\n }\n }\n }\n return { result: true }\n },\n async *call(input: any, toolUseContext: any) {\n const output = await runGrepTool({ input, toolUseContext })\n yield {\n type: 'result',\n data: output,\n resultForAssistant: this.renderResultForAssistant(output),\n }\n },\n} satisfies Tool<Input, Output>\n", "export const TOOL_NAME_FOR_PROMPT = 'Grep'\n\nexport const DESCRIPTION = `A powerful search tool built on ripgrep\n\n Usage:\n - ALWAYS use Grep for search tasks. NEVER invoke \\`grep\\` or \\`rg\\` as a Bash command. The Grep tool has been optimized for correct permissions and access.\n - Supports full regex syntax (e.g., \"log.*Error\", \"function\\\\s+\\\\w+\")\n - Filter files with glob parameter (e.g., \"*.js\", \"**/*.tsx\") or type parameter (e.g., \"js\", \"py\", \"rust\")\n - Output modes: \"content\" shows matching lines, \"files_with_matches\" shows only file paths (default), \"count\" shows match counts\n - Use Task tool for open-ended searches requiring multiple rounds\n - Pattern syntax: Uses ripgrep (not grep) - literal braces need escaping (use \\`interface\\\\{\\\\}\\` to find \\`interface{}\\` in Go code)\n - Multiline matching: By default patterns match within single lines only. For cross-line patterns like \\`struct \\\\{[\\\\s\\\\S]*?field\\`, use \\`multiline: true\\`\n`\n", "import { isAbsolute, relative } from 'path'\n\nimport { getCwd } from '#core/utils/state'\n\nexport const MAX_RESULT_CHARS = 20_000\nexport const EXCLUDED_DIRS = ['.git', '.svn', '.hg', '.bzr'] as const\n\nexport function paginate<T>(\n items: T[],\n limit: number | undefined,\n offset: number,\n): T[] {\n const windowed = offset > 0 ? items.slice(offset) : items\n if (limit === undefined || limit === 0) return windowed\n return windowed.slice(0, limit)\n}\n\nexport function truncateToCharBudget(text: string): string {\n if (text.length <= MAX_RESULT_CHARS) return text\n const head = text.slice(0, MAX_RESULT_CHARS)\n const truncatedLines = text.slice(MAX_RESULT_CHARS).split('\\n').length\n return `${head}\\n\\n... [${truncatedLines} lines truncated] ...`\n}\n\nexport function toProjectRelativeIfPossible(p: string): string {\n const projectRoot = getCwd()\n const rel = relative(projectRoot, p)\n if (!rel || rel === '') return p\n if (rel.startsWith('..')) return p\n if (isAbsolute(rel)) return p\n return rel\n}\n\nexport function formatPagination(\n limit: number | undefined,\n offset: number | undefined,\n): string {\n if (!limit && !offset) return ''\n return `limit: ${limit}, offset: ${offset ?? 0}`\n}\n\nexport function parseGlobString(glob: string): string[] {\n const parts = glob.split(/\\s+/).filter(Boolean)\n const expanded: string[] = []\n for (const part of parts) {\n if (part.includes('{') && part.includes('}')) {\n expanded.push(part)\n continue\n }\n expanded.push(...part.split(',').filter(Boolean))\n }\n return expanded\n}\n", "import { stat as statAsync } from 'fs/promises'\n\nimport { getAbsolutePath } from '#core/utils/file'\nimport { ripGrep } from '#core/utils/ripgrep'\nimport { getBunShellSandboxPlan } from '#core/utils/sandbox/bunShellSandboxPlan'\nimport { getCwd } from '#core/utils/state'\n\nimport {\n EXCLUDED_DIRS,\n paginate,\n parseGlobString,\n toProjectRelativeIfPossible,\n} from './helpers'\nimport type { GrepToolCallInput, GrepToolOutput } from './types'\nimport type { ToolUseContext } from '#core/tooling/Tool'\n\nexport async function runGrepTool(args: {\n input: GrepToolCallInput\n toolUseContext: ToolUseContext\n}): Promise<GrepToolOutput> {\n const {\n pattern,\n path,\n glob,\n type,\n output_mode = 'files_with_matches',\n '-B': before,\n '-A': after,\n '-C': context,\n '-n': lineNumbers = true,\n '-i': caseInsensitive = false,\n head_limit,\n offset = 0,\n multiline = false,\n } = args.input\n\n const start = Date.now()\n const absolutePath = getAbsolutePath(path) || getCwd()\n\n const baseArgs: string[] = ['--hidden']\n for (const dir of EXCLUDED_DIRS) {\n baseArgs.push('--glob', `!${dir}`)\n }\n baseArgs.push('--max-columns', '500')\n if (multiline) {\n baseArgs.push('-U', '--multiline-dotall')\n }\n if (caseInsensitive) {\n baseArgs.push('-i')\n }\n if (type) {\n baseArgs.push('--type', type)\n }\n\n const appliedLimit = head_limit !== undefined ? head_limit : undefined\n const appliedOffset = offset || 0\n\n if (glob) {\n for (const g of parseGlobString(glob)) {\n baseArgs.push('--glob', g)\n }\n }\n\n const rgArgs: string[] = [...baseArgs]\n if (output_mode === 'files_with_matches') rgArgs.push('-l')\n else if (output_mode === 'count') rgArgs.push('-c')\n\n if (lineNumbers && output_mode === 'content') rgArgs.push('-n')\n\n if (context !== undefined && output_mode === 'content') {\n rgArgs.push('-C', String(context))\n } else if (output_mode === 'content') {\n if (before !== undefined) rgArgs.push('-B', String(before))\n if (after !== undefined) rgArgs.push('-A', String(after))\n }\n\n if (String(pattern).startsWith('-')) rgArgs.push('-e', String(pattern))\n else rgArgs.push(String(pattern))\n\n const sandboxPlan = getBunShellSandboxPlan({\n command: 'rg',\n toolUseContext: args.toolUseContext,\n })\n const lines = await ripGrep(\n rgArgs,\n absolutePath,\n args.toolUseContext.abortController.signal,\n {\n sandbox: sandboxPlan.settings.enabled\n ? sandboxPlan.bunShellSandboxOptions\n : undefined,\n },\n )\n\n if (output_mode === 'content') {\n const rewritten = lines.map(line => {\n const idx = line.indexOf(':')\n if (idx > 0) {\n const filePart = line.slice(0, idx)\n const rest = line.slice(idx)\n return toProjectRelativeIfPossible(filePart) + rest\n }\n return line\n })\n\n const window = paginate(rewritten, appliedLimit, appliedOffset)\n return {\n mode: 'content',\n numFiles: 0,\n filenames: [],\n content: window.join('\\n'),\n numLines: window.length,\n ...(appliedLimit !== undefined ? { appliedLimit } : {}),\n ...(appliedOffset > 0 ? { appliedOffset } : {}),\n durationMs: Date.now() - start,\n }\n }\n\n if (output_mode === 'count') {\n const rewritten = lines.map(line => {\n const idx = line.lastIndexOf(':')\n if (idx > 0) {\n const filePart = line.slice(0, idx)\n const rest = line.slice(idx)\n return toProjectRelativeIfPossible(filePart) + rest\n }\n return line\n })\n\n const window = paginate(rewritten, appliedLimit, appliedOffset)\n let numMatches = 0\n let numFiles = 0\n for (const entry of window) {\n const idx = entry.lastIndexOf(':')\n if (idx > 0) {\n const countStr = entry.slice(idx + 1)\n const count = Number.parseInt(countStr, 10)\n if (!Number.isNaN(count)) {\n numMatches += count\n numFiles += 1\n }\n }\n }\n\n return {\n mode: 'count',\n numFiles,\n filenames: [],\n content: window.join('\\n'),\n numMatches,\n ...(appliedLimit !== undefined ? { appliedLimit } : {}),\n ...(appliedOffset > 0 ? { appliedOffset } : {}),\n durationMs: Date.now() - start,\n }\n }\n\n const stats = await Promise.all(\n lines.map(async filePath => {\n try {\n return await statAsync(filePath)\n } catch {\n return null\n }\n }),\n )\n\n const sorted = lines\n .map((filePath, i) => [filePath, stats[i]] as const)\n .sort((a, b) => {\n const diff = (b[1]?.mtimeMs ?? 0) - (a[1]?.mtimeMs ?? 0)\n if (diff !== 0) return diff\n return a[0].localeCompare(b[0])\n })\n .map(([filePath]) => filePath)\n\n const window = paginate(sorted, appliedLimit, appliedOffset).map(\n toProjectRelativeIfPossible,\n )\n\n return {\n mode: 'files_with_matches',\n filenames: window,\n numFiles: window.length,\n ...(appliedLimit !== undefined ? { appliedLimit } : {}),\n ...(appliedOffset > 0 ? { appliedOffset } : {}),\n durationMs: Date.now() - start,\n }\n}\n", "import { z } from 'zod'\nimport { Tool } from '#core/tooling/Tool'\nimport { BunShell } from '#runtime/shell'\nimport { DESCRIPTION, PROMPT, TOOL_NAME_FOR_PROMPT } from './prompt'\n\nconst inputSchema = z.strictObject({\n shell_id: z.string().describe('The ID of the background shell to kill'),\n})\n\ntype Input = z.infer<typeof inputSchema>\ntype Output = {\n message: string\n shell_id: string\n}\n\nexport const KillShellTool = {\n name: TOOL_NAME_FOR_PROMPT,\n async description() {\n return DESCRIPTION\n },\n userFacingName() {\n return 'Kill Shell'\n },\n inputSchema,\n isReadOnly() {\n return false\n },\n isConcurrencySafe() {\n return true\n },\n async isEnabled() {\n return true\n },\n needsPermissions() {\n return false\n },\n async prompt() {\n return PROMPT\n },\n renderToolUseMessage({ shell_id }: Input) {\n return `Kill shell: ${shell_id}`\n },\n renderResultForAssistant(output: Output) {\n return JSON.stringify(output)\n },\n async validateInput({ shell_id }: Input) {\n const bg = BunShell.getInstance().getBackgroundOutput(shell_id)\n if (!bg) {\n return {\n result: false,\n message: `No shell found with ID: ${shell_id}`,\n errorCode: 1,\n }\n }\n return { result: true }\n },\n async *call({ shell_id }: Input) {\n const bg = BunShell.getInstance().getBackgroundOutput(shell_id)\n if (!bg) {\n throw new Error(`No shell found with ID: ${shell_id}`)\n }\n\n const status = bg.killed\n ? 'killed'\n : bg.code === null\n ? 'running'\n : bg.code === 0\n ? 'completed'\n : 'failed'\n\n if (status !== 'running') {\n throw new Error(\n `Shell ${shell_id} is not running, so cannot be killed (status: ${status})`,\n )\n }\n\n const killed = BunShell.getInstance().killBackgroundShell(shell_id)\n const output: Output = {\n message: killed\n ? `Successfully killed shell: ${shell_id} (${bg.command})`\n : `No shell found with ID: ${shell_id}`,\n shell_id,\n }\n yield {\n type: 'result',\n data: output,\n resultForAssistant: this.renderResultForAssistant(output),\n }\n },\n} satisfies Tool<typeof inputSchema, Output>\n", "export const TOOL_NAME_FOR_PROMPT = 'KillShell'\nexport const DESCRIPTION = 'Kill a background bash shell by ID'\n\nexport const PROMPT = `\n- Kills a running background bash shell by its ID\n- Takes a shell_id parameter identifying the shell to kill\n- Returns a success or failure status \n- Use this tool when you need to terminate a long-running shell\n- Shell IDs can be found using the /tasks command\n`\n", "import { Box, Text } from 'ink'\nimport React from 'react'\nimport { z } from 'zod'\nimport type { Tool, ToolUseContext } from '#core/tooling/Tool'\nimport { getClients, type WrappedClient } from '#core/mcp/client'\nimport { ListResourcesResultSchema } from '@modelcontextprotocol/sdk/types.js'\nimport { DESCRIPTION, PROMPT, TOOL_NAME } from './prompt'\n\nconst inputSchema = z.strictObject({\n server: z\n .string()\n .optional()\n .describe('Optional server name to filter resources by'),\n})\n\ntype Input = z.infer<typeof inputSchema>\n\ntype OutputItem = {\n uri: string\n name: string\n mimeType?: string\n description?: string\n server: string\n}\n\ntype Output = OutputItem[]\n\nfunction isWrappedClient(value: unknown): value is WrappedClient {\n if (!value || typeof value !== 'object') return false\n const record = value as Record<string, unknown>\n if (typeof record.name !== 'string') return false\n if (record.type !== 'connected' && record.type !== 'failed') return false\n if (record.type === 'connected') {\n return typeof record.client === 'object' && record.client !== null\n }\n return true\n}\n\nasync function getMcpClients(\n context?: ToolUseContext,\n): Promise<WrappedClient[]> {\n const override = context?.options?.mcpClients\n if (Array.isArray(override) && override.every(isWrappedClient)) {\n return override\n }\n return await getClients()\n}\n\nexport const ListMcpResourcesTool = {\n name: TOOL_NAME,\n async description() {\n return DESCRIPTION\n },\n async prompt() {\n return PROMPT\n },\n inputSchema,\n userFacingName() {\n return 'listMcpResources'\n },\n async isEnabled() {\n return true\n },\n isReadOnly() {\n return true\n },\n isConcurrencySafe() {\n return true\n },\n needsPermissions() {\n return false\n },\n async validateInput({ server }: Input, context?: ToolUseContext) {\n if (!server) return { result: true }\n const clients = await getMcpClients(context)\n const found = clients.some(c => c.name === server)\n if (!found) {\n return {\n result: false,\n message: `Server \"${server}\" not found. Available servers: ${clients.map(c => c.name).join(', ')}`,\n errorCode: 1,\n }\n }\n return { result: true }\n },\n renderToolUseMessage({ server }: Input) {\n return server\n ? `List MCP resources from server \"${server}\"`\n : 'List all MCP resources'\n },\n renderToolResultMessage(output: Output) {\n return (\n <Box flexDirection=\"row\">\n <Text> \u23BF </Text>\n <Text bold>{output.length}</Text>\n <Text> resources</Text>\n </Box>\n )\n },\n renderResultForAssistant(output: Output) {\n return JSON.stringify(output)\n },\n async *call({ server }: Input, context: ToolUseContext) {\n const clients = await getMcpClients(context)\n const selected = server ? clients.filter(c => c.name === server) : clients\n if (server && selected.length === 0) {\n throw new Error(\n `Server \"${server}\" not found. Available servers: ${clients.map(c => c.name).join(', ')}`,\n )\n }\n\n const resources: OutputItem[] = []\n for (const wrapped of selected) {\n if (wrapped.type !== 'connected') continue\n try {\n let capabilities = wrapped.capabilities ?? null\n if (!capabilities) {\n try {\n capabilities = wrapped.client.getServerCapabilities() ?? null\n } catch {\n capabilities = null\n }\n }\n if (!capabilities?.resources) continue\n const result = await wrapped.client.request(\n { method: 'resources/list' },\n ListResourcesResultSchema,\n )\n if (!result.resources) continue\n resources.push(\n ...result.resources.map(r => ({\n ...r,\n server: wrapped.name,\n })),\n )\n } catch {\n // Best-effort: skip servers that fail to respond\n }\n }\n\n yield {\n type: 'result',\n data: resources,\n resultForAssistant: this.renderResultForAssistant(resources),\n }\n },\n} satisfies Tool<typeof inputSchema, Output>\n", "export const TOOL_NAME = 'ListMcpResourcesTool'\n\nexport const DESCRIPTION = `Lists available resources from configured MCP servers.\nEach resource object includes a 'server' field indicating which server it's from.\n\nUsage examples:\n- List all resources from all servers: \\`listMcpResources\\`\n- List resources from a specific server: \\`listMcpResources({ server: \"myserver\" })\\``\n\nexport const PROMPT = `List available resources from configured MCP servers.\nEach returned resource will include all standard MCP resource fields plus a 'server' field \nindicating which server the resource belongs to.\n\nParameters:\n- server (optional): The name of a specific MCP server to get resources from. If not provided,\n resources from all servers will be returned.`\n", "function isTruthyEnv(value: string | undefined): boolean {\n if (!value) return false\n return ['1', 'true', 'yes', 'on'].includes(value.trim().toLowerCase())\n}\n\nexport function isPackagedRuntime(): boolean {\n if (isTruthyEnv(process.env.KODE_PACKAGED)) return true\n\n // Heuristic fallback: if we're not running under bun/node, assume packaged binary.\n try {\n const exec = (process.execPath || '').split(/[\\\\/]/).pop()?.toLowerCase()\n if (!exec) return false\n if (exec === 'bun' || exec === 'bun.exe') return false\n if (exec === 'node' || exec === 'node.exe') return false\n return true\n } catch {\n return false\n }\n}\n\nexport type TruncateResult = {\n text: string\n truncated: boolean\n omittedLines: number\n omittedChars: number\n}\n\nexport function truncateTextForDisplay(\n text: string,\n options?: { maxLines?: number; maxChars?: number },\n): TruncateResult {\n const maxLines = options?.maxLines ?? 120\n const maxChars = options?.maxChars ?? 12_000\n\n const normalized = String(text ?? '')\n const lines = normalized.split(/\\r?\\n/)\n\n let workingLines = lines\n let omittedLines = 0\n if (maxLines > 0 && lines.length > maxLines) {\n workingLines = lines.slice(0, maxLines)\n omittedLines = lines.length - maxLines\n }\n\n let workingText = workingLines.join('\\n')\n let omittedChars = 0\n if (maxChars > 0 && workingText.length > maxChars) {\n omittedChars = workingText.length - maxChars\n workingText = workingText.slice(0, maxChars)\n }\n\n const truncated = omittedLines > 0 || omittedChars > 0\n if (!truncated) {\n return {\n text: workingText,\n truncated: false,\n omittedLines: 0,\n omittedChars: 0,\n }\n }\n\n const suffixParts: string[] = []\n if (omittedLines > 0) {\n suffixParts.push(`${omittedLines} lines`)\n }\n if (omittedChars > 0) {\n suffixParts.push(`${omittedChars} chars`)\n }\n\n const suffix = `\\n\\n... [truncated ${suffixParts.join(' \u00B7 ')}] ...`\n return {\n text: workingText + suffix,\n truncated: true,\n omittedLines,\n omittedChars,\n }\n}\n\nexport function maybeTruncateVerboseToolOutput(\n text: string,\n options?: { maxLines?: number; maxChars?: number },\n): { text: string; truncated: boolean } {\n const maxLinesEnv = Number(process.env.KODE_TOOL_OUTPUT_MAX_LINES ?? '')\n const maxCharsEnv = Number(process.env.KODE_TOOL_OUTPUT_MAX_CHARS ?? '')\n const envOverrides = {\n maxLines:\n Number.isFinite(maxLinesEnv) && maxLinesEnv > 0 ? maxLinesEnv : undefined,\n maxChars:\n Number.isFinite(maxCharsEnv) && maxCharsEnv > 0 ? maxCharsEnv : undefined,\n }\n\n const effective = {\n maxLines: envOverrides.maxLines ?? options?.maxLines,\n maxChars: envOverrides.maxChars ?? options?.maxChars,\n }\n\n const fullAllowed = isTruthyEnv(process.env.KODE_TOOL_OUTPUT_FULL)\n if (!isPackagedRuntime() || fullAllowed) {\n return { text: String(text ?? ''), truncated: false }\n }\n\n const result = truncateTextForDisplay(String(text ?? ''), effective)\n return { text: result.text, truncated: result.truncated }\n}\n", "import type { Tool, ToolUseContext } from '#core/tooling/Tool'\nimport { getAbsolutePath } from '#core/utils/file'\nimport { hasReadPermission } from '#core/utils/permissions/filesystem'\nimport { getCwd } from '#core/utils/state'\nimport { maybeTruncateVerboseToolOutput } from '#core/utils/toolOutputDisplay'\nimport { existsSync, readFileSync, statSync } from 'fs'\nimport { Box, Text } from 'ink'\nimport React from 'react'\nimport { z } from 'zod'\nimport { OPERATIONS } from './constants'\nimport { extractSymbolAtPosition, toProjectRelativeIfPossible } from './format'\nimport { summarizeToolResult } from './summary'\nimport { callLspTool, ensureLspManagerInitialized } from './call'\nimport { DESCRIPTION, PROMPT, TOOL_NAME_FOR_PROMPT } from './prompt'\n\nexport const inputSchema = z.strictObject({\n operation: z.enum(OPERATIONS).describe('The LSP operation to perform'),\n filePath: z.string().describe('The absolute or relative path to the file'),\n line: z\n .number()\n .int()\n .positive()\n .describe('The line number (1-based, as shown in editors)'),\n character: z\n .number()\n .int()\n .positive()\n .describe('The character offset (1-based, as shown in editors)'),\n})\n\nexport const outputSchema = z.object({\n operation: z\n .enum(OPERATIONS)\n .describe('The LSP operation that was performed'),\n result: z.string().describe('The formatted result of the LSP operation'),\n filePath: z.string().describe('The file path the operation was performed on'),\n resultCount: z\n .number()\n .int()\n .nonnegative()\n .optional()\n .describe('Number of results (definitions, references, symbols)'),\n fileCount: z\n .number()\n .int()\n .nonnegative()\n .optional()\n .describe('Number of files containing results'),\n})\n\nexport type Input = z.infer<typeof inputSchema>\nexport type Output = z.infer<typeof outputSchema>\n\nexport const LspTool = {\n name: TOOL_NAME_FOR_PROMPT,\n async description() {\n return DESCRIPTION\n },\n async prompt() {\n return PROMPT\n },\n inputSchema,\n userFacingName() {\n return 'LSP'\n },\n async isEnabled() {\n const manager = await ensureLspManagerInitialized()\n if (!manager) return false\n const servers = manager.getAllServers()\n if (servers.size === 0) return false\n return Array.from(servers.values()).some(s => s.state !== 'error')\n },\n isReadOnly() {\n return true\n },\n isConcurrencySafe() {\n return true\n },\n needsPermissions({ filePath }: Input) {\n const abs = getAbsolutePath(filePath) ?? filePath\n return !hasReadPermission(abs || getCwd())\n },\n async validateInput(input: Input) {\n const parsed = inputSchema.safeParse(input)\n if (!parsed.success) {\n return {\n result: false,\n message: `Invalid input: ${parsed.error.message}`,\n errorCode: 3,\n }\n }\n\n const absPath = getAbsolutePath(input.filePath) ?? input.filePath\n if (!existsSync(absPath)) {\n return {\n result: false,\n message: `File does not exist: ${input.filePath}`,\n errorCode: 1,\n }\n }\n try {\n if (!statSync(absPath).isFile()) {\n return {\n result: false,\n message: `Path is not a file: ${input.filePath}`,\n errorCode: 2,\n }\n }\n } catch (err) {\n const e = err instanceof Error ? err : new Error(String(err))\n return {\n result: false,\n message: `Cannot access file: ${input.filePath}. ${e.message}`,\n errorCode: 4,\n }\n }\n\n return { result: true }\n },\n renderToolUseMessage(input: Input, { verbose }: { verbose: boolean }) {\n const abs = getAbsolutePath(input.filePath) ?? input.filePath\n const filePathForDisplay = verbose ? abs : toProjectRelativeIfPossible(abs)\n const parts: string[] = []\n\n if (\n (input.operation === 'goToDefinition' ||\n input.operation === 'findReferences' ||\n input.operation === 'hover' ||\n input.operation === 'goToImplementation') &&\n input.filePath &&\n input.line !== undefined &&\n input.character !== undefined\n ) {\n try {\n const content = readFileSync(abs, 'utf8')\n const symbol = extractSymbolAtPosition(\n content.split('\\n'),\n input.line - 1,\n input.character - 1,\n )\n if (symbol) {\n parts.push(`operation: \"${input.operation}\"`)\n parts.push(`symbol: \"${symbol}\"`)\n parts.push(`in: \"${filePathForDisplay}\"`)\n return parts.join(', ')\n }\n } catch {\n // fall through\n }\n\n parts.push(`operation: \"${input.operation}\"`)\n parts.push(`file: \"${filePathForDisplay}\"`)\n parts.push(`position: ${input.line}:${input.character}`)\n return parts.join(', ')\n }\n\n parts.push(`operation: \"${input.operation}\"`)\n if (input.filePath) parts.push(`file: \"${filePathForDisplay}\"`)\n return parts.join(', ')\n },\n renderToolResultMessage(output: Output, { verbose }: { verbose: boolean }) {\n if (output.resultCount !== undefined && output.fileCount !== undefined) {\n const display = verbose\n ? maybeTruncateVerboseToolOutput(output.result, {\n maxLines: 120,\n maxChars: 20_000,\n })\n : null\n return (\n <Box flexDirection=\"column\">\n <Box flexDirection=\"row\">\n <Text> \u23BF </Text>\n {summarizeToolResult(\n output.operation,\n output.resultCount,\n output.fileCount,\n )}\n </Box>\n {display ? (\n <Box marginLeft={5}>\n <Text>{display.text}</Text>\n </Box>\n ) : null}\n </Box>\n )\n }\n\n return (\n <Box justifyContent=\"space-between\" width=\"100%\">\n <Box flexDirection=\"row\">\n <Text> \u23BF </Text>\n <Text>{output.result}</Text>\n </Box>\n </Box>\n )\n },\n renderResultForAssistant(output: Output) {\n return output.result\n },\n async *call(input: Input, context: ToolUseContext) {\n yield* callLspTool(input, context)\n },\n} satisfies Tool<typeof inputSchema, Output>\n", "export const OPERATIONS = [\n 'goToDefinition',\n 'findReferences',\n 'hover',\n 'documentSymbol',\n 'workspaceSymbol',\n 'goToImplementation',\n 'prepareCallHierarchy',\n 'incomingCalls',\n 'outgoingCalls',\n] as const\n\nexport type Operation = (typeof OPERATIONS)[number]\n\nexport const OPERATION_LABELS: Record<\n Operation,\n { singular: string; plural: string; special?: string }\n> = {\n goToDefinition: { singular: 'definition', plural: 'definitions' },\n findReferences: { singular: 'reference', plural: 'references' },\n documentSymbol: { singular: 'symbol', plural: 'symbols' },\n workspaceSymbol: { singular: 'symbol', plural: 'symbols' },\n hover: { singular: 'hover info', plural: 'hover info', special: 'available' },\n goToImplementation: { singular: 'implementation', plural: 'implementations' },\n prepareCallHierarchy: { singular: 'call item', plural: 'call items' },\n incomingCalls: { singular: 'caller', plural: 'callers' },\n outgoingCalls: { singular: 'callee', plural: 'callees' },\n}\n", "import { Text } from 'ink'\nimport React from 'react'\nimport type { Operation } from './constants'\nimport { OPERATION_LABELS } from './constants'\n\nexport function summarizeToolResult(\n operation: Operation,\n resultCount: number,\n fileCount: number,\n): React.ReactNode {\n const label = OPERATION_LABELS[operation] ?? {\n singular: 'result',\n plural: 'results',\n }\n const noun = resultCount === 1 ? label.singular : label.plural\n if (operation === 'hover' && resultCount > 0 && label.special) {\n return <Text>Hover info {label.special}</Text>\n }\n return (\n <Text>\n Found <Text bold>{resultCount}</Text> {noun}\n {fileCount > 1 ? (\n <>\n {' '}\n across <Text bold>{fileCount}</Text> files\n </>\n ) : null}\n </Text>\n )\n}\n", "export const TOOL_NAME_FOR_PROMPT = 'LSP'\n\nexport const PROMPT = `Interact with Language Server Protocol (LSP) servers to get code intelligence features.\n\nSupported operations:\n- goToDefinition: Find where a symbol is defined\n- findReferences: Find all references to a symbol\n- hover: Get hover information (documentation, type info) for a symbol\n- documentSymbol: Get all symbols (functions, classes, variables) in a document\n- workspaceSymbol: Search for symbols across the entire workspace\n- goToImplementation: Find implementations of an interface or abstract method\n- prepareCallHierarchy: Get call hierarchy item at a position (functions/methods)\n- incomingCalls: Find all functions/methods that call the function at a position\n- outgoingCalls: Find all functions/methods called by the function at a position\n\nAll operations require:\n- filePath: The file to operate on\n- line: The line number (1-based, as shown in editors)\n- character: The character offset (1-based, as shown in editors)\n\nNote: LSP servers must be configured for the file type. If no server is available, an error will be returned.`\n\nexport const DESCRIPTION = PROMPT\n", "import { Box, Text } from 'ink'\nimport * as React from 'react'\nimport { z } from 'zod'\nimport { type Tool } from '#core/tooling/Tool'\nimport { getTheme } from '#core/utils/theme'\nimport { DESCRIPTION, PROMPT } from './prompt'\nimport { OutputLine } from '#tools/tools/system/BashTool/OutputLine'\n\n// Allow any input object since MCP tools define their own schemas\nconst inputSchema = z.object({}).passthrough()\n\nexport const MCPTool = {\n isMcp: true,\n async isEnabled() {\n return true\n },\n isReadOnly() {\n return false\n },\n isConcurrencySafe() {\n return false // MCPTool can modify state through MCP calls, not safe for concurrent execution\n },\n // Overridden in mcpClient.ts\n name: 'mcp',\n // Overridden in mcpClient.ts\n async description() {\n return DESCRIPTION\n },\n // Overridden in mcpClient.ts\n async prompt() {\n return PROMPT\n },\n inputSchema,\n // Overridden in mcpClient.ts\n async *call() {\n yield {\n type: 'result',\n data: '',\n resultForAssistant: '',\n }\n },\n needsPermissions() {\n return true\n },\n renderToolUseMessage(input) {\n const entries = Object.entries(input)\n if (entries.length === 0) return null\n return entries\n .map(([key, value]) => `${key}: ${JSON.stringify(value)}`)\n .join(', ')\n },\n // Overridden in mcpClient.ts\n userFacingName: () => 'mcp',\n renderToolResultMessage(output) {\n const verbose = false // Set default value for verbose\n if (Array.isArray(output)) {\n return (\n <Box flexDirection=\"column\">\n {output.map((item, i) => {\n if (item.type === 'image') {\n return (\n <Box\n key={i}\n justifyContent=\"space-between\"\n overflowX=\"hidden\"\n width=\"100%\"\n >\n <Box flexDirection=\"row\">\n <Text> \u23BF </Text>\n <Text>[Image]</Text>\n </Box>\n </Box>\n )\n }\n const lines = item.text.split('\\n').length\n return (\n <OutputLine\n key={i}\n content={item.text}\n lines={lines}\n verbose={verbose}\n />\n )\n })}\n </Box>\n )\n }\n\n if (!output) {\n return (\n <Box justifyContent=\"space-between\" overflowX=\"hidden\" width=\"100%\">\n <Box flexDirection=\"row\">\n <Text> \u23BF </Text>\n <Text color={getTheme().secondaryText}>(No content)</Text>\n </Box>\n </Box>\n )\n }\n\n const lines = output.split('\\n').length\n return <OutputLine content={output} lines={lines} verbose={verbose} />\n },\n renderResultForAssistant(content) {\n return content\n },\n} satisfies Tool<typeof inputSchema, string>\n", "// Compatibility note: the base `mcp` tool's prompt/description are supplied by\n// the MCP client runtime and default to empty strings.\nexport const DESCRIPTION = ''\n\nexport const PROMPT = ''\n", "import { Box, Text } from 'ink'\nimport React from 'react'\nimport { z } from 'zod'\nimport type { Tool, ToolUseContext } from '#core/tooling/Tool'\nimport { getTheme } from '#core/utils/theme'\nimport { DESCRIPTION, getPrompt, TOOL_NAME_FOR_PROMPT } from './prompt'\n\nconst inputSchema = z.object({\n query: z\n .string()\n .describe(\n 'Query to find MCP tools. Use \"select:<tool_name>\" for direct selection, or keywords to search.',\n ),\n max_results: z\n .number()\n .optional()\n .default(5)\n .describe('Maximum number of results to return (default: 5)'),\n})\n\ntype Input = z.infer<typeof inputSchema>\n\ntype Output = {\n matches: string[]\n query: string\n total_mcp_tools: number\n}\n\ntype ToolReferenceBlock = {\n type: 'tool_reference'\n tool_name: string\n}\n\nfunction isToolLike(value: unknown): value is Tool {\n return (\n !!value &&\n typeof value === 'object' &&\n typeof (value as Tool).name === 'string' &&\n typeof (value as Tool).prompt === 'function'\n )\n}\n\nfunction getMcpToolsFromContext(context: ToolUseContext): Tool[] {\n const tools = context.options?.tools\n if (!Array.isArray(tools)) return []\n return tools.filter(isToolLike).filter(tool => tool.isMcp === true)\n}\n\nfunction signatureForTools(tools: Tool[]): string {\n return tools\n .map(tool => tool.name)\n .sort()\n .join(',')\n}\n\nconst promptCache = new Map<string, string>()\nlet lastMcpToolsSignature: string | null = null\n\nasync function getCachedToolPrompt(tool: Tool, tools: Tool[]): Promise<string> {\n const cached = promptCache.get(tool.name)\n if (cached !== undefined) return cached\n const prompt = await tool.prompt({ tools })\n promptCache.set(tool.name, prompt)\n return prompt\n}\n\nasync function keywordSearch(args: {\n query: string\n mcpTools: Tool[]\n tools: Tool[]\n maxResults: number\n}): Promise<string[]> {\n const keywords = args.query.toLowerCase().split(/\\s+/).filter(Boolean)\n\n const scored = await Promise.all(\n args.mcpTools.map(async tool => {\n const normalizedName = tool.name.toLowerCase().replace(/__/g, ' ')\n const normalizedPrompt = (\n await getCachedToolPrompt(tool, args.tools)\n ).toLowerCase()\n\n let score = 0\n for (const keyword of keywords) {\n if (normalizedName === keyword) score += 10\n else if (normalizedName.includes(keyword)) score += 5\n if (normalizedPrompt.includes(keyword)) score += 2\n }\n\n return { name: tool.name, score }\n }),\n )\n\n return scored\n .filter(item => item.score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, args.maxResults)\n .map(item => item.name)\n}\n\nexport const MCPSearchTool = {\n name: TOOL_NAME_FOR_PROMPT,\n async description() {\n return DESCRIPTION\n },\n async prompt(options?: { safeMode?: boolean; tools?: Tool[] }) {\n return getPrompt(options?.tools)\n },\n inputSchema,\n isReadOnly() {\n return true\n },\n isConcurrencySafe() {\n return true\n },\n async isEnabled() {\n return true\n },\n needsPermissions() {\n return false\n },\n userFacingName() {\n return TOOL_NAME_FOR_PROMPT\n },\n renderToolUseMessage(input: Input) {\n return `Search MCP tools: \"${input.query ?? '...'}\"`\n },\n renderToolUseRejectedMessage() {\n return null\n },\n renderToolResultMessage(output: Output) {\n const theme = getTheme()\n if (output.matches.length === 0) {\n return (\n <Box flexDirection=\"row\">\n <Text color={theme.text}>\u00A0\u00A0\u23BF \u00A0</Text>\n <Text dimColor>No matching MCP tools found</Text>\n </Box>\n )\n }\n return (\n <Box flexDirection=\"row\">\n <Text color={theme.text}>\u00A0\u00A0\u23BF \u00A0</Text>\n <Text>\n Found <Text bold>{output.matches.length}</Text>{' '}\n {output.matches.length === 1 ? 'tool' : 'tools'}\n </Text>\n </Box>\n )\n },\n renderResultForAssistant(output: Output): ToolReferenceBlock[] {\n return output.matches.map(toolName => ({\n type: 'tool_reference',\n tool_name: toolName,\n }))\n },\n async *call({ query, max_results }: Input, context: ToolUseContext) {\n const tools = Array.isArray(context.options?.tools)\n ? context.options.tools.filter(isToolLike)\n : []\n const mcpTools = getMcpToolsFromContext(context)\n\n const nextSignature = signatureForTools(mcpTools)\n if (lastMcpToolsSignature !== nextSignature) {\n promptCache.clear()\n lastMcpToolsSignature = nextSignature\n }\n\n const selectMatch = query.match(/^select:(.+)$/i)\n if (selectMatch) {\n const wanted = selectMatch[1]?.trim()\n const found = wanted\n ? mcpTools.find(tool => tool.name === wanted)\n : undefined\n\n const output: Output = {\n matches: found ? [found.name] : [],\n query,\n total_mcp_tools: mcpTools.length,\n }\n\n yield {\n type: 'result',\n data: output,\n resultForAssistant: this.renderResultForAssistant(output),\n }\n return\n }\n\n const matches = await keywordSearch({\n query,\n mcpTools,\n tools,\n maxResults: max_results ?? 5,\n })\n\n const output: Output = {\n matches,\n query,\n total_mcp_tools: mcpTools.length,\n }\n\n yield {\n type: 'result',\n data: output,\n resultForAssistant: this.renderResultForAssistant(output),\n }\n },\n} satisfies Tool<typeof inputSchema, Output>\n", "import type { Tool } from '#core/tooling/Tool'\n\nexport const TOOL_NAME_FOR_PROMPT = 'MCPSearch'\n\nexport const DESCRIPTION =\n 'Search for or select MCP tools to make them available for use.'\n\nconst BASE_PROMPT = `Search for or select MCP tools to make them available for use.\n\n**MANDATORY PREREQUISITE - THIS IS A HARD REQUIREMENT**\n\nYou MUST use this tool to load MCP tools BEFORE calling them directly.\n\nThis is a BLOCKING REQUIREMENT - MCP tools listed below are NOT available until you load them using this tool.\n\n**Why this is non-negotiable:**\n- MCP tools are deferred and not loaded until discovered via this tool\n- Calling an MCP tool without first loading it will fail\n\n**Query modes:**\n\n1. **Direct selection** - Use \\`select:<tool_name>\\` when you know exactly which tool you need:\n - \"select:mcp__slack__read_channel\"\n - \"select:mcp__filesystem__list_directory\"\n - Returns just that tool if it exists\n\n2. **Keyword search** - Use keywords when you're unsure which tool to use:\n - \"list directory\" - find tools for listing directories\n - \"read file\" - find tools for reading files\n - \"slack message\" - find slack messaging tools\n - Returns up to 5 matching tools ranked by relevance\n\n**CORRECT Usage Patterns:**\n\n<example>\nUser: List files in the src directory\nAssistant: I can see mcp__filesystem__list_directory in the available tools. Let me select it.\n[Calls MCPSearch with query: \"select:mcp__filesystem__list_directory\"]\n[Calls the MCP tool]\n</example>\n\n<example>\nUser: I need to work with slack somehow\nAssistant: Let me search for slack tools.\n[Calls MCPSearch with query: \"slack\"]\nAssistant: Found several options including mcp__slack__read_channel.\n[Calls the MCP tool]\n</example>\n\n**INCORRECT Usage Pattern - NEVER DO THIS:**\n\n<bad-example>\nUser: Read my slack messages\nAssistant: [Directly calls mcp__slack__read_channel without loading it first]\nWRONG - You must load the tool FIRST using this tool\n</bad-example>`\n\nfunction getMcpToolNames(tools: Tool[] | undefined): string[] {\n if (!Array.isArray(tools)) return []\n return tools\n .filter(tool => tool?.isMcp === true)\n .map(tool => tool.name)\n .filter(Boolean)\n}\n\nexport function getPrompt(tools: Tool[] | undefined): string {\n const mcpToolNames = getMcpToolNames(tools)\n if (mcpToolNames.length === 0) return BASE_PROMPT\n\n return `${BASE_PROMPT}\n\nAvailable MCP tools (must be loaded before use):\n${mcpToolNames.join('\\n')}`\n}\n", "import { Box, Text } from 'ink'\nimport React from 'react'\nimport { z } from 'zod'\nimport type { Tool, ToolUseContext } from '#core/tooling/Tool'\nimport { getClients, type WrappedClient } from '#core/mcp/client'\nimport { ReadResourceResultSchema } from '@modelcontextprotocol/sdk/types.js'\nimport { DESCRIPTION, PROMPT, TOOL_NAME } from './prompt'\n\nconst inputSchema = z.strictObject({\n server: z.string().describe('The MCP server name'),\n uri: z.string().describe('The resource URI to read'),\n})\n\ntype Input = z.infer<typeof inputSchema>\n\ntype Output = {\n contents: Array<{\n uri: string\n mimeType?: string\n text?: string\n }>\n}\n\nfunction isWrappedClient(value: unknown): value is WrappedClient {\n if (!value || typeof value !== 'object') return false\n const record = value as Record<string, unknown>\n if (typeof record.name !== 'string') return false\n if (record.type !== 'connected' && record.type !== 'failed') return false\n if (record.type === 'connected') {\n return typeof record.client === 'object' && record.client !== null\n }\n return true\n}\n\nasync function getMcpClients(\n context?: ToolUseContext,\n): Promise<WrappedClient[]> {\n const override = context?.options?.mcpClients\n if (Array.isArray(override) && override.every(isWrappedClient)) {\n return override\n }\n return await getClients()\n}\n\nexport const ReadMcpResourceTool = {\n name: TOOL_NAME,\n async description() {\n return DESCRIPTION\n },\n async prompt() {\n return PROMPT\n },\n inputSchema,\n userFacingName() {\n return 'readMcpResource'\n },\n async isEnabled() {\n return true\n },\n isReadOnly() {\n return true\n },\n isConcurrencySafe() {\n return true\n },\n needsPermissions() {\n return false\n },\n async validateInput({ server }: Input, context?: ToolUseContext) {\n const clients = await getMcpClients(context)\n const match = clients.find(c => c.name === server)\n if (!match) {\n return {\n result: false,\n message: `Server \"${server}\" not found. Available servers: ${clients.map(c => c.name).join(', ')}`,\n errorCode: 1,\n }\n }\n if (match.type !== 'connected') {\n return {\n result: false,\n message: `Server \"${server}\" is not connected`,\n errorCode: 2,\n }\n }\n let capabilities = match.capabilities ?? null\n if (!capabilities) {\n try {\n capabilities = match.client.getServerCapabilities() ?? null\n } catch {\n capabilities = null\n }\n }\n if (!capabilities?.resources) {\n return {\n result: false,\n message: `Server \"${server}\" does not support resources`,\n errorCode: 3,\n }\n }\n return { result: true }\n },\n renderToolUseMessage({ server, uri }: Input) {\n if (!server || !uri) return null\n return `Read resource \"${uri}\" from server \"${server}\"`\n },\n renderToolResultMessage(output: Output) {\n const count = output.contents?.length ?? 0\n return (\n <Box flexDirection=\"row\">\n <Text> \u23BF </Text>\n <Text bold>Read MCP resource</Text>\n <Text>{count ? ` (${count} part${count === 1 ? '' : 's'})` : ''}</Text>\n </Box>\n )\n },\n renderResultForAssistant(output: Output) {\n return JSON.stringify(output)\n },\n async *call({ server, uri }: Input, context: ToolUseContext) {\n const clients = await getMcpClients(context)\n const match = clients.find(c => c.name === server)\n if (!match) {\n throw new Error(\n `Server \"${server}\" not found. Available servers: ${clients.map(c => c.name).join(', ')}`,\n )\n }\n if (match.type !== 'connected') {\n throw new Error(`Server \"${server}\" is not connected`)\n }\n let capabilities = match.capabilities ?? null\n if (!capabilities) {\n try {\n capabilities = match.client.getServerCapabilities() ?? null\n } catch {\n capabilities = null\n }\n }\n if (!capabilities?.resources) {\n throw new Error(`Server \"${server}\" does not support resources`)\n }\n const result = (await match.client.request(\n { method: 'resources/read', params: { uri } },\n ReadResourceResultSchema,\n )) as Output\n yield {\n type: 'result',\n data: result,\n resultForAssistant: this.renderResultForAssistant(result),\n }\n },\n} satisfies Tool<typeof inputSchema, Output>\n", "export const TOOL_NAME = 'ReadMcpResourceTool'\n\nexport const DESCRIPTION = `Reads a specific resource from an MCP server.\n- server: The name of the MCP server to read from\n- uri: The URI of the resource to read\n\nUsage examples:\n- Read a resource from a server: \\`readMcpResource({ server: \"myserver\", uri: \"my-resource-uri\" })\\``\n\nexport const PROMPT = `Reads a specific resource from an MCP server, identified by server name and resource URI.\n\nParameters:\n- server (required): The name of the MCP server from which to read the resource\n- uri (required): The URI of the resource to read`\n", "import { z } from 'zod'\nimport { Tool } from '#core/tooling/Tool'\nimport type { Message } from '#core/query'\nimport { createUserMessage } from '#core/utils/messages'\nimport { callTaskTool } from '#tools/tools/ai/TaskTool/call'\nimport type {\n Output as TaskToolOutput,\n TaskModel,\n} from '#tools/tools/ai/TaskTool/schema'\nimport { TOOL_NAME_FOR_PROMPT } from './prompt'\nimport {\n findCommand,\n getCommandAllowedToolsFromContext,\n getCommandFlags,\n getCommandOverrides,\n parseSlashCommand,\n} from './utils'\n\nconst inputSchema = z.object({\n command: z\n .string()\n .describe(\n 'The slash command to execute with its arguments, e.g., \"/review-pr 123\"',\n ),\n})\n\ntype Input = z.infer<typeof inputSchema>\ntype InlineOutput = {\n success: boolean\n commandName: string\n status?: 'inline'\n}\n\ntype ForkedOutput = {\n success: boolean\n commandName: string\n status: 'forked'\n agentId: string\n result: string\n}\n\ntype Output = InlineOutput | ForkedOutput\n\ntype PromptLikeCommand = {\n type: 'prompt'\n name: string\n userFacingName?: () => string\n getPromptForCommand: (args: string) => Promise<Array<{ content: unknown }>>\n context?: string\n agent?: string\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n if (!value || typeof value !== 'object') return null\n return value as Record<string, unknown>\n}\n\nfunction isPromptLikeCommand(value: unknown): value is PromptLikeCommand {\n const record = asRecord(value)\n return (\n record?.type === 'prompt' &&\n typeof record.name === 'string' &&\n typeof record.getPromptForCommand === 'function'\n )\n}\n\nfunction isTextContentBlock(\n value: unknown,\n): value is { type: 'text'; text: string } {\n const record = asRecord(value)\n return record?.type === 'text' && typeof record.text === 'string'\n}\n\nfunction contentToText(content: unknown): string {\n if (typeof content === 'string') return content\n if (!Array.isArray(content)) return ''\n return content\n .map(b => (isTextContentBlock(b) ? b.text : ''))\n .join('\\n')\n .trim()\n}\n\nfunction getCommandName(cmd: PromptLikeCommand): string {\n const userFacing =\n typeof cmd.userFacingName === 'function' ? cmd.userFacingName() : ''\n return userFacing || cmd.name\n}\n\nfunction getCommandContext(cmd: unknown): 'fork' | undefined {\n const record = asRecord(cmd)\n return record?.context === 'fork' ? 'fork' : undefined\n}\n\nfunction getCommandAgent(cmd: unknown): string | undefined {\n const record = asRecord(cmd)\n const raw = record?.agent\n if (typeof raw !== 'string') return undefined\n const trimmed = raw.trim()\n return trimmed ? trimmed : undefined\n}\n\nfunction getRawModelSetting(cmd: unknown): string | undefined {\n const record = asRecord(cmd)\n return typeof record?.model === 'string' ? record.model : undefined\n}\n\nfunction toTaskToolModel(rawModel: string | undefined): TaskModel | undefined {\n if (!rawModel) return undefined\n const trimmed = rawModel.trim()\n if (!trimmed || trimmed === 'inherit') return undefined\n if (trimmed === 'haiku' || trimmed === 'quick') return 'haiku'\n if (trimmed === 'sonnet' || trimmed === 'task') return 'sonnet'\n if (trimmed === 'opus' || trimmed === 'main') return 'opus'\n return undefined\n}\n\nfunction mergeUniqueStrings(a: unknown, b: string[]): string[] {\n const left = Array.isArray(a) ? a.filter(x => typeof x === 'string') : []\n return [...new Set([...left, ...b])]\n}\n\nexport const SlashCommandTool = {\n name: TOOL_NAME_FOR_PROMPT,\n async description(input?: Input) {\n const command = input?.command\n return command\n ? `Execute slash command: ${command}`\n : 'Execute a slash command'\n },\n userFacingName() {\n return 'SlashCommand'\n },\n inputSchema,\n isReadOnly() {\n return false\n },\n isConcurrencySafe() {\n return false\n },\n async isEnabled() {\n return true\n },\n needsPermissions() {\n return true\n },\n async prompt() {\n return `Execute a slash command within the main conversation\n\nHow slash commands work:\nWhen you use this tool or when a user types a slash command, you will see <command-message>{name} is running\u2026</command-message> followed by the expanded prompt. For example, if .kode/commands/foo.md contains \"Print today's date\", then /foo expands to that prompt in the next message. (Legacy compatibility: .claude/commands/*.md is also supported.)\n\nUsage:\n- \\`command\\` (required): The slash command to execute, including any arguments\n- Example: \\`command: \"/review-pr 123\"\\`\n\nIMPORTANT: Only use this tool for custom slash commands that are available in the current host. Do NOT use for:\n- Built-in CLI commands (like /help, /clear, etc.)\n- Commands you think might exist but are not available\n\nNotes:\n- When a user requests multiple slash commands, execute each one sequentially and check for <command-message>{name} is running\u2026</command-message> to verify each has been processed\n- Do not invoke a command that is already running. For example, if you see <command-message>foo is running\u2026</command-message>, do NOT use this tool with \"/foo\" - process the expanded prompt in the following message\n- If a user's command is not available, ask them to check the slash command file and consult the docs.\n`\n },\n renderToolUseMessage({ command }: Input, _options: { verbose: boolean }) {\n return command || ''\n },\n renderResultForAssistant(output: Output) {\n if ('status' in output && output.status === 'forked') {\n const result = (output.result || '').trim()\n const resultBlock = result ? `\\n\\nResult:\\n${result}` : ''\n return `Slash command \"/${output.commandName}\" completed (forked execution).${resultBlock}\\n\\nAgent ID: ${output.agentId}`\n }\n return `Launching command: /${output.commandName}`\n },\n async validateInput({ command }: Input, context) {\n const parsed = parseSlashCommand(command)\n if (!parsed) {\n return {\n result: false,\n message: `Invalid slash command format: ${command}`,\n errorCode: 1,\n }\n }\n\n const commands = Array.isArray(context?.options?.commands)\n ? context.options.commands\n : []\n\n const cmd = findCommand(parsed.commandName, commands)\n if (!cmd) {\n return {\n result: false,\n message: `Unknown slash command: ${parsed.commandName}`,\n errorCode: 2,\n }\n }\n\n const flags = getCommandFlags(cmd)\n if (flags.disableModelInvocation) {\n return {\n result: false,\n message: `Slash command ${parsed.commandName} cannot be used with ${TOOL_NAME_FOR_PROMPT} tool due to disable-model-invocation`,\n errorCode: 4,\n }\n }\n\n if (flags.disableNonInteractive) {\n return {\n result: false,\n message: `Slash command ${parsed.commandName} cannot be used with ${TOOL_NAME_FOR_PROMPT} tool because it is non-interactive`,\n errorCode: 6,\n }\n }\n\n if (!isPromptLikeCommand(cmd)) {\n return {\n result: false,\n message: `Slash command ${parsed.commandName} is not a prompt-based command`,\n errorCode: 5,\n }\n }\n\n return { result: true }\n },\n async *call({ command }: Input, context) {\n const parsed = parseSlashCommand(command)\n if (!parsed) {\n throw new Error(`Invalid slash command format: ${command}`)\n }\n\n const commands = Array.isArray(context.options?.commands)\n ? context.options.commands\n : []\n const cmdUnknown = findCommand(parsed.commandName, commands)\n if (!cmdUnknown) {\n throw new Error(`Unknown slash command: ${parsed.commandName}`)\n }\n const flags = getCommandFlags(cmdUnknown)\n if (flags.disableModelInvocation) {\n throw new Error(\n `Slash command ${parsed.commandName} cannot be used with ${TOOL_NAME_FOR_PROMPT} tool due to disable-model-invocation`,\n )\n }\n if (flags.disableNonInteractive) {\n throw new Error(\n `Slash command ${parsed.commandName} cannot be used with ${TOOL_NAME_FOR_PROMPT} tool because it is non-interactive`,\n )\n }\n if (!isPromptLikeCommand(cmdUnknown)) {\n throw new Error(\n `Slash command ${parsed.commandName} is not a prompt-based command. Use /${parsed.commandName} directly in the main conversation.`,\n )\n }\n\n const cmd = cmdUnknown\n const prompt = await cmd.getPromptForCommand(parsed.args)\n\n const commandNameForMeta = getCommandName(cmd)\n const { progressMessage, allowedTools, model, maxThinkingTokens } =\n getCommandOverrides(cmd)\n\n if (getCommandContext(cmd) === 'fork') {\n const slashPrompt = prompt\n .map(msg => contentToText(msg.content))\n .join('\\n')\n .trim()\n\n const agentType = getCommandAgent(cmd) ?? 'general-purpose'\n const taskModel = toTaskToolModel(getRawModelSetting(cmd))\n\n const taskInput = {\n description: commandNameForMeta,\n prompt: slashPrompt,\n subagent_type: agentType,\n ...(taskModel ? { model: taskModel } : null),\n }\n\n let taskResult: TaskToolOutput | null = null\n const taskContext = {\n ...context,\n options: {\n ...(context.options ?? {}),\n forceForkContext: true,\n commandAllowedTools: mergeUniqueStrings(\n context.options?.commandAllowedTools,\n allowedTools,\n ),\n },\n } as any\n\n for await (const evt of callTaskTool(taskInput as any, taskContext)) {\n if (evt.type === 'progress') {\n yield { type: 'progress' as const, content: evt.content }\n continue\n }\n if (evt.type === 'result') {\n taskResult = evt.data as TaskToolOutput\n }\n }\n\n if (!taskResult) {\n throw new Error(\n `Forked slash command execution produced no result: ${parsed.commandName}`,\n )\n }\n\n const agentId = taskResult.agentId\n const resultText =\n taskResult.status === 'completed'\n ? taskResult.content\n .map(b => b.text)\n .join('\\n')\n .trim()\n : ''\n\n const output: ForkedOutput = {\n success: true,\n commandName: parsed.commandName,\n status: 'forked',\n agentId,\n result: resultText,\n }\n\n yield {\n type: 'result' as const,\n data: output,\n resultForAssistant: this.renderResultForAssistant(output),\n }\n return\n }\n\n const expandedMessages: Message[] = prompt.map(msg => {\n const userMessage = createUserMessage(contentToText(msg.content))\n userMessage.options = {\n ...userMessage.options,\n isCustomCommand: true,\n commandName: commandNameForMeta,\n commandArgs: parsed.args,\n }\n return userMessage\n })\n\n const metaMessage =\n createUserMessage(`<command-name>${commandNameForMeta}</command-name>\n<command-message>${commandNameForMeta} is ${progressMessage}\u2026</command-message>\n<command-args>${parsed.args}</command-args>`)\n\n const output: InlineOutput = {\n success: true,\n commandName: parsed.commandName,\n status: 'inline',\n }\n\n yield {\n type: 'result' as const,\n data: output,\n resultForAssistant: this.renderResultForAssistant(output),\n newMessages: [metaMessage, ...expandedMessages],\n contextModifier:\n allowedTools.length > 0 || model || maxThinkingTokens !== undefined\n ? {\n modifyContext(ctx) {\n const next = { ...ctx }\n\n if (allowedTools.length > 0) {\n const prev = getCommandAllowedToolsFromContext(next)\n next.options = {\n ...(next.options || {}),\n commandAllowedTools: [\n ...new Set([...prev, ...allowedTools]),\n ],\n }\n }\n\n if (model) {\n next.options = { ...(next.options || {}), model }\n }\n\n if (maxThinkingTokens !== undefined) {\n next.options = {\n ...(next.options || {}),\n maxThinkingTokens,\n }\n }\n\n return next\n },\n }\n : undefined,\n }\n },\n} satisfies Tool<typeof inputSchema, Output>\n", "import type { Message as ConversationMessage } from '#core/query'\n\nconst transcripts = new Map<string, ConversationMessage[]>()\n\nexport function saveAgentTranscript(\n agentId: string,\n messages: ConversationMessage[],\n): void {\n transcripts.set(agentId, messages)\n}\n\nexport function getAgentTranscript(\n agentId: string,\n): ConversationMessage[] | undefined {\n return transcripts.get(agentId)\n}\n", "import { type Tool } from '#core/tooling/Tool'\nimport { getTools, getReadOnlyTools } from '#tools'\nimport { FileWriteTool } from '#tools/tools/filesystem/FileWriteTool/FileWriteTool'\nimport { GlobTool } from '#tools/tools/filesystem/GlobTool/GlobTool'\nimport { FileReadTool } from '#tools/tools/filesystem/FileReadTool/FileReadTool'\nimport { getActiveAgents } from '#core/utils/agentLoader'\n\nconst TASK_TOOL_NAME = 'Task'\nconst TASK_OUTPUT_TOOL_NAME = 'TaskOutput'\n\nconst SUBAGENT_DISALLOWED_TOOL_NAMES = new Set<string>([\n 'Task',\n 'TaskOutput',\n 'KillShell',\n 'EnterPlanMode',\n 'ExitPlanMode',\n 'AskUserQuestion',\n])\n\nexport async function getTaskTools(safeMode: boolean): Promise<Tool[]> {\n // No recursive tasks, yet..\n return (await (!safeMode ? getTools() : getReadOnlyTools())).filter(\n tool => !SUBAGENT_DISALLOWED_TOOL_NAMES.has(tool.name),\n )\n}\n\nexport async function getPrompt(safeMode: boolean): Promise<string> {\n // Maintain compatibility with legacy agent packs and their tool lists.\n const agents = await getActiveAgents()\n\n // Format exactly as in original: (Tools: tool1, tool2)\n const agentDescriptions = agents\n .map(agent => {\n const toolsStr = Array.isArray(agent.tools)\n ? agent.tools.join(', ')\n : 'All tools'\n const properties = agent.forkContext\n ? 'Properties: access to current context; '\n : ''\n return `- ${agent.agentType}: ${agent.whenToUse} (${properties}Tools: ${toolsStr})`\n })\n .join('\\n')\n\n // Keep wording stable so shared legacy agent packs behave consistently.\n return `Launch a new agent to handle complex, multi-step tasks autonomously. \n\nThe ${TASK_TOOL_NAME} tool launches specialized agents (subprocesses) that autonomously handle complex tasks. Each agent type has specific capabilities and tools available to it.\n\nAvailable agent types and the tools they have access to:\n${agentDescriptions}\n\nWhen using the ${TASK_TOOL_NAME} tool, you must specify a subagent_type parameter to select which agent type to use.\n\nWhen NOT to use the ${TASK_TOOL_NAME} tool:\n- If you want to read a specific file path, use the ${FileReadTool.name} or ${GlobTool.name} tool instead of the ${TASK_TOOL_NAME} tool, to find the match more quickly\n- If you are searching for a specific class definition like \"class Foo\", use the ${GlobTool.name} tool instead, to find the match more quickly\n- If you are searching for code within a specific file or set of 2-3 files, use the ${FileReadTool.name} tool instead of the ${TASK_TOOL_NAME} tool, to find the match more quickly\n- Other tasks that are not related to the agent descriptions above\n\n\nUsage notes:\n- Always include a short description (3-5 words) summarizing what the agent will do\n- Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses\n- When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result.\n- You can optionally run agents in the background using the run_in_background parameter. When an agent runs in the background, you will need to use ${TASK_OUTPUT_TOOL_NAME} to retrieve its results once it's done. You can continue to work while background agents run - When you need their results to continue you can use ${TASK_OUTPUT_TOOL_NAME} in blocking mode to pause and wait for their results.\n- Agents can be resumed using the \\`resume\\` parameter by passing the agent ID from a previous invocation. When resumed, the agent continues with its full previous context preserved. When NOT resuming, each invocation starts fresh and you should provide a detailed task description with all necessary context.\n- When the agent is done, it will return a single message back to you along with its agent ID. You can use this ID to resume the agent later if needed for follow-up work.\n- Provide clear, detailed prompts so the agent can work autonomously and return exactly the information you need.\n- Agents with \"access to current context\" can see the full conversation history before the tool call. When using these agents, you can write concise prompts that reference earlier context (e.g., \"investigate the error discussed above\") instead of repeating information. The agent will receive all prior messages and understand the context.\n- The agent's outputs should generally be trusted\n- Clearly tell the agent whether you expect it to write code or just to do research (search, file reads, web fetches, etc.), since it is not aware of the user's intent\n- If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement.\n- If the user specifies that they want you to run agents \"in parallel\", you MUST send a single message with multiple ${TASK_TOOL_NAME} tool use content blocks. For example, if you need to launch both a code-reviewer agent and a test-runner agent in parallel, send a single message with both tool calls.\n\nExample usage:\n\n<example_agent_descriptions>\n\"code-reviewer\": use this agent after you are done writing a signficant piece of code\n\"greeting-responder\": use this agent when to respond to user greetings with a friendly joke\n</example_agent_description>\n\n<example>\nuser: \"Please write a function that checks if a number is prime\"\nassistant: Sure let me write a function that checks if a number is prime\nassistant: First let me use the ${FileWriteTool.name} tool to write a function that checks if a number is prime\nassistant: I'm going to use the ${FileWriteTool.name} tool to write the following code:\n<code>\nfunction isPrime(n) {\n if (n <= 1) return false\n for (let i = 2; i * i <= n; i++) {\n if (n % i === 0) return false\n }\n return true\n}\n</code>\n<commentary>\nSince a signficant piece of code was written and the task was completed, now use the code-reviewer agent to review the code\n</commentary>\nassistant: Now let me use the code-reviewer agent to review the code\nassistant: Uses the Task tool to launch the code-reviewer agent \n</example>\n\n<example>\nuser: \"Hello\"\n<commentary>\nSince the user is greeting, use the greeting-responder agent to respond with a friendly joke\n</commentary>\nassistant: \"I'm going to use the Task tool to launch the greeting-responder agent\"\n</example>`\n}\n", "import type {\n ToolResultBlockParam,\n ToolUseBlock,\n} from '@anthropic-ai/sdk/resources/index.mjs'\nimport { randomUUID } from 'crypto'\nimport { existsSync, readFileSync } from 'fs'\n\nimport type {\n Message as ConversationMessage,\n AssistantMessage,\n} from '#core/query'\nimport { getMessagesPath } from '#core/utils/log'\nimport { createUserMessage, type FullToolUseResult } from '#core/utils/messages'\n\nconst FORK_CONTEXT_TOOL_RESULT_TEXT = `### FORKING CONVERSATION CONTEXT ###\n### ENTERING SUB-AGENT ROUTINE ###\nEntered sub-agent context\n\nPLEASE NOTE: \n- The messages above this point are from the main thread prior to sub-agent execution. They are provided as context only.\n- Context messages may include tool_use blocks for tools that are not available in the sub-agent context. You should only use the tools specifically provided to you in the system prompt.\n- Only complete the specific sub-agent task you have been assigned below.`\n\ntype ToolUseLikeBlock = ToolUseBlock & {\n type: 'tool_use' | 'server_tool_use' | 'mcp_tool_use'\n}\n\nfunction isToolUseLikeBlock(block: unknown): block is ToolUseLikeBlock {\n if (!block || typeof block !== 'object') return false\n const type = (block as { type?: unknown }).type\n if (\n type !== 'tool_use' &&\n type !== 'server_tool_use' &&\n type !== 'mcp_tool_use'\n ) {\n return false\n }\n const id = (block as { id?: unknown }).id\n return typeof id === 'string' && id.length > 0\n}\n\nfunction isConversationMessage(value: unknown): value is ConversationMessage {\n if (!value || typeof value !== 'object') return false\n const type = (value as { type?: unknown }).type\n return type === 'assistant' || type === 'user' || type === 'progress'\n}\n\nfunction readJsonArrayFile(path: string): unknown[] | null {\n if (!existsSync(path)) return null\n try {\n const raw = readFileSync(path, 'utf8')\n const parsed: unknown = JSON.parse(raw)\n return Array.isArray(parsed) ? parsed : null\n } catch {\n return null\n }\n}\n\nfunction createForkContextToolResult(options: {\n toolUseId: string\n}): ConversationMessage {\n const toolResultBlock: ToolResultBlockParam = {\n type: 'tool_result',\n tool_use_id: options.toolUseId,\n content: FORK_CONTEXT_TOOL_RESULT_TEXT,\n }\n\n const toolUseResult: FullToolUseResult = {\n data: {\n status: 'sub_agent_entered',\n description: 'Entered sub-agent context',\n message: FORK_CONTEXT_TOOL_RESULT_TEXT,\n },\n resultForAssistant: FORK_CONTEXT_TOOL_RESULT_TEXT,\n }\n\n return createUserMessage([toolResultBlock], toolUseResult)\n}\n\nfunction createToolUseOnlyAssistantMessage(options: {\n message: AssistantMessage\n toolUseBlock: ToolUseLikeBlock\n}): AssistantMessage {\n return {\n ...options.message,\n uuid: randomUUID(),\n message: {\n ...options.message.message,\n content: [options.toolUseBlock],\n },\n }\n}\n\nexport function buildForkContextForAgent(options: {\n enabled: boolean\n prompt: string\n toolUseId: string | undefined\n messageLogName: string\n forkNumber: number\n}): {\n forkContextMessages: ConversationMessage[]\n promptMessages: ConversationMessage[]\n} {\n const userPromptMessage = createUserMessage(options.prompt)\n\n if (!options.enabled || !options.toolUseId) {\n return {\n forkContextMessages: [],\n promptMessages: [userPromptMessage],\n }\n }\n\n const mainPath = getMessagesPath(\n options.messageLogName,\n options.forkNumber,\n 0,\n )\n const raw = readJsonArrayFile(mainPath)\n const mainMessages = (raw ?? []).filter(isConversationMessage)\n if (mainMessages.length === 0) {\n return {\n forkContextMessages: [],\n promptMessages: [userPromptMessage],\n }\n }\n\n let toolUseMessageIndex = -1\n let toolUseMessage: AssistantMessage | null = null\n let taskToolUseBlock: ToolUseLikeBlock | null = null\n\n for (let i = 0; i < mainMessages.length; i++) {\n const msg = mainMessages[i]\n if (msg.type !== 'assistant') continue\n const blocks: unknown[] = Array.isArray(msg.message?.content)\n ? (msg.message.content as unknown[])\n : []\n const match = blocks.find(\n (b): b is ToolUseLikeBlock =>\n isToolUseLikeBlock(b) && b.id === options.toolUseId,\n )\n if (!match) continue\n toolUseMessageIndex = i\n toolUseMessage = msg\n taskToolUseBlock = match\n break\n }\n\n if (toolUseMessageIndex === -1 || !toolUseMessage || !taskToolUseBlock) {\n return {\n forkContextMessages: [],\n promptMessages: [userPromptMessage],\n }\n }\n\n const forkContextMessages = mainMessages.slice(0, toolUseMessageIndex) ?? []\n\n const toolUseOnlyAssistant = createToolUseOnlyAssistantMessage({\n message: toolUseMessage,\n toolUseBlock: taskToolUseBlock,\n })\n const forkContextToolResult = createForkContextToolResult({\n toolUseId: taskToolUseBlock.id,\n })\n\n return {\n forkContextMessages,\n promptMessages: [\n toolUseOnlyAssistant,\n forkContextToolResult,\n userPromptMessage,\n ],\n }\n}\n", "import type { TaskModel } from './schema'\n\nexport type ModelPointer = 'quick' | 'task' | 'main'\n\nexport function modelEnumToPointer(\n model?: TaskModel,\n): ModelPointer | undefined {\n if (!model) return undefined\n switch (model) {\n case 'haiku':\n return 'quick'\n case 'sonnet':\n return 'task'\n case 'opus':\n return 'main'\n }\n}\n\nexport function normalizeAgentModelName(\n model?: string,\n): string | 'inherit' | ModelPointer | undefined {\n if (!model) return undefined\n if (model === 'inherit') return 'inherit'\n if (model === 'haiku' || model === 'sonnet' || model === 'opus') {\n return modelEnumToPointer(model)\n }\n return model\n}\n", "export function getToolNameFromSpec(spec: string): string {\n const trimmed = spec.trim()\n if (!trimmed) return trimmed\n const match = trimmed.match(/^([^(]+)\\(([^)]+)\\)$/)\n if (!match) return trimmed\n const toolName = match[1]?.trim()\n const ruleContent = match[2]?.trim()\n if (!toolName || !ruleContent) return trimmed\n return toolName\n}\n", "import type { PermissionMode } from '#core/types/PermissionMode'\nimport type { ToolPermissionContext } from '#core/types/toolPermissionContext'\nimport type { AgentPermissionMode } from '#core/utils/agentLoader'\n\nexport function normalizeAgentPermissionMode(\n mode: AgentPermissionMode | undefined,\n): PermissionMode | undefined {\n if (!mode) return undefined\n if (mode === 'delegate') return 'default'\n if (\n mode === 'default' ||\n mode === 'acceptEdits' ||\n mode === 'plan' ||\n mode === 'bypassPermissions' ||\n mode === 'dontAsk'\n ) {\n return mode\n }\n return undefined\n}\n\nexport function applyAgentPermissionMode(\n base: ToolPermissionContext | undefined,\n options: {\n agentPermissionMode: PermissionMode | undefined\n safeMode: boolean\n },\n): ToolPermissionContext | undefined {\n if (!base) return base\n if (!options.agentPermissionMode) return base\n\n const rank = (mode: PermissionMode): number => {\n switch (mode) {\n case 'dontAsk':\n return 0\n case 'plan':\n return 1\n case 'default':\n return 2\n case 'acceptEdits':\n return 3\n case 'bypassPermissions':\n return 4\n }\n }\n\n let nextMode: PermissionMode = options.agentPermissionMode\n\n if (\n nextMode === 'bypassPermissions' &&\n (options.safeMode || base.isBypassPermissionsModeAvailable !== true)\n ) {\n nextMode = 'default'\n }\n\n // Subagents must not auto-escalate permission mode beyond the parent context.\n // They may narrow permissions (e.g. default -> plan), but must not loosen them\n // (e.g. plan -> acceptEdits/bypassPermissions) without an explicit user flow.\n if (rank(nextMode) > rank(base.mode)) return base\n\n if (nextMode === base.mode) return base\n return { ...base, mode: nextMode }\n}\n", "import { last } from 'lodash-es'\n\nimport type { TextBlock } from '@anthropic-ai/sdk/resources/index.mjs'\n\nimport type { Message as ConversationMessage } from '#core/query'\nimport {\n getLastAssistantMessageId,\n createAssistantMessage,\n} from '#core/utils/messages'\nimport {\n upsertBackgroundAgentTask,\n type BackgroundAgentTaskRuntime,\n} from '#core/utils/backgroundTasks'\nimport { saveAgentTranscript } from '#core/utils/agentTranscripts'\nimport { hasPermissionsToUseTool } from '#core/permissions'\nimport { appendTaskOutput, touchTaskOutputFile } from '#runtime/taskOutputStore'\n\nimport type { PreparedTaskToolRun } from './callTypes'\nimport type { Input, Output } from './schema'\nimport { asyncLaunchMessage } from './assistantText'\n\nfunction isTextBlock(block: unknown): block is TextBlock {\n return (\n Boolean(block) &&\n typeof block === 'object' &&\n (block as { type?: unknown }).type === 'text' &&\n typeof (block as { text?: unknown }).text === 'string'\n )\n}\n\nexport async function* callTaskToolBackground(\n input: Input,\n prepared: PreparedTaskToolRun,\n metadata?: {\n parentAgentId?: string\n parentToolUseId?: string\n subagentType?: string\n model?: string\n },\n): AsyncGenerator<{\n type: 'result'\n data: Output\n resultForAssistant: string\n}> {\n const bgAbortController = new AbortController()\n touchTaskOutputFile(prepared.agentId)\n\n const taskRecord: BackgroundAgentTaskRuntime = {\n type: 'async_agent',\n agentId: prepared.agentId,\n parentAgentId: metadata?.parentAgentId,\n parentToolUseId: metadata?.parentToolUseId,\n subagentType: metadata?.subagentType,\n model: metadata?.model,\n description: input.description,\n prompt: prepared.effectivePrompt,\n status: 'running',\n startedAt: Date.now(),\n messages: [...prepared.transcriptMessages],\n abortController: bgAbortController,\n done: Promise.resolve(),\n }\n\n taskRecord.done = (async () => {\n try {\n const bgMessages: ConversationMessage[] = [...prepared.messagesForQuery]\n const bgTranscriptMessages: ConversationMessage[] = [\n ...prepared.transcriptMessages,\n ]\n\n for await (const msg of prepared.queryFn(\n bgMessages,\n prepared.systemPrompt,\n prepared.context,\n hasPermissionsToUseTool,\n {\n abortController: bgAbortController,\n options: prepared.queryOptions,\n messageId: getLastAssistantMessageId(bgMessages),\n agentId: prepared.agentId,\n readFileTimestamps: prepared.readFileTimestamps,\n setToolJSX: () => {},\n },\n )) {\n bgMessages.push(msg)\n bgTranscriptMessages.push(msg)\n\n if (msg.type === 'assistant') {\n const content = msg.message.content\n const text =\n typeof content === 'string'\n ? content\n : Array.isArray(content)\n ? content\n .filter(isTextBlock)\n .map(b => b.text)\n .join('\\n')\n : ''\n if (text) appendTaskOutput(prepared.agentId, text.trimEnd() + '\\n')\n }\n\n taskRecord.messages = [...bgTranscriptMessages]\n upsertBackgroundAgentTask(taskRecord)\n }\n\n const lastAssistant = last(\n bgTranscriptMessages.filter(m => m.type === 'assistant'),\n )\n const content =\n lastAssistant?.type === 'assistant'\n ? lastAssistant.message.content.filter(isTextBlock)\n : []\n\n const resultText = content.map(b => b.text).join('\\n')\n\n if (taskRecord.status !== 'killed') {\n taskRecord.status = 'completed'\n taskRecord.completedAt = Date.now()\n taskRecord.resultText = resultText\n } else {\n taskRecord.completedAt = taskRecord.completedAt ?? Date.now()\n if (resultText) taskRecord.resultText = resultText\n appendTaskOutput(\n prepared.agentId,\n '\\n[task killed]\\n'.replace(/^\\n+/, ''),\n )\n }\n taskRecord.messages = [...bgTranscriptMessages]\n upsertBackgroundAgentTask(taskRecord)\n saveAgentTranscript(prepared.agentId, bgTranscriptMessages)\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e)\n\n if (taskRecord.status === 'killed' || bgAbortController.signal.aborted) {\n taskRecord.status = 'killed'\n taskRecord.completedAt = taskRecord.completedAt ?? Date.now()\n taskRecord.error = taskRecord.error ?? (message || 'Killed by user')\n appendTaskOutput(\n prepared.agentId,\n '\\n[task killed]\\n'.replace(/^\\n+/, ''),\n )\n } else {\n taskRecord.status = 'failed'\n taskRecord.completedAt = Date.now()\n taskRecord.error = message\n appendTaskOutput(\n prepared.agentId,\n `\\n[error] ${message}\\n`.replace(/^\\n+/, ''),\n )\n }\n upsertBackgroundAgentTask(taskRecord)\n }\n })()\n\n upsertBackgroundAgentTask(taskRecord)\n\n const output: Output = {\n status: 'async_launched',\n agentId: prepared.agentId,\n description: input.description,\n prompt: prepared.effectivePrompt,\n }\n\n yield {\n type: 'result',\n data: output,\n resultForAssistant: asyncLaunchMessage(prepared.agentId),\n }\n}\n", "export function asyncLaunchMessage(agentId: string): string {\n const toolName = 'TaskOutput'\n return `Async agent launched successfully.\nagentId: ${agentId} (This is an internal ID for your use, do not mention it to the user. Use this ID to retrieve results with ${toolName} when the agent finishes). \nThe agent is currently working in the background. If you have other tasks you you should continue working on them now. Wait to call ${toolName} until either:\n- If you want to check on the agent's progress - call ${toolName} with block=false to get an immediate update on the agent's status\n- If you run out of things to do and the agent is still running - call ${toolName} with block=true to idle and wait for the agent's result (do not use block=true unless you completely run out of things to do as it will waste time).`\n}\n", "import { last, memoize } from 'lodash-es'\n\nimport type { TextBlock } from '@anthropic-ai/sdk/resources/index.mjs'\n\nimport React from 'react'\n\nimport type { Message as ConversationMessage } from '#core/query'\nimport { hasPermissionsToUseTool } from '#core/permissions'\nimport type { SetToolJSXFn } from '#core/tooling/Tool'\nimport { saveAgentTranscript } from '#core/utils/agentTranscripts'\nimport {\n upsertBackgroundAgentTask,\n type BackgroundAgentTaskRuntime,\n} from '#core/utils/backgroundTasks'\nimport { countTokens } from '#core/utils/tokens'\nimport {\n getMessagesPath,\n getNextAvailableLogSidechainNumber,\n overwriteLog,\n} from '#core/utils/log'\nimport {\n createAssistantMessage,\n getLastAssistantMessageId,\n} from '#core/utils/messages'\nimport { appendTaskOutput, touchTaskOutputFile } from '#runtime/taskOutputStore'\nimport { BashToolRunInBackgroundOverlay } from '#tools/tools/system/BashTool/BashToolRunInBackgroundOverlay'\n\nimport { asyncLaunchMessage } from './assistantText'\nimport type { PreparedTaskToolRun } from './callTypes'\nimport type { Input, Output, TaskUsage } from './schema'\n\nfunction isTextBlock(block: unknown): block is TextBlock {\n return (\n Boolean(block) &&\n typeof block === 'object' &&\n (block as { type?: unknown }).type === 'text' &&\n typeof (block as { text?: unknown }).text === 'string'\n )\n}\n\nfunction getAssistantText(message: ConversationMessage): string {\n if (message.type !== 'assistant') return ''\n const content = message.message.content\n if (typeof content === 'string') return content\n if (!Array.isArray(content)) return ''\n return content\n .filter(isTextBlock)\n .map(b => b.text)\n .join('\\n')\n}\n\ntype ToolUseLikeBlock = {\n type: 'tool_use' | 'server_tool_use' | 'mcp_tool_use'\n name: string\n input?: unknown\n}\n\nfunction isToolUseLikeBlock(block: unknown): block is ToolUseLikeBlock {\n if (!block || typeof block !== 'object') return false\n const type = (block as { type?: unknown }).type\n if (\n type !== 'tool_use' &&\n type !== 'server_tool_use' &&\n type !== 'mcp_tool_use'\n ) {\n return false\n }\n const name = (block as { name?: unknown }).name\n return typeof name === 'string'\n}\n\nfunction isIteratorYieldResult<T, TReturn>(\n result: IteratorResult<T, TReturn>,\n): result is IteratorYieldResult<T> {\n return result.done !== true\n}\n\nfunction truncate(text: string, maxLen: number): string {\n const normalized = text.replace(/\\\\s+/g, ' ').trim()\n if (normalized.length <= maxLen) return normalized\n return `${normalized.slice(0, maxLen - 1)}\u2026`\n}\n\nfunction summarizeToolUse(name: string, rawInput: unknown): string {\n const input =\n rawInput && typeof rawInput === 'object'\n ? (rawInput as Record<string, unknown>)\n : {}\n switch (name) {\n case 'Read': {\n const filePath =\n (typeof input.file_path === 'string' && input.file_path) ||\n (typeof input.path === 'string' && input.path) ||\n ''\n return filePath ? `Read ${filePath}` : 'Read'\n }\n case 'Write': {\n const filePath =\n (typeof input.file_path === 'string' && input.file_path) ||\n (typeof input.path === 'string' && input.path) ||\n ''\n return filePath ? `Write ${filePath}` : 'Write'\n }\n case 'Edit':\n case 'MultiEdit': {\n const filePath =\n (typeof input.file_path === 'string' && input.file_path) ||\n (typeof input.path === 'string' && input.path) ||\n ''\n return filePath ? `${name} ${filePath}` : name\n }\n case 'Grep': {\n const pattern = typeof input.pattern === 'string' ? input.pattern : ''\n return pattern ? `Grep ${truncate(pattern, 80)}` : 'Grep'\n }\n case 'Glob': {\n const pattern =\n (typeof input.pattern === 'string' && input.pattern) ||\n (typeof input.glob === 'string' && input.glob) ||\n ''\n return pattern ? `Glob ${truncate(pattern, 80)}` : 'Glob'\n }\n case 'Bash': {\n const command = typeof input.command === 'string' ? input.command : ''\n return command ? `Bash ${truncate(command, 80)}` : 'Bash'\n }\n case 'WebFetch':\n case 'WebSearch': {\n const url = typeof input.url === 'string' ? input.url : ''\n const query = typeof input.query === 'string' ? input.query : ''\n if (url) return `${name} ${truncate(url, 100)}`\n if (query) return `${name} ${truncate(query, 100)}`\n return name\n }\n default:\n return name\n }\n}\n\nfunction normalizeUsage(rawUsage: unknown): TaskUsage {\n const usage =\n rawUsage && typeof rawUsage === 'object'\n ? (rawUsage as Record<string, unknown>)\n : {}\n\n const serverToolUse =\n usage.server_tool_use && typeof usage.server_tool_use === 'object'\n ? (usage.server_tool_use as Record<string, unknown>)\n : null\n\n const cacheCreation =\n usage.cache_creation && typeof usage.cache_creation === 'object'\n ? (usage.cache_creation as Record<string, unknown>)\n : null\n\n const serviceTier = usage.service_tier\n const serviceTierNormalized =\n serviceTier === 'standard' ||\n serviceTier === 'priority' ||\n serviceTier === 'batch'\n ? serviceTier\n : null\n\n return {\n input_tokens:\n typeof usage.input_tokens === 'number' ? usage.input_tokens : 0,\n output_tokens:\n typeof usage.output_tokens === 'number' ? usage.output_tokens : 0,\n cache_creation_input_tokens:\n typeof usage.cache_creation_input_tokens === 'number'\n ? usage.cache_creation_input_tokens\n : null,\n cache_read_input_tokens:\n typeof usage.cache_read_input_tokens === 'number'\n ? usage.cache_read_input_tokens\n : null,\n server_tool_use: serverToolUse\n ? {\n web_search_requests:\n typeof serverToolUse.web_search_requests === 'number'\n ? serverToolUse.web_search_requests\n : 0,\n web_fetch_requests:\n typeof serverToolUse.web_fetch_requests === 'number'\n ? serverToolUse.web_fetch_requests\n : 0,\n }\n : null,\n service_tier: serviceTierNormalized,\n cache_creation: cacheCreation\n ? {\n ephemeral_1h_input_tokens:\n typeof cacheCreation.ephemeral_1h_input_tokens === 'number'\n ? cacheCreation.ephemeral_1h_input_tokens\n : 0,\n ephemeral_5m_input_tokens:\n typeof cacheCreation.ephemeral_5m_input_tokens === 'number'\n ? cacheCreation.ephemeral_5m_input_tokens\n : 0,\n }\n : null,\n }\n}\n\nexport async function* callTaskToolForeground(\n input: Input,\n prepared: PreparedTaskToolRun,\n options?: {\n setToolJSX?: SetToolJSXFn\n backgroundMetadata?: {\n parentAgentId?: string\n parentToolUseId?: string\n subagentType?: string\n model?: string\n }\n },\n): AsyncGenerator<\n | { type: 'progress'; content: ConversationMessage }\n | {\n type: 'result'\n data: Output\n resultForAssistant: string | TextBlock[]\n }\n> {\n const getSidechainNumber = memoize(() =>\n getNextAvailableLogSidechainNumber(\n prepared.messageLogName,\n prepared.forkNumber,\n ),\n )\n\n const PROGRESS_THROTTLE_MS = 200\n const PROGRESS_INITIAL_DELAY_MS = 1800\n const MAX_RECENT_ACTIONS = 6\n let lastProgressEmitAt = 0\n let lastEmittedToolUseCount = 0\n const recentActions: string[] = []\n const setToolJSX = options?.setToolJSX\n\n let backgroundRequested = false\n let resolveBackgroundRequested: (() => void) | null = null\n const backgroundRequestedPromise = new Promise<void>(resolve => {\n resolveBackgroundRequested = resolve\n })\n\n const requestBackground = () => {\n if (backgroundRequested) return\n backgroundRequested = true\n resolveBackgroundRequested?.()\n }\n\n let backgrounded = false\n const runAbortController = new AbortController()\n const onParentAbort = () => {\n if (backgrounded) return\n runAbortController.abort()\n }\n prepared.abortController.signal.addEventListener('abort', onParentAbort)\n\n let overlayTimeout: ReturnType<typeof setTimeout> | null = null\n if (setToolJSX) {\n overlayTimeout = setTimeout(() => {\n if (backgrounded) return\n if (runAbortController.signal.aborted) return\n setToolJSX({\n jsx: React.createElement(BashToolRunInBackgroundOverlay, {\n onBackground: requestBackground,\n }),\n shouldHidePromptInput: false,\n })\n }, PROGRESS_INITIAL_DELAY_MS)\n overlayTimeout.unref?.()\n }\n\n touchTaskOutputFile(prepared.agentId)\n\n const addRecentAction = (action: string) => {\n const trimmed = action.trim()\n if (!trimmed) return\n recentActions.push(trimmed)\n if (recentActions.length > MAX_RECENT_ACTIONS) {\n recentActions.splice(0, recentActions.length - MAX_RECENT_ACTIONS)\n }\n }\n\n const renderProgressText = (toolUseCount: number): string => {\n const header = `${input.description || 'Task'}\u2026 (${toolUseCount} tool${toolUseCount === 1 ? '' : 's'})`\n if (recentActions.length === 0) return header\n const lines = recentActions.map(a => `- ${a}`)\n return [header, ...lines].join('\\\\n')\n }\n\n yield {\n type: 'progress',\n content: createAssistantMessage(\n `<tool-progress>${renderProgressText(0)}</tool-progress>`,\n ),\n }\n lastProgressEmitAt = Date.now()\n\n let toolUseCount = 0\n const recordMessage = (message: ConversationMessage, persistLog: boolean) => {\n prepared.messagesForQuery.push(message)\n prepared.transcriptMessages.push(message)\n\n if (persistLog) {\n overwriteLog(\n getMessagesPath(\n prepared.messageLogName,\n prepared.forkNumber,\n getSidechainNumber(),\n ),\n prepared.transcriptMessages.filter(m => m.type !== 'progress'),\n {\n conversationKey: `${prepared.messageLogName}:${prepared.forkNumber}`,\n },\n )\n }\n\n if (message.type === 'assistant') {\n const assistantText = getAssistantText(message)\n if (assistantText) {\n appendTaskOutput(prepared.agentId, assistantText.trimEnd() + '\\n')\n }\n\n for (const block of message.message.content) {\n if (!isToolUseLikeBlock(block)) continue\n toolUseCount += 1\n addRecentAction(summarizeToolUse(block.name, block.input))\n }\n }\n }\n\n const queryIterator = prepared\n .queryFn(\n prepared.messagesForQuery,\n prepared.systemPrompt,\n prepared.context,\n hasPermissionsToUseTool,\n {\n abortController: runAbortController,\n options: prepared.queryOptions,\n messageId: getLastAssistantMessageId(prepared.messagesForQuery),\n agentId: prepared.agentId,\n readFileTimestamps: prepared.readFileTimestamps,\n setToolJSX: () => {},\n },\n )\n [Symbol.asyncIterator]()\n\n let nextPromise = queryIterator.next()\n\n const startBackgroundTask = (\n firstNextPromise: Promise<IteratorResult<ConversationMessage, void>>,\n ): BackgroundAgentTaskRuntime => {\n const taskRecord: BackgroundAgentTaskRuntime = {\n type: 'async_agent',\n agentId: prepared.agentId,\n parentAgentId: options?.backgroundMetadata?.parentAgentId,\n parentToolUseId: options?.backgroundMetadata?.parentToolUseId,\n subagentType: options?.backgroundMetadata?.subagentType,\n model: options?.backgroundMetadata?.model,\n description: input.description,\n prompt: prepared.effectivePrompt,\n status: 'running',\n startedAt: prepared.startTime,\n messages: [...prepared.transcriptMessages],\n abortController: runAbortController,\n done: Promise.resolve(),\n }\n\n taskRecord.done = (async () => {\n try {\n let iterResult = await firstNextPromise\n while (isIteratorYieldResult(iterResult)) {\n recordMessage(iterResult.value, false)\n taskRecord.messages = [...prepared.transcriptMessages]\n upsertBackgroundAgentTask(taskRecord)\n iterResult = await queryIterator.next()\n }\n\n const lastAssistant = last(\n prepared.transcriptMessages.filter(m => m.type === 'assistant'),\n )\n const content =\n lastAssistant?.type === 'assistant'\n ? lastAssistant.message.content.filter(isTextBlock)\n : []\n const resultText = content.map(b => b.text).join('\\n')\n\n if (taskRecord.status !== 'killed') {\n taskRecord.status = 'completed'\n taskRecord.completedAt = Date.now()\n taskRecord.resultText = resultText\n } else {\n taskRecord.completedAt = taskRecord.completedAt ?? Date.now()\n if (resultText) taskRecord.resultText = resultText\n appendTaskOutput(\n prepared.agentId,\n '\\n[task killed]\\n'.replace(/^\\n+/, ''),\n )\n }\n\n taskRecord.messages = [...prepared.transcriptMessages]\n upsertBackgroundAgentTask(taskRecord)\n saveAgentTranscript(prepared.agentId, prepared.transcriptMessages)\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e)\n\n if (\n taskRecord.status === 'killed' ||\n runAbortController.signal.aborted\n ) {\n taskRecord.status = 'killed'\n taskRecord.completedAt = taskRecord.completedAt ?? Date.now()\n taskRecord.error = taskRecord.error ?? (message || 'Killed by user')\n appendTaskOutput(\n prepared.agentId,\n '\\n[task killed]\\n'.replace(/^\\n+/, ''),\n )\n } else {\n taskRecord.status = 'failed'\n taskRecord.completedAt = Date.now()\n taskRecord.error = message\n appendTaskOutput(\n prepared.agentId,\n `\\n[error] ${message}\\n`.replace(/^\\n+/, ''),\n )\n }\n\n taskRecord.messages = [...prepared.transcriptMessages]\n upsertBackgroundAgentTask(taskRecord)\n }\n })()\n\n upsertBackgroundAgentTask(taskRecord)\n return taskRecord\n }\n\n try {\n while (true) {\n const raced = await Promise.race([\n nextPromise.then(res => ({ kind: 'next' as const, res })),\n backgroundRequestedPromise.then(() => ({\n kind: 'background' as const,\n })),\n ])\n\n if (raced.kind === 'background') {\n backgrounded = true\n prepared.abortController.signal.removeEventListener(\n 'abort',\n onParentAbort,\n )\n if (overlayTimeout) clearTimeout(overlayTimeout)\n overlayTimeout = null\n\n startBackgroundTask(nextPromise)\n const output: Output = {\n status: 'async_launched',\n agentId: prepared.agentId,\n description: input.description,\n prompt: prepared.effectivePrompt,\n }\n\n yield {\n type: 'result',\n data: output,\n resultForAssistant: asyncLaunchMessage(prepared.agentId),\n }\n return\n }\n\n const iterResult = raced.res\n if (!isIteratorYieldResult(iterResult)) break\n recordMessage(iterResult.value, true)\n\n const now = Date.now()\n const hasNewToolUses = toolUseCount > lastEmittedToolUseCount\n const shouldEmit =\n hasNewToolUses &&\n (lastEmittedToolUseCount === 0 ||\n now - lastProgressEmitAt >= PROGRESS_THROTTLE_MS)\n if (shouldEmit) {\n yield {\n type: 'progress',\n content: createAssistantMessage(\n `<tool-progress>${renderProgressText(toolUseCount)}</tool-progress>`,\n ),\n }\n lastEmittedToolUseCount = toolUseCount\n lastProgressEmitAt = now\n }\n\n nextPromise = queryIterator.next()\n }\n } finally {\n if (overlayTimeout) clearTimeout(overlayTimeout)\n prepared.abortController.signal.removeEventListener('abort', onParentAbort)\n setToolJSX?.(null)\n }\n\n const lastAssistant = last(\n prepared.transcriptMessages.filter(m => m.type === 'assistant'),\n )\n if (!lastAssistant || lastAssistant.type !== 'assistant') {\n throw new Error('No assistant messages found')\n }\n\n const content = lastAssistant.message.content.filter(isTextBlock)\n\n const totalDurationMs = Date.now() - prepared.startTime\n const totalTokens = countTokens(prepared.transcriptMessages)\n const usage = normalizeUsage(lastAssistant.message.usage)\n\n const output: Output = {\n status: 'completed',\n agentId: prepared.agentId,\n prompt: prepared.effectivePrompt,\n content,\n totalToolUseCount: toolUseCount,\n totalDurationMs,\n totalTokens,\n usage,\n }\n const agentIdBlock: TextBlock = {\n type: 'text',\n text: `agentId: ${prepared.agentId} (for resuming to continue this agent's work if needed)`,\n citations: [],\n }\n\n yield {\n type: 'result',\n data: output,\n resultForAssistant: [...content, agentIdBlock],\n }\n}\n", "import { getAgentPrompt } from '#core/constants/prompts'\nimport { getContext } from '#core/context'\nimport { query } from '#core/query'\nimport type { ToolUseContext } from '#core/tooling/Tool'\nimport { getAvailableAgentTypes, getAgentByType } from '#core/utils/agentLoader'\nimport { generateAgentId } from '#core/utils/agentStorage'\nimport {\n getAgentTranscript,\n saveAgentTranscript,\n} from '#core/utils/agentTranscripts'\nimport { getCwd } from '#core/utils/state'\nimport { getMaxThinkingTokens } from '#core/utils/thinking'\nimport { createDefaultToolPermissionContext } from '#core/types/toolPermissionContext'\nimport { LEGACY_ENV } from '#core/compat/legacyEnv'\nimport { getKodeAgentSessionId } from '#protocol/utils/kodeAgentSessionId'\nimport { loadKodeAgentSidechainMessagesForResume } from '#protocol/utils/kodeAgentSessionLoad'\n\nimport { getTaskTools } from './prompt'\nimport { buildForkContextForAgent } from './forkContext'\nimport { normalizeAgentModelName, modelEnumToPointer } from './models'\nimport { getToolNameFromSpec } from './toolSpec'\nimport {\n applyAgentPermissionMode,\n normalizeAgentPermissionMode,\n} from './permissions'\nimport { callTaskToolBackground } from './callBackground'\nimport { callTaskToolForeground } from './callForeground'\nimport type { Input, Output } from './schema'\nimport type {\n PreparedTaskToolRun,\n QueryFn,\n TaskToolQueryOptions,\n} from './callTypes'\n\ntype TaskToolUseContext = ToolUseContext & {\n __testQuery?: QueryFn\n}\n\nexport async function* callTaskTool(\n input: Input,\n toolUseContext: TaskToolUseContext,\n): AsyncGenerator<\n | {\n type: 'progress'\n content: any\n normalizedMessages?: any[]\n tools?: any[]\n }\n | {\n type: 'result'\n data: Output\n resultForAssistant?: string | any[]\n newMessages?: unknown[]\n contextModifier?: {\n modifyContext: (ctx: ToolUseContext) => ToolUseContext\n }\n },\n void,\n unknown\n> {\n const startTime = Date.now()\n const options = toolUseContext.options ?? {}\n const safeMode = options.safeMode ?? false\n const forkNumber = options.forkNumber ?? 0\n const messageLogName = options.messageLogName ?? 'default'\n const verbose = options.verbose ?? false\n const parentModel = options.model\n\n const queryFn: QueryFn =\n typeof toolUseContext.__testQuery === 'function'\n ? toolUseContext.__testQuery\n : query\n\n const agentConfig = await getAgentByType(input.subagent_type)\n if (!agentConfig) {\n const available = await getAvailableAgentTypes()\n throw new Error(\n `Agent type '${input.subagent_type}' not found. Available agents: ${available.join(', ')}`,\n )\n }\n\n const effectivePrompt = input.prompt\n\n const normalizedAgentModel = normalizeAgentModelName(agentConfig.model)\n const defaultSubagentModel = 'task'\n const envSubagentModel =\n process.env.KODE_SUBAGENT_MODEL ??\n process.env[LEGACY_ENV.codeSubagentModel]\n const modelToUse: string =\n (typeof envSubagentModel === 'string' && envSubagentModel.trim()\n ? envSubagentModel.trim()\n : undefined) ||\n modelEnumToPointer(input.model) ||\n (normalizedAgentModel === 'inherit'\n ? parentModel || defaultSubagentModel\n : normalizedAgentModel) ||\n defaultSubagentModel\n\n const toolFilter = agentConfig.tools\n let tools = await getTaskTools(safeMode)\n if (toolFilter) {\n const isAllArray =\n Array.isArray(toolFilter) &&\n toolFilter.length === 1 &&\n toolFilter[0] === '*'\n if (toolFilter === '*' || isAllArray) {\n // Keep all tools\n } else if (Array.isArray(toolFilter)) {\n const allowedToolNames = new Set(\n toolFilter.map(getToolNameFromSpec).filter(Boolean),\n )\n tools = tools.filter(t => allowedToolNames.has(t.name))\n }\n }\n\n const disallowedTools = Array.isArray(agentConfig.disallowedTools)\n ? agentConfig.disallowedTools\n : []\n if (disallowedTools.length > 0) {\n const disallowedToolNames = new Set(\n disallowedTools.map(getToolNameFromSpec).filter(Boolean),\n )\n tools = tools.filter(t => !disallowedToolNames.has(t.name))\n }\n\n const agentId = input.resume || generateAgentId()\n let baseTranscript: any[] = []\n if (input.resume) {\n const cached = getAgentTranscript(input.resume)\n if (cached) {\n baseTranscript = cached.filter(m => m.type !== 'progress')\n } else {\n const loaded = loadKodeAgentSidechainMessagesForResume({\n cwd: getCwd(),\n sessionId: getKodeAgentSessionId(),\n agentId: input.resume,\n })\n if (loaded.length === 0) {\n throw new Error(`No transcript found for agent ID: ${input.resume}`)\n }\n baseTranscript = loaded\n saveAgentTranscript(input.resume, loaded as any)\n }\n }\n\n const { forkContextMessages, promptMessages } = buildForkContextForAgent({\n enabled:\n agentConfig.forkContext === true || options.forceForkContext === true,\n prompt: effectivePrompt,\n toolUseId: toolUseContext.toolUseId,\n messageLogName,\n forkNumber,\n })\n\n const transcriptMessages = [...(baseTranscript || []), ...promptMessages]\n const messagesForQuery = [...forkContextMessages, ...transcriptMessages]\n\n const [baseSystemPrompt, context, maxThinkingTokens] = await Promise.all([\n getAgentPrompt(),\n getContext(),\n getMaxThinkingTokens(messagesForQuery, {\n thinkingMode: options.thinkingMode,\n }),\n ])\n const systemPrompt =\n agentConfig.systemPrompt && agentConfig.systemPrompt.length > 0\n ? [...baseSystemPrompt, agentConfig.systemPrompt]\n : baseSystemPrompt\n\n const agentPermissionMode = normalizeAgentPermissionMode(\n agentConfig.permissionMode,\n )\n const baseToolPermissionContext =\n options.toolPermissionContext ??\n createDefaultToolPermissionContext({\n isBypassPermissionsModeAvailable: !safeMode,\n })\n const toolPermissionContext =\n applyAgentPermissionMode(baseToolPermissionContext, {\n agentPermissionMode,\n safeMode,\n }) ?? baseToolPermissionContext\n\n const queryOptions: TaskToolQueryOptions = {\n safeMode,\n forkNumber,\n messageLogName,\n tools,\n commands: [],\n verbose,\n permissionMode: toolPermissionContext.mode,\n toolPermissionContext,\n commandAllowedTools: options.commandAllowedTools,\n maxThinkingTokens,\n model: modelToUse,\n mcpClients: options.mcpClients,\n }\n\n const prepared: PreparedTaskToolRun = {\n queryFn,\n agentId,\n effectivePrompt,\n systemPrompt,\n context,\n messagesForQuery,\n transcriptMessages,\n queryOptions,\n messageLogName,\n forkNumber,\n abortController: toolUseContext.abortController,\n readFileTimestamps: toolUseContext.readFileTimestamps,\n startTime,\n }\n\n if (input.run_in_background) {\n yield* callTaskToolBackground(input, prepared, {\n parentAgentId: toolUseContext.agentId,\n parentToolUseId: toolUseContext.toolUseId,\n subagentType: input.subagent_type,\n model: modelToUse,\n })\n return\n }\n\n const setToolJSXMaybe = (toolUseContext as any).setToolJSX as unknown\n const setToolJSX =\n typeof setToolJSXMaybe === 'function' ? (setToolJSXMaybe as any) : undefined\n\n for await (const chunk of callTaskToolForeground(input, prepared, {\n setToolJSX,\n backgroundMetadata: {\n parentAgentId: toolUseContext.agentId,\n parentToolUseId: toolUseContext.toolUseId,\n subagentType: input.subagent_type,\n model: modelToUse,\n },\n })) {\n if (chunk.type === 'result') {\n saveAgentTranscript(prepared.agentId, prepared.transcriptMessages)\n }\n yield chunk\n }\n}\n", "export const TOOL_NAME_FOR_PROMPT = 'SlashCommand'\nexport const DESCRIPTION = `- Executes predefined project commands stored in .kode/commands/*.md (legacy: .claude/commands/*.md)\n- Input: command string (e.g., \"/test\" or \"/deploy staging\")\n- Only executes known commands; otherwise returns an error`\n", "export type ParsedSlashCommand = { commandName: string; args: string }\n\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n if (!value || typeof value !== 'object') return null\n return value as Record<string, unknown>\n}\n\nfunction stringArray(value: unknown): string[] {\n if (!Array.isArray(value)) return []\n return value.filter((item): item is string => typeof item === 'string')\n}\n\nexport function normalizeCommandModelName(model: unknown): string | undefined {\n if (typeof model !== 'string') return undefined\n const trimmed = model.trim()\n if (!trimmed || trimmed === 'inherit') return undefined\n if (trimmed === 'haiku') return 'quick'\n if (trimmed === 'sonnet') return 'task'\n if (trimmed === 'opus') return 'main'\n return trimmed\n}\n\nexport function parseSlashCommand(command: string): ParsedSlashCommand | null {\n const trimmed = command.trim()\n if (!trimmed.startsWith('/')) return null\n const withoutSlash = trimmed.slice(1)\n const spaceIdx = withoutSlash.indexOf(' ')\n const commandName =\n spaceIdx === -1\n ? withoutSlash.trim()\n : withoutSlash.slice(0, spaceIdx).trim()\n if (!commandName) return null\n const args = spaceIdx === -1 ? '' : withoutSlash.slice(spaceIdx + 1).trim()\n return { commandName, args }\n}\n\nexport function findCommand(\n commandName: string,\n commands: unknown[],\n): unknown | null {\n for (const c of commands) {\n const record = asRecord(c)\n if (!record) continue\n\n if (record.name === commandName) return c\n\n const userFacingName = record.userFacingName\n if (typeof userFacingName === 'function') {\n try {\n if (userFacingName.call(c) === commandName) return c\n } catch {}\n }\n\n if (Array.isArray(record.aliases) && record.aliases.includes(commandName)) {\n return c\n }\n }\n return null\n}\n\nexport function getCommandFlags(cmd: unknown): {\n disableModelInvocation: boolean\n disableNonInteractive: boolean\n} {\n const record = asRecord(cmd)\n return {\n disableModelInvocation: record?.disableModelInvocation === true,\n disableNonInteractive: record?.disableNonInteractive === true,\n }\n}\n\nexport function getCommandOverrides(cmd: unknown): {\n progressMessage: string\n allowedTools: string[]\n model: string | undefined\n maxThinkingTokens: number | undefined\n} {\n const record = asRecord(cmd)\n const progressMessage =\n typeof record?.progressMessage === 'string' && record.progressMessage.trim()\n ? record.progressMessage.trim()\n : 'running'\n\n const allowedTools = stringArray(record?.allowedTools)\n const model = normalizeCommandModelName(record?.model)\n const maxThinkingTokens =\n typeof record?.maxThinkingTokens === 'number'\n ? record.maxThinkingTokens\n : undefined\n\n return { progressMessage, allowedTools, model, maxThinkingTokens }\n}\n\nexport function getCommandAllowedToolsFromContext(ctx: unknown): string[] {\n const record = asRecord(ctx)\n const options = asRecord(record?.options)\n return stringArray(options?.commandAllowedTools)\n}\n", "import { z } from 'zod'\nimport { Tool } from '#core/tooling/Tool'\nimport type { Message } from '#core/query'\nimport { createUserMessage } from '#core/utils/messages'\nimport { callTaskTool } from '#tools/tools/ai/TaskTool/call'\nimport type {\n TaskModel,\n Output as TaskToolOutput,\n} from '#tools/tools/ai/TaskTool/schema'\nimport { TOOL_NAME_FOR_PROMPT } from './prompt'\nconst inputSchema = z.object({\n skill: z\n .string()\n .describe(\n 'The skill name (no arguments). Use a value from <available_skills>.',\n ),\n args: z\n .string()\n .optional()\n .describe('Optional arguments for the skill (freeform text)'),\n})\n\ntype Input = z.infer<typeof inputSchema>\ntype InlineOutput = {\n success: boolean\n commandName: string\n allowedTools?: string[]\n model?: string\n status?: 'inline'\n}\n\ntype ForkedOutput = {\n success: boolean\n commandName: string\n status: 'forked'\n agentId: string\n result: string\n}\n\ntype Output = InlineOutput | ForkedOutput\n\ntype PromptLikeCommand = {\n type: 'prompt'\n name: string\n userFacingName?: () => string\n aliases?: string[]\n getPromptForCommand: (args: string) => Promise<Array<{ content: unknown }>>\n context?: string\n agent?: string\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n if (!value || typeof value !== 'object') return null\n return value as Record<string, unknown>\n}\nfunction isTextContentBlock(\n value: unknown,\n): value is { type: 'text'; text: string } {\n const record = asRecord(value)\n return record?.type === 'text' && typeof record.text === 'string'\n}\nfunction contentToText(content: unknown): string {\n if (typeof content === 'string') return content\n if (!Array.isArray(content)) return ''\n return content\n .map(b => (isTextContentBlock(b) ? b.text : ''))\n .join('\\n')\n .trim()\n}\nfunction isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every(item => typeof item === 'string')\n}\n\nfunction isPromptLikeCommand(value: unknown): value is PromptLikeCommand {\n const record = asRecord(value)\n return (\n record?.type === 'prompt' &&\n typeof record.name === 'string' &&\n typeof record.getPromptForCommand === 'function'\n )\n}\n\nfunction getCommandName(cmd: PromptLikeCommand): string {\n const userFacing =\n typeof cmd.userFacingName === 'function' ? cmd.userFacingName() : ''\n return userFacing || cmd.name\n}\n\nfunction getDisableModelInvocation(cmd: unknown): boolean {\n const record = asRecord(cmd)\n return record?.disableModelInvocation === true\n}\n\nfunction getAllowedTools(cmd: unknown): string[] {\n const record = asRecord(cmd)\n return isStringArray(record?.allowedTools) ? record.allowedTools : []\n}\n\nfunction getCommandContext(cmd: unknown): 'fork' | undefined {\n const record = asRecord(cmd)\n return record?.context === 'fork' ? 'fork' : undefined\n}\n\nfunction getCommandAgent(cmd: unknown): string | undefined {\n const record = asRecord(cmd)\n const raw = record?.agent\n if (typeof raw !== 'string') return undefined\n const trimmed = raw.trim()\n return trimmed ? trimmed : undefined\n}\n\nfunction getModelSetting(cmd: unknown): string | undefined {\n const record = asRecord(cmd)\n return normalizeCommandModelName(record?.model)\n}\n\nfunction getRawModelSetting(cmd: unknown): string | undefined {\n const record = asRecord(cmd)\n return typeof record?.model === 'string' ? record.model : undefined\n}\n\nfunction getMaxThinkingTokens(cmd: unknown): number | undefined {\n const record = asRecord(cmd)\n return typeof record?.maxThinkingTokens === 'number'\n ? record.maxThinkingTokens\n : undefined\n}\n\nfunction normalizeCommandModelName(model: unknown): string | undefined {\n if (typeof model !== 'string') return undefined\n const trimmed = model.trim()\n if (!trimmed || trimmed === 'inherit') return undefined\n if (trimmed === 'haiku') return 'quick'\n if (trimmed === 'sonnet') return 'task'\n if (trimmed === 'opus') return 'main'\n return trimmed\n}\n\nfunction toTaskToolModel(rawModel: string | undefined): TaskModel | undefined {\n if (!rawModel) return undefined\n const trimmed = rawModel.trim()\n if (!trimmed || trimmed === 'inherit') return undefined\n if (trimmed === 'haiku' || trimmed === 'quick') return 'haiku'\n if (trimmed === 'sonnet' || trimmed === 'task') return 'sonnet'\n if (trimmed === 'opus' || trimmed === 'main') return 'opus'\n return undefined\n}\n\nfunction mergeUniqueStrings(a: unknown, b: string[]): string[] {\n const left = Array.isArray(a) ? a.filter(x => typeof x === 'string') : []\n return [...new Set([...left, ...b])]\n}\n\nexport const SkillTool = {\n name: TOOL_NAME_FOR_PROMPT,\n async description(input?: Input) {\n const skill = input?.skill\n return skill ? `Execute skill: ${skill}` : 'Execute a skill'\n },\n userFacingName() {\n return 'Skill'\n },\n inputSchema,\n isReadOnly() {\n return false\n },\n isConcurrencySafe() {\n return false\n },\n async isEnabled() {\n return true\n },\n needsPermissions() {\n return true\n },\n async prompt() {\n // Compatibility note: include a best-effort listing of available skills/commands,\n // truncated by a simple size budget.\n type CustomCommand = {\n type: 'prompt'\n name: string\n description: string\n isEnabled: boolean\n isHidden: boolean\n userFacingName: () => string\n filePath?: string\n scope?: 'user' | 'project' | string\n isSkill?: boolean\n disableModelInvocation?: boolean\n }\n\n const MAX_AVAILABLE_SKILLS_CHARS = 8000\n\n async function loadCommands(): Promise<CustomCommand[]> {\n try {\n const mod = await import('#cli-services/customCommands')\n if (typeof mod.loadCustomCommands !== 'function') return []\n const cmds = (await mod.loadCustomCommands()) as unknown\n if (!Array.isArray(cmds)) return []\n return cmds.filter((cmd): cmd is CustomCommand => {\n if (!cmd || typeof cmd !== 'object') return false\n const record = cmd as Record<string, unknown>\n return (\n record.type === 'prompt' &&\n typeof record.name === 'string' &&\n typeof record.description === 'string' &&\n typeof record.isEnabled === 'boolean' &&\n typeof record.isHidden === 'boolean' &&\n typeof record.userFacingName === 'function'\n )\n })\n } catch {\n return []\n }\n }\n\n function formatSkillBlock(cmd: CustomCommand): string {\n const name = cmd.userFacingName()\n const description = cmd.description\n const location = cmd.filePath ?? ''\n return `<skill>\n<name>\n${name}\n</name>\n<description>\n${description}\n</description>\n<location>\n${location}\n</location>\n</skill>`\n }\n\n function buildAvailableSkillsSection(cmds: CustomCommand[]): string {\n const eligible = cmds.filter(\n cmd => cmd.isEnabled && cmd.disableModelInvocation !== true,\n )\n\n const ordered = [...eligible].sort((a, b) => {\n const scopeRank = (scope: CustomCommand['scope']) =>\n scope === 'project' ? 0 : scope === 'user' ? 1 : 2\n const scopeDelta = scopeRank(a.scope) - scopeRank(b.scope)\n if (scopeDelta !== 0) return scopeDelta\n\n const skillDelta =\n (a.isSkill === true ? 0 : 1) - (b.isSkill === true ? 0 : 1)\n if (skillDelta !== 0) return skillDelta\n\n return a.userFacingName().localeCompare(b.userFacingName())\n })\n\n const blocks: string[] = []\n let totalChars = 0\n\n for (const cmd of ordered) {\n const block = formatSkillBlock(cmd)\n totalChars += block.length + 1\n if (totalChars > MAX_AVAILABLE_SKILLS_CHARS) break\n blocks.push(block)\n }\n\n const joined = blocks.join('\\n')\n const truncated =\n ordered.length > blocks.length\n ? `\\n<!-- Showing ${blocks.length} of ${ordered.length} skills due to token limits -->`\n : ''\n\n return `${joined}${truncated}`\n }\n\n const commands = await loadCommands()\n const availableSkills = buildAvailableSkillsSection(commands)\n\n return `Execute a skill within the main conversation\n\n<skills_instructions>\nWhen users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge.\n\nWhen users ask you to run a \"slash command\" or reference \"/<something>\" (e.g., \"/commit\", \"/review-pr\"), they are referring to a skill. Use this tool to invoke the corresponding skill.\n\n<example>\nUser: \"run /commit\"\nAssistant: [Calls Skill tool with skill: \"commit\"]\n</example>\n\nHow to invoke:\n- Use this tool with the skill name and optional arguments\n- Examples:\n - \\`skill: \"pdf\"\\` - invoke the pdf skill\n - \\`skill: \"commit\", args: \"-m 'Fix bug'\"\\` - invoke with arguments\n - \\`skill: \"review-pr\", args: \"123\"\\` - invoke with arguments\n - \\`skill: \"ms-office-suite:pdf\"\\` - invoke using fully qualified name\n\nImportant:\n- When a skill is relevant, you must invoke this tool IMMEDIATELY as your first action\n- NEVER just announce or mention a skill in your text response without actually calling this tool\n- This is a BLOCKING REQUIREMENT: invoke the relevant Skill tool BEFORE generating any other response about the task\n- Only use skills listed in <available_skills> below\n- Do not invoke a skill that is already running\n- Do not use this tool for built-in CLI commands (like /help, /clear, etc.)\n</skills_instructions>\n\n<available_skills>\n${availableSkills}\n</available_skills>\n`\n },\n renderToolUseMessage({ skill }: Input, _options: { verbose: boolean }) {\n return skill || ''\n },\n renderResultForAssistant(output: Output) {\n if ('status' in output && output.status === 'forked') {\n const result = (output.result || '').trim()\n const resultBlock = result ? `\\n\\nResult:\\n${result}` : ''\n return `Skill \"${output.commandName}\" completed (forked execution).${resultBlock}\\n\\nAgent ID: ${output.agentId}`\n }\n return `Launching skill: ${output.commandName}`\n },\n async validateInput({ skill }: Input, context) {\n const raw = skill.trim()\n if (!raw) {\n return {\n result: false,\n message: `Invalid skill format: ${skill}`,\n errorCode: 1,\n }\n }\n const skillName = raw.startsWith('/') ? raw.slice(1) : raw\n\n const commands = Array.isArray(context?.options?.commands)\n ? context.options.commands\n : []\n const cmd = findCommand(skillName, commands)\n if (!cmd) {\n return {\n result: false,\n message: `Unknown skill: ${skillName}. No matching skill is available in the current host.`,\n errorCode: 2,\n }\n }\n\n if (getDisableModelInvocation(cmd)) {\n return {\n result: false,\n message: `Skill ${skillName} cannot be used with ${TOOL_NAME_FOR_PROMPT} tool due to disable-model-invocation`,\n errorCode: 4,\n }\n }\n\n if (!isPromptLikeCommand(cmd)) {\n return {\n result: false,\n message: `Skill ${skillName} is not a prompt-based skill`,\n errorCode: 5,\n }\n }\n\n return { result: true }\n },\n async *call({ skill, args }: Input, context) {\n const raw = skill.trim()\n const skillName = raw.startsWith('/') ? raw.slice(1) : raw\n\n const commands = Array.isArray(context.options?.commands)\n ? context.options.commands\n : []\n const cmd = findCommand(skillName, commands)\n if (!cmd) {\n throw new Error(`Unknown skill: ${skillName}`)\n }\n if (getDisableModelInvocation(cmd)) {\n throw new Error(\n `Skill ${skillName} cannot be used with ${TOOL_NAME_FOR_PROMPT} tool due to disable-model-invocation`,\n )\n }\n if (!isPromptLikeCommand(cmd)) {\n throw new Error(`Skill ${skillName} is not a prompt-based skill`)\n }\n\n const allowedTools = getAllowedTools(cmd)\n const model = getModelSetting(cmd)\n const maxThinkingTokens = getMaxThinkingTokens(cmd)\n\n if (getCommandContext(cmd) === 'fork') {\n const promptMessages = await cmd.getPromptForCommand(args ?? '')\n const skillPrompt = promptMessages\n .map(msg => contentToText(msg.content))\n .join('\\n')\n .trim()\n\n const agentType = getCommandAgent(cmd) ?? 'general-purpose'\n const taskModel = toTaskToolModel(getRawModelSetting(cmd))\n\n const taskInput = {\n description: getCommandName(cmd),\n prompt: skillPrompt,\n subagent_type: agentType,\n ...(taskModel ? { model: taskModel } : null),\n }\n\n let taskResult: TaskToolOutput | null = null\n const taskContext = {\n ...context,\n options: {\n ...(context.options ?? {}),\n forceForkContext: true,\n commandAllowedTools: mergeUniqueStrings(\n context.options?.commandAllowedTools,\n allowedTools,\n ),\n },\n } as any\n\n for await (const evt of callTaskTool(taskInput as any, taskContext)) {\n if (evt.type === 'progress') {\n yield { type: 'progress' as const, content: evt.content }\n continue\n }\n if (evt.type === 'result') {\n taskResult = evt.data as TaskToolOutput\n }\n }\n\n if (!taskResult) {\n throw new Error(\n `Forked skill execution produced no result: ${skillName}`,\n )\n }\n\n const agentId = taskResult.agentId\n const resultText =\n taskResult.status === 'completed'\n ? taskResult.content\n .map(b => b.text)\n .join('\\n')\n .trim()\n : ''\n\n const output: ForkedOutput = {\n success: true,\n commandName: skillName,\n status: 'forked',\n agentId,\n result: resultText,\n }\n\n yield {\n type: 'result' as const,\n data: output,\n resultForAssistant: this.renderResultForAssistant(output),\n }\n return\n }\n\n const prompt = await cmd.getPromptForCommand(args ?? '')\n const expandedMessages: Message[] = prompt.map(msg => {\n const userMessage = createUserMessage(contentToText(msg.content))\n userMessage.options = {\n ...userMessage.options,\n isCustomCommand: true,\n commandName: getCommandName(cmd),\n commandArgs: '',\n }\n return userMessage\n })\n\n const output: InlineOutput = {\n success: true,\n commandName: skillName,\n status: 'inline',\n allowedTools: allowedTools.length > 0 ? allowedTools : undefined,\n model,\n }\n\n yield {\n type: 'result' as const,\n data: output,\n resultForAssistant: this.renderResultForAssistant(output),\n newMessages: expandedMessages,\n contextModifier:\n allowedTools.length > 0 || model || maxThinkingTokens !== undefined\n ? {\n modifyContext(ctx) {\n const next = { ...ctx }\n\n if (allowedTools.length > 0) {\n const prev = next.options?.commandAllowedTools ?? []\n next.options = {\n ...(next.options || {}),\n commandAllowedTools: [\n ...new Set([...prev, ...allowedTools]),\n ],\n }\n }\n\n if (model) {\n next.options = { ...(next.options || {}), model }\n }\n\n if (maxThinkingTokens !== undefined) {\n next.options = {\n ...(next.options || {}),\n maxThinkingTokens,\n }\n }\n\n return next\n },\n }\n : undefined,\n }\n },\n} satisfies Tool<typeof inputSchema, Output>\n\nfunction findCommand(commandName: string, commands: unknown[]): unknown | null {\n for (const candidate of commands) {\n const record = asRecord(candidate)\n if (!record) continue\n if (record.name === commandName) return candidate\n if (typeof record.userFacingName === 'function') {\n try {\n if (String(record.userFacingName()) === commandName) return candidate\n } catch {\n // ignore\n }\n }\n const aliases = record.aliases\n if (isStringArray(aliases) && aliases.includes(commandName)) {\n return candidate\n }\n }\n return null\n}\n", "export const TOOL_NAME_FOR_PROMPT = 'Skill'\nexport const DESCRIPTION = `- Executes predefined skills by name\n- Input: skill string\n- Fails if the skill is not available`\n", "export const TOOL_NAME = 'Task'\n", "import type { TextBlock } from '@anthropic-ai/sdk/resources/index.mjs'\nimport { z } from 'zod'\n\nexport const inputSchema = z.object({\n description: z\n .string()\n .describe('A short (3-5 word) description of the task'),\n prompt: z.string().describe('The task for the agent to perform'),\n subagent_type: z\n .string()\n .describe('The type of specialized agent to use for this task'),\n model: z\n .enum(['sonnet', 'opus', 'haiku'])\n .optional()\n .describe(\n 'Optional model to use for this agent. If not specified, inherits from parent. Prefer haiku for quick, straightforward tasks to minimize cost and latency.',\n ),\n resume: z\n .string()\n .optional()\n .describe(\n 'Optional agent ID to resume from. If provided, the agent will continue from the previous execution transcript.',\n ),\n run_in_background: z\n .boolean()\n .optional()\n .describe(\n 'Set to true to run this agent in the background. Use TaskOutput to read the output later.',\n ),\n max_turns: z\n .number()\n .optional()\n .describe(\n 'Maximum number of agentic turns (API round-trips) before stopping. Used internally for warmup.',\n ),\n})\n\nexport type Input = z.infer<typeof inputSchema>\nexport type TaskModel = NonNullable<Input['model']>\n\nexport type TaskUsage = {\n input_tokens: number\n output_tokens: number\n cache_creation_input_tokens: number | null\n cache_read_input_tokens: number | null\n server_tool_use: {\n web_search_requests: number\n web_fetch_requests: number\n } | null\n service_tier: 'standard' | 'priority' | 'batch' | null\n cache_creation: {\n ephemeral_1h_input_tokens: number\n ephemeral_5m_input_tokens: number\n } | null\n}\n\nexport type Output =\n | {\n status: 'async_launched'\n agentId: string\n description: string\n prompt: string\n }\n | {\n status: 'completed'\n agentId: string\n prompt: string\n content: TextBlock[]\n totalToolUseCount: number\n totalDurationMs: number\n totalTokens: number\n usage: TaskUsage\n }\n", "import type { TextBlock } from '@anthropic-ai/sdk/resources/index.mjs'\nimport React from 'react'\nimport { Box, Text } from 'ink'\n\nimport { formatDuration, formatNumber } from '#core/utils/format'\nimport { getTheme } from '#core/utils/theme'\nimport { maybeTruncateVerboseToolOutput } from '#core/utils/toolOutputDisplay'\n\nimport type { Input, Output } from './schema'\nimport { asyncLaunchMessage } from './assistantText'\n\nexport function renderTaskToolUseMessage(input: Input): string {\n if (!input.description || !input.prompt) return ''\n return input.description\n}\n\nexport function renderTaskToolResultMessage(\n output: Output,\n options: { verbose: boolean },\n): React.ReactElement {\n const theme = getTheme()\n if (output.status === 'async_launched') {\n const hint = output.prompt\n ? ' (down arrow \u2193 to manage \u00B7 ctrl+o to expand)'\n : ' (down arrow \u2193 to manage)'\n return (\n <Box flexDirection=\"column\">\n <Box flexDirection=\"row\">\n <Text> \u23BF </Text>\n <Text>\n Backgrounded agent\n {!options.verbose && <Text dimColor>{hint}</Text>}\n </Text>\n </Box>\n {options.verbose && output.prompt && (\n <Box\n paddingLeft={2}\n borderStyle=\"single\"\n borderLeft\n borderTop={false}\n borderRight={false}\n borderBottom={false}\n borderLeftColor={theme.secondaryBorder}\n >\n <Text color={theme.secondaryText} wrap=\"wrap\">\n {output.prompt}\n </Text>\n </Box>\n )}\n </Box>\n )\n }\n\n const summary = [\n output.totalToolUseCount === 1\n ? '1 tool use'\n : `${output.totalToolUseCount} tool uses`,\n `${formatNumber(output.totalTokens)} tokens`,\n formatDuration(output.totalDurationMs),\n ]\n return (\n <Box flexDirection=\"column\">\n {options.verbose && output.prompt && (\n <Box\n paddingLeft={2}\n borderStyle=\"single\"\n borderLeft\n borderTop={false}\n borderRight={false}\n borderBottom={false}\n borderLeftColor={theme.secondaryBorder}\n >\n <Text color={theme.secondaryText} wrap=\"wrap\">\n {\n maybeTruncateVerboseToolOutput(output.prompt, {\n maxLines: 120,\n maxChars: 20_000,\n }).text\n }\n </Text>\n </Box>\n )}\n {options.verbose && output.content.length > 0 && (\n <Box\n paddingLeft={2}\n borderStyle=\"single\"\n borderLeft\n borderTop={false}\n borderRight={false}\n borderBottom={false}\n borderLeftColor={theme.secondaryBorder}\n >\n <Text wrap=\"wrap\">\n {\n maybeTruncateVerboseToolOutput(\n output.content.map(b => b.text).join('\\n'),\n { maxLines: 200, maxChars: 40_000 },\n ).text\n }\n </Text>\n </Box>\n )}\n <Box flexDirection=\"row\">\n <Text> \u23BF </Text>\n <Text dimColor>Done ({summary.join(' \u00B7 ')})</Text>\n </Box>\n </Box>\n )\n}\n\nexport function renderTaskToolResultForAssistant(output: Output): string {\n if (output.status === 'async_launched')\n return asyncLaunchMessage(output.agentId)\n return output.content.map(b => b.text).join('\\n')\n}\n\nexport function buildAgentIdBlock(agentId: string): TextBlock {\n return {\n type: 'text',\n text: `agentId: ${agentId} (for resuming to continue this agent's work if needed)`,\n citations: [],\n }\n}\n", "import type { Tool } from '#core/tooling/Tool'\nimport { getAvailableAgentTypes } from '#core/utils/agentLoader'\nimport { getAgentTranscript } from '#core/utils/agentTranscripts'\nimport { getCwd } from '#core/utils/state'\nimport { getKodeAgentSessionId } from '#protocol/utils/kodeAgentSessionId'\nimport { loadKodeAgentSidechainMessagesForResume } from '#protocol/utils/kodeAgentSessionLoad'\n\nimport { TOOL_NAME } from './constants'\nimport { getPrompt } from './prompt'\nimport { callTaskTool } from './call'\nimport { inputSchema, type Input, type Output } from './schema'\nimport {\n renderTaskToolResultForAssistant,\n renderTaskToolResultMessage,\n renderTaskToolUseMessage,\n} from './render'\n\nexport const TaskTool = {\n name: TOOL_NAME,\n inputSchema,\n async description() {\n return 'Launch a new task'\n },\n async prompt({ safeMode }: { safeMode?: boolean }) {\n return await getPrompt(safeMode)\n },\n userFacingName(input?: Partial<Input>) {\n if (input?.subagent_type && input.subagent_type !== 'general-purpose') {\n return input.subagent_type\n }\n return 'Task'\n },\n async isEnabled() {\n return true\n },\n isReadOnly() {\n return true\n },\n isConcurrencySafe() {\n return true\n },\n needsPermissions() {\n return false\n },\n async validateInput(input: Input) {\n if (!input.description || typeof input.description !== 'string') {\n return {\n result: false,\n message: 'Description is required and must be a string',\n }\n }\n if (!input.prompt || typeof input.prompt !== 'string') {\n return {\n result: false,\n message: 'Prompt is required and must be a string',\n }\n }\n\n const availableTypes = await getAvailableAgentTypes()\n if (!availableTypes.includes(input.subagent_type)) {\n return {\n result: false,\n message: `Agent type '${input.subagent_type}' not found. Available agents: ${availableTypes.join(', ')}`,\n meta: { subagent_type: input.subagent_type, availableTypes },\n }\n }\n\n if (input.resume) {\n const transcript = getAgentTranscript(input.resume)\n if (!transcript) {\n try {\n const disk = loadKodeAgentSidechainMessagesForResume({\n cwd: getCwd(),\n sessionId: getKodeAgentSessionId(),\n agentId: input.resume,\n })\n if (disk.length === 0) {\n return {\n result: false,\n message: `No transcript found for agent ID: ${input.resume}`,\n meta: { resume: input.resume },\n }\n }\n } catch {\n return {\n result: false,\n message: `No transcript found for agent ID: ${input.resume}`,\n meta: { resume: input.resume },\n }\n }\n }\n }\n\n return { result: true }\n },\n renderToolUseMessage: renderTaskToolUseMessage,\n renderToolResultMessage: renderTaskToolResultMessage,\n renderResultForAssistant: renderTaskToolResultForAssistant,\n call: callTaskTool,\n} satisfies Tool<typeof inputSchema, Output>\n", "import { randomUUID } from 'crypto'\nimport { z } from 'zod'\nimport { Tool, ValidationResult } from '#core/tooling/Tool'\nimport {\n setTodos,\n getTodos,\n TodoItem as StoredTodoItem,\n} from '#core/utils/todoStorage'\nimport {\n getTodoRenderModel,\n TodoRenderModel,\n} from '#core/utils/todoRenderModel'\nimport { emitReminderEvent } from '#core/services/systemReminder'\nimport { startWatchingTodoFile } from '#core/services/fileFreshness'\nimport { DESCRIPTION, PROMPT } from './prompt'\n\nexport function __getTodoRenderModelForTests(\n todos: StoredTodoItem[],\n): TodoRenderModel {\n return getTodoRenderModel(todos)\n}\n\nconst TodoItemSchema = z.object({\n content: z\n .string()\n .min(1, 'Content cannot be empty')\n .describe('The task description or content'),\n status: z\n .enum(['pending', 'in_progress', 'completed'])\n .describe('Current status of the task'),\n activeForm: z\n .string()\n .min(1, 'Active form cannot be empty')\n .describe('The active form of the task (e.g., \"Writing tests\")'),\n})\n\nconst inputSchema = z.strictObject({\n todos: z.array(TodoItemSchema).describe('The updated todo list'),\n})\n\ntype InputTodo = z.infer<typeof TodoItemSchema>\ntype Output =\n | {\n oldTodos: InputTodo[]\n newTodos: InputTodo[]\n }\n | string\n\nfunction validateTodos(todos: InputTodo[]): ValidationResult {\n // Check for multiple in_progress tasks\n const inProgressTasks = todos.filter(todo => todo.status === 'in_progress')\n if (inProgressTasks.length > 1) {\n return {\n result: false,\n errorCode: 2,\n message: 'Only one task can be in_progress at a time',\n meta: { inProgressTasks: inProgressTasks.map(t => t.content) },\n }\n }\n\n // Validate each todo\n for (const todo of todos) {\n if (!todo.content?.trim()) {\n return {\n result: false,\n errorCode: 3,\n message: 'Todo has empty content',\n }\n }\n if (!['pending', 'in_progress', 'completed'].includes(todo.status)) {\n return {\n result: false,\n errorCode: 4,\n message: `Invalid status \"${todo.status}\" for todo \"${todo.content}\"`,\n meta: { invalidStatus: todo.status },\n }\n }\n if (!todo.activeForm?.trim()) {\n return {\n result: false,\n errorCode: 5,\n message: 'Todo has empty activeForm',\n meta: { todoContent: todo.content },\n }\n }\n }\n\n return { result: true }\n}\n\nfunction generateTodoSummary(todos: StoredTodoItem[]): string {\n const stats = {\n total: todos.length,\n pending: todos.filter(t => t.status === 'pending').length,\n inProgress: todos.filter(t => t.status === 'in_progress').length,\n completed: todos.filter(t => t.status === 'completed').length,\n }\n\n // Enhanced summary with statistics\n let summary = `Updated ${stats.total} todo(s)`\n if (stats.total > 0) {\n summary += ` (${stats.pending} pending, ${stats.inProgress} in progress, ${stats.completed} completed)`\n }\n summary += '. Continue tracking your progress with the todo list.'\n\n return summary\n}\n\nexport const TodoWriteTool = {\n name: 'TodoWrite',\n async description() {\n return DESCRIPTION\n },\n async prompt() {\n return PROMPT\n },\n inputSchema,\n userFacingName() {\n return ''\n },\n async isEnabled() {\n return true\n },\n isReadOnly() {\n return false\n },\n isConcurrencySafe() {\n return false // TodoWrite modifies state, not safe for concurrent execution\n },\n needsPermissions() {\n return false\n },\n renderResultForAssistant() {\n return 'Todos have been modified successfully. Ensure that you continue to use the todo list to track your progress. Please proceed with the current tasks if applicable'\n },\n renderToolUseMessage(input, { verbose }) {\n return null\n },\n renderToolResultMessage(_output: Output, _options: { verbose: boolean }) {\n return null\n },\n async validateInput({ todos }: z.infer<typeof inputSchema>) {\n const validation = validateTodos(todos)\n if (!validation.result) {\n return validation\n }\n return { result: true }\n },\n async *call({ todos }: z.infer<typeof inputSchema>, context) {\n // Get agent ID from context\n const agentId = context?.agentId\n\n // Start watching todo file for this agent if not already watching\n if (agentId) {\n startWatchingTodoFile(agentId)\n }\n\n // Store previous todos for comparison (agent-scoped)\n const previousTodos = getTodos(agentId)\n const oldTodos: InputTodo[] = previousTodos.map(todo => ({\n content: todo.content,\n status: todo.status,\n activeForm: todo.activeForm || todo.content,\n }))\n\n // Default behavior: if all todos are completed, clear the list\n const shouldClear =\n todos.length > 0 && todos.every(todo => todo.status === 'completed')\n\n const reusable = new Map<string, StoredTodoItem[]>()\n for (const todo of previousTodos) {\n const key = `${todo.content}|||${todo.activeForm || todo.content}`\n const list = reusable.get(key) ?? []\n list.push(todo)\n reusable.set(key, list)\n }\n\n const todoItems: StoredTodoItem[] = shouldClear\n ? []\n : todos.map(todo => {\n const key = `${todo.content}|||${todo.activeForm}`\n const list = reusable.get(key)\n const reused = list && list.length > 0 ? list.shift() : undefined\n\n return {\n id: reused?.id ?? randomUUID(),\n content: todo.content,\n status: todo.status,\n activeForm: todo.activeForm,\n priority: reused?.priority ?? 'medium',\n ...(reused?.createdAt ? { createdAt: reused.createdAt } : {}),\n }\n })\n\n try {\n // Update the todos in storage (agent-scoped)\n setTodos(todoItems, agentId)\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : 'Unknown error occurred'\n\n emitReminderEvent('todo:error', {\n error: errorMessage,\n timestamp: Date.now(),\n agentId: context?.agentId || 'default',\n context: 'TodoWriteTool.call',\n })\n\n throw error instanceof Error ? error : new Error(errorMessage)\n }\n\n // Emit todo change event for system reminders (optimized - only if todos actually changed)\n const hasChanged =\n JSON.stringify(previousTodos) !== JSON.stringify(todoItems)\n if (hasChanged) {\n emitReminderEvent('todo:changed', {\n previousTodos,\n newTodos: todoItems,\n timestamp: Date.now(),\n agentId: agentId || 'default',\n changeType:\n todoItems.length > previousTodos.length\n ? 'added'\n : todoItems.length < previousTodos.length\n ? 'removed'\n : 'modified',\n })\n }\n\n yield {\n type: 'result',\n data: {\n oldTodos,\n newTodos: todos,\n },\n resultForAssistant: this.renderResultForAssistant(),\n }\n },\n} satisfies Tool<typeof inputSchema, Output>\n", "export const DESCRIPTION =\n 'Update the todo list for the current session. To be used proactively and often to track progress and pending tasks. Make sure that at least one task is in_progress at all times. Always provide both content (imperative) and activeForm (present continuous) for each task.'\n\nexport const PROMPT = `Use this tool to create and manage a structured task list for your current coding session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.\nIt also helps the user understand the progress of the task and overall progress of their requests.\n\n## When to Use This Tool\nUse this tool proactively in these scenarios:\n\n1. Complex multi-step tasks - When a task requires 3 or more distinct steps or actions\n2. Non-trivial and complex tasks - Tasks that require careful planning or multiple operations\n3. User explicitly requests todo list - When the user directly asks you to use the todo list\n4. User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)\n5. After receiving new instructions - Immediately capture user requirements as todos\n6. When you start working on a task - Mark it as in_progress BEFORE beginning work. Ideally you should only have one todo as in_progress at a time\n7. After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation\n\n## When NOT to Use This Tool\n\nSkip using this tool when:\n1. There is only a single, straightforward task\n2. The task is trivial and tracking it provides no organizational benefit\n3. The task can be completed in less than 3 trivial steps\n4. The task is purely conversational or informational\n\nNOTE that you should not use this tool if there is only one trivial task to do. In this case you are better off just doing the task directly.\n\n## Examples of When to Use the Todo List\n\n<example>\nUser: I want to add a dark mode toggle to the application settings. Make sure you run the tests and build when you're done!\nAssistant: I'll help add a dark mode toggle to your application settings. Let me create a todo list to track this implementation.\n*Creates todo list with the following items:*\n1. Creating dark mode toggle component in Settings page\n2. Adding dark mode state management (context/store)\n3. Implementing CSS-in-JS styles for dark theme\n4. Updating existing components to support theme switching\n5. Running tests and build process, addressing any failures or errors that occur\n*Begins working on the first task*\n\n<reasoning>\nThe assistant used the todo list because:\n1. Adding dark mode is a multi-step feature requiring UI, state management, and styling changes\n2. The user explicitly requested tests and build be run afterward\n3. The assistant inferred that tests and build need to pass by adding \"Ensure tests and build succeed\" as the final task\n</reasoning>\n</example>\n\n<example>\nUser: Help me rename the function getCwd to getCurrentWorkingDirectory across my project\nAssistant: Let me first search through your codebase to find all occurrences of 'getCwd'.\n*Uses grep or search tools to locate all instances of getCwd in the codebase*\nAssistant: I've found 15 instances of 'getCwd' across 8 different files. Let me create a todo list to track these changes.\n*Creates todo list with specific items for each file that needs updating*\n\n<reasoning>\nThe assistant used the todo list because:\n1. First, the assistant searched to understand the scope of the task\n2. Upon finding multiple occurrences across different files, it determined this was a complex task with multiple steps\n3. The todo list helps ensure every instance is tracked and updated systematically\n4. This approach prevents missing any occurrences and maintains code consistency\n</reasoning>\n</example>\n\n\n<example>\nUser: I need to implement these features for my e-commerce site: user registration, product catalog, shopping cart, and checkout flow.\nAssistant: I'll help implement these features. First, let's add all the features to the todo list.\n*Creates a todo list breaking down each feature into specific tasks based on the project architecture*\nAssistant: Let's start with user registration. This will involve creating database models, API endpoints, and frontend forms that integrate with your existing authentication system.\n\n<reasoning>\nThe assistant used the todo list because:\n1. The user provided multiple complex features to implement in a comma separated list\n2. The todo list helps organize these large features into manageable tasks\n3. This approach allows for tracking progress across the entire implementation\n</reasoning>\n</example>\n\n<example>\nUser: Can you help optimize my React application? It's rendering slowly and has performance issues.</user>\nAssistant: I'll help optimize your React application. First, let me examine your codebase to identify potential performance bottlenecks.\n*Reviews component structure, render patterns, state management, and data fetching*\nAssistant: After analyzing your codebase, I've identified several performance issues. Let me create a todo list to track our optimization efforts.\n*Creates todo list with items like: 1) Implementing memoization for expensive calculations in ProductList, 2) Adding virtualization for long lists in Dashboard, 3) Optimizing image loading in Gallery component, 4) Fixing state update loops in ShoppingCart, 5) Reviewing bundle size and implementing code splitting*\nLet's start by implementing memoization for the expensive calculations in your ProductList component.</assistant>\n\n<reasoning>\nThe assistant used the todo list because:\n1. First, the assistant examined the codebase to identify specific performance issues\n2. Based on this analysis, it identified multiple optimization opportunities\n3. Performance optimization is a non-trivial task requiring multiple steps\n4. The todo list helps methodically track improvements across different components\n5. This systematic approach ensures all performance bottlenecks are addressed\n</reasoning>\n</example>\n\n## Examples of When NOT to Use the Todo List\n\n<example>\nUser: How do I print 'Hello World' in Python?\nAssistant: In Python, you can print \"Hello World\" with this simple code:\n\npython\nprint(\"Hello World\")\n\nThis will output the text \"Hello World\" to the console when executed.</assistant>\n\n<reasoning>\nThe assistant did not use the todo list because this is a single, trivial task that can be completed in one step. There's no need to track multiple tasks or steps for such a straightforward request.\n</reasoning>\n</example>\n\n<example>\nUser: What does the git status command do?\nAssistant: The git status command shows the current state of your working directory and staging area. It displays which changes have been staged, which haven't, and which files aren't being tracked by Git. This is a fundamental command for understanding the current state of your repository before making commits.\n\n<reasoning>\nThe assistant did not use the todo list because this is an informational request with no actual coding task to complete. The user is simply asking for an explanation, not for the assistant to perform multiple steps or tasks.\n</reasoning>\n</example>\n\n<example>\nUser: Can you add a comment to the calculateTotal function to explain what it does?\nAssistant: Sure, let me add a comment to the calculateTotal function to explain what it does.\n* Uses the Edit tool to add a comment to the calculateTotal function *\n\n<reasoning>\nThe assistant did not use the todo list because this is a single, straightforward task confined to one location in the code. Adding a comment doesn't require tracking multiple steps or systematic organization.\n</reasoning>\n</example>\n\n<example>\nUser: Run npm install for me and tell me what happens.\nAssistant: I'll run the npm install command for you.\n\n*Executes: npm install*\n\nThe command completed successfully. Here's the output:\n[Output of npm install command]\n\nAll dependencies have been installed according to your package.json file.\n\n<reasoning>\nThe assistant did not use the todo list because this is a single command execution with immediate results. There are no multiple steps to track or organize, making the todo list unnecessary for this straightforward task.\n</reasoning>\n</example>\n\n## Task States and Management\n\n1. **Task States**: Use these states to track progress:\n - pending: Task not yet started\n - in_progress: Currently working on (limit to ONE task at a time)\n - completed: Task finished successfully\n\n **IMPORTANT**: Task descriptions must have two forms:\n - content: The imperative form describing what needs to be done (e.g., \"Run tests\", \"Build the project\")\n - activeForm: The present continuous form shown during execution (e.g., \"Running tests\", \"Building the project\")\n\n2. **Task Management**:\n - Update task status in real-time as you work\n - Mark tasks complete IMMEDIATELY after finishing (don't batch completions)\n - Exactly ONE task must be in_progress at any time (not less, not more)\n - Complete current tasks before starting new ones\n - Remove tasks that are no longer relevant from the list entirely\n\n3. **Task Completion Requirements**:\n - ONLY mark a task as completed when you have FULLY accomplished it\n - If you encounter errors, blockers, or cannot finish, keep the task as in_progress\n - When blocked, create a new task describing what needs to be resolved\n - Never mark a task as completed if:\n - Tests are failing\n - Implementation is partial\n - You encountered unresolved errors\n - You couldn't find necessary files or dependencies\n\n4. **Task Breakdown**:\n - Create specific, actionable items\n - Break complex tasks into smaller, manageable steps\n - Use clear, descriptive task names\n - Always provide both forms:\n - content: \"Fix authentication bug\"\n - activeForm: \"Fixing authentication bug\"\n\nWhen in doubt, use this tool. Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully.\n`\n", "import { Box, Text } from 'ink'\nimport React from 'react'\nimport { z } from 'zod'\nimport { Tool, ToolUseContext } from '#core/tooling/Tool'\nimport { getModelManager } from '#core/utils/model'\nimport { getAnthropicProviderRuntime } from '#core/utils/anthropicProviderRuntime'\nimport { getAnthropicClient } from '#core/ai/llm/anthropic/client'\nimport { createAssistantMessage } from '#core/utils/messages'\nimport {\n buildRequestStrategyFallbackPlan,\n classifyRequestFailure,\n} from '#core/ai/llm/restrictedClientCompat'\nimport { PROMPT, TOOL_NAME_FOR_PROMPT } from './prompt'\nimport { searchProviders } from './searchProviders'\n\nconst inputSchema = z.object({\n query: z.string().describe('The search query to use'),\n allowed_domains: z\n .array(z.string())\n .optional()\n .describe('Only include search results from these domains'),\n blocked_domains: z\n .array(z.string())\n .optional()\n .describe('Never include search results from these domains'),\n})\n\ntype Input = z.infer<typeof inputSchema>\n\ntype WebSearchHit = {\n title: string\n url: string\n}\n\ntype WebSearchResultBlock = {\n tool_use_id: string\n content: WebSearchHit[]\n}\n\ntype Output = {\n query: string\n results: Array<WebSearchResultBlock | string>\n durationSeconds: number\n}\n\ntype AnthropicWebSearchToolConfig = {\n type: 'web_search_20250305'\n name: 'web_search'\n allowed_domains?: string[]\n blocked_domains?: string[]\n max_uses: number\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n if (!value || typeof value !== 'object') return null\n if (Array.isArray(value)) return null\n return value as Record<string, unknown>\n}\n\nfunction parseAnthropicWebSearchContentBlocks(\n blocks: unknown[],\n query: string,\n durationSeconds: number,\n): Output {\n // Compatibility note: this tool mirrors an upstream WebSearch behavior.\n const results: Output['results'] = []\n let textBuffer = ''\n let beforeFirstServerToolUse = true\n\n for (const raw of blocks) {\n const block = asRecord(raw)\n const type = typeof block?.type === 'string' ? block.type : ''\n\n if (type === 'server_tool_use') {\n if (beforeFirstServerToolUse) {\n beforeFirstServerToolUse = false\n if (textBuffer.trim().length > 0) results.push(textBuffer.trim())\n textBuffer = ''\n }\n continue\n }\n\n if (type === 'web_search_tool_result') {\n const toolUseId =\n typeof block?.tool_use_id === 'string'\n ? block.tool_use_id\n : 'web_search'\n\n const content = block?.content\n if (!Array.isArray(content)) {\n const errorCode =\n asRecord(content)?.error_code !== undefined\n ? String(asRecord(content)?.error_code)\n : 'unknown_error'\n results.push(`Web search error: ${errorCode}`)\n continue\n }\n\n const hits: WebSearchHit[] = content\n .map(item => {\n const r = asRecord(item)\n const title = typeof r?.title === 'string' ? r.title : null\n const url = typeof r?.url === 'string' ? r.url : null\n return title && url ? { title, url } : null\n })\n .filter((hit): hit is WebSearchHit => hit !== null)\n\n results.push({ tool_use_id: toolUseId, content: hits })\n continue\n }\n\n if (type === 'text') {\n const text = typeof block?.text === 'string' ? block.text : ''\n if (beforeFirstServerToolUse) {\n textBuffer += text\n } else {\n beforeFirstServerToolUse = true\n textBuffer = text\n }\n }\n }\n\n if (textBuffer.length) results.push(textBuffer.trim())\n\n return { query, results, durationSeconds }\n}\n\ntype WebSearchProgressEvent =\n | { type: 'query_update'; query: string }\n | { type: 'search_results_received'; query: string; resultCount: number }\n\nfunction hostnameMatchesDomain(hostname: string, domain: string): boolean {\n const normalizedHost = hostname.trim().toLowerCase()\n const normalizedDomain = domain.trim().toLowerCase()\n if (!normalizedHost || !normalizedDomain) return false\n if (normalizedHost === normalizedDomain) return true\n return normalizedHost.endsWith(`.${normalizedDomain}`)\n}\n\nfunction shouldIncludeResult(options: {\n url: string\n allowed_domains?: string[]\n blocked_domains?: string[]\n}): boolean {\n let hostname = ''\n try {\n hostname = new URL(options.url).hostname\n } catch {\n return false\n }\n\n if (options.allowed_domains?.length) {\n const allowed = options.allowed_domains.some(domain =>\n hostnameMatchesDomain(hostname, domain),\n )\n if (!allowed) return false\n }\n\n if (options.blocked_domains?.length) {\n const blocked = options.blocked_domains.some(domain =>\n hostnameMatchesDomain(hostname, domain),\n )\n if (blocked) return false\n }\n\n return true\n}\n\nasync function* streamDuckDuckGoWebSearch(args: {\n query: string\n allowed_domains?: string[]\n blocked_domains?: string[]\n}): AsyncGenerator<\n | { type: 'progress'; event: WebSearchProgressEvent }\n | {\n type: 'output'\n output: Output\n }\n> {\n const startedAt = Date.now()\n yield { type: 'progress', event: { type: 'query_update', query: args.query } }\n\n const provider = searchProviders.duckduckgo\n const results = await provider.search(args.query)\n const hits: WebSearchHit[] = results\n .filter(result =>\n shouldIncludeResult({\n url: result.link,\n allowed_domains: args.allowed_domains,\n blocked_domains: args.blocked_domains,\n }),\n )\n .map(result => ({ title: result.title, url: result.link }))\n\n yield {\n type: 'progress',\n event: {\n type: 'search_results_received',\n query: args.query,\n resultCount: hits.length,\n },\n }\n\n const durationSeconds = (Date.now() - startedAt) / 1000\n yield {\n type: 'output',\n output: {\n query: args.query,\n results: [{ tool_use_id: 'duckduckgo', content: hits }],\n durationSeconds,\n },\n }\n}\n\nfunction canUseAnthropicServerToolWebSearch(modelName: string): boolean {\n const runtime = getAnthropicProviderRuntime()\n const isClaude = modelName.toLowerCase().includes('claude')\n if (!isClaude) return false\n if (runtime === 'firstParty' || runtime === 'foundry') return true\n return runtime === 'vertex'\n}\n\nasync function* streamAnthropicServerToolWebSearch(args: {\n query: string\n allowed_domains?: string[]\n blocked_domains?: string[]\n context: ToolUseContext\n}): AsyncGenerator<\n | { type: 'progress'; event: WebSearchProgressEvent }\n | {\n type: 'output'\n output: Output\n }\n> {\n const modelManager = getModelManager()\n const modelProfile = modelManager.getModel('main')\n if (!modelProfile) {\n throw new Error('No configured model profile for WebSearch')\n }\n\n const provider = modelProfile.provider || 'anthropic'\n if (provider !== 'anthropic') {\n throw new Error(\n `WebSearch server tool is not supported for provider: ${provider}`,\n )\n }\n\n if (!modelProfile.apiKey) {\n throw new Error('Missing API key for Anthropic WebSearch')\n }\n\n const toolSchema: AnthropicWebSearchToolConfig = {\n type: 'web_search_20250305',\n name: 'web_search',\n ...(args.allowed_domains ? { allowed_domains: args.allowed_domains } : {}),\n ...(args.blocked_domains ? { blocked_domains: args.blocked_domains } : {}),\n max_uses: 8,\n }\n\n const payload = {\n model: modelProfile.modelName,\n system: 'You are an assistant for performing a web search tool use',\n messages: [\n {\n role: 'user',\n content: `Perform a web search for the query: ${args.query}`,\n },\n ],\n tools: [toolSchema],\n max_tokens: Math.max(modelProfile.maxTokens ?? 1024, 256),\n temperature: 0,\n }\n\n const timeoutMs = 45_000\n const fallbackPlan = buildRequestStrategyFallbackPlan(\n modelProfile.requestStrategy,\n modelProfile.modelName,\n )\n\n let lastError: unknown = null\n\n for (const step of fallbackPlan) {\n const startedAt = Date.now()\n const combinedAbort = new AbortController()\n const abort = () => combinedAbort.abort()\n const timer = setTimeout(() => combinedAbort.abort(), timeoutMs)\n\n args.context.abortController.signal.addEventListener('abort', abort, {\n once: true,\n })\n\n try {\n const anthropic = getAnthropicClient(modelProfile.modelName, {\n requestHeadersProfile: step.headers,\n })\n\n const stream = await anthropic.beta.messages.create(\n { ...(payload as any), stream: true } as any,\n {\n signal: combinedAbort.signal,\n },\n )\n\n const contentBlocks: any[] = []\n const inputJSONBuffers = new Map<number, string>()\n const lastQueryByToolUseId = new Map<string, string>()\n\n for await (const event of stream as any) {\n if (combinedAbort.signal.aborted) {\n throw new Error('Request was cancelled')\n }\n\n if (event?.type === 'content_block_start') {\n contentBlocks[event.index] = { ...event.content_block }\n\n const block = asRecord(event.content_block)\n const blockType = typeof block?.type === 'string' ? block.type : ''\n\n if (blockType === 'server_tool_use') {\n inputJSONBuffers.set(event.index, '')\n }\n\n if (blockType === 'web_search_tool_result') {\n const toolUseId =\n typeof block?.tool_use_id === 'string' ? block.tool_use_id : ''\n const queryForResult =\n (toolUseId && lastQueryByToolUseId.get(toolUseId)) || args.query\n const resultCount = Array.isArray(block?.content)\n ? block.content.length\n : 0\n yield {\n type: 'progress',\n event: {\n type: 'search_results_received',\n query: queryForResult,\n resultCount,\n },\n }\n }\n }\n\n if (event?.type === 'content_block_delta') {\n const idx = event.index\n const block = contentBlocks[idx] ?? null\n const blockType =\n block && typeof block.type === 'string' ? block.type : ''\n\n if (event.delta?.type === 'text_delta') {\n if (blockType !== 'text') {\n contentBlocks[idx] = { type: 'text', text: '' }\n }\n contentBlocks[idx].text += String(event.delta.text ?? '')\n }\n\n if (event.delta?.type === 'input_json_delta') {\n const current = inputJSONBuffers.get(idx) ?? ''\n const next = current + String(event.delta.partial_json ?? '')\n inputJSONBuffers.set(idx, next)\n\n if (blockType === 'server_tool_use') {\n const toolUseId =\n typeof block?.id === 'string' ? (block.id as string) : null\n const match = next.match(/\"query\"\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\"/)\n if (toolUseId && match && match[1]) {\n try {\n const decoded = JSON.parse(`\"${match[1]}\"`) as string\n const previous = lastQueryByToolUseId.get(toolUseId)\n if (decoded && decoded !== previous) {\n lastQueryByToolUseId.set(toolUseId, decoded)\n yield {\n type: 'progress',\n event: { type: 'query_update', query: decoded },\n }\n }\n } catch {\n // Ignore partial JSON decoding failures (compatibility behavior).\n }\n }\n }\n }\n }\n\n if (event?.type === 'content_block_stop') {\n inputJSONBuffers.delete(event.index)\n }\n\n if (event?.type === 'message_stop') {\n break\n }\n }\n\n const blocks = contentBlocks.filter(Boolean)\n const durationSeconds = (Date.now() - startedAt) / 1000\n const output = parseAnthropicWebSearchContentBlocks(\n blocks,\n args.query,\n durationSeconds,\n )\n\n yield { type: 'output', output }\n return\n } catch (error) {\n lastError = error\n if (classifyRequestFailure(error).kind === 'restricted_client_only') {\n continue\n }\n throw error\n } finally {\n clearTimeout(timer)\n args.context.abortController.signal.removeEventListener('abort', abort)\n }\n }\n\n throw lastError instanceof Error\n ? lastError\n : new Error(lastError ? String(lastError) : 'WebSearch failed')\n}\n\nfunction summarizeResults(results: Output['results']): {\n searchCount: number\n totalResultCount: number\n} {\n let searchCount = 0\n let totalResultCount = 0\n for (const item of results) {\n if (typeof item === 'string') continue\n searchCount += 1\n totalResultCount += item.content.length\n }\n return { searchCount, totalResultCount }\n}\n\nexport const WebSearchTool = {\n name: TOOL_NAME_FOR_PROMPT,\n async description(input?: Input) {\n const query = input?.query ?? ''\n return `The assistant wants to search the web for: ${query}`\n },\n userFacingName: () => 'Web Search',\n inputSchema,\n isReadOnly: () => true,\n isConcurrencySafe: () => true,\n async isEnabled() {\n return true\n },\n needsPermissions() {\n return true\n },\n async prompt() {\n return PROMPT\n },\n renderToolUseMessage(\n { query, allowed_domains, blocked_domains }: Input,\n { verbose }: { verbose: boolean },\n ) {\n let summary = `\"${query}\"`\n if (verbose) {\n if (allowed_domains && allowed_domains.length > 0) {\n summary += `, only allowing domains: ${allowed_domains.join(', ')}`\n }\n if (blocked_domains && blocked_domains.length > 0) {\n summary += `, blocking domains: ${blocked_domains.join(', ')}`\n }\n }\n return summary\n },\n renderToolResultMessage(output: Output) {\n const { searchCount } = summarizeResults(output.results)\n const duration =\n output.durationSeconds >= 1\n ? `${Math.round(output.durationSeconds)}s`\n : `${Math.round(output.durationSeconds * 1000)}ms`\n return (\n <Box flexDirection=\"row\">\n <Text> \u23BF Did </Text>\n <Text bold>{searchCount} </Text>\n <Text>\n search{searchCount === 1 ? '' : 'es'} in {duration}\n </Text>\n </Box>\n )\n },\n renderResultForAssistant(output: Output) {\n let result = `Web search results for query: \"${output.query}\"\\n\\n`\n for (const item of output.results) {\n if (typeof item === 'string') {\n result += `${item}\\n\\n`\n continue\n }\n if (item.content.length > 0) {\n result += `Links: ${JSON.stringify(item.content)}\\n\\n`\n } else {\n result += `No links found.\\n\\n`\n }\n }\n result +=\n '\\nREMINDER: You MUST include the sources above in your response to the user using markdown hyperlinks.'\n return result.trim()\n },\n async validateInput(input: Input) {\n if (!input.query || !input.query.length) {\n return {\n result: false,\n message: 'Error: Missing query',\n errorCode: 1,\n }\n }\n\n if (input.allowed_domains?.length && input.blocked_domains?.length) {\n return {\n result: false,\n message:\n 'Error: Cannot specify both allowed_domains and blocked_domains in the same request',\n errorCode: 2,\n }\n }\n return { result: true }\n },\n async *call(\n { query, allowed_domains, blocked_domains }: Input,\n context: ToolUseContext,\n ) {\n const modelProfile = getModelManager().getModel('main')\n const provider = modelProfile?.provider || 'anthropic'\n const modelName = modelProfile?.modelName ?? ''\n\n const shouldUseAnthropicServerTool =\n Boolean(modelProfile) &&\n provider === 'anthropic' &&\n canUseAnthropicServerToolWebSearch(modelName)\n\n async function* emitToolEvents(\n tool:\n | ReturnType<typeof streamAnthropicServerToolWebSearch>\n | ReturnType<typeof streamDuckDuckGoWebSearch>,\n ) {\n for await (const item of tool) {\n if (item.type === 'progress') {\n const message =\n item.event.type === 'query_update'\n ? `Searching: ${item.event.query}`\n : `Found ${item.event.resultCount} results for \"${item.event.query}\"`\n yield {\n type: 'progress' as const,\n content: createAssistantMessage(\n `<tool-progress>${message}</tool-progress>`,\n ),\n }\n continue\n }\n\n const output = item.output\n yield {\n type: 'result' as const,\n resultForAssistant: WebSearchTool.renderResultForAssistant(output),\n data: output,\n }\n return\n }\n }\n\n if (shouldUseAnthropicServerTool) {\n try {\n yield* emitToolEvents(\n streamAnthropicServerToolWebSearch({\n query,\n allowed_domains,\n blocked_domains,\n context,\n }),\n )\n return\n } catch (error) {\n if (context.abortController.signal.aborted) throw error\n yield {\n type: 'progress' as const,\n content: createAssistantMessage(\n `<tool-progress>WebSearch server tool unavailable; falling back\u2026</tool-progress>`,\n ),\n }\n }\n }\n\n yield* emitToolEvents(\n streamDuckDuckGoWebSearch({ query, allowed_domains, blocked_domains }),\n )\n },\n} satisfies Tool<typeof inputSchema, Output>\n", "export const TOOL_NAME_FOR_PROMPT = 'WebSearch'\n\nfunction todayISO(): string {\n const now = new Date()\n const year = now.getFullYear()\n const month = String(now.getMonth() + 1).padStart(2, '0')\n const day = String(now.getDate()).padStart(2, '0')\n return `${year}-${month}-${day}`\n}\n\nexport const PROMPT = `\n- Allows the assistant to search the web and use the results to inform responses\n- Provides up-to-date information for current events and recent data\n- Returns search result information formatted as search result blocks, including links as markdown hyperlinks\n- Use this tool for accessing information beyond the model's knowledge cutoff\n- Searches are performed automatically within a single API call\n\nCRITICAL REQUIREMENT - You MUST follow this:\n - After answering the user's question, you MUST include a \"Sources:\" section at the end of your response\n - In the Sources section, list all relevant URLs from the search results as markdown hyperlinks: [Title](URL)\n - This is MANDATORY - never skip including sources in your response\n - Example format:\n\n [Your answer here]\n\n Sources:\n - [Source Title 1](https://example.com/1)\n - [Source Title 2](https://example.com/2)\n\nUsage notes:\n - Domain filtering is supported to include or block specific websites\n - Web search is only available in the US\n\nIMPORTANT - Use the correct year in search queries:\n - Today's date is ${todayISO()}. You MUST use this year when searching for recent information, documentation, or current events.\n - Example: If today is 2025-07-15 and the user asks for \"latest React docs\", search for \"React documentation 2025\", NOT \"React documentation 2024\"\n`.trim()\n", "import { parse } from 'node-html-parser'\n\nexport interface SearchResult {\n title: string\n snippet: string\n link: string\n}\n\nexport interface SearchProvider {\n search: (query: string, apiKey?: string) => Promise<SearchResult[]>\n isEnabled: (apiKey?: string) => boolean\n}\n\nconst duckDuckGoSearchProvider: SearchProvider = {\n isEnabled: () => true,\n search: async (query: string): Promise<SearchResult[]> => {\n const response = await fetch(\n `https://html.duckduckgo.com/html/?q=${encodeURIComponent(query)}`,\n {\n headers: {\n 'User-Agent':\n 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',\n },\n },\n )\n\n if (!response.ok) {\n throw new Error(\n `DuckDuckGo search failed with status: ${response.status}`,\n )\n }\n\n const html = await response.text()\n const root = parse(html)\n const results: SearchResult[] = []\n\n const resultNodes = root.querySelectorAll('.result.web-result')\n\n for (const node of resultNodes) {\n const titleNode = node.querySelector('.result__a')\n const snippetNode = node.querySelector('.result__snippet')\n\n if (titleNode && snippetNode) {\n const title = titleNode.text\n const link = titleNode.getAttribute('href')\n const snippet = snippetNode.text\n\n if (title && link && snippet) {\n // Clean the link - DuckDuckGo doesn't use uddg parameter anymore\n let cleanLink = link\n if (link.startsWith('https://duckduckgo.com/l/?uddg=')) {\n try {\n const url = new URL(link)\n cleanLink = url.searchParams.get('uddg') || link\n } catch {\n cleanLink = link\n }\n }\n results.push({\n title: title.trim(),\n snippet: snippet.trim(),\n link: cleanLink,\n })\n }\n }\n }\n\n return results\n },\n}\n\nexport const searchProviders = {\n duckduckgo: duckDuckGoSearchProvider,\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,WAAAA,gBAAe;;;ACAxB,SAAS,KAAK,YAAY;AAC1B,OAAO,WAAW;AAClB,SAAS,SAAS;;;ACFlB,SAAS,cAAqB;AAE9B,OAAO,WAAW;AAClB,SAAS,WAAW;AACpB,SAAS,WAAW,wBAAwB;AAGrC,SAAS,cAAc,SAAyB;AACrD,SAAO,OACJ,MAAM,oBAAoB,OAAO,CAAC,EAClC,IAAI,OAAK,OAAO,CAAC,CAAC,EAClB,KAAK,EAAE,EACP,KAAK;AACV;AAEA,SAAS,OACP,OACA,YAAY,GACZ,oBAAmC,MACnC,SAAuB,MACf;AACR,UAAQ,MAAM,MAAM;AAAA,IAClB,KAAK;AACH,aAAO,MAAM,IAAI,QAAQ,MAAM,UAAU,CAAC,GAAG,IAAI,OAAK,OAAO,CAAC,CAAC,EAAE,KAAK,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AAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,IAAM,WAAWM;AAAA,EACtB,OAAO,qBAAgD;AACrD,UAAM,QAAQ,CAAC,GAAG,YAAY,GAAG,GAAI,MAAM,YAAY,CAAE;AAEzD,UAAM,YAAY,MAAM,QAAQ,IAAI,MAAM,IAAI,UAAQ,KAAK,UAAU,CAAC,CAAC;AACvE,UAAM,eAAe,MAAM,OAAO,CAAC,GAAG,MAAM,UAAU,CAAC,CAAC;AAGxD,UAAM,QAAQ,IAAI,aAAa,IAAI,UAAQ,uBAAuB,IAAI,CAAC,CAAC;AAExE,WAAO;AAAA,EACT;AAAA,EACA,CAAC,qBACC,GAAG,oBAAoB,EAAE,cAAc,yBAAyB,OAAO,CAAC;AAC5E;AAEO,IAAM,mBAAmBA,SAAQ,YAA6B;AACnE,QAAM,QAAQ,YAAY,EAAE,OAAO,UAAQ,KAAK,WAAW,CAAC;AAC5D,QAAM,YAAY,MAAM,QAAQ,IAAI,MAAM,IAAI,UAAQ,KAAK,UAAU,CAAC,CAAC;AACvE,QAAM,eAAe,MAAM,OAAO,CAAC,GAAG,UAAU,UAAU,KAAK,CAAC;AAGhE,QAAM,QAAQ,IAAI,aAAa,IAAI,UAAQ,uBAAuB,IAAI,CAAC,CAAC;AAExE,SAAO;AACT,CAAC;",
|
|
6
|
-
"names": ["memoize", "resolve", "Box", "Text", "React", "z", "DESCRIPTION", "PROMPT", "z", "inputSchema", "DESCRIPTION", "PROMPT", "React", "Box", "Text", "EOL", "isAbsolute", "resolve", "React", "z", "Box", "Text", "Box", "Text", "React", "chalk", "React", "Text", "chalk", "React", "Text", "chalk", "chalk", "Box", "Text", "React", "React", "Box", "Text", "formatDuration", "normalizeLineEndings", "parseBoolLike", "randomUUID", "mkdirSync", "writeFileSync", "join", "join", "mkdirSync", "randomUUID", "path", "writeFileSync", "queryLLM", "query", "EOL", "React", "Box", "Text", "React", "React", "Box", "Text", "randomUUID", "mkdirSync", "writeFileSync", "path", "path", "mkdirSync", "writeFileSync", "randomUUID", "resolve", "formatDuration", "normalizeLineEndings", "EOL", "URL", "path", "resolve", "net", "resolve", "existsSync", "join", "path", "resolve", "query", "resolve", "Box", "Text", "React", "z", "randomUUID", "TOOL_NAME_FOR_PROMPT", "PROMPT", "asRecord", "response", "inputSchema", "z", "TOOL_NAME_FOR_PROMPT", "PROMPT", "React", "Box", "Text", "codeText", "result", "output", "randomUUID", "inputSchema", "z", "isAbsolute", "resolve", "formatDuration", "base", "EOL", "z", "TOOL_NAME_FOR_PROMPT", "DESCRIPTION", "PROMPT", "inputSchema", "z", "resolve", "TOOL_NAME_FOR_PROMPT", "DESCRIPTION", "PROMPT", "out", "Box", "Text", "React", "z", "inputSchema", "z", "React", "Box", "Text", "Box", "Text", "React", "z", "inputSchema", "z", "React", "Box", "Text", "mkdirSync", "statSync", "isAbsolute", "relative", "resolve", "z", "Box", "Text", "relative", "React", "z", "highlight", "supportsLanguage", "DESCRIPTION", "PROMPT", "randomUUID", "isAbsolute", "resolve", "isAbsolute", "resolve", "randomUUID", "supportsLanguage", "highlight", "inputSchema", "z", "DESCRIPTION", "PROMPT", "relative", "Box", "Text", "DESCRIPTION", "isAbsolute", "resolve", "isAbsolute", "resolve", "inputSchema", "z", "DESCRIPTION", "relative", "isAbsolute", "resolve", "statSync", "mkdirSync", "z", "TOOL_NAME_FOR_PROMPT", "DESCRIPTION", "existsSync", "statSync", "isAbsolute", "join", "relative", "resolve", "inputSchema", "z", "TOOL_NAME_FOR_PROMPT", "DESCRIPTION", "path", "isAbsolute", "resolve", "existsSync", "statSync", "relative", "join", "z", "existsSync", "statSync", "isAbsolute", "relative", "resolve", "TOOL_NAME_FOR_PROMPT", "DESCRIPTION", "inputSchema", "z", "DEFAULT_LIMIT", "path", "isAbsolute", "resolve", "TOOL_NAME_FOR_PROMPT", "DESCRIPTION", "existsSync", "statSync", "relative", "output", "Box", "Text", "React", "existsSync", "z", "TOOL_NAME_FOR_PROMPT", "DESCRIPTION", "isAbsolute", "relative", "toProjectRelativeIfPossible", "relative", "isAbsolute", "path", "toProjectRelativeIfPossible", "window", "inputSchema", "z", "TOOL_NAME_FOR_PROMPT", "DESCRIPTION", "path", "React", "Box", "Text", "existsSync", "z", "TOOL_NAME_FOR_PROMPT", "DESCRIPTION", "PROMPT", "inputSchema", "z", "TOOL_NAME_FOR_PROMPT", "DESCRIPTION", "PROMPT", "Box", "Text", "React", "z", "DESCRIPTION", "PROMPT", "inputSchema", "z", "DESCRIPTION", "PROMPT", "React", "Box", "Text", "existsSync", "readFileSync", "statSync", "Box", "Text", "React", "z", "Text", "React", "React", "Text", "TOOL_NAME_FOR_PROMPT", "PROMPT", "DESCRIPTION", "inputSchema", "z", "TOOL_NAME_FOR_PROMPT", "DESCRIPTION", "PROMPT", "existsSync", "statSync", "readFileSync", "React", "Box", "Text", "Box", "Text", "React", "z", "DESCRIPTION", "PROMPT", "inputSchema", "z", "DESCRIPTION", "PROMPT", "Box", "Text", "lines", "Box", "Text", "React", "z", "TOOL_NAME_FOR_PROMPT", "DESCRIPTION", "inputSchema", "z", "TOOL_NAME_FOR_PROMPT", "DESCRIPTION", "React", "Box", "Text", "query", "output", "Box", "Text", "React", "z", "TOOL_NAME", "DESCRIPTION", "PROMPT", "inputSchema", "z", "isWrappedClient", "getMcpClients", "TOOL_NAME", "DESCRIPTION", "PROMPT", "React", "Box", "Text", "z", "getPrompt", "randomUUID", "existsSync", "readFileSync", "path", "existsSync", "readFileSync", "randomUUID", "content", "last", "React", "isTextBlock", "isToolUseLikeBlock", "query", "resolve", "React", "toolUseCount", "lastAssistant", "last", "content", "output", "TOOL_NAME_FOR_PROMPT", "asRecord", "inputSchema", "z", "asRecord", "isTextContentBlock", "TOOL_NAME_FOR_PROMPT", "output", "z", "TOOL_NAME_FOR_PROMPT", "inputSchema", "z", "asRecord", "isTextContentBlock", "contentToText", "isPromptLikeCommand", "getCommandName", "getCommandContext", "getCommandAgent", "normalizeCommandModelName", "getRawModelSetting", "getMaxThinkingTokens", "toTaskToolModel", "mergeUniqueStrings", "TOOL_NAME_FOR_PROMPT", "findCommand", "output", "TOOL_NAME", "z", "inputSchema", "React", "Box", "Text", "React", "Box", "Text", "TOOL_NAME", "inputSchema", "getPrompt", "randomUUID", "z", "DESCRIPTION", "PROMPT", "z", "inputSchema", "DESCRIPTION", "PROMPT", "inputSchema", "randomUUID", "Box", "Text", "React", "z", "TOOL_NAME_FOR_PROMPT", "PROMPT", "parse", "query", "inputSchema", "z", "asRecord", "query", "TOOL_NAME_FOR_PROMPT", "PROMPT", "React", "Box", "Text", "memoize"]
|
|
7
|
-
}
|