@ken-jo/agent-connector 0.4.8 → 0.4.43
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/README.md +36 -24
- package/dist/{action-RWPRIZIC.js → action-ZUHMOGLV.js} +12 -12
- package/dist/amazon-q-UFLBUSHG.js +570 -0
- package/dist/amazon-q-UFLBUSHG.js.map +1 -0
- package/dist/{amp-PU4LFSY6.js → amp-5DJK7VAL.js} +5 -7
- package/dist/{amp-PU4LFSY6.js.map → amp-5DJK7VAL.js.map} +1 -1
- package/dist/{amp-TULUPXXL.js → amp-BQZOL5GR.js} +2 -2
- package/dist/{antigravity-STHZWMP3.js → antigravity-EA4L225L.js} +2 -2
- package/dist/{antigravity-DWW35HZO.js → antigravity-NWP2TUG6.js} +5 -6
- package/dist/{antigravity-cli-P6HADOAO.js → antigravity-cli-B2HXZFYQ.js} +2 -2
- package/dist/{antigravity-cli-VTQ6DNWL.js → antigravity-cli-KPNLE7X4.js} +5 -6
- package/dist/{antigravity-cli-VTQ6DNWL.js.map → antigravity-cli-KPNLE7X4.js.map} +1 -1
- package/dist/{chunk-NLFPH4S2.js → chunk-2RPHDVHW.js} +2 -2
- package/dist/{chunk-CENEXP7K.js → chunk-3Q6YEDCG.js} +11 -6
- package/dist/chunk-3Q6YEDCG.js.map +1 -0
- package/dist/{chunk-A2T4Q7RM.js → chunk-3ZZK4KXG.js} +18 -18
- package/dist/{chunk-YYISBXOM.js → chunk-4CBHYWUG.js} +9 -8
- package/dist/{chunk-YYISBXOM.js.map → chunk-4CBHYWUG.js.map} +1 -1
- package/dist/{chunk-HOE2MN36.js → chunk-54B5HAVT.js} +4 -4
- package/dist/{chunk-XQUUNAGC.js → chunk-5HSLICR3.js} +36 -36
- package/dist/{chunk-CDVOBKSG.js → chunk-5TMIJ7AY.js} +26 -5
- package/dist/chunk-5TMIJ7AY.js.map +1 -0
- package/dist/{chunk-KG6T3YNJ.js → chunk-A767JFHW.js} +87 -7
- package/dist/chunk-A767JFHW.js.map +1 -0
- package/dist/{chunk-MOW2RKHX.js → chunk-AQ53TOH4.js} +8 -4
- package/dist/chunk-AQ53TOH4.js.map +1 -0
- package/dist/{chunk-YS2NYJ6R.js → chunk-ERV4TKRV.js} +3 -5
- package/dist/{chunk-YS2NYJ6R.js.map → chunk-ERV4TKRV.js.map} +1 -1
- package/dist/{chunk-BCHWFTV4.js → chunk-F4DSMVZ7.js} +2 -2
- package/dist/{chunk-OZ5EXXQV.js → chunk-H3BATOBP.js} +2 -2
- package/dist/{chunk-SCVBYSF7.js → chunk-IRUYJD23.js} +28 -28
- package/dist/{chunk-FAHIMJRU.js → chunk-L7ESV37V.js} +2 -2
- package/dist/{chunk-JNM3TPLX.js → chunk-LETB5HCK.js} +2 -2
- package/dist/{chunk-7TVBFRVI.js → chunk-M3H7PQWT.js} +2 -2
- package/dist/{chunk-JWNT5KW7.js → chunk-O7SDRBVB.js} +3 -1
- package/dist/chunk-O7SDRBVB.js.map +1 -0
- package/dist/{chunk-TRQKHP7D.js → chunk-QY42WGBX.js} +23 -2
- package/dist/chunk-QY42WGBX.js.map +1 -0
- package/dist/{chunk-VRKTVCYJ.js → chunk-RAJBLK2V.js} +33 -43
- package/dist/chunk-RAJBLK2V.js.map +1 -0
- package/dist/{chunk-WI6YSXOC.js → chunk-VDSXVNEH.js} +51 -28
- package/dist/chunk-VDSXVNEH.js.map +1 -0
- package/dist/{cursor-GJBSMXI6.js → chunk-XW46WVR2.js} +11 -12
- package/dist/chunk-XW46WVR2.js.map +1 -0
- package/dist/{chunk-NYR55UT7.js → chunk-YG3KFOOQ.js} +2 -2
- package/dist/{chunk-N6HH7K6P.js → chunk-ZY25RG4Y.js} +2 -2
- package/dist/{claude-code-W74MNTAC.js → claude-code-NMRKTAP7.js} +2 -2
- package/dist/{claude-code-64X6RR2S.js → claude-code-YNNKQCCR.js} +9 -11
- package/dist/{claude-code-64X6RR2S.js.map → claude-code-YNNKQCCR.js.map} +1 -1
- package/dist/cli/sdk.js +7 -7
- package/dist/cli.js +1 -1
- package/dist/{cline-T7ZDJYZQ.js → cline-AGFJF4AC.js} +5 -7
- package/dist/{cline-T7ZDJYZQ.js.map → cline-AGFJF4AC.js.map} +1 -1
- package/dist/{codebuff-3PMZJJHP.js → codebuff-ETYT5UBL.js} +2 -2
- package/dist/{codebuff-PPPY3SJV.js → codebuff-YUQ4PN7G.js} +5 -7
- package/dist/{codebuff-PPPY3SJV.js.map → codebuff-YUQ4PN7G.js.map} +1 -1
- package/dist/{codex-EEVN43C2.js → codex-FLU37DV3.js} +28 -13
- package/dist/codex-FLU37DV3.js.map +1 -0
- package/dist/{codex-Q3ATRRX3.js → codex-YAORPCOD.js} +2 -2
- package/dist/{continue-VLLZO4PM.js → continue-ZMI4YN75.js} +5 -6
- package/dist/{continue-VLLZO4PM.js.map → continue-ZMI4YN75.js.map} +1 -1
- package/dist/{copilot-cli-SJGIXVSD.js → copilot-cli-MZTAWMPW.js} +2 -2
- package/dist/{copilot-cli-A7G5WB4N.js → copilot-cli-XPRJ5MQB.js} +31 -7
- package/dist/copilot-cli-XPRJ5MQB.js.map +1 -0
- package/dist/{crush-AH24GDDB.js → crush-3OB5ZTCC.js} +13 -12
- package/dist/crush-3OB5ZTCC.js.map +1 -0
- package/dist/{crush-LN5QFFR2.js → crush-QBXLNN7T.js} +2 -2
- package/dist/{cursor-QZ6MTO74.js → cursor-DIW43TRZ.js} +2 -2
- package/dist/cursor-F4HYO2FP.js +22 -0
- package/dist/{detect-YDCZNV4W.js → detect-FXGBSNQU.js} +4 -4
- package/dist/{doctor-DGC7P3P7.js → doctor-2O65SAPG.js} +17 -14
- package/dist/{doctor-DGC7P3P7.js.map → doctor-2O65SAPG.js.map} +1 -1
- package/dist/{droid-RBWCFKL3.js → droid-NZCKYKOV.js} +5 -7
- package/dist/{droid-RBWCFKL3.js.map → droid-NZCKYKOV.js.map} +1 -1
- package/dist/{droid-W5WF5XEX.js → droid-U3ZBLQFO.js} +2 -2
- package/dist/{gemini-cli-CFPFEJEA.js → gemini-cli-3ZGCXUDD.js} +5 -7
- package/dist/{gemini-cli-CFPFEJEA.js.map → gemini-cli-3ZGCXUDD.js.map} +1 -1
- package/dist/{gemini-cli-CIRW37TU.js → gemini-cli-NMVVBO3K.js} +2 -2
- package/dist/{goose-A3M5GODH.js → goose-64V46Y2W.js} +2 -2
- package/dist/{goose-UBJVQFUE.js → goose-MGGNVXJP.js} +59 -12
- package/dist/goose-MGGNVXJP.js.map +1 -0
- package/dist/{hermes-ZYLMOFLZ.js → hermes-F3EGTK6N.js} +2 -2
- package/dist/{hermes-6FXGXLNL.js → hermes-L3CBJ37L.js} +11 -9
- package/dist/hermes-L3CBJ37L.js.map +1 -0
- package/dist/{hook-CDGSCASQ.js → hook-D3PY6TDK.js} +12 -12
- package/dist/index.d.ts +2 -2
- package/dist/index.js +5 -5
- package/dist/{install-2D3UKEME.js → install-SVBIK4VJ.js} +17 -14
- package/dist/{install-2D3UKEME.js.map → install-SVBIK4VJ.js.map} +1 -1
- package/dist/{introspect-Cn3MSA4_.d.ts → introspect-B164-hj3.d.ts} +1 -1
- package/dist/{jetbrains-copilot-K26KMA3U.js → jetbrains-copilot-M2LHJBAW.js} +5 -7
- package/dist/{jetbrains-copilot-K26KMA3U.js.map → jetbrains-copilot-M2LHJBAW.js.map} +1 -1
- package/dist/{kilo-BKZJ26RM.js → kilo-RMRP2EL7.js} +5 -7
- package/dist/{kilo-BKZJ26RM.js.map → kilo-RMRP2EL7.js.map} +1 -1
- package/dist/{kilo-NSWAVP6P.js → kilo-SW7BH6EG.js} +2 -2
- package/dist/{kilo-cli-6UVWCXQD.js → kilo-cli-6ITBNHTH.js} +16 -12
- package/dist/kilo-cli-6ITBNHTH.js.map +1 -0
- package/dist/{kilo-cli-EVBKUODA.js → kilo-cli-ZF272ZHN.js} +2 -2
- package/dist/{kimi-EI3UM3ZV.js → kimi-5FHEXGZD.js} +72 -13
- package/dist/kimi-5FHEXGZD.js.map +1 -0
- package/dist/{kimi-QALYPSRR.js → kimi-I35VOOY4.js} +69 -32
- package/dist/kimi-I35VOOY4.js.map +1 -0
- package/dist/{kiro-J5J42I5Z.js → kiro-2K5UJVGC.js} +13 -18
- package/dist/kiro-2K5UJVGC.js.map +1 -0
- package/dist/{kiro-UCLSLBW2.js → kiro-WGOI5CGT.js} +2 -2
- package/dist/{leaderboard-VZQXNWTX.js → leaderboard-ZMZST52G.js} +6 -6
- package/dist/{mimo-code-BEE622P2.js → mimo-code-K7AMX2QW.js} +38 -9
- package/dist/mimo-code-K7AMX2QW.js.map +1 -0
- package/dist/{mux-5HTNKK4K.js → mux-GT7FWVLH.js} +5 -7
- package/dist/{mux-5HTNKK4K.js.map → mux-GT7FWVLH.js.map} +1 -1
- package/dist/{mux-ZMLVAXOO.js → mux-XM6AP35L.js} +2 -2
- package/dist/{nemoclaw-DNFIZFDF.js → nemoclaw-GQMS6CUM.js} +5 -6
- package/dist/{nemoclaw-DNFIZFDF.js.map → nemoclaw-GQMS6CUM.js.map} +1 -1
- package/dist/{omp-I3UTRBNP.js → omp-2RPYIZUF.js} +4 -5
- package/dist/{omp-I3UTRBNP.js.map → omp-2RPYIZUF.js.map} +1 -1
- package/dist/{openclaw-IYA7ASL6.js → openclaw-5EQFGOWL.js} +2 -2
- package/dist/{openclaw-QE2LMWIF.js → openclaw-P5GMEEGC.js} +5 -6
- package/dist/openclaw-P5GMEEGC.js.map +1 -0
- package/dist/{opencode-ZFSUYJXI.js → opencode-5D2SK3EX.js} +5 -7
- package/dist/{opencode-ZFSUYJXI.js.map → opencode-5D2SK3EX.js.map} +1 -1
- package/dist/{opencode-HWT3RSMN.js → opencode-QGP4ALQY.js} +2 -2
- package/dist/{package-BSCCMW4E.js → package-EDYQF6C6.js} +13 -10
- package/dist/{package-BSCCMW4E.js.map → package-EDYQF6C6.js.map} +1 -1
- package/dist/{pi-UFX2OYFV.js → pi-GGDQREVG.js} +2 -2
- package/dist/{pi-H2KBBDDJ.js → pi-ZMM4KJTO.js} +4 -5
- package/dist/{pi-H2KBBDDJ.js.map → pi-ZMM4KJTO.js.map} +1 -1
- package/dist/{qwen-code-5LE34FNE.js → qwen-code-4ZLVGN2C.js} +12 -14
- package/dist/qwen-code-4ZLVGN2C.js.map +1 -0
- package/dist/{qwen-code-W7NUCDEN.js → qwen-code-GQILBJ5B.js} +2 -2
- package/dist/{roo-code-XH4GCYIS.js → roo-code-67QGLQRM.js} +6 -7
- package/dist/roo-code-67QGLQRM.js.map +1 -0
- package/dist/{roo-code-ZLKH4A7N.js → roo-code-SUWI4BBN.js} +2 -2
- package/dist/runtime/index.d.ts +1 -1
- package/dist/runtime/index.js +10 -10
- package/dist/sdk/index.d.ts +3 -3
- package/dist/sdk/index.js +6 -6
- package/dist/sdk/test.d.ts +2 -2
- package/dist/sdk/test.js +9 -9
- package/dist/{serve-MQNGPY2H.js → serve-427CCEYA.js} +12 -12
- package/dist/{status-MRHVRDFY.js → status-6IHRW6PI.js} +10 -10
- package/dist/{statusline-IYWA75TR.js → statusline-2CKH5RHO.js} +11 -11
- package/dist/{synthetic-UKR6SMGS.js → synthetic-6FRA7P5Q.js} +2 -2
- package/dist/{telemetry-IONIOMLC.js → telemetry-WNVKL7HW.js} +10 -10
- package/dist/{trae-PA26DPBW.js → trae-CPPYASR2.js} +2 -2
- package/dist/{trae-RVNRSV7X.js → trae-TMJPHWZ5.js} +5 -7
- package/dist/{trae-RVNRSV7X.js.map → trae-TMJPHWZ5.js.map} +1 -1
- package/dist/{types-_6arHbX9.d.ts → types-COSBYpKs.d.ts} +7 -5
- package/dist/{uninstall-ESLSVCLE.js → uninstall-QFCDXGKR.js} +17 -14
- package/dist/{uninstall-ESLSVCLE.js.map → uninstall-QFCDXGKR.js.map} +1 -1
- package/dist/{upgrade-VICY5T64.js → upgrade-PP46DURC.js} +17 -14
- package/dist/{upgrade-VICY5T64.js.map → upgrade-PP46DURC.js.map} +1 -1
- package/dist/{usage-TCUWV2YZ.js → usage-VDORZJPT.js} +3 -3
- package/dist/{usage-event-CBZZP37Q.js → usage-event-4533OURF.js} +11 -11
- package/dist/{vscode-copilot-B2QBBHJW.js → vscode-copilot-H7JKUKLZ.js} +21 -10
- package/dist/vscode-copilot-H7JKUKLZ.js.map +1 -0
- package/dist/{warp-JNQA7PBU.js → warp-NRBBJQR2.js} +2 -2
- package/dist/{warp-5R54ST3N.js → warp-SVDVKQQI.js} +5 -7
- package/dist/{warp-5R54ST3N.js.map → warp-SVDVKQQI.js.map} +1 -1
- package/dist/{windsurf-L32UEOLY.js → windsurf-H36YKOMR.js} +5 -7
- package/dist/{windsurf-L32UEOLY.js.map → windsurf-H36YKOMR.js.map} +1 -1
- package/dist/{zed-FDJHJZKD.js → zed-LHWJALLZ.js} +5 -7
- package/dist/{zed-FDJHJZKD.js.map → zed-LHWJALLZ.js.map} +1 -1
- package/dist/{zed-NNNX5MNT.js → zed-XJFOOKCO.js} +2 -2
- package/package.json +7 -2
- package/dist/amazon-q-5LJOB5L3.js +0 -264
- package/dist/amazon-q-5LJOB5L3.js.map +0 -1
- package/dist/chunk-CDVOBKSG.js.map +0 -1
- package/dist/chunk-CENEXP7K.js.map +0 -1
- package/dist/chunk-IEGR4TP3.js +0 -70
- package/dist/chunk-IEGR4TP3.js.map +0 -1
- package/dist/chunk-JWNT5KW7.js.map +0 -1
- package/dist/chunk-KG6T3YNJ.js.map +0 -1
- package/dist/chunk-MOW2RKHX.js.map +0 -1
- package/dist/chunk-TRQKHP7D.js.map +0 -1
- package/dist/chunk-VRKTVCYJ.js.map +0 -1
- package/dist/chunk-WI6YSXOC.js.map +0 -1
- package/dist/codex-EEVN43C2.js.map +0 -1
- package/dist/copilot-cli-A7G5WB4N.js.map +0 -1
- package/dist/crush-AH24GDDB.js.map +0 -1
- package/dist/cursor-GJBSMXI6.js.map +0 -1
- package/dist/goose-UBJVQFUE.js.map +0 -1
- package/dist/hermes-6FXGXLNL.js.map +0 -1
- package/dist/kilo-cli-6UVWCXQD.js.map +0 -1
- package/dist/kimi-EI3UM3ZV.js.map +0 -1
- package/dist/kimi-QALYPSRR.js.map +0 -1
- package/dist/kiro-J5J42I5Z.js.map +0 -1
- package/dist/mimo-code-BEE622P2.js.map +0 -1
- package/dist/qwen-code-5LE34FNE.js.map +0 -1
- package/dist/roo-code-XH4GCYIS.js.map +0 -1
- package/dist/vscode-copilot-B2QBBHJW.js.map +0 -1
- /package/dist/{action-RWPRIZIC.js.map → action-ZUHMOGLV.js.map} +0 -0
- /package/dist/{amp-TULUPXXL.js.map → amp-BQZOL5GR.js.map} +0 -0
- /package/dist/{antigravity-STHZWMP3.js.map → antigravity-EA4L225L.js.map} +0 -0
- /package/dist/{antigravity-DWW35HZO.js.map → antigravity-NWP2TUG6.js.map} +0 -0
- /package/dist/{antigravity-cli-P6HADOAO.js.map → antigravity-cli-B2HXZFYQ.js.map} +0 -0
- /package/dist/{chunk-NLFPH4S2.js.map → chunk-2RPHDVHW.js.map} +0 -0
- /package/dist/{chunk-A2T4Q7RM.js.map → chunk-3ZZK4KXG.js.map} +0 -0
- /package/dist/{chunk-HOE2MN36.js.map → chunk-54B5HAVT.js.map} +0 -0
- /package/dist/{chunk-XQUUNAGC.js.map → chunk-5HSLICR3.js.map} +0 -0
- /package/dist/{chunk-BCHWFTV4.js.map → chunk-F4DSMVZ7.js.map} +0 -0
- /package/dist/{chunk-OZ5EXXQV.js.map → chunk-H3BATOBP.js.map} +0 -0
- /package/dist/{chunk-SCVBYSF7.js.map → chunk-IRUYJD23.js.map} +0 -0
- /package/dist/{chunk-FAHIMJRU.js.map → chunk-L7ESV37V.js.map} +0 -0
- /package/dist/{chunk-JNM3TPLX.js.map → chunk-LETB5HCK.js.map} +0 -0
- /package/dist/{chunk-7TVBFRVI.js.map → chunk-M3H7PQWT.js.map} +0 -0
- /package/dist/{chunk-NYR55UT7.js.map → chunk-YG3KFOOQ.js.map} +0 -0
- /package/dist/{chunk-N6HH7K6P.js.map → chunk-ZY25RG4Y.js.map} +0 -0
- /package/dist/{claude-code-W74MNTAC.js.map → claude-code-NMRKTAP7.js.map} +0 -0
- /package/dist/{codebuff-3PMZJJHP.js.map → codebuff-ETYT5UBL.js.map} +0 -0
- /package/dist/{codex-Q3ATRRX3.js.map → codex-YAORPCOD.js.map} +0 -0
- /package/dist/{copilot-cli-SJGIXVSD.js.map → copilot-cli-MZTAWMPW.js.map} +0 -0
- /package/dist/{crush-LN5QFFR2.js.map → crush-QBXLNN7T.js.map} +0 -0
- /package/dist/{cursor-QZ6MTO74.js.map → cursor-DIW43TRZ.js.map} +0 -0
- /package/dist/{openclaw-QE2LMWIF.js.map → cursor-F4HYO2FP.js.map} +0 -0
- /package/dist/{detect-YDCZNV4W.js.map → detect-FXGBSNQU.js.map} +0 -0
- /package/dist/{droid-W5WF5XEX.js.map → droid-U3ZBLQFO.js.map} +0 -0
- /package/dist/{gemini-cli-CIRW37TU.js.map → gemini-cli-NMVVBO3K.js.map} +0 -0
- /package/dist/{goose-A3M5GODH.js.map → goose-64V46Y2W.js.map} +0 -0
- /package/dist/{hermes-ZYLMOFLZ.js.map → hermes-F3EGTK6N.js.map} +0 -0
- /package/dist/{hook-CDGSCASQ.js.map → hook-D3PY6TDK.js.map} +0 -0
- /package/dist/{kilo-NSWAVP6P.js.map → kilo-SW7BH6EG.js.map} +0 -0
- /package/dist/{kilo-cli-EVBKUODA.js.map → kilo-cli-ZF272ZHN.js.map} +0 -0
- /package/dist/{kiro-UCLSLBW2.js.map → kiro-WGOI5CGT.js.map} +0 -0
- /package/dist/{leaderboard-VZQXNWTX.js.map → leaderboard-ZMZST52G.js.map} +0 -0
- /package/dist/{mux-ZMLVAXOO.js.map → mux-XM6AP35L.js.map} +0 -0
- /package/dist/{openclaw-IYA7ASL6.js.map → openclaw-5EQFGOWL.js.map} +0 -0
- /package/dist/{opencode-HWT3RSMN.js.map → opencode-QGP4ALQY.js.map} +0 -0
- /package/dist/{pi-UFX2OYFV.js.map → pi-GGDQREVG.js.map} +0 -0
- /package/dist/{qwen-code-W7NUCDEN.js.map → qwen-code-GQILBJ5B.js.map} +0 -0
- /package/dist/{roo-code-ZLKH4A7N.js.map → roo-code-SUWI4BBN.js.map} +0 -0
- /package/dist/{serve-MQNGPY2H.js.map → serve-427CCEYA.js.map} +0 -0
- /package/dist/{status-MRHVRDFY.js.map → status-6IHRW6PI.js.map} +0 -0
- /package/dist/{statusline-IYWA75TR.js.map → statusline-2CKH5RHO.js.map} +0 -0
- /package/dist/{synthetic-UKR6SMGS.js.map → synthetic-6FRA7P5Q.js.map} +0 -0
- /package/dist/{telemetry-IONIOMLC.js.map → telemetry-WNVKL7HW.js.map} +0 -0
- /package/dist/{trae-PA26DPBW.js.map → trae-CPPYASR2.js.map} +0 -0
- /package/dist/{usage-TCUWV2YZ.js.map → usage-VDORZJPT.js.map} +0 -0
- /package/dist/{usage-event-CBZZP37Q.js.map → usage-event-4533OURF.js.map} +0 -0
- /package/dist/{warp-JNQA7PBU.js.map → warp-NRBBJQR2.js.map} +0 -0
- /package/dist/{zed-NNNX5MNT.js.map → zed-XJFOOKCO.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/adapters/cursor/index.ts"],"sourcesContent":["/**\n * adapters/cursor — Cursor platform adapter for agent-connector.\n *\n * Generalized from context-mode's proven Cursor adapter: the served identity is\n * now `ctx.connector` (not a hardcoded \"context-mode\"), and every hook command\n * points at the single stable home binary (the shared hook-merge engine builds\n * the command) so one framework update propagates everywhere.\n *\n * Cursor is a json-stdio host:\n * - MCP servers: user scope → ~/.cursor/mcp.json (\"mcpServers\"); project scope\n * → <projectDir>/.cursor/mcp.json (\"mcpServers\").\n * - Hooks: <configDir>/hooks.json with shape `{ version, hooks: { <cursorEvent>:\n * [ { command, matcher? } ] } }`. Unlike Claude, each entry is a FLAT command\n * object (no `{ matcher, hooks:[...] }` wrapper).\n * - Reply: a JSON object on stdout (exit 0). deny/ask carry `permission` +\n * `user_message`; modify carries `updated_input`; context injects via\n * `agent_message` (PreToolUse) or `additional_context` (Post/SessionStart).\n *\n * Cursor supports its own `${env:VAR}` native interpolation, so env/header/url\n * values are rewritten to that native token rather than baked into the file.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nimport { BaseAdapter, type HookMergeDescriptor } from \"../base.js\";\nimport type { Adapter, HookReply, InstallContext, NormalizedEvent } from \"../spi.js\";\nimport type {\n ChangeRecord,\n CommandDef,\n DetectedPlatform,\n HealthCheck,\n HookEventName,\n HookParadigm,\n HookResponse,\n PlatformCapabilities,\n PlatformId,\n PostToolUseEvent,\n PostToolUseFailureEvent,\n PreCompactEvent,\n PreToolUseEvent,\n ServerDef,\n SessionEndEvent,\n SessionStartEvent,\n StopEvent,\n SubagentDef,\n SubagentStartEvent,\n SubagentStopEvent,\n Transport,\n UserPromptSubmitEvent,\n} from \"../../core/types.js\";\nimport { rewriteEnvRefs } from \"../../core/interpolate.js\";\nimport {\n buildWrappedStdio,\n isHomeBinHookCommand,\n} from \"../../core/spawn.js\";\nimport { renderSkillMd } from \"../claude-code/render.js\";\nimport { normalizeSessionSource } from \"../claude-code/wire.js\";\n\nconst HOST: PlatformId = \"cursor\";\nconst MCP_ROOT_KEY = \"mcpServers\";\n\n/** Native hooks.json version Cursor expects. */\nconst CURSOR_HOOKS_VERSION = 1;\n\n/**\n * Cursor-native hook event names, in the lower-camel form Cursor reads from\n * hooks.json. The first four are the events the proven context-mode adapter\n * registers; postToolUseFailure / subagentStart / subagentStop are Cursor's\n * documented \"Subagent (Task tool) lifecycle\" + tool-failure hooks.\n */\nconst CURSOR_EVENT = {\n PreToolUse: \"preToolUse\",\n PostToolUse: \"postToolUse\",\n SessionStart: \"sessionStart\",\n Stop: \"stop\",\n PostToolUseFailure: \"postToolUseFailure\",\n SubagentStart: \"subagentStart\",\n SubagentStop: \"subagentStop\",\n // Lifecycle/prompt events Cursor 1.7+ documents (cursor.com/docs/hooks):\n // sessionEnd is fire-and-forget; preCompact is observational (cannot block);\n // beforeSubmitPrompt fires before a prompt is sent and CAN prevent submission\n // (Cursor itself matches beforeSubmitPrompt against the value \"UserPromptSubmit\").\n SessionEnd: \"sessionEnd\",\n PreCompact: \"preCompact\",\n UserPromptSubmit: \"beforeSubmitPrompt\",\n} as const;\n\n/**\n * Map our normalized event names to Cursor's native hook event names. Only the\n * events Cursor actually supports are present; everything else has no Cursor\n * equivalent and is reported as a skip/warn at install time.\n *\n * PermissionRequest is deliberately ABSENT: Cursor has no permission-dialog\n * event — its permission gate is the OUTPUT field `permission: \"allow\"|\"deny\"|\n * \"ask\"` of the before* hooks (beforeShellExecution / beforeMCPExecution /\n * beforeReadFile / preToolUse), not an observable event. Install reports the\n * standard skip-warn for it.\n */\nconst EVENT_MAP: Partial<Record<HookEventName, string>> = {\n PreToolUse: CURSOR_EVENT.PreToolUse,\n PostToolUse: CURSOR_EVENT.PostToolUse,\n SessionStart: CURSOR_EVENT.SessionStart,\n Stop: CURSOR_EVENT.Stop,\n PostToolUseFailure: CURSOR_EVENT.PostToolUseFailure,\n SubagentStart: CURSOR_EVENT.SubagentStart,\n SubagentStop: CURSOR_EVENT.SubagentStop,\n SessionEnd: CURSOR_EVENT.SessionEnd,\n PreCompact: CURSOR_EVENT.PreCompact,\n UserPromptSubmit: CURSOR_EVENT.UserPromptSubmit,\n};\n\n/** A single Cursor native hook entry — a flat command object. */\ninterface CursorHookEntry {\n command: string;\n matcher?: string;\n}\n\n/** Native MCP server entry shapes Cursor accepts under `mcpServers`. */\ninterface CursorStdioServer {\n command: string;\n args?: string[];\n env?: Record<string, string>;\n cwd?: string;\n}\ninterface CursorHttpServer {\n url: string;\n headers?: Record<string, string>;\n}\n\n/** Raw Cursor hook stdin payload (snake_case wire fields). */\ninterface CursorWireInput {\n connector?: unknown;\n tool_name?: string;\n tool_input?: Record<string, unknown>;\n tool_output?: string;\n error_message?: string;\n cwd?: string;\n workspace_roots?: string[];\n conversation_id?: string;\n session_id?: string;\n generation_id?: string;\n source?: string;\n trigger?: string;\n status?: string;\n loop_count?: number;\n stop_hook_active?: boolean;\n\n // beforeSubmitPrompt (UserPromptSubmit) — the submitted prompt text.\n // sessionEnd — the documented end reason. Both field names are taken\n // verbatim from cursor.com/docs/hooks (snake_case wire).\n prompt?: string;\n reason?: string;\n\n // postToolUseFailure — Cursor's existing error vocabulary is error_message;\n // the Claude-compatible names are accepted defensively (unverified wire).\n error?: string;\n tool_use_id?: string;\n is_interrupt?: boolean;\n duration_ms?: number;\n\n // subagentStart / subagentStop (Task-tool lifecycle). Both name families are\n // parsed defensively: agent_* (Claude-compatible) and subagent_* (Cursor-ish).\n agent_id?: string;\n agent_type?: string;\n subagent_id?: string;\n subagent_type?: string;\n last_assistant_message?: string;\n}\n\nexport class CursorAdapter extends BaseAdapter implements Adapter {\n readonly id: PlatformId = HOST;\n readonly name = \"Cursor\";\n readonly paradigm: HookParadigm = \"json-stdio\";\n\n readonly capabilities: PlatformCapabilities = {\n // Memory surface: AGENTS.md-first managed block via the BaseAdapter default\n // (memoryTargets: project <projectDir>/AGENTS.md; user scope where documented).\n supportsMemory: true,\n // Cursor natively supports pre/post tool-use, session start/end, prompt\n // submission, context compaction, and stop (cursor.com/docs/hooks, v1.7+).\n preToolUse: true,\n postToolUse: true,\n preCompact: true,\n sessionStart: true,\n sessionEnd: true,\n userPromptSubmit: true,\n stop: true,\n notification: false,\n // Newer events: Cursor has dedicated postToolUseFailure + subagentStart/\n // subagentStop hooks. permissionRequest stays unset — Cursor's permission\n // gate is an OUTPUT field of its before* hooks, not an observable event\n // (see the EVENT_MAP note).\n postToolUseFailure: true,\n subagentStart: true,\n subagentStop: true,\n // Cursor's preToolUse can rewrite tool input (updated_input) but cannot\n // rewrite already-emitted tool output.\n canModifyArgs: true,\n canModifyOutput: false,\n canInjectSessionContext: true,\n transports: [\"stdio\", \"http\"],\n // Content surfaces: Cursor supports all three (commands, skills, subagents).\n supportsCommands: true,\n supportsSkills: true,\n supportsSubagents: true,\n // Native passthrough hooks: Cursor documents many granular hooks with NO\n // canonical analog — beforeShellExecution / afterShellExecution /\n // beforeMCPExecution / afterMCPExecution / beforeReadFile / afterFileEdit /\n // beforeTabFileRead / afterTabFileEdit / workspaceOpen / afterAgentResponse /\n // afterAgentThought (cursor.com/docs/hooks). They are\n // host-specific (below the >=3-host core bar; see\n // docs/research/host-specific-hook-events-design.md). A connector reaches them\n // by declaring platforms[\"cursor\"].nativeHooks; installHooks writes those\n // event-name keys verbatim into hooks.json, and the generic uninstall reverses\n // them.\n supportsNativeHooks: true,\n // Cursor has a command-driven status line (`/statusline` → `statusLine` in\n // ~/.cursor/cli-config.json, GLOBAL scope only) per the Cursor changelog, but\n // the config-key shape + the Claude-parity stdin payload are sourced from a\n // community tool (agent-status-pills), not first-party Cursor docs — payload\n // field names unverified. Deferred pending a live cursor-agent capture; not a\n // permanent gap; user-scope only when wired.\n };\n\n // ── Detection ────────────────────────────────────────────────────────────\n\n detectInstalled(projectDir: string): DetectedPlatform {\n const userDir = join(homedir(), \".cursor\");\n const userMcp = join(userDir, \"mcp.json\");\n const userHooks = join(userDir, \"hooks.json\");\n const projectDirCursor = join(projectDir, \".cursor\");\n const installed =\n existsSync(userDir) ||\n existsSync(userMcp) ||\n existsSync(userHooks) ||\n existsSync(projectDirCursor);\n return {\n id: this.id,\n name: this.name,\n installed,\n paradigm: this.paradigm,\n capabilities: this.capabilities,\n configPath: userMcp,\n scope: \"user\",\n reason: installed\n ? `found Cursor config under ${userDir}`\n : `no Cursor config at ${userDir}`,\n confidence: installed ? \"high\" : \"low\",\n };\n }\n\n // ── Native paths ─────────────────────────────────────────────────────────\n\n getConfigDir(ctx: InstallContext): string {\n return ctx.scope === \"project\"\n ? join(ctx.projectDir, \".cursor\")\n : join(homedir(), \".cursor\");\n }\n\n getServerConfigPath(ctx: InstallContext): string {\n return join(this.getConfigDir(ctx), \"mcp.json\");\n }\n\n getHookConfigPath(ctx: InstallContext): string {\n return join(this.getConfigDir(ctx), \"hooks.json\");\n }\n\n // ── MCP server install / uninstall ───────────────────────────────────────\n\n installServer(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n const override = connector.platforms[HOST]?.server;\n if (!connector.server || override === false) {\n return [\n {\n platform: this.id,\n action: \"skip\",\n detail: connector.server\n ? \"server registration disabled for cursor\"\n : \"connector declares no MCP server\",\n },\n ];\n }\n\n // Shallow-merge any per-platform server override into the base ServerDef.\n const server: ServerDef =\n override && typeof override === \"object\"\n ? { ...connector.server, ...override }\n : connector.server;\n\n const serverPath = this.getServerConfigPath(ctx);\n const entry = this.renderServerEntry(ctx, server);\n\n return [\n this.upsertServerInJson(serverPath, MCP_ROOT_KEY, connector.id, entry, ctx.dryRun),\n ];\n }\n\n uninstallServer(ctx: InstallContext): ChangeRecord[] {\n const serverPath = this.getServerConfigPath(ctx);\n return [\n this.removeServerFromJson(serverPath, MCP_ROOT_KEY, ctx.connector.id, ctx.dryRun),\n ];\n }\n\n /** Render a normalized ServerDef into Cursor's native mcpServers entry. */\n private renderServerEntry(\n ctx: InstallContext,\n server: ServerDef,\n ): CursorStdioServer | CursorHttpServer {\n const transport: Transport = server.transport;\n\n if (transport === \"stdio\") {\n let command = server.command ?? \"\";\n let args = [...(server.args ?? [])];\n\n // Transparent telemetry wrapping: route the real command through\n // `<homeBin> serve --connector <id> -- <command> <args...>`.\n ({ command, args } = buildWrappedStdio(ctx, server, this.id, command, args));\n\n const entry: CursorStdioServer = { command: this.rewrite(command) };\n if (args.length > 0) entry.args = args.map((a) => this.rewrite(a));\n const env = this.renderEnv(server.env);\n if (env) entry.env = env;\n if (server.cwd) entry.cwd = this.rewrite(server.cwd);\n return entry;\n }\n\n // http (and any other remote transport we surface) — Cursor registers a URL.\n const entry: CursorHttpServer = { url: this.rewrite(server.url ?? \"\") };\n const headers = this.renderEnv(server.headers);\n if (headers) entry.headers = headers;\n return entry;\n }\n\n /**\n * Render env/header values. Cursor supports its own `${env:VAR}` native\n * interpolation, so translate `${env:VAR}` refs to that native token rather\n * than baking secrets into the file. Literals pass through unchanged.\n */\n private renderEnv(\n env: Record<string, string> | undefined,\n ): Record<string, string> | undefined {\n if (!env || Object.keys(env).length === 0) return undefined;\n const out: Record<string, string> = {};\n for (const [k, v] of Object.entries(env)) out[k] = this.rewrite(v);\n return out;\n }\n\n /** Translate `${env:VAR(:-default)}` to Cursor's native `${env:VAR}` token. */\n private rewrite(value: string): string {\n return rewriteEnvRefs(value, cursorEnvToken);\n }\n\n // ── Hook install / uninstall ─────────────────────────────────────────────\n\n installHooks(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n const override = connector.platforms[HOST];\n\n // `hooks: false` disables only the NORMALIZED events. nativeHooks is a\n // sibling, cursor-scoped declaration on the same override and installs\n // regardless.\n const normalizedEvents = override?.hooks === false ? [] : connector.hookEvents;\n const nativeHooks = override?.nativeHooks ?? {};\n const nativeEvents = Object.keys(nativeHooks);\n\n if (normalizedEvents.length === 0 && nativeEvents.length === 0) {\n return [\n {\n platform: this.id,\n action: \"skip\",\n detail: override?.hooks === false ? \"hooks disabled for cursor\" : \"connector declares no hooks\",\n },\n ];\n }\n\n // Normalized events go through the engine's mapEvent/warn path; native\n // event-name keys ride the separate `native` pass (verbatim keys, EXACT\n // command, the `(native)` detail) — see the descriptor + base.upsertHookEntries.\n const pending = normalizedEvents.map((event) => ({\n event,\n matcher: connector.hooks[event]?.matcher ?? \"\",\n }));\n const native = nativeEvents.map((event) => ({\n event,\n matcher: nativeHooks[event]?.matcher ?? \"\",\n }));\n return this.upsertHookEntries(\n ctx,\n this.getHookConfigPath(ctx),\n pending,\n this.hookDescriptor(ctx),\n native,\n );\n }\n\n uninstallHooks(ctx: InstallContext): ChangeRecord[] {\n return this.removeHookEntries(ctx, this.getHookConfigPath(ctx), this.hookDescriptor(ctx));\n }\n\n /**\n * Cursor's hook-merge descriptor (FLAT shape `{ command, matcher? }`):\n * - mapEvent renames canonical → Cursor's lower-camel native key (EVENT_MAP);\n * an unmapped event warn-skips (no Cursor equivalent).\n * - renderEntry omits the `matcher` key when the matcher is falsy — this\n * `{command}` vs `{command,matcher}` distinction is load-bearing on-disk\n * bytes (Cursor's flat entry shape), reproduced exactly here.\n * - install find is connector-generic (ANY of our commands at the flat\n * `entry.command`); uninstall drops whole owned entries (flat — NO\n * stripInner). The version stamp is install-only via onMutate.\n * - the native pass uses EXACT-command ownership so a native key coinciding\n * with a normalized event's mapped key adds a SECOND distinct command\n * rather than clobbering the normalized entry.\n */\n private hookDescriptor(ctx: InstallContext): HookMergeDescriptor<CursorHookEntry> {\n return {\n mapEvent: (e) => EVENT_MAP[e as HookEventName],\n unmappedWarnDetail: (e) => `${e} has no Cursor hook equivalent — skipped`,\n renderEntry: (_event, matcher, command) =>\n matcher ? { command, matcher } : { command },\n entryOwnsCommand: (entry, _command) => this.isOurCommand(entry.command, ctx),\n ownsEntryForRemove: (c) => (entry) => this.isOurCommand(entry.command, c),\n skipDetail: (e) => `hooks.${e} already registered`,\n removeDetail: (e, n) => `hooks.${e} (${n})`,\n absentDetail: \"no hooks section present\",\n noMatchDetail: \"no matching hook entries\",\n onMutate: (file) => {\n (file as { version?: number }).version = CURSOR_HOOKS_VERSION;\n },\n nativeOwnsCommand: (entry, command) => entry.command === command,\n nativeSkipDetail: (e) => `hooks.${e} (native) already registered`,\n nativeMutateDetail: (e) => `hooks.${e} (native)`,\n };\n }\n\n /** True when a hook command references our home binary AND this connector id\n * (anchored so a shared-prefix id can't collide — see isHomeBinHookCommand). */\n private isOurCommand(command: string | undefined, ctx: InstallContext): boolean {\n return isHomeBinHookCommand(command, ctx.homeBinPath, ctx.connector.id);\n }\n\n // ── Content surfaces: commands / skills / subagents ──────────────────────\n // CONTENT-ONLY: pure native-file writers under <configDir>/{commands,skills,\n // agents}. No runtime dispatch, no home-bin pointer, no telemetry wrap. Each\n // method is idempotent (byte-identical → skip) via BaseAdapter.writeContentFile\n // and reversible via removeContentFile. Honors platforms[\"cursor\"] per-surface\n // false to skip. Cursor commands are BODY-ONLY markdown (no frontmatter);\n // skills are the uniform <name>/SKILL.md + resources; subagents are md+fm.\n\n private commandsDir(ctx: InstallContext): string {\n return join(this.getConfigDir(ctx), \"commands\");\n }\n private skillsDir(ctx: InstallContext): string {\n return join(this.getConfigDir(ctx), \"skills\");\n }\n private agentsDir(ctx: InstallContext): string {\n return join(this.getConfigDir(ctx), \"agents\");\n }\n\n /** Native command file path: <configDir>/commands/<name>.md. */\n private commandPath(ctx: InstallContext, name: string): string {\n return join(this.commandsDir(ctx), `${name}.md`);\n }\n /** Native skill dir: <configDir>/skills/<name>. */\n private skillDir(ctx: InstallContext, name: string): string {\n return join(this.skillsDir(ctx), name);\n }\n /** Native subagent file path: <configDir>/agents/<name>.md. */\n private subagentPath(ctx: InstallContext, name: string): string {\n return join(this.agentsDir(ctx), `${name}.md`);\n }\n\n // ── Commands ──────────────────────────────────────────────────────────────\n\n override installCommands(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n if (connector.platforms[HOST]?.commands === false) {\n return [{ platform: this.id, action: \"skip\", detail: \"commands disabled for cursor\" }];\n }\n if (connector.commands.length === 0) {\n return [{ platform: this.id, action: \"skip\", detail: \"connector declares no commands\" }];\n }\n return connector.commands.map((cmd) =>\n this.writeContentFile(\n this.commandPath(ctx, cmd.name),\n this.renderCommand(cmd),\n ctx.dryRun,\n ),\n );\n }\n\n override uninstallCommands(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n if (connector.commands.length === 0) {\n return [{ platform: this.id, action: \"skip\", detail: \"connector declares no commands\" }];\n }\n return connector.commands.map((cmd) =>\n this.removeContentFile(this.commandPath(ctx, cmd.name), ctx.dryRun),\n );\n }\n\n /**\n * Render a Cursor command: BODY-ONLY markdown (no frontmatter). Cursor reads\n * the file as the command prompt verbatim. We prepend the one-line description\n * as an HTML comment header when present so authoring intent survives the\n * round-trip without leaking into the rendered prompt. A description containing\n * \"-->\" would prematurely CLOSE the HTML comment and leak the remainder into\n * the prompt, so we neutralize that sequence before embedding it.\n */\n private renderCommand(cmd: CommandDef): string {\n if (!cmd.description) return `${cmd.prompt}\\n`;\n // Break any literal comment-close so it cannot terminate our header early.\n const safe = cmd.description.replace(/--+>/g, (m) => m.replace(/>/g, \">\"));\n return `<!-- ${safe} -->\\n\\n${cmd.prompt}\\n`;\n }\n\n // ── Skills ────────────────────────────────────────────────────────────────\n\n override installSkills(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n if (connector.platforms[HOST]?.skills === false) {\n return [{ platform: this.id, action: \"skip\", detail: \"skills disabled for cursor\" }];\n }\n if (connector.skills.length === 0) {\n return [{ platform: this.id, action: \"skip\", detail: \"connector declares no skills\" }];\n }\n const changes: ChangeRecord[] = [];\n for (const skill of connector.skills) {\n const dir = this.skillDir(ctx, skill.name);\n changes.push(\n this.writeContentFile(join(dir, \"SKILL.md\"), renderSkillMd(skill), ctx.dryRun),\n );\n // Bundle any resource files beside SKILL.md (relative path → contents).\n // Defense-in-depth: skip+warn on any key that escapes the skill dir\n // (config-time validation already rejects these, but never trust input).\n for (const [rel, contents] of Object.entries(skill.resources ?? {})) {\n const target = this.resolveWithin(dir, rel);\n if (target === null) {\n changes.push({\n platform: this.id,\n action: \"warn\",\n detail: `skill resource \"${rel}\" escapes the skill dir; skipped`,\n });\n continue;\n }\n changes.push(this.writeContentFile(target, contents, ctx.dryRun));\n }\n }\n return changes;\n }\n\n override uninstallSkills(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n if (connector.skills.length === 0) {\n return [{ platform: this.id, action: \"skip\", detail: \"connector declares no skills\" }];\n }\n const changes: ChangeRecord[] = [];\n for (const skill of connector.skills) {\n const dir = this.skillDir(ctx, skill.name);\n // Remove only the files we wrote (SKILL.md + declared resources), then the\n // skill dir itself when we own its full contents.\n changes.push(this.removeContentFile(join(dir, \"SKILL.md\"), ctx.dryRun));\n for (const rel of Object.keys(skill.resources ?? {})) {\n const target = this.resolveWithin(dir, rel);\n if (target === null) continue; // never delete outside the skill dir\n changes.push(this.removeContentFile(target, ctx.dryRun));\n }\n // Only remove the skill dir when WE own its full contents — never rm -rf a\n // dir that still holds user-added / sibling-tool / shared files.\n changes.push(this.removeDirIfEmpty(dir, ctx.dryRun));\n }\n return changes;\n }\n\n // ── Subagents ───────────────────────────────────────────────────────────────\n\n override installSubagents(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n if (connector.platforms[HOST]?.subagents === false) {\n return [{ platform: this.id, action: \"skip\", detail: \"subagents disabled for cursor\" }];\n }\n if (connector.subagents.length === 0) {\n return [{ platform: this.id, action: \"skip\", detail: \"connector declares no subagents\" }];\n }\n return connector.subagents.map((agent) =>\n this.writeContentFile(\n this.subagentPath(ctx, agent.name),\n this.renderSubagent(agent),\n ctx.dryRun,\n ),\n );\n }\n\n override uninstallSubagents(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n if (connector.subagents.length === 0) {\n return [{ platform: this.id, action: \"skip\", detail: \"connector declares no subagents\" }];\n }\n return connector.subagents.map((agent) =>\n this.removeContentFile(this.subagentPath(ctx, agent.name), ctx.dryRun),\n );\n }\n\n /** Render a Cursor subagent to md+frontmatter (name, description, model, readonly) + prompt body. */\n private renderSubagent(agent: SubagentDef): string {\n const frontmatter: Record<string, unknown> = {\n name: agent.name,\n description: agent.description,\n };\n if (agent.model !== undefined) frontmatter.model = agent.model;\n if (agent.readonly !== undefined) frontmatter.readonly = agent.readonly;\n if (agent.extra) Object.assign(frontmatter, agent.extra);\n return this.renderFrontmatterMd(frontmatter, agent.prompt);\n }\n\n // ── Diagnostics ──────────────────────────────────────────────────────────\n\n override getHealthChecks(ctx: InstallContext): readonly HealthCheck[] {\n const mcpPath = this.getServerConfigPath(ctx);\n const hooksPath = this.getHookConfigPath(ctx);\n const checks: HealthCheck[] = [\n {\n name: `${this.name}: mcp.json present`,\n check: () =>\n existsSync(mcpPath)\n ? { status: \"OK\", detail: mcpPath }\n : { status: \"FAIL\", detail: `not found: ${mcpPath}` },\n },\n {\n name: `${this.name}: hooks.json present`,\n check: () => {\n // Same \"only assert what the connector declares\" rule as the\n // content-surface checks below: a hookless connector never writes\n // hooks.json, so its absence is healthy, not a failure.\n if (ctx.connector.hookEvents.length === 0) {\n return { status: \"OK\", detail: \"no hooks declared\" };\n }\n return existsSync(hooksPath)\n ? { status: \"OK\", detail: hooksPath }\n : { status: \"FAIL\", detail: `not found: ${hooksPath}` };\n },\n },\n ];\n\n // Content-surface checks: only assert presence of the files this connector\n // declares (skip silently for surfaces it never asked for).\n for (const cmd of ctx.connector.commands) {\n const p = this.commandPath(ctx, cmd.name);\n checks.push({\n name: `${this.name}: command ${cmd.name} present`,\n check: () =>\n existsSync(p) ? { status: \"OK\", detail: p } : { status: \"FAIL\", detail: `not found: ${p}` },\n });\n }\n for (const skill of ctx.connector.skills) {\n const p = join(this.skillDir(ctx, skill.name), \"SKILL.md\");\n checks.push({\n name: `${this.name}: skill ${skill.name} present`,\n check: () =>\n existsSync(p) ? { status: \"OK\", detail: p } : { status: \"FAIL\", detail: `not found: ${p}` },\n });\n }\n for (const agent of ctx.connector.subagents) {\n const p = this.subagentPath(ctx, agent.name);\n checks.push({\n name: `${this.name}: subagent ${agent.name} present`,\n check: () =>\n existsSync(p) ? { status: \"OK\", detail: p } : { status: \"FAIL\", detail: `not found: ${p}` },\n });\n }\n return checks;\n }\n\n // ── Runtime: parse Cursor stdin JSON → normalized event ──────────────────\n\n parseEvent(event: HookEventName, raw: unknown): NormalizedEvent {\n const input = (raw ?? {}) as CursorWireInput;\n const connectorId = typeof input.connector === \"string\" ? input.connector : \"\";\n const sessionId = extractSessionId(input);\n const projectDir = this.getProjectDir(input);\n\n const base = {\n hostPlatform: HOST,\n connectorId,\n sessionId,\n raw,\n ...(projectDir !== undefined ? { projectDir } : {}),\n } as const;\n\n switch (event) {\n case \"PreToolUse\": {\n const ev: PreToolUseEvent = {\n ...base,\n toolName: input.tool_name ?? \"\",\n toolInput: input.tool_input ?? {},\n };\n return ev;\n }\n case \"PostToolUse\": {\n const toolOutput = input.tool_output ?? input.error_message;\n const ev: PostToolUseEvent = {\n ...base,\n toolName: input.tool_name ?? \"\",\n toolInput: input.tool_input ?? {},\n ...(toolOutput !== undefined ? { toolOutput } : {}),\n ...(input.error_message ? { isError: true } : {}),\n };\n return ev;\n }\n case \"SessionStart\": {\n const ev: SessionStartEvent = {\n ...base,\n source: normalizeSessionSource(input.source ?? input.trigger),\n };\n return ev;\n }\n case \"Stop\": {\n const ev: StopEvent = {\n ...base,\n ...(typeof input.stop_hook_active === \"boolean\"\n ? { stopHookActive: input.stop_hook_active }\n : {}),\n };\n return ev;\n }\n case \"SessionEnd\": {\n // Cursor sessionEnd: { session_id, reason, duration_ms, ... }. session_id\n // is already folded into base.sessionId via extractSessionId; only the\n // documented `reason` enum maps onto the normalized SessionEnd shape.\n const ev: SessionEndEvent = {\n ...base,\n ...(typeof input.reason === \"string\" ? { reason: input.reason } : {}),\n };\n return ev;\n }\n case \"UserPromptSubmit\": {\n // Cursor beforeSubmitPrompt: { prompt, attachments }. attachments has no\n // normalized field and is preserved via base.raw; only `prompt` maps.\n const ev: UserPromptSubmitEvent = {\n ...base,\n prompt: typeof input.prompt === \"string\" ? input.prompt : \"\",\n };\n return ev;\n }\n case \"PreCompact\": {\n // Cursor preCompact: { trigger: \"auto\"|\"manual\", context_*… }. Only the\n // documented `trigger` enum maps onto the normalized PreCompact shape.\n const ev: PreCompactEvent = {\n ...base,\n ...(input.trigger === \"auto\" || input.trigger === \"manual\"\n ? { trigger: input.trigger }\n : {}),\n };\n return ev;\n }\n case \"PostToolUseFailure\": {\n // Cursor's established error field is error_message; fall back to the\n // Claude-compatible `error` defensively.\n const error = input.error_message ?? input.error ?? \"\";\n const ev: PostToolUseFailureEvent = {\n ...base,\n toolName: input.tool_name ?? \"\",\n toolInput: input.tool_input ?? {},\n error,\n ...(typeof input.tool_use_id === \"string\"\n ? { toolUseId: input.tool_use_id }\n : {}),\n ...(typeof input.is_interrupt === \"boolean\"\n ? { isInterrupt: input.is_interrupt }\n : {}),\n ...(typeof input.duration_ms === \"number\"\n ? { durationMs: input.duration_ms }\n : {}),\n };\n return ev;\n }\n case \"SubagentStart\": {\n const agentId = input.agent_id ?? input.subagent_id;\n const agentType = input.agent_type ?? input.subagent_type;\n const ev: SubagentStartEvent = {\n ...base,\n ...(typeof agentId === \"string\" ? { agentId } : {}),\n ...(typeof agentType === \"string\" ? { agentType } : {}),\n };\n return ev;\n }\n case \"SubagentStop\": {\n const agentId = input.agent_id ?? input.subagent_id;\n const agentType = input.agent_type ?? input.subagent_type;\n const ev: SubagentStopEvent = {\n ...base,\n ...(typeof agentId === \"string\" ? { agentId } : {}),\n ...(typeof agentType === \"string\" ? { agentType } : {}),\n ...(typeof input.last_assistant_message === \"string\"\n ? { lastAssistantMessage: input.last_assistant_message }\n : {}),\n ...(typeof input.stop_hook_active === \"boolean\"\n ? { stopHookActive: input.stop_hook_active }\n : {}),\n };\n return ev;\n }\n default: {\n // Cursor never delivers Notification / PermissionRequest (no native\n // equivalent — permission is an OUTPUT field of its before* hooks, not\n // an event). If the runtime dispatches one anyway, fail loudly.\n throw new Error(`unsupported cursor hook event: ${String(event)}`);\n }\n }\n }\n\n private getProjectDir(input: CursorWireInput): string | undefined {\n return input.cwd ?? input.workspace_roots?.[0] ?? undefined;\n }\n\n // ── Runtime: normalized response → Cursor native hook reply ──────────────\n\n formatReply(event: HookEventName, response: HookResponse): HookReply {\n const decision = response.decision ?? \"allow\";\n\n // postToolUseFailure (feedback beside the error) and subagentStart (context\n // injected into the SUBAGENT's conversation) are observe/context-only on\n // Cursor: \"context\" emits additional_context, and a \"deny\" DEGRADES to the\n // same shape carrying the reason (the tool already failed / the spawn is\n // not blockable). Everything else is a minimal no-op payload (Cursor\n // rejects empty stdout as \"no valid response\").\n if (event === \"PostToolUseFailure\" || event === \"SubagentStart\") {\n const context =\n decision === \"context\"\n ? response.additionalContext\n : decision === \"deny\"\n ? response.reason ?? response.additionalContext\n : undefined;\n return this.stdout({ additional_context: context ?? \"\" });\n }\n\n // beforeSubmitPrompt (UserPromptSubmit) is a BLOCK gate, not a permission/\n // context surface: its only documented output is { continue, user_message }\n // (cursor.com/docs/hooks). A \"deny\" prevents submission (continue:false +\n // reason); it cannot inject context (no additional_context/agent_message\n // field), so every non-deny decision is a no-op continue:true.\n if (event === \"UserPromptSubmit\") {\n if (decision === \"deny\") {\n return this.stdout({\n continue: false,\n user_message: response.reason ?? \"Blocked by hook\",\n });\n }\n return this.stdout({ continue: true });\n }\n\n // sessionEnd is fire-and-forget (the response is logged but not used) and\n // preCompact is observational (cannot block or modify compaction) per\n // cursor.com/docs/hooks — neither carries a decision Cursor honors, so both\n // are an unconditional no-op passthrough (mirrors Stop).\n if (event === \"SessionEnd\" || event === \"PreCompact\") {\n return { exitCode: 0 };\n }\n\n // deny → block the action with a user-facing message. (On SubagentStop\n // this follows the adapter's Stop idiom — the deny carries Stop semantics.)\n if (decision === \"deny\") {\n return this.stdout({\n permission: \"deny\",\n user_message: response.reason ?? \"Blocked by hook\",\n });\n }\n\n // ask → prompt the user to confirm.\n if (decision === \"ask\") {\n return this.stdout({\n permission: \"ask\",\n user_message: response.reason ?? \"Confirmation required by hook\",\n });\n }\n\n // modify → rewrite PreToolUse input (only where Cursor supports it).\n if (decision === \"modify\") {\n if (event === \"PreToolUse\" && response.updatedInput) {\n return this.stdout({ updated_input: response.updatedInput });\n }\n // Output rewrite is unsupported on Cursor; fall through to allow.\n }\n\n // context → inject soft guidance. PreToolUse uses `agent_message`; Post and\n // SessionStart use `additional_context`.\n if (decision === \"context\" && response.additionalContext) {\n return event === \"PreToolUse\"\n ? this.stdout({ agent_message: response.additionalContext })\n : this.stdout({ additional_context: response.additionalContext });\n }\n\n // SessionStart always emits valid JSON even on a no-op (Cursor rejects empty\n // stdout as \"no valid response\").\n if (event === \"SessionStart\") {\n return this.stdout({ additional_context: response.additionalContext ?? \"\" });\n }\n\n // allow / void → minimal no-op payload (Cursor rejects empty stdout).\n if (event === \"PreToolUse\") return this.stdout({ agent_message: \"\" });\n if (event === \"PostToolUse\") return this.stdout({ additional_context: \"\" });\n return { exitCode: 0 };\n }\n\n private stdout(payload: unknown): HookReply {\n return { exitCode: 0, stdout: JSON.stringify(payload) };\n }\n}\n\n/** Cursor native interpolation token: `${env:VAR}` → `${env:VAR}` (passthrough). */\nfunction cursorEnvToken(name: string): string {\n return `\\${env:${name}}`;\n}\n\nfunction extractSessionId(input: CursorWireInput): string {\n if (typeof input.conversation_id === \"string\") return input.conversation_id;\n if (typeof input.session_id === \"string\") return input.session_id;\n return \"\";\n}\n\nexport const adapter = new CursorAdapter();\nexport default adapter;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAsBA,SAAS,kBAAkB;AAC3B,SAAS,eAAe;AACxB,SAAS,YAAY;AAoCrB,IAAM,OAAmB;AACzB,IAAM,eAAe;AAGrB,IAAM,uBAAuB;AAQ7B,IAAM,eAAe;AAAA,EACnB,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,cAAc;AAAA,EACd,MAAM;AAAA,EACN,oBAAoB;AAAA,EACpB,eAAe;AAAA,EACf,cAAc;AAAA;AAAA;AAAA;AAAA;AAAA,EAKd,YAAY;AAAA,EACZ,YAAY;AAAA,EACZ,kBAAkB;AACpB;AAaA,IAAM,YAAoD;AAAA,EACxD,YAAY,aAAa;AAAA,EACzB,aAAa,aAAa;AAAA,EAC1B,cAAc,aAAa;AAAA,EAC3B,MAAM,aAAa;AAAA,EACnB,oBAAoB,aAAa;AAAA,EACjC,eAAe,aAAa;AAAA,EAC5B,cAAc,aAAa;AAAA,EAC3B,YAAY,aAAa;AAAA,EACzB,YAAY,aAAa;AAAA,EACzB,kBAAkB,aAAa;AACjC;AA4DO,IAAM,gBAAN,cAA4B,YAA+B;AAAA,EACvD,KAAiB;AAAA,EACjB,OAAO;AAAA,EACP,WAAyB;AAAA,EAEzB,eAAqC;AAAA;AAAA;AAAA,IAG5C,gBAAgB;AAAA;AAAA;AAAA,IAGhB,YAAY;AAAA,IACZ,aAAa;AAAA,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"],"sourcesContent":["/**\n * adapters/goose — Block's Goose platform adapter for agent-connector.\n *\n * Goose is a json-stdio host, but its two config surfaces use DIFFERENT formats:\n *\n * - MCP servers (Goose calls them \"extensions\") live in a YAML config under the\n * root key `extensions`. The native stdio entry shape is Goose-specific:\n * { type: \"stdio\", cmd: <exe>, args: [...], envs: {...}, timeout, enabled }\n * NOTE the field is `cmd` (NOT `command`) and the env map is `envs` (NOT\n * `env`). Because the file is YAML, the BaseAdapter JSON helpers do not apply\n * — we merge via core/yaml's readYaml/writeYaml, preserving any other config.\n *\n * - Hooks use Goose's Open Plugins system, which stores hook registrations in\n * JSON at <root>/.agents/plugins/<plugin-name>/hooks/hooks.json (project root\n * = <projectDir>/.agents; user root = ~/.agents):\n * { hooks: { <Event>: [ { matcher?, hooks:[{ type:\"command\", command }] } ] } }\n * The shape is the Claude-style NESTED rule (an optional `matcher` plus an\n * inner `hooks` array), and there is NO top-level `version` key. This file is\n * plain JSON, so the standard fs/JSON helpers are used for it.\n *\n * Wire protocol (parse) is Claude-compatible JSON on stdin, except Goose names\n * the working directory field `working_dir` (not `cwd`). The deny reply is\n * Goose's `{ decision: \"block\", reason }` (NOT Claude's hookSpecificOutput\n * permissionDecision shape).\n *\n * Native config locations (user scope):\n * - Linux/macOS: ~/.config/goose/config.yaml\n * - Windows: %APPDATA%/Block/goose/config/config.yaml\n */\n\nimport { existsSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nimport { BaseAdapter, type HookMergeDescriptor } from \"../base.js\";\nimport type { Adapter, HookReply, InstallContext, MemoryTarget, NormalizedEvent } from \"../spi.js\";\nimport type {\n ChangeRecord,\n DetectedPlatform,\n HealthCheck,\n HookEventName,\n HookParadigm,\n HookResponse,\n NotificationEvent,\n PlatformCapabilities,\n PlatformId,\n PostToolUseEvent,\n PostToolUseFailureEvent,\n PreCompactEvent,\n PreToolUseEvent,\n SessionEndEvent,\n SessionStartEvent,\n ServerDef,\n StopEvent,\n UserPromptSubmitEvent,\n} from \"../../core/types.js\";\nimport { removeFromObjectMap, upsertInObjectMap } from \"../../core/object-map.js\";\nimport { roamingAppData } from \"../../core/host-paths.js\";\nimport { readYaml, yamlObjectMapCodec } from \"../../core/yaml.js\";\nimport { resolveEnvRefsDeep } from \"../../core/interpolate.js\";\nimport {\n buildHomeBinHookCommand,\n buildWrappedStdio,\n isHomeBinHookCommand,\n} from \"../../core/spawn.js\";\nimport { renderSkillMd } from \"../claude-code/render.js\";\nimport { normalizeSessionSource } from \"../claude-code/wire.js\";\n\nconst HOST: PlatformId = \"goose\";\n/** Root key under which Goose stores MCP servers (\"extensions\") in config.yaml. */\nconst MCP_ROOT_KEY = \"extensions\";\n\n/**\n * Map each normalized hook event to the matching capability flag on this\n * adapter. The adapter's own `capabilities` literal is the single source of\n * truth for what Goose's Open-Plugins runtime delivers (PreToolUse/PostToolUse/\n * SessionStart/PostToolUseFailure); installHooks filters declared events\n * through this map so an unsupported event (e.g. UserPromptSubmit) is never\n * written verbatim into hooks.json — it is reported as a graceful warn/skip\n * instead.\n */\nconst EVENT_CAPABILITY: Record<HookEventName, keyof PlatformCapabilities> = {\n SessionStart: \"sessionStart\",\n SessionEnd: \"sessionEnd\",\n UserPromptSubmit: \"userPromptSubmit\",\n PreToolUse: \"preToolUse\",\n PostToolUse: \"postToolUse\",\n PreCompact: \"preCompact\",\n Stop: \"stop\",\n Notification: \"notification\",\n // Newer events. Goose's hooks system ships a dedicated PostToolUseFailure;\n // it has NO permission-dialog or subagent lifecycle events, so those three\n // flags stay unset on `capabilities` and warn-skip at install.\n PermissionRequest: \"permissionRequest\",\n PostToolUseFailure: \"postToolUseFailure\",\n SubagentStart: \"subagentStart\",\n SubagentStop: \"subagentStop\",\n // Goose has no post-compaction hook either — postCompact stays unset on\n // `capabilities`, so a declared PostCompact warn-skips at install.\n PostCompact: \"postCompact\",\n};\n\n/**\n * Goose extension (MCP server) entry — note the Goose-specific field names:\n * `cmd` (not `command`) and `envs` (not `env`).\n */\ninterface GooseStdioExtension {\n type: \"stdio\";\n cmd: string;\n args: string[];\n envs?: Record<string, string>;\n timeout: number;\n enabled: boolean;\n}\n\n/** One inner command entry inside a hook rule. */\ninterface GooseHookCommand {\n type: \"command\";\n command: string;\n}\n\n/**\n * One nested-rule entry under a hook event. Goose's Open Plugins spec uses the\n * Claude-shaped nested rule: an optional `matcher` plus an inner `hooks` array\n * of `{ type, command }` commands (NOT a flat list of commands).\n */\ninterface GooseHookRule {\n matcher?: string;\n hooks: GooseHookCommand[];\n}\n\n/**\n * Goose Open-Plugins hooks.json shape: `{ hooks: { <Event>: [ rule, ... ] } }`.\n * There is NO top-level `version` key in the spec.\n */\ninterface GooseHooksFile {\n hooks: Record<string, GooseHookRule[]>;\n}\n\n/** Raw Goose hook stdin payload (Claude-compatible JSON). */\ninterface GooseWireInput {\n session_id?: string;\n /** Goose names the working directory `working_dir`; `cwd` is a fallback. */\n working_dir?: string;\n cwd?: string;\n hook_event_name?: string;\n tool_name?: string;\n tool_input?: Record<string, unknown>;\n tool_response?: unknown;\n // PostToolUseFailure (Claude-compatible failure fields)\n tool_use_id?: string;\n error?: string;\n is_interrupt?: boolean;\n duration_ms?: number;\n source?: string;\n reason?: string;\n prompt?: string;\n trigger?: string;\n stop_hook_active?: boolean;\n message?: string;\n is_error?: boolean;\n /** Injected by the entrypoint so the runtime knows which connector to dispatch. */\n connector?: string;\n}\n\nexport class GooseAdapter extends BaseAdapter implements Adapter {\n readonly id: PlatformId = HOST;\n readonly name = \"Goose\";\n readonly paradigm: HookParadigm = \"json-stdio\";\n\n readonly capabilities: PlatformCapabilities = {\n // Memory surface: AGENTS.md-first managed block (project <projectDir>/AGENTS.md\n // via the base default — goose reads AGENTS.md AND .goosehints at each level,\n // .goosehints left untouched; user scope → the global .goosehints below).\n supportsMemory: true,\n preToolUse: true,\n postToolUse: true,\n preCompact: false,\n sessionStart: true,\n // Goose's Open Plugins runtime fires SessionEnd / UserPromptSubmit / Stop\n // (goose-docs.ai/blog/2026/05/14/goose-hooks/); parseEvent + the wire types\n // already handle all three, so they are wired (were incorrectly gated false).\n sessionEnd: true,\n userPromptSubmit: true,\n stop: true,\n notification: false,\n // Newer events: Goose ships a dedicated PostToolUseFailure hook (feedback\n // beside the error; the failure itself is not blockable). Goose has no\n // permission-dialog event and no subagent lifecycle hooks, so\n // permissionRequest / subagentStart / subagentStop stay unset — install\n // reports the standard skip-warn for them.\n postToolUseFailure: true,\n // Open Plugins documents PreToolUse/PostToolUse/SessionStart; argument\n // rewrite is not guaranteed across versions, so default to the safe value.\n canModifyArgs: false,\n canModifyOutput: false,\n canInjectSessionContext: true,\n transports: [\"stdio\", \"sse\", \"http\"],\n // Content surfaces: goose reads SKILL.md from the cross-agent .agents dir\n // skill → <projectDir>/.agents/skills/<name>/SKILL.md (project)\n // skill → ~/.agents/skills/<name>/SKILL.md (user)\n // (NOT ~/.config/goose). Commands/subagents have no confirmed native dir, so\n // those flags stay unset and warn-skip via the BaseAdapter default.\n supportsSkills: true,\n };\n\n // ── Detection ────────────────────────────────────────────────────────────\n\n detectInstalled(_projectDir: string): DetectedPlatform {\n const configPath = this.userConfigPath();\n const configDir = dirname(configPath);\n const installed = existsSync(configDir) || existsSync(configPath);\n return {\n id: this.id,\n name: this.name,\n installed,\n paradigm: this.paradigm,\n capabilities: this.capabilities,\n configPath,\n scope: \"user\",\n reason: installed\n ? `found Goose config at ${configPath}`\n : `no Goose config at ${configPath}`,\n confidence: installed ? \"high\" : \"low\",\n };\n }\n\n // ── Native paths ─────────────────────────────────────────────────────────\n\n override getConfigDir(_ctx: InstallContext): string {\n return dirname(this.userConfigPath());\n }\n\n /** MCP config: the YAML config.yaml (user scope). */\n override getServerConfigPath(_ctx: InstallContext): string {\n return this.userConfigPath();\n }\n\n /**\n * Hooks: Open-Plugins hooks.json under the `.agents/plugins/<plugin-name>/`\n * dir. The connector id is the plugin name. Project scope roots at\n * `<projectDir>/.agents`; user scope roots at `~/.agents`.\n */\n override getHookConfigPath(ctx: InstallContext): string {\n const root = ctx.scope === \"project\" ? ctx.projectDir : homedir();\n return join(root, \".agents\", \"plugins\", ctx.connector.id, \"hooks\", \"hooks.json\");\n }\n\n /**\n * OS-correct user config.yaml path:\n * - Windows: %APPDATA%/Block/goose/config/config.yaml\n * - macOS/Linux: ~/.config/goose/config.yaml\n */\n private userConfigPath(): string {\n if (process.platform === \"win32\") {\n return join(roamingAppData(), \"Block\", \"goose\", \"config\", \"config.yaml\");\n }\n return join(homedir(), \".config\", \"goose\", \"config.yaml\");\n }\n\n // ── Memory surface: global .goosehints at user scope ────────────────────\n // Project scope stays on the AGENTS.md base default (goose reads project\n // AGENTS.md and .goosehints at each level by default — one canonical copy in\n // the standard file; the user's .goosehints is never touched). User scope:\n // goose's only documented global memory file is the .goosehints next to\n // config.yaml (~/.config/goose/.goosehints; Windows under\n // %APPDATA%\\Block\\goose\\config — adapter-corroborated, verify per version).\n protected override memoryTargets(ctx: InstallContext): MemoryTarget[] {\n if (this.memoryOverride(ctx)?.path || ctx.scope !== \"user\") {\n return super.memoryTargets(ctx);\n }\n return [\n {\n path: join(dirname(this.userConfigPath()), \".goosehints\"),\n reason: \"goose global hints file (.goosehints beside config.yaml)\",\n },\n ];\n }\n\n // ── MCP server install / uninstall (YAML — merge via readYaml/writeYaml) ──\n\n override installServer(ctx: InstallContext): ChangeRecord[] {\n const { connector, dryRun } = ctx;\n const path = this.getServerConfigPath(ctx);\n const server = this.effectiveServer(ctx);\n\n if (!server) {\n return [\n {\n platform: this.id,\n action: \"skip\",\n path,\n detail: connector.server\n ? \"server registration disabled for goose\"\n : \"connector declares no MCP server\",\n },\n ];\n }\n\n const entry = this.renderExtension(ctx, server);\n\n // Merge into existing YAML, preserving every other config key + extension.\n return [\n upsertInObjectMap({\n codec: yamlObjectMapCodec(),\n rootKey: MCP_ROOT_KEY,\n policy: \"coerce\",\n platform: this.id,\n configPath: path,\n entryId: connector.id,\n entry,\n dryRun,\n }),\n ];\n }\n\n override uninstallServer(ctx: InstallContext): ChangeRecord[] {\n const { connector, dryRun } = ctx;\n const path = this.getServerConfigPath(ctx);\n return [\n removeFromObjectMap({\n codec: yamlObjectMapCodec(),\n rootKey: MCP_ROOT_KEY,\n policy: \"coerce\",\n platform: this.id,\n configPath: path,\n entryId: connector.id,\n dryRun,\n }),\n ];\n }\n\n /**\n * Render a normalized ServerDef into Goose's native extension entry. Goose has\n * no native env interpolation, so `${env:VAR}` refs are resolved to literals at\n * install time. Honors the telemetry serve-wrapper (cmd=homeBin, args=[serve…]).\n */\n private renderExtension(ctx: InstallContext, server: ServerDef): GooseStdioExtension {\n let cmd = server.command ?? \"\";\n let args = [...(server.args ?? [])];\n\n ({ command: cmd, args } = buildWrappedStdio(ctx, server, this.id, cmd, args));\n\n cmd = resolveEnvRefsDeep(cmd);\n args = resolveEnvRefsDeep(args);\n\n const timeoutMs = server.timeoutMs;\n const timeout =\n typeof timeoutMs === \"number\" && timeoutMs > 0 ? Math.round(timeoutMs / 1000) : 300;\n\n const entry: GooseStdioExtension = {\n type: \"stdio\",\n cmd,\n args,\n timeout,\n enabled: server.enabled !== false,\n };\n\n if (server.env && Object.keys(server.env).length > 0) {\n const envs: Record<string, string> = {};\n for (const [k, v] of Object.entries(resolveEnvRefsDeep(server.env))) {\n envs[k] = String(v);\n }\n entry.envs = envs;\n }\n return entry;\n }\n\n // ── Hook install / uninstall (JSON Open-Plugins hooks.json) ───────────────\n\n override installHooks(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n const path = this.getHookConfigPath(ctx);\n\n if (connector.platforms[HOST]?.hooks === false) {\n return [{ platform: this.id, action: \"skip\", path, detail: \"hooks disabled for goose\" }];\n }\n if (connector.hookEvents.length === 0) {\n return [{ platform: this.id, action: \"skip\", path, detail: \"connector declares no hooks\" }];\n }\n\n const pending = connector.hookEvents.map((event) => ({\n event,\n matcher: connector.hooks[event]?.matcher ?? \"\",\n }));\n return this.upsertHookEntries(ctx, path, pending, this.hookDescriptor(ctx));\n }\n\n override uninstallHooks(ctx: InstallContext): ChangeRecord[] {\n return this.removeHookEntries(ctx, this.getHookConfigPath(ctx), this.hookDescriptor(ctx));\n }\n\n /**\n * Goose's hook-merge descriptor for the shared object-map engine. Goose's hook\n * file is the DEDICATED per-connector `.agents/plugins/<id>/hooks/hooks.json`\n * (NESTED rule shape `{ matcher?, hooks:[{type,command}] }`), so every\n * observable string + ownership predicate is carried here to reproduce the\n * prior in-adapter loop byte-for-byte:\n * - malformedPolicy \"coerce\" — a present-but-malformed `hooks` root (array /\n * primitive, hand-edited) and a non-array event bucket are coerced to fresh\n * containers, matching the old readHooksFile coerce + the `??=` bucket fill.\n * - mapEvent = the CAPABILITY FILTER: an event Goose's Open-Plugins runtime\n * does not deliver (e.g. UserPromptSubmit, PreCompact) maps to undefined →\n * the engine emits the `<event> unsupported on goose — skipped` warn and\n * never writes it; supported events map to themselves (identity).\n * - entryOwnsCommand is connector-GENERIC (ANY of our commands in the nested\n * inner `hooks`) — the old ruleHasOurCommand.\n * - uninstall is NESTED: ownsEntryForRemove is never-true so the engine only\n * runs stripInner — strip our owned inner commands, keep foreign ones, drop\n * emptied rules. The rebuilt rule OMITS `matcher` when it was undefined\n * (distinct from claude/droid/qwen, which always emit a matcher); `removed`\n * is the inner-command count, surfaced in the `(<n>)` remove detail.\n */\n private hookDescriptor(ctx: InstallContext): HookMergeDescriptor<GooseHookRule> {\n return {\n malformedPolicy: \"coerce\",\n // CAPABILITY FILTER → identity-or-undefined: supported events map to\n // themselves; an unsupported one (capability !== true) maps to undefined,\n // routing it to the warn-skip path.\n mapEvent: (e) =>\n this.capabilities[EVENT_CAPABILITY[e as HookEventName]] === true ? e : undefined,\n unmappedWarnDetail: (e) => `${e} unsupported on goose — skipped`,\n // NESTED rule, matcher-FIRST key order (matches the old `desired`).\n renderEntry: (_event, matcher, command) => ({\n matcher,\n hooks: [{ type: \"command\", command }],\n }),\n // Connector-generic find (= the old ruleHasOurCommand): ANY inner command ours.\n entryOwnsCommand: (rule, _command) =>\n (rule.hooks ?? []).some((h) => this.isOurCommand(h.command, ctx)),\n // NESTED: never drop a whole rule; inner-strip only.\n ownsEntryForRemove: () => () => false,\n stripInner: (c) => (rule) => {\n const innerBefore = rule.hooks?.length ?? 0;\n const inner = (rule.hooks ?? []).filter((h) => !this.isOurCommand(h.command, c));\n return {\n // MATCHER-OMITTED-WHEN-UNDEFINED: reproduce the old rebuild exactly —\n // key order is `matcher` (only when present) then `hooks`.\n next:\n inner.length > 0\n ? { ...(rule.matcher !== undefined ? { matcher: rule.matcher } : {}), hooks: inner }\n : null,\n removed: innerBefore - inner.length,\n };\n },\n skipDetail: (e) => `hooks.${e}`,\n removeDetail: (e, n) => `hooks.${e} (${n})`,\n absentDetail: \"no hooks.json\",\n noMatchDetail: \"no matching hook entries\",\n };\n }\n\n /** True when a hook command is ours (anchored home-bin + connector id). */\n private isOurCommand(command: string | undefined, ctx: InstallContext): boolean {\n return isHomeBinHookCommand(command, ctx.homeBinPath, ctx.connector.id);\n }\n\n // ── Diagnostics ──────────────────────────────────────────────────────────\n\n override getHealthChecks(ctx: InstallContext): readonly HealthCheck[] {\n const serverPath = this.getServerConfigPath(ctx);\n const hookPath = this.getHookConfigPath(ctx);\n const id = ctx.connector.id;\n const homeBin = ctx.homeBinPath;\n const hookEvents = ctx.connector.hookEvents;\n const checks: HealthCheck[] = [\n {\n name: `${this.name}: config.yaml present`,\n check: () =>\n existsSync(serverPath)\n ? { status: \"OK\", detail: serverPath }\n : { status: \"FAIL\", detail: `not found: ${serverPath}` },\n },\n {\n name: `${this.name}: ${MCP_ROOT_KEY}.${id} registered`,\n check: () => {\n if (!ctx.connector.server) return { status: \"OK\", detail: \"no MCP server declared\" };\n const cfg = readYaml<Record<string, unknown>>(serverPath);\n const bucket = cfg?.[MCP_ROOT_KEY];\n const present =\n typeof bucket === \"object\" &&\n bucket !== null &&\n !Array.isArray(bucket) &&\n id in (bucket as Record<string, unknown>);\n return present\n ? { status: \"OK\", detail: `${MCP_ROOT_KEY}.${id}` }\n : { status: \"FAIL\", detail: `${MCP_ROOT_KEY}.${id} not found in ${serverPath}` };\n },\n },\n {\n name: `${this.name}: hook command registered`,\n check: () => {\n if (hookEvents.length === 0) return { status: \"OK\", detail: \"no hooks declared\" };\n const file = this.readJson<GooseHooksFile>(hookPath);\n if (!file || !file.hooks) {\n return { status: \"FAIL\", detail: `cannot read ${hookPath}` };\n }\n const registered = Object.values(file.hooks).some((bucket) =>\n (bucket ?? []).some((rule) =>\n (rule.hooks ?? []).some((h) => isHomeBinHookCommand(h.command, homeBin, id)),\n ),\n );\n return registered\n ? { status: \"OK\", detail: \"hook command present\" }\n : { status: \"FAIL\", detail: `no hook for ${id} in ${hookPath}` };\n },\n },\n ];\n\n // Content-surface checks: assert presence only for skills this connector\n // declares (goose skills live under the .agents skills dir at either scope).\n for (const skill of ctx.connector.skills) {\n const p = join(this.skillDir(ctx, skill.name), \"SKILL.md\");\n checks.push({\n name: `${this.name}: skill ${skill.name} present`,\n check: () =>\n existsSync(p) ? { status: \"OK\", detail: p } : { status: \"FAIL\", detail: `not found: ${p}` },\n });\n }\n return checks;\n }\n\n // ── Content surface: skills ───────────────────────────────────────────────\n // CONTENT-ONLY: pure native-file writer. No runtime dispatch, no home-bin\n // pointer, no telemetry wrap. Idempotent (byte-identical → skip) via\n // writeContentFile and reversible via removeContentFile + removeDirIfEmpty.\n // Honors platforms[\"goose\"].skills === false to skip.\n //\n // goose reads SKILL.md from the cross-agent .agents dir (NOT ~/.config/goose):\n // project scope → <projectDir>/.agents/skills/<name>/SKILL.md\n // user scope → ~/.agents/skills/<name>/SKILL.md\n\n private skillsDir(ctx: InstallContext): string {\n return ctx.scope === \"project\"\n ? join(ctx.projectDir, \".agents\", \"skills\")\n : join(homedir(), \".agents\", \"skills\");\n }\n\n private skillDir(ctx: InstallContext, name: string): string {\n return join(this.skillsDir(ctx), name);\n }\n\n override installSkills(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n if (connector.platforms[HOST]?.skills === false) {\n return [{ platform: this.id, action: \"skip\", detail: \"skills disabled for goose\" }];\n }\n if (connector.skills.length === 0) {\n return [{ platform: this.id, action: \"skip\", detail: \"connector declares no skills\" }];\n }\n const changes: ChangeRecord[] = [];\n for (const skill of connector.skills) {\n const dir = this.skillDir(ctx, skill.name);\n changes.push(\n this.writeContentFile(join(dir, \"SKILL.md\"), renderSkillMd(skill), ctx.dryRun),\n );\n // Bundle any resource files beside SKILL.md (relative path → contents).\n // Defense-in-depth: skip+warn on any key that escapes the skill dir\n // (config-time validation already rejects these, but never trust input).\n for (const [rel, contents] of Object.entries(skill.resources ?? {})) {\n const target = this.resolveWithin(dir, rel);\n if (target === null) {\n changes.push({\n platform: this.id,\n action: \"warn\",\n detail: `skill resource \"${rel}\" escapes the skill dir; skipped`,\n });\n continue;\n }\n changes.push(this.writeContentFile(target, contents, ctx.dryRun));\n }\n }\n return changes;\n }\n\n override uninstallSkills(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n if (connector.skills.length === 0) {\n return [{ platform: this.id, action: \"skip\", detail: \"connector declares no skills\" }];\n }\n const changes: ChangeRecord[] = [];\n for (const skill of connector.skills) {\n const dir = this.skillDir(ctx, skill.name);\n // Remove only the files we wrote (SKILL.md + declared resources), then the\n // skill dir itself when we own its full contents.\n changes.push(this.removeContentFile(join(dir, \"SKILL.md\"), ctx.dryRun));\n for (const rel of Object.keys(skill.resources ?? {})) {\n const target = this.resolveWithin(dir, rel);\n if (target === null) continue; // never delete outside the skill dir\n changes.push(this.removeContentFile(target, ctx.dryRun));\n }\n // Only remove the skill dir when WE own its full contents — never rm -rf a\n // dir that still holds user-added / sibling-tool / shared files.\n changes.push(this.removeDirIfEmpty(dir, ctx.dryRun));\n }\n return changes;\n }\n\n // ── Runtime: parse Goose stdin JSON → normalized event ───────────────────\n\n parseEvent(event: HookEventName, raw: unknown): NormalizedEvent {\n const input = (raw ?? {}) as GooseWireInput;\n // Goose sends the working directory as `working_dir`; fall back to `cwd`.\n const projectDir =\n typeof input.working_dir === \"string\"\n ? input.working_dir\n : typeof input.cwd === \"string\"\n ? input.cwd\n : undefined;\n const base = {\n hostPlatform: HOST,\n connectorId: typeof input.connector === \"string\" ? input.connector : \"\",\n sessionId: typeof input.session_id === \"string\" ? input.session_id : \"\",\n ...(projectDir !== undefined ? { projectDir } : {}),\n raw,\n } as const;\n\n switch (event) {\n case \"PreToolUse\": {\n const ev: PreToolUseEvent = {\n ...base,\n toolName: input.tool_name ?? \"\",\n toolInput: input.tool_input ?? {},\n };\n return ev;\n }\n case \"PostToolUse\": {\n const ev: PostToolUseEvent = {\n ...base,\n toolName: input.tool_name ?? \"\",\n toolInput: input.tool_input ?? {},\n ...(toolResponseToString(input.tool_response) !== undefined\n ? { toolOutput: toolResponseToString(input.tool_response) }\n : {}),\n ...(typeof input.is_error === \"boolean\" ? { isError: input.is_error } : {}),\n };\n return ev;\n }\n case \"SessionStart\": {\n const ev: SessionStartEvent = { ...base, source: normalizeSessionSource(input.source) };\n return ev;\n }\n case \"SessionEnd\": {\n const ev: SessionEndEvent = {\n ...base,\n ...(typeof input.reason === \"string\" ? { reason: input.reason } : {}),\n };\n return ev;\n }\n case \"UserPromptSubmit\": {\n const ev: UserPromptSubmitEvent = {\n ...base,\n prompt: typeof input.prompt === \"string\" ? input.prompt : \"\",\n };\n return ev;\n }\n case \"PreCompact\": {\n const ev: PreCompactEvent = {\n ...base,\n ...(input.trigger === \"auto\" || input.trigger === \"manual\"\n ? { trigger: input.trigger }\n : {}),\n };\n return ev;\n }\n case \"Stop\": {\n const ev: StopEvent = {\n ...base,\n ...(typeof input.stop_hook_active === \"boolean\"\n ? { stopHookActive: input.stop_hook_active }\n : {}),\n };\n return ev;\n }\n case \"Notification\": {\n const ev: NotificationEvent = {\n ...base,\n message: typeof input.message === \"string\" ? input.message : \"\",\n };\n return ev;\n }\n case \"PostToolUseFailure\": {\n const ev: PostToolUseFailureEvent = {\n ...base,\n toolName: input.tool_name ?? \"\",\n toolInput: input.tool_input ?? {},\n error: typeof input.error === \"string\" ? input.error : \"\",\n ...(typeof input.tool_use_id === \"string\"\n ? { toolUseId: input.tool_use_id }\n : {}),\n ...(typeof input.is_interrupt === \"boolean\"\n ? { isInterrupt: input.is_interrupt }\n : {}),\n ...(typeof input.duration_ms === \"number\"\n ? { durationMs: input.duration_ms }\n : {}),\n };\n return ev;\n }\n case \"PermissionRequest\":\n case \"SubagentStart\":\n case \"SubagentStop\":\n case \"PostCompact\": {\n // No Goose analog (no permission-dialog event, no subagent lifecycle\n // hooks, no post-compaction hook). Install already skip-warns these via\n // EVENT_CAPABILITY; a runtime dispatch is a mis-route — fail loudly.\n throw new Error(`unsupported goose hook event: ${String(event)}`);\n }\n default: {\n const _never: never = event;\n throw new Error(`unsupported goose hook event: ${String(_never)}`);\n }\n }\n }\n\n // ── Runtime: normalized response → Goose native hook reply (Claude-shaped) ─\n\n formatReply(event: HookEventName, response: HookResponse): HookReply {\n const decision = response.decision ?? \"allow\";\n\n // PostToolUseFailure is feedback-only (the tool already failed, nothing is\n // blockable): \"context\" injects additionalContext beside the error, and a\n // \"deny\" DEGRADES to the same shape carrying the reason — it must never\n // render as `{ decision: \"block\" }`.\n if (event === \"PostToolUseFailure\") {\n const context =\n decision === \"context\"\n ? response.additionalContext\n : decision === \"deny\"\n ? response.reason ?? response.additionalContext\n : undefined;\n if (context) return this.stdout({ additionalContext: context });\n return { exitCode: 0 };\n }\n\n // deny → Goose blocks via `{ decision: \"block\", reason }` on stdout JSON\n // (NOT Claude's hookSpecificOutput.permissionDecision shape).\n if (decision === \"deny\") {\n return this.stdout({\n decision: \"block\",\n reason: response.reason ?? \"Blocked by hook\",\n });\n }\n\n // ask → Goose has no native \"ask\"; degrade to block to stay fail-safe.\n if (decision === \"ask\") {\n return this.stdout({\n decision: \"block\",\n reason: response.reason ?? \"Confirmation required by hook\",\n });\n }\n\n if (decision === \"context\" && response.additionalContext) {\n return this.stdout({ additionalContext: response.additionalContext });\n }\n\n // allow / modify (unsupported) / void → pass through.\n return { exitCode: 0 };\n }\n\n private stdout(payload: unknown): HookReply {\n return { exitCode: 0, stdout: JSON.stringify(payload) };\n }\n\n // ── Internal helpers ──────────────────────────────────────────────────────\n\n /** Resolve the per-platform server override into an effective ServerDef. */\n private effectiveServer(ctx: InstallContext): ServerDef | undefined {\n const override = ctx.connector.platforms[this.id]?.server;\n if (override === false) return undefined;\n const base = ctx.connector.server;\n if (!base) return undefined;\n return override && typeof override === \"object\" ? { ...base, ...override } : base;\n }\n}\n\n/** Coerce a Goose PostToolUse `tool_response` into a string. */\nfunction toolResponseToString(value: unknown): string | undefined {\n if (value == null) return undefined;\n if (typeof value === \"string\") return value;\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\nexport const adapter = new GooseAdapter();\nexport default adapter;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,SAAS,kBAAkB;AAC3B,SAAS,eAAe;AACxB,SAAS,SAAS,YAAY;AAoC9B,IAAM,OAAmB;AAEzB,IAAM,eAAe;AAWrB,IAAM,mBAAsE;AAAA,EAC1E,cAAc;AAAA,EACd,YAAY;AAAA,EACZ,kBAAkB;AAAA,EAClB,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,YAAY;AAAA,EACZ,MAAM;AAAA,EACN,cAAc;AAAA;AAAA;AAAA;AAAA,EAId,mBAAmB;AAAA,EACnB,oBAAoB;AAAA,EACpB,eAAe;AAAA,EACf,cAAc;AAAA;AAAA;AAAA,EAGd,aAAa;AACf;AAiEO,IAAM,eAAN,cAA2B,YAA+B;AAAA,EACtD,KAAiB;AAAA,EACjB,OAAO;AAAA,EACP,WAAyB;AAAA,EAEzB,eAAqC;AAAA;AAAA;AAAA;AAAA,IAI5C,gBAAgB;AAAA,IAChB,YAAY;AAAA,IACZ,aAAa;AAAA,IACb,YAAY;AAAA,IACZ,cAAc;AAAA;AAAA;AAAA;AAAA,IAId,YAAY;AAAA,IACZ,kBAAkB;AAAA,IA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A,EACxD;AAAA;AAAA;AAAA,EAKQ,gBAAgB,KAA4C;AAClE,UAAM,WAAW,IAAI,UAAU,UAAU,KAAK,EAAE,GAAG;AACnD,QAAI,aAAa,MAAO,QAAO;AAC/B,UAAM,OAAO,IAAI,UAAU;AAC3B,QAAI,CAAC,KAAM,QAAO;AAClB,WAAO,YAAY,OAAO,aAAa,WAAW,EAAE,GAAG,MAAM,GAAG,SAAS,IAAI;AAAA,EAC/E;AACF;AAGA,SAAS,qBAAqB,OAAoC;AAChE,MAAI,SAAS,KAAM,QAAO;AAC1B,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,MAAI;AACF,WAAO,KAAK,UAAU,KAAK;AAAA,EAC7B,QAAQ;AACN,WAAO,OAAO,KAAK;AAAA,EACrB;AACF;AAEO,IAAM,UAAU,IAAI,aAAa;AACxC,IAAO,gBAAQ;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/adapters/hermes/index.ts"],"sourcesContent":["/**\n * adapters/hermes — Hermes Agent platform adapter for agent-connector.\n *\n * Hermes is a json-stdio host whose ENTIRE configuration — both the MCP servers\n * and the lifecycle hooks — lives in a single user-scope YAML file:\n *\n * ~/.hermes/config.yaml\n *\n * Because the file is YAML, the BaseAdapter JSON helpers do not apply; this\n * adapter merges via core/yaml's readYaml/writeYaml, preserving any unrelated\n * config the user has authored.\n *\n * - MCP servers: top-level snake_case root key `mcp_servers`. The stdio entry\n * uses the portable field names { command, args, env } (unlike Goose's\n * cmd/envs). Hermes has no native env interpolation, so `${env:VAR}` refs are\n * resolved to literals at install time.\n *\n * - Hooks: a top-level `hooks` map keyed by Hermes' NATIVE snake_case event\n * names (pre_tool_call / post_tool_call / on_session_start / on_session_end /\n * subagent_stop — NOT the canonical PascalCase names; see EVENT_TO_HERMES).\n * Each value is a\n * list of shell-hook entries { matcher, command:\"<homeBin> hook …\", timeout }.\n * The command keeps the canonical event token so the runtime dispatcher\n * (parseEvent/formatReply) stays consistent. Hermes shell hooks pipe the\n * event JSON to the command on stdin and read the reply JSON from stdout —\n * the same wire protocol as Claude Code, so the runtime parse/format mirror\n * the Claude adapter (a Claude-like JSON shape; the exact Hermes field map is\n * documented inline where it could vary).\n *\n * Since hooks are external shell commands (not an in-process plugin), Hermes\n * cannot let a hook rewrite tool arguments — canModifyArgs is false. Hermes has\n * no SSE transport, so only stdio + http are advertised.\n */\n\nimport { existsSync, statSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nimport { BaseAdapter } from \"../base.js\";\nimport type { Adapter, HookReply, InstallContext, MemoryTarget, NormalizedEvent } from \"../spi.js\";\nimport type {\n ChangeRecord,\n DetectedPlatform,\n HealthCheck,\n HookEventName,\n HookParadigm,\n HookResponse,\n NotificationEvent,\n PlatformCapabilities,\n PlatformId,\n PostToolUseEvent,\n PostCompactEvent,\n PreCompactEvent,\n PreToolUseEvent,\n SessionEndEvent,\n SessionStartEvent,\n ServerDef,\n StopEvent,\n SubagentStopEvent,\n UserPromptSubmitEvent,\n} from \"../../core/types.js\";\nimport { removeFromObjectMap, upsertInObjectMap } from \"../../core/object-map.js\";\nimport { readYaml, writeYaml, yamlObjectMapCodec } from \"../../core/yaml.js\";\nimport { resolveEnvRefsDeep } from \"../../core/interpolate.js\";\nimport {\n buildHomeBinHookCommand,\n buildWrappedStdio,\n isHomeBinActionCommand,\n isHomeBinHookCommand,\n} from \"../../core/spawn.js\";\nimport { renderSkillMd } from \"../claude-code/render.js\";\nimport { normalizeSessionSource } from \"../claude-code/wire.js\";\n\nconst HOST: PlatformId = \"hermes\";\n/** Root key under which Hermes stores MCP servers in config.yaml (snake_case). */\nconst MCP_ROOT_KEY = \"mcp_servers\";\n/** Top-level key under which Hermes stores shell hooks in config.yaml. */\nconst HOOKS_KEY = \"hooks\";\n/**\n * Top-level map under which Hermes stores `/<id>` slash commands. A\n * `{ type: \"exec\", command }` entry runs the shell command directly, bypassing\n * the LLM — the action emitter's target.\n */\nconst QUICK_COMMANDS_KEY = \"quick_commands\";\n/** Default per-hook timeout (seconds) when the connector declares none. */\nconst DEFAULT_HOOK_TIMEOUT = 60;\n\n/** One Hermes quick-command entry (a `/<id>` slash command). */\ninterface HermesQuickCommand {\n type: \"exec\";\n command: string;\n}\n\n/**\n * Canonical → Hermes native hook event name. Hermes keys its `hooks:` block by\n * its OWN snake_case lifecycle names (pre_tool_call / post_tool_call /\n * on_session_start / on_session_end — see docs/research/platform-research.json),\n * NOT the canonical PascalCase names. A connector event is only wired when it\n * appears here AND is declared by the connector; everything else is reported as\n * a warn/skip at install time.\n */\nconst EVENT_TO_HERMES: Partial<Record<HookEventName, string>> = {\n PreToolUse: \"pre_tool_call\",\n PostToolUse: \"post_tool_call\",\n SessionStart: \"on_session_start\",\n SessionEnd: \"on_session_end\",\n // Hermes is a STOP-ONLY subagent host: subagent_stop fires when a\n // delegate_task child exits (child_status ∈ completed/failed/interrupted/\n // error); there is NO subagent_start analog. PermissionRequest is also\n // deliberately ABSENT: Hermes' pre_approval_request/post_approval_response\n // hooks OBSERVE the approval prompt but carry no decision control, so a\n // PermissionRequest handler could never be honored — install skip-warns it.\n SubagentStop: \"subagent_stop\",\n};\n\n/** Hermes stdio MCP entry — portable field names (command/args/env). */\ninterface HermesStdioServer {\n command: string;\n args?: string[];\n env?: Record<string, string>;\n}\n\n/**\n * Hermes remote HTTP MCP entry — `{ url, headers? }` under the SAME mcp_servers\n * key (no transport/type discriminator). Per the Hermes Agent docs\n * (website/docs/user-guide/features/mcp.md \"HTTP servers\"); OAuth servers add\n * `auth: oauth`, which AC's static-header model does not express.\n */\ninterface HermesHttpServer {\n url: string;\n headers?: Record<string, string>;\n}\n\n/** One Hermes shell-hook entry. */\ninterface HermesHookEntry {\n /** Tool-name matcher (empty = all). Tool events only; \"\" elsewhere. */\n matcher: string;\n /** The home-bin hook command Hermes invokes (event JSON on stdin). */\n command: string;\n /** Hook timeout in seconds. */\n timeout: number;\n}\n\n/** Raw Hermes hook stdin payload. Hermes uses snake_case pre_tool_call /\n * post_tool_call event tokens; field names below cover both its tool-call and\n * session payloads. Shape kept Claude-like where Hermes does not document it. */\ninterface HermesWireInput {\n session_id?: string;\n cwd?: string;\n event?: string;\n hook_event_name?: string;\n tool_name?: string;\n tool_input?: Record<string, unknown>;\n tool_response?: unknown;\n tool_output?: unknown;\n source?: string;\n reason?: string;\n prompt?: string;\n trigger?: string;\n stop_hook_active?: boolean;\n message?: string;\n is_error?: boolean;\n // subagent_stop — fires when a delegate_task child exits. agent_* are the\n // Claude-compatible names, child_* the Hermes-native ones (child_status ∈\n // completed/failed/interrupted/error stays accessible via `raw`).\n agent_id?: string;\n agent_type?: string;\n child_id?: string;\n child_status?: string;\n last_assistant_message?: string;\n /** Injected by the entrypoint so the runtime knows which connector to dispatch. */\n connector?: string;\n}\n\nexport class HermesAdapter extends BaseAdapter implements Adapter {\n readonly id: PlatformId = HOST;\n readonly name = \"Hermes Agent\";\n readonly paradigm: HookParadigm = \"json-stdio\";\n\n readonly capabilities: PlatformCapabilities = {\n // Memory surface: AGENTS.md-first managed block. memoryTargets below probes\n // for .hermes.md / HERMES.md (first context category wins on hermes —\n // AGENTS.md is ignored when they exist); ~/.hermes holds identity/volatile\n // files (SOUL.md, MEMORY.md), not a rules surface → user-scope skip-warn.\n supportsMemory: true,\n preToolUse: true,\n postToolUse: true,\n preCompact: false,\n // Hermes exposes on_session_start / on_session_end lifecycle hooks.\n sessionStart: true,\n sessionEnd: true,\n userPromptSubmit: false,\n stop: false,\n notification: false,\n // Newer events: Hermes ships subagent_stop (stop-only — no subagent_start\n // analog). permissionRequest stays unset because pre_approval_request is\n // observe-only (no decision control); postToolUseFailure stays unset (a\n // tool failure arrives merged into post_tool_call's result, not as a\n // dedicated event). Install reports the standard skip-warn for those.\n subagentStop: true,\n // Shell hooks cannot rewrite tool args/output in-process.\n canModifyArgs: false,\n canModifyOutput: false,\n canInjectSessionContext: true,\n // Hermes has no SSE transport.\n transports: [\"stdio\", \"http\"],\n // Content surface: Hermes auto-discovers dir-per-skill SKILL.md from its\n // LOCAL skills root ~/.hermes/skills — the \"single source of truth,\n // read-write\" dir (hermes-agent.nousresearch.com/docs/user-guide/features/\n // skills, fetched 2026-06-16). The directory name becomes the skill's\n // install slug; frontmatter is { name, description } + optional\n // metadata.hermes.*. USER scope only — there is no documented hermes-owned\n // project skills dir (~/.agents/skills is the cross-tool external dir, not\n // ours), so a project-scope install skip-warns via the base default.\n supportsSkills: true,\n // Native passthrough hooks: Hermes documents many host-specific lifecycle\n // events with NO canonical analog — pre_llm_call / post_llm_call /\n // on_session_finalize / on_session_reset / pre_gateway_dispatch /\n // pre_approval_request / post_approval_response / transform_tool_result\n // (docs/research/platform-research.json). They are host-specific (below the\n // >=3-host core bar; docs/research/host-specific-hook-events-design.md). A\n // connector reaches them by declaring platforms[\"hermes\"].nativeHooks;\n // installHooks files those event-name keys verbatim into the YAML hooks map,\n // and the generic uninstall reverses them.\n supportsNativeHooks: true,\n // Actions surface: Hermes ships `quick_commands.<id>: { type: \"exec\",\n // command }` — a `/<id>` slash command that runs the shell command directly,\n // bypassing the LLM (hermes-agent.nousresearch.com/docs/user-guide/cli:\n // \"custom commands that run shell commands instantly without invoking the\n // LLM\"). We emit one per declared action bound to the home-bin action verb.\n supportsActions: true,\n };\n\n // ── Detection ────────────────────────────────────────────────────────────\n\n detectInstalled(_projectDir: string): DetectedPlatform {\n const configPath = this.userConfigPath();\n const configDir = dirname(configPath);\n const installed = existsSync(configDir) || existsSync(configPath);\n return {\n id: this.id,\n name: this.name,\n installed,\n paradigm: this.paradigm,\n capabilities: this.capabilities,\n configPath,\n scope: \"user\",\n reason: installed\n ? `found Hermes config at ${configPath}`\n : `no Hermes config at ${configPath}`,\n confidence: installed ? \"high\" : \"low\",\n };\n }\n\n // ── Memory surface: .hermes.md / HERMES.md shadow probe (project) ────────\n // Hermes assembles project context by FIRST CATEGORY WINS: .hermes.md or\n // HERMES.md (cwd walking up to the git root) → AGENTS.md (cwd only) →\n // CLAUDE.md (cwd only). When a hermes-native file exists our block must live\n // there or it is never loaded. Reason strings note the cwd-only AGENTS.md\n // read and hermes' ~20k-chars-per-file truncation.\n protected override memoryTargets(ctx: InstallContext): MemoryTarget[] {\n if (this.memoryOverride(ctx)?.path || ctx.scope !== \"project\") {\n return super.memoryTargets(ctx); // user scope: no rules surface → skip-warn\n }\n for (const name of [\".hermes.md\", \"HERMES.md\"]) {\n const candidate = join(ctx.projectDir, name);\n if (existsSync(candidate)) {\n return [\n {\n path: candidate,\n reason: `${name} shadows AGENTS.md on hermes (first context category wins)`,\n budgetBytes: 18 * 1024, // hermes truncates each context file at ~20k chars\n },\n ];\n }\n }\n return [\n {\n path: join(ctx.projectDir, \"AGENTS.md\"),\n reason:\n \"AGENTS.md (hermes reads it from the cwd only — run from the project root; ~20k chars/file truncation)\",\n budgetBytes: 18 * 1024,\n },\n ];\n }\n\n // ── Native paths (server + hooks share the SAME file) ─────────────────────\n\n override getConfigDir(_ctx: InstallContext): string {\n return dirname(this.userConfigPath());\n }\n\n override getServerConfigPath(_ctx: InstallContext): string {\n return this.userConfigPath();\n }\n\n /** Same file as the server config — Hermes hooks live in config.yaml. */\n override getHookConfigPath(_ctx: InstallContext): string {\n return this.userConfigPath();\n }\n\n private userConfigPath(): string {\n return join(homedir(), \".hermes\", \"config.yaml\");\n }\n\n // ── MCP server install / uninstall (YAML mcp_servers) ─────────────────────\n\n override installServer(ctx: InstallContext): ChangeRecord[] {\n const { connector, dryRun } = ctx;\n const path = this.getServerConfigPath(ctx);\n const server = this.effectiveServer(ctx);\n\n if (!server) {\n return [\n {\n platform: this.id,\n action: \"skip\",\n path,\n detail: connector.server\n ? \"server registration disabled for hermes\"\n : \"connector declares no MCP server\",\n },\n ];\n }\n // Hermes registers stdio sidecars ({command,args,env}) AND remote HTTP\n // servers ({url,headers}) under the same mcp_servers key. It has no SSE\n // transport (docs: website/docs/user-guide/features/mcp.md), so anything\n // else is reported, never silently dropped.\n const isStdio = server.transport === \"stdio\" && !!server.command;\n const isHttp = server.transport === \"http\" && !!server.url;\n if (!isStdio && !isHttp) {\n return [\n {\n platform: this.id,\n action: \"skip\",\n path,\n detail: `transport \"${server.transport}\" not registrable in ${MCP_ROOT_KEY} (stdio + http only)`,\n },\n ];\n }\n\n const entry = this.renderServerEntry(ctx, server);\n\n return [\n upsertInObjectMap({\n codec: yamlObjectMapCodec(),\n rootKey: MCP_ROOT_KEY,\n policy: \"coerce\",\n platform: this.id,\n configPath: path,\n entryId: connector.id,\n entry,\n dryRun,\n }),\n ];\n }\n\n override uninstallServer(ctx: InstallContext): ChangeRecord[] {\n const { connector, dryRun } = ctx;\n const path = this.getServerConfigPath(ctx);\n return [\n removeFromObjectMap({\n codec: yamlObjectMapCodec(),\n rootKey: MCP_ROOT_KEY,\n policy: \"coerce\",\n platform: this.id,\n configPath: path,\n entryId: connector.id,\n dryRun,\n }),\n ];\n }\n\n /**\n * Render the MCP entry — a remote HTTP `{ url, headers? }` or a stdio sidecar\n * `{ command, args, env }`. Hermes has no native interpolation, so env-refs\n * resolve to literals here. The stdio path honors the telemetry serve-wrapper.\n */\n private renderServerEntry(\n ctx: InstallContext,\n server: ServerDef,\n ): HermesStdioServer | HermesHttpServer {\n // Remote HTTP — { url, headers? }. Never telemetry-wrapped (a URL has no\n // local command to route through the serve proxy). Hermes has no native env\n // token, so ${env:VAR} refs in url/headers resolve to literals.\n if (server.transport === \"http\") {\n const entry: HermesHttpServer = { url: resolveEnvRefsDeep(server.url ?? \"\") };\n if (server.headers && Object.keys(server.headers).length > 0) {\n const headers: Record<string, string> = {};\n for (const [k, v] of Object.entries(resolveEnvRefsDeep(server.headers))) {\n headers[k] = String(v);\n }\n entry.headers = headers;\n }\n return entry;\n }\n\n let command = server.command as string;\n let args = [...(server.args ?? [])];\n\n ({ command, args } = buildWrappedStdio(ctx, server, this.id, command, args));\n\n command = resolveEnvRefsDeep(command);\n args = resolveEnvRefsDeep(args);\n\n const entry: HermesStdioServer = { command };\n if (args.length > 0) entry.args = args;\n if (server.env && Object.keys(server.env).length > 0) {\n const env: Record<string, string> = {};\n for (const [k, v] of Object.entries(resolveEnvRefsDeep(server.env))) {\n env[k] = String(v);\n }\n entry.env = env;\n }\n return entry;\n }\n\n // ── Hook install / uninstall (YAML hooks map in the SAME config.yaml) ─────\n\n override installHooks(ctx: InstallContext): ChangeRecord[] {\n const { connector, dryRun } = ctx;\n const path = this.getHookConfigPath(ctx);\n const override = connector.platforms[HOST];\n\n // `hooks: false` disables only the NORMALIZED events. nativeHooks is a\n // sibling, hermes-scoped declaration on the same override and installs\n // regardless.\n const events = override?.hooks === false ? [] : connector.hookEvents;\n const nativeHooks = override?.nativeHooks ?? {};\n const nativeEvents = Object.keys(nativeHooks);\n\n if (events.length === 0 && nativeEvents.length === 0) {\n return [\n {\n platform: this.id,\n action: \"skip\",\n path,\n detail: override?.hooks === false ? \"hooks disabled for hermes\" : \"connector declares no hooks\",\n },\n ];\n }\n\n const cfg = readYaml<Record<string, unknown>>(path) ?? {};\n const hooks = this.hooksBucket(cfg);\n const changes: ChangeRecord[] = [];\n let mutated = false;\n\n for (const event of events) {\n const hermesEvent = EVENT_TO_HERMES[event];\n if (!hermesEvent) {\n // No Hermes equivalent for this canonical event — report and skip.\n changes.push({\n platform: this.id,\n action: \"warn\",\n path,\n detail: `${event} has no Hermes hook equivalent — skipped`,\n });\n continue;\n }\n\n // The hook command keeps the CANONICAL event token so the runtime\n // dispatcher (parseEvent/formatReply) stays consistent; only the YAML KEY\n // the entry is filed under is the native Hermes name.\n const command = buildHomeBinHookCommand(ctx.homeBinPath, HOST, event, connector.id);\n const matcher = connector.hooks[event]?.matcher ?? \"\";\n const timeout = this.hookTimeout(connector.server);\n const desired: HermesHookEntry = { matcher, command, timeout };\n\n const bucket = Array.isArray(hooks[hermesEvent])\n ? (hooks[hermesEvent] as HermesHookEntry[])\n : (hooks[hermesEvent] = [] as HermesHookEntry[]);\n const idx = bucket.findIndex((e) => this.isOurCommand(e?.command, ctx));\n\n if (idx >= 0) {\n if (JSON.stringify(bucket[idx]) === JSON.stringify(desired)) {\n changes.push({ platform: this.id, action: \"skip\", path, detail: `${HOOKS_KEY}.${hermesEvent}` });\n continue;\n }\n bucket[idx] = desired;\n changes.push({ platform: this.id, action: \"update\", path, detail: `${HOOKS_KEY}.${hermesEvent}` });\n } else {\n bucket.push(desired);\n changes.push({ platform: this.id, action: \"create\", path, detail: `${HOOKS_KEY}.${hermesEvent}` });\n }\n mutated = true;\n }\n\n // NATIVE passthrough events: Hermes-native event-name keys (e.g. pre_llm_call,\n // transform_tool_result) filed VERBATIM into the YAML hooks map — no\n // EVENT_TO_HERMES mapping, since they ARE Hermes events. Same entry shape +\n // idempotency, matched by EXACT command so a native key coinciding with a\n // mapped canonical key never clobbers it.\n for (const event of nativeEvents) {\n const command = buildHomeBinHookCommand(ctx.homeBinPath, HOST, event, connector.id);\n const matcher = nativeHooks[event]?.matcher ?? \"\";\n const timeout = this.hookTimeout(connector.server);\n const desired: HermesHookEntry = { matcher, command, timeout };\n const bucket = Array.isArray(hooks[event])\n ? (hooks[event] as HermesHookEntry[])\n : (hooks[event] = [] as HermesHookEntry[]);\n const idx = bucket.findIndex((e) => e?.command === command);\n if (idx >= 0) {\n if (JSON.stringify(bucket[idx]) === JSON.stringify(desired)) {\n changes.push({ platform: this.id, action: \"skip\", path, detail: `${HOOKS_KEY}.${event} (native)` });\n } else {\n bucket[idx] = desired;\n changes.push({ platform: this.id, action: \"update\", path, detail: `${HOOKS_KEY}.${event} (native)` });\n mutated = true;\n }\n } else {\n bucket.push(desired);\n changes.push({ platform: this.id, action: \"create\", path, detail: `${HOOKS_KEY}.${event} (native)` });\n mutated = true;\n }\n }\n\n if (mutated) writeYaml(path, cfg, dryRun);\n return changes;\n }\n\n override uninstallHooks(ctx: InstallContext): ChangeRecord[] {\n const path = this.getHookConfigPath(ctx);\n const cfg = readYaml<Record<string, unknown>>(path);\n const hooksRaw = cfg?.[HOOKS_KEY];\n if (\n !cfg ||\n !hooksRaw ||\n typeof hooksRaw !== \"object\" ||\n Array.isArray(hooksRaw)\n ) {\n return [{ platform: this.id, action: \"skip\", path, detail: \"no hooks section present\" }];\n }\n const hooks = hooksRaw as Record<string, unknown>;\n\n const changes: ChangeRecord[] = [];\n let mutated = false;\n for (const event of Object.keys(hooks)) {\n const bucket = hooks[event];\n if (!Array.isArray(bucket)) continue;\n const kept = (bucket as HermesHookEntry[]).filter(\n (e) => !this.isOurCommand(e?.command, ctx),\n );\n if (kept.length === bucket.length) continue;\n mutated = true;\n if (kept.length > 0) hooks[event] = kept;\n else delete hooks[event];\n changes.push({\n platform: this.id,\n action: \"remove\",\n path,\n detail: `${HOOKS_KEY}.${event} (${bucket.length - kept.length})`,\n });\n }\n\n if (mutated) writeYaml(path, cfg, ctx.dryRun);\n if (changes.length === 0) {\n return [{ platform: this.id, action: \"skip\", path, detail: \"no matching hook entries\" }];\n }\n return changes;\n }\n\n // ── Action surface (quick_commands map in the SAME config.yaml) ───────────\n // Each declared action emits `quick_commands.<id>: { type: \"exec\", command }`\n // where command is the home-bin action verb — a `/<id>` slash command that\n // runs it directly, bypassing the LLM. MERGE-preserve: never clobber another\n // entry. Set-if-absent per id; if `quick_commands.<id>` exists and is NOT\n // ours, skip-warn (the configPatch ownership semantics).\n\n override installActions(ctx: InstallContext): ChangeRecord[] {\n const { connector, dryRun } = ctx;\n const path = this.getHookConfigPath(ctx);\n\n if (connector.platforms[HOST]?.actions === false) {\n return [{ platform: this.id, action: \"skip\", path, detail: \"actions disabled for hermes\" }];\n }\n const triggers = this.actionTriggers(ctx);\n if (triggers.length === 0) {\n return [{ platform: this.id, action: \"skip\", path, detail: \"connector declares no actions\" }];\n }\n\n const cfg = readYaml<Record<string, unknown>>(path) ?? {};\n const bucket = this.objectBucket(cfg, QUICK_COMMANDS_KEY);\n const changes: ChangeRecord[] = [];\n let mutated = false;\n\n for (const trigger of triggers) {\n const desired: HermesQuickCommand = { type: \"exec\", command: trigger.command };\n const existing = bucket[trigger.id];\n if (existing !== undefined) {\n // Set-if-absent: only re-write an entry that is already OURS (an\n // exec entry whose command is our action verb for this connector).\n if (!this.isOurQuickCommand(existing, ctx)) {\n changes.push({\n platform: this.id,\n action: \"warn\",\n path,\n detail: `${QUICK_COMMANDS_KEY}.${trigger.id} exists and is not ours — skipped`,\n });\n continue;\n }\n if (JSON.stringify(existing) === JSON.stringify(desired)) {\n changes.push({\n platform: this.id,\n action: \"skip\",\n path,\n detail: `${QUICK_COMMANDS_KEY}.${trigger.id}`,\n });\n continue;\n }\n bucket[trigger.id] = desired;\n changes.push({\n platform: this.id,\n action: \"update\",\n path,\n detail: `${QUICK_COMMANDS_KEY}.${trigger.id}`,\n });\n } else {\n bucket[trigger.id] = desired;\n changes.push({\n platform: this.id,\n action: \"create\",\n path,\n detail: `${QUICK_COMMANDS_KEY}.${trigger.id}`,\n });\n }\n mutated = true;\n }\n\n if (mutated) writeYaml(path, cfg, dryRun);\n return changes;\n }\n\n override uninstallActions(ctx: InstallContext): ChangeRecord[] {\n const path = this.getHookConfigPath(ctx);\n const cfg = readYaml<Record<string, unknown>>(path);\n const bucketRaw = cfg?.[QUICK_COMMANDS_KEY];\n if (\n !cfg ||\n !bucketRaw ||\n typeof bucketRaw !== \"object\" ||\n Array.isArray(bucketRaw)\n ) {\n return [{ platform: this.id, action: \"skip\", path, detail: \"no quick_commands section present\" }];\n }\n const bucket = bucketRaw as Record<string, unknown>;\n\n const changes: ChangeRecord[] = [];\n let mutated = false;\n // Remove ONLY our exec entries; leave foreign entries (and the map itself\n // when any remain) untouched.\n for (const id of Object.keys(bucket)) {\n if (!this.isOurQuickCommand(bucket[id], ctx)) continue;\n delete bucket[id];\n mutated = true;\n changes.push({\n platform: this.id,\n action: \"remove\",\n path,\n detail: `${QUICK_COMMANDS_KEY}.${id}`,\n });\n }\n\n if (mutated) {\n // Drop an emptied map so we leave no orphan key behind.\n if (Object.keys(bucket).length === 0) delete cfg[QUICK_COMMANDS_KEY];\n writeYaml(path, cfg, ctx.dryRun);\n }\n if (changes.length === 0) {\n return [{ platform: this.id, action: \"skip\", path, detail: \"no matching quick_commands entries\" }];\n }\n return changes;\n }\n\n /** True when a quick-command entry is OUR exec action verb for this connector. */\n private isOurQuickCommand(entry: unknown, ctx: InstallContext): boolean {\n if (!entry || typeof entry !== \"object\" || Array.isArray(entry)) return false;\n const e = entry as Partial<HermesQuickCommand>;\n if (e.type !== \"exec\" || typeof e.command !== \"string\") return false;\n return isHomeBinActionCommand(e.command, ctx.homeBinPath, ctx.connector.id);\n }\n\n /** True when a hook command is ours (anchored home-bin + connector id). */\n private isOurCommand(command: string | undefined, ctx: InstallContext): boolean {\n return isHomeBinHookCommand(command, ctx.homeBinPath, ctx.connector.id);\n }\n\n private hookTimeout(server: ServerDef | undefined): number {\n const ms = server?.timeoutMs;\n if (typeof ms === \"number\" && ms > 0) return Math.round(ms / 1000);\n return DEFAULT_HOOK_TIMEOUT;\n }\n\n // ── Content surface: skills (dir-per-skill SKILL.md) ─────────────────────\n // CONTENT-ONLY: pure native-file writers, mirroring goose/openclaw. No\n // runtime dispatch, no home-bin pointer, no telemetry wrap. Idempotent\n // (byte-identical → skip) via writeContentFile and reversible via\n // removeContentFile + removeDirIfEmpty. Honors platforms[\"hermes\"].skills\n // === false. No config.yaml entry — Hermes auto-discovers ~/.hermes/skills.\n //\n // USER scope only: ~/.hermes/skills/<name>/SKILL.md (the documented local,\n // read-write \"single source of truth\"). Project scope skip-warns — there is\n // no hermes-owned project skills dir documented.\n\n /** The user-scope skills ROOT dir (~/.hermes/skills). */\n private skillsDir(): string {\n return join(dirname(this.userConfigPath()), \"skills\");\n }\n\n /** Per-skill directory: ~/.hermes/skills/<name>. */\n private skillDir(name: string): string {\n return join(this.skillsDir(), name);\n }\n\n override installSkills(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n if (connector.platforms[HOST]?.skills === false) {\n return [{ platform: this.id, action: \"skip\", detail: \"skills disabled for hermes\" }];\n }\n if (connector.skills.length === 0) {\n return [{ platform: this.id, action: \"skip\", detail: \"connector declares no skills\" }];\n }\n if (ctx.scope !== \"user\") {\n // Hermes documents only the user-scope ~/.hermes/skills root; there is no\n // hermes-owned project skills dir. Report rather than guess a path.\n return [\n {\n platform: this.id,\n action: \"warn\",\n detail:\n `no project-scope skills dir on hermes (~/.hermes/skills is user-scope only); ` +\n `${connector.skills.length} skipped`,\n },\n ];\n }\n const changes: ChangeRecord[] = [];\n for (const skill of connector.skills) {\n const dir = this.skillDir(skill.name);\n // Guard a skills path occupied by a regular FILE (would throw ENOTDIR on\n // mkdir): skip-warn rather than crash (the cline `.clinerules`-is-a-file\n // precedent). The skills root or the per-skill dir is the likely culprit.\n const blockingFile = this.firstFileOnSkillPath(dir);\n if (blockingFile !== null) {\n changes.push({\n platform: this.id,\n action: \"warn\",\n path: blockingFile,\n detail: `${blockingFile} is a file, not a directory; skill \"${skill.name}\" skipped`,\n });\n continue;\n }\n changes.push(\n this.writeContentFile(join(dir, \"SKILL.md\"), renderSkillMd(skill), ctx.dryRun),\n );\n // Bundle any resource files beside SKILL.md (relative path → contents).\n // Defense-in-depth: skip+warn on any key that escapes the skill dir\n // (config-time validation already rejects these, but never trust input).\n for (const [rel, contents] of Object.entries(skill.resources ?? {})) {\n const target = this.resolveWithin(dir, rel);\n if (target === null) {\n changes.push({\n platform: this.id,\n action: \"warn\",\n detail: `skill resource \"${rel}\" escapes the skill dir; skipped`,\n });\n continue;\n }\n changes.push(this.writeContentFile(target, contents, ctx.dryRun));\n }\n }\n return changes;\n }\n\n /**\n * Walk from the skills root (~/.hermes/skills) down to `leaf` and return the\n * FIRST segment that exists as a regular file (a mkdir there throws ENOTDIR),\n * else null — so installSkills can skip-warn instead of crashing.\n */\n private firstFileOnSkillPath(leaf: string): string | null {\n const root = this.skillsDir();\n const segments: string[] = [];\n let cur = leaf;\n while (cur.length >= root.length) {\n segments.unshift(cur);\n if (cur === root) break;\n const parent = dirname(cur);\n if (parent === cur) break;\n cur = parent;\n }\n for (const p of segments) {\n if (!existsSync(p)) return null;\n try {\n if (statSync(p).isFile()) return p;\n } catch {\n return null;\n }\n }\n return null;\n }\n\n override uninstallSkills(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n if (connector.skills.length === 0) {\n return [{ platform: this.id, action: \"skip\", detail: \"connector declares no skills\" }];\n }\n if (ctx.scope !== \"user\") {\n // Nothing is written at project scope (install skip-warned), so nothing\n // to clean — report the same scope reason as install for symmetry.\n return [\n {\n platform: this.id,\n action: \"skip\",\n detail: \"no project-scope skills dir on hermes (user-scope only); nothing to remove\",\n },\n ];\n }\n const changes: ChangeRecord[] = [];\n for (const skill of connector.skills) {\n const dir = this.skillDir(skill.name);\n // Remove only the files we wrote (SKILL.md + declared resources), then the\n // skill dir itself when we own its full contents.\n changes.push(this.removeContentFile(join(dir, \"SKILL.md\"), ctx.dryRun));\n for (const rel of Object.keys(skill.resources ?? {})) {\n const target = this.resolveWithin(dir, rel);\n if (target === null) continue; // never delete outside the skill dir\n changes.push(this.removeContentFile(target, ctx.dryRun));\n }\n // Only remove the skill dir when WE own its full contents — never rm -rf a\n // dir that still holds user-added / sibling-tool / shared files.\n changes.push(this.removeDirIfEmpty(dir, ctx.dryRun));\n }\n return changes;\n }\n\n // ── Diagnostics ──────────────────────────────────────────────────────────\n\n override getHealthChecks(ctx: InstallContext): readonly HealthCheck[] {\n const path = this.getServerConfigPath(ctx);\n const id = ctx.connector.id;\n const homeBin = ctx.homeBinPath;\n const hookEvents = ctx.connector.hookEvents;\n return [\n {\n name: `${this.name}: config.yaml present`,\n check: () =>\n existsSync(path)\n ? { status: \"OK\", detail: path }\n : { status: \"FAIL\", detail: `not found: ${path}` },\n },\n {\n name: `${this.name}: ${MCP_ROOT_KEY}.${id} registered`,\n check: () => {\n // Only assert what the connector declares: a server-less connector\n // never writes an mcp entry, so its absence is healthy.\n if (!ctx.connector.server) return { status: \"OK\", detail: \"no MCP server declared\" };\n const cfg = readYaml<Record<string, unknown>>(path);\n const bucket = cfg?.[MCP_ROOT_KEY];\n const present =\n typeof bucket === \"object\" &&\n bucket !== null &&\n !Array.isArray(bucket) &&\n id in (bucket as Record<string, unknown>);\n return present\n ? { status: \"OK\", detail: `${MCP_ROOT_KEY}.${id}` }\n : { status: \"FAIL\", detail: `${MCP_ROOT_KEY}.${id} not found in ${path}` };\n },\n },\n {\n name: `${this.name}: hook command registered`,\n check: () => {\n if (hookEvents.length === 0) return { status: \"OK\", detail: \"no hooks declared\" };\n const cfg = readYaml<Record<string, unknown>>(path);\n const hooks = cfg?.[HOOKS_KEY];\n if (!hooks || typeof hooks !== \"object\" || Array.isArray(hooks)) {\n return { status: \"FAIL\", detail: `no ${HOOKS_KEY} section in ${path}` };\n }\n const registered = Object.values(hooks as Record<string, unknown>).some(\n (bucket) =>\n Array.isArray(bucket) &&\n (bucket as HermesHookEntry[]).some((e) =>\n isHomeBinHookCommand(e?.command, homeBin, id),\n ),\n );\n return registered\n ? { status: \"OK\", detail: \"hook command present\" }\n : { status: \"FAIL\", detail: `no hook for ${id} in ${path}` };\n },\n },\n ];\n }\n\n // ── Runtime: parse Hermes stdin JSON → normalized event ──────────────────\n\n parseEvent(event: HookEventName, raw: unknown): NormalizedEvent {\n const input = (raw ?? {}) as HermesWireInput;\n const base = {\n hostPlatform: HOST,\n connectorId: typeof input.connector === \"string\" ? input.connector : \"\",\n sessionId: typeof input.session_id === \"string\" ? input.session_id : \"\",\n ...(typeof input.cwd === \"string\" ? { projectDir: input.cwd } : {}),\n raw,\n } as const;\n\n switch (event) {\n case \"PreToolUse\": {\n const ev: PreToolUseEvent = {\n ...base,\n toolName: input.tool_name ?? \"\",\n toolInput: input.tool_input ?? {},\n };\n return ev;\n }\n case \"PostToolUse\": {\n // Hermes may carry the result under tool_output or tool_response.\n const out = toStringOrUndefined(input.tool_output ?? input.tool_response);\n const ev: PostToolUseEvent = {\n ...base,\n toolName: input.tool_name ?? \"\",\n toolInput: input.tool_input ?? {},\n ...(out !== undefined ? { toolOutput: out } : {}),\n ...(typeof input.is_error === \"boolean\" ? { isError: input.is_error } : {}),\n };\n return ev;\n }\n case \"SessionStart\": {\n const ev: SessionStartEvent = { ...base, source: normalizeSessionSource(input.source) };\n return ev;\n }\n case \"SessionEnd\": {\n const ev: SessionEndEvent = {\n ...base,\n ...(typeof input.reason === \"string\" ? { reason: input.reason } : {}),\n };\n return ev;\n }\n case \"UserPromptSubmit\": {\n const ev: UserPromptSubmitEvent = {\n ...base,\n prompt: typeof input.prompt === \"string\" ? input.prompt : \"\",\n };\n return ev;\n }\n case \"PreCompact\": {\n const ev: PreCompactEvent = {\n ...base,\n ...(input.trigger === \"auto\" || input.trigger === \"manual\"\n ? { trigger: input.trigger }\n : {}),\n };\n return ev;\n }\n case \"PostCompact\": {\n // Hermes does not fire PostCompact natively (postCompact unset →\n // warn-skip at install). Parsed defensively, mirroring PreCompact, so a\n // manual/mis-routed dispatch normalizes instead of hitting the guard.\n const ev: PostCompactEvent = {\n ...base,\n ...(input.trigger === \"auto\" || input.trigger === \"manual\"\n ? { trigger: input.trigger }\n : {}),\n };\n return ev;\n }\n case \"Stop\": {\n const ev: StopEvent = {\n ...base,\n ...(typeof input.stop_hook_active === \"boolean\"\n ? { stopHookActive: input.stop_hook_active }\n : {}),\n };\n return ev;\n }\n case \"Notification\": {\n const ev: NotificationEvent = {\n ...base,\n message: typeof input.message === \"string\" ? input.message : \"\",\n };\n return ev;\n }\n case \"SubagentStop\": {\n // agent_id/agent_type stay optional (some hosts never populate them);\n // Hermes' native child_id is accepted as the id fallback. child_status\n // is host-specific and stays accessible via `raw`.\n const agentId = input.agent_id ?? input.child_id;\n const ev: SubagentStopEvent = {\n ...base,\n ...(typeof agentId === \"string\" ? { agentId } : {}),\n ...(typeof input.agent_type === \"string\"\n ? { agentType: input.agent_type }\n : {}),\n ...(typeof input.last_assistant_message === \"string\"\n ? { lastAssistantMessage: input.last_assistant_message }\n : {}),\n ...(typeof input.stop_hook_active === \"boolean\"\n ? { stopHookActive: input.stop_hook_active }\n : {}),\n };\n return ev;\n }\n case \"PermissionRequest\":\n case \"PostToolUseFailure\":\n case \"SubagentStart\": {\n // No Hermes analog: pre_approval_request is observe-only (no decision\n // control), tool failures arrive merged into post_tool_call, and there\n // is no subagent_start. Install already skip-warns these; a runtime\n // dispatch is a mis-route — fail loudly.\n throw new Error(`unsupported hermes hook event: ${String(event)}`);\n }\n default: {\n const _never: never = event;\n throw new Error(`unsupported hermes hook event: ${String(_never)}`);\n }\n }\n }\n\n // ── Runtime: normalized response → Hermes native hook reply ──────────────\n // Hermes shell hooks read a JSON reply from stdout (exit 0 = allow). We emit a\n // Claude-like `hookSpecificOutput` wrapper; if Hermes' exact reply schema\n // differs, this is the single place to adjust the mapping.\n\n formatReply(event: HookEventName, response: HookResponse): HookReply {\n const decision = response.decision ?? \"allow\";\n\n if (decision === \"deny\") {\n // SubagentStop deny carries Stop semantics — it keeps the subagent\n // running with `reason` as its next instruction — and (like Claude's\n // Stop class) is honored only as the TOP-LEVEL {\"decision\":\"block\",\n // \"reason\"}, not as a permissionDecision envelope.\n if (event === \"SubagentStop\") {\n return this.stdout({\n decision: \"block\",\n reason: response.reason ?? \"Blocked by hook\",\n });\n }\n return this.stdout({\n hookSpecificOutput: {\n hookEventName: event,\n permissionDecision: \"deny\",\n permissionDecisionReason: response.reason ?? \"Blocked by hook\",\n },\n });\n }\n\n if (decision === \"ask\") {\n return this.stdout({\n hookSpecificOutput: {\n hookEventName: event,\n permissionDecision: \"ask\",\n permissionDecisionReason: response.reason ?? \"Confirmation required by hook\",\n },\n });\n }\n\n if (decision === \"context\" && response.additionalContext) {\n return this.stdout({\n hookSpecificOutput: { hookEventName: event, additionalContext: response.additionalContext },\n });\n }\n\n // allow / modify (unsupported — shell hooks can't rewrite args) / void.\n return { exitCode: 0 };\n }\n\n private stdout(payload: unknown): HookReply {\n return { exitCode: 0, stdout: JSON.stringify(payload) };\n }\n\n // ── Internal helpers ──────────────────────────────────────────────────────\n\n /** Resolve the per-platform server override into an effective ServerDef. */\n private effectiveServer(ctx: InstallContext): ServerDef | undefined {\n const override = ctx.connector.platforms[this.id]?.server;\n if (override === false) return undefined;\n const base = ctx.connector.server;\n if (!base) return undefined;\n return override && typeof override === \"object\" ? { ...base, ...override } : base;\n }\n\n /** Get-or-create an object bucket (map) at `cfg[key]`. */\n private objectBucket(cfg: Record<string, unknown>, key: string): Record<string, unknown> {\n const existing = cfg[key];\n if (existing && typeof existing === \"object\" && !Array.isArray(existing)) {\n return existing as Record<string, unknown>;\n }\n const fresh: Record<string, unknown> = {};\n cfg[key] = fresh;\n return fresh;\n }\n\n /** Get-or-create the hooks map at `cfg.hooks`. */\n private hooksBucket(cfg: Record<string, unknown>): Record<string, unknown> {\n return this.objectBucket(cfg, HOOKS_KEY);\n }\n}\n\n/** Coerce an unknown value into a string for the normalized event. */\nfunction toStringOrUndefined(value: unknown): string | undefined {\n if (value == null) return undefined;\n if (typeof value === \"string\") return value;\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\nexport const adapter = new HermesAdapter();\nexport default adapter;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,SAAS,YAAY,gBAAgB;AACrC,SAAS,eAAe;AACxB,SAAS,SAAS,YAAY;AAqC9B,IAAM,OAAmB;AAEzB,IAAM,eAAe;AAErB,IAAM,YAAY;AAMlB,IAAM,qBAAqB;AAE3B,IAAM,uBAAuB;AAgB7B,IAAM,kBAA0D;AAAA,EAC9D,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,cAAc;AAAA,EACd,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOZ,cAAc;AAChB;AA6DO,IAAM,gBAAN,cAA4B,YAA+B;AAAA,EACvD,KAAiB;AAAA,EACjB,OAAO;AAAA,EACP,WAAyB;AAAA,EAEzB,eAAqC;AAAA;AAAA;AAAA;AAAA;AAAA,IAK5C,gBAAgB;AAAA,IAChB,YAAY;AAAA,IACZ,aAAa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"sourcesContent":["/**\n * adapters/kilo-cli — Kilo CLI platform adapter for agent-connector.\n *\n * The Kilo CLI (the `kilo` binary) is a **live-confirmed OpenCode fork**: a\n * SQLite-backed command-line agent (storage `~/.local/share/kilo/kilo.db`) that\n * loads `@kilocode/plugin` modules. It is DISTINCT from the Kilo Code VS Code\n * extension (adapter id \"kilo\", a Roo/Cline fork) — the two products carry\n * different platformIds so their config and usage never merge.\n *\n * Paradigm — **ts-plugin** (mirrors the OpenCode adapter):\n * The fork has no JSON hook table. Instead it loads JS/TS plugin modules whose\n * default export is a `@kilocode/plugin` PluginModule:\n * { id?, server: async (input) => Hooks }\n * where the returned `Hooks` object is keyed by the fork's event names\n * (\"tool.execute.before\", \"tool.execute.after\", a session/system event). The\n * `server` factory runs in-process inside Kilo and is handed mutable args/output\n * objects; it throws to block a tool call.\n *\n * Why we BRIDGE instead of importing handlers (identical rationale to OpenCode):\n * the connector's hook handlers are arbitrary developer code we must not import\n * into Kilo's runtime (wrong cwd, wrong deps, version skew). So instead of\n * importing handlers we synthesize a tiny, fully self-contained ESM plugin\n * module that imports NOTHING from agent-connector and, on each hook firing,\n * shells out to the ONE stable home binary's universal entrypoint\n * <homeBin> hook kilo-cli <event> --connector <id>\n * feeding the event payload on stdin and JSON.parsing the normalized\n * HookResponse back from stdout. Fail-open: any bridge error → no-op.\n *\n * Registration (hooks — array + auto-discovery both work):\n * Since kilo v7.3.16 the fork auto-discovers every file in its plugin dir\n * (.kilo/plugin/*.js, ~/.config/kilo/plugin/*.js), so writing the file is\n * sufficient for discovery. We ALSO register the path in kilo.jsonc's `plugin`\n * array because both loading mechanisms coexist and the array write is harmless\n * (idempotent); older versions relied on it exclusively.\n *\n * Plugin module location (project | user):\n * user → ~/.config/kilo/plugin/<id>.js\n * project → <projectDir>/.kilo/plugin/<id>.js\n *\n * MCP config (the CLI's new-gen dialect — already correct, KEPT verbatim):\n * - user scope → ~/.config/kilo/kilo.jsonc\n * - project scope → <projectDir>/.kilo/kilo.jsonc (project overrides global)\n * Both are JSON/JSONC; we write plain JSON, which is valid JSONC. The root key\n * is \"mcp\" (NOT the extension's \"mcpServers\").\n *\n * Server entry shape (mirrors OpenCode's new-gen dialect):\n * - stdio → { type: \"local\", command: [exe, ...args], environment: {...} }\n * NOTE the command is a single ARRAY (exe + args together), unlike\n * Claude/Cursor's scalar `command` + `args[]` split.\n * - remote → { type: \"remote\", url }\n *\n * The Kilo CLI documents no native `${env:VAR}` interpolation token, so env/url\n * refs are resolved to literals at install time (the no-native-token path).\n *\n * Content surfaces (live-confirmed, kilo v7.3.16):\n * - commands → .kilo/command/<name>.md (user ~/.config/kilo/command/)\n * - skills → .kilo/skills/<name>/SKILL.md (user ~/.config/kilo/skills/ or ~/.agents/skills)\n * - subagents → .kilo/agent/<name>.md with frontmatter mode:subagent\n *\n * Capability degradations (documented, never thrown):\n * - The fork has no \"ask\" gate. A decision of \"ask\" degrades to a block (throw\n * with the reason) in tool.execute.before — the safe direction.\n */\n\nimport {\n chmodSync,\n existsSync,\n mkdirSync,\n readFileSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nimport { BaseAdapter } from \"../base.js\";\nimport { renderCommandMd, renderSkillMd } from \"../claude-code/render.js\";\nimport type {\n Adapter,\n GeneratedPluginFile,\n HookReply,\n InstallContext,\n MemoryTarget,\n NormalizedEvent,\n} from \"../spi.js\";\nimport type {\n ChangeRecord,\n DetectedPlatform,\n HealthCheck,\n HookEventName,\n HookParadigm,\n HookResponse,\n PermissionRequestEvent,\n PlatformCapabilities,\n PlatformId,\n PostToolUseEvent,\n PreToolUseEvent,\n ServerDef,\n SessionStartEvent,\n StopEvent,\n Transport,\n UserPromptSubmitEvent,\n} from \"../../core/types.js\";\nimport { resolveEnvRefsDeep } from \"../../core/interpolate.js\";\nimport { renderBridgePrelude } from \"../../core/ts-plugin-bridge.js\";\nimport {\n buildWrappedStdio,\n} from \"../../core/spawn.js\";\n\nconst HOST: PlatformId = \"kilo-cli\";\n/** New-generation root key for MCP servers — \"mcp\", not the extension's \"mcpServers\". */\nconst MCP_ROOT_KEY = \"mcp\";\n/** kilo.jsonc array of plugin module paths the fork loads (NOT auto-discovery). */\nconst PLUGIN_ARRAY_KEY = \"plugin\";\n/** New-generation config filename (JSON/JSONC). */\nconst CONFIG_FILE = \"kilo.jsonc\";\n/** The Kilo CLI's SQLite session store — a CLI-exclusive detection marker. */\nconst CLI_DB_RELPATH = [\".local\", \"share\", \"kilo\", \"kilo.db\"] as const;\n\n/**\n * Canonical → Kilo (OpenCode-fork) event name map. A connector hook event is\n * only emitted by the generated plugin when it appears here AND is declared by\n * the connector.\n *\n * The fork inherits OpenCode's tool-execution events; like OpenCode it has no\n * real SessionStart hook, so SessionStart maps to the same system-prompt\n * transform surrogate (the verified context-injection point) — we inject\n * additionalContext into the system prompt there.\n */\nconst EVENT_TO_KILO: Partial<Record<HookEventName, string>> = {\n PreToolUse: \"tool.execute.before\",\n PostToolUse: \"tool.execute.after\",\n SessionStart: \"experimental.chat.system.transform\",\n // chat.message fires when a new user message arrives (inspect/modify parts) →\n // canonical UserPromptSubmit (mirrors the mimo-code OpenCode fork).\n UserPromptSubmit: \"chat.message\",\n // permission.ask is the decision-capable gate (auto-allow/auto-deny). The\n // handler MUTATES output.status (\"ask\"|\"deny\"|\"allow\") — mirrors OpenCode.\n PermissionRequest: \"permission.ask\",\n // session.idle (\"session finished responding\") → canonical Stop. NOT a direct\n // hook key — dispatched through the generic `event` hook (event.type switch).\n // session.idle is doc-listed for the VS Code extension & CLI but its runtime\n // firing on a given Kilo build is not separately verified (an upstream FR for\n // session-lifecycle hooks exists); if it never fires, Stop is a silent no-op\n // (an acceptable degrade — it never mis-fires), so coverage may be optimistic.\n Stop: \"session.idle\",\n};\n\n/** Raw payload the generated plugin posts to the universal hook entrypoint. */\ninterface KiloBridgePayload {\n toolName?: string;\n toolInput?: Record<string, unknown>;\n toolOutput?: string;\n isError?: boolean;\n prompt?: string;\n sessionId?: string;\n projectDir?: string;\n}\n\n/**\n * Native MCP server entry shapes the Kilo CLI's new-gen config accepts under\n * `mcp`. QUIRK: a local (stdio) server keys its whole invocation as\n * `command: [...]` — a single array of [executable, ...args] — and env as\n * `environment`.\n */\ninterface KiloLocalServer {\n type: \"local\";\n command: string[];\n environment?: Record<string, string>;\n}\ninterface KiloRemoteServer {\n type: \"remote\";\n url: string;\n}\n\nexport class KiloCliAdapter extends BaseAdapter implements Adapter {\n readonly id: PlatformId = HOST;\n readonly name = \"Kilo CLI\";\n readonly paradigm: HookParadigm = \"ts-plugin\";\n\n readonly capabilities: PlatformCapabilities = {\n // Memory surface: AGENTS.md-first managed block (project <projectDir>/AGENTS.md\n // via the base default; user scope → ~/.kilocode/rules/agent-connector.md below).\n supportsMemory: true,\n // Matches the OpenCode capability surface — the fork inherits its plugin\n // event model.\n preToolUse: true,\n postToolUse: true,\n // The fork's compaction hook is experimental and not wired here.\n preCompact: false,\n sessionStart: true,\n sessionEnd: false,\n // chat.message backs UserPromptSubmit; session.idle (via the generic `event`\n // hook) backs Stop.\n userPromptSubmit: true,\n stop: true,\n notification: false,\n // Newer events: the fork's decision-capable `permission.ask` plugin hook is\n // now wired (PermissionRequest → permission.ask, mutating output.status), and\n // session.idle (\"session finished responding\") backs Stop via the generic\n // `event` hook. subagents run as child sessions (bus events only) and tool\n // failure is merged into tool.execute.after / session.error, so\n // postToolUseFailure / subagentStart / subagentStop stay unset — the\n // generated bridge never references them and install reports them as\n // \"unsupported here\".\n permissionRequest: true,\n // tool.execute.before mutates output.args → input rewrite supported.\n canModifyArgs: true,\n // tool.execute.after mutates output.output → output rewrite supported.\n canModifyOutput: true,\n // injected via the system-prompt transform at session start.\n canInjectSessionContext: true,\n // The Kilo CLI registers stdio (local), SSE, and Streamable HTTP MCP servers.\n transports: [\"stdio\", \"sse\", \"http\"],\n // Content surfaces: live-confirmed on kilo v7.3.16 (see header).\n supportsCommands: true,\n supportsSkills: true,\n supportsSubagents: true,\n };\n\n // ── Detection ────────────────────────────────────────────────────────────\n\n detectInstalled(projectDir: string): DetectedPlatform {\n const userDir = join(homedir(), \".config\", \"kilo\");\n const userConfig = join(userDir, CONFIG_FILE);\n const projectConfig = join(projectDir, \".kilo\", CONFIG_FILE);\n // The SQLite session DB is a CLI-exclusive marker (the VS Code extension\n // never writes it), so it disambiguates the CLI from the \"kilo\" extension\n // even when neither writes a kilo.jsonc yet.\n const cliDb = join(homedir(), ...CLI_DB_RELPATH);\n const userInstalled = existsSync(userDir) || existsSync(cliDb);\n const projInstalled = existsSync(projectConfig);\n const installed = userInstalled || projInstalled;\n // Report the scope/path/reason for the marker that actually matched, so a\n // project-only install isn't misreported as a (non-existent) user install.\n const scope = projInstalled && !userInstalled ? \"project\" : \"user\";\n const configPath = scope === \"project\" ? projectConfig : userConfig;\n return {\n id: this.id,\n name: this.name,\n installed,\n paradigm: this.paradigm,\n capabilities: this.capabilities,\n configPath,\n scope,\n reason: installed\n ? scope === \"project\"\n ? `found project Kilo CLI config at ${projectConfig}`\n : existsSync(cliDb)\n ? `found Kilo CLI session store at ${cliDb}`\n : `found Kilo CLI config under ${userDir}`\n : `no Kilo CLI config at ${userDir} or session store at ${cliDb}`,\n confidence: installed ? \"high\" : \"low\",\n };\n }\n\n // ── Memory surface: global rules dir at user scope ──────────────────────\n // Project scope stays on the AGENTS.md base default. User scope targets a\n // dedicated agent-connector.md in the legacy-compatible ~/.kilocode/rules/\n // dir (always loaded; avoids JSONC `instructions` edits in kilo.jsonc; the\n // AC-created file is cleanly deletable on uninstall). Shared backend with\n // the kilo extension — the convergent write dedupes via the content hash.\n protected override memoryTargets(ctx: InstallContext): MemoryTarget[] {\n if (this.memoryOverride(ctx)?.path || ctx.scope !== \"user\") {\n return super.memoryTargets(ctx);\n }\n return [\n {\n path: join(homedir(), \".kilocode\", \"rules\", \"agent-connector.md\"),\n reason: \"kilo global rules dir (~/.kilocode/rules; agent-connector-owned file)\",\n },\n ];\n }\n\n // ── Native paths ─────────────────────────────────────────────────────────\n\n getConfigDir(ctx: InstallContext): string {\n return ctx.scope === \"project\"\n ? join(ctx.projectDir, \".kilo\")\n : join(homedir(), \".config\", \"kilo\");\n }\n\n getServerConfigPath(ctx: InstallContext): string {\n return join(this.getConfigDir(ctx), CONFIG_FILE);\n }\n\n /**\n * For ts-plugin hosts the \"hook config path\" is the generated plugin FILE.\n * Unlike OpenCode, writing the file is NOT sufficient: the fork loads only the\n * module paths listed in kilo.jsonc's `plugin` array, so installHooks also\n * registers this path there.\n */\n getHookConfigPath(ctx: InstallContext): string {\n return join(this.pluginDir(ctx), this.pluginFileName(ctx));\n }\n\n /** Plugin directory the synthesized module is written into, per scope. */\n private pluginDir(ctx: InstallContext): string {\n return ctx.scope === \"project\"\n ? join(ctx.projectDir, \".kilo\", \"plugin\")\n : join(homedir(), \".config\", \"kilo\", \"plugin\");\n }\n\n /** Plugin module file name (one per connector, kebab-case id). */\n private pluginFileName(ctx: InstallContext): string {\n return `${ctx.connector.id}.js`;\n }\n\n // ── MCP server install / uninstall ───────────────────────────────────────\n\n installServer(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n const override = connector.platforms[HOST]?.server;\n if (!connector.server || override === false) {\n return [\n {\n platform: this.id,\n action: \"skip\",\n detail: connector.server\n ? \"server registration disabled for kilo-cli\"\n : \"connector declares no MCP server\",\n },\n ];\n }\n\n // Shallow-merge any per-platform server override into the base ServerDef.\n const server: ServerDef =\n override && typeof override === \"object\"\n ? { ...connector.server, ...override }\n : connector.server;\n\n const serverPath = this.getServerConfigPath(ctx);\n const entry = this.renderServerEntry(ctx, server);\n\n return [\n this.upsertServerInJson(serverPath, MCP_ROOT_KEY, connector.id, entry, ctx.dryRun),\n ];\n }\n\n uninstallServer(ctx: InstallContext): ChangeRecord[] {\n const serverPath = this.getServerConfigPath(ctx);\n return [\n this.removeServerFromJson(serverPath, MCP_ROOT_KEY, ctx.connector.id, ctx.dryRun),\n ];\n }\n\n /** Render a normalized ServerDef into the Kilo CLI's new-gen `mcp` entry. */\n private renderServerEntry(\n ctx: InstallContext,\n server: ServerDef,\n ): KiloLocalServer | KiloRemoteServer {\n const transport: Transport = server.transport;\n\n if (transport === \"stdio\") {\n let command = server.command ?? \"\";\n let args = [...(server.args ?? [])];\n\n // Transparent telemetry wrapping: route the real command through\n // `<homeBin> serve --connector <id> -- <command> <args...>`.\n ({ command, args } = buildWrappedStdio(ctx, server, this.id, command, args));\n\n // QUIRK: the Kilo CLI's new-gen local server keys its whole invocation as\n // a single `command` ARRAY (executable + args together), like OpenCode.\n // The CLI has no documented native interpolation token, so resolve every\n // ${env:VAR} to a literal at install time.\n const entry: KiloLocalServer = {\n type: \"local\",\n command: resolveEnvRefsDeep([command, ...args]),\n };\n const env = this.renderEnv(server.env);\n if (env) entry.environment = env;\n return entry;\n }\n\n // sse / http (and any other remote transport) — the Kilo CLI registers a URL.\n const entry: KiloRemoteServer = {\n type: \"remote\",\n url: resolveEnvRefsDeep(server.url ?? \"\"),\n };\n return entry;\n }\n\n /**\n * Render env values. The Kilo CLI documents no native interpolation token, so\n * resolve `${env:VAR}` references to literals at install time.\n */\n private renderEnv(\n env: Record<string, string> | undefined,\n ): Record<string, string> | undefined {\n if (!env || Object.keys(env).length === 0) return undefined;\n return resolveEnvRefsDeep({ ...env });\n }\n\n // ── Hook install / uninstall (ts-plugin + explicit `plugin` array) ────────\n\n installHooks(ctx: InstallContext): ChangeRecord[] {\n const pluginPath = this.getHookConfigPath(ctx);\n const configPath = this.getServerConfigPath(ctx);\n\n if (ctx.connector.platforms[HOST]?.hooks === false) {\n return [\n { platform: this.id, action: \"skip\", path: pluginPath, detail: \"hooks disabled for kilo-cli\" },\n ];\n }\n if (ctx.connector.hookEvents.length === 0) {\n return [\n { platform: this.id, action: \"skip\", path: pluginPath, detail: \"connector declares no hooks\" },\n ];\n }\n\n const changes: ChangeRecord[] = [];\n\n // 1. Write the synthesized plugin module.\n for (const file of this.synthesizePlugin(ctx)) {\n const before = existsSync(file.path) ? this.safeRead(file.path) : undefined;\n let action: ChangeRecord[\"action\"];\n if (before === undefined) action = \"create\";\n else if (before === file.contents) action = \"skip\";\n else action = \"update\";\n\n if (action !== \"skip\" && !ctx.dryRun) {\n ensureDir(dirname(file.path));\n writeFileSync(file.path, file.contents, \"utf8\");\n chmodSync(file.path, file.executable ? 0o755 : 0o644);\n }\n changes.push({\n platform: this.id,\n action,\n path: file.path,\n detail: `kilo plugin module (${this.hookDetail(ctx)})`,\n });\n }\n\n // 2. Register the module path in kilo.jsonc's `plugin` array (the fork does\n // NOT auto-discover by directory — it reads this array).\n changes.push(this.upsertPluginInArray(configPath, pluginPath, ctx.dryRun));\n\n return changes;\n }\n\n /**\n * Human-facing summary of which declared events the synthesized module ACTUALLY\n * wires. Only events present in EVENT_TO_KILO are mapped/wired; any declared\n * event with no Kilo mapping is reported separately as \"unsupported here\" so\n * the detail never overstates coverage.\n */\n private hookDetail(ctx: InstallContext): string {\n const declared = ctx.connector.hookEvents;\n const mapped = declared.filter((e) => EVENT_TO_KILO[e] !== undefined);\n const unsupported = declared.filter((e) => EVENT_TO_KILO[e] === undefined);\n const base = mapped.join(\",\");\n return unsupported.length > 0\n ? `${base}; unsupported here: ${unsupported.join(\",\")}`\n : base;\n }\n\n uninstallHooks(ctx: InstallContext): ChangeRecord[] {\n const pluginPath = this.getHookConfigPath(ctx);\n const configPath = this.getServerConfigPath(ctx);\n const changes: ChangeRecord[] = [];\n\n // 1. Deregister the module path from kilo.jsonc's `plugin` array.\n changes.push(this.removePluginFromArray(configPath, pluginPath, ctx.dryRun));\n\n // 2. Remove the plugin module on disk.\n if (existsSync(pluginPath)) {\n if (!ctx.dryRun) rmSync(pluginPath, { force: true });\n changes.push({\n platform: this.id,\n action: \"remove\",\n path: pluginPath,\n detail: \"kilo plugin module\",\n });\n } else {\n changes.push({\n platform: this.id,\n action: \"skip\",\n path: pluginPath,\n detail: \"no kilo plugin module present\",\n });\n }\n\n // 3. Drop the now-empty plugin dir (only if WE own its full contents).\n changes.push(this.removeDirIfEmpty(this.pluginDir(ctx), ctx.dryRun));\n\n return changes;\n }\n\n /** Upsert the module path into kilo.jsonc's top-level `plugin` array (idempotent). */\n private upsertPluginInArray(\n configPath: string,\n modulePath: string,\n dryRun: boolean,\n ): ChangeRecord {\n // OVERWRITE GUARD: never blank a present-but-unparseable kilo.jsonc.\n if (this.isPresentButUnparseable(configPath)) {\n return {\n platform: this.id,\n action: \"warn\",\n path: configPath,\n detail: `existing ${configPath} is not parseable; left untouched (back it up / fix it, then re-run)`,\n };\n }\n const cfg = this.readJson<Record<string, unknown>>(configPath) ?? {};\n const plugins = this.pluginArrayBucket(cfg);\n if (plugins.includes(modulePath)) {\n return {\n platform: this.id,\n action: \"skip\",\n path: configPath,\n detail: `${PLUGIN_ARRAY_KEY}[] already includes module`,\n };\n }\n plugins.push(modulePath);\n this.writeJson(configPath, cfg, dryRun);\n return {\n platform: this.id,\n action: \"create\",\n path: configPath,\n detail: `${PLUGIN_ARRAY_KEY}[] += module`,\n };\n }\n\n /** Remove the module path from kilo.jsonc's `plugin` array. */\n private removePluginFromArray(\n configPath: string,\n modulePath: string,\n dryRun: boolean,\n ): ChangeRecord {\n // OVERWRITE GUARD: a present-but-unparseable file would round-trip to `{}`.\n if (this.isPresentButUnparseable(configPath)) {\n return {\n platform: this.id,\n action: \"warn\",\n path: configPath,\n detail: `existing ${configPath} is not parseable; left untouched (back it up / fix it, then re-run)`,\n };\n }\n const cfg = this.readJson<Record<string, unknown>>(configPath);\n const raw = cfg?.[PLUGIN_ARRAY_KEY];\n const plugins = Array.isArray(raw) ? (raw as unknown[]) : undefined;\n const idx = plugins ? plugins.indexOf(modulePath) : -1;\n if (!cfg || !plugins || idx < 0) {\n return {\n platform: this.id,\n action: \"skip\",\n path: configPath,\n detail: `${PLUGIN_ARRAY_KEY}[] does not include module`,\n };\n }\n plugins.splice(idx, 1);\n this.writeJson(configPath, cfg, dryRun);\n return {\n platform: this.id,\n action: \"remove\",\n path: configPath,\n detail: `${PLUGIN_ARRAY_KEY}[] -= module`,\n };\n }\n\n /** Get-or-create the top-level `plugin` array as a mutable string array. */\n private pluginArrayBucket(cfg: Record<string, unknown>): string[] {\n const existing = cfg[PLUGIN_ARRAY_KEY];\n // Normalize to a fresh string[] (drop any non-string a user may have placed\n // here) and write it back so the caller mutates the live array.\n const plugins = Array.isArray(existing)\n ? existing.filter((p): p is string => typeof p === \"string\")\n : [];\n cfg[PLUGIN_ARRAY_KEY] = plugins;\n return plugins;\n }\n\n // ── Content surfaces: commands / skills / subagents ─────────────────────\n // CONTENT-ONLY: pure native-file writers under the kilo config dir.\n // No runtime dispatch, no home-bin pointer, no telemetry wrap. Each method\n // is idempotent (byte-identical → skip) via BaseAdapter.writeContentFile and\n // reversible via removeContentFile. Honors platforms[\"kilo-cli\"] per-surface\n // false opt-outs.\n //\n // Dirs (live-confirmed kilo v7.3.16 — kilo-pi-ground-truth.md):\n // commands → <kiloDir>/command/<name>.md\n // skills → <kiloDir>/skills/<name>/SKILL.md\n // subagents → <kiloDir>/agent/<name>.md (frontmatter mode:subagent)\n //\n // <kiloDir>:\n // project scope → <projectDir>/.kilo\n // user scope → ~/.config/kilo\n\n private commandsDir(ctx: InstallContext): string {\n return join(this.getConfigDir(ctx), \"command\");\n }\n private skillsDir(ctx: InstallContext): string {\n return join(this.getConfigDir(ctx), \"skills\");\n }\n private agentDir(ctx: InstallContext): string {\n return join(this.getConfigDir(ctx), \"agent\");\n }\n\n private commandPath(ctx: InstallContext, name: string): string {\n return join(this.commandsDir(ctx), `${name}.md`);\n }\n private skillDir(ctx: InstallContext, name: string): string {\n return join(this.skillsDir(ctx), name);\n }\n private subagentPath(ctx: InstallContext, name: string): string {\n return join(this.agentDir(ctx), `${name}.md`);\n }\n\n // ── Commands ───────────────────────────────────────────────────────────────\n\n override installCommands(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n if (connector.platforms[HOST]?.commands === false) {\n return [{ platform: this.id, action: \"skip\", detail: \"commands disabled for kilo-cli\" }];\n }\n if (connector.commands.length === 0) {\n return [{ platform: this.id, action: \"skip\", detail: \"connector declares no commands\" }];\n }\n return connector.commands.map((cmd) =>\n this.writeContentFile(this.commandPath(ctx, cmd.name), renderCommandMd(cmd), ctx.dryRun),\n );\n }\n\n override uninstallCommands(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n if (connector.commands.length === 0) {\n return [{ platform: this.id, action: \"skip\", detail: \"connector declares no commands\" }];\n }\n return connector.commands.map((cmd) =>\n this.removeContentFile(this.commandPath(ctx, cmd.name), ctx.dryRun),\n );\n }\n\n // ── Skills ─────────────────────────────────────────────────────────────────\n\n override installSkills(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n if (connector.platforms[HOST]?.skills === false) {\n return [{ platform: this.id, action: \"skip\", detail: \"skills disabled for kilo-cli\" }];\n }\n if (connector.skills.length === 0) {\n return [{ platform: this.id, action: \"skip\", detail: \"connector declares no skills\" }];\n }\n const changes: ChangeRecord[] = [];\n for (const skill of connector.skills) {\n const dir = this.skillDir(ctx, skill.name);\n changes.push(\n this.writeContentFile(join(dir, \"SKILL.md\"), renderSkillMd(skill), ctx.dryRun),\n );\n for (const [rel, contents] of Object.entries(skill.resources ?? {})) {\n const target = this.resolveWithin(dir, rel);\n if (target === null) {\n changes.push({\n platform: this.id,\n action: \"warn\",\n detail: `skill resource \"${rel}\" escapes the skill dir; skipped`,\n });\n continue;\n }\n changes.push(this.writeContentFile(target, contents, ctx.dryRun));\n }\n }\n return changes;\n }\n\n override uninstallSkills(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n if (connector.skills.length === 0) {\n return [{ platform: this.id, action: \"skip\", detail: \"connector declares no skills\" }];\n }\n const changes: ChangeRecord[] = [];\n for (const skill of connector.skills) {\n const dir = this.skillDir(ctx, skill.name);\n changes.push(this.removeContentFile(join(dir, \"SKILL.md\"), ctx.dryRun));\n for (const rel of Object.keys(skill.resources ?? {})) {\n const target = this.resolveWithin(dir, rel);\n if (target === null) continue;\n changes.push(this.removeContentFile(target, ctx.dryRun));\n }\n changes.push(this.removeDirIfEmpty(dir, ctx.dryRun));\n }\n return changes;\n }\n\n // ── Subagents ──────────────────────────────────────────────────────────────\n\n override installSubagents(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n if (connector.platforms[HOST]?.subagents === false) {\n return [{ platform: this.id, action: \"skip\", detail: \"subagents disabled for kilo-cli\" }];\n }\n if (connector.subagents.length === 0) {\n return [{ platform: this.id, action: \"skip\", detail: \"connector declares no subagents\" }];\n }\n return connector.subagents.map((agent) =>\n this.writeContentFile(\n this.subagentPath(ctx, agent.name),\n this.renderKiloSubagent(agent),\n ctx.dryRun,\n ),\n );\n }\n\n override uninstallSubagents(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n if (connector.subagents.length === 0) {\n return [{ platform: this.id, action: \"skip\", detail: \"connector declares no subagents\" }];\n }\n return connector.subagents.map((agent) =>\n this.removeContentFile(this.subagentPath(ctx, agent.name), ctx.dryRun),\n );\n }\n\n /**\n * Render a subagent to md+frontmatter for kilo-cli.\n * Kilo's shape is (description, mode:\"subagent\", model, permission) with the\n * system prompt as the body — mirrors the opencode adapter's renderSubagent.\n * `name` is NOT a frontmatter field — it comes from the filename.\n * `permission` is derived from the coarse `readonly` knob.\n */\n private renderKiloSubagent(agent: import(\"../../core/types.js\").SubagentDef): string {\n const frontmatter: Record<string, unknown> = {\n description: agent.description,\n mode: \"subagent\",\n };\n if (agent.model !== undefined) frontmatter.model = agent.model;\n if (agent.readonly === true) {\n frontmatter.permission = { edit: \"deny\", bash: \"deny\" };\n }\n if (agent.extra) Object.assign(frontmatter, agent.extra);\n // renderFrontmatterMd is inherited from BaseAdapter (delegates to render.ts).\n return this.renderFrontmatterMd(frontmatter, agent.prompt);\n }\n\n // ── ts-plugin synthesis ────────────────────────────────────────────────\n\n /**\n * Build ONE self-contained ESM plugin module for the Kilo CLI fork.\n *\n * The module imports nothing from agent-connector. It embeds two constants\n * (the absolute home-bin path and the connector id) and a `bridge()` helper\n * that shells out to the universal hook entrypoint via execFileSync, feeding\n * the Kilo payload on stdin and JSON.parsing the normalized HookResponse back\n * from stdout (fail-open: any error → null). Its default export is the\n * `@kilocode/plugin` PluginModule shape — { id, server: async (input) =>\n * ({ \"tool.execute.before\": …, \"tool.execute.after\": …, … }) } — keyed only by\n * the fork event names for the events this connector actually declares.\n */\n synthesizePlugin(ctx: InstallContext): GeneratedPluginFile[] {\n const path = this.getHookConfigPath(ctx);\n const contents = this.buildPluginSource(ctx);\n return [{ path, contents, executable: false }];\n }\n\n /** Compose the generated plugin source with plain string concatenation. */\n private buildPluginSource(ctx: InstallContext): string {\n // The Kilo event keys this connector declares (and that we can map).\n const events = ctx.connector.hookEvents.filter(\n (e): e is HookEventName => EVENT_TO_KILO[e] !== undefined,\n );\n const has = (e: HookEventName) => events.includes(e);\n\n const header = `/**\n * AUTO-GENERATED by agent-connector — DO NOT EDIT.\n *\n * Self-contained Kilo CLI plugin bridge for connector ${ctx.connector.id}.\n * It imports nothing from agent-connector: every hook invocation shells out to\n * the stable home binary's universal entrypoint and JSON-parses the normalized\n * response. Fail-open: any bridge error degrades to \"allow\".\n *\n * Default export is the @kilocode/plugin PluginModule shape\n * ({ id, server: async (input) => Hooks }); the fork loads it because its path\n * is registered in kilo.jsonc's \"plugin\" array.\n */\nimport { execFileSync, execSync } from \"node:child_process\";\n\n${renderBridgePrelude({\n homeBin: ctx.homeBinPath,\n connectorId: ctx.connector.id,\n hookSlug: \"kilo-cli\",\n payloadNoun: \"Kilo\",\n eventDoc: \" (PreToolUse|PostToolUse|SessionStart)\",\n failOpenComment: \"Fail-open — never wedge a tool call on a bridge error.\",\n})}\n`;\n\n const handlers: string[] = [];\n\n if (has(\"PreToolUse\")) {\n handlers.push(` // PreToolUse → block (throw) / rewrite args (mutate output.args).\n \"tool.execute.before\": async (input, output) => {\n const payload = {\n toolName: input.tool ?? \"\",\n toolInput: (output && output.args) ?? {},\n sessionId: input.sessionID ?? \"\",\n projectDir: PROJECT_DIR,\n };\n const res = bridge(\"PreToolUse\", payload);\n if (!res) return;\n // Kilo has no \"ask\" gate — degrade \"ask\" to a block (safe direction).\n if (res.decision === \"deny\" || res.decision === \"ask\") {\n throw new Error(res.reason || \"Blocked by ${ctx.connector.id}\");\n }\n if (res.updatedInput && output && output.args) {\n Object.assign(output.args, res.updatedInput);\n }\n },`);\n }\n\n if (has(\"PostToolUse\")) {\n handlers.push(` // PostToolUse → observe / rewrite tool output (mutate output.output).\n \"tool.execute.after\": async (input, output) => {\n const payload = {\n toolName: input.tool ?? \"\",\n toolInput: input.args ?? {},\n toolOutput: output ? output.output : undefined,\n sessionId: input.sessionID ?? \"\",\n projectDir: PROJECT_DIR,\n };\n const res = bridge(\"PostToolUse\", payload);\n if (!res) return;\n if (typeof res.updatedOutput === \"string\" && output) {\n output.output = res.updatedOutput;\n }\n },`);\n }\n\n if (has(\"SessionStart\")) {\n handlers.push(` // SessionStart surrogate → inject context into the system prompt.\n // The fork has no real SessionStart hook; the system-prompt transform is the\n // verified injection point (mirrors OpenCode).\n \"experimental.chat.system.transform\": async (input, output) => {\n const payload = {\n sessionId: (input && input.sessionID) ?? \"\",\n projectDir: PROJECT_DIR,\n };\n const res = bridge(\"SessionStart\", payload);\n if (!res) return;\n if (res.additionalContext && output && Array.isArray(output.system)) {\n // Insert at index 1 (after the header) to preserve the prompt-cache fold\n // (header must remain system[0]).\n output.system.splice(1, 0, res.additionalContext);\n }\n },`);\n }\n\n if (has(\"UserPromptSubmit\")) {\n handlers.push(` // UserPromptSubmit → context injection on prompt submission.\n // chat.message fires when a new user message arrives; output.parts holds the\n // prompt parts. Inject context by PUSHING a text part onto output.parts.\n // chat.message has NO documented block/abort, so a \"deny\" decision degrades\n // to a NO-OP (best-effort) — mirrors the mimo-code OpenCode fork.\n \"chat.message\": async (input, output) => {\n const promptText =\n output && Array.isArray(output.parts)\n ? output.parts\n .filter((p) => p && p.type === \"text\" && typeof p.text === \"string\")\n .map((p) => p.text)\n .join(\"\\\\n\")\n : \"\";\n const res = bridge(\"UserPromptSubmit\", {\n prompt: promptText,\n sessionId: (input && input.sessionID) || \"\",\n projectDir: PROJECT_DIR,\n });\n if (!res) return;\n if (res.additionalContext && output && Array.isArray(output.parts)) {\n output.parts.push({ type: \"text\", text: res.additionalContext });\n }\n },`);\n }\n\n if (has(\"PermissionRequest\")) {\n handlers.push(` // PermissionRequest → decision-capable permission gate.\n // permission.ask MUTATES output.status (\"ask\"|\"deny\"|\"allow\") — it does NOT\n // return a value (mirrors tool.execute.before mutating output.args). A\n // normalized \"deny\" maps to output.status \"deny\"; \"ask\" to \"ask\"; allow/void\n // leave the default status untouched.\n \"permission.ask\": async (input, output) => {\n const payload = {\n toolName: (input && (input.type || input.tool)) ?? \"\",\n toolInput: (input && (input.metadata || input.args)) ?? {},\n sessionId: (input && input.sessionID) ?? \"\",\n projectDir: PROJECT_DIR,\n };\n const res = bridge(\"PermissionRequest\", payload);\n if (!res || !output) return;\n if (res.decision === \"deny\") output.status = \"deny\";\n else if (res.decision === \"ask\") output.status = \"ask\";\n },`);\n }\n\n if (has(\"Stop\")) {\n handlers.push(` // Stop → session.idle (\"session finished responding\"). session.idle is NOT a\n // direct hook key — it is dispatched through the generic \\`event\\` hook\n // switching on event.type. A block decision throws to halt (Kilo has no\n // Stop-gate return value).\n event: async ({ event }) => {\n if (!event || event.type !== \"session.idle\") return;\n const res = bridge(\"Stop\", {\n sessionId: (event.properties && event.properties.sessionID) || \"\",\n projectDir: PROJECT_DIR,\n });\n if (res && res.decision === \"deny\") {\n throw new Error(res.reason || \"Stop blocked by ${ctx.connector.id}\");\n }\n },`);\n }\n\n const definition = `\nconst plugin = {\n id: CONNECTOR_ID,\n // @kilocode/plugin PluginModule: server(input) returns the Hooks object keyed\n // by the fork's event names. ctx.directory is the project root; fall back to cwd.\n server: async (input) => {\n const PROJECT_DIR =\n (input && (input.directory || (input.worktree && input.worktree.path))) ||\n process.cwd();\n\n return {\n${handlers.join(\"\\n\")}\n };\n },\n};\n\nexport default plugin;\n`;\n\n return header + definition;\n }\n\n // ── Runtime: parse OUR bridge payload → normalized event ───────────────\n\n /**\n * `raw` is the payload OUR generated plugin posts (NOT a host-native shape):\n * { toolName, toolInput, toolOutput?, isError?, sessionId, projectDir }\n * so this maps straight through.\n */\n parseEvent(event: HookEventName, raw: unknown): NormalizedEvent {\n const input = (raw ?? {}) as KiloBridgePayload;\n const base = {\n hostPlatform: HOST,\n connectorId: \"\",\n sessionId: typeof input.sessionId === \"string\" ? input.sessionId : \"\",\n raw,\n ...(typeof input.projectDir === \"string\" ? { projectDir: input.projectDir } : {}),\n } as const;\n\n switch (event) {\n case \"PreToolUse\": {\n const ev: PreToolUseEvent = {\n ...base,\n toolName: input.toolName ?? \"\",\n toolInput: input.toolInput ?? {},\n };\n return ev;\n }\n case \"PostToolUse\": {\n const ev: PostToolUseEvent = {\n ...base,\n toolName: input.toolName ?? \"\",\n toolInput: input.toolInput ?? {},\n ...(typeof input.toolOutput === \"string\" ? { toolOutput: input.toolOutput } : {}),\n ...(typeof input.isError === \"boolean\" ? { isError: input.isError } : {}),\n };\n return ev;\n }\n case \"SessionStart\": {\n const ev: SessionStartEvent = { ...base, source: \"startup\" };\n return ev;\n }\n case \"UserPromptSubmit\": {\n const ev: UserPromptSubmitEvent = {\n ...base,\n prompt: typeof input.prompt === \"string\" ? input.prompt : \"\",\n };\n return ev;\n }\n case \"PermissionRequest\": {\n const ev: PermissionRequestEvent = {\n ...base,\n toolName: input.toolName ?? \"\",\n toolInput: input.toolInput ?? {},\n };\n return ev;\n }\n case \"Stop\": {\n const ev: StopEvent = { ...base };\n return ev;\n }\n default:\n // Other canonical events are not surfaced by Kilo; treat as a\n // session-start-shaped no-op so the dispatcher fails open gracefully.\n return { ...base, source: \"startup\" } satisfies SessionStartEvent;\n }\n }\n\n // ── Runtime: normalized response → reply the generated bridge parses ───\n\n /**\n * Unlike json-stdio hosts (whose reply is the host's NATIVE control payload),\n * OUR generated bridge consumes this stdout directly. So the reply body is the\n * NORMALIZED HookResponse itself — the bridge JSON.parses it and reads\n * decision / updatedInput / updatedOutput / additionalContext.\n */\n formatReply(_event: HookEventName, response: HookResponse): HookReply {\n return {\n exitCode: 0,\n stdout: JSON.stringify(response ?? { decision: \"allow\" }),\n };\n }\n\n // ── Diagnostics ──────────────────────────────────────────────────────────\n\n override getHealthChecks(ctx: InstallContext): readonly HealthCheck[] {\n const configPath = this.getServerConfigPath(ctx);\n const pluginPath = this.getHookConfigPath(ctx);\n const connectorId = ctx.connector.id;\n const hasHooks = ctx.connector.hookEvents.length > 0;\n\n return [\n {\n name: `${this.name}: ${CONFIG_FILE} present`,\n check: () =>\n existsSync(configPath)\n ? { status: \"OK\", detail: configPath }\n : { status: \"FAIL\", detail: `not found: ${configPath}` },\n },\n {\n name: `${this.name}: server entry registered`,\n check: () => {\n if (!ctx.connector.server) {\n return { status: \"OK\", detail: \"no MCP server declared\" };\n }\n const cfg = this.readJson<{ [k: string]: Record<string, unknown> }>(configPath);\n const bucket = cfg?.[MCP_ROOT_KEY];\n if (!cfg || !bucket) {\n return { status: \"FAIL\", detail: `no ${MCP_ROOT_KEY} in ${configPath}` };\n }\n return connectorId in bucket\n ? { status: \"OK\", detail: `${MCP_ROOT_KEY}.${connectorId} present` }\n : {\n status: \"FAIL\",\n detail: `no ${MCP_ROOT_KEY}.${connectorId} in ${configPath}`,\n };\n },\n },\n {\n name: `${this.name}: plugin module present`,\n check: () => {\n if (!hasHooks) return { status: \"OK\", detail: \"no hooks declared\" };\n return existsSync(pluginPath)\n ? { status: \"OK\", detail: pluginPath }\n : { status: \"FAIL\", detail: `not found: ${pluginPath}` };\n },\n },\n {\n name: `${this.name}: plugin registered in ${PLUGIN_ARRAY_KEY}[]`,\n check: () => {\n if (!hasHooks) return { status: \"OK\", detail: \"no hooks declared\" };\n const cfg = this.readJson<Record<string, unknown>>(configPath);\n const raw = cfg?.[PLUGIN_ARRAY_KEY];\n const plugins = Array.isArray(raw) ? (raw as unknown[]) : undefined;\n return plugins && plugins.includes(pluginPath)\n ? { status: \"OK\", detail: `${PLUGIN_ARRAY_KEY}[] includes module` }\n : {\n status: \"FAIL\",\n detail: `module not in ${PLUGIN_ARRAY_KEY}[] of ${configPath} (fork will not load it)`,\n };\n },\n },\n ];\n }\n\n /** Read a file, returning undefined on any error (idempotency compare). */\n private safeRead(path: string): string | undefined {\n try {\n return readFileSync(path, \"utf8\");\n } catch {\n return undefined;\n }\n }\n}\n\n/** Create a directory (recursive) if it does not already exist. */\nfunction ensureDir(dir: string): void {\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true });\n}\n\nexport const adapter = new KiloCliAdapter();\nexport default adapter;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAgEA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,eAAe;AACxB,SAAS,SAAS,YAAY;AAoC9B,IAAM,OAAmB;AAEzB,IAAM,eAAe;AAErB,IAAM,mBAAmB;AAEzB,IAAM,cAAc;AAEpB,IAAM,iBAAiB,CAAC,UAAU,SAAS,QAAQ,SAAS;AAY5D,IAAM,gBAAwD;AAAA,EAC5D,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,cAAc;AAAA;AAAA;AAAA,EAGd,kBAAkB;AAAA;AAAA;AAAA,EAGlB,mBAAmB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOnB,MAAM;AACR;AA6BO,IAAM,iBAAN,cAA6B,YAA+B;AAAA,EACxD,KAAiB;AAAA,EACjB,OAAO;AAAA,EACP,WAAyB;AAAA,EAEzB,eAAqC;AAAA;AAAA;AAAA,IAG5C,gBAAgB;AAAA;AAAA;AAAA,IAGhB,YAAY;AAAA,IACZ,aAAa;AAAA;AAAA,IAEb,YAAY;AAAA,IACZ,cAAc;AAAA,IACd,YAAY;AAAA;AAAA;AAAA,IAGZ,kBAAkB;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AAE,QAAQ,MAAM,QAAQ,oBAAoB;AAClE,iBAAO,WAAW,UAAU,IACxB,EAAE,QAAQ,MAAM,QAAQ,WAAW,IACnC,EAAE,QAAQ,QAAQ,QAAQ,cAAc,UAAU,GAAG;AAAA,QAC3D;AAAA,MACF;AAAA,MACA;AAAA,QACE,MAAM,GAAG,KAAK,IAAI,0BAA0B,gBAAgB;AAAA,QAC5D,OAAO,MAAM;AACX,cAAI,CAAC,SAAU,QAAO,EAAE,QAAQ,MAAM,QAAQ,oBAAoB;AAClE,gBAAM,MAAM,KAAK,SAAkC,UAAU;AAC7D,gBAAM,MAAM,MAAM,gBAAgB;AAClC,gBAAM,UAAU,MAAM,QAAQ,GAAG,IAAK,MAAoB;AAC1D,iBAAO,WAAW,QAAQ,SAAS,UAAU,IACzC,EAAE,QAAQ,MAAM,QAAQ,GAAG,gBAAgB,qBAAqB,IAChE;AAAA,YACE,QAAQ;AAAA,YACR,QAAQ,iBAAiB,gBAAgB,SAAS,UAAU;AAAA,UAC9D;AAAA,QACN;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAAA;AAAA,EAGQ,SAAS,MAAkC;AACjD,QAAI;AACF,aAAO,aAAa,MAAM,MAAM;AAAA,IAClC,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAGA,SAAS,UAAU,KAAmB;AACpC,MAAI,CAAC,WAAW,GAAG,EAAG,WAAU,KAAK,EAAE,WAAW,KAAK,CAAC;AAC1D;AAEO,IAAM,UAAU,IAAI,eAAe;AAC1C,IAAO,mBAAQ;","names":["entry"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/usage/readers/kimi.ts"],"sourcesContent":["/**\n * usage/readers/kimi — Kimi CLI (Moonshot) native session-log reader.\n *\n * Faithful port of tokscale sessions/kimi.rs. Reads the wire protocol log at\n * ~/.kimi/sessions/<GROUP_ID>/<SESSION_UUID>/wire.jsonl\n * (the model name is read from the sibling ~/.kimi/config.json). Each line is a\n * timestamped wire frame; only frames whose `message.type === \"StatusUpdate\"`\n * carry a `payload.token_usage` block:\n * input_other → input\n * output → output\n * input_cache_read → cacheRead\n * input_cache_creation → cacheWrite (cache CREATION cost, not a read)\n * reasoning is always 0 (the wire protocol folds reasoning into output).\n *\n * The first line (`{\"type\":\"metadata\", …}`) and every non-StatusUpdate frame\n * (TurnBegin / ContentPart / ToolCall / StepBegin …) are skipped. Zero-token\n * StatusUpdates are dropped.\n *\n * DEDUP (the double-counting hazard): Kimi emits PROGRESSIVE StatusUpdates for a\n * single assistant message as generation streams (e.g. message_id \"msg-x\" at\n * 100→10 tokens, then 120→30). We dedup by `payload.message_id`, keeping the row\n * with the MAX total tokens (tie-break: the later timestamp). Records WITHOUT a\n * (non-empty) message_id are never merged — each passes through as its own row,\n * exactly as the Rust push_or_replace_status_update does. The kept row's\n * `dedupKey` is its message_id (absent for un-keyed rows).\n *\n * Storage root: ~/.kimi/sessions, with two overrides honored on top of the fixed\n * paths.ts resolution — the AGENT_CONNECTOR_KIMI_DIR override (via\n * firstExistingRoot) and $KIMI_CODE_HOME, which relocates the Kimi home (the\n * config.json lookup is path-relative, so it transparently handles a `.kimi-code`\n * home as well as `.kimi`).\n *\n * Model: `.model` from <home>/config.json (fallback \"kimi-for-coding\"); provider\n * is hard-coded \"moonshot\". Session id is the SESSION_UUID directory name. Kimi's\n * wire log carries no cwd, so there is no project attribution. Confidence is\n * \"host-reported\" (real host token counts).\n *\n * Fail-open: no root → []; an unreadable/malformed file or line → skipped.\n */\n\nimport { basename, dirname, join } from \"node:path\";\n\nimport type { TokenBreakdown, UsageReader, UsageRecord } from \"../types.js\";\nimport { emptyTokens } from \"../aggregate.js\";\nimport { fileMtimeMs, readJsonFile, readJsonlLines } from \"../jsonl.js\";\nimport { expandHome, firstExistingRoot, isDir, walkFiles } from \"../paths.js\";\n\nconst PLATFORM_ID = \"kimi\" as const;\nconst DEFAULT_MODEL = \"kimi-for-coding\";\nconst DEFAULT_PROVIDER = \"moonshot\";\n\n/** A wire.jsonl line: metadata header OR a timestamped message frame. */\ninterface WireLine {\n type?: unknown;\n timestamp?: unknown;\n message?: {\n type?: unknown;\n payload?: {\n token_usage?: {\n input_other?: unknown;\n output?: unknown;\n input_cache_read?: unknown;\n input_cache_creation?: unknown;\n };\n message_id?: unknown;\n };\n };\n}\n\n/** Coerce an unknown to a non-negative integer (0 on absence/garbage). */\nfunction toNonNegInt(v: unknown): number {\n const n = typeof v === \"number\" ? v : typeof v === \"string\" ? Number(v) : NaN;\n if (!Number.isFinite(n)) return 0;\n return Math.max(0, Math.trunc(n));\n}\n\n/**\n * Convert the wire `timestamp` (Unix seconds, often fractional like\n * 1770983426.420942) to epoch ms. Returns null when unusable so the caller can\n * fall back to the file mtime (port of `timestamp * 1000.0 as i64`).\n */\nfunction parseWireTs(v: unknown): number | null {\n if (typeof v === \"number\" && Number.isFinite(v) && v > 0) {\n return Math.trunc(v * 1000);\n }\n return null;\n}\n\n/**\n * Read the model name from the Kimi home's config.json (port of\n * read_model_from_config). The wire path is\n * <home>/sessions/<GROUP_ID>/<SESSION_UUID>/wire.jsonl\n * so the home dir is four `dirname` hops up, and config.json sits beside the\n * sessions dir. Fail-open to DEFAULT_MODEL on any missing/garbage value.\n */\nfunction readModelFromConfig(wirePath: string): string {\n // wire.jsonl → SESSION_UUID → GROUP_ID → sessions → <home>\n const sessionDir = dirname(wirePath);\n const groupDir = dirname(sessionDir);\n const sessionsDir = dirname(groupDir);\n const homeDir = dirname(sessionsDir);\n const configPath = join(homeDir, \"config.json\");\n\n const parsed = readJsonFile(configPath);\n if (typeof parsed === \"object\" && parsed !== null) {\n const model = (parsed as { model?: unknown }).model;\n if (typeof model === \"string\" && model !== \"\") return model;\n }\n return DEFAULT_MODEL;\n}\n\n/**\n * Session id from the wire path: the SESSION_UUID directory name (the immediate\n * parent of wire.jsonl). Port of extract_session_id.\n */\nfunction extractSessionId(wirePath: string): string {\n const dir = basename(dirname(wirePath));\n return dir === \"\" ? \"unknown\" : dir;\n}\n\n/** Sum of the five token dimensions (port of TokenBreakdown::total). */\nfunction tokenTotal(t: TokenBreakdown): number {\n return t.input + t.output + t.cacheRead + t.cacheWrite + t.reasoning;\n}\n\n/**\n * Whether `candidate` should replace `existing` for the same message_id. Port of\n * should_replace_status_update: a strictly larger total wins; on an equal total\n * the later-or-equal timestamp wins (so the freshest progressive update is kept).\n */\nfunction shouldReplace(existing: UsageRecord, candidate: UsageRecord): boolean {\n const existingTotal = tokenTotal(existing.tokens);\n const candidateTotal = tokenTotal(candidate.tokens);\n return (\n candidateTotal > existingTotal ||\n (candidateTotal === existingTotal && candidate.ts >= existing.ts)\n );\n}\n\n/** Parse one Kimi wire.jsonl file into usage records (port of parse_kimi_file). */\nfunction parseKimiFile(path: string): UsageRecord[] {\n const lines = readJsonlLines(path);\n if (lines.length === 0) return [];\n\n const model = readModelFromConfig(path);\n const sessionId = extractSessionId(path);\n const mtime = fileMtimeMs(path);\n\n const out: UsageRecord[] = [];\n // message_id → index into `out`, for progressive-StatusUpdate dedup.\n const keyedIndices = new Map<string, number>();\n\n for (const raw of lines) {\n if (typeof raw !== \"object\" || raw === null) continue;\n const wire = raw as WireLine;\n\n // Skip the metadata header line.\n if (wire.type === \"metadata\") continue;\n\n const message = wire.message;\n if (typeof message !== \"object\" || message === null) continue;\n\n // Only StatusUpdate frames carry token usage.\n if (message.type !== \"StatusUpdate\") continue;\n\n const payload = message.payload;\n if (typeof payload !== \"object\" || payload === null) continue;\n\n const usage = payload.token_usage;\n if (typeof usage !== \"object\" || usage === null) continue;\n\n const input = toNonNegInt(usage.input_other);\n const output = toNonNegInt(usage.output);\n const cacheRead = toNonNegInt(usage.input_cache_read);\n const cacheWrite = toNonNegInt(usage.input_cache_creation);\n\n // Skip zero-token entries.\n if (input + output + cacheRead + cacheWrite === 0) continue;\n\n const ts = parseWireTs(wire.timestamp) ?? mtime;\n\n const tokens = emptyTokens();\n tokens.input = input;\n tokens.output = output;\n tokens.cacheRead = cacheRead;\n tokens.cacheWrite = cacheWrite;\n // reasoning stays 0 — the Kimi wire protocol folds reasoning into output.\n\n const messageId = payload.message_id;\n const dedupKey =\n typeof messageId === \"string\" && messageId !== \"\" ? messageId : undefined;\n\n const record: UsageRecord = {\n platformId: PLATFORM_ID,\n modelId: model,\n providerId: DEFAULT_PROVIDER,\n sessionId,\n tokens,\n ts,\n messageCount: 1,\n confidence: \"host-reported\",\n };\n if (dedupKey !== undefined) record.dedupKey = dedupKey;\n\n if (dedupKey === undefined) {\n // Un-keyed StatusUpdates are never merged — each is its own row.\n out.push(record);\n continue;\n }\n\n const existingIndex = keyedIndices.get(dedupKey);\n if (existingIndex !== undefined) {\n const existing = out[existingIndex];\n if (existing !== undefined && shouldReplace(existing, record)) {\n out[existingIndex] = record;\n }\n continue;\n }\n\n keyedIndices.set(dedupKey, out.length);\n out.push(record);\n }\n\n return out;\n}\n\n/**\n * Candidate Kimi session roots, most-preferred first. Honors the fixed paths.ts\n * resolution (AGENT_CONNECTOR_KIMI_DIR override → ~/.kimi/sessions) plus\n * $KIMI_CODE_HOME, which relocates the Kimi home directory.\n */\nfunction kimiSessionRoots(): string[] {\n const roots: string[] = [];\n\n const codeHome = process.env.KIMI_CODE_HOME;\n if (codeHome != null && codeHome.trim() !== \"\") {\n roots.push(join(expandHome(codeHome.trim()), \"sessions\"));\n }\n\n const standard = firstExistingRoot(PLATFORM_ID);\n if (standard !== undefined) roots.push(standard);\n\n return roots;\n}\n\n/** The Kimi CLI usage reader singleton. */\nconst kimiReader: UsageReader = {\n platformId: PLATFORM_ID,\n kind: \"local\",\n async read({ sinceMs }: { sinceMs?: number }): Promise<UsageRecord[]> {\n const roots = kimiSessionRoots().filter((r) => isDir(r));\n if (roots.length === 0) return []; // no ~/.kimi/sessions → fail-open\n\n // <root>/<GROUP_ID>/<SESSION_UUID>/wire.jsonl\n const seen = new Set<string>();\n const records: UsageRecord[] = [];\n for (const root of roots) {\n const files = walkFiles(root, (name) => name === \"wire.jsonl\");\n for (const file of files) {\n if (seen.has(file)) continue; // de-overlap if KIMI_CODE_HOME == ~/.kimi\n seen.add(file);\n const rows = parseKimiFile(file);\n for (const row of rows) {\n if (sinceMs !== undefined && row.ts < sinceMs) continue;\n records.push(row);\n }\n }\n }\n return records;\n },\n};\n\nexport default kimiReader;\n"],"mappings":";;;;;;;;;;;;;;;;;AAwCA,SAAS,UAAU,SAAS,YAAY;AAOxC,IAAM,cAAc;AACpB,IAAM,gBAAgB;AACtB,IAAM,mBAAmB;AAqBzB,SAAS,YAAY,GAAoB;AACvC,QAAM,IAAI,OAAO,MAAM,WAAW,IAAI,OAAO,MAAM,WAAW,OAAO,CAAC,IAAI;AAC1E,MAAI,CAAC,OAAO,SAAS,CAAC,EAAG,QAAO;AAChC,SAAO,KAAK,IAAI,GAAG,KAAK,MAAM,CAAC,CAAC;AAClC;AAOA,SAAS,YAAY,GAA2B;AAC9C,MAAI,OAAO,MAAM,YAAY,OAAO,SAAS,CAAC,KAAK,IAAI,GAAG;AACxD,WAAO,KAAK,MAAM,IAAI,GAAI;AAAA,EAC5B;AACA,SAAO;AACT;AASA,SAAS,oBAAoB,UAA0B;AAErD,QAAM,aAAa,QAAQ,QAAQ;AACnC,QAAM,WAAW,QAAQ,UAAU;AACnC,QAAM,cAAc,QAAQ,QAAQ;AACpC,QAAM,UAAU,QAAQ,WAAW;AACnC,QAAM,aAAa,KAAK,SAAS,aAAa;AAE9C,QAAM,SAAS,aAAa,UAAU;AACtC,MAAI,OAAO,WAAW,YAAY,WAAW,MAAM;AACjD,UAAM,QAAS,OAA+B;AAC9C,QAAI,OAAO,UAAU,YAAY,UAAU,GAAI,QAAO;AAAA,EACxD;AACA,SAAO;AACT;AAMA,SAAS,iBAAiB,UAA0B;AAClD,QAAM,MAAM,SAAS,QAAQ,QAAQ,CAAC;AACtC,SAAO,QAAQ,KAAK,YAAY;AAClC;AAGA,SAAS,WAAW,GAA2B;AAC7C,SAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,YAAY,EAAE,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