@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/core/load-connector.ts"],"sourcesContent":["/**\n * core/load-connector — discover, load, and register connector definitions.\n *\n * Responsibilities:\n * 1. Locate the developer's `agent-connector.config.{mjs,js,json}` by walking\n * upward from a start directory (the project root convention).\n * 2. Load a config from a path into a LIVE ResolvedConnector (with handlers).\n * 3. Register a connector by persisting SERIALIZABLE metadata (no functions)\n * to `connectorDir(id)/connector.json`, pointing at the source module so\n * live handlers can be re-imported at runtime from a stable record.\n *\n * Why split live vs. serialized? Hook handlers are functions and cannot survive\n * JSON. The registry stores only what JSON can hold plus an absolute\n * `modulePath`; the runtime re-imports that module to recover the live handlers.\n */\n\nimport { existsSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from \"node:fs\";\nimport { dirname, isAbsolute, join, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\nimport type {\n CommandDef,\n HookEventName,\n InstallScope,\n MemoryDef,\n PlatformId,\n PlatformOverride,\n ResolvedConnector,\n ServerDef,\n SkillDef,\n SubagentDef,\n} from \"./types.js\";\nimport { defineConnector } from \"./define-connector.js\";\nimport { assertNoSymlinkInPath, connectorDir, connectorsDir, ensureDir } from \"./paths.js\";\nimport {\n readConnectorPackageMetadataNearFile,\n withConnectorPackageMetadata,\n} from \"./package-metadata.js\";\n\n/** Candidate config filenames, in resolution-precedence order. */\nconst CONFIG_FILENAMES = [\n \"agent-connector.config.mjs\",\n \"agent-connector.config.js\",\n \"agent-connector.config.json\",\n] as const;\n\n/**\n * The serializable subset of a connector persisted to `connector.json`.\n * Hook handler functions are intentionally absent — only the absolute\n * `modulePath` is stored so the live ResolvedConnector can be re-imported.\n */\nexport interface RegisteredMeta {\n id: string;\n displayName: string;\n version: string;\n /** Package-derived identity, when available from config or package.json. */\n mcp?: ResolvedConnector[\"mcp\"];\n /** Absolute path to the source module that produced this connector. */\n modulePath: string;\n telemetry: ResolvedConnector[\"telemetry\"];\n /** Canonical event names the connector handles (handlers themselves stripped). */\n hookEvents: HookEventName[];\n hasServer: boolean;\n server: ServerDef | null;\n /**\n * Content surfaces (commands/skills/subagents). These are JSON-serializable\n * (no functions) so they persist cleanly and let uninstall locate the files\n * to remove even when the source module is gone.\n */\n commands: CommandDef[];\n skills: SkillDef[];\n subagents: SubagentDef[];\n /**\n * Memory entries (managed-block content surface). Plain content, persisted\n * whole so uninstall normally has the full entry list even when the source\n * module is gone (the marker prefix-scan is the fallback beyond that).\n */\n memory: MemoryDef[];\n targets: ResolvedConnector[\"targets\"];\n /** Per-platform overrides with any hook handler functions stripped. */\n platforms: Partial<Record<PlatformId, PlatformOverride>>;\n /**\n * The install scope this connector was registered under, persisted so the\n * runtime entrypoints (hook/statusline/action) can recover it cheaply (sync)\n * and stamp it onto the HostCtx/event — scope is an install-time property the\n * runtime otherwise has no access to. OPTIONAL: absent for an ad-hoc register\n * that passed no scope, or a record written before this field existed.\n * This is the install's RUN-WIDE DEFAULT scope; it can differ from the\n * effective per-host scope when a `platforms[host].scope` override is set (the\n * record is keyed by connector id only and holds no per-host scope map).\n */\n scope?: InstallScope;\n}\n\n/**\n * Search `startDir` and each ancestor for a connector config file. Returns the\n * absolute path to the first match (filesystem-root-stopping), or null.\n */\nexport function findConnectorConfig(startDir: string): string | null {\n let dir = resolve(startDir);\n // Walk upward until `dirname(dir) === dir` (filesystem root).\n for (;;) {\n for (const name of CONFIG_FILENAMES) {\n const candidate = join(dir, name);\n if (existsSync(candidate)) return candidate;\n }\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\n/** True if a value already looks like a ResolvedConnector (vs. a raw config). */\nfunction isResolvedConnector(value: unknown): value is ResolvedConnector {\n return (\n typeof value === \"object\" &&\n value !== null &&\n Array.isArray((value as { hookEvents?: unknown }).hookEvents)\n );\n}\n\n/**\n * Load a connector from an absolute or relative path.\n * - `.json` → JSON.parse, then defineConnector().\n * - `.mjs` / `.js` → dynamic import (via pathToFileURL, Windows-safe),\n * take the default export. If it already looks like a\n * ResolvedConnector use it as-is; otherwise treat it as\n * a ConnectorConfig and run it through defineConnector().\n * Returns the live connector plus the absolute module path it came from.\n */\nexport async function loadConnectorFromPath(\n path: string,\n): Promise<{ connector: ResolvedConnector; modulePath: string }> {\n let modulePath = isAbsolute(path) ? path : resolve(path);\n // Canonicalize before building the file:// URL for dynamic import. On Windows a\n // short (8.3) temp path like C:\\Users\\RUNNER~1\\...\\x.mjs round-trips the \"~\" as\n // %7E and fails to load; realpathSync.native expands it to the real long path.\n // It also resolves symlinked temp roots (e.g. macOS /var -> /private/var).\n // If the file does not exist yet, fall through with the resolve()'d path so the\n // subsequent read/import throws the real not-found error.\n try {\n modulePath = realpathSync.native(modulePath);\n } catch {\n /* keep the resolve()'d path */\n }\n\n if (modulePath.endsWith(\".json\")) {\n const text = readFileSync(modulePath, \"utf8\");\n const config = JSON.parse(text) as unknown;\n const connector = await withConnectorPackageMetadata(\n readConnectorPackageMetadataNearFile(modulePath),\n async () => defineConnector(config as Parameters<typeof defineConnector>[0]),\n );\n return { connector, modulePath };\n }\n\n // .mjs / .js — dynamic ESM import. pathToFileURL keeps Windows paths valid.\n const moduleUrl = pathToFileURL(modulePath).href;\n const connector = await withConnectorPackageMetadata(\n readConnectorPackageMetadataNearFile(modulePath),\n async () => {\n const mod = (await import(/* @vite-ignore */ moduleUrl)) as {\n default?: unknown;\n };\n const exported = mod.default;\n if (exported == null) {\n throw new Error(\n `Connector module has no default export: ${modulePath}`,\n );\n }\n return isResolvedConnector(exported)\n ? exported\n : defineConnector(exported as Parameters<typeof defineConnector>[0]);\n },\n );\n return { connector, modulePath };\n}\n\n/**\n * Strip any function-valued `hooks` from per-platform overrides so the result\n * is JSON-serializable. A boolean `hooks` override is preserved; an object\n * override is dropped (it can only carry handler functions, which are not\n * serializable). `nativeHooks` declarations are persisted HANDLER-LESS (event\n * name + matcher only) so meta-based inspection (doctor / health checks / the\n * hook CLI) can still see WHICH native events were declared — the live handlers\n * are re-imported from `modulePath` at runtime, exactly like normalized hooks.\n * Everything else on the override is kept verbatim — notably `configPatch`\n * declarations, which are pure JSON (key/value/reason/docsUrl, no functions)\n * and persist WHOLE so uninstall/doctor can reason about them even when the\n * source module is gone.\n */\nfunction serializablePlatforms(\n platforms: Partial<Record<PlatformId, PlatformOverride>>,\n): Partial<Record<PlatformId, PlatformOverride>> {\n const out: Partial<Record<PlatformId, PlatformOverride>> = {};\n for (const [id, override] of Object.entries(platforms) as [\n PlatformId,\n PlatformOverride | undefined,\n ][]) {\n if (!override) continue;\n const { hooks, nativeHooks, ...rest } = override;\n const clean: PlatformOverride = { ...rest };\n // Keep only a boolean hooks flag; object hooks carry handler functions.\n if (typeof hooks === \"boolean\") clean.hooks = hooks;\n if (nativeHooks && typeof nativeHooks === \"object\") {\n const stripped: Record<string, { matcher?: string }> = {};\n for (const [event, def] of Object.entries(nativeHooks)) {\n stripped[event] =\n typeof def?.matcher === \"string\" ? { matcher: def.matcher } : {};\n }\n // Cast: the persisted record deliberately omits the (non-serializable)\n // handler; consumers of meta-derived connectors never dispatch handlers.\n clean.nativeHooks = stripped as PlatformOverride[\"nativeHooks\"];\n }\n out[id] = clean;\n }\n return out;\n}\n\n/**\n * Persist a connector's serializable metadata to `connectorDir(id)/connector.json`.\n * Handlers are NOT serialized — they are re-imported from `modulePath` at runtime.\n * The optional `scope` (the install scope the caller deployed under) is persisted\n * so the runtime entrypoints can recover it and stamp it onto the HostCtx/event.\n * Returns the absolute path of the written record.\n */\nexport function registerConnector(\n connector: ResolvedConnector,\n modulePath: string,\n scope?: InstallScope,\n): string {\n const meta: RegisteredMeta = {\n id: connector.id,\n displayName: connector.displayName,\n version: connector.version,\n ...(connector.mcp ? { mcp: connector.mcp } : {}),\n modulePath: resolve(modulePath),\n telemetry: connector.telemetry,\n hookEvents: connector.hookEvents,\n hasServer: !!connector.server,\n server: connector.server ?? null,\n commands: connector.commands,\n skills: connector.skills,\n subagents: connector.subagents,\n memory: connector.memory,\n targets: connector.targets,\n platforms: serializablePlatforms(connector.platforms),\n // Persist the install scope when the caller supplied one (the installer\n // passes its install scope). Omitted from the record when undefined so an\n // ad-hoc register stays minimal and round-trips as \"no scope known\".\n ...(scope !== undefined ? { scope } : {}),\n };\n\n const dir = connectorDir(connector.id);\n const outPath = join(dir, \"connector.json\");\n assertNoSymlinkInPath(outPath);\n ensureDir(dir);\n writeFileSync(outPath, `${JSON.stringify(meta, null, 2)}\\n`, \"utf8\");\n return outPath;\n}\n\n/**\n * Deregister a connector by removing its DATA-dir record directory\n * (`connectorDir(id)`) recursively. This is the inverse of {@link registerConnector}:\n * registerConnector writes `connectorDir(id)/connector.json`, but per-target\n * uninstall only strips host-native registrations — it never removes this record,\n * leaving an orphan behind. Best-effort + guarded: returns the directory path and\n * whether it existed before removal.\n */\nexport function deregisterConnector(id: string): {\n removed: boolean;\n path: string;\n} {\n const dir = connectorDir(id);\n assertNoSymlinkInPath(dir);\n const existed = existsSync(dir);\n if (existed) rmSync(dir, { recursive: true, force: true });\n return { removed: existed, path: dir };\n}\n\n/**\n * Read the registered metadata record for `id`, or null if not registered or\n * the record is unreadable/corrupt.\n */\nexport function readRegisteredMeta(id: string): RegisteredMeta | null {\n const recordPath = join(connectorDir(id), \"connector.json\");\n if (!existsSync(recordPath)) return null;\n try {\n return JSON.parse(readFileSync(recordPath, \"utf8\")) as RegisteredMeta;\n } catch {\n return null;\n }\n}\n\n/**\n * Load the LIVE ResolvedConnector (with hook handlers) for a registered id by\n * re-importing its source module. Throws a clear error when the connector is\n * not registered or its source module no longer resolves to it.\n */\nexport async function loadRegisteredConnector(\n id: string,\n): Promise<ResolvedConnector> {\n const meta = readRegisteredMeta(id);\n if (!meta) {\n throw new Error(\n `Connector \"${id}\" is not registered (no record at ${join(connectorDir(id), \"connector.json\")}). ` +\n `Run an install/register step first.`,\n );\n }\n if (!meta.modulePath || !existsSync(meta.modulePath)) {\n throw new Error(\n `Connector \"${id}\" record points at a missing module: ${meta.modulePath}`,\n );\n }\n const { connector } = await loadConnectorFromPath(meta.modulePath);\n return connector;\n}\n\n/**\n * Build a handler-less ResolvedConnector from stored metadata. Suitable for\n * inspection/doctor where live hook handlers are not needed (and where the\n * source module may even be gone). `hooks` is empty; `hookEvents` is preserved.\n */\nexport function connectorFromMeta(meta: RegisteredMeta): ResolvedConnector {\n return {\n id: meta.id,\n displayName: meta.displayName,\n version: meta.version,\n ...(meta.mcp ? { mcp: meta.mcp } : {}),\n ...(meta.server ? { server: meta.server } : {}),\n hooks: {},\n hookEvents: meta.hookEvents ?? [],\n telemetry: meta.telemetry,\n commands: meta.commands ?? [],\n skills: meta.skills ?? [],\n subagents: meta.subagents ?? [],\n memory: meta.memory ?? [],\n // Actions carry live `run` handlers, so they are NOT serialized into the\n // record (like the statusline render). A handler-less meta-derived connector\n // gets [] — inspection/uninstall never dispatch action handlers, and the\n // BaseAdapter action default already tolerates an empty list.\n actions: [],\n platforms: meta.platforms ?? {},\n targets: meta.targets,\n };\n}\n\n/**\n * List every registered connector as a handler-less ResolvedConnector (read\n * from `connectorsDir()`). Used by doctor to health-check what is actually\n * installed, rather than guessing from the local working directory.\n */\nexport function listRegisteredConnectors(): ResolvedConnector[] {\n const dir = connectorsDir();\n if (!existsSync(dir)) return [];\n const out: ResolvedConnector[] = [];\n for (const entry of readdirSync(dir)) {\n const meta = readRegisteredMeta(entry);\n if (meta) out.push(connectorFromMeta(meta));\n }\n return out;\n}\n"],"mappings":";;;;;;;;;;;;;;AAgBA,SAAS,YAAY,aAAa,cAAc,cAAc,QAAQ,qBAAqB;AAC3F,SAAS,SAAS,YAAY,MAAM,eAAe;AACnD,SAAS,qBAAqB;AAsB9B,IAAM,mBAAmB;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AACF;AAsDO,SAAS,oBAAoB,UAAiC;AACnE,MAAI,MAAM,QAAQ,QAAQ;AAE1B,aAAS;AACP,eAAW,QAAQ,kBAAkB;AACnC,YAAM,YAAY,KAAK,KAAK,IAAI;AAChC,UAAI,WAAW,SAAS,EAAG,QAAO;AAAA,IACpC;AACA,UAAM,SAAS,QAAQ,GAAG;AAC1B,QAAI,WAAW,IAAK;AACpB,UAAM;A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AW,KAAK,aAAa,CAAC;AAAA,IAC9B,SAAS,KAAK;AAAA,EAChB;AACF;AAOO,SAAS,2BAAgD;AAC9D,QAAM,MAAM,cAAc;AAC1B,MAAI,CAAC,WAAW,GAAG,EAAG,QAAO,CAAC;AAC9B,QAAM,MAA2B,CAAC;AAClC,aAAW,SAAS,YAAY,GAAG,GAAG;AACpC,UAAM,OAAO,mBAAmB,KAAK;AACrC,QAAI,KAAM,KAAI,KAAK,kBAAkB,IAAI,CAAC;AAAA,EAC5C;AACA,SAAO;AACT;","names":["connector"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/usage/jsonl.ts"],"sourcesContent":["/**\n * usage/jsonl — tolerant JSONL / JSON readers + a file-mtime helper.\n *\n * Every reader is fail-open: a malformed line is skipped (never thrown), a\n * missing/unreadable file yields no rows. Mirrors the NdjsonStore.query and host\n * parser behavior — bad input degrades to empty, it does not crash a report.\n *\n * Ports tokscale sessions/utils.rs file_modified_timestamp_ms (mtime fallback)\n * and the per-line skip-malformed loop used by every JSONL parser.\n */\n\nimport { readFileSync, statSync } from \"node:fs\";\n\n/**\n * Parse a JSONL file into objects, skipping blank/malformed lines. Returns [] on\n * any read error (missing file, permissions). Each yielded value is whatever\n * `JSON.parse` produced — callers narrow it. Order matches the file.\n *\n * Returns an array (not a generator) so callers can index/slice; for the file\n * sizes here (session logs) a full read is acceptable, matching the Rust\n * BufReader-per-file approach.\n */\nexport function readJsonlLines(path: string): unknown[] {\n let text: string;\n try {\n text = readFileSync(path, \"utf8\");\n } catch {\n return [];\n }\n\n const out: unknown[] = [];\n for (const line of text.split(\"\\n\")) {\n const trimmed = line.trim();\n if (trimmed === \"\") continue;\n try {\n out.push(JSON.parse(trimmed));\n } catch {\n continue; // skip malformed line\n }\n }\n return out;\n}\n\n/**\n * Read and parse a whole JSON file. Returns undefined on any read/parse error\n * (the fail-open contract for JSON readers). Caller narrows the unknown result.\n */\nexport function readJsonFile(path: string): unknown {\n let text: string;\n try {\n text = readFileSync(path, \"utf8\");\n } catch {\n return undefined;\n }\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n\n/**\n * File modification time in epoch ms, used as a timestamp fallback when a log\n * line carries none. Port of file_modified_timestamp_ms: falls back to \"now\"\n * when the file cannot be stat'd so a row is never dropped for lack of a ts.\n */\nexport function fileMtimeMs(path: string): number {\n try {\n return Math.floor(statSync(path).mtimeMs);\n } catch {\n return Date.now();\n }\n}\n"],"mappings":";;;AAWA,SAAS,cAAc,gBAAgB;AAWhC,SAAS,eAAe,MAAyB;AACtD,MAAI;AACJ,MAAI;AACF,WAAO,aAAa,MAAM,MAAM;AAAA,EAClC,QAAQ;AACN,WAAO,CAAC;AAAA,EACV;AAEA,QAAM,MAAiB,CAAC;AACxB,aAAW,QAAQ,KAAK,MAAM,IAAI,GAAG;AACnC,UAAM,UAAU,KAAK,KAAK;AAC1B,QAAI,YAAY,GAAI;AACpB,QAAI;AACF,UAAI,KAAK,KAAK,MAAM,OAAO,CAAC;AAAA,IAC9B,QAAQ;AACN;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAMO,SAAS,aAAa,MAAuB;AAClD,MAAI;AACJ,MAAI;AACF,WAAO,aAAa,MAAM,MAAM;AAAA,EAClC,QAAQ;AACN,WAAO;AAAA,EACT;AACA,MAAI;AACF,WAAO,KAAK,MAAM,IAAI;AAAA,EACxB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAOO,SAAS,YAAY,MAAsB;AAChD,MAAI;AACF,WAAO,KAAK,MAAM,SAAS,IAAI,EAAE,OAAO;AAAA,EAC1C,QAAQ;AACN,WAAO,KAAK,IAAI;AAAA,EAClB;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/host-paths.ts"],"sourcesContent":["// ─────────────────────────────────────────────────────────────────────────\n// host-paths.ts — shared OS user-config-dir base resolvers\n//\n// Several adapters resolve the SAME per-OS \"user config base\" directory with\n// the same logic (XDG on posix; %APPDATA%/%LOCALAPPDATA% on Windows, each with\n// a ~/AppData fallback). These helpers consolidate that resolution so the\n// per-host adapters only carry their host-specific SUFFIX. The result is\n// byte-identical for absolute/clean config-dir inputs (the realistic case);\n// a non-canonical env value (relative, trailing slash, `..`) is normalized via\n// `resolve()` rather than passed through bare — a safe canonicalization.\n//\n// Scope note: these are the USER-CONFIG-DIR bases (where a host keeps its\n// settings/config files). The agent-connector *data-root* paths (our own\n// per-project state) live in core/paths.ts — do NOT conflate the two.\n//\n// Host-specific config-home resolvers that are SHARED across modules (e.g.\n// `codexConfigHome`, used by BOTH the codex adapter and marketplace detection)\n// DO live here, so the writer and the probe can never disagree on the dir.\n// Single-caller host envs (PI_CODING_AGENT_DIR, OPENCLAW_*) stay in their own\n// adapter.\n// ─────────────────────────────────────────────────────────────────────────\n\nimport { homedir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\n\n/** $XDG_CONFIG_HOME when set & non-empty, else ~/.config. */\nexport function xdgConfigHome(): string {\n const xdg = process.env.XDG_CONFIG_HOME;\n return xdg && xdg.trim() !== \"\" ? resolve(xdg) : join(homedir(), \".config\");\n}\n\n/** %APPDATA% (Roaming) when set & non-empty, else ~/AppData/Roaming. */\nexport function roamingAppData(): string {\n const appData = process.env.APPDATA;\n return appData && appData.trim() !== \"\"\n ? resolve(appData)\n : join(homedir(), \"AppData\", \"Roaming\");\n}\n\n/** %LOCALAPPDATA% when set & non-empty, else ~/AppData/Local. */\nexport function localAppData(): string {\n const local = process.env.LOCALAPPDATA;\n return local && local.trim() !== \"\"\n ? resolve(local)\n : join(homedir(), \"AppData\", \"Local\");\n}\n\n/** Codex's config home: $CODEX_HOME (tilde-expanded, then resolved) when set\n * & non-empty, else ~/.codex. Shared by the codex adapter (writer) and the\n * marketplace detection probe so they never disagree on the config dir. */\nexport function codexConfigHome(): string {\n const env = process.env.CODEX_HOME;\n if (env && env.trim() !== \"\") {\n if (env.startsWith(\"~\")) return join(homedir(), env.replace(/^~[/\\\\]?/, \"\"));\n return resolve(env);\n }\n return join(homedir(), \".codex\");\n}\n"],"mappings":";;;AAsBA,SAAS,eAAe;AACxB,SAAS,MAAM,eAAe;AAGvB,SAAS,gBAAwB;AACtC,QAAM,MAAM,QAAQ,IAAI;AACxB,SAAO,OAAO,IAAI,KAAK,MAAM,KAAK,QAAQ,GAAG,IAAI,KAAK,QAAQ,GAAG,SAAS;AAC5E;AAGO,SAAS,iBAAyB;AACvC,QAAM,UAAU,QAAQ,IAAI;AAC5B,SAAO,WAAW,QAAQ,KAAK,MAAM,KACjC,QAAQ,OAAO,IACf,KAAK,QAAQ,GAAG,WAAW,SAAS;AAC1C;AAGO,SAAS,eAAuB;AACrC,QAAM,QAAQ,QAAQ,IAAI;AAC1B,SAAO,SAAS,MAAM,KAAK,MAAM,KAC7B,QAAQ,KAAK,IACb,KAAK,QAAQ,GAAG,WAAW,OAAO;AACxC;AAKO,SAAS,kBAA0B;AACxC,QAAM,MAAM,QAAQ,IAAI;AACxB,MAAI,OAAO,IAAI,KAAK,MAAM,IAAI;AAC5B,QAAI,IAAI,WAAW,GAAG,EAAG,QAAO,KAAK,QAAQ,GAAG,IAAI,QAAQ,YAAY,EAAE,CAAC;AAC3E,WAAO,QAAQ,GAAG;AAAA,EACpB;AACA,SAAO,KAAK,QAAQ,GAAG,QAAQ;AACjC;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/managed-block.ts"],"sourcesContent":["/**\n * core/managed-block — the marker-fenced MANAGED BLOCK engine behind the\n * `memory` content surface.\n *\n * Memory/rules files (AGENTS.md, CLAUDE.md, GEMINI.md, …) are SHARED,\n * user-authored files — unlike commands/skills/subagents, agent-connector does\n * not own them. Every write therefore goes through this one module, which\n * implements idempotent, hash-stamped, uninstall-reversible blocks:\n *\n * <!-- agent-connector:begin <connectorId>/<name> hash=<sha256-12> -->\n * <!-- Managed by agent-connector for \"<connectorId>\". Do not edit … -->\n * …guidance…\n * <!-- agent-connector:end <connectorId>/<name> -->\n *\n * Design rules (each grounded in surveyed prior art — ansible blockinfile,\n * conda init, OMC mergeClaudeMd, Ruler, doctoc):\n * • UNIQUE marker per block: the blockId (`<connectorId>/<entryName>`) lives\n * ON the marker line, so multiple connectors coexist in one file and each\n * update path only ever touches its own pair (ansible's documented\n * multi-block rule). The shared `agent-connector` namespace token lets\n * doctor/uninstall enumerate every block with one scan.\n * • `hash=` is the first 12 hex chars of sha256 over the NORMALIZED inner\n * region (CRLF→LF + trim — stable under prettier/EOL converters): O(1)\n * idempotence (unchanged → skip, no mtime/git churn) and tamper detection\n * (actual inner hash ≠ recorded ⇒ the user edited inside the block ⇒ warn,\n * never clobber without an explicit force).\n * • IN-PLACE replacement (conda semantics): zero bytes outside the marker\n * pair ever change — no move-to-top, no user blank-line reflow.\n * • Line-anchored matching that explicitly tolerates `\\r` line ends and a\n * FENCE-AWARE scanner (markers quoted inside ``` / ~~~ code fences never\n * match) — fixes the CRLF duplicate-block and quoted-marker classes.\n * • First-begin / FIRST-end-after pairing (never last-end): a missing end\n * marker must not swallow a sibling connector's block.\n * • HTML-comment markers are CORRECT for CLAUDE.md: Claude Code strips HTML\n * comments from CLAUDE.md before context injection (verified against docs\n * and the 2.1.172 binary), so the markers and the do-not-edit notice are\n * INVISIBLE to the model there while remaining fully parseable by us for\n * sync/doctor/uninstall. On AGENTS.md hosts (which inline the whole file\n * into the prompt) the short notice doubles as an in-prompt \"do not edit\"\n * instruction to the host's own agent. A `commentStyle: \"hash\"` variant\n * exists for future non-markdown targets (`#`-prefixed marker lines).\n *\n * The module also owns the per-connector MEMORY OWNERSHIP LEDGER\n * (`connectorDir(id)/memory-state.json`): the markers in the file remain the\n * source of truth for uninstall (a teammate's machine with no ledger still\n * uninstalls via the prefix scan); the ledger only adds the created-vs-modified\n * distinction (file deletion rights) and doctor diagnostics.\n */\n\nimport { createHash } from \"node:crypto\";\nimport {\n chmodSync,\n copyFileSync,\n existsSync,\n readFileSync,\n renameSync,\n rmSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { basename, dirname, join } from \"node:path\";\n\nimport { assertNoSymlinkInPath, backupsDir, connectorDir, ensureDir } from \"./paths.js\";\n\n// ─────────────────────────────────────────────────────────────────────────\n// Grammar constants (shared with defineConnector's content validation)\n// ─────────────────────────────────────────────────────────────────────────\n\n/** Literal begin token. Connector memory content MUST NOT contain it. */\nexport const MANAGED_BLOCK_BEGIN_TOKEN = \"agent-connector:begin\";\n/** Literal end token. Connector memory content MUST NOT contain it. */\nexport const MANAGED_BLOCK_END_TOKEN = \"agent-connector:end\";\n\n/** Hard cap on one memory entry's content (ConnectorConfigError above this). */\nexport const MEMORY_CONTENT_HARD_CAP_BYTES = 16 * 1024;\n/**\n * Soft per-entry budget — exceeded → install-time `warn` ChangeRecord (memory\n * files are injected into EVERY prompt of EVERY session on the host; codex\n * additionally caps combined project docs at 32 KiB).\n */\nexport const MEMORY_CONTENT_SOFT_BUDGET_BYTES = 4 * 1024;\n\n/** Marker comment style: HTML comments (default, all v1 markdown targets) or `#` lines. */\nexport type BlockCommentStyle = \"html\" | \"hash\";\n\n// ─────────────────────────────────────────────────────────────────────────\n// Hashing / rendering\n// ─────────────────────────────────────────────────────────────────────────\n\n/** CRLF/CR → LF + trim: the normalization both hashing sides use. */\nfunction normalizeInner(s: string): string {\n return s.replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\").trim();\n}\n\n/** First 12 hex chars of sha256 over the NORMALIZED inner region. */\nexport function hashBlockContent(inner: string): string {\n return createHash(\"sha256\").update(normalizeInner(inner), \"utf8\").digest(\"hex\").slice(0, 12);\n}\n\n/** The conda-style in-block warning, adapted for the LLM era (see header). */\nfunction defaultNotice(connectorId: string): string {\n return (\n `Managed by agent-connector for \"${connectorId}\". Do not edit between these markers: ` +\n `run your connector package's upgrade/sync command to rewrite this block; ` +\n `run its uninstall command to remove it ` +\n `(framework fallback: \\`agent-connector uninstall ${connectorId}\\`).`\n );\n}\n\nfunction beginLine(blockId: string, hash: string, style: BlockCommentStyle): string {\n return style === \"hash\"\n ? `# ${MANAGED_BLOCK_BEGIN_TOKEN} ${blockId} hash=${hash}`\n : `<!-- ${MANAGED_BLOCK_BEGIN_TOKEN} ${blockId} hash=${hash} -->`;\n}\n\n/** END line is a fixed exact string (no hash) so a content change never strands it. */\nfunction endLine(blockId: string, style: BlockCommentStyle): string {\n return style === \"hash\"\n ? `# ${MANAGED_BLOCK_END_TOKEN} ${blockId}`\n : `<!-- ${MANAGED_BLOCK_END_TOKEN} ${blockId} -->`;\n}\n\nfunction noticeLine(notice: string, style: BlockCommentStyle): string {\n return style === \"hash\" ? `# ${notice}` : `<!-- ${notice} -->`;\n}\n\nexport interface RenderBlockOptions {\n /** `<connectorId>/<entryName>` (or the reserved `_shared/<name>` bridge prefix). */\n blockId: string;\n /** Connector id named in the default do-not-edit notice line. */\n connectorId: string;\n /** The guidance payload (plain markdown; normalized + trimmed on emit). */\n content: string;\n /** Marker comment style; default \"html\". */\n commentStyle?: BlockCommentStyle;\n /** Override the default notice line TEXT (without comment delimiters). */\n notice?: string;\n}\n\n/**\n * Render the block as LOGICAL lines (no EOL chars). The recorded `hash=`\n * covers the full inner region (notice line + content) so install and scan\n * compare like for like.\n */\nexport function renderBlockLines(opts: RenderBlockOptions): string[] {\n const style = opts.commentStyle ?? \"html\";\n const inner = [\n noticeLine(opts.notice ?? defaultNotice(opts.connectorId), style),\n ...normalizeInner(opts.content).split(\"\\n\"),\n ];\n const hash = hashBlockContent(inner.join(\"\\n\"));\n return [beginLine(opts.blockId, hash, style), ...inner, endLine(opts.blockId, style)];\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// Scanning (fence-aware, line-anchored, CRLF-tolerant)\n// ─────────────────────────────────────────────────────────────────────────\n\n// Both comment styles are RECOGNIZED in one pass (a file may legitimately mix\n// styles only across rewrites; emission always uses the requested style).\nconst BEGIN_RE =\n /^(?:<!--\\s+agent-connector:begin\\s+(\\S+)\\s+hash=([0-9a-f]{12})\\s+-->|#\\s+agent-connector:begin\\s+(\\S+)\\s+hash=([0-9a-f]{12}))\\s*$/;\nconst END_RE = /^(?:<!--\\s+agent-connector:end\\s+(\\S+)\\s+-->|#\\s+agent-connector:end\\s+(\\S+))\\s*$/;\n\ninterface MarkerEvent {\n kind: \"begin\" | \"end\";\n blockId: string;\n /** Recorded hash (begin markers only). */\n hash?: string;\n /** Line index into the logical-lines array. */\n index: number;\n}\n\n/** Strip ONE trailing `\\r` — `raw.split(\"\\n\")` leaves it on CRLF files. */\nfunction stripCr(line: string): string {\n return line.endsWith(\"\\r\") ? line.slice(0, -1) : line;\n}\n\n/**\n * Scan logical lines for marker events, tracking ``` / ~~~ fence state so a\n * marker QUOTED inside a fenced code block never matches (the OMC class of\n * false positives, eliminated rather than just reduced).\n */\nfunction scanMarkers(logical: string[]): MarkerEvent[] {\n const events: MarkerEvent[] = [];\n let fence: { char: string; len: number } | null = null;\n for (let i = 0; i < logical.length; i++) {\n const line = logical[i]!;\n if (fence) {\n const close = line.match(/^ {0,3}(`{3,}|~{3,})\\s*$/);\n if (close && close[1]![0] === fence.char && close[1]!.length >= fence.len) fence = null;\n continue;\n }\n const open = line.match(/^ {0,3}(`{3,}|~{3,})/);\n if (open) {\n fence = { char: open[1]![0]!, len: open[1]!.length };\n continue;\n }\n const b = line.match(BEGIN_RE);\n if (b) {\n events.push({ kind: \"begin\", blockId: (b[1] ?? b[3])!, hash: (b[2] ?? b[4])!, index: i });\n continue;\n }\n const e = line.match(END_RE);\n if (e) events.push({ kind: \"end\", blockId: (e[1] ?? e[2])!, index: i });\n }\n return events;\n}\n\n/**\n * Logical lines of `raw` that sit OUTSIDE ``` / ~~~ code fences — for host\n * probes that must ignore quoted examples (e.g. the claude-code `@AGENTS.md`\n * import detection). Fence lines themselves are excluded.\n */\nexport function linesOutsideFences(raw: string): string[] {\n const body = raw.startsWith(\"\\uFEFF\") ? raw.slice(1) : raw;\n const logical = body.split(\"\\n\").map(stripCr);\n const out: string[] = [];\n let fence: { char: string; len: number } | null = null;\n for (const line of logical) {\n if (fence) {\n const close = line.match(/^ {0,3}(`{3,}|~{3,})\\s*$/);\n if (close && close[1]![0] === fence.char && close[1]!.length >= fence.len) fence = null;\n continue;\n }\n const open = line.match(/^ {0,3}(`{3,}|~{3,})/);\n if (open) {\n fence = { char: open[1]![0]!, len: open[1]!.length };\n continue;\n }\n out.push(line);\n }\n return out;\n}\n\ninterface BlockPair {\n blockId: string;\n begin: MarkerEvent;\n end: MarkerEvent;\n}\n\n/**\n * Pair markers per blockId: first begin, then the FIRST end at-or-after it.\n * A nested begin for the SAME id (inside an open pair) is treated as inner\n * content; unpaired markers are returned as strays. Per-id state means a\n * missing end for connector A can never swallow connector B's block.\n */\nfunction pairMarkers(events: MarkerEvent[]): { pairs: BlockPair[]; strays: MarkerEvent[] } {\n const open = new Map<string, MarkerEvent>();\n const pairs: BlockPair[] = [];\n const strays: MarkerEvent[] = [];\n for (const ev of events) {\n if (ev.kind === \"begin\") {\n if (!open.has(ev.blockId)) open.set(ev.blockId, ev);\n // else: a begin inside an open pair — inner content / abuse; the hash\n // check will flag the pair as drifted rather than guessing boundaries.\n } else {\n const b = open.get(ev.blockId);\n if (b) {\n pairs.push({ blockId: ev.blockId, begin: b, end: ev });\n open.delete(ev.blockId);\n } else {\n strays.push(ev);\n }\n }\n }\n for (const b of open.values()) strays.push(b);\n return { pairs, strays };\n}\n\n/** One discovered block (for doctor / refcount / uninstall enumeration). */\nexport interface ManagedBlockInfo {\n blockId: string;\n /** The hash recorded on the begin marker line. */\n recordedHash: string;\n /** Hash of the actual normalized inner region as found on disk. */\n actualHash: string;\n /** True when recordedHash ≠ actualHash — the user edited inside the block. */\n drifted: boolean;\n beginLine: number;\n endLine: number;\n}\n\n/** Enumerate every complete agent-connector block in `raw` (namespace scan). */\nexport function listManagedBlocks(raw: string): ManagedBlockInfo[] {\n const body = raw.startsWith(\"\\uFEFF\") ? raw.slice(1) : raw;\n const logical = body.split(\"\\n\").map(stripCr);\n const { pairs } = pairMarkers(scanMarkers(logical));\n return pairs.map((p) => {\n const inner = logical.slice(p.begin.index + 1, p.end.index).join(\"\\n\");\n const actualHash = hashBlockContent(inner);\n const recordedHash = p.begin.hash ?? \"\";\n return {\n blockId: p.blockId,\n recordedHash,\n actualHash,\n drifted: recordedHash !== actualHash,\n beginLine: p.begin.index,\n endLine: p.end.index,\n };\n });\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// Pure text upsert / removal\n// ─────────────────────────────────────────────────────────────────────────\n\nexport interface UpsertBlockOptions extends RenderBlockOptions {\n /** Overwrite a USER-EDITED (drifted) block. Default false → warn + leave intact. */\n force?: boolean;\n}\n\nexport interface BlockTextResult {\n /** Resulting full text (=== input when nothing changed). */\n text: string;\n action: \"create\" | \"update\" | \"skip\" | \"warn\";\n detail: string;\n changed: boolean;\n /**\n * True when the rewrite was DESTRUCTIVE-ADJACENT (force-overwrote a drifted\n * block, collapsed duplicate pairs, or stripped stray markers) — the file\n * wrapper writes a timestamped backup before persisting such a change.\n */\n recovered: boolean;\n /** Hash of the (new) rendered inner region — recorded in the ledger. */\n hash: string;\n}\n\n/** Detect the file's dominant EOL; new/replaced lines are emitted with it. */\nfunction detectEol(body: string): \"\\n\" | \"\\r\\n\" {\n const crlf = (body.match(/\\r\\n/g) ?? []).length;\n const total = (body.match(/\\n/g) ?? []).length;\n return crlf > 0 && crlf >= total - crlf ? \"\\r\\n\" : \"\\n\";\n}\n\n/** Add `\\r` to logical lines when the file is CRLF (joined with \"\\n\" later). */\nfunction withEol(lines: string[], eol: \"\\n\" | \"\\r\\n\"): string[] {\n return eol === \"\\r\\n\" ? lines.map((l) => `${l}\\r`) : lines;\n}\n\n/**\n * Strip trailing newline(s) + whitespace-only line tails WITHOUT touching\n * trailing spaces on the last content line (bytes outside our block).\n */\nfunction trimTrailingBlank(body: string): string {\n let out = body;\n for (;;) {\n const m = out.match(/\\r?\\n[ \\t]*$/);\n if (!m) return out;\n out = out.slice(0, out.length - m[0].length);\n }\n}\n\n/** Append the rendered block at EOF with exactly ONE blank separator line. */\nfunction appendBlock(body: string, blockLines: string[], eol: \"\\n\" | \"\\r\\n\"): string {\n const blockText = blockLines.join(eol) + eol;\n if (body.trim() === \"\") return blockText;\n return trimTrailingBlank(body) + eol + eol + blockText;\n}\n\n/**\n * Idempotent upsert of one managed block into `raw` (pure; no I/O).\n * See the module header for the full algorithm contract.\n */\nexport function upsertBlockInText(raw: string, opts: UpsertBlockOptions): BlockTextResult {\n const bom = raw.startsWith(\"\\uFEFF\");\n const body = bom ? raw.slice(1) : raw;\n const eol = detectEol(body);\n const lines = body.split(\"\\n\"); // elements keep a trailing \"\\r\" on CRLF files\n const logical = lines.map(stripCr);\n\n const events = scanMarkers(logical).filter((e) => e.blockId === opts.blockId);\n const { pairs, strays } = pairMarkers(events);\n\n const newLines = renderBlockLines(opts);\n const newHash = hashBlockContent(newLines.slice(1, -1).join(\"\\n\"));\n const finish = (text: string, r: Omit<BlockTextResult, \"text\" | \"hash\">): BlockTextResult => ({\n text: bom ? `\\uFEFF${text}` : text,\n hash: newHash,\n ...r,\n });\n\n if (pairs.length > 0) {\n const { begin, end } = pairs[0]!;\n const recorded = begin.hash ?? \"\";\n const actualHash = hashBlockContent(logical.slice(begin.index + 1, end.index).join(\"\\n\"));\n const drifted = actualHash !== recorded;\n\n if (drifted && !opts.force) {\n return finish(body, {\n action: \"warn\",\n detail:\n `block ${opts.blockId} was edited inside the markers ` +\n `(recorded hash ${recorded}, found ${actualHash}); left untouched — ` +\n `re-run with --force to overwrite the in-block edits`,\n changed: false,\n recovered: false,\n });\n }\n\n const duplicates = pairs.slice(1);\n const needsWrite =\n drifted || recorded !== newHash || duplicates.length > 0 || strays.length > 0;\n if (!needsWrite) {\n return finish(body, {\n action: \"skip\",\n detail: `block ${opts.blockId} already up to date (hash ${newHash})`,\n changed: false,\n recovered: false,\n });\n }\n\n // Build the deletion set: the canonical pair region (replaced in place),\n // duplicate pairs (+ ONE adjacent blank line each), and stray marker LINES.\n const del = new Set<number>();\n for (let i = begin.index; i <= end.index; i++) del.add(i);\n for (const dup of duplicates) {\n for (let i = dup.begin.index; i <= dup.end.index; i++) del.add(i);\n reclaimBlankLine(logical, dup.begin.index, dup.end.index, del, lines.length);\n }\n for (const s of strays) del.add(s.index);\n\n const out: string[] = [];\n for (let i = 0; i < lines.length; i++) {\n if (i === begin.index) out.push(...withEol(newLines, eol));\n if (!del.has(i)) out.push(lines[i]!);\n }\n const notes: string[] = [];\n if (drifted) notes.push(\"in-block edits overwritten (--force; backup taken)\");\n if (duplicates.length > 0) notes.push(`${duplicates.length} duplicate pair(s) collapsed`);\n if (strays.length > 0) notes.push(`${strays.length} stray marker line(s) removed`);\n return finish(out.join(\"\\n\"), {\n action: \"update\",\n detail:\n `block ${opts.blockId} updated (hash ${recorded || \"?\"} → ${newHash})` +\n (notes.length > 0 ? `; ${notes.join(\"; \")}` : \"\"),\n changed: true,\n recovered: drifted || duplicates.length > 0 || strays.length > 0,\n });\n }\n\n if (strays.length > 0) {\n // Corruption recovery: strip ONLY the stray marker line(s) (never the text\n // between guessed boundaries), then proceed as not-found.\n const del = new Set(strays.map((s) => s.index));\n const cleaned = lines.filter((_, i) => !del.has(i)).join(\"\\n\");\n return finish(appendBlock(cleaned, newLines, eol), {\n action: \"create\",\n detail:\n `block ${opts.blockId} appended after recovery: ${strays.length} stray ` +\n `marker line(s) removed (backup taken)`,\n changed: true,\n recovered: true,\n });\n }\n\n // Not found → append at EOF (one blank separator; whole file when empty).\n return finish(appendBlock(body, newLines, eol), {\n action: \"create\",\n detail: `block ${opts.blockId} appended (hash ${newHash})`,\n changed: true,\n recovered: false,\n });\n}\n\n/**\n * Mark ONE blank line adjacent to a removed begin..end region for deletion\n * (prefer the line before; never the post-final-newline \"\" sentinel).\n */\nfunction reclaimBlankLine(\n logical: string[],\n beginIdx: number,\n endIdx: number,\n del: Set<number>,\n lineCount: number,\n): void {\n const before = beginIdx - 1;\n if (before >= 0 && !del.has(before) && logical[before]!.trim() === \"\") {\n del.add(before);\n return;\n }\n const after = endIdx + 1;\n // The final \"\" element of split(\"\\n\") on a newline-terminated file is the\n // trailing-newline sentinel, not a blank line — leave it alone.\n const isSentinel = after === lineCount - 1 && logical[after] === \"\";\n if (after < lineCount && !isSentinel && !del.has(after) && logical[after]!.trim() === \"\") {\n del.add(after);\n }\n}\n\nexport interface RemoveBlocksOptions {\n /** Remove the block with EXACTLY this id… */\n blockId?: string;\n /** …or every block whose id starts with this prefix (e.g. `<connectorId>/`). */\n blockIdPrefix?: string;\n}\n\nexport interface RemoveRecord {\n blockId: string;\n action: \"remove\" | \"warn\";\n detail: string;\n}\n\nexport interface RemoveBlocksResult {\n text: string;\n changed: boolean;\n records: RemoveRecord[];\n /** True when the remaining text is whitespace-only (file-deletion candidate). */\n fileNowEmpty: boolean;\n /** True when a drifted block was removed or stray markers were stripped. */\n recovered: boolean;\n}\n\n/**\n * Remove every matching managed block (begin..end inclusive + at most ONE\n * adjacent blank separator line — no blank-line accumulation across cycles).\n * Drifted blocks are removed WITH a warn (uninstall intent is explicit; the\n * file wrapper backs the file up first). Stray matching markers are stripped\n * line-only with a warn. Pure; no I/O.\n */\nexport function removeBlocksFromText(raw: string, match: RemoveBlocksOptions): RemoveBlocksResult {\n const bom = raw.startsWith(\"\\uFEFF\");\n const body = bom ? raw.slice(1) : raw;\n const lines = body.split(\"\\n\");\n const logical = lines.map(stripCr);\n\n const matches = (id: string): boolean =>\n (match.blockId !== undefined && id === match.blockId) ||\n (match.blockIdPrefix !== undefined && id.startsWith(match.blockIdPrefix));\n\n const { pairs, strays } = pairMarkers(scanMarkers(logical));\n const targetPairs = pairs.filter((p) => matches(p.blockId));\n const targetStrays = strays.filter((s) => matches(s.blockId));\n\n if (targetPairs.length === 0 && targetStrays.length === 0) {\n return { text: raw, changed: false, records: [], fileNowEmpty: false, recovered: false };\n }\n\n const del = new Set<number>();\n const records: RemoveRecord[] = [];\n let recovered = false;\n\n for (const p of targetPairs) {\n const recorded = p.begin.hash ?? \"\";\n const actualHash = hashBlockContent(\n logical.slice(p.begin.index + 1, p.end.index).join(\"\\n\"),\n );\n for (let i = p.begin.index; i <= p.end.index; i++) del.add(i);\n reclaimBlankLine(logical, p.begin.index, p.end.index, del, lines.length);\n if (actualHash !== recorded) {\n recovered = true;\n records.push({\n blockId: p.blockId,\n action: \"warn\",\n detail:\n `block ${p.blockId} had in-block edits (recorded hash ${recorded}, found ` +\n `${actualHash}); removed anyway (backup taken)`,\n });\n }\n records.push({ blockId: p.blockId, action: \"remove\", detail: `block ${p.blockId} removed` });\n }\n for (const s of targetStrays) {\n del.add(s.index);\n recovered = true;\n records.push({\n blockId: s.blockId,\n action: \"warn\",\n detail: `stray ${s.kind} marker for ${s.blockId} removed (marker line only)`,\n });\n }\n\n const text = lines.filter((_, i) => !del.has(i)).join(\"\\n\");\n return {\n text: bom ? `\\uFEFF${text}` : text,\n changed: true,\n records,\n fileNowEmpty: text.trim() === \"\",\n recovered,\n };\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// File-level wrappers (atomic write, backups, dry-run)\n// ─────────────────────────────────────────────────────────────────────────\n\nexport interface BlockFileChange {\n action: \"create\" | \"update\" | \"skip\" | \"warn\" | \"remove\";\n path: string;\n detail: string;\n /** True when the FILE did not exist and this upsert created it (ledger fact). */\n createdFile: boolean;\n /** Set when a pre-mutation backup was written (destructive/recovery paths only). */\n backupPath?: string;\n /** Hash of the rendered inner region (ledger / doctor). */\n hash: string;\n}\n\n/** Timestamped copy into backupsDir(); best-effort (null on failure). */\nfunction backupFile(path: string): string | null {\n try {\n ensureDir(backupsDir());\n const stamp = new Date().toISOString().replace(/[:.]/g, \"-\");\n const dest = join(backupsDir(), `memory-${stamp}-${basename(path)}`);\n copyFileSync(path, dest);\n return dest;\n } catch {\n return null;\n }\n}\n\n/**\n * Atomic write: temp file in the SAME directory + rename, preserving the\n * destination's mode. Shrinks (does not eliminate) the read-modify-write race\n * with hosts that append to memory files mid-session (Claude `#` quick-memory).\n */\nfunction atomicWriteFile(path: string, text: string): void {\n const dir = dirname(path);\n ensureDir(dir);\n const tmp = join(dir, `.${basename(path)}.ac-tmp-${process.pid}-${Date.now()}`);\n try {\n writeFileSync(tmp, text, \"utf8\");\n try {\n chmodSync(tmp, statSync(path).mode);\n } catch {\n /* destination absent — default mode is fine */\n }\n renameSync(tmp, path);\n } catch (err) {\n rmSync(tmp, { force: true });\n throw err;\n }\n}\n\n/**\n * Upsert one managed block into the file at `path` (created when absent).\n * Re-reads immediately before computing+writing; honors dryRun (the action is\n * computed and reported, nothing is written).\n */\nexport function upsertManagedBlockFile(\n path: string,\n opts: UpsertBlockOptions & { dryRun: boolean },\n): BlockFileChange {\n let raw: string | null = null;\n if (existsSync(path)) {\n try {\n raw = readFileSync(path, \"utf8\");\n } catch {\n return {\n action: \"warn\",\n path,\n detail: `cannot read ${path}; memory block ${opts.blockId} not written`,\n createdFile: false,\n hash: \"\",\n };\n }\n }\n\n if (raw === null) {\n const lines = renderBlockLines(opts);\n const hash = hashBlockContent(lines.slice(1, -1).join(\"\\n\"));\n if (!opts.dryRun) atomicWriteFile(path, `${lines.join(\"\\n\")}\\n`);\n return {\n action: \"create\",\n path,\n detail: `created ${basename(path)} with block ${opts.blockId} (hash ${hash})`,\n createdFile: true,\n hash,\n };\n }\n\n const res = upsertBlockInText(raw, opts);\n const change: BlockFileChange = {\n action: res.action,\n path,\n detail: res.detail,\n createdFile: false,\n hash: res.hash,\n };\n if (res.changed && !opts.dryRun) {\n if (res.recovered) {\n const backup = backupFile(path);\n if (backup) change.backupPath = backup;\n }\n atomicWriteFile(path, res.text);\n }\n return change;\n}\n\n/**\n * Remove every matching managed block from the file at `path`. Missing file or\n * no matching markers → a single idempotent \"skip\". When the remaining content\n * is whitespace-only AND `deleteFileIfCreated` is true (the ledger recorded\n * that agent-connector created this file), the file itself is deleted (Ruler\n * revert semantics: delete only what we created).\n */\nexport function removeManagedBlocksFile(\n path: string,\n match: RemoveBlocksOptions,\n opts: { dryRun: boolean; deleteFileIfCreated?: boolean },\n): BlockFileChange[] {\n if (!existsSync(path)) {\n return [\n {\n action: \"skip\",\n path,\n detail: `${basename(path)} absent; nothing to remove`,\n createdFile: false,\n hash: \"\",\n },\n ];\n }\n let raw: string;\n try {\n raw = readFileSync(path, \"utf8\");\n } catch {\n return [\n {\n action: \"warn\",\n path,\n detail: `cannot read ${path}; managed blocks left in place`,\n createdFile: false,\n hash: \"\",\n },\n ];\n }\n\n const res = removeBlocksFromText(raw, match);\n if (!res.changed) {\n return [\n {\n action: \"skip\",\n path,\n detail: `no agent-connector blocks matching ${match.blockId ?? match.blockIdPrefix ?? \"?\"} in ${basename(path)}`,\n createdFile: false,\n hash: \"\",\n },\n ];\n }\n\n const changes: BlockFileChange[] = [];\n let backupPath: string | undefined;\n if (!opts.dryRun) {\n if (res.recovered) backupPath = backupFile(path) ?? undefined;\n if (res.fileNowEmpty && opts.deleteFileIfCreated) {\n rmSync(path, { force: true });\n } else {\n atomicWriteFile(path, res.text);\n }\n }\n for (const r of res.records) {\n changes.push({\n action: r.action,\n path,\n detail: r.detail,\n createdFile: false,\n hash: \"\",\n ...(backupPath && r.action === \"warn\" ? { backupPath } : {}),\n });\n }\n if (res.fileNowEmpty && opts.deleteFileIfCreated) {\n changes.push({\n action: \"remove\",\n path,\n detail: `${basename(path)} deleted (agent-connector created it; only whitespace remained)`,\n createdFile: false,\n hash: \"\",\n });\n }\n return changes;\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// Memory ownership ledger — connectorDir(id)/memory-state.json\n// ─────────────────────────────────────────────────────────────────────────\n\nexport interface MemoryLedgerTarget {\n platform: string;\n scope: string;\n path: string;\n blockId: string;\n /** True when agent-connector CREATED the file (grants deletion rights). */\n createdFile: boolean;\n /** Inner-region hash we last wrote (doctor drift detection). */\n hash: string;\n}\n\nexport interface MemoryLedger {\n version: 1;\n targets: MemoryLedgerTarget[];\n}\n\nexport function memoryLedgerPath(connectorId: string): string {\n return join(connectorDir(connectorId), \"memory-state.json\");\n}\n\nexport function loadMemoryLedger(connectorId: string): MemoryLedger {\n const p = memoryLedgerPath(connectorId);\n if (!existsSync(p)) return { version: 1, targets: [] };\n try {\n const parsed = JSON.parse(readFileSync(p, \"utf8\")) as MemoryLedger;\n if (parsed && Array.isArray(parsed.targets)) return { version: 1, targets: parsed.targets };\n } catch {\n /* corrupt → fresh ledger; the markers remain the source of truth */\n }\n return { version: 1, targets: [] };\n}\n\n/** Persist the ledger; an EMPTY ledger deletes the file (no orphan state). */\nexport function saveMemoryLedger(connectorId: string, ledger: MemoryLedger): void {\n const p = memoryLedgerPath(connectorId);\n assertNoSymlinkInPath(p);\n if (ledger.targets.length === 0) {\n rmSync(p, { force: true });\n return;\n }\n ensureDir(dirname(p));\n writeFileSync(p, `${JSON.stringify(ledger, null, 2)}\\n`, \"utf8\");\n}\n\n/** True when the connector has any recorded memory targets (uninstall guard). */\nexport function hasMemoryLedger(connectorId: string): boolean {\n return loadMemoryLedger(connectorId).targets.length > 0;\n}\n\n/**\n * Upsert one ledger row (keyed by platform+scope+path+blockId). The\n * `createdFile` fact is STICKY: once we created the file, deletion rights\n * survive later syncs that found it present.\n */\nexport function recordMemoryTarget(ledger: MemoryLedger, t: MemoryLedgerTarget): void {\n const i = ledger.targets.findIndex(\n (x) =>\n x.platform === t.platform &&\n x.scope === t.scope &&\n x.path === t.path &&\n x.blockId === t.blockId,\n );\n if (i >= 0) {\n ledger.targets[i] = { ...t, createdFile: ledger.targets[i]!.createdFile || t.createdFile };\n } else {\n ledger.targets.push(t);\n }\n}\n"],"mappings":";;;;;;;;;AAiDA,SAAS,kBAAkB;AAC3B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,UAAU,SAAS,YAAY;AASjC,IAAM,4BAA4B;AAElC,IAAM,0BAA0B;AAGhC,IAAM,gCAAgC,KAAK;AAM3C,IAAM,mCAAmC,IAAI;AAUpD,SAAS,eAAe,GAAmB;AACzC,SA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U,QAAQ,CAAC,CAAC;AACpB,gBAAc,GAAG,GAAG,KAAK,UAAU,QAAQ,MAAM,CAAC,CAAC;AAAA,GAAM,MAAM;AACjE;AAGO,SAAS,gBAAgB,aAA8B;AAC5D,SAAO,iBAAiB,WAAW,EAAE,QAAQ,SAAS;AACxD;AAOO,SAAS,mBAAmB,QAAsB,GAA6B;AACpF,QAAM,IAAI,OAAO,QAAQ;AAAA,IACvB,CAAC,MACC,EAAE,aAAa,EAAE,YACjB,EAAE,UAAU,EAAE,SACd,EAAE,SAAS,EAAE,QACb,EAAE,YAAY,EAAE;AAAA,EACpB;AACA,MAAI,KAAK,GAAG;AACV,WAAO,QAAQ,CAAC,IAAI,EAAE,GAAG,GAAG,aAAa,OAAO,QAAQ,CAAC,EAAG,eAAe,EAAE,YAAY;AAAA,EAC3F,OAAO;AACL,WAAO,QAAQ,KAAK,CAAC;AAAA,EACvB;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/adapters/antigravity/index.ts"],"sourcesContent":["/**\n * adapters/antigravity — Google Antigravity (IDE) platform adapter.\n *\n * Antigravity is a Gemini-family host that, as of the 2.0 line, exposes a real\n * lifecycle-hook system on top of MCP — so this adapter is `json-stdio` (not the\n * old `mcp-only` framing): the host pipes a JSON payload to a hook command on\n * stdin and reads a JSON control object back, the same paradigm as Claude Code /\n * Gemini CLI. It installs the MCP server, lifecycle hooks, slash-command\n * Workflows, and Agent Skills.\n *\n * CONFIRMED-BY-INSTALL (2026-06-03, docs/research/antigravity-paths-confirmed.md):\n * a real machine with Antigravity IDE + `agy` CLI v1.0.0 shows the canonical user\n * customization root is `~/.gemini/antigravity/` — `~/.gemini/antigravity/mcp_config.json`\n * EXISTS and `~/.gemini/config/mcp_config.json` does NOT. So the fresh-install\n * default user MCP path is `~/.gemini/antigravity/mcp_config.json` (candidate[0]);\n * the `config/` and `antigravity-cli/` paths remain probed fallbacks only (honored\n * when a pre-existing config is found there, never the fresh default).\n *\n * STILL MEDIUM-CONFIDENCE / PATH-PROBING: hooks.json and the global skills dir were\n * NOT present on the observed install, so those locations stay corroborated-but-not-\n * byte-verified. Every user-scope path is PROBED at runtime — prefer a candidate\n * that already exists on disk, else fall back to the canonical path — and the doctor\n * flags each probed path with \"verify for your Antigravity version.\" We NEVER\n * hard-code a single guessed path, and any unsupported event or surface warn-skips\n * (never throws) at install time.\n *\n * Native config formats:\n * - MCP config (JSONC; we WRITE plain JSON), root key \"mcpServers\". stdio is\n * `{ command, args, env }`; a remote server is `{ serverUrl, headers }`\n * (NOTE: the key is `serverUrl`, NOT `url` and NOT Gemini CLI's `httpUrl`).\n * user scope → prefer existing of:\n * ~/.gemini/antigravity/mcp_config.json (CONFIRMED canonical)\n * ~/.gemini/config/mcp_config.json (probed fallback)\n * ~/.gemini/antigravity-cli/mcp_config.json (probed fallback)\n * else default to candidate[0] (antigravity/).\n * project scope → <projectDir>/.agents/mcp_config.json\n * - Hooks: a SEPARATE hooks.json in the customization dir (NOT the mcp_config),\n * project → <projectDir>/.agents/hooks.json\n * user → <resolvedUserConfigDir>/hooks.json\n * Shape: { hooks: { <Event>: [ { matcher, hooks:[{ type:\"command\", command }] } ] } }.\n * Supported events: PreToolUse, PostToolUse, SessionStart, Stop. All other\n * normalized events warn-skip. I/O fields are camelCase (see parse/format).\n * - Commands = \"Workflows\": markdown `.md` (body = the prompt; an optional\n * leading description line). Project prefer existing <proj>/.agent/workflows\n * or <proj>/.agents/workflows (default .agent/workflows per launch docs);\n * user ~/.gemini/antigravity/global_workflows.\n * - Skills = Agent Skills (uniform SKILL.md). Project\n * <proj>/.agents/skills/<name>/SKILL.md; user PROBE\n * ~/.gemini/antigravity-cli/skills then ~/.gemini/skills (NEVER\n * ~/.gemini/antigravity/skills — reportedly broken). NOTE: the global skills\n * dir was NOT present on the confirmed install, so it stays medium-confidence\n * + doctor \"verify for your version.\"\n * - Subagents: declarative subagents exist only inside a plugin bundle, which\n * agent-connector does not emit; supportsSubagents is false and the\n * BaseAdapter skip/warn default applies.\n *\n * Env handling: Antigravity (Gemini family) documents no `${env:VAR}` token of\n * the framework's syntax, so env/header/url refs are resolved to literals at\n * install time via resolveEnvRefsDeep — the safe default matching the Gemini CLI\n * adapter.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nimport { BaseAdapter } from \"../base.js\";\nimport type { Adapter, HookReply, InstallContext, NormalizedEvent } from \"../spi.js\";\nimport type {\n ChangeRecord,\n CommandDef,\n DetectedPlatform,\n HealthCheck,\n HookEventName,\n HookParadigm,\n HookResponse,\n PlatformCapabilities,\n PlatformId,\n PostToolUseEvent,\n PreToolUseEvent,\n ServerDef,\n SessionStartEvent,\n StopEvent,\n Transport,\n} from \"../../core/types.js\";\nimport { resolveEnvRefsDeep } from \"../../core/interpolate.js\";\nimport {\n buildHomeBinHookCommand,\n buildWrappedStdio,\n buildUsageEventCommand,\n isHomeBinHookCommand,\n isHostNativeUsageEnabled,\n isUsageEventCommand,\n} from \"../../core/spawn.js\";\nimport { renderSkillMd } from \"../claude-code/render.js\";\nimport { normalizeSessionSource } from \"../claude-code/wire.js\";\n\nconst HOST: PlatformId = \"antigravity\";\nconst MCP_ROOT_KEY = \"mcpServers\";\n\n/**\n * Known user-scope MCP config candidates, in preference order. We pick the first\n * that already exists on disk; otherwise we default to candidate[0]\n * (~/.gemini/antigravity/mcp_config.json — CONFIRMED canonical on a real install:\n * docs/research/antigravity-paths-confirmed.md). The `config/` and CLI-only\n * `antigravity-cli/` paths are kept ONLY as probed fallbacks so a pre-existing\n * config in either is still honored, but neither is ever the fresh-install default.\n */\nconst USER_CONFIG_CANDIDATES = [\n [\".gemini\", \"antigravity\", \"mcp_config.json\"],\n [\".gemini\", \"config\", \"mcp_config.json\"],\n [\".gemini\", \"antigravity-cli\", \"mcp_config.json\"],\n] as const;\n\n/**\n * Antigravity's supported lifecycle hook events. These happen to share the\n * normalized PascalCase names 1:1; everything else has no Antigravity equivalent\n * and is reported as a warn/skip at install time.\n */\nconst SUPPORTED_EVENTS: ReadonlySet<HookEventName> = new Set<HookEventName>([\n \"PreToolUse\",\n \"PostToolUse\",\n \"SessionStart\",\n \"Stop\",\n]);\n\n/**\n * Native hooks.json key for the OPT-IN host-native turn-usage hook (enricher 4a).\n * Antigravity shares the Gemini-family `AfterModel` model-turn hook, whose payload\n * carries `usageMetadata`. This is a host-native-only sink (no connector handler);\n * it is installed ONLY when host-native capture is enabled and records a DISTINCT\n * `model_turn` telemetry row that is never summed with the per-MCP `serve` rows.\n */\nconst USAGE_HOOK_EVENT = \"AfterModel\";\n\n/** A single Antigravity native hook registration entry (nested, Claude-shaped). */\ninterface AntigravityHookEntry {\n matcher: string;\n hooks: Array<{ type: \"command\"; command: string }>;\n}\n\n/** The shape of Antigravity's hooks.json (only the parts we touch). */\ninterface AntigravityHooksFile {\n hooks?: Record<string, AntigravityHookEntry[]>;\n [key: string]: unknown;\n}\n\n/**\n * Native MCP server entry shapes Antigravity accepts under `mcpServers`.\n * A stdio server is `{ command, args, env }`; a remote server is\n * `{ serverUrl, headers }` — the key is `serverUrl` (NOT `url`).\n */\ninterface AntigravityStdioServer {\n command: string;\n args?: string[];\n env?: Record<string, string>;\n}\ninterface AntigravityHttpServer {\n serverUrl: string;\n headers?: Record<string, string>;\n}\n\n/**\n * Raw Antigravity hook stdin payload (camelCase wire fields).\n *\n * SOURCE-VERIFIED against Google's official Antigravity hooks docs\n * (antigravity.google/docs/hooks) and corroborated by production integrations\n * (Cisco defenseclaw, camjac251/tool-gates, ntd4996/agentpet): Antigravity does\n * NOT use the flat Claude-Code shape. It carries no `hook_event_name`; the tool\n * descriptor is NESTED under `toolCall` (`toolCall.name` / `toolCall.args`); the\n * stable session id is `conversationId`; and the workspace roots are a string\n * array `workspacePaths` (first entry is the project dir). PostToolUse sends NO\n * tool fields — only `stepIdx`, an `error` string (empty/absent on success), and\n * the common fields.\n */\ninterface AntigravityToolCall {\n name?: string;\n args?: Record<string, unknown>;\n}\ninterface AntigravityWireInput {\n connector?: unknown;\n /** PreToolUse: nested tool descriptor (`toolCall.name`, `toolCall.args`). */\n toolCall?: AntigravityToolCall;\n toolOutput?: string;\n /** PostToolUse: runtime error message — empty/absent on success. */\n error?: string;\n /** Stable session id (the active agent conversation UUID). */\n conversationId?: string;\n /** Mounted workspace roots; the first entry is the project dir. */\n workspacePaths?: string[];\n source?: string;\n reason?: string;\n stopHookActive?: boolean;\n}\n\nexport class AntigravityAdapter extends BaseAdapter implements Adapter {\n readonly id: PlatformId = HOST;\n readonly name: string = \"Google Antigravity\";\n readonly paradigm: HookParadigm = \"json-stdio\";\n\n readonly capabilities: PlatformCapabilities = {\n // Memory surface: AGENTS.md-first managed block via the BaseAdapter default\n // (memoryTargets: project <projectDir>/AGENTS.md; user scope where documented).\n supportsMemory: true,\n // Antigravity 2.0 fires PreToolUse / PostToolUse / SessionStart / Stop.\n preToolUse: true,\n postToolUse: true,\n sessionStart: true,\n stop: true,\n // No documented equivalents — kept false; the corresponding normalized\n // events warn-skip at install time.\n preCompact: false,\n sessionEnd: false,\n userPromptSubmit: false,\n notification: false,\n // Newer events: no documented permission-dialog, tool-failure, or subagent\n // lifecycle hooks on Antigravity (IDE or `agy` CLI — the CLI adapter\n // inherits this surface), so permissionRequest / postToolUseFailure /\n // subagentStart / subagentStop stay unset — install reports the standard\n // skip-warn for them.\n // Transform-category hooks can rewrite tool input and tool output; the\n // SessionStart hook can inject additional context.\n canModifyArgs: true,\n canModifyOutput: true,\n canInjectSessionContext: true,\n // Antigravity registers stdio, SSE, and Streamable HTTP MCP servers.\n transports: [\"stdio\", \"sse\", \"http\"],\n // Content surfaces: Workflows (markdown commands) + Agent Skills (SKILL.md).\n // Declarative subagents exist only inside a plugin bundle (not emitted), so\n // subagents are unsupported and inherit the BaseAdapter skip/warn default.\n supportsCommands: true,\n supportsSkills: true,\n supportsSubagents: false,\n };\n\n // ── Detection ────────────────────────────────────────────────────────────\n\n detectInstalled(projectDir: string): DetectedPlatform {\n const userConfig = this.resolveUserConfigPath();\n const userDir = join(homedir(), \".gemini\");\n const projectConfig = join(projectDir, \".agents\", \"mcp_config.json\");\n\n const userInstalled =\n existsSync(userDir) ||\n this.userConfigCandidates().some((parts) => existsSync(join(homedir(), ...parts)));\n const projInstalled = existsSync(projectConfig);\n const installed = userInstalled || projInstalled;\n\n // Report the scope/path that actually matched, so a project-only install\n // isn't misreported as a (non-existent) user install.\n const scope = projInstalled && !userInstalled ? \"project\" : \"user\";\n const configPath = scope === \"project\" ? projectConfig : userConfig;\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: installed\n ? scope === \"project\"\n ? `found project Antigravity config at ${projectConfig}`\n : `found Antigravity config under ${userDir}`\n : `no Antigravity config at ${userDir} or ${projectConfig}`,\n confidence: installed ? \"high\" : \"low\",\n };\n }\n\n /**\n * The lifecycle hook events this host actually writes; every other normalized\n * event warn-skips at install time. Defaults to the IDE's\n * {@link SUPPORTED_EVENTS}. Overridable by forks whose underlying binary\n * recognizes a DIFFERENT event set (e.g. the `agy` CLI, which does NOT\n * recognize SessionStart). Kept in lock-step with the per-event capability\n * flags so the docs hooks-matrix and the fleet-wide never-silent-drop contract\n * stay consistent.\n */\n protected supportedHookEvents(): ReadonlySet<HookEventName> {\n return SUPPORTED_EVENTS;\n }\n\n // ── Native paths ─────────────────────────────────────────────────────────\n\n getConfigDir(ctx: InstallContext): string {\n if (ctx.scope === \"project\") return join(ctx.projectDir, \".agents\");\n // User scope: parent dir of the resolved user mcp_config.json.\n return dirname(this.resolveUserConfigPath());\n }\n\n getServerConfigPath(ctx: InstallContext): string {\n return ctx.scope === \"project\"\n ? join(ctx.projectDir, \".agents\", \"mcp_config.json\")\n : this.resolveUserConfigPath();\n }\n\n /**\n * Hooks live in a SEPARATE hooks.json in the customization dir — NOT the\n * mcp_config.json. Project → <proj>/.agents/hooks.json; user →\n * <resolvedUserConfigDir>/hooks.json (the dir holding the resolved user MCP\n * config). Path is medium-confidence and surfaced by the doctor.\n */\n getHookConfigPath(ctx: InstallContext): string {\n return join(this.getConfigDir(ctx), \"hooks.json\");\n }\n\n /**\n * The user-scope MCP config candidates, in preference order. Overridable by\n * forks (e.g. the Antigravity CLI) that resolve a different user-scope root\n * while reusing resolveUserConfigPath's prefer-existing-else-candidate[0] logic.\n */\n protected userConfigCandidates(): ReadonlyArray<readonly string[]> {\n return USER_CONFIG_CANDIDATES;\n }\n\n /**\n * Pick the user-scope mcp_config.json: prefer a candidate that already exists,\n * else default to candidate[0] (the CONFIRMED canonical ~/.gemini/antigravity path).\n */\n protected resolveUserConfigPath(): string {\n const home = homedir();\n const candidates = this.userConfigCandidates();\n for (const parts of candidates) {\n const p = join(home, ...parts);\n if (existsSync(p)) return p;\n }\n const fallback = candidates[0];\n if (fallback === undefined) {\n // Defensive: a non-empty candidate list is an invariant, but never throw.\n return join(home, \".gemini\", \"antigravity\", \"mcp_config.json\");\n }\n return join(home, ...fallback);\n }\n\n /**\n * Resolve the Workflows (slash-command) dir, prefer-existing-else-canonical.\n * project → prefer existing <proj>/.agent/workflows or <proj>/.agents/workflows;\n * default .agent/workflows (launch-era singular `.agent`).\n * user → ~/.gemini/antigravity/global_workflows.\n */\n protected resolveWorkflowsDir(ctx: InstallContext): string {\n if (ctx.scope === \"project\") {\n const singular = join(ctx.projectDir, \".agent\", \"workflows\");\n const plural = join(ctx.projectDir, \".agents\", \"workflows\");\n if (existsSync(singular)) return singular;\n if (existsSync(plural)) return plural;\n return singular;\n }\n return join(homedir(), \".gemini\", \"antigravity\", \"global_workflows\");\n }\n\n /**\n * Resolve the Agent Skills dir, prefer-existing-else-canonical.\n * project → <proj>/.agents/skills (plural — matches mcp/skills convention).\n * user → prefer existing ~/.gemini/antigravity-cli/skills, else\n * ~/.gemini/skills. NEVER ~/.gemini/antigravity/skills\n * (reportedly broken), so it is not a candidate.\n */\n protected resolveSkillsDir(ctx: InstallContext): string {\n if (ctx.scope === \"project\") {\n return join(ctx.projectDir, \".agents\", \"skills\");\n }\n const home = homedir();\n const cliSkills = join(home, \".gemini\", \"antigravity-cli\", \"skills\");\n const sharedSkills = join(home, \".gemini\", \"skills\");\n if (existsSync(cliSkills)) return cliSkills;\n if (existsSync(sharedSkills)) return sharedSkills;\n return cliSkills;\n }\n\n // ── MCP server install / uninstall ───────────────────────────────────────\n\n installServer(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n const override = connector.platforms[this.id]?.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 ${this.id}`\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 Antigravity's native mcpServers entry. */\n private renderServerEntry(\n ctx: InstallContext,\n server: ServerDef,\n ): AntigravityStdioServer | AntigravityHttpServer {\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> --scope <scope> -- <command> <args...>`.\n ({ command, args } = buildWrappedStdio(ctx, server, this.id, command, args));\n\n // Antigravity (Gemini family) has no documented native interpolation token,\n // so resolve every ${env:VAR} to a literal at install time.\n const entry: AntigravityStdioServer = { command: resolveEnvRefsDeep(command) };\n if (args.length > 0) entry.args = resolveEnvRefsDeep(args);\n const env = this.renderEnv(server.env);\n if (env) entry.env = env;\n return entry;\n }\n\n // sse / http (and any other remote transport) — Antigravity registers a URL\n // under the `serverUrl` key (NOT `url`).\n const entry: AntigravityHttpServer = { serverUrl: resolveEnvRefsDeep(server.url ?? \"\") };\n const headers = this.renderEnv(server.headers);\n if (headers) entry.headers = headers;\n return entry;\n }\n\n /**\n * Render env/header values. Antigravity documents no native interpolation\n * token, so 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 ─────────────────────────────────────────────\n\n installHooks(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n if (connector.platforms[this.id]?.hooks === false) {\n return [{ platform: this.id, action: \"skip\", detail: `hooks disabled for ${this.id}` }];\n }\n // The opt-in host-native usage hook (4a) needs no connector handler, so it may\n // be installed even when the connector declares no normalized hook events.\n const hostNative = isHostNativeUsageEnabled(connector.telemetry);\n if (connector.hookEvents.length === 0 && !hostNative) {\n return [{ platform: this.id, action: \"skip\", detail: \"connector declares no hooks\" }];\n }\n\n const hooksPath = this.getHookConfigPath(ctx);\n // OVERWRITE GUARD: never clobber a present-but-unparseable hooks.json.\n if (this.isPresentButUnparseable(hooksPath)) {\n return [\n {\n platform: this.id,\n action: \"warn\",\n path: hooksPath,\n detail: `existing ${hooksPath} is not parseable; left untouched (back it up / fix it, then re-run)`,\n },\n ];\n }\n\n const file = this.readJson<AntigravityHooksFile>(hooksPath) ?? {};\n const __skip = this.malformedHookRootSkip(hooksPath, (file as Record<string, unknown>).hooks);\n if (__skip) return [__skip];\n const hooks = (file.hooks ??= {});\n\n const changes: ChangeRecord[] = [];\n let mutated = false;\n\n const supportedEvents = this.supportedHookEvents();\n for (const event of connector.hookEvents) {\n if (!supportedEvents.has(event)) {\n // No Antigravity equivalent for this normalized event — report.\n changes.push({\n platform: this.id,\n action: \"warn\",\n path: hooksPath,\n detail: `${event} has no Antigravity hook equivalent — skipped`,\n });\n continue;\n }\n\n const command = buildHomeBinHookCommand(ctx.homeBinPath, this.id, event, connector.id);\n const matcher = connector.hooks[event]?.matcher ?? \"\";\n const entry: AntigravityHookEntry = {\n matcher,\n hooks: [{ type: \"command\", command }],\n };\n\n const bucket = (hooks[event] ??= []);\n const existingIdx = bucket.findIndex((e) => this.entryHasOurCommand(e, ctx));\n\n if (existingIdx >= 0) {\n if (JSON.stringify(bucket[existingIdx]) === JSON.stringify(entry)) {\n changes.push({\n platform: this.id,\n action: \"skip\",\n path: hooksPath,\n detail: `hooks.${event} already registered`,\n });\n continue;\n }\n bucket[existingIdx] = entry;\n changes.push({\n platform: this.id,\n action: \"update\",\n path: hooksPath,\n detail: `hooks.${event}`,\n });\n } else {\n bucket.push(entry);\n changes.push({\n platform: this.id,\n action: \"create\",\n path: hooksPath,\n detail: `hooks.${event}`,\n });\n }\n mutated = true;\n }\n\n // OPT-IN host-native usage hook (4a): register the AfterModel `usage-event`\n // sink when enabled. Records a DISTINCT `model_turn` row (whole-conversation),\n // never summed with the per-MCP `serve`-proxy rows.\n if (hostNative) {\n if (this.installUsageHook(hooks, ctx, hooksPath, changes)) mutated = true;\n }\n\n if (mutated) this.writeJson(hooksPath, file, ctx.dryRun);\n return changes;\n }\n\n /**\n * Register the opt-in AfterModel host-native usage hook (4a) into `hooks`.\n * Idempotent (byte-identical → skip, drift → update); returns true on mutation.\n * The command is the hidden `usage-event` entrypoint (NOT a connector hook), so\n * it carries an empty matcher. Reads `this.id` so the CLI fork installs its own\n * `usage-event antigravity-cli …` variant.\n */\n private installUsageHook(\n hooks: Record<string, AntigravityHookEntry[]>,\n ctx: InstallContext,\n hooksPath: string,\n changes: ChangeRecord[],\n ): boolean {\n const command = buildUsageEventCommand(ctx.homeBinPath, this.id, ctx.connector.id);\n const entry: AntigravityHookEntry = {\n matcher: \"\",\n hooks: [{ type: \"command\", command }],\n };\n const bucket = (hooks[USAGE_HOOK_EVENT] ??= []);\n const existingIdx = bucket.findIndex((e) =>\n (e.hooks ?? []).some((h) => isUsageEventCommand(h.command, ctx.homeBinPath, ctx.connector.id)),\n );\n\n if (existingIdx >= 0) {\n if (JSON.stringify(bucket[existingIdx]) === JSON.stringify(entry)) {\n changes.push({\n platform: this.id,\n action: \"skip\",\n path: hooksPath,\n detail: `hooks.${USAGE_HOOK_EVENT} (host-native usage) already registered`,\n });\n return false;\n }\n bucket[existingIdx] = entry;\n changes.push({\n platform: this.id,\n action: \"update\",\n path: hooksPath,\n detail: `hooks.${USAGE_HOOK_EVENT} (host-native usage)`,\n });\n } else {\n bucket.push(entry);\n changes.push({\n platform: this.id,\n action: \"create\",\n path: hooksPath,\n detail: `hooks.${USAGE_HOOK_EVENT} (host-native usage)`,\n });\n }\n return true;\n }\n\n uninstallHooks(ctx: InstallContext): ChangeRecord[] {\n const hooksPath = this.getHookConfigPath(ctx);\n const file = this.readJson<AntigravityHooksFile>(hooksPath);\n const hooks = file?.hooks;\n if (!file || !hooks) {\n return [\n {\n platform: this.id,\n action: \"skip\",\n path: hooksPath,\n detail: \"no hooks section present\",\n },\n ];\n }\n\n const changes: ChangeRecord[] = [];\n let mutated = false;\n\n for (const event of Object.keys(hooks)) {\n const bucket = hooks[event];\n if (!Array.isArray(bucket)) continue;\n\n // Strip our hook command from each entry; drop entries left empty so we\n // never remove another connector's (or the user's own) hook commands.\n const next: AntigravityHookEntry[] = [];\n let removed = 0;\n for (const e of bucket) {\n const innerBefore = e.hooks?.length ?? 0;\n const inner = (e.hooks ?? []).filter((h) => !this.isOurCommand(h.command, ctx));\n removed += innerBefore - inner.length;\n if (inner.length > 0) next.push({ matcher: e.matcher ?? \"\", hooks: inner });\n }\n\n if (removed > 0) {\n if (next.length > 0) hooks[event] = next;\n else delete hooks[event];\n changes.push({\n platform: this.id,\n action: \"remove\",\n path: hooksPath,\n detail: `hooks.${event} (${removed})`,\n });\n mutated = true;\n }\n }\n\n if (mutated) this.writeJson(hooksPath, file, ctx.dryRun);\n if (changes.length === 0) {\n changes.push({\n platform: this.id,\n action: \"skip\",\n path: hooksPath,\n detail: \"no matching hook entries\",\n });\n }\n return changes;\n }\n\n private entryHasOurCommand(entry: AntigravityHookEntry, ctx: InstallContext): boolean {\n return (entry.hooks ?? []).some((h) => this.isOurCommand(h.command, ctx));\n }\n\n /**\n * True when a hook command is ONE OF OURS for this connector — the universal\n * `hook` dispatcher OR the opt-in `usage-event` sink. Both are anchored on the\n * connector id (see isHomeBinHookCommand) so a shared-prefix id can't collide,\n * and so uninstall reverses the AfterModel usage hook too.\n */\n private isOurCommand(command: string | undefined, ctx: InstallContext): boolean {\n return (\n isHomeBinHookCommand(command, ctx.homeBinPath, ctx.connector.id) ||\n isUsageEventCommand(command, ctx.homeBinPath, ctx.connector.id)\n );\n }\n\n // ── Content surfaces: commands (Workflows) / skills ───────────────────────\n // CONTENT-ONLY: pure native-file writers under the probed workflows / skills\n // dirs. No runtime dispatch, no home-bin pointer, no telemetry wrap. Each\n // method is idempotent (byte-identical → skip) via BaseAdapter.writeContentFile\n // and reversible via removeContentFile. Honors platforms[\"antigravity\"]\n // per-surface false to skip. Commands are markdown Workflows (NOT TOML, unlike\n // gemini-cli); skills are the uniform Claude-compatible SKILL.md. Subagents are\n // unsupported (plugin-bundle-only) and inherit the BaseAdapter skip/warn.\n\n /** Native Workflow file path: <workflowsDir>/<name>.md. */\n private commandPath(ctx: InstallContext, name: string): string {\n return join(this.resolveWorkflowsDir(ctx), `${name}.md`);\n }\n /** Native skill dir: <skillsDir>/<name>. */\n private skillDir(ctx: InstallContext, name: string): string {\n return join(this.resolveSkillsDir(ctx), name);\n }\n\n // ── Commands (Workflows) ──────────────────────────────────────────────────\n\n override installCommands(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n if (connector.platforms[this.id]?.commands === false) {\n return [{ platform: this.id, action: \"skip\", detail: `commands disabled for ${this.id}` }];\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), this.renderCommand(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 /**\n * Render a command to an Antigravity Workflow: a plain markdown `.md` whose\n * body is the command prompt, optionally preceded by a leading description\n * line. No frontmatter / TOML (unlike gemini-cli).\n */\n private renderCommand(cmd: CommandDef): string {\n const body = cmd.prompt.endsWith(\"\\n\") ? cmd.prompt : `${cmd.prompt}\\n`;\n if (cmd.description !== undefined && cmd.description !== \"\") {\n return `${cmd.description}\\n\\n${body}`;\n }\n return body;\n }\n\n // ── Skills ────────────────────────────────────────────────────────────────\n\n override installSkills(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n if (connector.platforms[this.id]?.skills === false) {\n return [{ platform: this.id, action: \"skip\", detail: `skills disabled for ${this.id}` }];\n }\n if (connector.skills.length === 0) {\n return [{ platform: this.id, action: \"skip\", detail: \"connector declares no skills\" }];\n }\n const changes: ChangeRecord[] = [];\n for (const skill of connector.skills) {\n const dir = this.skillDir(ctx, skill.name);\n changes.push(\n this.writeContentFile(join(dir, \"SKILL.md\"), renderSkillMd(skill), ctx.dryRun),\n );\n // Bundle any resource files beside SKILL.md (relative path → contents).\n // Defense-in-depth: skip+warn on any key that escapes the skill dir.\n for (const [rel, contents] of Object.entries(skill.resources ?? {})) {\n const target = this.resolveWithin(dir, rel);\n if (target === null) {\n changes.push({\n platform: this.id,\n action: \"warn\",\n detail: `skill resource \"${rel}\" escapes the skill dir; skipped`,\n });\n continue;\n }\n changes.push(this.writeContentFile(target, contents, ctx.dryRun));\n }\n }\n return changes;\n }\n\n override uninstallSkills(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n if (connector.skills.length === 0) {\n return [{ platform: this.id, action: \"skip\", detail: \"connector declares no skills\" }];\n }\n const changes: ChangeRecord[] = [];\n for (const skill of connector.skills) {\n const dir = this.skillDir(ctx, skill.name);\n // Remove only the files we wrote (SKILL.md + declared resources), then the\n // skill dir itself when we own its full contents.\n changes.push(this.removeContentFile(join(dir, \"SKILL.md\"), ctx.dryRun));\n for (const rel of Object.keys(skill.resources ?? {})) {\n const target = this.resolveWithin(dir, rel);\n if (target === null) continue; // never delete outside the skill dir\n changes.push(this.removeContentFile(target, ctx.dryRun));\n }\n // Only remove the skill dir when WE own its full contents — never rm -rf a\n // dir that still holds user-added / sibling-tool / shared files.\n changes.push(this.removeDirIfEmpty(dir, ctx.dryRun));\n }\n return changes;\n }\n\n // ── Diagnostics ──────────────────────────────────────────────────────────\n\n override getHealthChecks(ctx: InstallContext): readonly HealthCheck[] {\n const mcpPath = this.getServerConfigPath(ctx);\n const hooksPath = this.getHookConfigPath(ctx);\n const connectorId = ctx.connector.id;\n const homeBin = ctx.homeBinPath;\n const hookEvents = ctx.connector.hookEvents;\n const workflowsDir = this.resolveWorkflowsDir(ctx);\n const skillsDir = this.resolveSkillsDir(ctx);\n\n const checks: HealthCheck[] = [\n {\n name: `${this.name}: mcp_config.json present`,\n check: () =>\n existsSync(mcpPath)\n ? { status: \"OK\", detail: `${mcpPath} (path probed; verify for your Antigravity version)` }\n : { status: \"FAIL\", detail: `not found: ${mcpPath} (path probed; verify for your Antigravity version)` },\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}: hooks.json hook command registered`,\n check: () => {\n if (hookEvents.length === 0) {\n return { status: \"OK\", detail: \"no hooks declared\" };\n }\n const file = this.readJson<AntigravityHooksFile>(hooksPath);\n if (!file) {\n return {\n status: \"FAIL\",\n detail: `not found: ${hooksPath} (path probed; verify for your Antigravity version)`,\n };\n }\n const hooks = file.hooks ?? {};\n const registered = Object.values(hooks).some((entries) =>\n (entries ?? []).some((e) =>\n (e.hooks ?? []).some((h) =>\n isHomeBinHookCommand(h.command, homeBin, connectorId),\n ),\n ),\n );\n return registered\n ? { status: \"OK\", detail: `hook command present in ${hooksPath}` }\n : { status: \"FAIL\", detail: `no hook for ${connectorId} in ${hooksPath}` };\n },\n },\n ];\n\n // Content-surface checks: only assert presence of the files this connector\n // declares (skip silently for surfaces it never asked for). The probed dirs\n // are noted so doctor output makes the medium-confidence path explicit.\n for (const cmd of ctx.connector.commands) {\n const p = join(workflowsDir, `${cmd.name}.md`);\n checks.push({\n name: `${this.name}: workflow ${cmd.name} present`,\n check: () =>\n existsSync(p)\n ? { status: \"OK\", detail: `${p} (workflows dir probed; verify for your version)` }\n : { status: \"FAIL\", detail: `not found: ${p} (workflows dir probed; verify for your version)` },\n });\n }\n for (const skill of ctx.connector.skills) {\n const p = join(skillsDir, skill.name, \"SKILL.md\");\n checks.push({\n name: `${this.name}: skill ${skill.name} present`,\n check: () =>\n existsSync(p)\n ? { status: \"OK\", detail: `${p} (skills dir probed; verify for your version)` }\n : { status: \"FAIL\", detail: `not found: ${p} (skills dir probed; verify for your version)` },\n });\n }\n return checks;\n }\n\n // ── Runtime: parse Antigravity stdin JSON → normalized event ──────────────\n\n parseEvent(event: HookEventName, raw: unknown): NormalizedEvent {\n const input = (raw ?? {}) as AntigravityWireInput;\n const connectorId = typeof input.connector === \"string\" ? input.connector : \"\";\n // Stable session id is `conversationId` (NOT a flat `sessionId`).\n const sessionId = typeof input.conversationId === \"string\" ? input.conversationId : \"\";\n // Project dir is the first mounted workspace root (`workspacePaths[0]`), a\n // string array — NOT a flat `cwd` string.\n const projectDir =\n Array.isArray(input.workspacePaths) && typeof input.workspacePaths[0] === \"string\"\n ? input.workspacePaths[0]\n : undefined;\n\n const base = {\n hostPlatform: this.id,\n connectorId,\n sessionId,\n raw,\n ...(projectDir !== undefined ? { projectDir } : {}),\n } as const;\n\n switch (event) {\n case \"PreToolUse\": {\n // Tool descriptor is nested under `toolCall` (`.name` / `.args`).\n const ev: PreToolUseEvent = {\n ...base,\n toolName: input.toolCall?.name ?? \"\",\n toolInput: input.toolCall?.args ?? {},\n };\n return ev;\n }\n case \"PostToolUse\": {\n // Antigravity's PostToolUse carries no tool fields — only `stepIdx`,\n // an `error` string, and the common fields. Derive isError from a\n // non-empty error string and surface it as the failure output.\n const error = typeof input.error === \"string\" ? input.error : \"\";\n const ev: PostToolUseEvent = {\n ...base,\n toolName: \"\",\n toolInput: {},\n ...(error.length > 0\n ? { isError: true, toolOutput: error }\n : input.toolOutput !== undefined\n ? { toolOutput: input.toolOutput }\n : {}),\n };\n return ev;\n }\n case \"SessionStart\": {\n const ev: SessionStartEvent = {\n ...base,\n source: normalizeSessionSource(input.source),\n };\n return ev;\n }\n case \"Stop\": {\n const ev: StopEvent = {\n ...base,\n ...(typeof input.stopHookActive === \"boolean\"\n ? { stopHookActive: input.stopHookActive }\n : {}),\n };\n return ev;\n }\n default: {\n // Antigravity only delivers the four SUPPORTED_EVENTS. If the runtime\n // dispatches anything else, surface it loudly rather than mis-parse.\n throw new Error(`unsupported ${this.id} hook event: ${String(event)}`);\n }\n }\n }\n\n // ── Runtime: normalized response → Antigravity native hook reply ──────────\n\n formatReply(event: HookEventName, response: HookResponse): HookReply {\n const decision = response.decision ?? \"allow\";\n\n // deny → Antigravity blocks the action via a top-level `decision:\"deny\"` +\n // reason (the Decide category).\n if (decision === \"deny\") {\n return this.stdout({\n decision: \"deny\",\n reason: response.reason ?? \"Blocked by hook\",\n });\n }\n\n // ask → Antigravity has no native \"ask\"; degrade to deny to stay fail-safe.\n if (decision === \"ask\") {\n return this.stdout({\n decision: \"deny\",\n reason: response.reason ?? \"Action requires user confirmation (security policy)\",\n });\n }\n\n // modify → Transform category. camelCase: rewrite PreToolUse input via\n // updatedInput; rewrite PostToolUse output via updatedOutput.\n if (decision === \"modify\") {\n if (event === \"PreToolUse\" && response.updatedInput) {\n return this.stdout({ updatedInput: response.updatedInput });\n }\n if (event === \"PostToolUse\" && response.updatedOutput !== undefined) {\n return this.stdout({ updatedOutput: response.updatedOutput });\n }\n // Nothing to apply; fall through to allow.\n }\n\n // context → inject soft guidance via additionalContext (the SessionStart\n // context-injection path).\n if (decision === \"context\" && response.additionalContext) {\n return this.stdout({ additionalContext: response.additionalContext });\n }\n\n // allow / void / unsupported-degradation → pass through with exit 0.\n return { exitCode: 0 };\n }\n\n private stdout(payload: unknown): HookReply {\n return { exitCode: 0, stdout: JSON.stringify(payload) };\n }\n}\n\nexport const adapter = new AntigravityAdapter();\nexport default adapter;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA8DA,SAAS,kBAAkB;AAC3B,SAAS,eAAe;AACxB,SAAS,SAAS,YAAY;AAiC9B,IAAM,OAAmB;AACzB,IAAM,eAAe;AAUrB,IAAM,yBAAyB;AAAA,EAC7B,CAAC,WAAW,eAAe,iBAAiB;AAAA,EAC5C,CAAC,WAAW,UAAU,iBAAiB;AAAA,EACvC,CAAC,WAAW,mBAAmB,iBAAiB;AAClD;AAOA,IAAM,mBAA+C,oBAAI,IAAmB;AAAA,EAC1E;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AASD,IAAM,mBAAmB;AA8DlB,IAAM,qBAAN,cAAiC,YAA+B;AAAA,EAC5D,KAAiB;AAAA,EACjB,OAAe;AAAA,EACf,WAAyB;AAAA,EAEzB,eAAqC;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IAAI,MAAM,eAAe,KAAK,EAAE,gBAAgB,OAAO,KAAK,CAAC,EAAE;AAAA,MACvE;AAAA,IACF;AAAA,EACF;AAAA;AAAA,EAIA,YAAY,OAAsB,UAAmC;AACnE,UAAM,WAAW,SAAS,YAAY;AAItC,QAAI,aAAa,QAAQ;AACvB,aAAO,KAAK,OAAO;AAAA,QACjB,UAAU;AAAA,QACV,QAAQ,SAAS,UAAU;AAAA,MAC7B,CAAC;AAAA,IACH;AAGA,QAAI,aAAa,OAAO;AACtB,aAAO,KAAK,OAAO;AAAA,QACjB,UAAU;AAAA,QACV,QAAQ,SAAS,UAAU;AAAA,MAC7B,CAAC;AAAA,IACH;AAIA,QAAI,aAAa,UAAU;AACzB,UAAI,UAAU,gBAAgB,SAAS,cAAc;AACnD,eAAO,KAAK,OAAO,EAAE,cAAc,SAAS,aAAa,CAAC;AAAA,MAC5D;AACA,UAAI,UAAU,iBAAiB,SAAS,kBAAkB,QAAW;AACnE,eAAO,KAAK,OAAO,EAAE,eAAe,SAAS,cAAc,CAAC;AAAA,MAC9D;AAAA,IAEF;AAIA,QAAI,aAAa,aAAa,SAAS,mBAAmB;AACxD,aAAO,KAAK,OAAO,EAAE,mBAAmB,SAAS,kBAAkB,CAAC;AAAA,IACtE;AAGA,WAAO,EAAE,UAAU,EAAE;AAAA,EACvB;AAAA,EAEQ,OAAO,SAA6B;AAC1C,WAAO,EAAE,UAAU,GAAG,QAAQ,KAAK,UAAU,OAAO,EAAE;AAAA,EACxD;AACF;AAEO,IAAM,UAAU,IAAI,mBAAmB;AAC9C,IAAO,sBAAQ;","names":["entry"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/usage/normalize.ts","../src/usage/aggregate.ts"],"sourcesContent":["/**\n * usage/normalize — model/provider/workspace normalization.\n *\n * `normalizeModelForGrouping` and `inferProvider` are FAITHFUL ports of\n * tokscale's order-dependent logic (tokscale-core/src/lib.rs\n * normalize_model_for_grouping + provider_identity.rs inferred_provider_from_model).\n * The matching order is load-bearing — keep the steps in sequence.\n *\n * `normalizeWorkspaceKey` / `workspaceLabelFromKey` port tokscale\n * sessions/mod.rs (same slash-collapsing + UNC-prefix handling) so a cwd string\n * from a host log maps to the same stable project key tokscale would produce.\n */\n\n// ─────────────────────────────────────────────────────────────────────────\n// Model normalization (port of lib.rs normalize_model_for_grouping)\n// ─────────────────────────────────────────────────────────────────────────\n\nconst REASONING_TIERS: ReadonlySet<string> = new Set([\n \"minimal\",\n \"low\",\n \"medium\",\n \"high\",\n \"xhigh\",\n \"auto\",\n \"none\",\n]);\n\n/**\n * Strip a `(level)` reasoning-effort suffix, returning the base model — or null\n * when the suffix is not one of the recognized tiers. Port of\n * strip_parenthesized_reasoning_tier: the base must be non-empty and already\n * trimmed (no surrounding whitespace).\n */\nfunction stripParenthesizedReasoningTier(modelId: string): string | null {\n if (!modelId.endsWith(\")\")) return null;\n const withoutClosing = modelId.slice(0, -1);\n const open = withoutClosing.lastIndexOf(\"(\");\n if (open < 0) return null;\n const base = withoutClosing.slice(0, open);\n const tier = withoutClosing.slice(open + 1);\n if (base === \"\" || base.trim() !== base) return null;\n if (!REASONING_TIERS.has(tier)) return null;\n return base;\n}\n\n/**\n * Map an `anthropic/claude-<major>-<minor>-<family>` id to the canonical\n * `claude-<family>-<major>-<minor>` form. Returns null when the shape does not\n * match exactly (too many parts, unknown family). Port of\n * normalize_anthropic_prefixed_claude_model.\n */\nfunction normalizeAnthropicPrefixedClaudeModel(modelId: string): string | null {\n const prefix = \"anthropic/claude-\";\n if (!modelId.startsWith(prefix)) return null;\n const rest = modelId.slice(prefix.length);\n const parts = rest.split(\"-\");\n const major = parts[0];\n const minor = parts[1];\n const family = parts[2];\n if (major === undefined || minor === undefined || family === undefined) return null;\n if (parts.length > 3) return null; // too many parts\n if (family !== \"opus\" && family !== \"sonnet\" && family !== \"haiku\") return null;\n return `claude-${family}-${major}-${minor}`;\n}\n\n/**\n * Normalize a raw model id to a stable grouping key. ORDER MATTERS — this is the\n * exact tokscale sequence:\n * 1. lowercase;\n * 2. strip a recognized `(tier)` reasoning suffix;\n * 3. strip a trailing `-YYYYMMDD` 8-digit date (only when len > 9 and the\n * 9th-from-end char is '-');\n * 4. for claude ids, replace dots between two digits with dashes\n * (e.g. \"claude-3.5-sonnet\" → \"claude-3-5-sonnet\");\n * 5. canonicalize an `anthropic/claude-*` prefix.\n */\nexport function normalizeModelForGrouping(modelId: string): string {\n let name = modelId.toLowerCase();\n\n const base = stripParenthesizedReasoningTier(name);\n if (base !== null) name = base;\n\n if (name.length > 9) {\n const potentialDate = name.slice(name.length - 8);\n const allDigits = /^[0-9]{8}$/.test(potentialDate);\n if (allDigits && name.charCodeAt(name.length - 9) === 0x2d /* '-' */) {\n name = name.slice(0, name.length - 9);\n }\n }\n\n if (name.includes(\"claude\")) {\n const chars = [...name];\n let result = \"\";\n for (let i = 0; i < chars.length; i++) {\n const c = chars[i] as string;\n const prev = chars[i - 1];\n const next = chars[i + 1];\n if (\n c === \".\" &&\n i > 0 &&\n i < chars.length - 1 &&\n prev !== undefined &&\n next !== undefined &&\n isAsciiDigit(prev) &&\n isAsciiDigit(next)\n ) {\n result += \"-\";\n } else {\n result += c;\n }\n }\n name = result;\n }\n\n const canonical = normalizeAnthropicPrefixedClaudeModel(name);\n if (canonical !== null) name = canonical;\n\n return name;\n}\n\nfunction isAsciiDigit(c: string): boolean {\n return c >= \"0\" && c <= \"9\";\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// Provider inference (port of provider_identity.rs inferred_provider_from_model)\n// ─────────────────────────────────────────────────────────────────────────\n\n/**\n * Whether `needle` occurs in `haystack` not flanked by alphanumerics on either\n * side (so \"o1\" matches \"o1-preview\" but not \"protocol1\"). Port of\n * contains_delimited.\n */\nfunction containsDelimited(haystack: string, needle: string): boolean {\n let from = 0;\n for (;;) {\n const pos = haystack.indexOf(needle, from);\n if (pos < 0) return false;\n const beforeOk = pos === 0 || !isAlphaNum(haystack.charCodeAt(pos - 1));\n const afterPos = pos + needle.length;\n const afterOk = afterPos === haystack.length || !isAlphaNum(haystack.charCodeAt(afterPos));\n if (beforeOk && afterOk) return true;\n from = pos + 1;\n }\n}\n\nfunction isAlphaNum(code: number): boolean {\n return (\n (code >= 0x30 && code <= 0x39) || // 0-9\n (code >= 0x41 && code <= 0x5a) || // A-Z\n (code >= 0x61 && code <= 0x7a) // a-z\n );\n}\n\n/**\n * Infer a canonical provider id from a model id. ORDER MATTERS — first match\n * wins, exactly as tokscale's inferred_provider_from_model. Returns null when no\n * family matches (caller supplies a platform default).\n */\nexport function inferProvider(model: string): string | null {\n const lower = model.toLowerCase();\n\n if (\n lower.includes(\"claude\") ||\n lower.includes(\"anthropic\") ||\n containsDelimited(lower, \"opus\") ||\n containsDelimited(lower, \"sonnet\") ||\n containsDelimited(lower, \"haiku\")\n ) {\n return \"anthropic\";\n }\n if (\n lower.includes(\"gpt\") ||\n lower.includes(\"openai\") ||\n containsDelimited(lower, \"o1\") ||\n containsDelimited(lower, \"o3\") ||\n containsDelimited(lower, \"o4\")\n ) {\n return \"openai\";\n }\n if (lower.includes(\"gemini\") || lower.includes(\"google\")) return \"google\";\n if (lower.includes(\"grok\")) return \"xai\";\n if (lower.includes(\"deepseek\")) return \"deepseek\";\n if (lower.includes(\"minimax\")) return \"minimax\";\n if (lower.includes(\"mistral\") || lower.includes(\"mixtral\")) return \"mistral\";\n if (lower.includes(\"llama\") || containsDelimited(lower, \"meta\")) return \"meta\";\n if (lower.includes(\"qwen\")) return \"qwen\";\n return null;\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// Agent-name normalization (port of sessions/mod.rs normalize_agent_name +\n// normalize_opencode_agent_name). The opencode reader MUST normalize the agent\n// before its dedup fingerprint, or fork-copied history (which differs only in a\n// raw agent string) escapes dedup and double-counts.\n// ─────────────────────────────────────────────────────────────────────────\n\n// U+200B ZWSP, U+200C ZWNJ, U+200D ZWJ, U+FEFF BOM/ZWNBSP.\nconst ZERO_WIDTH_RE = /[​‌‍]/g;\n\n/** Strip zero-width chars oh-my-openagent uses as invisible sort prefixes. */\nfunction stripZeroWidthChars(s: string): string {\n ZERO_WIDTH_RE.lastIndex = 0;\n return ZERO_WIDTH_RE.test(s) ? s.replace(ZERO_WIDTH_RE, \"\") : s;\n}\n\nconst AGENT_PREFIXES = [\"astrape:\", \"oh-my-claudecode:\", \"oh-my-codex:\"] as const;\n\n/** Strip a known namespace prefix (case-insensitive), else return as-is. */\nfunction stripAgentPrefix(name: string): string {\n for (const prefix of AGENT_PREFIXES) {\n if (name.length >= prefix.length && name.slice(0, prefix.length).toLowerCase() === prefix) {\n return name.slice(prefix.length);\n }\n }\n return name;\n}\n\n/** Collapse internal whitespace runs to single spaces (port of canonicalize_agent_name). */\nfunction canonicalizeAgentName(name: string): string {\n return name.split(/\\s+/).filter((w) => w !== \"\").join(\" \");\n}\n\n/** Titlecase one word, with UI/UX/API kept uppercase (port of titlecase_word). */\nfunction titlecaseWord(word: string): string {\n const lower = word.toLowerCase();\n if (lower === \"ui\") return \"UI\";\n if (lower === \"ux\") return \"UX\";\n if (lower === \"api\") return \"API\";\n if (word === \"\") return \"\";\n const chars = [...word];\n const first = chars[0] as string;\n return first.toUpperCase() + chars.slice(1).join(\"\");\n}\n\n/** Titlecase an agent name across '-' and whitespace boundaries (port of titlecase_agent). */\nfunction titlecaseAgent(name: string): string {\n if (name === \"\") return \"\";\n return name\n .split(\"-\")\n .flatMap((part) => part.split(/\\s+/))\n .filter((w) => w !== \"\")\n .map(titlecaseWord)\n .join(\" \");\n}\n\n/** Port of normalize_agent_name. */\nexport function normalizeAgentName(agent: string): string {\n const cleaned = stripZeroWidthChars(agent);\n const trimmed = cleaned.trim();\n const stripped = stripAgentPrefix(trimmed);\n const canonical = canonicalizeAgentName(stripped);\n const agentLower = canonical.toLowerCase();\n\n if (agentLower.includes(\"plan\")) {\n if (agentLower.includes(\"omo\") || agentLower.includes(\"sisyphus\")) {\n return \"Planner-Sisyphus\";\n }\n return titlecaseAgent(canonical);\n }\n if (agentLower === \"omo\" || agentLower === \"sisyphus\") return \"Sisyphus\";\n if (agentLower === \"orchestrator-sisyphus\") return \"Atlas\";\n return titlecaseAgent(canonical);\n}\n\n/** Port of normalize_oh_my_opencode_agent_name (returns undefined when no match). */\nfunction normalizeOhMyOpencodeAgentName(agentLower: string): string | undefined {\n switch (agentLower) {\n case \"sisyphus (ultraworker)\":\n case \"sisyphus - ultraworker\":\n case \"sisyphus ultraworker\":\n case \"sisyphus\":\n return \"Sisyphus\";\n case \"hephaestus (deep agent)\":\n case \"hephaestus - deep agent\":\n case \"hephaestus deep agent\":\n case \"hephaestus\":\n return \"Hephaestus\";\n case \"prometheus (plan builder)\":\n case \"prometheus - plan builder\":\n case \"prometheus plan builder\":\n case \"prometheus (planner)\":\n case \"prometheus\":\n return \"Prometheus\";\n case \"atlas (plan executor)\":\n case \"atlas - plan executor\":\n case \"atlas plan executor\":\n case \"atlas\":\n return \"Atlas\";\n case \"metis (plan consultant)\":\n case \"metis - plan consultant\":\n case \"metis plan consultant\":\n case \"metis\":\n return \"Metis\";\n case \"momus (plan critic)\":\n case \"momus - plan critic\":\n case \"momus plan critic\":\n case \"momus (plan reviewer)\":\n case \"momus\":\n return \"Momus\";\n case \"orchestrator-sisyphus\":\n return \"Atlas\";\n case \"sisyphus-junior\":\n return \"Sisyphus-Junior\";\n case \"planner-sisyphus\":\n return \"Planner-Sisyphus\";\n default:\n return undefined;\n }\n}\n\n/**\n * Port of normalize_opencode_agent_name (sessions/mod.rs:88-154). Applies the\n * shared cleaning pipeline, then the oh-my-opencode agent table, then falls back\n * to normalizeAgentName. Used by the opencode reader BEFORE its dedup fingerprint\n * so fork copies collapse (matching opencode.rs:272).\n */\nexport function normalizeOpencodeAgentName(agent: string): string {\n const cleaned = stripZeroWidthChars(agent);\n const trimmed = cleaned.trim();\n const stripped = stripAgentPrefix(trimmed);\n const canonical = canonicalizeAgentName(stripped);\n const agentLower = canonical.toLowerCase();\n\n const ohMy = normalizeOhMyOpencodeAgentName(agentLower);\n if (ohMy !== undefined) return ohMy;\n\n return normalizeAgentName(canonical);\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// Workspace key / label (port of sessions/mod.rs)\n// ─────────────────────────────────────────────────────────────────────────\n\n/**\n * Normalize an arbitrary cwd/dir string to a stable workspace key. Port of\n * normalize_workspace_key: backslashes → forward slashes, collapse repeated\n * slashes, strip a trailing slash (preserving a leading `//` UNC prefix).\n * Returns undefined for an empty input.\n */\nexport function normalizeWorkspaceKey(raw: string): string | undefined {\n const trimmed = raw.trim();\n if (trimmed === \"\") return undefined;\n\n const preserveUnc = trimmed.startsWith(\"\\\\\\\\\") || trimmed.startsWith(\"//\");\n let normalized = trimmed.replace(/\\\\/g, \"/\");\n\n if (preserveUnc) {\n let body = normalized.replace(/^\\/+/, \"\");\n while (body.includes(\"//\")) body = body.replace(/\\/\\//g, \"/\");\n normalized = `//${body}`;\n } else {\n while (normalized.includes(\"//\")) normalized = normalized.replace(/\\/\\//g, \"/\");\n }\n\n const minLen = preserveUnc ? 2 : 1;\n if (normalized.length > minLen) {\n normalized = normalized.replace(/\\/+$/, \"\");\n }\n\n return normalized === \"\" ? undefined : normalized;\n}\n\n/**\n * Human-readable label from a workspace key: the last non-empty path segment.\n * Port of workspace_label_from_key. Returns undefined when no segment remains.\n */\nexport function workspaceLabelFromKey(key: string): string | undefined {\n const segments = key.split(\"/\");\n for (let i = segments.length - 1; i >= 0; i--) {\n const seg = segments[i];\n if (seg !== undefined && seg !== \"\") return seg;\n }\n return undefined;\n}\n\n/**\n * Convert a cwd/dir string to both its normalized key and label in one call.\n * Both fields are undefined when the input does not yield a usable key.\n */\nexport function workspaceFromPath(raw: string): {\n projectKey?: string;\n projectLabel?: string;\n} {\n const key = normalizeWorkspaceKey(raw);\n if (key === undefined) return {};\n const label = workspaceLabelFromKey(key);\n return label === undefined ? { projectKey: key } : { projectKey: key, projectLabel: label };\n}\n","/**\n * usage/aggregate — token math, cross-source de-dup, and group-by rollups.\n *\n * Ports tokscale's shared aggregation model (docs/research/usage-shared-model.md\n * §4–5): a TokenBreakdown total is the sum of all five dimensions; dedup keeps\n * the FIRST occurrence per dedupKey in insertion order (un-keyed records always\n * pass through); group-by folds records into UsageSummary rows summing tokens /\n * cost / messages, counting distinct sessions, tracking the worst confidence and\n * the latest timestamp, sorted by total desc.\n */\n\nimport type {\n TokenBreakdown,\n UsageConfidence,\n UsageGroupBy,\n UsageRecord,\n UsageSummary,\n} from \"./types.js\";\nimport { normalizeModelForGrouping } from \"./normalize.js\";\n\n// ─────────────────────────────────────────────────────────────────────────\n// Token helpers\n// ─────────────────────────────────────────────────────────────────────────\n\n/** A fresh all-zero TokenBreakdown. */\nexport function emptyTokens(): TokenBreakdown {\n return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, reasoning: 0 };\n}\n\n/** Element-wise sum of two breakdowns into a NEW object (operands untouched). */\nexport function addTokens(a: TokenBreakdown, b: TokenBreakdown): TokenBreakdown {\n return {\n input: a.input + b.input,\n output: a.output + b.output,\n cacheRead: a.cacheRead + b.cacheRead,\n cacheWrite: a.cacheWrite + b.cacheWrite,\n reasoning: a.reasoning + b.reasoning,\n };\n}\n\n/** Scalar total across all five token dimensions. */\nexport function sumTokens(t: TokenBreakdown): number {\n return t.input + t.output + t.cacheRead + t.cacheWrite + t.reasoning;\n}\n\n/** Accumulate `b` into `a` in place (used inside the rollup fold). */\nfunction addTokensInPlace(a: TokenBreakdown, b: TokenBreakdown): void {\n a.input += b.input;\n a.output += b.output;\n a.cacheRead += b.cacheRead;\n a.cacheWrite += b.cacheWrite;\n a.reasoning += b.reasoning;\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// Confidence\n// ─────────────────────────────────────────────────────────────────────────\n\n/** Least-trustworthy (0) → most-trustworthy. host-estimated is the weaker. */\nconst CONFIDENCE_RANK: Record<UsageConfidence, number> = {\n \"host-estimated\": 0,\n \"host-reported\": 1,\n};\n\n/** The worse (least-confident) of two provenance labels. */\nexport function worstConfidence(a: UsageConfidence, b: UsageConfidence): UsageConfidence {\n return CONFIDENCE_RANK[b] < CONFIDENCE_RANK[a] ? b : a;\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// De-duplication\n// ─────────────────────────────────────────────────────────────────────────\n\n/**\n * Cross-source de-dup. Keep the FIRST record seen per `dedupKey` in insertion\n * order; records without a dedupKey always pass through (the per-reader dedup is\n * the real safeguard — this is the global backstop, per shared-model §5 and\n * design §6). Deterministic: same input order → same output.\n */\nexport function dedupe(records: UsageRecord[]): UsageRecord[] {\n const seen = new Set<string>();\n const out: UsageRecord[] = [];\n for (const rec of records) {\n const key = rec.dedupKey;\n if (key === undefined || key === \"\") {\n out.push(rec); // un-keyed → always include\n continue;\n }\n if (!seen.has(key)) {\n seen.add(key);\n out.push(rec);\n }\n // duplicate key → drop (keep-first)\n }\n return out;\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// Group-by aggregation\n// ─────────────────────────────────────────────────────────────────────────\n\n/** Local YYYY-MM-DD for an epoch-ms timestamp (matches tokscale's local-tz date). */\nfunction localDay(ts: number): string {\n const d = new Date(ts);\n const y = d.getFullYear();\n const m = `${d.getMonth() + 1}`.padStart(2, \"0\");\n const day = `${d.getDate()}`.padStart(2, \"0\");\n return `${y}-${m}-${day}`;\n}\n\n/** The grouping key value for a record under the requested dimension. */\nfunction groupKey(rec: UsageRecord, by: UsageGroupBy): string {\n switch (by) {\n case \"platform\":\n return rec.platformId;\n case \"project\":\n return rec.projectLabel ?? rec.projectKey ?? \"(no project)\";\n case \"session\":\n return rec.sessionId;\n case \"model\":\n return normalizeModelForGrouping(rec.modelId);\n case \"day\":\n return localDay(rec.ts);\n }\n}\n\ninterface MutableSummary extends UsageSummary {\n /** Distinct session ids folded into this group (counted at finalization). */\n _sessions: Set<string>;\n}\n\n/**\n * Roll records up into {@link UsageSummary} rows by the chosen dimension. Tokens,\n * cost, and message counts sum; `sessions` counts distinct session ids; the row\n * carries the worst confidence and the latest timestamp seen. Sorted by total\n * tokens descending (ties broken by recency).\n */\nexport function aggregateBy(records: UsageRecord[], by: UsageGroupBy): UsageSummary[] {\n const groups = new Map<string, MutableSummary>();\n\n for (const rec of records) {\n const key = groupKey(rec, by);\n let g = groups.get(key);\n if (g === undefined) {\n g = {\n key,\n tokens: emptyTokens(),\n total: 0,\n sessions: 0,\n messages: 0,\n confidence: rec.confidence,\n lastTs: rec.ts,\n _sessions: new Set<string>(),\n };\n groups.set(key, g);\n }\n\n addTokensInPlace(g.tokens, rec.tokens);\n g.messages += rec.messageCount;\n g._sessions.add(rec.sessionId);\n g.confidence = worstConfidence(g.confidence, rec.confidence);\n if (rec.ts > g.lastTs) g.lastTs = rec.ts;\n if (rec.cost !== undefined) g.cost = (g.cost ?? 0) + rec.cost;\n }\n\n const rows: UsageSummary[] = [];\n for (const g of groups.values()) {\n const { _sessions, ...summary } = g;\n summary.total = sumTokens(summary.tokens);\n summary.sessions = _sessions.size;\n rows.push(summary);\n }\n\n rows.sort((a, b) => b.total - a.total || b.lastTs - a.lastTs);\n return rows;\n}\n"],"mappings":";;;AAiBA,IAAM,kBAAuC,oBAAI,IAAI;AAAA,EACnD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAQD,SAAS,gCAAgC,SAAgC;AACvE,MAAI,CAAC,QAAQ,SAAS,GAAG,EAAG,QAAO;AACnC,QAAM,iBAAiB,QAAQ,MAAM,GAAG,EAAE;AAC1C,QAAM,OAAO,eAAe,YAAY,GAAG;AAC3C,MAAI,OAAO,EAAG,QAAO;AACrB,QAAM,OAAO,eAAe,MAAM,GAAG,IAAI;AACzC,QAAM,OAAO,eAAe,MAAM,OAAO,CAAC;AAC1C,MAAI,SAAS,MAAM,KAAK,KAAK,MAAM,KAAM,QAAO;AAChD,MAAI,CAAC,gBAAgB,IAAI,IAAI,EAAG,QAAO;AACvC,SAAO;AACT;AAQA,SAAS,sCAAsC,SAAgC;AAC7E,QAAM,SAAS;AACf,MAAI,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,SAAS,EAAE,MAAM;AAC5D,SAAO;AACT;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/runtime/serve.ts","../src/telemetry/calibration.ts","../src/telemetry/proxy.ts","../src/runtime/usage-event.ts","../src/runtime/statusline-entrypoint.ts","../src/runtime/action-entrypoint.ts"],"sourcesContent":["/**\n * runtime/serve — the `agent-connector serve` telemetry-wrapping entrypoint.\n *\n * When a stdio MCP server opts into transparent telemetry, its host config is\n * rewritten (by the adapter, via core/spawn.buildServeWrapperCommand) to launch\n * <homeBin> serve --connector <id> -- <realCommand> <realArgs...>\n * instead of the server directly. The CLI parses those flags and calls\n * {@link runServe}, which stands up the per-session telemetry context (store,\n * tokenizer, project identity, host detection) and hands off to the proxy.\n *\n * The proxy (telemetry/proxy.runServeProxy) forwards bytes VERBATIM in both\n * directions and measures aggregate per-tool token counts out of band, so this\n * wrapper is transparent to both the host and the real server. It resolves with\n * the child server's exit code, which the CLI uses as its own.\n */\n\nimport { randomUUID } from \"node:crypto\";\n\nimport { detectRuntimeHost } from \"../adapters/detect.js\";\nimport { REGISTERED_PLATFORM_IDS } from \"../adapters/registry.js\";\nimport { readRegisteredMeta } from \"../core/load-connector.js\";\nimport { projectIdentity } from \"../core/paths.js\";\nimport { detectLaunchMethod } from \"../core/spawn.js\";\nimport type { PlatformId } from \"../core/types.js\";\nimport { runServeProxy } from \"../telemetry/proxy.js\";\nimport { openStore } from \"../telemetry/store.js\";\nimport { getTokenizer } from \"../telemetry/tokenizer.js\";\nimport type { TelemetryInstallScope } from \"../telemetry/types.js\";\n\n/** Flags the CLI hands to {@link runServe}. */\nexport interface RunServeOptions {\n /** Connector id from `--connector <id>`; selects telemetry config + stamps records. */\n connectorId: string;\n /** The real MCP server executable to spawn (everything after `--`). */\n serverCommand: string;\n /** Arguments passed to that executable. */\n serverArgs: string[];\n /**\n * Install scope from `--scope <user|project>`. OPTIONAL: absent for configs\n * written before scope plumbing existed — left unstamped so older rows read\n * as \"unknown\". Stamped verbatim onto every telemetry record when present.\n */\n installScope?: TelemetryInstallScope;\n /**\n * Install TARGET platform id from `--host <platformId>` (baked into the\n * wrapper at install time). OPTIONAL: when a recognized platform id, it\n * OVERRIDES runtime env detection so headless spawns stamp hostPlatform\n * correctly (detectRuntimeHost only knows env markers for a few hosts and\n * otherwise mis-attributes). Absent/unrecognized → fall back to detection.\n */\n hostPlatformOverride?: PlatformId;\n /**\n * Framework data-root from `--data-dir <path>` (baked into the wrapper at\n * install time, only for a NON-DEFAULT root). OPTIONAL: when present, it pins\n * the data-root the WHOLE child resolves — connector record lookup AND the\n * telemetry store — by populating AGENT_CONNECTOR_DATA_DIR before anything\n * reads it. This is the env-independent path for hosts (codex) that strip the\n * MCP child's environment and would otherwise drop the override, leaving the\n * child to resolve the default `~/.agent-connector` and fail \"not registered\".\n * Absent → resolve the data-root the usual way (env or default).\n */\n dataDir?: string;\n}\n\n/**\n * Launch the developer's real MCP server under the telemetry-wrapping proxy.\n *\n * Resolves with the child server's exit code (propagated as this process's exit\n * code by the CLI). The session id comes from AGENT_CONNECTOR_SESSION when the\n * host sets it (empty otherwise); the host platform is detected from runtime env\n * markers; the project identity partitions telemetry by the stable project key.\n */\n/**\n * Resolve a session id for telemetry attribution. Prefers a host-provided\n * session/thread marker (so records from the same host session group together);\n * falls back to a per-process UUID — each `serve` invocation is one server\n * session, a sensible default granularity — so `--by session` rollups are never\n * collapsed into a single empty-keyed group.\n */\nfunction resolveSessionId(env: NodeJS.ProcessEnv = process.env): string {\n return (\n env.AGENT_CONNECTOR_SESSION ||\n env.CLAUDE_SESSION_ID ||\n env.CODEX_THREAD_ID ||\n env.CURSOR_TRACE_ID ||\n env.MCP_SESSION_ID ||\n `proc-${randomUUID()}`\n );\n}\n\nexport async function runServe(opts: RunServeOptions): Promise<number> {\n const {\n connectorId,\n serverCommand,\n serverArgs,\n installScope,\n hostPlatformOverride,\n dataDir,\n } = opts;\n\n // Pin the data-root BEFORE anything resolves it (the connector record lookup\n // below and openStore later both read dataRoot()). The wrapper passes\n // --data-dir only for a non-default root on a host that may strip the child\n // env (codex) — populating AGENT_CONNECTOR_DATA_DIR here makes the whole child\n // resolve that root regardless of whether the host propagated the env var.\n if (dataDir !== undefined && dataDir.trim() !== \"\") {\n process.env.AGENT_CONNECTOR_DATA_DIR = dataDir;\n }\n\n const connector = readRegisteredMeta(connectorId);\n if (!connector) {\n throw new Error(\n `Connector \"${connectorId}\" is not registered. Run an install/register step first.`,\n );\n }\n\n const id = projectIdentity(process.cwd());\n // Prefer the install TARGET platform baked into the wrapper (--host), but only\n // when it is a KNOWN registered platform id — a bad/unknown value falls back to\n // runtime env detection so a config typo can never poison hostPlatform.\n const hostPlatform: PlatformId =\n hostPlatformOverride !== undefined &&\n REGISTERED_PLATFORM_IDS.has(hostPlatformOverride)\n ? hostPlatformOverride\n : detectRuntimeHost().platform;\n const sessionId = resolveSessionId();\n\n // `serve` only ever wraps a locally-spawned stdio server (a remote/http server\n // is never launched through the proxy), so isRemote is always false here.\n const launchMethod = detectLaunchMethod(serverCommand, serverArgs);\n\n const store = openStore({});\n const tok = getTokenizer();\n\n return runServeProxy({\n connectorId,\n command: serverCommand,\n args: serverArgs,\n store,\n tokenizer: tok,\n modelFamilyHint: connector.telemetry.modelFamilyHint,\n hostPlatform,\n sessionId,\n projectKey: id.key,\n projectDir: id.dir,\n measureToolDefs: connector.telemetry.measureToolDefs,\n installScope,\n launchMethod,\n });\n}\n","/**\n * telemetry/calibration — OPT-IN Anthropic count_tokens calibration.\n *\n * The default tokenizer counts every family with the OpenAI o200k_base BPE, so\n * an Anthropic session's counts are an honest-but-approximate stand-in\n * (\"tokenizer-approx\"). This module lets a developer OPT IN to calibrating that\n * approximation against Anthropic's real `count_tokens` endpoint: we sample a\n * tiny fraction of tool calls off-box, learn a per-family correction factor\n * (rolling mean of exact/approx), and apply it to the locally-tokenized counts\n * so they land much closer to the host's real numbers — labeled honestly as\n * \"tokenizer-calibrated\".\n *\n * PRIVACY + SAFETY — load-bearing invariants:\n * • OPT-IN only. Nothing here runs unless BOTH AGENT_CONNECTOR_CALIBRATE\n * contains \"anthropic\" AND ANTHROPIC_API_KEY is set (see isCalibrationEnabled).\n * • Sampling only — shouldSample() rate-limits hard so we never hammer the API.\n * • Content leaves the box ONLY on a sampled call, ONLY when opted in. We store\n * a single scalar factor + sample count — NEVER the sampled text itself.\n * • Fail-open everywhere: a network/parse/IO error returns null / passes the\n * approximation through unchanged and NEVER throws into a tool call or hook.\n *\n * No new dependencies: uses Node's global fetch (Node >= 18) and node:fs.\n */\n\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport { dataRoot, ensureDir } from \"../core/paths.js\";\nimport type { ConfidenceSource, ModelFamily } from \"./types.js\";\n\n// ── Env switches ──────────────────────────────────────────────────────────\n\n/**\n * Is opt-in Anthropic calibration enabled for this process?\n *\n * Requires BOTH:\n * • AGENT_CONNECTOR_CALIBRATE — a comma-separated allowlist that INCLUDES\n * `anthropic` (so a future `AGENT_CONNECTOR_CALIBRATE=openai,anthropic` can\n * opt other families in without touching this gate), and\n * • ANTHROPIC_API_KEY — a non-empty key to authenticate the off-box call.\n *\n * Either missing → disabled (the privacy-safe default).\n */\nexport function isCalibrationEnabled(): boolean {\n const families = (process.env.AGENT_CONNECTOR_CALIBRATE || \"\")\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => s !== \"\");\n const key = (process.env.ANTHROPIC_API_KEY || \"\").trim();\n return families.includes(\"anthropic\") && key !== \"\";\n}\n\n// ── Factor store (dataRoot/calibration.json) ────────────────────────────────\n\n/** One learned correction factor for a model family: factor + sample count. */\nexport interface CalibrationFactor {\n /** Multiply an approx count by this to estimate the real count. */\n factor: number;\n /** How many samples have folded into the rolling mean. */\n samples: number;\n}\n\n/** The on-disk factor map, keyed by model family. */\nexport type CalibrationFactors = Partial<Record<ModelFamily, CalibrationFactor>>;\n\n/** Path to the learned-factor store: dataRoot()/calibration.json. */\nexport function calibrationPath(): string {\n return join(dataRoot(), \"calibration.json\");\n}\n\n/**\n * Clamp a measured exact/approx ratio into a sane range. A pathological sample\n * (e.g. an empty-string approx of 0 → Infinity, or a parse glitch) must never\n * poison the rolling mean, so ratios are pinned to [0.2, 5].\n */\nconst RATIO_MIN = 0.2;\nconst RATIO_MAX = 5;\n\nfunction clampRatio(ratio: number): number | null {\n if (!Number.isFinite(ratio) || ratio <= 0) return null;\n if (ratio < RATIO_MIN) return RATIO_MIN;\n if (ratio > RATIO_MAX) return RATIO_MAX;\n return ratio;\n}\n\n/**\n * Load the learned factors from disk. Fail-open: a missing/unreadable/malformed\n * file returns an empty map rather than throwing.\n */\nexport function loadFactors(): CalibrationFactors {\n const path = calibrationPath();\n if (!existsSync(path)) return {};\n try {\n const parsed = JSON.parse(readFileSync(path, \"utf8\")) as unknown;\n if (parsed === null || typeof parsed !== \"object\") return {};\n const out: CalibrationFactors = {};\n for (const [family, value] of Object.entries(parsed as Record<string, unknown>)) {\n if (value === null || typeof value !== \"object\") continue;\n const rec = value as Record<string, unknown>;\n const factor = rec[\"factor\"];\n const samples = rec[\"samples\"];\n if (\n typeof factor === \"number\" &&\n Number.isFinite(factor) &&\n factor > 0 &&\n typeof samples === \"number\" &&\n Number.isFinite(samples) &&\n samples >= 0\n ) {\n (out as Record<string, CalibrationFactor>)[family] = {\n factor,\n samples,\n };\n }\n }\n return out;\n } catch {\n return {};\n }\n}\n\n/**\n * Fold one observed exact/approx `ratio` into the rolling mean for `family` and\n * persist it. A running average converges to the true mean while staying cheap\n * and stateless across processes (each writer reads the prior count, blends in\n * the new sample, writes back). Fail-open: any read/write/clamp problem leaves\n * the store untouched and never throws.\n */\nexport function recordSample(family: ModelFamily, ratio: number): void {\n const clamped = clampRatio(ratio);\n if (clamped === null) return;\n try {\n const factors = loadFactors();\n const prior = factors[family];\n let next: CalibrationFactor;\n if (prior === undefined || prior.samples <= 0) {\n next = { factor: clamped, samples: 1 };\n } else {\n const samples = prior.samples + 1;\n // Running average: new mean = old mean + (sample - old mean) / n.\n const factor = prior.factor + (clamped - prior.factor) / samples;\n next = { factor, samples };\n }\n const updated: CalibrationFactors = { ...factors, [family]: next };\n const path = calibrationPath();\n ensureDir(dataRoot());\n writeFileSync(path, `${JSON.stringify(updated, null, 2)}\\n`, \"utf8\");\n } catch {\n /* fail-open: a calibration write must never break a tool call */\n }\n}\n\n// ── Anthropic count_tokens (off-box, sampled, fail-open) ─────────────────────\n\n/** Default model used for count_tokens when no family→model map applies. */\nconst DEFAULT_ANTHROPIC_MODEL = \"claude-3-5-sonnet-latest\";\n\n/** Anthropic count_tokens endpoint. */\nconst COUNT_TOKENS_URL = \"https://api.anthropic.com/v1/messages/count_tokens\";\n\n/** The single field we read out of a successful response. */\ninterface CountTokensResponse {\n input_tokens?: unknown;\n}\n\n/**\n * Ask Anthropic's `count_tokens` endpoint for the exact token count of `text`\n * under `model`. Returns the integer count, or `null` on ANY failure (no key,\n * non-200, network error, unparseable body) — fail-open by contract.\n *\n * Only ever called on a SAMPLED tool call when calibration is opted in, so the\n * sampled text leaves the box only under explicit operator consent.\n */\nexport async function countTokensAnthropic(\n text: string,\n model: string = DEFAULT_ANTHROPIC_MODEL,\n): Promise<number | null> {\n const apiKey = (process.env.ANTHROPIC_API_KEY || \"\").trim();\n if (apiKey === \"\") return null;\n try {\n const res = await fetch(COUNT_TOKENS_URL, {\n method: \"POST\",\n headers: {\n \"x-api-key\": apiKey,\n \"anthropic-version\": \"2023-06-01\",\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({\n model,\n messages: [{ role: \"user\", content: text }],\n }),\n });\n if (!res.ok) return null;\n const body = (await res.json()) as CountTokensResponse;\n const n = body.input_tokens;\n if (typeof n === \"number\" && Number.isFinite(n) && n >= 0) {\n return n;\n }\n return null;\n } catch {\n return null;\n }\n}\n\n// ── Sampling (rate-limit so we never hammer the API) ─────────────────────────\n\n/**\n * Sample roughly 1 in {@link SAMPLE_EVERY} calls, with a hard per-minute cap so\n * a burst of tool calls can never fan out into a burst of API calls. Both\n * counters are in-memory (per process) — calibration is a best-effort,\n * low-volume background signal, not a per-call requirement.\n */\nconst SAMPLE_EVERY = 20;\nconst MAX_SAMPLES_PER_MINUTE = 10;\n\nlet callCounter = 0;\nlet windowStartMs = 0;\nlet samplesThisWindow = 0;\n\n/**\n * Should THIS call fire an off-box count_tokens sample? Combines a 1-in-N\n * counter with a rolling per-minute cap. Pure in-memory bookkeeping; never\n * throws, never blocks.\n */\nexport function shouldSample(now: number = Date.now()): boolean {\n // Roll the per-minute window.\n if (now - windowStartMs >= 60_000) {\n windowStartMs = now;\n samplesThisWindow = 0;\n }\n callCounter += 1;\n if (callCounter % SAMPLE_EVERY !== 0) return false;\n if (samplesThisWindow >= MAX_SAMPLES_PER_MINUTE) return false;\n samplesThisWindow += 1;\n return true;\n}\n\n/** Reset the in-memory sampling counters. Test-only seam; cheap + side-effect-free. */\nexport function _resetSamplingForTest(): void {\n callCounter = 0;\n windowStartMs = 0;\n samplesThisWindow = 0;\n}\n\n// ── Apply a learned factor to a local approximation ──────────────────────────\n\n/** Result of {@link applyCalibration}: the adjusted count + its honest source. */\nexport interface CalibratedCount {\n tokens: number;\n source: Extract<ConfidenceSource, \"tokenizer-approx\" | \"tokenizer-calibrated\">;\n}\n\n/**\n * Adjust a locally-tokenized `approxTokens` count by the learned factor for\n * `family`. When a stored factor exists for the anthropic family, return the\n * scaled count labeled \"tokenizer-calibrated\"; otherwise pass the approximation\n * through unchanged as \"tokenizer-approx\". Pure: reads the factor store but\n * mutates nothing.\n */\nexport function applyCalibration(\n approxTokens: number,\n family: ModelFamily,\n factors: CalibrationFactors = loadFactors(),\n): CalibratedCount {\n if (family === \"anthropic\") {\n const f = factors[family];\n if (f !== undefined && f.samples > 0 && Number.isFinite(f.factor) && f.factor > 0) {\n return {\n tokens: Math.max(0, Math.round(approxTokens * f.factor)),\n source: \"tokenizer-calibrated\",\n };\n }\n }\n return { tokens: approxTokens, source: \"tokenizer-approx\" };\n}\n\n/** The model used for a family's count_tokens sample (anthropic → default model). */\nexport function modelForFamily(_family: ModelFamily): string {\n return DEFAULT_ANTHROPIC_MODEL;\n}\n","/**\n * telemetry/proxy — the telemetry-wrapping MCP stdio proxy.\n *\n * `agent-connector serve <command> <args…>` spawns the developer's REAL MCP\n * server as a child and sits transparently between the host and that server,\n * speaking the MCP stdio wire format: NEWLINE-DELIMITED JSON-RPC (one single-line\n * JSON object per message, terminated by `\\n`; stdio has NO Content-Length\n * framing). Bytes are forwarded VERBATIM in both directions so the proxy can\n * never corrupt the stream; a side line-buffer tees a COPY of each direction,\n * parses complete messages, and measures per-tool token usage out of band.\n *\n * Honesty / safety rules baked in here:\n * • Forwarding always happens FIRST. Measurement runs after the bytes are out\n * the door and is wrapped so a measurement bug can never break a tool call.\n * • Telemetry stores AGGREGATE COUNTS ONLY — the parsed `tools/call` arguments\n * and results are tokenized and discarded; raw content is never persisted.\n * • AGENT_CONNECTOR_TELEMETRY=0 → still proxy transparently, skip all measure.\n *\n * The proxy resolves with the child's exit code and propagates SIGINT/SIGTERM.\n */\n\nimport type { PlatformId } from \"../core/types.js\";\nimport { spawnChild } from \"../core/spawn-child.js\";\nimport { type JsonRpcMessage, LineBuffer, idKey, isObject } from \"./jsonrpc.js\";\nimport {\n applyCalibration,\n countTokensAnthropic,\n isCalibrationEnabled,\n modelForFamily,\n recordSample,\n shouldSample,\n} from \"./calibration.js\";\nimport { measureToolCall, measureToolDefs } from \"./measure.js\";\nimport { newRecordId } from \"./store.js\";\nimport { inferModelFamily } from \"./tokenizer.js\";\nimport type {\n ConfidenceSource,\n LaunchMethod,\n ModelFamily,\n TelemetryInstallScope,\n TelemetryStore,\n Tokenizer,\n ToolEventRecord,\n} from \"./types.js\";\n\n/** Options for {@link runServeProxy}. */\nexport interface RunServeProxyOptions {\n /** Connector id this server belongs to (stamped on every record). */\n connectorId: string;\n /** The real MCP server executable to spawn. */\n command: string;\n /** Arguments passed to that executable. */\n args: string[];\n /** Where measured records are appended. */\n store: TelemetryStore;\n /** Tokenizer used for measurement (defaults baked into measure helpers). */\n tokenizer: Tokenizer;\n /**\n * Telemetry model-family hint. \"auto\" infers the family from the MCP client's\n * `initialize` clientInfo.name; any explicit family wins outright.\n */\n modelFamilyHint: \"auto\" | ModelFamily;\n /** Host platform executing this proxy (stamped on every record). */\n hostPlatform: PlatformId;\n /** Host session id (stamped on every record). */\n sessionId: string;\n /** Hashed stable project identity (stamped on every record). */\n projectKey: string;\n /** Human-readable project directory (stamped on every record). */\n projectDir: string;\n /** When true, tokenize the `tools/list` schema once → tool-defs overhead. */\n measureToolDefs: boolean;\n /**\n * Install scope (global user vs project-local) stamped on every record.\n * OPTIONAL: omitted for configs written before scope plumbing existed, leaving\n * the field off the row so it reads as \"unknown\".\n */\n installScope?: TelemetryInstallScope;\n /**\n * How the wrapped server was launched (npx/bunx/uvx/node/binary/http), stamped\n * on every record. OPTIONAL for the same backward-compat reason as above.\n */\n launchMethod?: LaunchMethod;\n}\n\n// ── JSON-RPC shapes we read (kept local + narrow; everything else opaque) ─────\n\n/** A client→server `tools/call` we remember until its result comes back. */\ninterface PendingCall {\n toolName: string;\n args: unknown;\n}\n\n/**\n * Canonical string form of a tool call's arguments for an off-box count_tokens\n * sample — mirrors the tokenizer's own serialization so the sampled text equals\n * the bytes we approximated locally. A string passes through; anything else is\n * JSON-stringified; a value that stringifies to undefined becomes \"\".\n */\nfunction canonicalArgs(value: unknown): string {\n if (typeof value === \"string\") return value;\n try {\n return JSON.stringify(value) ?? \"\";\n } catch {\n return \"\";\n }\n}\n\n/**\n * Run the telemetry-wrapping MCP stdio proxy.\n *\n * Spawns `command args` with piped stdin/stdout (stderr inherited), forwards\n * both directions byte-for-byte, and measures `tools/call` round-trips and the\n * one-time `tools/list` tool-defs overhead into `store`. Resolves with the\n * child's exit code (or a signal-derived code) once the child closes.\n */\nexport async function runServeProxy(\n opts: RunServeProxyOptions,\n): Promise<number> {\n const {\n connectorId,\n command,\n args,\n store,\n tokenizer,\n modelFamilyHint,\n hostPlatform,\n sessionId,\n projectKey,\n projectDir,\n measureToolDefs: shouldMeasureToolDefs,\n installScope,\n launchMethod,\n } = opts;\n\n // Global kill switch: still proxy transparently, but skip ALL measurement.\n const measuringEnabled = process.env.AGENT_CONNECTOR_TELEMETRY !== \"0\";\n // OPT-IN Anthropic count_tokens calibration. Resolved once per session — the\n // gate (AGENT_CONNECTOR_CALIBRATE + ANTHROPIC_API_KEY) is process-level and\n // does not change mid-session. Off by default; privacy-safe.\n const calibrationEnabled = isCalibrationEnabled();\n\n // spawnChild fixes native-Windows package-runner launches: a bare npx/uvx\n // resolves to a .cmd shim that raw CreateProcess can't find/launch, so it is\n // run via a quoted single command line with a shell. No-op on macOS/Linux.\n const child = spawnChild(command, args, {\n stdio: [\"pipe\", \"pipe\", \"inherit\"],\n env: process.env,\n });\n\n // ── Per-session measurement state ───────────────────────────────────────\n // Family resolved from the client's `initialize` (or the hint) and cached.\n let family: ModelFamily = inferModelFamily(\"\", modelFamilyHint);\n // Outstanding tools/call requests, keyed by JSON-RPC id.\n const pending = new Map<string, PendingCall>();\n // Monotonic sequence so two records in the same ms still get distinct ids.\n let seq = 0;\n // tools/list overhead is measured exactly once per session.\n let toolDefsMeasured = false;\n\n /**\n * Build a base record stamped with the per-session identity fields plus the\n * scope dimensions. `installScope` / `launchMethod` are spread in ONLY when\n * defined, so a session without them leaves those fields off the row entirely\n * (read as \"unknown\") rather than writing an explicit `undefined`.\n */\n function baseRecord(): Omit<\n ToolEventRecord,\n \"toolName\" | \"scope\" | \"inputTokens\" | \"outputTokens\" | \"confidenceSource\" | \"isError\"\n > {\n return {\n id: newRecordId(seq++),\n ts: Date.now(),\n connectorId,\n hostPlatform,\n sessionId,\n projectKey,\n projectDir,\n ...(installScope !== undefined ? { installScope } : {}),\n ...(launchMethod !== undefined ? { launchMethod } : {}),\n };\n }\n\n /**\n * Inspect one parsed CLIENT→SERVER message. Caches the model family on\n * `initialize` and remembers `tools/call` requests so their results can be\n * measured when they come back. Never throws into the data path.\n */\n function onClientMessage(msg: JsonRpcMessage): void {\n const method = msg.method;\n if (method === \"initialize\") {\n const params = isObject(msg.params) ? msg.params : undefined;\n const clientInfo =\n params && isObject(params[\"clientInfo\"])\n ? (params[\"clientInfo\"] as Record<string, unknown>)\n : undefined;\n const clientName =\n clientInfo && typeof clientInfo[\"name\"] === \"string\"\n ? (clientInfo[\"name\"] as string)\n : \"\";\n family = inferModelFamily(clientName, modelFamilyHint);\n return;\n }\n\n if (method === \"tools/call\") {\n const key = idKey(msg.id);\n if (key === null) return; // a call with no id has no result to match\n const params = isObject(msg.params) ? msg.params : undefined;\n const toolName =\n params && typeof params[\"name\"] === \"string\"\n ? (params[\"name\"] as string)\n : \"unknown\";\n const callArgs = params ? params[\"arguments\"] : undefined;\n pending.set(key, { toolName, args: callArgs });\n }\n }\n\n /**\n * Inspect one parsed SERVER→CLIENT message. Matches `tools/call` results to\n * remembered requests and measures them; measures `tools/list` results once.\n * Never throws into the data path.\n */\n function onServerMessage(msg: JsonRpcMessage): void {\n const key = idKey(msg.id);\n if (key === null) return; // notifications carry no id we can correlate\n\n const pendingCall = pending.get(key);\n if (pendingCall !== undefined) {\n pending.delete(key);\n recordToolCall(pendingCall, msg);\n return;\n }\n\n // Not a tracked tools/call — it may be the tools/list result we measure\n // once for the fixed tool-definition overhead.\n if (shouldMeasureToolDefs && !toolDefsMeasured) {\n const result = isObject(msg.result) ? msg.result : undefined;\n const tools = result ? result[\"tools\"] : undefined;\n if (Array.isArray(tools)) {\n recordToolDefs(tools);\n }\n }\n }\n\n /** Measure a matched tools/call round-trip and append the record. */\n function recordToolCall(call: PendingCall, response: JsonRpcMessage): void {\n const hasError = response.error !== undefined;\n const result = response.result;\n // A JSON-RPC error has no `result`; measure against an empty object so the\n // input (args) tokens are still recorded honestly.\n const resultForMeasure = hasError ? {} : result;\n const measurement = measureToolCall(\n call.args,\n resultForMeasure,\n family,\n tokenizer,\n );\n\n // OPT-IN calibration: for an anthropic session, nudge the locally-tokenized\n // approx counts toward Anthropic's real numbers via the learned factor, and\n // fire a sampled off-box count_tokens to keep that factor fresh. Both steps\n // are best-effort and wrapped so they can never break the record path.\n let inputTokens = measurement.inputTokens;\n let outputTokens = measurement.outputTokens;\n let confidenceSource: ConfidenceSource = measurement.source;\n if (calibrationEnabled && family === \"anthropic\") {\n try {\n ({ inputTokens, outputTokens, confidenceSource } = calibrateCounts(\n measurement.inputTokens,\n measurement.outputTokens,\n measurement.source,\n ));\n maybeSampleCalibration(call.args, measurement.inputTokens);\n } catch {\n // Calibration is a non-essential enrichment — fall back to the raw\n // measurement values already captured above.\n }\n }\n\n // MCP signals a tool-level failure via result.isError===true; a JSON-RPC\n // protocol error (response.error) is also a failure.\n const resultIsError =\n isObject(result) && result[\"isError\"] === true;\n store.append({\n ...baseRecord(),\n toolName: call.toolName,\n scope: \"call\",\n inputTokens,\n outputTokens,\n confidenceSource,\n isError: hasError || resultIsError,\n });\n }\n\n /**\n * Apply the learned anthropic factor to the approx input/output counts. Only\n * a `tokenizer-approx` measurement is calibratable (a heuristic fallback or\n * host-native count is left exactly as-is); the combined source becomes\n * `tokenizer-calibrated` only when at least one side was actually scaled.\n */\n function calibrateCounts(\n rawIn: number,\n rawOut: number,\n rawSource: ConfidenceSource,\n ): { inputTokens: number; outputTokens: number; confidenceSource: ConfidenceSource } {\n if (rawSource !== \"tokenizer-approx\") {\n return { inputTokens: rawIn, outputTokens: rawOut, confidenceSource: rawSource };\n }\n const cin = applyCalibration(rawIn, family);\n const cout = applyCalibration(rawOut, family);\n const calibrated =\n cin.source === \"tokenizer-calibrated\" || cout.source === \"tokenizer-calibrated\";\n return {\n inputTokens: cin.tokens,\n outputTokens: cout.tokens,\n confidenceSource: calibrated ? \"tokenizer-calibrated\" : \"tokenizer-approx\",\n };\n }\n\n /**\n * On a SAMPLED call, fire-and-forget an off-box count_tokens for the call's\n * input args and fold the resulting exact/approx ratio into the learned\n * factor. Returns immediately — the network round-trip never blocks\n * forwarding or measurement. Fail-open: any error is swallowed.\n */\n function maybeSampleCalibration(args: unknown, approxInputTokens: number): void {\n if (approxInputTokens <= 0) return; // nothing to ratio against\n if (!shouldSample()) return;\n const text = canonicalArgs(args);\n if (text === \"\") return;\n // Detached promise — intentionally NOT awaited so the proxy never blocks on\n // the network. Errors are handled inside countTokensAnthropic (returns null)\n // and the .catch is a belt-and-braces guard against an unhandled rejection.\n void countTokensAnthropic(text, modelForFamily(family))\n .then((exact) => {\n if (exact !== null && exact > 0) {\n recordSample(family, exact / approxInputTokens);\n }\n })\n .catch(() => {\n /* fail-open: a calibration sample must never surface an error */\n });\n }\n\n /** Measure the one-time tools/list overhead and append the record. */\n function recordToolDefs(tools: readonly unknown[]): void {\n toolDefsMeasured = true;\n const count = measureToolDefs(tools, family, tokenizer);\n store.append({\n ...baseRecord(),\n toolName: \"*\",\n scope: \"tool_defs\",\n inputTokens: count.tokens,\n outputTokens: 0,\n confidenceSource: count.source,\n isError: false,\n });\n }\n\n /** Parse one NDJSON line and route it, swallowing any measurement error. */\n function handleLine(line: string, direction: \"client\" | \"server\"): void {\n if (!measuringEnabled) return;\n let msg: JsonRpcMessage;\n try {\n const parsed = JSON.parse(line) as unknown;\n if (!isObject(parsed)) return;\n msg = parsed as JsonRpcMessage;\n } catch {\n return; // not a complete/valid JSON message — ignore for telemetry\n }\n try {\n if (direction === \"client\") onClientMessage(msg);\n else onServerMessage(msg);\n } catch {\n // Measurement must NEVER break the proxy. Drop the record silently.\n }\n }\n\n const clientLines = new LineBuffer((line) => handleLine(line, \"client\"));\n const serverLines = new LineBuffer((line) => handleLine(line, \"server\"));\n\n // ── Transparent byte forwarding (host stdin → child stdin) ───────────────\n // Forward VERBATIM first, then tee a copy into the line buffer to measure.\n // Honor backpressure: if the child's stdin buffer is full, pause the host\n // stdin and resume on drain so a slow server can't make us buffer unboundedly.\n process.stdin.on(\"data\", (chunk: Buffer) => {\n if (child.stdin && child.stdin.writable) {\n const ok = child.stdin.write(chunk);\n if (!ok) {\n process.stdin.pause();\n child.stdin.once(\"drain\", () => process.stdin.resume());\n }\n }\n if (measuringEnabled) {\n try {\n clientLines.push(chunk);\n } catch {\n /* tee side-channel must never affect forwarding */\n }\n }\n });\n process.stdin.on(\"end\", () => {\n if (child.stdin && !child.stdin.destroyed) child.stdin.end();\n });\n\n // ── Transparent byte forwarding (child stdout → host stdout) ─────────────\n if (child.stdout) {\n const childStdout = child.stdout;\n childStdout.on(\"data\", (chunk: Buffer) => {\n const ok = process.stdout.write(chunk);\n if (!ok) {\n childStdout.pause();\n process.stdout.once(\"drain\", () => childStdout.resume());\n }\n if (measuringEnabled) {\n try {\n serverLines.push(chunk);\n } catch {\n /* tee side-channel must never affect forwarding */\n }\n }\n });\n }\n\n // ── Signal propagation: forward SIGINT/SIGTERM to the child ──────────────\n const forwardSignal = (signal: NodeJS.Signals): void => {\n try {\n if (!child.killed) child.kill(signal);\n } catch {\n /* child may already be gone */\n }\n };\n const onSigint = (): void => forwardSignal(\"SIGINT\");\n const onSigterm = (): void => forwardSignal(\"SIGTERM\");\n process.on(\"SIGINT\", onSigint);\n process.on(\"SIGTERM\", onSigterm);\n\n // ── Resolve with the child's exit code (or signal-derived code) ──────────\n return await new Promise<number>((resolve) => {\n const finish = (code: number): void => {\n process.removeListener(\"SIGINT\", onSigint);\n process.removeListener(\"SIGTERM\", onSigterm);\n try {\n store.close();\n } catch {\n /* best-effort flush */\n }\n resolve(code);\n };\n\n child.on(\"error\", () => {\n // The server could not be spawned/launched. Surface a conventional\n // \"command not executable\" style failure code.\n finish(126);\n });\n\n child.on(\"close\", (code, signal) => {\n if (typeof code === \"number\") {\n finish(code);\n return;\n }\n // Killed by a signal → conventional 128 + signal number where known.\n if (signal) {\n const num = signalToNumber(signal);\n finish(num === undefined ? 1 : 128 + num);\n return;\n }\n finish(1);\n });\n });\n}\n\n/** Map the common termination signals to their numbers for exit-code math. */\nfunction signalToNumber(signal: NodeJS.Signals): number | undefined {\n const table: Partial<Record<NodeJS.Signals, number>> = {\n SIGINT: 2,\n SIGQUIT: 3,\n SIGKILL: 9,\n SIGTERM: 15,\n };\n return table[signal];\n}\n\nexport default runServeProxy;\n","/**\n * runtime/usage-event — the OPT-IN host-native turn-usage enricher (enricher 4a).\n *\n * Gemini CLI / Antigravity fire an `AfterModel` (Antigravity CLI: `PostInvocation`)\n * hook AFTER each model turn, whose stdin payload carries a `usageMetadata` block\n * with the host's OWN exact token accounting for that whole conversation turn:\n * { promptTokenCount, candidatesTokenCount, cachedContentTokenCount,\n * thoughtsTokenCount, totalTokenCount }\n * This is the single point in the whole matrix where a host reports REAL per-turn\n * usage to a command we control — so we record it as `confidenceSource:\"host-native\"`\n * (the top of CONFIDENCE_RANK), upgrading those rows from the serve-proxy estimate.\n *\n * DISTINCT, NEVER-SUMMED ORIGIN. Host-native turn usage is WHOLE-CONVERSATION, not\n * per-MCP. To avoid double-counting against (a) the per-MCP serve-proxy `call`\n * rows and (b) the usage-reader host-scan numbers, every record written here uses\n * the DISTINCT scope `\"model_turn\"`. The MCP leaderboard excludes that scope (just\n * as it special-cases `tool_defs`); the unified leaderboard surfaces it as its own\n * clearly-labeled section that is explicitly never added to the other two origins.\n *\n * PRIVACY + FAIL-OPEN. This enricher is OPT-IN at install time (see the adapters);\n * it stores AGGREGATE COUNTS ONLY (no raw content — the payload's prompt/response\n * text is never read). ANY parse / store / IO error degrades to exit 0 and records\n * NOTHING: a host-native usage hook must never break a model turn. This function\n * never throws.\n */\n\nimport { projectIdentity } from \"../core/paths.js\";\nimport { newRecordId, openStore } from \"../telemetry/store.js\";\nimport type { PlatformId } from \"../core/types.js\";\nimport type { ToolEventRecord } from \"../telemetry/types.js\";\n\n/** Flags + stdin the CLI hands to {@link runUsageEvent}. */\nexport interface RunUsageEventOptions {\n /** Host platform id from the command (`usage-event <platformId> …`). */\n platformId: string;\n /** Connector id from `--connector <id>` (stamped on the record). */\n connectorId: string;\n /** Raw stdin payload (host-native JSON). Empty string is tolerated → no record. */\n stdin: string;\n}\n\n/** Process-level result the CLI translates into an exit code. */\nexport interface RunUsageEventResult {\n /** Always 0 — a host-native usage hook must never block a model turn. */\n exitCode: number;\n /** True when a `model_turn` record was appended (false on any fail-open path). */\n recorded: boolean;\n}\n\n/** The never-records, never-throws result. */\nconst NOOP: RunUsageEventResult = { exitCode: 0, recorded: false };\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\n/** Coerce a value to a non-negative safe integer (NaN/negatives/floats → 0). */\nfunction toNonNegInt(v: unknown): number {\n const n = typeof v === \"number\" ? v : typeof v === \"string\" ? Number(v) : NaN;\n if (!Number.isFinite(n) || n < 0) return 0;\n return Math.floor(n);\n}\n\n/** First non-empty string among the given keys of an object. */\nfunction firstStr(obj: Record<string, unknown>, keys: readonly string[]): string | undefined {\n for (const k of keys) {\n const v = obj[k];\n if (typeof v === \"string\" && v.trim() !== \"\") return v;\n }\n return undefined;\n}\n\n/** Read a token field tolerant of both camelCase and snake_case spellings. */\nfunction tokenField(\n meta: Record<string, unknown>,\n keys: readonly string[],\n): number {\n for (const k of keys) {\n if (k in meta) return toNonNegInt(meta[k]);\n }\n return 0;\n}\n\n/** Locate the `usageMetadata` block under either spelling, top-level or nested. */\nfunction findUsageMetadata(root: Record<string, unknown>): Record<string, unknown> | undefined {\n for (const k of [\"usageMetadata\", \"usage_metadata\"]) {\n if (isObject(root[k])) return root[k] as Record<string, unknown>;\n }\n // Some hosts nest the model response (with its usage) under a `response` /\n // `modelResponse` envelope — probe one level down, best-effort.\n for (const k of [\"response\", \"modelResponse\", \"model_response\"]) {\n const nested = root[k];\n if (isObject(nested)) {\n for (const mk of [\"usageMetadata\", \"usage_metadata\"]) {\n if (isObject(nested[mk])) return nested[mk] as Record<string, unknown>;\n }\n }\n }\n return undefined;\n}\n\n/** A registered PlatformId, or \"unknown\" when the id is not one we know. */\nconst KNOWN_PLATFORMS: ReadonlySet<string> = new Set<PlatformId>([\n \"claude-code\", \"codex\", \"cursor\", \"vscode-copilot\", \"jetbrains-copilot\",\n \"copilot-cli\", \"gemini-cli\", \"opencode\", \"kilo\", \"kilo-cli\", \"warp\", \"hermes\",\n \"openclaw\", \"zed\", \"antigravity\", \"antigravity-cli\", \"kiro\", \"qwen-code\",\n \"kimi\", \"pi\", \"omp\", \"droid\", \"roo-code\", \"trae\", \"amp\", \"codebuff\", \"mux\",\n \"crush\", \"goose\", \"synthetic\", \"unknown\",\n]);\n\nfunction asPlatformId(id: string): PlatformId {\n return (KNOWN_PLATFORMS.has(id) ? id : \"unknown\") as PlatformId;\n}\n\n/**\n * Record one host-native model turn. Parses the host's `usageMetadata`, maps it to\n * a DISTINCT `model_turn` `ToolEventRecord` (confidence `host-native`, toolName\n * `\"*\"`), and appends it to the shared telemetry store. NEVER throws and never\n * blocks the turn: every failure path resolves to {@link NOOP} (exit 0, nothing\n * recorded).\n */\nexport async function runUsageEvent(\n opts: RunUsageEventOptions,\n): Promise<RunUsageEventResult> {\n try {\n // Global telemetry kill switch is honored by the store's append (no-op when\n // AGENT_CONNECTOR_TELEMETRY=0); we still parse cheaply and let append drop it.\n const trimmed = opts.stdin.trim();\n if (trimmed === \"\") return NOOP;\n\n let raw: unknown;\n try {\n raw = JSON.parse(trimmed);\n } catch {\n return NOOP; // malformed payload → fail-open, record nothing\n }\n if (!isObject(raw)) return NOOP;\n\n const meta = findUsageMetadata(raw);\n if (meta === undefined) return NOOP;\n\n const promptTokens = tokenField(meta, [\"promptTokenCount\", \"prompt_token_count\"]);\n const candidates = tokenField(meta, [\"candidatesTokenCount\", \"candidates_token_count\"]);\n const cached = tokenField(meta, [\"cachedContentTokenCount\", \"cached_content_token_count\"]);\n const thoughts = tokenField(meta, [\"thoughtsTokenCount\", \"thoughts_token_count\"]);\n\n // promptTokenCount is cache-INCLUSIVE (Gemini-family semantics, mirrored by\n // the antigravity-shared usage reader): net fresh input = prompt - cached.\n const inputTokens = Math.max(0, promptTokens - Math.min(cached, promptTokens));\n // Output = generated candidates + reasoning (\"thoughts\") tokens.\n const outputTokens = candidates + thoughts;\n\n // A turn with no measurable tokens is not worth a row.\n if (inputTokens === 0 && outputTokens === 0) return NOOP;\n\n // Identity: prefer payload session/cwd; fall back to process.cwd() for the\n // project key so a turn always lands in a stable project partition.\n const sessionId =\n firstStr(raw, [\"session_id\", \"sessionId\", \"conversationId\", \"conversation_id\"]) ?? \"\";\n const cwd = firstStr(raw, [\"cwd\", \"workspace\", \"projectDir\", \"project_dir\"]) ?? process.cwd();\n const id = projectIdentity(cwd);\n\n const record: ToolEventRecord = {\n id: newRecordId(0),\n ts: Date.now(),\n connectorId: opts.connectorId,\n toolName: \"*\",\n scope: \"model_turn\",\n hostPlatform: asPlatformId(opts.platformId),\n sessionId,\n projectKey: id.key,\n projectDir: id.dir,\n inputTokens,\n outputTokens,\n confidenceSource: \"host-native\",\n isError: false,\n };\n\n const store = openStore({});\n try {\n store.append(record);\n } finally {\n try {\n store.close();\n } catch {\n /* best-effort flush */\n }\n }\n return { exitCode: 0, recorded: true };\n } catch {\n // Fail-open: a host-native usage enricher must never surface an error.\n return NOOP;\n }\n}\n\nexport default runUsageEvent;\n","/**\n * runtime/statusline-entrypoint — the universal statusline (HUD) renderer.\n *\n * A statusline-supporting host points its status line config at the single stable\n * home binary (`<homeBin> statusline <platformId> --connector <id>`, built by\n * core/spawn.buildHomeBinStatuslineCommand). The CLI reads stdin and calls\n * {@link runStatusline} with the parsed flags + the raw stdin string. This module:\n *\n * 1. Loads the registered connector (live render handler) and the host adapter.\n * 2. Parses the host's raw status payload into a normalized StatuslineContext.\n * 3. Calls the connector's render(ctx) and coerces the result to a string.\n * 4. Formats the line into the host's native status reply (exit code + stdout).\n *\n * FAIL-SAFE is the contract (NOT fail-open with carve-outs like hooks): a status\n * line is decorative — it must NEVER wedge the host or spew an error/stack trace\n * into the status bar. So ANY error path — bad payload, missing connector,\n * throwing render, adapter without statusline support — returns exit 0 with NO\n * stdout (an empty status line), never a non-zero exit and never partial output.\n *\n * NOTE (follow-up): no telemetry is recorded for statusline renders in v1 (out of\n * scope). When added, it MUST stay inside the same fail-safe envelope.\n */\n\nimport type { PlatformId } from \"../core/types.js\";\nimport { log } from \"../core/logger.js\";\nimport {\n loadRegisteredConnector,\n readRegisteredMeta,\n} from \"../core/load-connector.js\";\nimport { loadAdapter } from \"../adapters/registry.js\";\nimport {\n attachLazyTelemetryUsage,\n buildTelemetryAccessor,\n} from \"./telemetry-accessor.js\";\n\n/** Flags + stdin the CLI hands to {@link runStatusline}. */\nexport interface RunStatuslineOptions {\n /** Host platform id from the command (`statusline <platformId> …`). */\n platformId: string;\n /** Connector id from `--connector <id>`. */\n connectorId: string;\n /** Raw stdin payload (host-native status JSON). Empty string is tolerated → `{}`. */\n stdin: string;\n}\n\n/** Process-level result the CLI translates into exit code + stdout/stderr. */\nexport interface RunStatuslineResult {\n exitCode: number;\n stdout?: string;\n stderr?: string;\n}\n\n/** The fail-safe result: exit 0, no output (an empty status line). */\nconst EMPTY: RunStatuslineResult = { exitCode: 0 };\n\n/**\n * Tolerantly parse the host's stdin payload. Empty / whitespace-only input is a\n * legitimate \"no payload\" signal and resolves to `{}`. Malformed JSON also\n * degrades to `{}` rather than throwing — fail-safe is the contract.\n */\nfunction parseStdin(stdin: string): unknown {\n const trimmed = stdin.trim();\n if (trimmed === \"\") return {};\n try {\n return JSON.parse(trimmed);\n } catch {\n return {};\n }\n}\n\n/**\n * Render one host status-line invocation. Always resolves (never rejects): every\n * failure path returns the empty {@link EMPTY} result so the CLI exits cleanly\n * with an empty status line. See the module header for the fail-safe contract.\n */\nexport async function runStatusline(\n opts: RunStatuslineOptions,\n): Promise<RunStatuslineResult> {\n const { platformId, connectorId, stdin } = opts;\n\n try {\n const connector = await loadRegisteredConnector(connectorId);\n const adapter = await loadAdapter(platformId);\n\n // Nothing to render: no statusline declared, or the host adapter has no\n // statusline runtime support (parse/format pair). Empty line, exit 0.\n if (\n !connector.statusline ||\n typeof connector.statusline.render !== \"function\" ||\n !adapter ||\n !adapter.parseStatusInput ||\n !adapter.formatStatusOutput\n ) {\n return EMPTY;\n }\n\n const raw = parseStdin(stdin);\n const ctx = adapter.parseStatusInput(raw);\n // The command carries the authoritative connector id; stamp it so render()\n // sees the connector it was dispatched for.\n ctx.connectorId = connectorId;\n // capabilities is REQUIRED on StatuslineContext. claude-code's parseStatusInput\n // sets it, but a future/third-party adapter could omit it — backfill so the\n // runtime guarantee matches the type (mirrors the simulate harness). Never\n // let render() see undefined capabilities while the type claims it is present.\n if (ctx.capabilities == null) ctx.capabilities = adapter.capabilities;\n // Recover the install scope from the registered metadata (sync) and stamp it\n // onto the ctx — scope is an install-time property the entrypoint has no\n // other access to. Undefined when the meta carries none. Also expose the\n // per-connector telemetry usage accessor (lazy, fail-safe to zeros).\n ctx.scope = readRegisteredMeta(connectorId)?.scope;\n ctx.telemetry = buildTelemetryAccessor(connectorId);\n // Keep `ctx.usage` synchronous for render functions, but compute it only if\n // the render actually reads the property. Status lines refresh frequently,\n // and the NDJSON backend has to scan the store for an all-time summary.\n attachLazyTelemetryUsage(ctx, connectorId);\n\n // Per-host render override: when rendering for host X, `hosts[X].render`\n // wins over the top-level render; a host not listed (or a per-host entry\n // that is somehow not a function) falls back to the top-level render.\n // Selection NEVER throws — fail-safe is preserved.\n const perHost = connector.statusline.hosts?.[platformId as PlatformId]?.render;\n const render =\n typeof perHost === \"function\" ? perHost : connector.statusline.render;\n\n const rendered = await render(ctx);\n // Coerce: a non-string return (number, accidental object) is stringified so\n // a misbehaving render never crashes the format step. null/undefined → \"\".\n const line = rendered == null ? \"\" : String(rendered);\n\n const reply = adapter.formatStatusOutput(line);\n return {\n exitCode: reply.exitCode,\n ...(reply.stdout !== undefined ? { stdout: reply.stdout } : {}),\n ...(reply.stderr !== undefined ? { stderr: reply.stderr } : {}),\n };\n } catch (err) {\n // FAIL-SAFE: a status line must never wedge the host or surface an error.\n // Log for diagnostics (stderr of the home binary — not the status bar) and\n // return the empty line.\n const message = err instanceof Error ? err.message : String(err);\n log.error(`statusline ${platformId} (${connectorId}) failed:`, message);\n return EMPTY;\n }\n}\n\nexport default runStatusline;\n","/**\n * runtime/action-entrypoint — the universal user-invokable action dispatcher.\n *\n * A future host affordance (slash command / keybinding) points at the single\n * stable home binary (`<homeBin> action <platformId> <actionId> --connector\n * <id>`, built by core/spawn.buildHomeBinActionCommand). The CLI parses the\n * flags and calls {@link runAction}. This module:\n *\n * 1. Loads the registered connector (live run handler) and the host adapter.\n * 2. Builds the shared {@link HostCtx} (host + the adapter's capabilities; NO\n * stdin — an action takes no host payload, unlike a hook or status line).\n * 3. Finds the action by id, resolves the per-host run override, runs it, and\n * prints the optional result.message.\n *\n * USER-TRIGGERED ERROR SEMANTICS (the key difference from hooks/statusline):\n * actions are invoked DELIBERATELY by a user, so errors are SURFACED, never\n * failed silently. An unknown action id or a throwing run → exit 1 + a stderr\n * message. (Hooks fail-open to exit 0; the statusline fail-safes to an empty\n * line — both are passive surfaces a host fires automatically. An action is not:\n * swallowing its failure would leave the user staring at nothing, unable to\n * tell the action ran.)\n *\n * NOTE (follow-up): no telemetry is recorded for action runs in v1 (out of\n * scope), and no adapter EMITS the affordance yet — v1 ships the dispatch\n * backbone only.\n */\n\nimport type {\n HostCtx,\n PlatformCapabilities,\n PlatformId,\n} from \"../core/types.js\";\nimport {\n loadRegisteredConnector,\n readRegisteredMeta,\n} from \"../core/load-connector.js\";\nimport { loadAdapter, REGISTERED_PLATFORM_IDS } from \"../adapters/registry.js\";\nimport { buildTelemetryAccessor } from \"./telemetry-accessor.js\";\n\n/** Flags the CLI hands to {@link runAction} (no stdin — actions take no payload). */\nexport interface RunActionOptions {\n /** Host platform id from the command (`action <platformId> <actionId> …`). */\n platformId: string;\n /** Connector id from `--connector <id>`. */\n connectorId: string;\n /** The action id positional (`action <platformId> <actionId> …`). */\n actionId: string;\n}\n\n/** Process-level result the CLI translates into exit code + stdout/stderr. */\nexport interface RunActionResult {\n exitCode: number;\n stdout?: string;\n stderr?: string;\n}\n\n/**\n * Minimal all-false capabilities for the fallback ctx when the host adapter is\n * unknown/unregistered. The action still runs (it takes no host payload), but\n * branching on `ctx.capabilities` reads every flag as off — no affordance is\n * advertised for a host we cannot describe.\n */\nconst EMPTY_CAPABILITIES: PlatformCapabilities = {\n preToolUse: false,\n postToolUse: false,\n preCompact: false,\n sessionStart: false,\n sessionEnd: false,\n userPromptSubmit: false,\n stop: false,\n notification: false,\n canModifyArgs: false,\n canModifyOutput: false,\n canInjectSessionContext: false,\n transports: [],\n};\n\n/**\n * Dispatch one user-invokable action. Always resolves (never rejects): every\n * path returns a concrete {@link RunActionResult} so the CLI can exit cleanly,\n * but UNLIKE the hook/statusline runtimes an error resolves to exit 1 + a stderr\n * message (actions are user-triggered — surface the failure). See the module\n * header for the user-triggered error contract.\n */\nexport async function runAction(\n opts: RunActionOptions,\n): Promise<RunActionResult> {\n const { platformId, connectorId, actionId } = opts;\n\n let connector;\n try {\n connector = await loadRegisteredConnector(connectorId);\n } catch (err) {\n // A user asked to run an action on a connector we cannot load — surface it\n // (do NOT fail-open: the user would otherwise see nothing and assume it ran).\n const message = err instanceof Error ? err.message : String(err);\n return { exitCode: 1, stderr: message };\n }\n\n const action = connector.actions.find((a) => a.id === actionId);\n if (!action) {\n return {\n exitCode: 1,\n stderr: `no action \"${actionId}\" on connector ${connectorId}`,\n };\n }\n\n // Build the shared HostCtx. capabilities come from the adapter; an unknown\n // adapter still runs with the minimal ctx (an action takes no host payload).\n const adapter = await loadAdapter(platformId).catch(() => undefined);\n const host: PlatformId = REGISTERED_PLATFORM_IDS.has(platformId as PlatformId)\n ? (platformId as PlatformId)\n : \"unknown\";\n const ctx: HostCtx = {\n host,\n capabilities: adapter?.capabilities ?? EMPTY_CAPABILITIES,\n // Recover the install scope from the registered metadata (sync) — scope is\n // an install-time property the entrypoint otherwise has no access to —\n // and expose the per-connector telemetry usage accessor (lazy, fail-safe).\n scope: readRegisteredMeta(connectorId)?.scope,\n telemetry: buildTelemetryAccessor(connectorId),\n };\n\n // Per-host run override: when running for host X, `hosts[X].run` wins over the\n // top-level run; a host not listed (or a per-host entry that is somehow not a\n // function) falls back to the top-level run.\n const perHost = action.hosts?.[platformId as PlatformId]?.run;\n const run = typeof perHost === \"function\" ? perHost : action.run;\n\n try {\n const result = await run(ctx);\n const message = result?.message;\n if (typeof message === \"string\" && message !== \"\") {\n return { exitCode: 0, stdout: message };\n }\n // void / no message → success with no output.\n return { exitCode: 0 };\n } catch (err) {\n // USER-TRIGGERED: a throwing action surfaces its failure (exit 1 + stderr),\n // never a silent fail-open. This is the documented difference from\n // hooks/statusline.\n const message = err instanceof Error ? err.message : String(err);\n return {\n exitCode: 1,\n stderr: `action \"${actionId}\" failed: ${message}`,\n };\n }\n}\n\nexport default runAction;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBA,SAAS,kBAAkB;;;ACQ3B,SAAS,YAAY,cAAc,qBAAqB;AACxD,SAAS,YAAY;AAkBd,SAAS,uBAAgC;AAC9C,QAAM,YAAY,QAAQ,IAAI,6BAA6B,IACxD,MAAM,GAAG,EACT,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,EACnB,OAAO,CAAC,MAAM,MAAM,EAAE;AACzB,QAAM,OAAO,QAAQ,IAAI,qBAAqB,IAAI,KAAK;AACvD,SAAO,SAAS,SAAS,WAAW,KAAK,QAAQ;AACnD;AAgBO,SAAS,kBAA0B;AACxC,SAAO,KAAK,SAAS,GAAG,kBAAkB;AAC5C;AAOA,IAAM,YAAY;AAClB,IAAM,YAAY;AAElB,SAAS,WAAW,OAA8B;AAChD,MAAI,CAAC,OAAO,SAAS,KAAK,KAAK,SAAS,EAAG,QAAO;AAClD,MAAI,QAAQ,UAAW,QAAO;AAC9B,MAAI,QAAQ,UAAW,QAAO;AAC9B,SAAO;AACT;AAMO,SAAS,cAAkC;AAChD,QAAM,OAAO,gBAAgB;AAC7B,MAAI,CAAC,WAAW,IAAI,EAAG,QAAO,CAAC;AAC/B,MAAI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