@ken-jo/agent-connector 0.4.95 → 0.4.97

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.
Files changed (378) hide show
  1. package/LICENSE +202 -202
  2. package/NOTICE +6 -6
  3. package/README.md +605 -599
  4. package/dist/{action-Q7GGO4PA.js → action-IPFDPOZU.js} +16 -16
  5. package/dist/action-IPFDPOZU.js.map +1 -0
  6. package/dist/{amazon-q-ETMAGY3D.js → amazon-q-IT44LEWV.js} +6 -6
  7. package/dist/amazon-q-IT44LEWV.js.map +1 -0
  8. package/dist/{amp-BQZOL5GR.js → amp-CEWOSWQO.js} +4 -4
  9. package/dist/amp-CEWOSWQO.js.map +1 -0
  10. package/dist/{amp-67BZONGF.js → amp-P35FRU2Z.js} +7 -7
  11. package/dist/amp-P35FRU2Z.js.map +1 -0
  12. package/dist/{antigravity-EA4L225L.js → antigravity-LHFEFNMC.js} +5 -5
  13. package/dist/antigravity-LHFEFNMC.js.map +1 -0
  14. package/dist/antigravity-TWIWXTQH.js +18 -0
  15. package/dist/{antigravity-cli-B2HXZFYQ.js → antigravity-cli-MOKFSWOU.js} +5 -5
  16. package/dist/antigravity-cli-MOKFSWOU.js.map +1 -0
  17. package/dist/{antigravity-cli-OM6SC3PE.js → antigravity-cli-MPE27LPI.js} +9 -9
  18. package/dist/antigravity-cli-MPE27LPI.js.map +1 -0
  19. package/dist/audit-3E5JAOP2.js +311 -0
  20. package/dist/audit-3E5JAOP2.js.map +1 -0
  21. package/dist/{chunk-PW42ZXCB.js → chunk-3EP5V2F4.js} +3 -3
  22. package/dist/chunk-3EP5V2F4.js.map +1 -0
  23. package/dist/{chunk-MGTDQLJJ.js → chunk-3FINQ2ZF.js} +4 -4
  24. package/dist/chunk-3FINQ2ZF.js.map +1 -0
  25. package/dist/{chunk-KHO5WNTP.js → chunk-4GH2KA7V.js} +1 -1
  26. package/dist/chunk-4GH2KA7V.js.map +1 -0
  27. package/dist/{chunk-2Y2MZRLP.js → chunk-7C2IPIIB.js} +3 -3
  28. package/dist/chunk-7C2IPIIB.js.map +1 -0
  29. package/dist/{chunk-NLE2J5P4.js → chunk-7HHW23AC.js} +29 -29
  30. package/dist/chunk-7HHW23AC.js.map +1 -0
  31. package/dist/{chunk-XD7MY6HB.js → chunk-7PSNXUFK.js} +1 -1
  32. package/dist/chunk-7PSNXUFK.js.map +1 -0
  33. package/dist/{chunk-5IOTP7LQ.js → chunk-7ZFK2WEO.js} +7 -5
  34. package/dist/chunk-7ZFK2WEO.js.map +1 -0
  35. package/dist/{chunk-XC5SJ35F.js → chunk-C63AAXK7.js} +5 -5
  36. package/dist/chunk-C63AAXK7.js.map +1 -0
  37. package/dist/{chunk-UM5S7DKK.js → chunk-C747DYNT.js} +1 -1
  38. package/dist/chunk-C747DYNT.js.map +1 -0
  39. package/dist/{chunk-YPAXJ7EW.js → chunk-FHYR5Q5T.js} +13 -13
  40. package/dist/chunk-FHYR5Q5T.js.map +1 -0
  41. package/dist/{chunk-I5UXHIDT.js → chunk-GCPEPUD7.js} +8 -8
  42. package/dist/chunk-GCPEPUD7.js.map +1 -0
  43. package/dist/{chunk-ISEJWBFF.js → chunk-GZZCHJDP.js} +2 -2
  44. package/dist/chunk-GZZCHJDP.js.map +1 -0
  45. package/dist/{chunk-UMQ6NBQR.js → chunk-ILWHLGIC.js} +2 -2
  46. package/dist/chunk-ILWHLGIC.js.map +1 -0
  47. package/dist/{chunk-IVAWP6HH.js → chunk-IOJDZJ72.js} +2 -2
  48. package/dist/chunk-IOJDZJ72.js.map +1 -0
  49. package/dist/{chunk-NBYKLUF6.js → chunk-KFPSJRHR.js} +2 -2
  50. package/dist/chunk-KFPSJRHR.js.map +1 -0
  51. package/dist/{chunk-O7SDRBVB.js → chunk-KM2YXO6V.js} +1 -1
  52. package/dist/chunk-KM2YXO6V.js.map +1 -0
  53. package/dist/{chunk-7F5KHLEP.js → chunk-L2C5UMKW.js} +4 -4
  54. package/dist/chunk-L2C5UMKW.js.map +1 -0
  55. package/dist/{chunk-OP4KBXUO.js → chunk-LFWYYWLV.js} +1 -1
  56. package/dist/chunk-LFWYYWLV.js.map +1 -0
  57. package/dist/{chunk-APZDTY76.js → chunk-LQ55E7QI.js} +7 -7
  58. package/dist/chunk-LQ55E7QI.js.map +1 -0
  59. package/dist/{chunk-PAPMUAR5.js → chunk-MLU7NDAZ.js} +12 -12
  60. package/dist/chunk-MLU7NDAZ.js.map +1 -0
  61. package/dist/{chunk-H33M77DD.js → chunk-N4ENLZEU.js} +22 -19
  62. package/dist/chunk-N4ENLZEU.js.map +1 -0
  63. package/dist/{chunk-D4ELPBB5.js → chunk-NDMNMAKP.js} +43 -43
  64. package/dist/chunk-NDMNMAKP.js.map +1 -0
  65. package/dist/{chunk-H53QZQJI.js → chunk-PSGTHJQU.js} +1 -1
  66. package/dist/chunk-PSGTHJQU.js.map +1 -0
  67. package/dist/{chunk-FBJQGRET.js → chunk-Q4ISQHUQ.js} +1 -1
  68. package/dist/chunk-Q4ISQHUQ.js.map +1 -0
  69. package/dist/{chunk-6TF7MHG5.js → chunk-Q7PR2WGT.js} +2 -2
  70. package/dist/chunk-Q7PR2WGT.js.map +1 -0
  71. package/dist/{chunk-GZGLCCEE.js → chunk-QYOUQCC6.js} +1 -1
  72. package/dist/chunk-QYOUQCC6.js.map +1 -0
  73. package/dist/{chunk-Z2MRSS2I.js → chunk-SLJI5BOM.js} +2 -2
  74. package/dist/chunk-SLJI5BOM.js.map +1 -0
  75. package/dist/{chunk-JKKU2WKG.js → chunk-TGZFDXNH.js} +4 -4
  76. package/dist/chunk-TGZFDXNH.js.map +1 -0
  77. package/dist/{chunk-FJCUKXGX.js → chunk-THI4PI4H.js} +2 -2
  78. package/dist/chunk-THI4PI4H.js.map +1 -0
  79. package/dist/{chunk-MQPNU2CY.js → chunk-UZZTWWGG.js} +1 -1
  80. package/dist/chunk-UZZTWWGG.js.map +1 -0
  81. package/dist/{chunk-3NH2ARIS.js → chunk-WPTNMYYM.js} +2 -2
  82. package/dist/chunk-WPTNMYYM.js.map +1 -0
  83. package/dist/{chunk-OPXAP3AC.js → chunk-XN7S44U4.js} +1 -1
  84. package/dist/chunk-XN7S44U4.js.map +1 -0
  85. package/dist/{chunk-6WZODR3Z.js → chunk-XVEJAFKW.js} +5 -5
  86. package/dist/chunk-XVEJAFKW.js.map +1 -0
  87. package/dist/{chunk-BEFVJ2OE.js → chunk-XXLCMSD3.js} +1 -1
  88. package/dist/chunk-XXLCMSD3.js.map +1 -0
  89. package/dist/{chunk-YT43MUSJ.js → chunk-XZWMJLIT.js} +1 -1
  90. package/dist/chunk-XZWMJLIT.js.map +1 -0
  91. package/dist/{chunk-4NHXLXSD.js → chunk-Y3K6KJMS.js} +2 -2
  92. package/dist/chunk-Y3K6KJMS.js.map +1 -0
  93. package/dist/{chunk-RK6VBLXP.js → chunk-ZSOS2KOR.js} +1 -1
  94. package/dist/chunk-ZSOS2KOR.js.map +1 -0
  95. package/dist/{claude-code-NMRKTAP7.js → claude-code-FS42PXZO.js} +4 -4
  96. package/dist/claude-code-FS42PXZO.js.map +1 -0
  97. package/dist/{claude-code-GRWO6XBZ.js → claude-code-QBWDT5RT.js} +11 -11
  98. package/dist/claude-code-QBWDT5RT.js.map +1 -0
  99. package/dist/cli/sdk.js +9 -8
  100. package/dist/cli/sdk.js.map +1 -1
  101. package/dist/cli.js +1 -1
  102. package/dist/cli.js.map +1 -1
  103. package/dist/{cline-25KW25IN.js → cline-JKEAYWVR.js} +6 -6
  104. package/dist/cline-JKEAYWVR.js.map +1 -0
  105. package/dist/{codebuddy-ZNYQACMF.js → codebuddy-EB6EYPC3.js} +7 -7
  106. package/dist/codebuddy-EB6EYPC3.js.map +1 -0
  107. package/dist/{codebuff-VR6JUDIY.js → codebuff-5RSXFU6G.js} +6 -6
  108. package/dist/codebuff-5RSXFU6G.js.map +1 -0
  109. package/dist/{codebuff-ETYT5UBL.js → codebuff-6KWBW6CT.js} +4 -4
  110. package/dist/codebuff-6KWBW6CT.js.map +1 -0
  111. package/dist/{codex-CPNKTXG3.js → codex-ART46CDD.js} +9 -9
  112. package/dist/codex-ART46CDD.js.map +1 -0
  113. package/dist/{codex-YAORPCOD.js → codex-DKBAAUCO.js} +4 -4
  114. package/dist/codex-DKBAAUCO.js.map +1 -0
  115. package/dist/{continue-WU2IB5KS.js → continue-JHZCMSPH.js} +8 -8
  116. package/dist/continue-JHZCMSPH.js.map +1 -0
  117. package/dist/{copilot-cli-MZTAWMPW.js → copilot-cli-CLBJACQ5.js} +4 -4
  118. package/dist/copilot-cli-CLBJACQ5.js.map +1 -0
  119. package/dist/{copilot-cli-PAP377OM.js → copilot-cli-QVAU5CFM.js} +7 -7
  120. package/dist/copilot-cli-QVAU5CFM.js.map +1 -0
  121. package/dist/{crush-3AVQA4YU.js → crush-7TORBYUL.js} +7 -7
  122. package/dist/crush-7TORBYUL.js.map +1 -0
  123. package/dist/{crush-QBXLNN7T.js → crush-A5C5USRL.js} +4 -4
  124. package/dist/crush-A5C5USRL.js.map +1 -0
  125. package/dist/{cursor-DIW43TRZ.js → cursor-D5SWDVSW.js} +3 -3
  126. package/dist/cursor-D5SWDVSW.js.map +1 -0
  127. package/dist/cursor-W7I4QUFO.js +22 -0
  128. package/dist/{detect-6V4LC3MA.js → detect-JHSA3G3U.js} +4 -4
  129. package/dist/detect-JHSA3G3U.js.map +1 -0
  130. package/dist/{devin-QMEM3OFA.js → devin-SSR7S4WX.js} +7 -7
  131. package/dist/devin-SSR7S4WX.js.map +1 -0
  132. package/dist/{doctor-2YDUVSAU.js → doctor-CQJ7TZPA.js} +26 -26
  133. package/dist/doctor-CQJ7TZPA.js.map +1 -0
  134. package/dist/{droid-MOKV53J4.js → droid-45PJ7JGF.js} +7 -7
  135. package/dist/droid-45PJ7JGF.js.map +1 -0
  136. package/dist/{droid-U3ZBLQFO.js → droid-PFQ2PZSF.js} +4 -4
  137. package/dist/droid-PFQ2PZSF.js.map +1 -0
  138. package/dist/{gemini-cli-47ZHCOZR.js → gemini-cli-24PFDK7D.js} +8 -8
  139. package/dist/gemini-cli-24PFDK7D.js.map +1 -0
  140. package/dist/{gemini-cli-NMVVBO3K.js → gemini-cli-Y6RJMU24.js} +4 -4
  141. package/dist/gemini-cli-Y6RJMU24.js.map +1 -0
  142. package/dist/{goose-64V46Y2W.js → goose-K2HKUTBK.js} +4 -4
  143. package/dist/goose-K2HKUTBK.js.map +1 -0
  144. package/dist/{goose-4EI5MYTI.js → goose-U5D3LCPC.js} +9 -9
  145. package/dist/goose-U5D3LCPC.js.map +1 -0
  146. package/dist/{grok-cli-QYQPDSVB.js → grok-cli-L2MHAPBY.js} +7 -7
  147. package/dist/grok-cli-L2MHAPBY.js.map +1 -0
  148. package/dist/{hermes-F75OSK3Y.js → hermes-2S5JUTTJ.js} +7 -7
  149. package/dist/hermes-2S5JUTTJ.js.map +1 -0
  150. package/dist/{hermes-F3EGTK6N.js → hermes-MF3NX4ZY.js} +4 -4
  151. package/dist/hermes-MF3NX4ZY.js.map +1 -0
  152. package/dist/{hook-OEVRDMXD.js → hook-VHICXHXL.js} +16 -16
  153. package/dist/hook-VHICXHXL.js.map +1 -0
  154. package/dist/index.js +5 -5
  155. package/dist/{install-5NMCUDG5.js → install-WLENR4KF.js} +192 -28
  156. package/dist/install-WLENR4KF.js.map +1 -0
  157. package/dist/{jetbrains-copilot-ZGIWI6YV.js → jetbrains-copilot-Z4FC3RM3.js} +6 -6
  158. package/dist/jetbrains-copilot-Z4FC3RM3.js.map +1 -0
  159. package/dist/{junie-DIFN2P22.js → junie-ULGJJIHB.js} +6 -6
  160. package/dist/junie-ULGJJIHB.js.map +1 -0
  161. package/dist/{kilo-SW7BH6EG.js → kilo-SMHPOHJ5.js} +4 -4
  162. package/dist/kilo-SMHPOHJ5.js.map +1 -0
  163. package/dist/{kilo-EMZJBEBB.js → kilo-WWIJOVWD.js} +8 -8
  164. package/dist/kilo-WWIJOVWD.js.map +1 -0
  165. package/dist/{kilo-cli-S3GXBPAE.js → kilo-cli-QKE2EQLS.js} +8 -8
  166. package/dist/kilo-cli-QKE2EQLS.js.map +1 -0
  167. package/dist/{kilo-cli-ZF272ZHN.js → kilo-cli-T2SRRRJS.js} +5 -5
  168. package/dist/kilo-cli-T2SRRRJS.js.map +1 -0
  169. package/dist/{kimi-IQJOIY6B.js → kimi-JMUFTVSF.js} +7 -7
  170. package/dist/kimi-JMUFTVSF.js.map +1 -0
  171. package/dist/{kimi-5FHEXGZD.js → kimi-MSIDEMCI.js} +4 -4
  172. package/dist/kimi-MSIDEMCI.js.map +1 -0
  173. package/dist/{kiro-WGOI5CGT.js → kiro-NYRRBIKW.js} +4 -4
  174. package/dist/kiro-NYRRBIKW.js.map +1 -0
  175. package/dist/{kiro-BYX4HEAJ.js → kiro-UWUCRKR3.js} +7 -7
  176. package/dist/kiro-UWUCRKR3.js.map +1 -0
  177. package/dist/{leaderboard-XEKS7B3H.js → leaderboard-NJWKGMXP.js} +7 -7
  178. package/dist/leaderboard-NJWKGMXP.js.map +1 -0
  179. package/dist/{mimo-code-7R53QDHB.js → mimo-code-BPNYYIVM.js} +7 -7
  180. package/dist/mimo-code-BPNYYIVM.js.map +1 -0
  181. package/dist/{mistral-vibe-LHJ55FSB.js → mistral-vibe-LT3DAJ3L.js} +6 -6
  182. package/dist/mistral-vibe-LT3DAJ3L.js.map +1 -0
  183. package/dist/{mux-XM6AP35L.js → mux-7PIJ7HUQ.js} +4 -4
  184. package/dist/mux-7PIJ7HUQ.js.map +1 -0
  185. package/dist/{mux-NYCNGL43.js → mux-AHNUAY5Z.js} +6 -6
  186. package/dist/mux-AHNUAY5Z.js.map +1 -0
  187. package/dist/{nemoclaw-WSIPSE7U.js → nemoclaw-RE5RZASZ.js} +7 -7
  188. package/dist/nemoclaw-RE5RZASZ.js.map +1 -0
  189. package/dist/{omp-562NK5BJ.js → omp-D2EXEPH7.js} +7 -7
  190. package/dist/omp-D2EXEPH7.js.map +1 -0
  191. package/dist/{open-interpreter-I2CNOEXY.js → open-interpreter-SSGBEUKX.js} +6 -6
  192. package/dist/open-interpreter-SSGBEUKX.js.map +1 -0
  193. package/dist/openclaw-IJ33K45M.js +17 -0
  194. package/dist/{openclaw-5EQFGOWL.js → openclaw-KAFTNLR2.js} +4 -4
  195. package/dist/openclaw-KAFTNLR2.js.map +1 -0
  196. package/dist/{opencode-YS4WX2E2.js → opencode-YKUKZY3J.js} +7 -7
  197. package/dist/opencode-YKUKZY3J.js.map +1 -0
  198. package/dist/{opencode-QGP4ALQY.js → opencode-Z65JYILL.js} +4 -4
  199. package/dist/opencode-Z65JYILL.js.map +1 -0
  200. package/dist/{openhands-QMYIKNOS.js → openhands-SEZMCUC3.js} +7 -7
  201. package/dist/openhands-SEZMCUC3.js.map +1 -0
  202. package/dist/{package-G25GVTH2.js → package-JECVQEFT.js} +15 -15
  203. package/dist/package-JECVQEFT.js.map +1 -0
  204. package/dist/{pi-GGDQREVG.js → pi-DLKCPOJE.js} +4 -4
  205. package/dist/pi-DLKCPOJE.js.map +1 -0
  206. package/dist/{pi-644FIN3A.js → pi-YPYV2ULH.js} +6 -6
  207. package/dist/pi-YPYV2ULH.js.map +1 -0
  208. package/dist/{qwen-code-GQILBJ5B.js → qwen-code-26CSFDX6.js} +4 -4
  209. package/dist/qwen-code-26CSFDX6.js.map +1 -0
  210. package/dist/{qwen-code-STDMX7EM.js → qwen-code-ZHCLCYMC.js} +9 -9
  211. package/dist/qwen-code-ZHCLCYMC.js.map +1 -0
  212. package/dist/{roo-code-DLPIHHQ6.js → roo-code-7F4HYB34.js} +6 -6
  213. package/dist/roo-code-7F4HYB34.js.map +1 -0
  214. package/dist/{roo-code-SUWI4BBN.js → roo-code-HSAE2CJU.js} +4 -4
  215. package/dist/roo-code-HSAE2CJU.js.map +1 -0
  216. package/dist/runtime/index.js +14 -14
  217. package/dist/sdk/index.js +6 -6
  218. package/dist/sdk/index.js.map +1 -1
  219. package/dist/sdk/test.js +11 -11
  220. package/dist/{serve-XTMIUHKK.js → serve-LYSBH43G.js} +16 -16
  221. package/dist/serve-LYSBH43G.js.map +1 -0
  222. package/dist/{status-VJAGO4Z7.js → status-PHKKGEW5.js} +11 -11
  223. package/dist/status-PHKKGEW5.js.map +1 -0
  224. package/dist/{statusline-EY2E2UGF.js → statusline-ZDD4OZ4F.js} +15 -15
  225. package/dist/statusline-ZDD4OZ4F.js.map +1 -0
  226. package/dist/{synthetic-6FRA7P5Q.js → synthetic-LUT6V6SD.js} +4 -4
  227. package/dist/synthetic-LUT6V6SD.js.map +1 -0
  228. package/dist/{telemetry-OLZQBADT.js → telemetry-HDGMI2BK.js} +10 -10
  229. package/dist/telemetry-HDGMI2BK.js.map +1 -0
  230. package/dist/{trae-CPPYASR2.js → trae-SIQI3C66.js} +4 -4
  231. package/dist/trae-SIQI3C66.js.map +1 -0
  232. package/dist/{trae-UOYD6JZZ.js → trae-Y67HSDOW.js} +6 -6
  233. package/dist/trae-Y67HSDOW.js.map +1 -0
  234. package/dist/{uninstall-AZEUPAND.js → uninstall-RWO2GM2I.js} +21 -21
  235. package/dist/uninstall-RWO2GM2I.js.map +1 -0
  236. package/dist/{upgrade-CAUUHSSC.js → upgrade-YJCXNUEE.js} +21 -21
  237. package/dist/upgrade-YJCXNUEE.js.map +1 -0
  238. package/dist/{usage-3KHZ4RYZ.js → usage-IWO4RQN6.js} +4 -4
  239. package/dist/usage-IWO4RQN6.js.map +1 -0
  240. package/dist/{usage-event-TZWOZPRJ.js → usage-event-AFFKCLHE.js} +15 -15
  241. package/dist/usage-event-AFFKCLHE.js.map +1 -0
  242. package/dist/{vscode-copilot-NIMH2DGU.js → vscode-copilot-5CI5B3X6.js} +7 -7
  243. package/dist/vscode-copilot-5CI5B3X6.js.map +1 -0
  244. package/dist/{warp-NRBBJQR2.js → warp-5YBSP7FP.js} +4 -4
  245. package/dist/warp-5YBSP7FP.js.map +1 -0
  246. package/dist/{warp-QYJGKURM.js → warp-INAKVGBV.js} +6 -6
  247. package/dist/warp-INAKVGBV.js.map +1 -0
  248. package/dist/{windsurf-75LLZ37C.js → windsurf-4HM57QAY.js} +6 -6
  249. package/dist/windsurf-4HM57QAY.js.map +1 -0
  250. package/dist/{zed-XJFOOKCO.js → zed-XXCNYOIN.js} +4 -4
  251. package/dist/zed-XXCNYOIN.js.map +1 -0
  252. package/dist/{zed-HKAZXEJW.js → zed-YN5X37PQ.js} +7 -7
  253. package/dist/zed-YN5X37PQ.js.map +1 -0
  254. package/package.json +92 -88
  255. package/dist/action-Q7GGO4PA.js.map +0 -1
  256. package/dist/amazon-q-ETMAGY3D.js.map +0 -1
  257. package/dist/amp-67BZONGF.js.map +0 -1
  258. package/dist/amp-BQZOL5GR.js.map +0 -1
  259. package/dist/antigravity-EA4L225L.js.map +0 -1
  260. package/dist/antigravity-VXLDLTO7.js +0 -18
  261. package/dist/antigravity-cli-B2HXZFYQ.js.map +0 -1
  262. package/dist/antigravity-cli-OM6SC3PE.js.map +0 -1
  263. package/dist/chunk-2Y2MZRLP.js.map +0 -1
  264. package/dist/chunk-3NH2ARIS.js.map +0 -1
  265. package/dist/chunk-4NHXLXSD.js.map +0 -1
  266. package/dist/chunk-5IOTP7LQ.js.map +0 -1
  267. package/dist/chunk-6TF7MHG5.js.map +0 -1
  268. package/dist/chunk-6WZODR3Z.js.map +0 -1
  269. package/dist/chunk-7F5KHLEP.js.map +0 -1
  270. package/dist/chunk-APZDTY76.js.map +0 -1
  271. package/dist/chunk-BEFVJ2OE.js.map +0 -1
  272. package/dist/chunk-D4ELPBB5.js.map +0 -1
  273. package/dist/chunk-FBJQGRET.js.map +0 -1
  274. package/dist/chunk-FJCUKXGX.js.map +0 -1
  275. package/dist/chunk-GZGLCCEE.js.map +0 -1
  276. package/dist/chunk-H33M77DD.js.map +0 -1
  277. package/dist/chunk-H53QZQJI.js.map +0 -1
  278. package/dist/chunk-I5UXHIDT.js.map +0 -1
  279. package/dist/chunk-ISEJWBFF.js.map +0 -1
  280. package/dist/chunk-IVAWP6HH.js.map +0 -1
  281. package/dist/chunk-JKKU2WKG.js.map +0 -1
  282. package/dist/chunk-KHO5WNTP.js.map +0 -1
  283. package/dist/chunk-MGTDQLJJ.js.map +0 -1
  284. package/dist/chunk-MQPNU2CY.js.map +0 -1
  285. package/dist/chunk-NBYKLUF6.js.map +0 -1
  286. package/dist/chunk-NLE2J5P4.js.map +0 -1
  287. package/dist/chunk-O7SDRBVB.js.map +0 -1
  288. package/dist/chunk-OP4KBXUO.js.map +0 -1
  289. package/dist/chunk-OPXAP3AC.js.map +0 -1
  290. package/dist/chunk-PAPMUAR5.js.map +0 -1
  291. package/dist/chunk-PW42ZXCB.js.map +0 -1
  292. package/dist/chunk-RK6VBLXP.js.map +0 -1
  293. package/dist/chunk-UM5S7DKK.js.map +0 -1
  294. package/dist/chunk-UMQ6NBQR.js.map +0 -1
  295. package/dist/chunk-XC5SJ35F.js.map +0 -1
  296. package/dist/chunk-XD7MY6HB.js.map +0 -1
  297. package/dist/chunk-YPAXJ7EW.js.map +0 -1
  298. package/dist/chunk-YT43MUSJ.js.map +0 -1
  299. package/dist/chunk-Z2MRSS2I.js.map +0 -1
  300. package/dist/claude-code-GRWO6XBZ.js.map +0 -1
  301. package/dist/claude-code-NMRKTAP7.js.map +0 -1
  302. package/dist/cline-25KW25IN.js.map +0 -1
  303. package/dist/codebuddy-ZNYQACMF.js.map +0 -1
  304. package/dist/codebuff-ETYT5UBL.js.map +0 -1
  305. package/dist/codebuff-VR6JUDIY.js.map +0 -1
  306. package/dist/codex-CPNKTXG3.js.map +0 -1
  307. package/dist/codex-YAORPCOD.js.map +0 -1
  308. package/dist/continue-WU2IB5KS.js.map +0 -1
  309. package/dist/copilot-cli-MZTAWMPW.js.map +0 -1
  310. package/dist/copilot-cli-PAP377OM.js.map +0 -1
  311. package/dist/crush-3AVQA4YU.js.map +0 -1
  312. package/dist/crush-QBXLNN7T.js.map +0 -1
  313. package/dist/cursor-DIW43TRZ.js.map +0 -1
  314. package/dist/cursor-GSLUET3V.js +0 -22
  315. package/dist/detect-6V4LC3MA.js.map +0 -1
  316. package/dist/devin-QMEM3OFA.js.map +0 -1
  317. package/dist/doctor-2YDUVSAU.js.map +0 -1
  318. package/dist/droid-MOKV53J4.js.map +0 -1
  319. package/dist/droid-U3ZBLQFO.js.map +0 -1
  320. package/dist/gemini-cli-47ZHCOZR.js.map +0 -1
  321. package/dist/gemini-cli-NMVVBO3K.js.map +0 -1
  322. package/dist/goose-4EI5MYTI.js.map +0 -1
  323. package/dist/goose-64V46Y2W.js.map +0 -1
  324. package/dist/grok-cli-QYQPDSVB.js.map +0 -1
  325. package/dist/hermes-F3EGTK6N.js.map +0 -1
  326. package/dist/hermes-F75OSK3Y.js.map +0 -1
  327. package/dist/hook-OEVRDMXD.js.map +0 -1
  328. package/dist/install-5NMCUDG5.js.map +0 -1
  329. package/dist/jetbrains-copilot-ZGIWI6YV.js.map +0 -1
  330. package/dist/junie-DIFN2P22.js.map +0 -1
  331. package/dist/kilo-EMZJBEBB.js.map +0 -1
  332. package/dist/kilo-SW7BH6EG.js.map +0 -1
  333. package/dist/kilo-cli-S3GXBPAE.js.map +0 -1
  334. package/dist/kilo-cli-ZF272ZHN.js.map +0 -1
  335. package/dist/kimi-5FHEXGZD.js.map +0 -1
  336. package/dist/kimi-IQJOIY6B.js.map +0 -1
  337. package/dist/kiro-BYX4HEAJ.js.map +0 -1
  338. package/dist/kiro-WGOI5CGT.js.map +0 -1
  339. package/dist/leaderboard-XEKS7B3H.js.map +0 -1
  340. package/dist/mimo-code-7R53QDHB.js.map +0 -1
  341. package/dist/mistral-vibe-LHJ55FSB.js.map +0 -1
  342. package/dist/mux-NYCNGL43.js.map +0 -1
  343. package/dist/mux-XM6AP35L.js.map +0 -1
  344. package/dist/nemoclaw-WSIPSE7U.js.map +0 -1
  345. package/dist/omp-562NK5BJ.js.map +0 -1
  346. package/dist/open-interpreter-I2CNOEXY.js.map +0 -1
  347. package/dist/openclaw-5EQFGOWL.js.map +0 -1
  348. package/dist/openclaw-7EYBQS4R.js +0 -17
  349. package/dist/opencode-QGP4ALQY.js.map +0 -1
  350. package/dist/opencode-YS4WX2E2.js.map +0 -1
  351. package/dist/openhands-QMYIKNOS.js.map +0 -1
  352. package/dist/package-G25GVTH2.js.map +0 -1
  353. package/dist/pi-644FIN3A.js.map +0 -1
  354. package/dist/pi-GGDQREVG.js.map +0 -1
  355. package/dist/qwen-code-GQILBJ5B.js.map +0 -1
  356. package/dist/qwen-code-STDMX7EM.js.map +0 -1
  357. package/dist/roo-code-DLPIHHQ6.js.map +0 -1
  358. package/dist/roo-code-SUWI4BBN.js.map +0 -1
  359. package/dist/serve-XTMIUHKK.js.map +0 -1
  360. package/dist/status-VJAGO4Z7.js.map +0 -1
  361. package/dist/statusline-EY2E2UGF.js.map +0 -1
  362. package/dist/synthetic-6FRA7P5Q.js.map +0 -1
  363. package/dist/telemetry-OLZQBADT.js.map +0 -1
  364. package/dist/trae-CPPYASR2.js.map +0 -1
  365. package/dist/trae-UOYD6JZZ.js.map +0 -1
  366. package/dist/uninstall-AZEUPAND.js.map +0 -1
  367. package/dist/upgrade-CAUUHSSC.js.map +0 -1
  368. package/dist/usage-3KHZ4RYZ.js.map +0 -1
  369. package/dist/usage-event-TZWOZPRJ.js.map +0 -1
  370. package/dist/vscode-copilot-NIMH2DGU.js.map +0 -1
  371. package/dist/warp-NRBBJQR2.js.map +0 -1
  372. package/dist/warp-QYJGKURM.js.map +0 -1
  373. package/dist/windsurf-75LLZ37C.js.map +0 -1
  374. package/dist/zed-HKAZXEJW.js.map +0 -1
  375. package/dist/zed-XJFOOKCO.js.map +0 -1
  376. /package/dist/{antigravity-VXLDLTO7.js.map → antigravity-TWIWXTQH.js.map} +0 -0
  377. /package/dist/{cursor-GSLUET3V.js.map → cursor-W7I4QUFO.js.map} +0 -0
  378. /package/dist/{openclaw-7EYBQS4R.js.map → openclaw-IJ33K45M.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/adapters/kilo/index.ts"],"sourcesContent":["/**\n * adapters/kilo — Kilo Code (VS Code extension) platform adapter.\n *\n * Kilo Code (`kilocode.kilo-code`) is a Roo/Cline-fork VS Code extension that\n * as of vsix 7.x was REBUILT on the Kilo CLI server and shares ONE backend with\n * the Kilo CLI (adapter id \"kilo-cli\"). Paradigm: **ts-plugin** (same plugin\n * layer the CLI uses).\n *\n * MCP config (vsix 7.3.28 — delegated to the kilo backend):\n * - user scope → ~/.config/kilo/kilo.json (XDG: $XDG_CONFIG_HOME/kilo)\n * - project scope → <projectDir>/.kilo/kilo.json\n * Both are JSON, root key **\"mcp\"**, entry shape\n * { type:\"local\", command:[exe,...args], environment:{} } (array command).\n * The legacy globalStorage `<vscodeUserDir>/globalStorage/kilocode.kilo-code/\n * settings/mcp_settings.json` (root \"mcpServers\") is MIGRATION-ONLY in 7.3.28\n * and is no longer the live write target — detectInstalled() still probes it so\n * an older install is recognized, but we install into kilo.json.\n *\n * SHARED BACKEND NOTE: kilo.json (VS Code ext) AND kilo.jsonc (CLI) are MERGED\n * by the ONE shared backend at user / project-root / .kilo/ levels — 3-way merge\n * verified live. The two platform IDs remain distinct for collision tracking, but\n * they share the same config dir and the backend dedupes across both files.\n *\n * Env interpolation: {env:VARIABLE_NAME} is documented by the pi/kilo backend.\n * We still resolve env refs to literals at install time (the conservative path,\n * consistent with kilo-cli) to avoid any version dependency on the interpolation\n * feature being present at runtime.\n *\n * Hooks (ts-plugin — same layer as kilo-cli):\n * The plugins doc banner reads \"applies to current VSCode extension & CLI\".\n * Plugin dirs: project → <projectDir>/.kilo/plugin/, user → ~/.config/kilo/plugin/.\n * Auto-discovery applies (as in the CLI ≥ 7.3.16), and we ALSO register the\n * module path in kilo.json's `plugin` array for explicit load (both loaded).\n * Event names: same as kilo-cli (\"tool.execute.before\", \"tool.execute.after\",\n * \"experimental.chat.system.transform\"). Bridge shims to \"kilo\" (not \"kilo-cli\").\n *\n * Content surfaces:\n * Commands → .kilo/commands (project) / ~/.config/kilo/commands (user)\n * Skills → .kilo/skills/<name>/SKILL.md (project) / ~/.kilo/skills (user)\n * Subagents → .kilo/agents (project) / ~/.config/kilo/agents (user)\n */\n\nimport { existsSync } from \"node:fs\";\nimport { homedir, platform as osPlatform } from \"node:os\";\nimport { join } from \"node:path\";\n\nimport { BaseAdapter } from \"../base.js\";\nimport type {\n Adapter,\n GeneratedPluginFile,\n HookReply,\n InstallContext,\n MemoryTarget,\n NormalizedEvent,\n} from \"../spi.js\";\nimport type {\n ChangeRecord,\n CommandDef,\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 { xdgConfigHome } from \"../../core/host-paths.js\";\nimport {\n buildWrappedStdio,\n} from \"../../core/spawn.js\";\nimport { renderOpenCodeSubagentMd, renderSkillMd } from \"../claude-code/render.js\";\n\nconst HOST: PlatformId = \"kilo\";\n/** vsix 7.3.28 root key in kilo.json (delegated kilo backend). */\nconst MCP_ROOT_KEY = \"mcp\";\n/** kilo.json array of plugin module paths (also supports auto-discovery). */\nconst PLUGIN_ARRAY_KEY = \"plugin\";\n/** Live config filename for the VS Code ext (DISTINCT from the CLI's kilo.jsonc). */\nconst CONFIG_FILE = \"kilo.json\";\n\n/** Kilo Code extension id → its (legacy, migration-only) VS Code globalStorage folder. */\nconst KILO_EXTENSION_ID = \"kilocode.kilo-code\";\n/**\n * Legacy globalStorage MCP settings filenames (MIGRATION-ONLY in 7.3.28). The\n * Cline-family alternative is probed during detection so an older install is\n * still recognized; we no longer WRITE there.\n */\nconst LEGACY_MCP_SETTINGS_FILE = \"mcp_settings.json\";\nconst LEGACY_CLINE_SETTINGS_FILE = \"cline_mcp_settings.json\";\n\n/**\n * Canonical → Kilo (shared ts-plugin layer) event name map. Identical to the\n * kilo-cli mapping: the extension and CLI share the same plugin event model.\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 kilo.json accepts under `mcp` (the delegated\n * kilo backend). Local (stdio) servers use a SINGLE array command that folds the\n * executable and its args together; env lives under `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 headers?: Record<string, string>;\n}\n\n/**\n * Resolve the kilo backend user config dir: `$XDG_CONFIG_HOME/kilo` when set,\n * else `~/.config/kilo`. This is the SAME backend dir kilo-cli uses (the two\n * differ only by filename — kilo.json here vs kilo.jsonc for the CLI).\n */\nfunction kiloConfigDir(): string {\n return join(xdgConfigHome(), \"kilo\");\n}\n\n/**\n * Resolve the cross-OS VS Code per-user data directory (the \"User\" folder that\n * contains `globalStorage`) — used ONLY to probe the legacy migration-only MCP\n * settings file during detection. See module header for the per-platform mapping.\n */\nfunction vscodeUserDir(): string {\n const home = homedir();\n switch (osPlatform()) {\n case \"darwin\":\n return join(home, \"Library\", \"Application Support\", \"Code\", \"User\");\n case \"win32\": {\n const appData = process.env.APPDATA ?? join(home, \"AppData\", \"Roaming\");\n return join(appData, \"Code\", \"User\");\n }\n default:\n // Linux / other POSIX: XDG-style config dir.\n return join(home, \".config\", \"Code\", \"User\");\n }\n}\n\nexport class KiloAdapter extends BaseAdapter implements Adapter {\n readonly id: PlatformId = HOST;\n readonly name = \"Kilo Code\";\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 // Kilo Code 7.x shares the ts-plugin layer with the Kilo CLI — same events.\n preToolUse: true,\n postToolUse: true,\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 // Decision-capable permission gate (permission.ask) — mutates output.status.\n permissionRequest: true,\n canModifyArgs: true,\n canModifyOutput: true,\n canInjectSessionContext: true,\n // Kilo Code registers stdio, SSE, and Streamable HTTP MCP servers.\n transports: [\"stdio\", \"sse\", \"http\"],\n // Content surfaces: commands, skills (since 7.x rebuild), and subagents.\n supportsCommands: true,\n supportsSkills: true,\n supportsSubagents: true,\n };\n\n // ── Detection ────────────────────────────────────────────────────────────\n\n detectInstalled(projectDir: string): DetectedPlatform {\n const userConfig = this.userConfigPath();\n const userBackendDir = kiloConfigDir();\n // Probe the legacy (migration-only) globalStorage MCP settings too so an\n // older install is still recognized; we never WRITE there anymore.\n const legacyExtDir = join(vscodeUserDir(), \"globalStorage\", KILO_EXTENSION_ID);\n const legacySettings = join(legacyExtDir, \"settings\", LEGACY_MCP_SETTINGS_FILE);\n const legacyClineSettings = join(\n legacyExtDir,\n \"settings\",\n LEGACY_CLINE_SETTINGS_FILE,\n );\n const projectConfig = join(projectDir, \".kilo\", CONFIG_FILE);\n\n const userMatch =\n existsSync(userConfig) ||\n existsSync(userBackendDir) ||\n existsSync(legacySettings) ||\n existsSync(legacyClineSettings) ||\n existsSync(legacyExtDir);\n const projectMatch = existsSync(projectConfig);\n const installed = userMatch || projectMatch;\n\n // Prefer the user scope/path when present; otherwise surface the project one.\n const scope = userMatch || !projectMatch ? \"user\" : \"project\";\n const configPath = scope === \"user\" ? userConfig : projectConfig;\n const reason = installed\n ? userMatch\n ? `found Kilo Code config under ${userBackendDir}`\n : `found Kilo Code project config at ${projectConfig}`\n : `no Kilo Code config at ${userBackendDir} or ${projectConfig}`;\n\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,\n confidence: installed ? \"high\" : \"low\",\n };\n }\n\n // ── Native paths ─────────────────────────────────────────────────────────\n\n /** Absolute path to the user-scope kilo.json (kilo backend, XDG dir). */\n private userConfigPath(): string {\n return join(kiloConfigDir(), CONFIG_FILE);\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 // kilo-cli — 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 /**\n * MCP config dir. Note the project surface is `.kilo/` (kilo backend), NOT the\n * extension's `.kilocode/` content tree (which still hosts commands/subagents).\n */\n getConfigDir(ctx: InstallContext): string {\n return ctx.scope === \"project\"\n ? join(ctx.projectDir, \".kilo\")\n : kiloConfigDir();\n }\n\n getServerConfigPath(ctx: InstallContext): string {\n return ctx.scope === \"project\"\n ? join(ctx.projectDir, \".kilo\", CONFIG_FILE)\n : this.userConfigPath();\n }\n\n /**\n * For ts-plugin hosts the \"hook config path\" is the generated plugin FILE.\n * The backend also supports auto-discovery from the plugin dir, but we ALSO\n * register the path in kilo.json's `plugin` array for explicit load (idempotent).\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(kiloConfigDir(), \"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\"\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 /**\n * Render a normalized ServerDef into kilo.json's native `mcp` entry. Local\n * (stdio) servers fold the executable + args into a SINGLE `command` array and\n * carry env under `environment`; remote servers use a `type:\"remote\"` URL entry.\n */\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 // Resolve ${env:VAR} to literals at install time (conservative; consistent\n // with kilo-cli even though {env:VARIABLE_NAME} is documented).\n const argv: string[] = [\n resolveEnvRefsDeep(command),\n ...resolveEnvRefsDeep(args),\n ];\n const entry: KiloLocalServer = {\n type: \"local\",\n command: argv,\n environment: this.renderEnv(server.env) ?? {},\n };\n return entry;\n }\n\n // sse / http (and any other remote transport) — kilo registers a remote URL.\n const entry: KiloRemoteServer = {\n type: \"remote\",\n url: resolveEnvRefsDeep(server.url ?? \"\"),\n };\n const headers = this.renderEnv(server.headers);\n if (headers) entry.headers = headers;\n return entry;\n }\n\n /**\n * Render env/header values. Resolve `${env:VAR}` references to literals at\n * install time for consistency with kilo-cli.\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\" },\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 changes.push(\n this.writeManagedFile(\n file.path,\n file.contents,\n ctx.dryRun,\n `kilo plugin module (${this.hookDetail(ctx)})`,\n file.executable,\n ),\n );\n }\n\n // 2. Register the module path in kilo.json's `plugin` array. The backend also\n // auto-discovers from the plugin dir, but explicit registration is idempotent\n // and ensures loading even if auto-discovery is disabled.\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\".\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.json's `plugin` array.\n changes.push(this.removePluginFromArray(configPath, pluginPath, ctx.dryRun));\n\n // 2. Remove the plugin module on disk.\n changes.push(\n this.removeManagedFile(pluginPath, ctx.dryRun, \"kilo plugin module\", \"no kilo plugin module present\"),\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.json's top-level `plugin` array (idempotent). */\n private upsertPluginInArray(\n configPath: string,\n modulePath: string,\n dryRun: boolean,\n ): ChangeRecord {\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.json's `plugin` array. */\n private removePluginFromArray(\n configPath: string,\n modulePath: string,\n dryRun: boolean,\n ): ChangeRecord {\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 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 // ── ts-plugin synthesis ────────────────────────────────────────────────\n\n /**\n * Build ONE self-contained ESM plugin module for Kilo Code (the VS Code\n * extension). Structurally identical to the kilo-cli plugin but bridges to\n * \"kilo\" (not \"kilo-cli\") so the dispatcher routes to the correct adapter.\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 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 Code (VS Code extension) 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 extension loads it via the\n * plugin dir auto-discovery and/or the \"plugin\" array in kilo.json.\n */\nimport { execFileSync, execSync } from \"node:child_process\";\n\n${renderBridgePrelude({\n homeBin: ctx.homeBinPath,\n connectorId: ctx.connector.id,\n hookSlug: \"kilo\",\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 extension has no real SessionStart hook; the system-prompt transform is\n // the verified injection point (mirrors OpenCode and kilo-cli).\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 return { ...base, source: \"startup\" } satisfies SessionStartEvent;\n }\n }\n\n // ── Runtime: normalized response → reply the generated bridge parses ───\n\n /**\n * OUR generated bridge consumes this stdout directly. 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 // ── Content surfaces: commands / skills / subagents ───────────────────\n // CONTENT-ONLY: pure native-file writers. No runtime dispatch, no home-bin\n // pointer, no telemetry wrap. Each method is idempotent (byte-identical →\n // skip) via BaseAdapter.writeContentFile and reversible via removeContentFile.\n // Honors platforms[\"kilo\"] per-surface false to skip.\n //\n // NOTE on dirs: the CURRENT kilo backend (7.x, shared with kilo-cli) reads\n // commands, subagents, and skills from the .kilo/ tree (project) + the XDG\n // backend config dir ~/.config/kilo (user) — NOT the .kilocode/ VS Code\n // extension legacy tree (which only carries legacy workflows). Verified against\n // kilo.ai/docs/customize/{custom-subagents,workflows,skills} (2026-06-16):\n // commands → <projectDir>/.kilo/commands | ~/.config/kilo/commands\n // subagents → <projectDir>/.kilo/agents | ~/.config/kilo/agents\n // skills → <projectDir>/.kilo/skills | ~/.kilo/skills (skills keep the\n // ~/.kilo user root per the docs — surface-specific).\n\n /** Skills root: project → <projectDir>/.kilo/skills; user → ~/.kilo/skills. */\n private skillsRootDir(ctx: InstallContext): string {\n return ctx.scope === \"project\"\n ? join(ctx.projectDir, \".kilo\", \"skills\")\n : join(homedir(), \".kilo\", \"skills\");\n }\n\n /** Commands root: project → <projectDir>/.kilo/commands; user → ~/.config/kilo/commands. */\n private commandsDir(ctx: InstallContext): string {\n return ctx.scope === \"project\"\n ? join(ctx.projectDir, \".kilo\", \"commands\")\n : join(kiloConfigDir(), \"commands\");\n }\n\n /** Subagents root: project → <projectDir>/.kilo/agents; user → ~/.config/kilo/agents. */\n private agentsDir(ctx: InstallContext): string {\n return ctx.scope === \"project\"\n ? join(ctx.projectDir, \".kilo\", \"agents\")\n : join(kiloConfigDir(), \"agents\");\n }\n\n /** Native command file path: <commandsDir>/<name>.md. */\n private commandPath(ctx: InstallContext, name: string): string {\n return join(this.commandsDir(ctx), `${name}.md`);\n }\n\n /** Native skill dir: <skillsRootDir>/<name>. */\n private skillDir(ctx: InstallContext, name: string): string {\n return join(this.skillsRootDir(ctx), name);\n }\n\n /** Native subagent file path: <agentsDir>/<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 kilo\" }];\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 /** Render a command to md+frontmatter (description, argument-hint, mode, model). */\n private renderCommand(cmd: CommandDef): string {\n const frontmatter: Record<string, unknown> = {};\n if (cmd.description !== undefined) frontmatter.description = cmd.description;\n if (cmd.argumentHint !== undefined) frontmatter[\"argument-hint\"] = cmd.argumentHint;\n if (cmd.model !== undefined) frontmatter.model = cmd.model;\n if (cmd.extra) Object.assign(frontmatter, cmd.extra);\n return this.renderFrontmatterMd(frontmatter, cmd.prompt);\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\" }];\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 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\" }];\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 renderOpenCodeSubagentMd(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 // ── Diagnostics ──────────────────────────────────────────────────────────\n\n override getHealthChecks(ctx: InstallContext): readonly HealthCheck[] {\n const mcpPath = 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 const checks: HealthCheck[] = [\n {\n name: `${this.name}: kilo.json present`,\n check: () =>\n existsSync(mcpPath)\n ? { status: \"OK\", detail: mcpPath }\n : { status: \"FAIL\", detail: `not found: ${mcpPath}` },\n },\n {\n // The backend merges kilo.json AND kilo.jsonc at user/project/.kilo/ levels.\n name: `${this.name}: MCP delegated to kilo backend`,\n check: () => ({\n status: \"OK\",\n detail:\n ctx.scope === \"user\"\n ? `using ${CONFIG_FILE} under ${kiloConfigDir()} (merged with kilo.jsonc by shared backend)`\n : `project scope uses .kilo/${CONFIG_FILE} (merged with kilo.jsonc by shared backend)`,\n }),\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> }>(mcpPath);\n const bucket = cfg?.[MCP_ROOT_KEY];\n if (!cfg || !bucket) {\n return { status: \"FAIL\", detail: `no ${MCP_ROOT_KEY} in ${mcpPath}` };\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 ${mcpPath}`,\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>>(mcpPath);\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 ${mcpPath}`,\n };\n },\n },\n ];\n\n // Content-surface checks.\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 /** Read a file, returning undefined on any error (idempotency compare). */\n}\n\nexport const adapter = new KiloAdapter();\nexport default adapter;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA0CA,SAAS,kBAAkB;AAC3B,SAAS,SAAS,YAAY,kBAAkB;AAChD,SAAS,YAAY;AAsCrB,IAAM,OAAmB;AAEzB,IAAM,eAAe;AAErB,IAAM,mBAAmB;AAEzB,IAAM,cAAc;AAGpB,IAAM,oBAAoB;AAM1B,IAAM,2BAA2B;AACjC,IAAM,6BAA6B;AAMnC,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,EA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AAAA,QACN;AAAA,MACF;AAAA,IACF;AAGA,eAAW,OAAO,IAAI,UAAU,UAAU;AACxC,YAAM,IAAI,KAAK,YAAY,KAAK,IAAI,IAAI;AACxC,aAAO,KAAK;AAAA,QACV,MAAM,GAAG,KAAK,IAAI,aAAa,IAAI,IAAI;AAAA,QACvC,OAAO,MACL,WAAW,CAAC,IAAI,EAAE,QAAQ,MAAM,QAAQ,EAAE,IAAI,EAAE,QAAQ,QAAQ,QAAQ,cAAc,CAAC,GAAG;AAAA,MAC9F,CAAC;AAAA,IACH;AACA,eAAW,SAAS,IAAI,UAAU,QAAQ;AACxC,YAAM,IAAI,KAAK,KAAK,SAAS,KAAK,MAAM,IAAI,GAAG,UAAU;AACzD,aAAO,KAAK;AAAA,QACV,MAAM,GAAG,KAAK,IAAI,WAAW,MAAM,IAAI;AAAA,QACvC,OAAO,MACL,WAAW,CAAC,IAAI,EAAE,QAAQ,MAAM,QAAQ,EAAE,IAAI,EAAE,QAAQ,QAAQ,QAAQ,cAAc,CAAC,GAAG;AAAA,MAC9F,CAAC;AAAA,IACH;AACA,eAAW,SAAS,IAAI,UAAU,WAAW;AAC3C,YAAM,IAAI,KAAK,aAAa,KAAK,MAAM,IAAI;AAC3C,aAAO,KAAK;AAAA,QACV,MAAM,GAAG,KAAK,IAAI,cAAc,MAAM,IAAI;AAAA,QAC1C,OAAO,MACL,WAAW,CAAC,IAAI,EAAE,QAAQ,MAAM,QAAQ,EAAE,IAAI,EAAE,QAAQ,QAAQ,QAAQ,cAAc,CAAC,GAAG;AAAA,MAC9F,CAAC;AAAA,IACH;AACA,WAAO;AAAA,EACT;AAAA;AAGF;AAEO,IAAM,UAAU,IAAI,YAAY;AACvC,IAAO,eAAQ;","names":["entry"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/usage/readers/kilo.ts"],"sourcesContent":["/**\n * usage/readers/kilo — Kilo Code (VS Code extension) task-log reader.\n *\n * Faithful port of tokscale sessions/kilocode.rs, which is a one-line wrapper\n * around roocode.rs `parse_roo_kilo_file(path, \"kilocode\")` — Kilo Code shares\n * the EXACT same task-log format as Roo Code, differing only in its VS Code\n * extension id (`kilocode.kilo-code`) and the source label. This is the Kilo\n * VS Code extension usage (distinct from the kilo-cli SQLite reader, platformId\n * \"kilo-cli\", which lands separately).\n *\n * Kilo Code (kilocode.kilo-code) persists per-task logs under its VS Code\n * globalStorage:\n * <vscodeUserDir>/globalStorage/kilocode.kilo-code/tasks/<taskId>/\n * ui_messages.json (the UI message stream — token source)\n * api_conversation_history.json (sibling — model/agent source)\n * The Rust scanner additionally discovers a remote-host server path under\n * ~/.vscode-server/data/User/globalStorage/kilocode.kilo-code/tasks, so we scan\n * both the desktop and server tasks roots that exist.\n *\n * kilo is NOT in paths.ts hostRoots (that per-platform table targets CLIs with\n * ~/.<tool> roots, not VS Code extension globalStorage), so this reader resolves\n * the cross-OS VS Code \"User\" dir itself, mirroring readers/roo-code.ts:\n * - macOS → ~/Library/Application Support/Code/User\n * - Windows → %APPDATA%/Code/User (else ~/AppData/Roaming/Code/User)\n * - Linux → ~/.config/Code/User\n * An AGENT_CONNECTOR_KILO_DIR override (verbatim, non-empty, ~-expanded, resolved\n * against CWD when relative) points directly at a single `tasks` parent when set,\n * matching the env convention in paths.ts hostRoots.\n *\n * Tokens (ui_messages.json): the file is a JSON ARRAY of entries; only entries\n * with type==\"say\" AND say==\"api_req_started\" carry usage. Each such entry's\n * `text` field is a JSON-in-string payload (SAME shape as Roo Code):\n * tokensIn → input\n * tokensOut → output\n * cacheReads → cacheRead\n * cacheWrites → cacheWrite\n * cost (f64) → cost\n * apiProtocol → providerId (preserved verbatim, e.g. \"azure/openai\")\n * reasoning is ALWAYS 0 (Kilo Code does not report it). A malformed text payload,\n * a missing text, or an unparseable `ts` skips just that entry.\n *\n * model / agent (api_conversation_history.json): scan every\n * <environment_details>…</environment_details> block for <model>, <slug>, <name>\n * tags; the LAST <model> wins (default \"unknown\"); agent prefers <slug> then\n * <name> (optional). When the sibling file is absent/unreadable: model \"unknown\",\n * no agent — exactly the Rust read_task_metadata fallback.\n *\n * session id is the taskId — the parent directory name of ui_messages.json\n * (port of extract_session_id), defaulting to \"unknown\". provider from\n * apiProtocol (trimmed, default \"unknown\"). No project attribution (Kilo Code's\n * logs carry no cwd). No dedup — one row per api_req_started event (file\n * isolation is the implicit unique context). Confidence is \"host-reported\"\n * (real host-logged token counts; the design rates this medium qualitatively).\n *\n * Fail-open: no root → []; unreadable/malformed file, entry, or payload → skipped\n * (never throws). Read-only.\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { homedir, platform as osPlatform } from \"node:os\";\nimport { basename, dirname, isAbsolute, join, resolve } from \"node:path\";\n\nimport type { UsageReader, UsageRecord } from \"../types.js\";\nimport { emptyTokens } from \"../aggregate.js\";\nimport { readJsonFile } from \"../jsonl.js\";\nimport { expandHome, walkFiles } from \"../paths.js\";\n\nconst PLATFORM_ID = \"kilo\" as const;\nconst DEFAULT_MODEL = \"unknown\";\nconst DEFAULT_PROVIDER = \"unknown\";\nconst DEFAULT_SESSION = \"unknown\";\n\n/** Kilo Code extension id → its VS Code globalStorage folder. */\nconst KILO_EXTENSION_ID = \"kilocode.kilo-code\";\n\n// ─────────────────────────────────────────────────────────────────────────\n// Storage-root resolution (mirrors readers/roo-code.ts vscodeUserDir + the\n// AGENT_CONNECTOR_<PLATFORM>_DIR env convention in paths.ts hostRoots, plus the\n// remote .vscode-server server path the Rust scanner adds for KiloCode)\n// ─────────────────────────────────────────────────────────────────────────\n\n/** Resolve the cross-OS VS Code per-user \"User\" dir (the globalStorage parent). */\nfunction vscodeUserDir(): string {\n const home = homedir();\n switch (osPlatform()) {\n case \"darwin\":\n return join(home, \"Library\", \"Application Support\", \"Code\", \"User\");\n case \"win32\": {\n const appData = process.env.APPDATA ?? join(home, \"AppData\", \"Roaming\");\n return join(appData, \"Code\", \"User\");\n }\n default:\n return join(home, \".config\", \"Code\", \"User\");\n }\n}\n\n/**\n * The `tasks` roots holding per-task subdirectories. An\n * AGENT_CONNECTOR_KILO_DIR override (verbatim, non-empty, ~-expanded, resolved\n * against CWD when relative) short-circuits to that single root. Otherwise we\n * return the desktop globalStorage tasks dir and the remote-host\n * ~/.vscode-server tasks dir (the two roots the Rust scanner discovers for\n * KiloCode); the caller scans whichever exist.\n */\nfunction tasksRoots(): string[] {\n const raw = process.env.AGENT_CONNECTOR_KILO_DIR;\n if (raw != null && raw.trim() !== \"\") {\n const expanded = expandHome(raw.trim());\n return [isAbsolute(expanded) ? expanded : resolve(expanded)];\n }\n const home = homedir();\n return [\n join(vscodeUserDir(), \"globalStorage\", KILO_EXTENSION_ID, \"tasks\"),\n join(home, \".vscode-server\", \"data\", \"User\", \"globalStorage\", KILO_EXTENSION_ID, \"tasks\"),\n ];\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// Value coercion (ports of utils.rs extract_i64 / extract_f64 / parse_timestamp_str)\n// ─────────────────────────────────────────────────────────────────────────\n\n/** Port of extract_i64: number / numeric-string → integer, else undefined. */\nfunction extractI64(v: unknown): number | undefined {\n if (typeof v === \"number\") {\n if (!Number.isFinite(v)) return undefined;\n return Math.trunc(v);\n }\n if (typeof v === \"string\") {\n const trimmed = v.trim();\n if (!/^[+-]?\\d+$/.test(trimmed)) return undefined; // Rust parses as i64 (integer-only)\n const n = Number(trimmed);\n return Number.isFinite(n) ? Math.trunc(n) : undefined;\n }\n return undefined;\n}\n\n/** A non-negative integer from a payload field (0 on absence/garbage, clamped ≥ 0). */\nfunction tokenField(v: unknown): number {\n const n = extractI64(v);\n return n === undefined ? 0 : Math.max(0, n);\n}\n\n/** Port of extract_f64: number / numeric-string → f64, else undefined. */\nfunction extractF64(v: unknown): number | undefined {\n if (typeof v === \"number\") return Number.isFinite(v) ? v : undefined;\n if (typeof v === \"string\") {\n const n = Number(v.trim());\n return Number.isFinite(n) ? n : undefined;\n }\n return undefined;\n}\n\n/**\n * Port of utils.rs parse_timestamp_str / parse_entry_timestamp: an RFC3339 string\n * → epoch ms; an integer (string or number) → ms (×1000 when below the 1e12 ms\n * threshold); rejects ≤ 0. Returns null when unusable so the entry is skipped.\n */\nfunction parseEntryTimestamp(v: unknown): number | null {\n let s: string;\n if (typeof v === \"string\") s = v;\n else if (typeof v === \"number\" && Number.isFinite(v)) s = String(Math.trunc(v));\n else return null;\n\n return parseTimestampStr(s);\n}\n\nfunction parseTimestampStr(value: string): number | null {\n const ms = Date.parse(value);\n if (!Number.isNaN(ms)) return ms; // RFC3339 / any Date-parseable form\n\n if (/^[+-]?\\d+$/.test(value.trim())) {\n const numeric = Number(value.trim());\n if (!Number.isFinite(numeric) || numeric <= 0) return null;\n return numeric >= 1_000_000_000_000 ? numeric : numeric * 1000;\n }\n return null;\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// session id (port of extract_session_id)\n// ─────────────────────────────────────────────────────────────────────────\n\n/** Session id = the parent directory (taskId) of ui_messages.json, else \"unknown\". */\nfunction extractSessionId(path: string): string {\n const parent = basename(dirname(path));\n return parent !== \"\" ? parent : DEFAULT_SESSION;\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// model / agent (ports of read_task_metadata / extract_model_and_agent / extract_tag_value)\n// ─────────────────────────────────────────────────────────────────────────\n\ninterface TaskMetadata {\n model: string;\n agent?: string;\n}\n\n/** Read the sibling api_conversation_history.json for model/agent (fail-open). */\nfunction readTaskMetadata(uiMessagesPath: string): TaskMetadata {\n const historyPath = join(dirname(uiMessagesPath), \"api_conversation_history.json\");\n let content: string;\n try {\n content = readFileSync(historyPath, \"utf8\");\n } catch {\n return { model: DEFAULT_MODEL }; // missing/unreadable → (\"unknown\", None)\n }\n return extractModelAndAgent(content);\n}\n\n/**\n * Scan every <environment_details>…</environment_details> block, extracting\n * <model>, <slug>, <name>. The LAST non-empty value of each tag wins (port of the\n * Rust last_* accumulation). model defaults to \"unknown\"; agent prefers slug then\n * name (and is omitted when neither is present).\n */\nfunction extractModelAndAgent(content: string): TaskMetadata {\n const ENV_START = \"<environment_details>\";\n const ENV_END = \"</environment_details>\";\n\n let offset = 0;\n let lastModel: string | undefined;\n let lastSlug: string | undefined;\n let lastName: string | undefined;\n\n for (;;) {\n const startRel = content.indexOf(ENV_START, offset);\n if (startRel < 0) break;\n const startIdx = startRel + ENV_START.length;\n\n const endRel = content.indexOf(ENV_END, startIdx);\n if (endRel < 0) break;\n\n const block = content.slice(startIdx, endRel);\n\n const model = extractTagValue(block, \"model\");\n if (model !== undefined) lastModel = model;\n const slug = extractTagValue(block, \"slug\");\n if (slug !== undefined) lastSlug = slug;\n const name = extractTagValue(block, \"name\");\n if (name !== undefined) lastName = name;\n\n offset = endRel + ENV_END.length;\n }\n\n const agent = lastSlug ?? lastName;\n const result: TaskMetadata = { model: lastModel ?? DEFAULT_MODEL };\n if (agent !== undefined) result.agent = agent;\n return result;\n}\n\n/** First <tag>…</tag> value in `block`, trimmed; undefined when absent or empty. */\nfunction extractTagValue(block: string, tag: string): string | undefined {\n const open = `<${tag}>`;\n const close = `</${tag}>`;\n\n const openIdx = block.indexOf(open);\n if (openIdx < 0) return undefined;\n const start = openIdx + open.length;\n const endRel = block.indexOf(close, start);\n if (endRel < 0) return undefined;\n\n const value = block.slice(start, endRel).trim();\n return value === \"\" ? undefined : value;\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// api_req_started payload (port of parse_api_req_started_payload + provider_from_api_protocol)\n// ─────────────────────────────────────────────────────────────────────────\n\ninterface ApiReqStartedPayload {\n cost: number;\n tokensIn: number;\n tokensOut: number;\n cacheReads: number;\n cacheWrites: number;\n apiProtocol?: string;\n}\n\n/** Parse the JSON-in-string `text` payload of an api_req_started entry. */\nfunction parseApiReqStartedPayload(text: string): ApiReqStartedPayload | undefined {\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch {\n return undefined;\n }\n if (typeof value !== \"object\" || value === null) return undefined;\n const obj = value as Record<string, unknown>;\n\n // cost: extract_f64(.cost).unwrap_or(0.0).max(0.0)\n const cost = Math.max(0, extractF64(obj[\"cost\"]) ?? 0);\n const apiProtocolRaw = typeof obj[\"apiProtocol\"] === \"string\" ? (obj[\"apiProtocol\"] as string) : undefined;\n\n const payload: ApiReqStartedPayload = {\n cost,\n tokensIn: tokenField(obj[\"tokensIn\"]),\n tokensOut: tokenField(obj[\"tokensOut\"]),\n cacheReads: tokenField(obj[\"cacheReads\"]),\n cacheWrites: tokenField(obj[\"cacheWrites\"]),\n };\n if (apiProtocolRaw !== undefined) payload.apiProtocol = apiProtocolRaw;\n return payload;\n}\n\n/** Provider from apiProtocol: trimmed, non-empty, else \"unknown\" (verbatim — no inference). */\nfunction providerFromApiProtocol(apiProtocol: string | undefined): string {\n if (apiProtocol === undefined) return DEFAULT_PROVIDER;\n const trimmed = apiProtocol.trim();\n return trimmed === \"\" ? DEFAULT_PROVIDER : trimmed;\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// File parse (port of parse_roo_kilo_file with source \"kilocode\")\n// ─────────────────────────────────────────────────────────────────────────\n\n/** The fields we read off a ui_messages.json entry (all optional / unknown). */\ninterface UiMessageEntry {\n type?: unknown;\n say?: unknown;\n text?: unknown;\n ts?: unknown;\n}\n\n/** Parse one task's ui_messages.json into usage records. */\nfunction parseKiloFile(path: string): UsageRecord[] {\n const data = readJsonFile(path);\n if (!Array.isArray(data)) return []; // malformed / non-array → no rows\n\n const sessionId = extractSessionId(path);\n const { model, agent } = readTaskMetadata(path);\n\n const out: UsageRecord[] = [];\n for (const raw of data) {\n if (typeof raw !== \"object\" || raw === null) continue;\n const entry = raw as UiMessageEntry;\n\n if (entry.type !== \"say\" || entry.say !== \"api_req_started\") continue;\n\n if (typeof entry.text !== \"string\") continue; // None => skip\n const ts = parseEntryTimestamp(entry.ts);\n if (ts === null) continue; // unparseable ts => skip\n\n const payload = parseApiReqStartedPayload(entry.text);\n if (payload === undefined) continue; // malformed payload => skip\n\n const providerId = providerFromApiProtocol(payload.apiProtocol);\n\n const tokens = emptyTokens();\n tokens.input = payload.tokensIn;\n tokens.output = payload.tokensOut;\n tokens.cacheRead = payload.cacheReads;\n tokens.cacheWrite = payload.cacheWrites;\n // reasoning stays 0 (Kilo Code does not report it).\n\n const record: UsageRecord = {\n platformId: PLATFORM_ID,\n modelId: model,\n providerId,\n sessionId,\n tokens,\n ts,\n messageCount: 1,\n confidence: \"host-reported\",\n };\n if (payload.cost > 0) record.cost = payload.cost;\n if (agent !== undefined) record.agent = agent;\n out.push(record);\n }\n\n return out;\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// Reader singleton\n// ─────────────────────────────────────────────────────────────────────────\n\n/** The Kilo Code (VS Code extension) usage reader singleton. */\nconst kiloReader: UsageReader = {\n platformId: PLATFORM_ID,\n kind: \"local\",\n async read({ sinceMs }: { sinceMs?: number }): Promise<UsageRecord[]> {\n const roots = tasksRoots().filter((root) => existsSync(root));\n if (roots.length === 0) return []; // no tasks dir → fail-open\n\n const records: UsageRecord[] = [];\n for (const root of roots) {\n // <root>/<taskId>/ui_messages.json\n const files = walkFiles(root, (name, abs) => {\n return name === \"ui_messages.json\" && /[\\\\/]ui_messages\\.json$/.test(abs);\n });\n\n for (const file of files) {\n let rows: UsageRecord[];\n try {\n rows = parseKiloFile(file);\n } catch {\n continue; // fail-open per file\n }\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 kiloReader;\n"],"mappings":";;;;;;;;;;;;;AA0DA,SAAS,YAAY,oBAAoB;AACzC,SAAS,SAAS,YAAY,kBAAkB;AAChD,SAAS,UAAU,SAAS,YAAY,MAAM,eAAe;AAO7D,IAAM,cAAc;AACpB,IAAM,gBAAgB;AACtB,IAAM,mBAAmB;AACzB,IAAM,kBAAkB;AAGxB,IAAM,oBAAoB;AAS1B,SAAS,gBAAwB;AAC/B,QAAM,OAAO,QAAQ;AACrB,UAAQ,WAAW,GAAG;AAAA,IACpB,KAAK;AACH,aAAO,KAAK,MAAM,WAAW,uBAAuB,QAAQ,MAAM;AAAA,IACpE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AW,QAAO,QAAQ;AACxC,QAAI,KAAK,MAAM;AAAA,EACjB;AAEA,SAAO;AACT;AAOA,IAAM,aAA0B;AAAA,EAC9B,YAAY;AAAA,EACZ,MAAM;AAAA,EACN,MAAM,KAAK,EAAE,QAAQ,GAAiD;AACpE,UAAM,QAAQ,WAAW,EAAE,OAAO,CAAC,SAAS,WAAW,IAAI,CAAC;AAC5D,QAAI,MAAM,WAAW,EAAG,QAAO,CAAC;AAEhC,UAAM,UAAyB,CAAC;AAChC,eAAW,QAAQ,OAAO;AAExB,YAAM,QAAQ,UAAU,MAAM,CAAC,MAAM,QAAQ;AAC3C,eAAO,SAAS,sBAAsB,0BAA0B,KAAK,GAAG;AAAA,MAC1E,CAAC;AAED,iBAAW,QAAQ,OAAO;AACxB,YAAI;AACJ,YAAI;AACF,iBAAO,cAAc,IAAI;AAAA,QAC3B,QAAQ;AACN;AAAA,QACF;AACA,mBAAW,OAAO,MAAM;AACtB,cAAI,YAAY,UAAa,IAAI,KAAK,QAAS;AAC/C,kBAAQ,KAAK,GAAG;AAAA,QAClB;AAAA,MACF;AAAA,IACF;AACA,WAAO;AAAA,EACT;AACF;AAEA,IAAO,eAAQ;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/adapters/kilo-cli/index.ts"],"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 * User config dir (XDG): the kilo backend honors `$XDG_CONFIG_HOME`, so the user\n * scope resolves to `$XDG_CONFIG_HOME/kilo` when that env var is set & non-empty,\n * else `~/.config/kilo` (the default). This is the SAME backend dir the kilo\n * extension uses — every user-scope path below (writer, detection probe, plugin\n * dir, content surfaces) flows through `kiloCliConfigDir()` so they cannot\n * disagree with where the Kilo CLI actually reads.\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 (XDG: $XDG_CONFIG_HOME/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 (XDG: $XDG_CONFIG_HOME/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; user dir is XDG-resolved):\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 { existsSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { 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 { xdgConfigHome } from \"../../core/host-paths.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\n/**\n * Resolve the kilo backend user config dir: `$XDG_CONFIG_HOME/kilo` when set,\n * else `~/.config/kilo`. This is the SAME backend dir the kilo extension uses\n * (kilo's own `kiloConfigDir()`), so the CLI writer, detection probe, and\n * content surfaces all agree with where the XDG-honoring Kilo CLI reads. When\n * `$XDG_CONFIG_HOME` is unset this is byte-identical to `~/.config/kilo`.\n */\nfunction kiloCliConfigDir(): string {\n return join(xdgConfigHome(), \"kilo\");\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 = kiloCliConfigDir();\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 : kiloCliConfigDir();\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(kiloCliConfigDir(), \"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 changes.push(\n this.writeManagedFile(\n file.path,\n file.contents,\n ctx.dryRun,\n `kilo plugin module (${this.hookDetail(ctx)})`,\n file.executable,\n ),\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 changes.push(\n this.removeManagedFile(pluginPath, ctx.dryRun, \"kilo plugin module\", \"no kilo plugin module present\"),\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> (via getConfigDir):\n // project scope → <projectDir>/.kilo\n // user scope → ~/.config/kilo (XDG: $XDG_CONFIG_HOME/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}\n\nexport const adapter = new KiloCliAdapter();\nexport default adapter;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAuEA,SAAS,kBAAkB;AAC3B,SAAS,eAAe;AACxB,SAAS,YAAY;AAqCrB,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;AAoCA,SAAS,mBAA2B;AAClC,SAAO,KAAK,cAAc,GAAG,MAAM;AACrC;AAEO,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;AAAA,IAClB,MAAM;AAAA,IACN,cAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IASd,mBAAmB;AAAA;AAAA,IAEnB,eAAe;AAAA;AAAA,IAEf,iBAAiB;AAAA;AAAA,IAEjB,yBAAyB;AAAA;AAAA,IAEzB,YAAY,CAAC,SAAS,OAAO,MAAM;AAAA;AAAA,IAEnC,kBAAkB;AAAA,IAClB,gBAAgB;AAAA,IAChB,mBAAmB;AAAA,EACrB;AAAA;AAAA,EAIA,gB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GAAG,YAAY,IAAI,WAAW,WAAW,IACjE;AAAA,YACE,QAAQ;AAAA,YACR,QAAQ,MAAM,YAAY,IAAI,WAAW,OAAO,UAAU;AAAA,UAC5D;AAAA,QACN;AAAA,MACF;AAAA,MACA;AAAA,QACE,MAAM,GAAG,KAAK,IAAI;AAAA,QAClB,OAAO,MAAM;AACX,cAAI,CAAC,SAAU,QAAO,EAAE,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;AAGF;AAEO,IAAM,UAAU,IAAI,eAAe;AAC1C,IAAO,mBAAQ;","names":["entry"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/usage/readers/kilo-cli.ts"],"sourcesContent":["/**\n * usage/readers/kilo-cli — Kilo CLI SQLite session reader.\n *\n * Faithful port of tokscale sessions/kilo.rs (parse_kilo_sqlite /\n * parse_kilo_sqlite_with_fallback, lines 53-155). The Kilo CLI stores every\n * message as one row in a `message` table whose `data` column is the raw message\n * JSON (TEXT) — the same shape OpenCode uses. This reader opens that DB read-only\n * and reports the assistant rows' token usage.\n *\n * This is the SQLite Kilo CLI reader and is DISTINCT from the already-shipped\n * `kilo` reader (sessions/kilocode.rs), which parses the VS Code KiloCode task\n * logs (`ui_messages.json`, the Roo/Kilo `api_req_started` JSON format). They are\n * different products with different storage and carry different platformIds\n * (`kilo-cli` here vs `kilo` there) so their rows never merge.\n *\n * DB path: ~/.local/share/kilo/kilo.db (XDG_DATA_HOME and the\n * AGENT_CONNECTOR_KILO_CLI_DIR override are honored via paths.ts hostRoots).\n *\n * SQL (port of the Rust `query`):\n * SELECT m.id, m.session_id, m.data\n * FROM message m\n * WHERE json_valid(m.data)\n * AND json_extract(m.data, '$.role') = 'assistant'\n * AND json_extract(m.data, '$.tokens') IS NOT NULL\n *\n * Tokens (off the parsed `data` JSON, each clamped ≥ 0 — the Rust `.max(0)` on\n * the i64 fields; KiloTokens makes input/output/cache.read/cache.write required\n * and reasoning optional, so a row missing one of the required fields fails the\n * serde deserialize and is skipped — replicated here):\n * tokens.input → input\n * tokens.output → output\n * tokens.cache.read → cacheRead\n * tokens.cache.write → cacheWrite\n * tokens.reasoning → reasoning (optional; 0 when absent)\n * cost is `data.$.cost` (clamped ≥ 0), emitted only when > 0.\n *\n * model / provider: data.$.modelID is REQUIRED — a row without it is skipped\n * (the Rust `match msg.model_id { None => continue }`). provider prefers\n * data.$.providerID, then inferProvider(modelId), then the \"kilo\" default.\n *\n * agent: data.$.agent then data.$.mode (Rust `msg.agent.or(msg.mode)` — note this\n * is the OPPOSITE precedence to the OpenCode reader's mode-then-agent).\n *\n * session: data.$.session_id (preferred) else the m.session_id column.\n *\n * project: NONE — the Kilo CLI log carries no cwd/workspace, so no projectKey\n * is emitted (matches the spec's \"projectAttribution: None\").\n *\n * timestamp: data.$.time.created (Unix MILLISECONDS, float, truncated to int).\n * When the `time` block is absent the fallback is the DB file's mtime (port of\n * file_modified_timestamp_ms). A `time` block present but with a non-numeric\n * `created` fails the serde deserialize, so the row is skipped (not fallen back).\n *\n * DEDUP — dedupKey = data.$.id (the embedded message id) else the m.id row id\n * (Rust `msg.id.or(Some(row_id))`). No fingerprint merge: the Kilo CLI is a\n * single source of record, so a row-id backstop is sufficient.\n *\n * confidence: \"host-reported\" (Kilo logs real token counts).\n *\n * Fail-open: DB missing/locked/unreadable/corrupt → openSqlite() returns null →\n * []; a malformed row → skipped. Never throws. Read-only.\n */\n\nimport type { SqliteDb } from \"../sqlite.js\";\nimport type { UsageReader, UsageRecord } from \"../types.js\";\nimport { emptyTokens } from \"../aggregate.js\";\nimport { fileMtimeMs } from \"../jsonl.js\";\nimport { inferProvider } from \"../normalize.js\";\nimport { firstExistingRoot } from \"../paths.js\";\nimport { openSqlite } from \"../sqlite.js\";\n\nconst PLATFORM_ID = \"kilo-cli\" as const;\nconst DEFAULT_PROVIDER = \"kilo\";\n\nconst QUERY = `\n SELECT m.id, m.session_id, m.data\n FROM message m\n WHERE json_valid(m.data)\n AND json_extract(m.data, '$.role') = 'assistant'\n AND json_extract(m.data, '$.tokens') IS NOT NULL\n`;\n\n// ─────────────────────────────────────────────────────────────────────────\n// Value coercion\n// ─────────────────────────────────────────────────────────────────────────\n\n/** A non-negative integer token field (port of `.max(0)` on an i64). */\nfunction tokenField(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/** A finite number (the serde i64/f64 required-field semantics), or undefined. */\nfunction asFiniteNumber(v: unknown): number | undefined {\n const n = typeof v === \"number\" ? v : typeof v === \"string\" ? Number(v) : NaN;\n return Number.isFinite(n) ? n : undefined;\n}\n\n/** A non-empty string, or undefined. */\nfunction asNonEmptyString(v: unknown): string | undefined {\n return typeof v === \"string\" && v !== \"\" ? v : undefined;\n}\n\n/** A SELECT column that may come back as Uint8Array (BLOB) / number — to string. */\nfunction asString(v: unknown): string | undefined {\n if (typeof v === \"string\") return v;\n if (typeof v === \"number\" && Number.isFinite(v)) return String(v);\n return undefined;\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// The parsed `data` column (the KiloMessage subset we read)\n// ─────────────────────────────────────────────────────────────────────────\n\ninterface KiloTokens {\n input: number;\n output: number;\n reasoning: number;\n cacheRead: number;\n cacheWrite: number;\n}\n\ninterface ParsedMessage {\n /** Embedded message id (preferred dedup key); undefined when absent. */\n id: string | undefined;\n /** Embedded session id (preferred over the row column); undefined when absent. */\n sessionId: string | undefined;\n modelId: string;\n providerId: string;\n agent: string | undefined;\n tokens: KiloTokens;\n cost: number;\n /** Truncated time.created (ms), or undefined → caller uses the mtime fallback. */\n ts: number | undefined;\n}\n\n/**\n * Parse the `data` JSON of a row (port of the KiloMessage deserialize + the\n * post-deserialize checks). Returns undefined for any row the Rust would skip:\n * • not a JSON object / not parseable;\n * • role != \"assistant\" (redundant with the SQL filter, but the Rust re-checks);\n * • no tokens block, or a tokens block missing a REQUIRED field\n * (input / output / cache.read / cache.write — serde would fail the struct);\n * • a `time` block present but with a non-numeric `created` (serde fails);\n * • no modelID (the Rust `match msg.model_id { None => continue }`).\n */\nfunction parseData(dataJson: string): ParsedMessage | undefined {\n let value: unknown;\n try {\n value = JSON.parse(dataJson);\n } catch {\n return undefined;\n }\n if (typeof value !== \"object\" || value === null) return undefined;\n const obj = value as Record<string, unknown>;\n\n if (obj[\"role\"] !== \"assistant\") return undefined;\n\n // tokens — required block; input/output/cache.{read,write} are required fields\n // (KiloTokens / KiloCache), reasoning is optional. A missing required field\n // would fail serde, so we reject the row rather than coerce it to 0.\n const tokensRaw = obj[\"tokens\"];\n if (typeof tokensRaw !== \"object\" || tokensRaw === null) return undefined;\n const t = tokensRaw as Record<string, unknown>;\n const input = asFiniteNumber(t[\"input\"]);\n const output = asFiniteNumber(t[\"output\"]);\n if (input === undefined || output === undefined) return undefined;\n\n const cacheRaw = t[\"cache\"];\n if (typeof cacheRaw !== \"object\" || cacheRaw === null) return undefined;\n const cache = cacheRaw as Record<string, unknown>;\n const cacheRead = asFiniteNumber(cache[\"read\"]);\n const cacheWrite = asFiniteNumber(cache[\"write\"]);\n if (cacheRead === undefined || cacheWrite === undefined) return undefined;\n\n // modelID — required (the Rust skips a row that lacks it).\n const modelId = asNonEmptyString(obj[\"modelID\"]);\n if (modelId === undefined) return undefined;\n\n // time — optional block; when present, `created` is a required f64 (serde\n // would fail an absent/non-numeric created), so a malformed time skips the row.\n const timeRaw = obj[\"time\"];\n let ts: number | undefined;\n if (timeRaw !== undefined && timeRaw !== null) {\n if (typeof timeRaw !== \"object\") return undefined;\n const created = asFiniteNumber((timeRaw as Record<string, unknown>)[\"created\"]);\n if (created === undefined) return undefined;\n ts = Math.trunc(created);\n }\n\n // provider: data.$.providerID, then inferred from model, then the \"kilo\" default.\n const providerId =\n asNonEmptyString(obj[\"providerID\"]) ?? inferProvider(modelId) ?? DEFAULT_PROVIDER;\n\n // agent prefers agent then mode (Rust: msg.agent.or(msg.mode)).\n const agent = asNonEmptyString(obj[\"agent\"]) ?? asNonEmptyString(obj[\"mode\"]);\n\n return {\n id: asNonEmptyString(obj[\"id\"]),\n sessionId: asNonEmptyString(obj[\"session_id\"]),\n modelId,\n providerId,\n agent,\n tokens: {\n input: tokenField(input),\n output: tokenField(output),\n reasoning: tokenField(t[\"reasoning\"]),\n cacheRead: tokenField(cacheRead),\n cacheWrite: tokenField(cacheWrite),\n },\n cost: Math.max(0, asFiniteNumber(obj[\"cost\"]) ?? 0),\n ts,\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// DB read\n// ─────────────────────────────────────────────────────────────────────────\n\n/** The three selected columns of one row. */\ninterface Row {\n id: string;\n sessionId: string;\n data: string;\n}\n\n/** Select the assistant rows that carry a tokens block. */\nfunction selectRows(db: SqliteDb): Row[] {\n const rows: Row[] = [];\n for (const r of db.all(QUERY)) {\n const id = asString(r[\"id\"]);\n const sessionId = asString(r[\"session_id\"]);\n const data = asString(r[\"data\"]);\n if (id === undefined || sessionId === undefined || data === undefined) continue;\n rows.push({ id, sessionId, data });\n }\n return rows;\n}\n\n/** Parse the Kilo CLI SQLite DB into usage records (fallbackTs = DB file mtime). */\nfunction parseDb(db: SqliteDb, fallbackTs: number): UsageRecord[] {\n const records: UsageRecord[] = [];\n\n for (const row of selectRows(db)) {\n const msg = parseData(row.data);\n if (msg === undefined) continue;\n\n // dedupKey prefers the embedded message id; falls back to the row id.\n const dedupKey = msg.id ?? row.id;\n // session prefers the embedded id; falls back to the m.session_id column.\n const sessionId = msg.sessionId ?? row.sessionId;\n // timestamp prefers time.created; falls back to the DB file mtime.\n const ts = msg.ts ?? fallbackTs;\n\n const tokens = emptyTokens();\n tokens.input = msg.tokens.input;\n tokens.output = msg.tokens.output;\n tokens.cacheRead = msg.tokens.cacheRead;\n tokens.cacheWrite = msg.tokens.cacheWrite;\n tokens.reasoning = msg.tokens.reasoning;\n\n const record: UsageRecord = {\n platformId: PLATFORM_ID,\n modelId: msg.modelId,\n providerId: msg.providerId,\n sessionId,\n tokens,\n ts,\n messageCount: 1,\n dedupKey,\n confidence: \"host-reported\",\n };\n if (msg.cost > 0) record.cost = msg.cost;\n if (msg.agent !== undefined) record.agent = msg.agent;\n\n records.push(record);\n }\n\n return records;\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// Reader singleton\n// ─────────────────────────────────────────────────────────────────────────\n\n/** The Kilo CLI usage reader singleton. */\nconst kiloCliReader: UsageReader = {\n platformId: PLATFORM_ID,\n kind: \"local\",\n async read({ sinceMs }: { sinceMs?: number }): Promise<UsageRecord[]> {\n const dbPath = firstExistingRoot(PLATFORM_ID);\n if (dbPath === undefined) return []; // no kilo.db → fail-open\n\n const db = await openSqlite(dbPath);\n if (db === null) return []; // missing/locked/unreadable/corrupt → fail-open\n\n try {\n const fallbackTs = fileMtimeMs(dbPath);\n const rows = parseDb(db, fallbackTs);\n if (sinceMs === undefined) return rows;\n return rows.filter((r) => r.ts >= sinceMs);\n } catch {\n return []; // any unexpected error → fail-open\n } finally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C;AAEzB,QAAI;AACF,YAAM,aAAa,YAAY,MAAM;AACrC,YAAM,OAAO,QAAQ,IAAI,UAAU;AACnC,UAAI,YAAY,OAAW,QAAO;AAClC,aAAO,KAAK,OAAO,CAAC,MAAM,EAAE,MAAM,OAAO;AAAA,IAC3C,QAAQ;AACN,aAAO,CAAC;AAAA,IACV,UAAE;AACA,SAAG,MAAM;AAAA,IACX;AAAA,EACF;AACF;AAEA,IAAO,mBAAQ;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/usage/readers/kimi.ts"],"sourcesContent":["/**\n * usage/readers/kimi — Moonshot native session-log reader (TWO products).\n *\n * Originally a faithful port of tokscale sessions/kimi.rs (origin of the Kimi\n * CLI wire parse), this reader now PARSES BOTH Moonshot products that share the\n * \"kimi\" platform id. They lay out their logs DIFFERENTLY *and* write a\n * different wire.jsonl record shape, so the parser auto-routes per line (a given\n * wire.jsonl is one product's format; no root-based branching is needed):\n *\n * - Kimi CLI (older, ~/.kimi):\n * ~/.kimi/sessions/<GROUP_ID>/<SESSION_UUID>/wire.jsonl\n * config.json sits at ~/.kimi/config.json. This is the tree tokscale's\n * sessions/kimi.rs reads and the one this port was first written against.\n * PARSE MODEL: progressive `message.type===\"StatusUpdate\"` snapshots,\n * deduped by `payload.message_id` keeping the MAX total (see parseKimiFile).\n *\n * - Kimi Code (newer, @moonshot-ai/kimi-code, ~/.kimi-code):\n * ~/.kimi-code/sessions/<SESSION>/agents/<AGENT>/wire.jsonl\n * config.json sits at ~/.kimi-code/config.json. This is a DEEPER tree (an\n * extra `agents/<AGENT>/` level) — the product our connector adapter\n * targets. The `~/.kimi-code` base + `$KIMI_CODE_HOME` override are\n * primary-doc-confirmed (moonshotai.github.io/kimi-code/en/configuration/\n * config-files.html), as is the `wire.jsonl` filename (\"the agent event\n * stream\", moonshotai.github.io/kimi-code docs).\n * PARSE MODEL: per-LLM-call usage DELTAS, SUMMED (see parseKimiCodeFile).\n *\n * Both default trees are scanned (Kimi Code preferred first); $KIMI_CODE_HOME\n * relocates the Kimi Code home and is honored ahead of the defaults; the\n * AGENT_CONNECTOR_KIMI_DIR override (via paths.ts hostRoots) is honored first.\n *\n * ─── Kimi CLI wire frame parse (port of tokscale sessions/kimi.rs) ───\n * Each line is a timestamped wire frame; only frames whose\n * `message.type === \"StatusUpdate\"` 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 * The first line (`{\"type\":\"metadata\", …}`) and every non-StatusUpdate frame\n * (TurnBegin / ContentPart / ToolCall / StepBegin …) are skipped. Zero-token\n * StatusUpdates are dropped.\n * DEDUP (the double-counting hazard): Kimi CLI emits PROGRESSIVE StatusUpdates\n * for a single assistant message as generation streams (e.g. message_id \"msg-x\"\n * at 100→10 tokens, then 120→30). We dedup by `payload.message_id`, keeping the\n * row with the MAX total tokens (tie-break: the later timestamp). Records\n * WITHOUT a (non-empty) message_id are never merged — each passes through as its\n * own row, exactly as the Rust push_or_replace_status_update does. The kept\n * row's `dedupKey` is its message_id (absent for un-keyed rows).\n *\n * ─── Kimi Code wire record parse (SOURCE-VERIFIED from MoonshotAI/kimi-code) ───\n * The on-disk usage record is `{ type:\"usage.record\", time?, model, usage,\n * usageScope? }` — verified against the readable (non-minified) TypeScript\n * source:\n * - packages/agent-core/src/agent/records/types.ts → the wire.jsonl usage\n * record shape `{ type:\"usage.record\", time?:number, model:string,\n * usage:TokenUsage, usageScope?:\"session\"|\"turn\" }`.\n * - packages/kosong/src/usage.ts → `TokenUsage = { inputOther, output,\n * inputCacheRead, inputCacheCreation }` (camelCase; NO reasoning field).\n * - packages/agent-core/src/agent/usage/index.ts `record(model, usage, scope)`\n * logs exactly ONE `usage.record` per LLM call carrying that call's per-call\n * DELTA usage; the canonical session total is the SUM of all deltas\n * (`addUsage`), confirmed by packages/agent-core/test/agent/usage.test.ts\n * (record(inputOther:1)+record(inputOther:10) ⇒ total inputOther:11).\n * - `usageScope` ('session'|'turn') only drives an IN-MEMORY currentTurn\n * rollup; exactly one `usage.record` is written per record() call, so SUMMING\n * ALL usage.record deltas of ANY scope = the correct session total with NO\n * double-count. We deliberately do NOT filter or dedup by scope.\n * Field map (TokenUsage → TokenBreakdown):\n * inputOther → input\n * output → output\n * inputCacheRead → cacheRead\n * inputCacheCreation → cacheWrite\n * reasoning is always 0 (TokenUsage has no reasoning field).\n * Each usage.record is a DELTA, so each becomes its OWN row (no message_id\n * dedup; dedupKey is absent so aggregation never merges them) and the rows SUM\n * downstream. Zero-token records are dropped (consistent with the CLI path).\n * Per-record `model` is taken from the record itself (DEFAULT_MODEL fallback),\n * so the config.json walk is NOT consulted for the Kimi Code model. Timestamp is\n * `record.time` normalized via normalizeTimestampMs (>1e12 ⇒ ms, else\n * seconds×1000), falling back to the file mtime like the CLI path.\n *\n * Model (Kimi CLI only): `.model` from <home>/config.json (fallback\n * \"kimi-for-coding\"), where <home> is found by walking UP from wire.jsonl to the\n * nearest dir containing config.json — depth-robust, so it lands on ~/.kimi for\n * the CLI tree (and would land on ~/.kimi-code for the deeper tree, though Kimi\n * Code records carry their own model). Provider is hard-coded \"moonshot\".\n * Session id is the immediate parent dir of wire.jsonl: the SESSION_UUID for\n * Kimi CLI; for the deeper Kimi Code tree that is the <AGENT> dir (the best\n * available id at that depth — documented, acceptable). Kimi's wire log carries\n * no cwd, so there is no project attribution. Confidence is \"host-reported\"\n * (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, hostRoots, isDir, isFile, walkFiles } from \"../paths.js\";\n\nconst PLATFORM_ID = \"kimi\" as const;\nconst DEFAULT_MODEL = \"kimi-for-coding\";\nconst DEFAULT_PROVIDER = \"moonshot\";\n\n/**\n * Bound on the upward config.json walk. Kimi CLI needs 4 hops (wire.jsonl →\n * UUID → GROUP → sessions → home); Kimi Code's deeper tree needs 5 (wire.jsonl →\n * AGENT → agents → SESSION → sessions → home). 6 leaves headroom without letting\n * a stray config.json far up the filesystem masquerade as the Kimi home.\n */\nconst MAX_HOME_WALK_LEVELS = 6;\n\n/** A Kimi CLI 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/**\n * A Kimi Code wire.jsonl `usage.record` line (SOURCE-VERIFIED, see header). The\n * `usage` block is TokenUsage (camelCase, no reasoning); `time` is the record\n * timestamp; `model` is the per-call model; `usageScope` is informational only\n * and intentionally not read (every record is summed regardless of scope).\n */\ninterface KimiCodeUsageRecord {\n type?: unknown;\n time?: unknown;\n model?: unknown;\n usage?: {\n inputOther?: unknown;\n output?: unknown;\n inputCacheRead?: unknown;\n inputCacheCreation?: unknown;\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 Kimi CLI 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 * Normalize a Kimi Code `usage.record.time` to epoch ms, disambiguating\n * seconds-vs-ms by magnitude (the repo-wide convention): a value already in ms\n * (> 1e12) passes through truncated; a smaller value is treated as Unix seconds\n * (× 1000). Returns null when unusable so the caller falls back to the file mtime.\n */\nfunction normalizeTimestampMs(v: unknown): number | null {\n if (typeof v === \"number\" && Number.isFinite(v) && v > 0) {\n return v > 1e12 ? Math.trunc(v) : Math.trunc(v * 1000);\n }\n return null;\n}\n\n/**\n * Find the Kimi home for a wire.jsonl and read its `.model` (depth-robust\n * evolution of the Rust read_model_from_config). The two product trees differ in\n * DEPTH:\n * Kimi CLI : <home>/sessions/<GROUP_ID>/<SESSION_UUID>/wire.jsonl (4 hops)\n * Kimi Code: <home>/sessions/<SESSION>/agents/<AGENT>/wire.jsonl (5 hops)\n * A fixed dirname-hop count would land on `sessions/` for the deeper tree, so we\n * walk UP the ancestor chain (bounded by MAX_HOME_WALK_LEVELS) reading the first\n * `config.json` found — but the home is DEFINITIONALLY the parent of the\n * `sessions/` segment, so the moment we reach the `sessions` dir we read its\n * parent's config.json and STOP. That hard ceiling keeps the search inside the\n * Kimi home: it can never escape into an ancestor (e.g. a repo's or $HOME's stray\n * config.json) when the real home lacks one. For the Kimi CLI tree this resolves\n * the SAME <home> as the old 4-hop logic, so CLI behavior is byte-identical.\n * Fail-open to DEFAULT_MODEL on no config.json or any missing/garbage value.\n */\nfunction modelFromConfigAt(dir: string): string {\n const parsed = readJsonFile(join(dir, \"config.json\"));\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; // config.json absent/unreadable or no usable .model\n}\n\nfunction readModelFromConfig(wirePath: string): string {\n let dir = dirname(wirePath);\n for (let level = 0; level <= MAX_HOME_WALK_LEVELS; level += 1) {\n if (isFile(join(dir, \"config.json\"))) return modelFromConfigAt(dir);\n // The home is the parent of the `sessions/` segment — read it and STOP so the\n // walk never climbs above the Kimi home into a stray ancestor config.json.\n if (basename(dir) === \"sessions\") return modelFromConfigAt(dirname(dir));\n const parent = dirname(dir);\n if (parent === dir) break; // reached filesystem root\n dir = parent;\n }\n return DEFAULT_MODEL;\n}\n\n/**\n * Session id from the wire path: the immediate parent directory of wire.jsonl\n * (port of extract_session_id, UNCHANGED). For Kimi CLI that is the SESSION_UUID;\n * for the deeper Kimi Code tree (.../sessions/<SESSION>/agents/<AGENT>/wire.jsonl)\n * that is the <AGENT> dir — the best available id at that depth (documented,\n * acceptable). Keeping the immediate-parent rule keeps Kimi CLI byte-identical.\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 * Parse one Kimi Code wire.jsonl file into usage records (SOURCE-VERIFIED, see\n * header). Each `type === \"usage.record\"` line is a per-LLM-call usage DELTA;\n * we emit each as its OWN row (NO message_id dedup — dedupKey is absent so\n * aggregation never merges them) and the rows SUM to the canonical session\n * total. usageScope is ignored on purpose: exactly one usage.record is written\n * per record() call, so summing all deltas of any scope never double-counts.\n * Non-usage.record lines (metadata, turn_begin, …) are skipped; zero-token\n * records are dropped, matching the CLI path.\n */\nfunction parseKimiCodeFile(path: string): UsageRecord[] {\n const lines = readJsonlLines(path);\n if (lines.length === 0) return [];\n\n const sessionId = extractSessionId(path);\n const mtime = fileMtimeMs(path);\n\n const out: UsageRecord[] = [];\n\n for (const raw of lines) {\n if (typeof raw !== \"object\" || raw === null) continue;\n const rec = raw as KimiCodeUsageRecord;\n\n // Only usage.record lines carry token usage in the Kimi Code format.\n if (rec.type !== \"usage.record\") continue;\n\n const usage = rec.usage;\n if (typeof usage !== \"object\" || usage === null) continue;\n\n // TokenUsage → TokenBreakdown (camelCase source fields; no reasoning field).\n const input = toNonNegInt(usage.inputOther);\n const output = toNonNegInt(usage.output);\n const cacheRead = toNonNegInt(usage.inputCacheRead);\n const cacheWrite = toNonNegInt(usage.inputCacheCreation);\n\n // Skip zero-token deltas (consistent with the CLI path).\n if (input + output + cacheRead + cacheWrite === 0) continue;\n\n const ts = normalizeTimestampMs(rec.time) ?? 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 — Kimi Code's TokenUsage has no reasoning field.\n\n const model =\n typeof rec.model === \"string\" && rec.model !== \"\" ? rec.model : DEFAULT_MODEL;\n\n // Each delta is its own row (no dedupKey ⇒ never merged at aggregation).\n out.push({\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 }\n\n return out;\n}\n\n/**\n * Detect which product wrote a wire.jsonl by its record shape (a given file is\n * ONE product's format). A file is Kimi Code iff it carries any\n * `type === \"usage.record\"` line; otherwise it is parsed as Kimi CLI. This keeps\n * the Kimi CLI path (parseKimiFile) provably untouched — a CLI StatusUpdate file\n * has no usage.record line and routes to parseKimiFile byte-identically.\n */\nfunction parseWireFile(path: string): UsageRecord[] {\n const lines = readJsonlLines(path);\n for (const raw of lines) {\n if (typeof raw === \"object\" && raw !== null && (raw as KimiCodeUsageRecord).type === \"usage.record\") {\n return parseKimiCodeFile(path);\n }\n }\n return parseKimiFile(path);\n}\n\n/**\n * Candidate Kimi session roots, most-preferred first. Covers BOTH Moonshot\n * products under the \"kimi\" id:\n * 1. $KIMI_CODE_HOME/sessions — Kimi Code's relocated home, when set (the env\n * var our adapter and the official kimi-code docs honor).\n * 2. paths.ts hostRoots(\"kimi\"), in order:\n * - AGENT_CONNECTOR_KIMI_DIR/sessions (explicit framework override)\n * - ~/.kimi-code/sessions (Kimi Code default — preferred)\n * - ~/.kimi/sessions (Kimi CLI default)\n * All existing roots are scanned (not just the first) so a box running BOTH\n * products is fully covered; the reader's `seen` set de-overlaps any duplicate\n * wire.jsonl reached via two roots (e.g. KIMI_CODE_HOME == ~/.kimi-code).\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 // hostRoots already prepends the AGENT_CONNECTOR_KIMI_DIR override and lists\n // ~/.kimi-code/sessions then ~/.kimi/sessions as the two product defaults.\n for (const root of hostRoots(PLATFORM_ID)) roots.push(root);\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 session root present → fail-open\n\n // Kimi CLI : <root>/<GROUP_ID>/<SESSION_UUID>/wire.jsonl\n // Kimi Code: <root>/<SESSION>/agents/<AGENT>/wire.jsonl (deeper — walkFiles\n // recurses, so the extra `agents/` level is found transparently).\n // parseWireFile routes each file to its product parser by record shape.\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 across overlapping roots\n seen.add(file);\n const rows = parseWireFile(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":";;;;;;;;;;;;;;;;;;AA+FA,SAAS,UAAU,SAAS,YAAY;AAOxC,IAAM,cAAc;AACpB,IAAM,gBAAgB;AACtB,IAAM,mBAAmB;AAQzB,IAAM,uBAAuB;AAuC7B,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;AAQA,SAAS,qBAAqB,GAA2B;AACvD,MAAI,OAAO,MAAM,YAAY,OAAO,SAAS,CAAC,KAAK,IAAI,GAAG;AACxD,WAAO,IAAI,OAAO,KAAK,MAAM,CAAC,IAAI,KAAK,MAAM,IAAI,GAAI;AAAA,EACvD;AACA,SAAO;AACT;AAkBA,SAAS,kBAAkB,KAAqB;AAC9C,QAAM,SAAS,aAAa,KAAK,KAAK,aAAa,CAAC;AACpD,MAAI,OAAO,WAAW,YAAY,WAAW,MAAM;AACjD,UAAM,QAAS,OAA+B;AAC9C,QAAI,OAAO,UAAU,YAAY,UAAU,GAAI,QAAO;AAAA,EACxD;AACA,SAAO;AACT;AAEA,SAAS,oBAAoB,UAA0B;AACrD,MAAI,MAAM,QAAQ,QAAQ;AAC1B,WAAS,QAAQ,GAAG,SAAS,sBAAsB,SAAS,GAAG;AAC7D,QAAI,OAAO,KAAK,KAAK,aAAa,CAAC,EAAG,QAAO,kBAAkB,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