@ken-jo/agent-connector 0.4.0 → 0.4.6

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 (185) hide show
  1. package/README.md +9 -9
  2. package/dist/{action-PLZW5BGX.js → action-EV63GAPY.js} +11 -10
  3. package/dist/{action-PLZW5BGX.js.map → action-EV63GAPY.js.map} +1 -1
  4. package/dist/amazon-q-COAL3764.js +276 -0
  5. package/dist/amazon-q-COAL3764.js.map +1 -0
  6. package/dist/amp-XJQ4TDAU.js +666 -0
  7. package/dist/amp-XJQ4TDAU.js.map +1 -0
  8. package/dist/{antigravity-ANDKF3K7.js → antigravity-AMKKKHS4.js} +4 -4
  9. package/dist/{antigravity-cli-LLRPDDOT.js → antigravity-cli-XERXEH5W.js} +4 -4
  10. package/dist/{chunk-MAH6QQTO.js → chunk-2X4EH2D7.js} +5 -4
  11. package/dist/chunk-2X4EH2D7.js.map +1 -0
  12. package/dist/{chunk-G3ER4SY5.js → chunk-5G4EPJ4Y.js} +9 -9
  13. package/dist/chunk-BMD7ANKF.js +237 -0
  14. package/dist/chunk-BMD7ANKF.js.map +1 -0
  15. package/dist/{chunk-IW77FFNX.js → chunk-CPLK7GTE.js} +41 -5
  16. package/dist/chunk-CPLK7GTE.js.map +1 -0
  17. package/dist/{chunk-ADTHT2FN.js → chunk-DCK5FADX.js} +10 -173
  18. package/dist/chunk-DCK5FADX.js.map +1 -0
  19. package/dist/{chunk-J3D5W5T2.js → chunk-EROJDXMW.js} +2 -2
  20. package/dist/{chunk-22Y24V7O.js → chunk-F5RX62T7.js} +2 -2
  21. package/dist/chunk-FAHIMJRU.js +177 -0
  22. package/dist/chunk-FAHIMJRU.js.map +1 -0
  23. package/dist/{chunk-BHUCB6LY.js → chunk-H67V7DEL.js} +8 -7
  24. package/dist/{chunk-BHUCB6LY.js.map → chunk-H67V7DEL.js.map} +1 -1
  25. package/dist/{chunk-BXGFUENQ.js → chunk-I5MLE6S7.js} +14 -1
  26. package/dist/{chunk-BXGFUENQ.js.map → chunk-I5MLE6S7.js.map} +1 -1
  27. package/dist/{chunk-LL4OBGRU.js → chunk-LQRAPXS4.js} +3 -3
  28. package/dist/{chunk-KGJWE6A2.js → chunk-MZF2YCXX.js} +2 -2
  29. package/dist/{chunk-KGXDYGNJ.js → chunk-QC5A3TFQ.js} +19 -19
  30. package/dist/{chunk-KGXDYGNJ.js.map → chunk-QC5A3TFQ.js.map} +1 -1
  31. package/dist/{chunk-CIRDOY2V.js → chunk-QOGMDOUX.js} +3 -3
  32. package/dist/{chunk-KGGBNKI4.js → chunk-RQPKL62M.js} +144 -21
  33. package/dist/chunk-RQPKL62M.js.map +1 -0
  34. package/dist/{chunk-6XHB6BE3.js → chunk-SCVBYSF7.js} +1 -1
  35. package/dist/{chunk-76FUSVIA.js → chunk-SRVAA2VN.js} +6 -5
  36. package/dist/chunk-SRVAA2VN.js.map +1 -0
  37. package/dist/chunk-WZA4CSGJ.js +28 -0
  38. package/dist/chunk-WZA4CSGJ.js.map +1 -0
  39. package/dist/{claude-code-MLWS7CW6.js → claude-code-T2LPFNC3.js} +20 -30
  40. package/dist/claude-code-T2LPFNC3.js.map +1 -0
  41. package/dist/cli/sdk.js +5 -4
  42. package/dist/cli/sdk.js.map +1 -1
  43. package/dist/cli.js +1 -1
  44. package/dist/cline-WRYMNS7Z.js +442 -0
  45. package/dist/cline-WRYMNS7Z.js.map +1 -0
  46. package/dist/{codebuff-SH2S3QAN.js → codebuff-PODYPOOP.js} +130 -5
  47. package/dist/codebuff-PODYPOOP.js.map +1 -0
  48. package/dist/{codex-BXA4FIF4.js → codex-O4G7D7KK.js} +61 -13
  49. package/dist/codex-O4G7D7KK.js.map +1 -0
  50. package/dist/continue-K43SUHLQ.js +790 -0
  51. package/dist/continue-K43SUHLQ.js.map +1 -0
  52. package/dist/{copilot-cli-ROIBTTDT.js → copilot-cli-Q3SSPT4V.js} +70 -12
  53. package/dist/copilot-cli-Q3SSPT4V.js.map +1 -0
  54. package/dist/{crush-QLEFLHUC.js → crush-MBEH2R3I.js} +130 -6
  55. package/dist/crush-MBEH2R3I.js.map +1 -0
  56. package/dist/{cursor-ASJPWZ4R.js → cursor-TMBXDYR4.js} +119 -19
  57. package/dist/cursor-TMBXDYR4.js.map +1 -0
  58. package/dist/{detect-ZIIS55LD.js → detect-AHJIUMBO.js} +5 -4
  59. package/dist/{detect-ZIIS55LD.js.map → detect-AHJIUMBO.js.map} +1 -1
  60. package/dist/{doctor-TJUGSQ5C.js → doctor-G5MLCPAB.js} +221 -95
  61. package/dist/doctor-G5MLCPAB.js.map +1 -0
  62. package/dist/{droid-NCSS3B5Y.js → droid-JC2NT6S4.js} +135 -13
  63. package/dist/droid-JC2NT6S4.js.map +1 -0
  64. package/dist/{gemini-cli-SLVWLXJW.js → gemini-cli-ILR7M5X3.js} +62 -10
  65. package/dist/gemini-cli-ILR7M5X3.js.map +1 -0
  66. package/dist/{goose-PBA7KTE5.js → goose-SFO5BBGW.js} +15 -8
  67. package/dist/goose-SFO5BBGW.js.map +1 -0
  68. package/dist/{hermes-ONDCECP2.js → hermes-3N7WN4WS.js} +329 -15
  69. package/dist/hermes-3N7WN4WS.js.map +1 -0
  70. package/dist/{hook-OU522ABV.js → hook-76JBKTUX.js} +14 -11
  71. package/dist/hook-76JBKTUX.js.map +1 -0
  72. package/dist/index.d.ts +2 -2
  73. package/dist/index.js +3 -2
  74. package/dist/{install-UDCBL7HP.js → install-R7252QFH.js} +11 -10
  75. package/dist/{install-UDCBL7HP.js.map → install-R7252QFH.js.map} +1 -1
  76. package/dist/{introspect-DuZSPSHB.d.ts → introspect-Cn3MSA4_.d.ts} +1 -1
  77. package/dist/{jetbrains-copilot-YABZ3HFA.js → jetbrains-copilot-NRZHI5PC.js} +85 -18
  78. package/dist/jetbrains-copilot-NRZHI5PC.js.map +1 -0
  79. package/dist/{kilo-F3ZDZKCT.js → kilo-IX4T3OHJ.js} +115 -19
  80. package/dist/kilo-IX4T3OHJ.js.map +1 -0
  81. package/dist/{kilo-cli-3HWPWBY4.js → kilo-cli-2AYCXBQD.js} +109 -13
  82. package/dist/kilo-cli-2AYCXBQD.js.map +1 -0
  83. package/dist/{kimi-NV72FVAO.js → kimi-2YFK2GBA.js} +87 -25
  84. package/dist/kimi-2YFK2GBA.js.map +1 -0
  85. package/dist/{kiro-C5W6AGDR.js → kiro-YL6AWUYG.js} +3 -3
  86. package/dist/{leaderboard-TIBVONVT.js → leaderboard-V6VWA5ZV.js} +3 -3
  87. package/dist/{mimo-code-IMM5YM3M.js → mimo-code-FTMGSKMQ.js} +41 -5
  88. package/dist/mimo-code-FTMGSKMQ.js.map +1 -0
  89. package/dist/{mux-DSSH4AFS.js → mux-5XZFB44C.js} +156 -6
  90. package/dist/mux-5XZFB44C.js.map +1 -0
  91. package/dist/{nemoclaw-3EVNKD3I.js → nemoclaw-CQYXZVQN.js} +4 -4
  92. package/dist/{omp-Z6FRNDPN.js → omp-2QMEY6HD.js} +138 -18
  93. package/dist/omp-2QMEY6HD.js.map +1 -0
  94. package/dist/{openclaw-7G437NT7.js → openclaw-UZC437RW.js} +4 -4
  95. package/dist/{opencode-Q6KBSAKW.js → opencode-L4BGFP25.js} +87 -27
  96. package/dist/opencode-L4BGFP25.js.map +1 -0
  97. package/dist/{package-RMPN57YZ.js → package-DNLQTPNN.js} +8 -7
  98. package/dist/{package-RMPN57YZ.js.map → package-DNLQTPNN.js.map} +1 -1
  99. package/dist/{pi-LZT6WWAZ.js → pi-PVVPVWKG.js} +3 -2
  100. package/dist/{pi-LZT6WWAZ.js.map → pi-PVVPVWKG.js.map} +1 -1
  101. package/dist/{qwen-code-WQBKRPWJ.js → qwen-code-G4CXKUHR.js} +426 -10
  102. package/dist/qwen-code-G4CXKUHR.js.map +1 -0
  103. package/dist/{roo-code-GWSNU3OW.js → roo-code-67TYJIQR.js} +3 -3
  104. package/dist/runtime/index.d.ts +1 -1
  105. package/dist/runtime/index.js +9 -8
  106. package/dist/sdk/index.d.ts +3 -3
  107. package/dist/sdk/index.js +4 -3
  108. package/dist/sdk/index.js.map +1 -1
  109. package/dist/sdk/test.d.ts +2 -2
  110. package/dist/sdk/test.js +6 -5
  111. package/dist/sdk/test.js.map +1 -1
  112. package/dist/{serve-D3GO36UT.js → serve-EOVWYBGZ.js} +11 -10
  113. package/dist/{serve-D3GO36UT.js.map → serve-EOVWYBGZ.js.map} +1 -1
  114. package/dist/{status-KOSKCETC.js → status-VTD6XXLW.js} +7 -6
  115. package/dist/{status-KOSKCETC.js.map → status-VTD6XXLW.js.map} +1 -1
  116. package/dist/{statusline-ZNTCL5YC.js → statusline-3ET5YPQ5.js} +10 -9
  117. package/dist/{statusline-ZNTCL5YC.js.map → statusline-3ET5YPQ5.js.map} +1 -1
  118. package/dist/{telemetry-XIKUUGTQ.js → telemetry-QCTMKDBQ.js} +6 -5
  119. package/dist/{telemetry-XIKUUGTQ.js.map → telemetry-QCTMKDBQ.js.map} +1 -1
  120. package/dist/{trae-NWT3TMSZ.js → trae-7CZZGOGI.js} +3 -3
  121. package/dist/{types-BEKsAium.d.ts → types-_6arHbX9.d.ts} +67 -24
  122. package/dist/{uninstall-2LBLQVFA.js → uninstall-FL3SH2DT.js} +11 -10
  123. package/dist/{uninstall-2LBLQVFA.js.map → uninstall-FL3SH2DT.js.map} +1 -1
  124. package/dist/{upgrade-ZC2S7VRN.js → upgrade-SLFG2FCT.js} +11 -10
  125. package/dist/{upgrade-ZC2S7VRN.js.map → upgrade-SLFG2FCT.js.map} +1 -1
  126. package/dist/{usage-E2A4O2CY.js → usage-IRBLVUZM.js} +3 -3
  127. package/dist/{usage-event-JKMC4QC4.js → usage-event-VFF77WYY.js} +10 -9
  128. package/dist/{usage-event-JKMC4QC4.js.map → usage-event-VFF77WYY.js.map} +1 -1
  129. package/dist/{vscode-copilot-ALV45XF6.js → vscode-copilot-MF2CDNMT.js} +23 -10
  130. package/dist/vscode-copilot-MF2CDNMT.js.map +1 -0
  131. package/dist/{warp-H6IX4U3J.js → warp-VKG55TAT.js} +55 -4
  132. package/dist/warp-VKG55TAT.js.map +1 -0
  133. package/dist/windsurf-FU5G4SHF.js +443 -0
  134. package/dist/windsurf-FU5G4SHF.js.map +1 -0
  135. package/dist/{zed-RH34TNSW.js → zed-SFUHL3GS.js} +3 -3
  136. package/package.json +2 -2
  137. package/dist/amp-B524U6LO.js +0 -300
  138. package/dist/amp-B524U6LO.js.map +0 -1
  139. package/dist/chunk-3PFFTFCU.js +0 -190
  140. package/dist/chunk-3PFFTFCU.js.map +0 -1
  141. package/dist/chunk-76FUSVIA.js.map +0 -1
  142. package/dist/chunk-ADTHT2FN.js.map +0 -1
  143. package/dist/chunk-IW77FFNX.js.map +0 -1
  144. package/dist/chunk-KGGBNKI4.js.map +0 -1
  145. package/dist/chunk-MAH6QQTO.js.map +0 -1
  146. package/dist/claude-code-MLWS7CW6.js.map +0 -1
  147. package/dist/codebuff-SH2S3QAN.js.map +0 -1
  148. package/dist/codex-BXA4FIF4.js.map +0 -1
  149. package/dist/copilot-cli-ROIBTTDT.js.map +0 -1
  150. package/dist/crush-QLEFLHUC.js.map +0 -1
  151. package/dist/cursor-ASJPWZ4R.js.map +0 -1
  152. package/dist/doctor-TJUGSQ5C.js.map +0 -1
  153. package/dist/droid-NCSS3B5Y.js.map +0 -1
  154. package/dist/gemini-cli-SLVWLXJW.js.map +0 -1
  155. package/dist/goose-PBA7KTE5.js.map +0 -1
  156. package/dist/hermes-ONDCECP2.js.map +0 -1
  157. package/dist/hook-OU522ABV.js.map +0 -1
  158. package/dist/jetbrains-copilot-YABZ3HFA.js.map +0 -1
  159. package/dist/kilo-F3ZDZKCT.js.map +0 -1
  160. package/dist/kilo-cli-3HWPWBY4.js.map +0 -1
  161. package/dist/kimi-NV72FVAO.js.map +0 -1
  162. package/dist/mimo-code-IMM5YM3M.js.map +0 -1
  163. package/dist/mux-DSSH4AFS.js.map +0 -1
  164. package/dist/omp-Z6FRNDPN.js.map +0 -1
  165. package/dist/opencode-Q6KBSAKW.js.map +0 -1
  166. package/dist/qwen-code-WQBKRPWJ.js.map +0 -1
  167. package/dist/vscode-copilot-ALV45XF6.js.map +0 -1
  168. package/dist/warp-H6IX4U3J.js.map +0 -1
  169. /package/dist/{antigravity-ANDKF3K7.js.map → antigravity-AMKKKHS4.js.map} +0 -0
  170. /package/dist/{antigravity-cli-LLRPDDOT.js.map → antigravity-cli-XERXEH5W.js.map} +0 -0
  171. /package/dist/{chunk-G3ER4SY5.js.map → chunk-5G4EPJ4Y.js.map} +0 -0
  172. /package/dist/{chunk-J3D5W5T2.js.map → chunk-EROJDXMW.js.map} +0 -0
  173. /package/dist/{chunk-22Y24V7O.js.map → chunk-F5RX62T7.js.map} +0 -0
  174. /package/dist/{chunk-LL4OBGRU.js.map → chunk-LQRAPXS4.js.map} +0 -0
  175. /package/dist/{chunk-KGJWE6A2.js.map → chunk-MZF2YCXX.js.map} +0 -0
  176. /package/dist/{chunk-CIRDOY2V.js.map → chunk-QOGMDOUX.js.map} +0 -0
  177. /package/dist/{chunk-6XHB6BE3.js.map → chunk-SCVBYSF7.js.map} +0 -0
  178. /package/dist/{kiro-C5W6AGDR.js.map → kiro-YL6AWUYG.js.map} +0 -0
  179. /package/dist/{leaderboard-TIBVONVT.js.map → leaderboard-V6VWA5ZV.js.map} +0 -0
  180. /package/dist/{nemoclaw-3EVNKD3I.js.map → nemoclaw-CQYXZVQN.js.map} +0 -0
  181. /package/dist/{openclaw-7G437NT7.js.map → openclaw-UZC437RW.js.map} +0 -0
  182. /package/dist/{roo-code-GWSNU3OW.js.map → roo-code-67TYJIQR.js.map} +0 -0
  183. /package/dist/{trae-NWT3TMSZ.js.map → trae-7CZZGOGI.js.map} +0 -0
  184. /package/dist/{usage-E2A4O2CY.js.map → usage-IRBLVUZM.js.map} +0 -0
  185. /package/dist/{zed-RH34TNSW.js.map → zed-SFUHL3GS.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/package.ts","../src/core/package-formats/claude-family.ts","../src/core/package-formats/shared.ts","../src/core/package-formats/cursor.ts","../src/core/package-formats/gemini.ts","../src/core/package-formats/agy.ts","../src/core/package-formats/kimi.ts","../src/core/package-formats/npm.ts","../src/core/package-formats/mcp-server.ts","../src/core/package-formats/mcpb.ts"],"sourcesContent":["/**\n * core/package — emit a marketplace/extension-installable connector bundle.\n *\n * Turns a {@link ResolvedConnector} into a self-contained plugin/extension bundle\n * for ANY of the emit-feasible plugin/marketplace formats the agent ecosystem\n * supports. The format-specific emitters live under `package-formats/<family>.ts`,\n * each conforming to the shared {@link FormatEmitter} signature; this module is\n * the single, consistent dispatch over them.\n *\n * Supported formats (PackageFormat):\n * • claude-plugin — Claude Code / codex / vscode-copilot / openclaw / omp\n * • codex-plugin — Codex `.codex-plugin/` manifest variant of claude-plugin\n * • factory-plugin — droid `.factory-plugin/` (droids/, mcp.json) variant\n * • gemini-extension — Gemini CLI extension (gemini-extension.json + TOML commands)\n * • qwen-extension — Qwen Code extension (qwen-extension.json + Markdown commands)\n * • agy-plugin — Antigravity CLI/IDE (root plugin.json + mcp_config.json)\n * • cursor-plugin — Cursor (.cursor-plugin/ + pointer fields + marketplace.json)\n * • kimi-plugin — Kimi (skills + MCP only; hooks/commands/subagents dropped)\n * • npm-plugin — opencode / kilo-cli / pi (publishable npm package + bridge)\n *\n * The command / skill / subagent markdown is rendered through the SAME shared\n * claude-code renderers the live adapters write with (where the target uses\n * markdown), hooks via buildHomeBinHookCommand, and MCP via buildServeWrapperCommand\n * with `--host <platform>` — so telemetry-wrap + the universal home-bin pointer\n * carry through every bundle exactly as an `agent-connector install` would.\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\n\nimport type { ResolvedConnector } from \"./types.js\";\nimport { homeBinPath as defaultHomeBinPath } from \"./paths.js\";\nimport type { EmitContext, FormatEmitter, PackageResult } from \"./package-formats/shared.js\";\nimport {\n emitClaudePlugin,\n emitCodexPlugin,\n emitFactoryPlugin,\n} from \"./package-formats/claude-family.js\";\nimport { emitCursorPlugin } from \"./package-formats/cursor.js\";\nimport {\n emitGeminiExtension,\n emitQwenExtension,\n} from \"./package-formats/gemini.js\";\nimport { emitAgyPlugin } from \"./package-formats/agy.js\";\nimport { emitKimiPlugin } from \"./package-formats/kimi.js\";\nimport { emitNpmPlugin } from \"./package-formats/npm.js\";\nimport { emitMcpServerJson } from \"./package-formats/mcp-server.js\";\nimport { emitMcpbBundle } from \"./package-formats/mcpb.js\";\n\nexport type { PackageResult } from \"./package-formats/shared.js\";\n\n/** Every packaging format `package` can emit. */\nexport type PackageFormat =\n | \"claude-plugin\"\n | \"codex-plugin\"\n | \"factory-plugin\"\n | \"gemini-extension\"\n | \"qwen-extension\"\n | \"agy-plugin\"\n | \"cursor-plugin\"\n | \"kimi-plugin\"\n | \"npm-plugin\"\n // Official MCP standard artifacts (describe the dev's REAL upstream server,\n // not our serve wrapper; require `publish` metadata, so they are opt-in and\n // excluded from `--format all`).\n | \"mcp-server-json\"\n | \"mcpb\";\n\n/** The single consistent dispatch map: format → emitter. */\nconst EMITTERS: Record<PackageFormat, FormatEmitter> = {\n \"claude-plugin\": emitClaudePlugin,\n \"codex-plugin\": emitCodexPlugin,\n \"factory-plugin\": emitFactoryPlugin,\n \"gemini-extension\": emitGeminiExtension,\n \"qwen-extension\": emitQwenExtension,\n \"agy-plugin\": emitAgyPlugin,\n \"cursor-plugin\": emitCursorPlugin,\n \"kimi-plugin\": emitKimiPlugin,\n \"npm-plugin\": emitNpmPlugin,\n \"mcp-server-json\": emitMcpServerJson,\n mcpb: emitMcpbBundle,\n};\n\n/** All formats, in a stable, documented order. */\nexport const ALL_FORMATS: readonly PackageFormat[] = [\n \"claude-plugin\",\n \"codex-plugin\",\n \"factory-plugin\",\n \"gemini-extension\",\n \"qwen-extension\",\n \"agy-plugin\",\n \"cursor-plugin\",\n \"kimi-plugin\",\n \"npm-plugin\",\n \"mcp-server-json\",\n \"mcpb\",\n] as const;\n\n/**\n * The formats `--format all` emits — the host plugin/marketplace bundles that\n * work for ANY connector. The official MCP standard artifacts (mcp-server-json,\n * and the MCPB bundle) are deliberately EXCLUDED: they require `publish`\n * metadata (a namespace the dev owns, their published package) and would error\n * for a connector that has not opted into publishing, so they are emitted only\n * when requested explicitly by name.\n */\nexport const FEASIBLE_FORMATS: readonly PackageFormat[] = [\n \"claude-plugin\",\n \"codex-plugin\",\n \"factory-plugin\",\n \"gemini-extension\",\n \"qwen-extension\",\n \"agy-plugin\",\n \"cursor-plugin\",\n \"kimi-plugin\",\n \"npm-plugin\",\n] as const;\n\n/** Type guard: is `s` a supported {@link PackageFormat}? */\nexport function isPackageFormat(s: string): s is PackageFormat {\n return Object.prototype.hasOwnProperty.call(EMITTERS, s);\n}\n\nexport interface PackageOptions {\n /** Directory the bundle is written under (the format root). */\n outDir: string;\n /** Output format. Defaults to \"claude-plugin\". */\n format?: PackageFormat;\n /**\n * Absolute path to agent-connector's stable home-bin that hooks + the MCP\n * serve-wrapper point at. Defaults to {@link defaultHomeBinPath}.\n */\n homeBinPath?: string;\n /** Compute the file list without writing anything. */\n dryRun?: boolean;\n}\n\n/**\n * Emit a bundle for `connector` in a single `format` (default claude-plugin).\n *\n * Writes (or, for dryRun, only enumerates) the bundle under `opts.outDir`.\n * Returns the absolute file list, the plugin root dir, an optional marketplace\n * path, and optional drop notes (for lossy formats like kimi-plugin).\n */\n/**\n * Host-bundle formats whose hooks/MCP entries embed the ABSOLUTE home-bin path\n * of the machine that ran `package`. They install fine locally, but on another\n * machine/user the baked path points at nothing — so every emit carries a note.\n * (npm-plugin resolves the CLI by name on PATH; mcp-server-json/mcpb describe\n * the dev's real upstream server — none of those embed a local path.)\n */\nconst HOME_BIN_EMBED_FORMATS: ReadonlySet<PackageFormat> = new Set([\n \"claude-plugin\",\n \"codex-plugin\",\n \"factory-plugin\",\n \"gemini-extension\",\n \"qwen-extension\",\n \"agy-plugin\",\n \"cursor-plugin\",\n \"kimi-plugin\",\n]);\n\nexport function packageConnector(\n connector: ResolvedConnector,\n opts: PackageOptions,\n): PackageResult {\n const format = opts.format ?? \"claude-plugin\";\n const emitter = EMITTERS[format];\n if (!emitter) {\n throw new Error(`unsupported package format: ${format}`);\n }\n\n const ctx: EmitContext = {\n outDir: resolve(opts.outDir),\n homeBinPath: opts.homeBinPath ?? defaultHomeBinPath(),\n dryRun: opts.dryRun ?? false,\n };\n const result = emitter(connector, ctx);\n if (HOME_BIN_EMBED_FORMATS.has(format)) {\n const note =\n `bundle embeds this machine's agent-connector launcher path (${ctx.homeBinPath}) — ` +\n \"valid for LOCAL install; for a shared marketplace, consumers need agent-connector \" +\n \"at the same home path (run `agent-connector upgrade` there) or re-run `package` per machine\";\n result.notes = [...(result.notes ?? []), note];\n }\n return result;\n}\n\n/** One entry in a multi-format ({@link packageConnectorAll}) emit. */\nexport interface MultiPackageResult {\n format: PackageFormat;\n result: PackageResult;\n}\n\n/**\n * Emit EVERY feasible format, each into its own `<outDir>/<format>/` subdir, so a\n * single `package --format all` produces the whole matrix without collisions.\n */\nexport function packageConnectorAll(\n connector: ResolvedConnector,\n opts: { outDir: string; homeBinPath?: string; dryRun?: boolean },\n): MultiPackageResult[] {\n const base = resolve(opts.outDir);\n const homeBin = opts.homeBinPath ?? defaultHomeBinPath();\n const dryRun = opts.dryRun ?? false;\n return FEASIBLE_FORMATS.map((format) => ({\n format,\n result: packageConnector(connector, {\n outDir: resolve(base, format),\n format,\n homeBinPath: homeBin,\n dryRun,\n }),\n }));\n}\n\n/**\n * Per-format MANUAL install commands (the accurate two-step add+install where\n * applicable). Lives in core (not the CLI) so both `package`'s printed\n * instructions and the marketplace method's skip-warn records for non-drivable\n * hosts quote the SAME commands — one copy, no drift.\n */\nexport function installInstructions(\n format: PackageFormat,\n id: string,\n outDir: string,\n): string[] {\n switch (format) {\n case \"claude-plugin\":\n return [\n `/plugin marketplace add ${outDir}`,\n `/plugin install ${id}@agent-connector`,\n `(CLI: claude plugin marketplace add ${outDir} && claude plugin install ${id}@agent-connector)`,\n ];\n case \"codex-plugin\":\n return [\n `codex plugin marketplace add ${outDir}`,\n `codex plugin add ${id}@agent-connector`,\n ];\n case \"factory-plugin\":\n return [\n `droid plugin marketplace add ${outDir}`,\n `droid plugin install ${id}@agent-connector`,\n ];\n case \"gemini-extension\":\n return [`gemini extensions install ${join(outDir, id)}`];\n case \"qwen-extension\":\n return [`qwen extensions install ${join(outDir, id)}`];\n case \"agy-plugin\":\n return [\n `agy plugin install ${join(outDir, id)}`,\n `(validate: agy plugin validate ${join(outDir, id)})`,\n ];\n case \"cursor-plugin\":\n return [\n `link ${join(outDir, id)} into ~/.cursor/plugins/local/${id}/ then Developer: Reload Window`,\n `(or publish ${outDir} as a Cursor marketplace repo)`,\n ];\n case \"kimi-plugin\":\n return [`kimi plugin install ${join(outDir, id)}`];\n case \"npm-plugin\":\n return [\n `npm publish ${join(outDir, id)} (then: opencode plugin install <pkg> | kilo plugin <pkg> | pi install npm:<pkg>)`,\n ];\n case \"mcp-server-json\":\n return [\n `mcp-publisher login <github|dns|http> (prove ownership of your namespace once)`,\n `cd ${outDir} && mcp-publisher publish (uploads server.json to the official MCP Registry)`,\n ];\n case \"mcpb\":\n return [\n `vendor your built server under ${join(outDir, \"server\")}/ (see the emitted README)`,\n `npx @anthropic-ai/mcpb pack ${outDir} (then optionally: mcpb sign)`,\n ];\n default:\n return [];\n }\n}\n\n/** Read + parse a JSON file (used by callers/tests). Returns null on absence/parse error. */\nexport function readPackagedJson<T = unknown>(path: string): T | null {\n if (!existsSync(path)) return null;\n try {\n return JSON.parse(readFileSync(path, \"utf8\")) as T;\n } catch {\n return null;\n }\n}\n","/**\n * core/package-formats/claude-family — the claude-plugin emitter + its two\n * manifest-rename siblings (codex-plugin, factory-plugin).\n *\n * All three share ONE component tree (commands/ agents-or-droids/ skills/<n>/\n * SKILL.md + hooks/hooks.json + an MCP json) and differ only in:\n * • the manifest DIR + filename (.claude-plugin/ | .codex-plugin/ | .factory-plugin/)\n * • the subagent dir name (agents/ vs droids/ for factory)\n * • the MCP filename (.mcp.json vs mcp.json for factory)\n * • the manifest extra fields (claude adds $schema; factory pins version+author)\n * • the marketplace catalog shape (claude/codex object-owner; factory git-repo catalog)\n *\n * The command / skill / subagent markdown is rendered through the SAME shared\n * claude-code renderers the live adapter writes with, so an installed plugin and\n * an `agent-connector install` produce byte-identical content files. Hooks use\n * the universal home-bin command (telemetry-routed) and the MCP entry is\n * serve-wrapped with `--host <platform>` so telemetry carries through.\n */\n\nimport { join } from \"node:path\";\n\nimport type { PlatformId, ResolvedConnector } from \"../types.js\";\nimport {\n renderCommandMd,\n renderSkillMd,\n renderSubagentMd,\n} from \"../../adapters/claude-code/render.js\";\nimport {\n buildClaudeHooksJson,\n buildMcpEntry,\n createEmitter,\n json,\n resolveWithin,\n type EmitContext,\n type FormatEmitter,\n type PackageResult,\n} from \"./shared.js\";\n\n/** Per-variant layout + manifest knobs for a Claude-family bundle. */\ninterface ClaudeFamilySpec {\n /** Host platform stamped into the serve-wrapper + hook command (--host). */\n platformId: PlatformId;\n /** Manifest directory under the plugin root (e.g. \".claude-plugin\"). */\n manifestDir: string;\n /** Subagent directory name (claude/codex: \"agents\"; factory: \"droids\"). */\n subagentDir: string;\n /** MCP filename at the plugin root (claude/codex: \".mcp.json\"; factory: \"mcp.json\"). */\n mcpFile: string;\n /** Add `$schema` to plugin.json (claude only). */\n schemaUrl?: string;\n /** Always carry a version in plugin.json, defaulting placeholder to \"0.0.1\" (factory requires it). */\n requireVersion?: boolean;\n /** Always carry an `author` object in plugin.json (factory pins it). */\n alwaysAuthor?: boolean;\n /**\n * Where to write the marketplace catalog, relative to outDir, and which shape.\n * \"claude\": <outDir>/.claude-plugin/marketplace.json (object owner).\n * \"codex\": <outDir>/.agents/plugins/marketplace.json (same object-owner\n * catalog; codex's documented location — `codex plugin marketplace\n * add` REJECTS a `.codex-plugin/` catalog with \"marketplace root\n * does not contain a supported manifest\"; live-verified 0.139.0).\n * \"factory\":<outDir>/marketplace.json (git-repo catalog at the repo root).\n */\n marketplace: { dir: string | null; file: string; shape: \"claude\" | \"factory\" };\n}\n\nconst SPECS: Record<string, ClaudeFamilySpec> = {\n \"claude-plugin\": {\n platformId: \"claude-code\",\n manifestDir: \".claude-plugin\",\n subagentDir: \"agents\",\n mcpFile: \".mcp.json\",\n schemaUrl: \"https://json.schemastore.org/claude-code-plugin-manifest.json\",\n marketplace: { dir: \".claude-plugin\", file: \"marketplace.json\", shape: \"claude\" },\n },\n \"codex-plugin\": {\n platformId: \"codex\",\n manifestDir: \".codex-plugin\",\n subagentDir: \"agents\",\n mcpFile: \".mcp.json\",\n marketplace: {\n dir: join(\".agents\", \"plugins\"),\n file: \"marketplace.json\",\n shape: \"claude\",\n },\n },\n \"factory-plugin\": {\n platformId: \"droid\",\n manifestDir: \".factory-plugin\",\n subagentDir: \"droids\",\n mcpFile: \"mcp.json\",\n requireVersion: true,\n alwaysAuthor: true,\n // droid marketplaces are Git-repo catalogs; the catalog sits at the repo root.\n marketplace: { dir: null, file: \"marketplace.json\", shape: \"factory\" },\n },\n};\n\n/** Build the plugin manifest for a Claude-family variant. */\nfunction buildManifest(\n connector: ResolvedConnector,\n spec: ClaudeFamilySpec,\n): Record<string, unknown> {\n const manifest: Record<string, unknown> = {};\n if (spec.schemaUrl) manifest.$schema = spec.schemaUrl;\n manifest.name = connector.id;\n manifest.description = `${connector.displayName} — connector emitted by agent-connector`;\n\n const hasRealVersion = connector.version && connector.version !== \"0.0.0\";\n if (hasRealVersion) {\n manifest.version = connector.version;\n } else if (spec.requireVersion) {\n // factory requires a semver version; supply a sane default when unpinned.\n manifest.version = \"0.0.1\";\n }\n // Attribute the bundle to the connector developer when they declared an\n // author (publish.author); the framework name is only the fallback.\n if (spec.alwaysAuthor) {\n manifest.author = { name: connector.publish?.author?.name ?? \"agent-connector\" };\n }\n return manifest;\n}\n\n/** Build the marketplace catalog for a Claude-family variant. */\nfunction buildMarketplace(connector: ResolvedConnector): Record<string, unknown> {\n // Both the claude/codex object-owner catalog and the droid git-repo catalog\n // use the same minimal { name, owner, plugins:[{name,source,description}] }\n // shape — droid reads source as a path relative to the marketplace repo root.\n // The catalog NAME stays \"agent-connector\" (the printed install instructions\n // `<id>@agent-connector` key on it); the OWNER is the developer when known.\n return {\n name: \"agent-connector\",\n owner: { name: connector.publish?.author?.name ?? \"agent-connector\" },\n plugins: [\n {\n name: connector.id,\n source: `./${connector.id}`,\n description: `${connector.displayName} — connector emitted by agent-connector`,\n },\n ],\n };\n}\n\n/** Emit a Claude-family bundle (claude-plugin | codex-plugin | factory-plugin). */\nfunction emitClaudeFamily(\n connector: ResolvedConnector,\n ctx: EmitContext,\n format: keyof typeof SPECS,\n): PackageResult {\n const spec = SPECS[format];\n if (!spec) throw new Error(`unknown claude-family format: ${format}`);\n\n const { emit, files } = createEmitter(ctx.dryRun);\n const pluginDir = join(ctx.outDir, connector.id);\n\n // ── plugin.json (the ONLY file inside the manifest dir) ───────────────────\n emit(\n join(pluginDir, spec.manifestDir, \"plugin.json\"),\n json(buildManifest(connector, spec)),\n );\n\n // ── commands/<name>.md ────────────────────────────────────────────────────\n for (const cmd of connector.commands) {\n emit(join(pluginDir, \"commands\", `${cmd.name}.md`), renderCommandMd(cmd));\n }\n\n // ── agents|droids/<name>.md ───────────────────────────────────────────────\n for (const agent of connector.subagents) {\n emit(\n join(pluginDir, spec.subagentDir, `${agent.name}.md`),\n renderSubagentMd(agent),\n );\n }\n\n // ── skills/<name>/SKILL.md (+ resources) ──────────────────────────────────\n for (const skill of connector.skills) {\n const skillDir = join(pluginDir, \"skills\", skill.name);\n emit(join(skillDir, \"SKILL.md\"), renderSkillMd(skill));\n for (const [rel, contents] of Object.entries(skill.resources ?? {})) {\n const target = resolveWithin(skillDir, rel);\n if (target === null) continue; // never write outside the skill dir\n emit(target, contents);\n }\n }\n\n // ── hooks/hooks.json (mapped events only) ─────────────────────────────────\n const hooksJson = buildClaudeHooksJson(connector, ctx.homeBinPath, spec.platformId);\n if (hooksJson) emit(join(pluginDir, \"hooks\", \"hooks.json\"), json(hooksJson));\n\n // ── MCP json (serve-wrapped stdio server) ─────────────────────────────────\n const mcp = buildMcpEntry(connector, ctx.homeBinPath, spec.platformId);\n if (mcp) {\n emit(\n join(pluginDir, spec.mcpFile),\n json({ mcpServers: { [mcp.serverName]: mcp.entry } }),\n );\n }\n\n // ── marketplace catalog ───────────────────────────────────────────────────\n const marketplacePath = spec.marketplace.dir\n ? join(ctx.outDir, spec.marketplace.dir, spec.marketplace.file)\n : join(ctx.outDir, spec.marketplace.file);\n emit(marketplacePath, json(buildMarketplace(connector)));\n\n return { files, pluginDir, marketplacePath };\n}\n\nexport const emitClaudePlugin: FormatEmitter = (connector, ctx) =>\n emitClaudeFamily(connector, ctx, \"claude-plugin\");\n\nexport const emitCodexPlugin: FormatEmitter = (connector, ctx) =>\n emitClaudeFamily(connector, ctx, \"codex-plugin\");\n\nexport const emitFactoryPlugin: FormatEmitter = (connector, ctx) =>\n emitClaudeFamily(connector, ctx, \"factory-plugin\");\n","/**\n * core/package-formats/shared — the common emitter contract + helpers every\n * format family is built on.\n *\n * A format emitter is a pure function conforming to {@link FormatEmitter}: it\n * takes a {@link ResolvedConnector} plus an {@link EmitContext} ({outDir,\n * homeBinPath, dryRun}) and either writes the bundle (dryRun=false) or only\n * enumerates the files it WOULD write (dryRun=true), returning a\n * {@link PackageResult} ({pluginDir, files[], marketplacePath?, notes?}).\n *\n * Everything below is shared across families so each emitter file is just the\n * format-specific manifest + layout, never a re-implementation of file writing,\n * JSON serialization, traversal-safe resource placement, the home-bin hooks\n * block, or the serve-wrapper MCP entry. Reusing these keeps telemetry-wrap +\n * the universal home-bin hook command byte-identical to the live adapters.\n */\n\nimport { dirname, relative, resolve, sep } from \"node:path\";\nimport { writeFileSync } from \"node:fs\";\n\nimport type {\n HookEventName,\n PlatformId,\n ResolvedConnector,\n} from \"../types.js\";\nimport { ensureDir } from \"../paths.js\";\nimport {\n buildHomeBinHookCommand,\n buildServeWrapperCommand,\n shouldWrapForTelemetry,\n} from \"../spawn.js\";\n\n/** Inputs every format emitter receives. */\nexport interface EmitContext {\n /** Directory the bundle is written under (the format root). */\n outDir: string;\n /** Absolute path to agent-connector's stable home-bin (hooks + serve wrapper point here). */\n homeBinPath: string;\n /** Enumerate the file list without writing anything. */\n dryRun: boolean;\n}\n\n/** What every format emitter returns. */\nexport interface PackageResult {\n /** Absolute paths of every file the bundle comprises (written, or planned for dryRun). */\n files: string[];\n /** Absolute path to the plugin/extension root directory. */\n pluginDir: string;\n /** Absolute path to the emitted marketplace catalog, when the format has one. */\n marketplacePath?: string;\n /**\n * Human-readable notes about surfaces the format intentionally DROPS (e.g.\n * Kimi ignores hooks/commands/subagents). The CLI surfaces these so a lossy\n * bundle is never silent. Empty when nothing was dropped.\n */\n notes?: string[];\n}\n\n/** The shared signature every `package-formats/<family>.ts` exports. */\nexport type FormatEmitter = (\n connector: ResolvedConnector,\n ctx: EmitContext,\n) => PackageResult;\n\n/** A small file-collecting writer bound to one emit run (honors dryRun). */\nexport interface Emitter {\n /** Write `contents` to `path` (skipped under dryRun) and record it. */\n emit(path: string, contents: string): void;\n /** The accumulated absolute file list (in emit order). */\n readonly files: string[];\n}\n\n/** Build a dryRun-aware {@link Emitter} that records every (would-be) write. */\nexport function createEmitter(dryRun: boolean): Emitter {\n const files: string[] = [];\n return {\n files,\n emit(path: string, contents: string): void {\n if (!dryRun) {\n ensureDir(dirname(path));\n writeFileSync(path, contents, \"utf8\");\n }\n files.push(path);\n },\n };\n}\n\n/** Pretty-print a value as 2-space JSON with a trailing newline. */\nexport function json(value: unknown): string {\n return `${JSON.stringify(value, null, 2)}\\n`;\n}\n\n/**\n * Resolve a skill-resource relative key against `baseDir`, returning the\n * absolute target ONLY when it stays inside the dir (defense-in-depth — config\n * validation already rejects traversal, but never trust input). Null otherwise.\n */\nexport function resolveWithin(baseDir: string, rel: string): string | null {\n const base = resolve(baseDir);\n const target = resolve(base, rel);\n if (target === base) return null;\n const rind = relative(base, target);\n if (rind === \"\" || rind.startsWith(\"..\") || resolve(base, rind) !== target) {\n return null;\n }\n if (rind === \"..\" || rind.startsWith(`..${sep}`)) return null;\n return target;\n}\n\n/** Pass env through unchanged when present, else undefined (drops empty objects). */\nexport function renderEnv(\n env: Record<string, string> | undefined,\n): Record<string, string> | undefined {\n if (!env || Object.keys(env).length === 0) return undefined;\n return { ...env };\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// Hooks — the Claude-shaped hooks.json block, shared by every format whose\n// hooks file mirrors Claude Code's `{ type:\"command\", command:\"<string>\" }`.\n// ─────────────────────────────────────────────────────────────────────────\n\n/** Claude event names a Claude-style plugin's hooks.json may key on. */\nexport const CLAUDE_MAPPED_EVENTS: ReadonlySet<HookEventName> =\n new Set<HookEventName>([\n \"PreToolUse\",\n \"PostToolUse\",\n \"PreCompact\",\n \"SessionStart\",\n \"SessionEnd\",\n \"UserPromptSubmit\",\n \"Stop\",\n \"Notification\",\n \"PermissionRequest\",\n \"PostToolUseFailure\",\n \"SubagentStart\",\n \"SubagentStop\",\n ]);\n\n/** A single hooks.json entry (identical in shape to a settings.json hooks block). */\nexport interface PluginHookEntry {\n matcher?: string;\n hooks: Array<{ type: \"command\"; command: string }>;\n}\n\n/**\n * Build the Claude-shaped hooks.json body for the MAPPED events the connector\n * declares. Each command is the SAME single-string home-bin form the live\n * adapters write (via buildHomeBinHookCommand). `platformId` lets a format point\n * the hook at the right host (e.g. \"cursor\", \"claude-code\"). Returns null when\n * the connector declares no mapped events.\n */\nexport function buildClaudeHooksJson(\n connector: ResolvedConnector,\n homeBin: string,\n platformId: PlatformId,\n): { hooks: Record<string, PluginHookEntry[]> } | null {\n const events = connector.hookEvents.filter((e) => CLAUDE_MAPPED_EVENTS.has(e));\n if (events.length === 0) return null;\n\n const hooks: Record<string, PluginHookEntry[]> = {};\n for (const event of events) {\n const matcher = connector.hooks[event]?.matcher ?? \"\";\n const command = {\n type: \"command\" as const,\n command: buildHomeBinHookCommand(homeBin, platformId, event, connector.id),\n };\n hooks[event] = [matcher ? { matcher, hooks: [command] } : { hooks: [command] }];\n }\n return { hooks };\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// MCP — the serve-wrapped stdio server entry, shared by every format whose MCP\n// file carries a launchable { command, args, env?, cwd? } (the Claude .mcp.json\n// dialect). Remote/non-stdio servers are out of scope for a launchable bundle.\n// ─────────────────────────────────────────────────────────────────────────\n\n/** Native MCP server entry shape a Claude-dialect mcpServers map accepts. */\nexport interface PluginMcpEntry {\n command: string;\n args: string[];\n env?: Record<string, string>;\n cwd?: string;\n}\n\n/**\n * Render the connector's ServerDef into a serve-wrapped MCP entry for\n * `platformId`, so per-tool telemetry carries through the bundle exactly as the\n * live adapter's install does. Returns null when there is no stdio command to\n * launch (remote / server-less connectors). The returned `serverName` is the\n * connector id (the conventional single-server key).\n */\nexport function buildMcpEntry(\n connector: ResolvedConnector,\n homeBin: string,\n platformId: PlatformId,\n): { serverName: string; entry: PluginMcpEntry } | null {\n const server = connector.server;\n if (!server) return null;\n // A launchable bundle entry can only carry stdio servers; remote (http/sse/ws)\n // servers register a URL elsewhere, out of scope for the bundled plugin.\n if (server.transport !== \"stdio\") return null;\n\n const realCommand = server.command ?? \"\";\n if (realCommand === \"\") return null;\n const realArgs = [...(server.args ?? [])];\n\n let entry: PluginMcpEntry;\n if (shouldWrapForTelemetry(server, connector.telemetry)) {\n const wrapped = buildServeWrapperCommand(\n homeBin,\n connector.id,\n realCommand,\n realArgs,\n undefined,\n platformId,\n );\n entry = { command: wrapped.command, args: wrapped.args };\n } else {\n entry = { command: realCommand, args: realArgs };\n }\n\n const env = renderEnv(server.env);\n if (env) entry.env = env;\n if (server.cwd) entry.cwd = server.cwd;\n\n return { serverName: connector.id, entry };\n}\n","/**\n * core/package-formats/cursor — the `cursor-plugin` emitter.\n *\n * Cursor's bundle is near-isomorphic to claude-plugin: manifest at\n * `.cursor-plugin/plugin.json` (only `name` required) with the surface fields\n * declared as POINTERS (\"skills\":\"./skills/\", \"hooks\":\"./hooks/hooks.json\",\n * \"mcpServers\":\"./mcp.json\") so a validator/IDE finds each dir; components live\n * at the plugin root: commands/<n>.md, agents/<n>.md, skills/<n>/SKILL.md,\n * mcp.json, hooks/hooks.json. A multi-plugin repo adds .cursor-plugin/\n * marketplace.json { name, owner:{name,email?}, plugins:[{name,source,description}] }.\n *\n * Markdown reuses the shared claude-code renderers (Cursor reads the same md +\n * frontmatter command/agent/skill documents). Hooks + MCP use the shared\n * builders with --host cursor so the home-bin hook + serve-wrapper telemetry\n * carry through.\n *\n * (Cursor also supports `rules/*.mdc`, but a connector declares no rules surface,\n * so no rules/ dir is emitted and the manifest omits the `rules` pointer.)\n */\n\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport type { PlatformId, ResolvedConnector } from \"../types.js\";\nimport {\n renderCommandMd,\n renderSkillMd,\n renderSubagentMd,\n} from \"../../adapters/claude-code/render.js\";\nimport {\n buildClaudeHooksJson,\n buildMcpEntry,\n createEmitter,\n json,\n resolveWithin,\n type EmitContext,\n type FormatEmitter,\n type PackageResult,\n} from \"./shared.js\";\n\nconst PLATFORM: PlatformId = \"cursor\";\n\n/** Build .cursor-plugin/plugin.json with pointer surface fields for what exists. */\nfunction buildManifest(\n connector: ResolvedConnector,\n has: { commands: boolean; agents: boolean; skills: boolean; hooks: boolean; mcp: boolean },\n): Record<string, unknown> {\n const manifest: Record<string, unknown> = {\n name: connector.id,\n description: `${connector.displayName} — connector emitted by agent-connector`,\n };\n if (connector.version && connector.version !== \"0.0.0\") {\n manifest.version = connector.version;\n }\n // Pointer fields: only declare a surface that actually ships in the bundle.\n if (has.commands) manifest.commands = \"./commands/\";\n if (has.agents) manifest.agents = \"./agents/\";\n if (has.skills) manifest.skills = \"./skills/\";\n if (has.hooks) manifest.hooks = \"./hooks/hooks.json\";\n if (has.mcp) manifest.mcpServers = \"./mcp.json\";\n return manifest;\n}\n\n/** Build .cursor-plugin/marketplace.json (owner object carries name; email optional). */\nfunction buildMarketplace(connector: ResolvedConnector): Record<string, unknown> {\n // Catalog NAME stays \"agent-connector\" (install instructions key on it); the\n // OWNER is the connector developer when publish.author is declared.\n return {\n name: \"agent-connector\",\n owner: { name: connector.publish?.author?.name ?? \"agent-connector\" },\n plugins: [\n {\n name: connector.id,\n source: `./${connector.id}`,\n description: `${connector.displayName} — connector emitted by agent-connector`,\n },\n ],\n };\n}\n\nexport const emitCursorPlugin: FormatEmitter = (\n connector: ResolvedConnector,\n ctx: EmitContext,\n): PackageResult => {\n const { emit, files } = createEmitter(ctx.dryRun);\n const pluginDir = join(ctx.outDir, connector.id);\n\n const hooksJson = buildClaudeHooksJson(connector, ctx.homeBinPath, PLATFORM);\n const mcp = buildMcpEntry(connector, ctx.homeBinPath, PLATFORM);\n\n const has = {\n commands: connector.commands.length > 0,\n agents: connector.subagents.length > 0,\n skills: connector.skills.length > 0,\n hooks: hooksJson !== null,\n mcp: mcp !== null,\n };\n\n // ── .cursor-plugin/plugin.json (ONLY file under .cursor-plugin/) ───────────\n emit(\n join(pluginDir, \".cursor-plugin\", \"plugin.json\"),\n json(buildManifest(connector, has)),\n );\n\n // ── commands/<name>.md ────────────────────────────────────────────────────\n for (const cmd of connector.commands) {\n emit(join(pluginDir, \"commands\", `${cmd.name}.md`), renderCommandMd(cmd));\n }\n\n // ── agents/<name>.md ──────────────────────────────────────────────────────\n for (const agent of connector.subagents) {\n emit(join(pluginDir, \"agents\", `${agent.name}.md`), renderSubagentMd(agent));\n }\n\n // ── skills/<name>/SKILL.md (+ resources) ──────────────────────────────────\n for (const skill of connector.skills) {\n const skillDir = join(pluginDir, \"skills\", skill.name);\n emit(join(skillDir, \"SKILL.md\"), renderSkillMd(skill));\n for (const [rel, contents] of Object.entries(skill.resources ?? {})) {\n const target = resolveWithin(skillDir, rel);\n if (target === null) continue;\n emit(target, contents);\n }\n }\n\n // ── hooks/hooks.json ──────────────────────────────────────────────────────\n if (hooksJson) emit(join(pluginDir, \"hooks\", \"hooks.json\"), json(hooksJson));\n\n // ── mcp.json (Cursor's MCP filename, no leading dot) ──────────────────────\n if (mcp) {\n emit(\n join(pluginDir, \"mcp.json\"),\n json({ mcpServers: { [mcp.serverName]: mcp.entry } }),\n );\n }\n\n // ── .cursor-plugin/marketplace.json ───────────────────────────────────────\n const marketplacePath = join(ctx.outDir, \".cursor-plugin\", \"marketplace.json\");\n emit(marketplacePath, json(buildMarketplace(connector)));\n\n return { files, pluginDir, marketplacePath };\n};\n\n/** True when a local install of this plugin already exists (used by the CLI hint). */\nexport function cursorLocalInstallExists(name: string, home: string): boolean {\n return existsSync(join(home, \".cursor\", \"plugins\", \"local\", name));\n}\n","/**\n * core/package-formats/gemini — the `gemini-extension` emitter + its `qwen-extension`\n * variant.\n *\n * A Gemini CLI extension is a directory with `gemini-extension.json` at its root\n * carrying `{ name, version, description, mcpServers, contextFileName }` plus the\n * component dirs: commands/<n>.toml (slash commands), skills/<n>/SKILL.md,\n * agents/<n>.md, hooks/hooks.json, and a GEMINI.md context file. UNLIKE the\n * Claude family, MCP is declared INLINE in the manifest's `mcpServers` map (not a\n * separate .mcp.json) — we still serve-wrap it so telemetry carries through.\n *\n * Qwen Code is a Gemini-CLI fork with its own `qwen-extension.json` (same shape)\n * but two differences captured here: commands are MARKDOWN (commands/<n>.md) not\n * TOML, and the context file is QWEN.md.\n *\n * Commands render to Gemini's native TOML `{ description, prompt }` (the same\n * shape the live gemini-cli adapter writes); skills/subagents reuse the shared\n * claude-code renderers (Gemini/Qwen read the same SKILL.md + md+frontmatter).\n * Hooks use the universal home-bin command; the MCP entry is serve-wrapped with\n * --host gemini-cli | qwen-code.\n */\n\nimport { join } from \"node:path\";\n\nimport type { CommandDef, PlatformId, ResolvedConnector } from \"../types.js\";\nimport { writeTomlString } from \"../toml.js\";\nimport {\n renderCommandMd,\n renderSkillMd,\n renderSubagentMd,\n} from \"../../adapters/claude-code/render.js\";\nimport {\n buildClaudeHooksJson,\n buildMcpEntry,\n createEmitter,\n json,\n resolveWithin,\n type EmitContext,\n type FormatEmitter,\n type PackageResult,\n} from \"./shared.js\";\n\n/** Per-variant knobs for a Gemini-family extension. */\ninterface GeminiFamilySpec {\n platformId: PlatformId;\n /** Manifest filename at the extension root. */\n manifestFile: string;\n /** Context file name (GEMINI.md | QWEN.md). */\n contextFile: string;\n /** Command file format: TOML (gemini) or Markdown (qwen). */\n commandFormat: \"toml\" | \"md\";\n}\n\nconst SPECS: Record<string, GeminiFamilySpec> = {\n \"gemini-extension\": {\n platformId: \"gemini-cli\",\n manifestFile: \"gemini-extension.json\",\n contextFile: \"GEMINI.md\",\n commandFormat: \"toml\",\n },\n \"qwen-extension\": {\n platformId: \"qwen-code\",\n manifestFile: \"qwen-extension.json\",\n contextFile: \"QWEN.md\",\n commandFormat: \"md\",\n },\n};\n\n/** Render a command to Gemini's native TOML `{ description, prompt }`. */\nfunction renderCommandToml(cmd: CommandDef): string {\n const obj: Record<string, unknown> = {};\n if (cmd.description !== undefined) obj.description = cmd.description;\n obj.prompt = cmd.prompt;\n return writeTomlString(obj);\n}\n\n/** Build gemini-extension.json | qwen-extension.json (with optional inline mcpServers). */\nfunction buildManifest(\n connector: ResolvedConnector,\n spec: GeminiFamilySpec,\n homeBin: string,\n): Record<string, unknown> {\n const manifest: Record<string, unknown> = {\n name: connector.id,\n // gemini requires a version; default a placeholder to a real semver.\n version:\n connector.version && connector.version !== \"0.0.0\"\n ? connector.version\n : \"0.0.1\",\n description: `${connector.displayName} — connector emitted by agent-connector`,\n };\n\n const mcp = buildMcpEntry(connector, homeBin, spec.platformId);\n if (mcp) {\n manifest.mcpServers = { [mcp.serverName]: mcp.entry };\n }\n manifest.contextFileName = spec.contextFile;\n return manifest;\n}\n\nfunction emitGeminiFamily(\n connector: ResolvedConnector,\n ctx: EmitContext,\n format: keyof typeof SPECS,\n): PackageResult {\n const spec = SPECS[format];\n if (!spec) throw new Error(`unknown gemini-family format: ${format}`);\n\n const { emit, files } = createEmitter(ctx.dryRun);\n const pluginDir = join(ctx.outDir, connector.id);\n\n // ── gemini-extension.json | qwen-extension.json (MCP is inline here) ──────\n emit(\n join(pluginDir, spec.manifestFile),\n json(buildManifest(connector, spec, ctx.homeBinPath)),\n );\n\n // ── context file (GEMINI.md | QWEN.md) ────────────────────────────────────\n emit(\n join(pluginDir, spec.contextFile),\n `# ${connector.displayName}\\n\\nConnector context emitted by agent-connector.\\n`,\n );\n\n // ── commands/<name>.{toml|md} ─────────────────────────────────────────────\n for (const cmd of connector.commands) {\n if (spec.commandFormat === \"toml\") {\n emit(join(pluginDir, \"commands\", `${cmd.name}.toml`), renderCommandToml(cmd));\n } else {\n emit(join(pluginDir, \"commands\", `${cmd.name}.md`), renderCommandMd(cmd));\n }\n }\n\n // ── agents/<name>.md ──────────────────────────────────────────────────────\n for (const agent of connector.subagents) {\n emit(join(pluginDir, \"agents\", `${agent.name}.md`), renderSubagentMd(agent));\n }\n\n // ── skills/<name>/SKILL.md (+ resources) ──────────────────────────────────\n for (const skill of connector.skills) {\n const skillDir = join(pluginDir, \"skills\", skill.name);\n emit(join(skillDir, \"SKILL.md\"), renderSkillMd(skill));\n for (const [rel, contents] of Object.entries(skill.resources ?? {})) {\n const target = resolveWithin(skillDir, rel);\n if (target === null) continue;\n emit(target, contents);\n }\n }\n\n // ── hooks/hooks.json ──────────────────────────────────────────────────────\n const hooksJson = buildClaudeHooksJson(connector, ctx.homeBinPath, spec.platformId);\n if (hooksJson) emit(join(pluginDir, \"hooks\", \"hooks.json\"), json(hooksJson));\n\n // A Gemini/Qwen extension has no separate marketplace catalog (it installs by\n // URL/path); marketplacePath is left undefined.\n return { files, pluginDir };\n}\n\nexport const emitGeminiExtension: FormatEmitter = (connector, ctx) =>\n emitGeminiFamily(connector, ctx, \"gemini-extension\");\n\nexport const emitQwenExtension: FormatEmitter = (connector, ctx) =>\n emitGeminiFamily(connector, ctx, \"qwen-extension\");\n","/**\n * core/package-formats/agy — the `agy plugin` bundle emitter (Antigravity CLI +\n * Antigravity IDE, which share the bundle).\n *\n * Live-confirmed layout (`agy plugin validate`):\n * • REQUIRED root `plugin.json` marker { name, version, description } — its\n * absence is the one hard error the validator reports.\n * • MCP MUST be a SEPARATE `mcp_config.json` { mcpServers:{...} } — an inline\n * `mcpServers` in plugin.json is NOT picked up. (This is the one structural\n * difference from the Claude family.)\n * • hooks.json at the BUNDLE ROOT keyed { hooks:{ <Event>:[{matcher,hooks:[{type,command}]}] } }\n * — agy 1.0.7 NEVER reads hooks/hooks.json: validate+install report\n * \"hooks: skipped (not found)\" and copy the file unprocessed. The root\n * location was fix-proven live (\"hooks: 1 processed\", components +hooks).\n * • skills/<n>/SKILL.md, agents/<n>.md, commands/<n>.md (commands are converted\n * to skills on validate — still emitted as Markdown command files).\n *\n * Markdown reuses the shared claude-code renderers; hooks use the universal\n * home-bin command; the MCP entry is serve-wrapped with --host antigravity-cli so\n * telemetry carries through. No marketplace catalog ships in the bundle (agy\n * installs by target / plugin@marketplace).\n */\n\nimport { join } from \"node:path\";\n\nimport type { PlatformId, ResolvedConnector } from \"../types.js\";\nimport {\n renderCommandMd,\n renderSkillMd,\n renderSubagentMd,\n} from \"../../adapters/claude-code/render.js\";\nimport {\n buildClaudeHooksJson,\n buildMcpEntry,\n createEmitter,\n json,\n resolveWithin,\n type EmitContext,\n type FormatEmitter,\n type PackageResult,\n} from \"./shared.js\";\n\nconst PLATFORM: PlatformId = \"antigravity-cli\";\n\n/** Build the required root plugin.json marker. */\nfunction buildManifest(connector: ResolvedConnector): Record<string, unknown> {\n return {\n name: connector.id,\n // agy expects a version on the marker; default a placeholder to a real semver.\n version:\n connector.version && connector.version !== \"0.0.0\"\n ? connector.version\n : \"0.0.1\",\n description: `${connector.displayName} — connector emitted by agent-connector`,\n };\n}\n\nexport const emitAgyPlugin: FormatEmitter = (\n connector: ResolvedConnector,\n ctx: EmitContext,\n): PackageResult => {\n const { emit, files } = createEmitter(ctx.dryRun);\n const pluginDir = join(ctx.outDir, connector.id);\n\n // ── plugin.json (REQUIRED root marker) ────────────────────────────────────\n emit(join(pluginDir, \"plugin.json\"), json(buildManifest(connector)));\n\n // ── commands/<name>.md (validator converts these to skills) ───────────────\n for (const cmd of connector.commands) {\n emit(join(pluginDir, \"commands\", `${cmd.name}.md`), renderCommandMd(cmd));\n }\n\n // ── agents/<name>.md ──────────────────────────────────────────────────────\n for (const agent of connector.subagents) {\n emit(join(pluginDir, \"agents\", `${agent.name}.md`), renderSubagentMd(agent));\n }\n\n // ── skills/<name>/SKILL.md (+ resources) ──────────────────────────────────\n for (const skill of connector.skills) {\n const skillDir = join(pluginDir, \"skills\", skill.name);\n emit(join(skillDir, \"SKILL.md\"), renderSkillMd(skill));\n for (const [rel, contents] of Object.entries(skill.resources ?? {})) {\n const target = resolveWithin(skillDir, rel);\n if (target === null) continue;\n emit(target, contents);\n }\n }\n\n // ── hooks.json (bundle ROOT — agy silently ignores hooks/hooks.json) ──────\n const hooksJson = buildClaudeHooksJson(connector, ctx.homeBinPath, PLATFORM);\n if (hooksJson) emit(join(pluginDir, \"hooks.json\"), json(hooksJson));\n\n // ── mcp_config.json (SEPARATE file — inline mcpServers is NOT read by agy) ─\n const mcp = buildMcpEntry(connector, ctx.homeBinPath, PLATFORM);\n if (mcp) {\n emit(\n join(pluginDir, \"mcp_config.json\"),\n json({ mcpServers: { [mcp.serverName]: mcp.entry } }),\n );\n }\n\n return { files, pluginDir };\n};\n","/**\n * core/package-formats/kimi — the `kimi-plugin` emitter (skills + MCP ONLY).\n *\n * A Kimi plugin is a directory whose manifest is `kimi.plugin.json` at the root\n * carrying { name, version, description, skills, mcpServers }. Kimi plugins carry\n * exactly TWO functional surfaces:\n * • skills/<n>/SKILL.md (declared via the `skills` pointer)\n * • mcpServers (a standard MCP map, stdio + http)\n *\n * Kimi EXPLICITLY ignores `tools`, `commands`, `hooks`, `apps`, `inject`,\n * `configFile` (they surface as diagnostics). So when the connector declares\n * commands, subagents, or hooks, those surfaces are DROPPED — and a note is\n * returned so the lossy bundle is never silent. The MCP entry is still\n * serve-wrapped with --host kimi so telemetry carries through; hooks are NOT\n * emitted because Kimi has no hooks surface.\n */\n\nimport { join } from \"node:path\";\n\nimport type { PlatformId, ResolvedConnector } from \"../types.js\";\nimport { renderSkillMd } from \"../../adapters/claude-code/render.js\";\nimport {\n buildMcpEntry,\n createEmitter,\n json,\n resolveWithin,\n type EmitContext,\n type FormatEmitter,\n type PackageResult,\n} from \"./shared.js\";\n\nconst PLATFORM: PlatformId = \"kimi\";\n\n/** Build kimi.plugin.json (skills pointer + inline mcpServers when present). */\nfunction buildManifest(\n connector: ResolvedConnector,\n hasSkills: boolean,\n homeBin: string,\n): Record<string, unknown> {\n const manifest: Record<string, unknown> = {\n name: connector.id,\n version:\n connector.version && connector.version !== \"0.0.0\"\n ? connector.version\n : \"0.0.1\",\n description: `${connector.displayName} — connector emitted by agent-connector`,\n };\n if (hasSkills) manifest.skills = \"./skills/\";\n const mcp = buildMcpEntry(connector, homeBin, PLATFORM);\n if (mcp) manifest.mcpServers = { [mcp.serverName]: mcp.entry };\n return manifest;\n}\n\nexport const emitKimiPlugin: FormatEmitter = (\n connector: ResolvedConnector,\n ctx: EmitContext,\n): PackageResult => {\n const { emit, files } = createEmitter(ctx.dryRun);\n const pluginDir = join(ctx.outDir, connector.id);\n const notes: string[] = [];\n\n const hasSkills = connector.skills.length > 0;\n\n // ── kimi.plugin.json (root manifest; MCP inline; hooks/commands ignored) ──\n emit(join(pluginDir, \"kimi.plugin.json\"), json(buildManifest(connector, hasSkills, ctx.homeBinPath)));\n\n // ── skills/<name>/SKILL.md (+ resources) ──────────────────────────────────\n for (const skill of connector.skills) {\n const skillDir = join(pluginDir, \"skills\", skill.name);\n emit(join(skillDir, \"SKILL.md\"), renderSkillMd(skill));\n for (const [rel, contents] of Object.entries(skill.resources ?? {})) {\n const target = resolveWithin(skillDir, rel);\n if (target === null) continue;\n emit(target, contents);\n }\n }\n\n // ── Surfaces Kimi cannot carry → DROPPED, with an explicit note ───────────\n if (connector.commands.length > 0) {\n notes.push(\n `kimi-plugin: dropped ${connector.commands.length} command(s) — Kimi plugins ignore commands`,\n );\n }\n if (connector.subagents.length > 0) {\n notes.push(\n `kimi-plugin: dropped ${connector.subagents.length} subagent(s) — Kimi plugins ignore subagents`,\n );\n }\n if (connector.hookEvents.length > 0) {\n notes.push(\n `kimi-plugin: dropped ${connector.hookEvents.length} hook event(s) — Kimi plugins ignore hooks`,\n );\n }\n\n return { files, pluginDir, ...(notes.length > 0 ? { notes } : {}) };\n};\n","/**\n * core/package-formats/npm — the `npm-plugin` emitter (opencode + kilo-cli + pi).\n *\n * This is the one genuinely NET-NEW artifact: a publishable npm package whose\n * default export is a plugin module. It is emitted ONLY in its clean form — a\n * real package.json + a self-contained ESM `index.js` bridge — never a\n * half-baked stub. The surface limit (documented, and returned as notes) is\n * inherent to the opencode/kilo plugin contract: ONLY hook code rides inside the\n * npm package; commands/skills/subagents are native host dirs and MCP is a\n * config key, so they do NOT ride inside the published module.\n *\n * Layout:\n * <outDir>/<id>/\n * ├── package.json (type:module, exports \".\", keywords incl. \"opencode-plugin\"\n * │ + \"pi-package\", engines.node)\n * ├── index.js (default-export plugin fn; bridges each declared hook event\n * │ to `<homeBin> hook opencode <event> --connector <id>`)\n * ├── skills/<n>/SKILL.md (pi packages DO bundle skills; opencode ignores them)\n * └── README.md\n *\n * The bridge shells out to the ONE stable home binary over child_process, so the\n * SAME universal json-stdio dispatcher every other host uses serves the npm host\n * too — and telemetry continues to flow through the home-bin. (MCP wrapping is\n * NOT inlined here: opencode's MCP is the opencode.json \"mcp\" key, out of band\n * for the npm package; a note records this.)\n */\n\nimport { join } from \"node:path\";\n\nimport type { HookEventName, ResolvedConnector } from \"../types.js\";\nimport { renderSkillMd } from \"../../adapters/claude-code/render.js\";\nimport {\n createEmitter,\n json,\n resolveWithin,\n type EmitContext,\n type FormatEmitter,\n type PackageResult,\n} from \"./shared.js\";\n\n/** OpenCode event keys this connector can bridge (PreToolUse/PostToolUse/SessionStart). */\nconst EVENT_TO_OPENCODE: Partial<Record<HookEventName, string>> = {\n PreToolUse: \"tool.execute.before\",\n PostToolUse: \"tool.execute.after\",\n SessionStart: \"experimental.chat.system.transform\",\n};\n\n/** Build the publishable package.json for an opencode/kilo/pi plugin package. */\nfunction buildPackageJson(connector: ResolvedConnector): Record<string, unknown> {\n // Use an opencode- name prefix (the discovery-confirmed convention) so the\n // package is discoverable; keywords cover opencode + pi-package.\n const pkgName = connector.id.startsWith(\"opencode-\")\n ? connector.id\n : `opencode-${connector.id}`;\n const version =\n connector.version && connector.version !== \"0.0.0\" ? connector.version : \"0.0.1\";\n const pkg: Record<string, unknown> = {\n name: pkgName,\n version,\n description: `${connector.displayName} — connector emitted by agent-connector`,\n type: \"module\",\n main: \"index.js\",\n exports: { \".\": \"./index.js\" },\n keywords: [\"opencode\", \"opencode-plugin\", \"pi-package\", \"agent-connector\"],\n // pi reads skills/prompts/themes/extensions from the package.json \"pi\" key.\n pi: { extensions: [\"./index.js\"], skills: [\"./skills\"] },\n engines: { node: \">=18.17\", opencode: \">=1.0.0\" },\n // NOTE: no hardcoded license — this is the DEVELOPER'S publishable package\n // and agent-connector has no authority to license it. The emitter returns a\n // note telling the dev to set license (and author) before `npm publish`.\n };\n if (connector.publish?.author?.name) {\n pkg.author = connector.publish.author.name;\n }\n return pkg;\n}\n\n/** Compose the self-contained ESM plugin bridge (default-export plugin fn). */\nfunction buildIndexJs(connector: ResolvedConnector): string {\n const homeBin = JSON.stringify(\"agent-connector\");\n const connectorId = JSON.stringify(connector.id);\n\n const events = connector.hookEvents.filter(\n (e): e is HookEventName => EVENT_TO_OPENCODE[e] !== undefined,\n );\n const has = (e: HookEventName): boolean => events.includes(e);\n\n const header = `/**\n * AUTO-GENERATED by agent-connector — DO NOT EDIT.\n *\n * Publishable OpenCode/Kilo/Pi plugin for connector ${connector.id}. It imports\n * nothing from agent-connector: every hook invocation shells out to the stable\n * home binary's universal entrypoint and JSON-parses the normalized response.\n * Fail-open: any bridge error degrades to \"allow\".\n */\nimport { execFileSync, execSync } from \"node:child_process\";\n\nconst HOME_BIN = ${homeBin};\nconst CONNECTOR_ID = ${connectorId};\n\nfunction bridge(event, payload) {\n try {\n // The published bridge resolves HOME_BIN by bare name via the consumer's\n // PATH, where on Windows it is agent-connector.cmd. Node cannot execFile a\n // .cmd, and shell+args is deprecated (DEP0190), so on Windows run one quoted\n // command line via a shell (cmd.exe applies PATHEXT). POSIX keeps execFile.\n const args = [\"hook\", \"opencode\", event, \"--connector\", CONNECTOR_ID];\n const opts = { input: JSON.stringify(payload), encoding: \"utf8\" };\n const stdout =\n process.platform === \"win32\"\n ? execSync([HOME_BIN, ...args].map((a) => '\"' + a + '\"').join(\" \"), opts)\n : execFileSync(HOME_BIN, args, opts);\n const text = (stdout || \"\").trim();\n if (text === \"\") return { decision: \"allow\" };\n return JSON.parse(text);\n } catch {\n return null;\n }\n}\n`;\n\n const handlers: string[] = [];\n if (has(\"PreToolUse\")) {\n handlers.push(` \"tool.execute.before\": async (input, output) => {\n const res = bridge(\"PreToolUse\", {\n toolName: input.tool ?? \"\",\n toolInput: (output && output.args) ?? {},\n sessionId: input.sessionID ?? \"\",\n projectDir: PROJECT_DIR,\n });\n if (!res) return;\n if (res.decision === \"deny\" || res.decision === \"ask\") {\n throw new Error(res.reason || \"Blocked by ${connector.id}\");\n }\n if (res.updatedInput && output && output.args) Object.assign(output.args, res.updatedInput);\n },`);\n }\n if (has(\"PostToolUse\")) {\n handlers.push(` \"tool.execute.after\": async (input, output) => {\n const res = bridge(\"PostToolUse\", {\n toolName: input.tool ?? \"\",\n toolInput: input.args ?? {},\n toolOutput: output ? output.output : undefined,\n sessionId: input.sessionID ?? \"\",\n projectDir: PROJECT_DIR,\n });\n if (!res) return;\n if (typeof res.updatedOutput === \"string\" && output) output.output = res.updatedOutput;\n },`);\n }\n if (has(\"SessionStart\")) {\n handlers.push(` \"experimental.chat.system.transform\": async (input, output) => {\n const res = bridge(\"SessionStart\", {\n sessionId: (input && input.sessionID) ?? \"\",\n projectDir: PROJECT_DIR,\n });\n if (!res) return;\n if (res.additionalContext && output && Array.isArray(output.system)) {\n output.system.splice(1, 0, res.additionalContext);\n }\n },`);\n }\n\n const factory = `\nexport default async function (ctx) {\n const PROJECT_DIR =\n (ctx && (ctx.directory || (ctx.worktree && ctx.worktree.path))) || process.cwd();\n return {\n${handlers.join(\"\\n\")}\n };\n}\n`;\n return header + factory;\n}\n\nexport const emitNpmPlugin: FormatEmitter = (\n connector: ResolvedConnector,\n ctx: EmitContext,\n): PackageResult => {\n const { emit, files } = createEmitter(ctx.dryRun);\n const pluginDir = join(ctx.outDir, connector.id);\n const notes: string[] = [];\n\n // ── package.json (publishable) ────────────────────────────────────────────\n emit(join(pluginDir, \"package.json\"), json(buildPackageJson(connector)));\n\n // ── index.js (the default-export plugin bridge) ───────────────────────────\n emit(join(pluginDir, \"index.js\"), buildIndexJs(connector));\n\n // ── skills/<name>/SKILL.md (+ resources) — pi bundles skills ──────────────\n for (const skill of connector.skills) {\n const skillDir = join(pluginDir, \"skills\", skill.name);\n emit(join(skillDir, \"SKILL.md\"), renderSkillMd(skill));\n for (const [rel, contents] of Object.entries(skill.resources ?? {})) {\n const target = resolveWithin(skillDir, rel);\n if (target === null) continue;\n emit(target, contents);\n }\n }\n\n // ── README.md ─────────────────────────────────────────────────────────────\n emit(\n join(pluginDir, \"README.md\"),\n `# ${connector.displayName}\\n\\nOpenCode / Kilo / Pi plugin package emitted by agent-connector.\\n\\n` +\n \"Install with `opencode plugin install <pkg>` / `kilo plugin <pkg>` / `pi install <pkg>`.\\n\\n\" +\n \"Local install (no npm publish needed — live-verified on opencode 1.17.0 / kilo 7.3.16):\\n\" +\n \"`opencode plugin --global file:///<abs-dir>` or `kilo plugin --global file:///<abs-dir>`\\n\" +\n \"(bare absolute paths work too; the entry lands in the config `plugin` array —\\n\" +\n \"there is no uninstall verb, remove it by editing that array).\\n\\n\" +\n \"## Prerequisite\\n\\n\" +\n \"Hooks shell out to the `agent-connector` CLI resolved from the consumer's PATH —\\n\" +\n \"the consumer machine needs `npm i -g @ken-jo/agent-connector` (hooks silently no-op,\\n\" +\n \"fail-open, without it).\\n\\n\" +\n \"## Before you publish\\n\\n\" +\n \"The emitted package.json carries **no `license` and no `author`** unless your\\n\" +\n \"connector declared `publish.author` — set them to YOUR terms before `npm publish`.\\n\",\n );\n\n // The published bridge resolves the CLI by bare name on the consumer's PATH.\n notes.push(\n \"npm-plugin: hooks require `npm i -g @ken-jo/agent-connector` on the consumer machine (bridge resolves the CLI by name on PATH; silently fail-open without it)\",\n );\n notes.push(\n \"npm-plugin: set license/author in the emitted package.json before `npm publish` — agent-connector does not license your plugin for you\",\n );\n\n // Surface the inherent limits of the npm-plugin contract.\n if (connector.commands.length > 0) {\n notes.push(\n `npm-plugin: ${connector.commands.length} command(s) NOT bundled — opencode/kilo commands are native host dirs`,\n );\n }\n if (connector.subagents.length > 0) {\n notes.push(\n `npm-plugin: ${connector.subagents.length} subagent(s) NOT bundled — opencode/kilo subagents are native host dirs`,\n );\n }\n if (connector.server) {\n notes.push(\n `npm-plugin: MCP server NOT bundled inside the package — register it via the opencode.json \"mcp\" key`,\n );\n }\n\n return { files, pluginDir, ...(notes.length > 0 ? { notes } : {}) };\n};\n","/**\n * core/package-formats/mcp-server — emit an official MCP Registry `server.json`.\n *\n * Unlike the host plugin/marketplace bundles, server.json is a DISCOVERY +\n * PUBLISH artifact: it describes the developer's REAL upstream MCP server (what\n * a registry installer runs DIRECTLY), so it must NOT carry agent-connector's\n * `serve` telemetry wrapper. It is emitted from the connector's `publish`\n * metadata (the namespace the dev proved ownership of + their published package)\n * and conforms to the pinned 2025-12-11 schema:\n * • name = `${publish.registryNamespace}/${connector.id}` (one '/', regex-checked)\n * • version = concrete SemVer (ranges are rejected by the registry)\n * • stdio → packages[] { registryType:\"npm\", identifier:<dev pkg>, transport:{type:\"stdio\"} }\n * • remote → remotes[] { type:\"streamable-http\"|\"sse\", url, headers }\n * • token env vars are marked isSecret.\n *\n * agent-connector EMITS a conformant server.json; the dev runs the publish-time\n * ownership proof + upload themselves with the official `mcp-publisher` CLI.\n */\n\nimport { resolve } from \"node:path\";\n\nimport type { ResolvedConnector, ServerDef } from \"../types.js\";\nimport {\n MCP_SERVER_SCHEMA_URL,\n NPM_REGISTRY_BASE_URL,\n REGISTRY_NAME_RE,\n isConcreteSemver,\n isPlaceholderVersion,\n registryTransportType,\n} from \"../mcp-standard.js\";\nimport type { EmitContext, FormatEmitter, PackageResult } from \"./shared.js\";\nimport { createEmitter, json } from \"./shared.js\";\n\n/** A server.json KeyValueInput (environmentVariables[] / headers[] entry). */\ninterface KeyValueInput {\n name: string;\n isSecret?: boolean;\n isRequired?: boolean;\n}\n\n/** Build environmentVariables[] from a stdio ServerDef, marking the bearer token secret. */\nfunction buildEnvVars(server: ServerDef): KeyValueInput[] {\n const vars: KeyValueInput[] = [];\n const byName = new Map<string, KeyValueInput>();\n for (const key of Object.keys(server.env ?? {})) {\n const v: KeyValueInput = { name: key };\n vars.push(v);\n byName.set(key, v);\n }\n if (server.auth?.type === \"bearerEnv\" && server.auth.bearerEnvVar) {\n const name = server.auth.bearerEnvVar;\n const existing = byName.get(name);\n if (existing) {\n existing.isSecret = true;\n existing.isRequired = true;\n } else {\n vars.push({ name, isSecret: true, isRequired: true });\n }\n }\n return vars;\n}\n\n/** Build the conformant server.json object (throws a clear error on missing inputs). */\nfunction buildServerJson(\n connector: ResolvedConnector,\n notes: string[],\n): Record<string, unknown> {\n const publish = connector.publish ?? {};\n\n if (!publish.registryNamespace) {\n throw new Error(\n 'package --format mcp-server-json needs publish.registryNamespace — a reverse-DNS ' +\n 'namespace you OWN (e.g. \"io.github.<your-handle>\" or \"com.<your-domain>\"). ' +\n \"agent-connector never publishes under a namespace it owns; set it in your connector config.\",\n );\n }\n const name = `${publish.registryNamespace}/${connector.id}`;\n if (!REGISTRY_NAME_RE.test(name)) {\n throw new Error(\n `server.json name \"${name}\" must match ${REGISTRY_NAME_RE} (exactly one \"/\").`,\n );\n }\n if (!isConcreteSemver(connector.version)) {\n throw new Error(\n `server.json version must be a concrete SemVer (the registry rejects ranges); got \"${connector.version}\".`,\n );\n }\n if (isPlaceholderVersion(connector.version)) {\n notes.push(\n 'version is the unset placeholder \"0.0.0\" — set a real version before publishing to the registry.',\n );\n }\n\n const out: Record<string, unknown> = {\n $schema: MCP_SERVER_SCHEMA_URL,\n name,\n description: connector.displayName,\n version: connector.version,\n };\n\n const server = connector.server;\n if (!server) {\n notes.push(\n \"connector declares no server — emitted server.json carries neither packages nor remotes \" +\n \"(a hooks/commands-only connector is not a registry server).\",\n );\n return out;\n }\n\n const tt = registryTransportType(server.transport);\n if (tt === null) {\n notes.push(\n `transport \"${server.transport}\" is not an MCP spec transport and cannot be represented in ` +\n \"server.json; emitted server metadata without a package/remote entry.\",\n );\n return out;\n }\n\n if (server.transport === \"stdio\") {\n if (!publish.packageName) {\n throw new Error(\n \"package --format mcp-server-json needs publish.packageName — your REAL published npm \" +\n 'package that runs the MCP server (e.g. \"@acme/acme-db-mcp\"). The registry runs that ' +\n \"package directly, not agent-connector's serve wrapper.\",\n );\n }\n const pkg: Record<string, unknown> = {\n registryType: \"npm\",\n registryBaseUrl: publish.registryBaseUrl ?? NPM_REGISTRY_BASE_URL,\n identifier: publish.packageName,\n version: connector.version,\n transport: { type: \"stdio\" },\n };\n const envVars = buildEnvVars(server);\n if (envVars.length > 0) pkg.environmentVariables = envVars;\n out.packages = [pkg];\n } else {\n // streamable-http | sse → remotes[]\n const remote: Record<string, unknown> = { type: tt, url: server.url };\n const headers = Object.keys(server.headers ?? {}).map((k): KeyValueInput => ({ name: k }));\n if (headers.length > 0) remote.headers = headers;\n if (server.auth && server.auth.type !== \"none\") {\n notes.push(\n `remote server uses auth \"${server.auth.type}\" — add the credential header (isSecret) to ` +\n \"the emitted remotes[].headers before publishing.\",\n );\n }\n out.remotes = [remote];\n }\n\n return out;\n}\n\n/** Emit a registry-conformant server.json for `connector` into ctx.outDir. */\nexport const emitMcpServerJson: FormatEmitter = (\n connector: ResolvedConnector,\n ctx: EmitContext,\n): PackageResult => {\n const emitter = createEmitter(ctx.dryRun);\n const notes: string[] = [];\n const serverJson = buildServerJson(connector, notes);\n const path = resolve(ctx.outDir, \"server.json\");\n emitter.emit(path, json(serverJson));\n return {\n files: emitter.files,\n pluginDir: ctx.outDir,\n ...(notes.length > 0 ? { notes } : {}),\n };\n};\n","/**\n * core/package-formats/mcpb — emit an MCPB (.mcpb, formerly DXT) bundle manifest.\n *\n * MCPB is the official cross-client one-click LOCAL-install bundle (Claude\n * Desktop + any MCPB host). A real .mcpb is a SELF-CONTAINED zip (manifest.json\n * + the server + vendored node_modules), which agent-connector cannot assemble\n * at emit time — we do not have the developer's built server tree. So, per the\n * conformance analysis, we emit a CONFORMANT manifest.json describing a\n * self-contained node bundle (NOT an out-of-spec `npx` command-reference, which\n * would assume network + node on PATH at launch and break offline/signing) plus\n * a packaging RECIPE, and leave the `mcpb pack`/`mcpb sign` to the developer —\n * mirroring how server.json defers the publish-time ownership proof.\n *\n * Secrets (the bearer token / sensitive env) are routed through `user_config`\n * (sensitive:true) and referenced as `${user_config.<key>}` in mcp_config.env,\n * so credentials are collected by the host keychain, never inlined.\n */\n\nimport { resolve } from \"node:path\";\n\nimport type { ResolvedConnector, ServerDef } from \"../types.js\";\nimport {\n MCPB_MANIFEST_VERSION,\n isConcreteSemver,\n isPlaceholderVersion,\n} from \"../mcp-standard.js\";\nimport type { EmitContext, FormatEmitter, PackageResult } from \"./shared.js\";\nimport { createEmitter, json } from \"./shared.js\";\n\n/** \"ACME_DB_TOKEN\" → \"Acme Db Token\" for a user_config field title. */\nfunction titleize(s: string): string {\n return s\n .toLowerCase()\n .split(/[_-]+/)\n .filter(Boolean)\n .map((w) => w[0]!.toUpperCase() + w.slice(1))\n .join(\" \");\n}\n\n/** The names of env vars that hold secrets (the bearer token). */\nfunction secretEnvNames(server: ServerDef): Set<string> {\n const names = new Set<string>();\n if (server.auth?.type === \"bearerEnv\" && server.auth.bearerEnvVar) {\n names.add(server.auth.bearerEnvVar);\n }\n return names;\n}\n\nfunction recipeReadme(connector: ResolvedConnector): string {\n return `# ${connector.displayName} — MCPB bundle\n\n\\`agent-connector package --format mcpb\\` emitted the conformant **manifest.json**\n(manifest_version ${MCPB_MANIFEST_VERSION}) for this connector. It does NOT build\nthe \\`.mcpb\\` zip — that step vendors your server and is yours to run, so the\nbundle stays self-contained and signable.\n\n## Finish the bundle\n\n1. Put your built, self-contained MCP server at \\`server/index.js\\`\n (the manifest's \\`entry_point\\` / \\`mcp_config\\`).\n2. Vendor production dependencies into the bundle:\n\n \\`\\`\\`bash\n cd server && npm install --omit=dev && cd ..\n \\`\\`\\`\n\n3. Pack (and optionally sign) with the official MCPB CLI:\n\n \\`\\`\\`bash\n npx @anthropic-ai/mcpb pack . # → ${connector.id}.mcpb\n npx @anthropic-ai/mcpb sign ${connector.id}.mcpb\n \\`\\`\\`\n\nThe resulting \\`.mcpb\\` installs one-click into Claude Desktop and any MCPB host.\nSecrets are declared under \\`user_config\\` and collected by the host keychain at\ninstall time — never inline them in the manifest.\n`;\n}\n\n/** Emit a conformant MCPB manifest.json + packaging recipe for `connector`. */\nexport const emitMcpbBundle: FormatEmitter = (\n connector: ResolvedConnector,\n ctx: EmitContext,\n): PackageResult => {\n const publish = connector.publish ?? {};\n if (!publish.author?.name) {\n throw new Error(\n \"package --format mcpb needs publish.author.name — the MCPB manifest requires an author.\",\n );\n }\n if (!isConcreteSemver(connector.version)) {\n throw new Error(\n `mcpb manifest version must be a concrete SemVer; got \"${connector.version}\".`,\n );\n }\n\n const server = connector.server;\n if (!server) {\n throw new Error(\"package --format mcpb needs a server (an MCPB bundle packages an MCP server).\");\n }\n if (server.transport !== \"stdio\") {\n throw new Error(\n `package --format mcpb supports stdio servers; \"${server.transport}\" is a remote server — ` +\n \"publish it via the registry (--format mcp-server-json) instead.\",\n );\n }\n\n const notes: string[] = [];\n if (isPlaceholderVersion(connector.version)) {\n notes.push('version is the unset placeholder \"0.0.0\" — set a real version before packing.');\n }\n\n // Route secret env vars through user_config; pass the rest through verbatim.\n const secrets = secretEnvNames(server);\n const env: Record<string, string> = {};\n const userConfig: Record<string, Record<string, unknown>> = {};\n for (const [k, v] of Object.entries(server.env ?? {})) {\n if (secrets.has(k)) {\n const key = k.toLowerCase();\n userConfig[key] = {\n type: \"string\",\n title: titleize(k),\n description: `Value for ${k}`,\n sensitive: true,\n required: true,\n };\n env[k] = `\\${user_config.${key}}`;\n } else {\n env[k] = v;\n }\n }\n // A bearer-token env not already present in server.env still needs a field.\n for (const name of secrets) {\n if (!(name in env)) {\n const key = name.toLowerCase();\n userConfig[key] = {\n type: \"string\",\n title: titleize(name),\n description: `Value for ${name}`,\n sensitive: true,\n required: true,\n };\n env[name] = `\\${user_config.${key}}`;\n }\n }\n\n const author: Record<string, string> = { name: publish.author.name };\n if (publish.author.email) author.email = publish.author.email;\n if (publish.author.url) author.url = publish.author.url;\n\n const mcpConfig: Record<string, unknown> = {\n command: \"node\",\n args: [\"${__dirname}/server/index.js\"],\n };\n if (Object.keys(env).length > 0) mcpConfig.env = env;\n\n const manifest: Record<string, unknown> = {\n manifest_version: MCPB_MANIFEST_VERSION,\n name: connector.id,\n version: connector.version,\n description: connector.displayName,\n author,\n server: {\n type: \"node\",\n entry_point: \"server/index.js\",\n mcp_config: mcpConfig,\n },\n };\n if (Object.keys(userConfig).length > 0) manifest.user_config = userConfig;\n\n // If the dev's real command is not node-ish, the node template needs adjusting.\n if (server.command && !/\\b(node|npx)\\b/.test(server.command)) {\n notes.push(\n `your server command is \"${server.command}\" — the emitted manifest assumes a node ` +\n \"server (server.type:node); adjust server.type/entry_point for your runtime (python|binary).\",\n );\n }\n notes.push(\n \"emitted manifest.json + README recipe; this format does NOT build the .mcpb zip. \" +\n \"Place your self-contained server at server/index.js, vendor deps, then run `mcpb pack` (see README).\",\n );\n\n const emitter = createEmitter(ctx.dryRun);\n emitter.emit(resolve(ctx.outDir, \"manifest.json\"), json(manifest));\n emitter.emit(resolve(ct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CAAgC,MAAM;AAAA,QACtC,oBAAoB,EAAE;AAAA,MACxB;AAAA,IACF,KAAK;AACH,aAAO;AAAA,QACL,gCAAgC,MAAM;AAAA,QACtC,wBAAwB,EAAE;AAAA,MAC5B;AAAA,IACF,KAAK;AACH,aAAO,CAAC,6BAA6BC,MAAK,QAAQ,EAAE,CAAC,EAAE;AAAA,IACzD,KAAK;AACH,aAAO,CAAC,2BAA2BA,MAAK,QAAQ,EAAE,CAAC,EAAE;AAAA,IACvD,KAAK;AACH,aAAO;AAAA,QACL,sBAAsBA,MAAK,QAAQ,EAAE,CAAC;AAAA,QACtC,kCAAkCA,MAAK,QAAQ,EAAE,CAAC;AAAA,MACpD;AAAA,IACF,KAAK;AACH,aAAO;AAAA,QACL,QAAQA,MAAK,QAAQ,EAAE,CAAC,iCAAiC,EAAE;AAAA,QAC3D,eAAe,MAAM;AAAA,MACvB;AAAA,IACF,KAAK;AACH,aAAO,CAAC,uBAAuBA,MAAK,QAAQ,EAAE,CAAC,EAAE;AAAA,IACnD,KAAK;AACH,aAAO;AAAA,QACL,eAAeA,MAAK,QAAQ,EAAE,CAAC;AAAA,MACjC;AAAA,IACF,KAAK;AACH,aAAO;AAAA,QACL;AAAA,QACA,MAAM,MAAM;AAAA,MACd;AAAA,IACF,KAAK;AACH,aAAO;AAAA,QACL,kCAAkCA,MAAK,QAAQ,QAAQ,CAAC;AAAA,QACxD,+BAA+B,MAAM;AAAA,MACvC;AAAA,IACF;AACE,aAAO,CAAC;AAAA,EACZ;AACF;","names":["existsSync","join","resolve","join","buildManifest","buildMarketplace","join","join","SPECS","buildManifest","join","join","PLATFORM","buildManifest","join","join","PLATFORM","buildManifest","join","join","join","resolve","resolve","resolve","resolve","resolve","join"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/adapters/claude-code/index.ts","../src/adapters/claude-code/wire.ts"],"sourcesContent":["/**\n * adapters/claude-code — Claude Code platform adapter for agent-connector.\n *\n * Generalized from context-mode's proven 15-platform Claude adapter: the served\n * identity is now `ctx.connector` (not a hardcoded \"context-mode\"), and every\n * hook command points at the single stable home binary\n * (`buildHomeBinHookCommand`) so one framework update propagates everywhere.\n *\n * Claude Code is a json-stdio host:\n * - MCP servers: user scope → ~/.claude.json (\"mcpServers\"); project scope →\n * <projectDir>/.mcp.json (\"mcpServers\").\n * - Hooks: <configDir>/settings.json under \"hooks\", keyed by event name, each\n * value an array of { matcher, hooks:[{ type:\"command\", command }] }.\n * - Reply: a `hookSpecificOutput` object (allow|deny|ask + reason,\n * additionalContext, updatedInput) on stdout with exit 0.\n */\n\nimport { copyFileSync, existsSync, lstatSync, readFileSync, realpathSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { basename, dirname, join } from \"node:path\";\n\nimport { BaseAdapter } from \"../base.js\";\nimport type { Adapter, HookReply, InstallContext, MemoryTarget, NormalizedEvent } from \"../spi.js\";\nimport type {\n ChangeRecord,\n CommandDef,\n ConfigPatchDef,\n DetectedPlatform,\n DiagnosticResult,\n HealthCheck,\n HookEventName,\n HookParadigm,\n HookResponse,\n JsonValue,\n NotificationEvent,\n PermissionRequestEvent,\n PlatformCapabilities,\n PlatformId,\n PostToolUseEvent,\n PostToolUseFailureEvent,\n PreCompactEvent,\n PreToolUseEvent,\n SessionEndEvent,\n SessionStartEvent,\n ServerDef,\n SkillDef,\n StatuslineContext,\n StopEvent,\n SubagentDef,\n SubagentStartEvent,\n SubagentStopEvent,\n Transport,\n UserPromptSubmitEvent,\n} from \"../../core/types.js\";\nimport { resolveEnvRefsDeep, rewriteEnvRefs } from \"../../core/interpolate.js\";\nimport {\n buildHomeBinHookCommand,\n buildHomeBinStatuslineCommand,\n buildServeWrapperCommand,\n isHomeBinHookCommand,\n isHomeBinStatuslineCommand,\n shouldWrapForTelemetry,\n} from \"../../core/spawn.js\";\nimport {\n type ConfigPatchLedgerEntry,\n addLedgerOwner,\n configPatchManualEdit,\n configPatchNamespaceViolation,\n createLedgerEntry,\n describeJsonValue,\n dropLedgerEntry,\n findLedgerEntry,\n hashJsonValue,\n isValidConfigPatchKey,\n jsonDeepEquals,\n ledgerEntriesOwnedBy,\n loadConfigPatchLedger,\n removeLedgerOwner,\n saveConfigPatchLedger,\n} from \"../../core/config-patch-ledger.js\";\nimport { readRegisteredMeta } from \"../../core/load-connector.js\";\nimport {\n linesOutsideFences,\n listManagedBlocks,\n loadMemoryLedger,\n recordMemoryTarget,\n removeBlocksFromText,\n removeManagedBlocksFile,\n saveMemoryLedger,\n upsertManagedBlockFile,\n} from \"../../core/managed-block.js\";\nimport { backupsDir, ensureDir } from \"../../core/paths.js\";\nimport {\n type ClaudeHookEvent,\n type ClaudeWireInput,\n extractSessionId,\n toolResponseToString,\n} from \"./wire.js\";\nimport { renderCommandMd, renderSkillMd, renderSubagentMd } from \"./render.js\";\n\nconst HOST: PlatformId = \"claude-code\";\nconst MCP_ROOT_KEY = \"mcpServers\";\n\n/**\n * settings.json leaf key the statusline surface owns. Wired through the SAME\n * set-if-absent ownership ledger as configPatch (it is NOT on the configPatch\n * sensitive-key denylist — verified — and is a single top-level leaf), so a\n * non-AC statusLine is never clobbered.\n */\nconst STATUSLINE_KEY = \"statusLine\";\n\n/**\n * Reserved blockId of the SHARED `@AGENTS.md` import bridge in CLAUDE.md\n * (agents-import mode). The `_shared/` prefix cannot collide with a connector\n * blockId (connector ids match ^[a-z0-9][a-z0-9-]*$), and the bridge is\n * refcounted namespace-wide: it is removed only when the LAST agent-connector\n * block leaves the sibling AGENTS.md.\n */\nconst CLAUDE_AGENTS_IMPORT_BLOCK_ID = \"_shared/claude-agents-import\";\n\n/** A single hook registration entry as Claude Code stores it in settings.json. */\ninterface ClaudeHookEntry {\n matcher: string;\n hooks: Array<{ type: \"command\"; command: string }>;\n}\n\n/** Native MCP server entry shapes Claude Code accepts under `mcpServers`. */\ninterface ClaudeStdioServer {\n type: \"stdio\";\n command: string;\n args: string[];\n env?: Record<string, string>;\n cwd?: string;\n}\ninterface ClaudeHttpServer {\n type: \"http\";\n url: string;\n headers?: Record<string, string>;\n}\n\n/**\n * Claude Code statusLine command stdin payload (the documented status-line hook\n * input). Every field optional — a refresh only carries what the host knows.\n * `version` and any unmodeled fields stay in StatuslineContext.raw.\n */\ninterface ClaudeStatuslineInput {\n session_id?: string;\n transcript_path?: string;\n cwd?: string;\n version?: string;\n model?: { id?: string; display_name?: string };\n workspace?: { current_dir?: string; project_dir?: string };\n cost?: { total_cost_usd?: number };\n}\n\nexport class ClaudeCodeAdapter extends BaseAdapter implements Adapter {\n readonly id: PlatformId = HOST;\n readonly name = \"Claude Code\";\n readonly paradigm: HookParadigm = \"json-stdio\";\n\n readonly capabilities: PlatformCapabilities = {\n preToolUse: true,\n postToolUse: true,\n preCompact: true,\n sessionStart: true,\n sessionEnd: true,\n userPromptSubmit: true,\n stop: true,\n notification: true,\n // Newer events — Claude Code is the reference host for all four.\n permissionRequest: true,\n postToolUseFailure: true,\n subagentStart: true,\n subagentStop: true,\n // Claude Code can rewrite PreToolUse input (updatedInput) but does NOT let a\n // PostToolUse hook rewrite already-emitted tool output.\n canModifyArgs: true,\n canModifyOutput: false,\n canInjectSessionContext: true,\n // Native passthrough hooks: settings.json hook keys are free-form event\n // names, so any host event (TaskCreated, TeammateIdle, WorktreeCreate, …)\n // declared under platforms[\"claude-code\"].nativeHooks installs verbatim.\n supportsNativeHooks: true,\n // Declarative host-config key patches: claude-code is the ONLY v1 host\n // (set-if-absent leaf keys in settings.json, refcounted ownership ledger,\n // sensitive-key denylist — see SENSITIVE_KEY_RULES below).\n supportsConfigPatch: true,\n // Statusline surface: claude-code is the ONLY v1 host. installStatusline\n // wires settings.json.statusLine = {type:\"command\", command:<home-bin\n // statusline cmd>} through the SAME set-if-absent ownership ledger as\n // configPatch (never clobbers a statusLine agent-connector does not own).\n supportsStatusline: true,\n transports: [\"stdio\", \"http\"],\n // Content surfaces: Claude Code is the reference implementation for all three.\n supportsCommands: true,\n supportsSkills: true,\n supportsSubagents: true,\n // Memory surface — EXCEPTION host: Claude Code reads CLAUDE.md, NOT\n // AGENTS.md (docs are explicit; no AGENTS.md support through v2.1.172), so\n // memoryTargets/installMemory below override the base AGENTS.md default.\n supportsMemory: true,\n };\n\n // ── Detection ────────────────────────────────────────────────────────────\n\n detectInstalled(projectDir: string): DetectedPlatform {\n const userDir = join(homedir(), \".claude\");\n const userSettings = join(userDir, \"settings.json\");\n const userServers = join(homedir(), \".claude.json\");\n const projectServers = join(projectDir, \".mcp.json\");\n const userInstalled =\n existsSync(userDir) || existsSync(userSettings) || existsSync(userServers);\n const projInstalled = existsSync(projectServers);\n const installed = userInstalled || projInstalled;\n // Report the scope/path/reason for the marker that actually matched, so a\n // project-only install isn't misreported as a (non-existent) user install.\n const scope = projInstalled && !userInstalled ? \"project\" : \"user\";\n const configPath = scope === \"project\" ? projectServers : userSettings;\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 Claude Code config at ${projectServers}`\n : `found Claude Code config under ${userDir}`\n : `no Claude Code config at ${userDir}`,\n confidence: installed ? \"high\" : \"low\",\n };\n }\n\n // ── Native paths ─────────────────────────────────────────────────────────\n\n getConfigDir(ctx: InstallContext): string {\n return ctx.scope === \"project\"\n ? join(ctx.projectDir, \".claude\")\n : join(homedir(), \".claude\");\n }\n\n getServerConfigPath(ctx: InstallContext): string {\n return ctx.scope === \"project\"\n ? join(ctx.projectDir, \".mcp.json\")\n : join(homedir(), \".claude.json\");\n }\n\n getHookConfigPath(ctx: InstallContext): string {\n return join(this.getConfigDir(ctx), \"settings.json\");\n }\n\n // ── MCP server install / uninstall ───────────────────────────────────────\n\n installServer(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n const override = connector.platforms[HOST]?.server;\n if (!connector.server || override === false) {\n return [\n {\n platform: this.id,\n action: \"skip\",\n detail: connector.server\n ? \"server registration disabled for claude-code\"\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 Claude Code's native mcpServers entry. */\n private renderServerEntry(\n ctx: InstallContext,\n server: ServerDef,\n ): ClaudeStdioServer | ClaudeHttpServer {\n const transport: Transport = server.transport;\n\n if (transport === \"stdio\") {\n let command = server.command ?? \"\";\n let args = [...(server.args ?? [])];\n\n // Transparent telemetry wrapping: route the real command through\n // `<homeBin> serve --connector <id> -- <command> <args...>`.\n if (shouldWrapForTelemetry(server, ctx.connector.telemetry)) {\n const wrapped = buildServeWrapperCommand(\n ctx.homeBinPath,\n ctx.connector.id,\n command,\n args,\n ctx.scope,\n this.id,\n );\n command = wrapped.command;\n args = wrapped.args;\n }\n\n const entry: ClaudeStdioServer = { type: \"stdio\", command, args };\n const env = this.renderEnv(server.env);\n if (env) entry.env = env;\n if (server.cwd) entry.cwd = resolveEnvRefsDeep(server.cwd);\n return entry;\n }\n\n // http (and any other remote transport we surface) — Claude registers a URL.\n const entry: ClaudeHttpServer = {\n type: \"http\",\n url: rewriteEnvRefs(server.url ?? \"\", claudeEnvToken),\n };\n if (server.headers) {\n entry.headers = this.renderEnv(server.headers) ?? {};\n }\n return entry;\n }\n\n /**\n * Render env/header values. Claude Code supports its own `${VAR}` native\n * interpolation, so translate `${env:VAR}` refs to that native token rather\n * than baking secrets into the file. Literals pass through unchanged.\n */\n private renderEnv(\n env: Record<string, string> | undefined,\n ): Record<string, string> | undefined {\n if (!env || Object.keys(env).length === 0) return undefined;\n const out: Record<string, string> = {};\n for (const [k, v] of Object.entries(env)) {\n out[k] = rewriteEnvRefs(v, claudeEnvToken);\n }\n return out;\n }\n\n // ── Hook install / uninstall ─────────────────────────────────────────────\n\n installHooks(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n const override = connector.platforms[HOST];\n\n // `hooks: false` disables only the NORMALIZED hooks. nativeHooks is a\n // sibling, explicitly claude-code-scoped declaration on the same override —\n // it installs regardless (the dev wrote both keys on the same object).\n const normalizedEvents = override?.hooks === false ? [] : connector.hookEvents;\n const nativeHooks = override?.nativeHooks ?? {};\n const nativeEvents = Object.keys(nativeHooks);\n\n if (normalizedEvents.length === 0 && nativeEvents.length === 0) {\n return [\n {\n platform: this.id,\n action: \"skip\",\n detail:\n override?.hooks === false\n ? \"hooks disabled for claude-code\"\n : \"connector declares no hooks\",\n },\n ];\n }\n\n const settingsPath = this.getHookConfigPath(ctx);\n const settings = this.readJson<Record<string, unknown>>(settingsPath) ?? {};\n const hooks = (settings.hooks ??= {}) as Record<string, ClaudeHookEntry[]>;\n\n const changes: ChangeRecord[] = [];\n let mutated = false;\n\n // One pass over normalized + NATIVE events: native event-name keys are\n // written VERBATIM (e.g. \"TaskCreated\"), matcher from the def, and the\n // exact same home-bin command shape — so uninstall/doctor/telemetry treat\n // both identically.\n const pending: Array<{ event: string; matcher: string }> = [\n ...normalizedEvents.map((event) => ({\n event: event as string,\n matcher: connector.hooks[event]?.matcher ?? \"\",\n })),\n ...nativeEvents.map((event) => ({\n event,\n matcher: nativeHooks[event]?.matcher ?? \"\",\n })),\n ];\n\n for (const { event, matcher } of pending) {\n const command = buildHomeBinHookCommand(ctx.homeBinPath, HOST, event, connector.id);\n const entry: ClaudeHookEntry = {\n matcher,\n hooks: [{ type: \"command\", command }],\n };\n\n const bucket = (hooks[event] ??= []);\n const existingIdx = bucket.findIndex((e) => this.entryHasCommand(e, command));\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: settingsPath,\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: settingsPath,\n detail: `hooks.${event}`,\n });\n } else {\n bucket.push(entry);\n changes.push({\n platform: this.id,\n action: \"create\",\n path: settingsPath,\n detail: `hooks.${event}`,\n });\n }\n mutated = true;\n }\n\n if (mutated) this.writeJson(settingsPath, settings, ctx.dryRun);\n return changes;\n }\n\n uninstallHooks(ctx: InstallContext): ChangeRecord[] {\n const settingsPath = this.getHookConfigPath(ctx);\n const settings = this.readJson<Record<string, unknown>>(settingsPath);\n const hooks = settings?.hooks as Record<string, ClaudeHookEntry[]> | undefined;\n if (!settings || !hooks) {\n return [\n {\n platform: this.id,\n action: \"skip\",\n path: settingsPath,\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.\n const next: ClaudeHookEntry[] = [];\n let removed = 0;\n for (const e of bucket) {\n const innerBefore = e.hooks?.length ?? 0;\n const inner = (e.hooks ?? []).filter(\n (h) => !this.isOurCommand(h.command, ctx),\n );\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: settingsPath,\n detail: `hooks.${event} (${removed})`,\n });\n mutated = true;\n }\n }\n\n if (mutated) this.writeJson(settingsPath, settings, ctx.dryRun);\n if (changes.length === 0) {\n changes.push({\n platform: this.id,\n action: \"skip\",\n path: settingsPath,\n detail: \"no matching hook entries\",\n });\n }\n return changes;\n }\n\n private entryHasCommand(entry: ClaudeHookEntry, command: string): boolean {\n return (entry.hooks ?? []).some((h) => h.command === command);\n }\n\n // ── Declarative host-config key patches (configPatch) ────────────────────\n // FIXED semantics (docs/ARCHITECTURE.md §4): set-if-absent on a single\n // dotted LEAF key of settings.json, skip-warn on ANY conflict (present key,\n // non-object intermediate, drift), refcounted ownership in the persisted\n // ledger at <dataRoot>/state/config-patches.json. Reuses the adapter's\n // existing whole-file settings.json JSON IO (the same handling the hook\n // install performs on this exact file) — Claude Code itself rewrites this\n // file, so format preservation is a non-issue here. NOTE for future hosts:\n // VS Code JSONC needs jsonc-parser modify/applyEdits and Codex TOML needs an\n // anchored edit — core/toml.ts's round-trip is BANNED for configPatch.\n\n /** The ONLY file configPatch may touch on claude-code: settings.json at scope. */\n getPatchableConfigPath(ctx: InstallContext): string {\n return join(this.getConfigDir(ctx), \"settings.json\");\n }\n\n override installConfigPatches(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n const patches = connector.platforms[HOST]?.configPatch ?? [];\n if (patches.length === 0) {\n return [\n { platform: this.id, action: \"skip\", detail: \"connector declares no configPatch entries\" },\n ];\n }\n return this.applyConfigPatches(ctx, patches);\n }\n\n /**\n * The shared set-if-absent / ownership-ledger apply loop behind BOTH\n * {@link installConfigPatches} and {@link installStatusline}. Routing the\n * statusline through the EXACT same path is how a connector's statusLine\n * inherits the configPatch contract verbatim: never clobber a statusLine\n * agent-connector does not own (skip-warn), record prior state + owner,\n * refcounted across connectors, reversible by uninstallConfigPatches.\n */\n private applyConfigPatches(\n ctx: InstallContext,\n patches: ConfigPatchDef[],\n opts: { surfaceLabel?: \"configPatch\" | \"statusline\" } = {},\n ): ChangeRecord[] {\n // The user-facing surface name in every ChangeRecord.detail. \"statusline\"\n // routes the AC-modeled statusLine key through this loop INTERNALLY — that\n // key is namespace-reserved against raw configPatch, so the internal path\n // bypasses the namespace guard (the surface, not a smuggled patch, owns it).\n const surfaceLabel = opts.surfaceLabel ?? \"configPatch\";\n const internal = surfaceLabel !== \"configPatch\";\n const { connector } = ctx;\n const filePath = this.getPatchableConfigPath(ctx);\n // OVERWRITE GUARD (upsertServerInJson precedent): never round-trip a\n // present-but-unparseable settings file into `{}`.\n if (this.isPresentButUnparseable(filePath)) {\n return [\n {\n platform: this.id,\n action: \"warn\",\n path: filePath,\n detail: `existing ${filePath} is not parseable; configPatch left unapplied (back it up / fix it, then re-run)`,\n },\n ];\n }\n const settings = this.readJson<Record<string, unknown>>(filePath) ?? {};\n if (typeof settings !== \"object\" || Array.isArray(settings)) {\n return [\n {\n platform: this.id,\n action: \"warn\",\n path: filePath,\n detail: `existing ${filePath} is not a JSON object; configPatch left unapplied`,\n },\n ];\n }\n\n const ledger = loadConfigPatchLedger(ctx.dataRoot);\n const changes: ChangeRecord[] = [];\n let fileMutated = false;\n let ledgerMutated = false;\n\n for (const patch of patches) {\n // Defense in depth: re-validate grammar + AC-namespace here (a connector\n // loaded from raw meta/JSON must not bypass defineConnector's checks).\n if (!isValidConfigPatchKey(patch.key)) {\n changes.push({\n platform: this.id,\n action: \"warn\",\n detail:\n `configPatch ${JSON.stringify(patch.key)} refused: not a dotted leaf path ` +\n `(segments must match [A-Za-z0-9_-]+; no array indices)`,\n });\n continue;\n }\n // The statusline surface intentionally models the (now namespace-reserved)\n // statusLine key, so its internal patches skip this guard.\n if (!internal) {\n const namespace = configPatchNamespaceViolation(patch.key);\n if (namespace) {\n changes.push({\n platform: this.id,\n action: \"warn\",\n detail: `configPatch refused: ${namespace}`,\n });\n continue;\n }\n }\n // SENSITIVE-KEY DENYLIST — hard refuse, no override flag in v1.\n const sensitive = claudeSensitiveKeyViolation(patch.key);\n if (sensitive) {\n changes.push({\n platform: this.id,\n action: \"warn\",\n detail:\n `configPatch ${patch.key} refused: matches the claude-code sensitive-key ` +\n `denylist (${sensitive}); security-relevant keys are never patched`,\n });\n continue;\n }\n\n // `${env:VAR}` refs resolve at install time, matching server-entry behavior.\n const desired = resolveEnvRefsDeep(patch.value) as JsonValue;\n const segments = patch.key.split(\".\");\n const leaf = readJsonLeaf(settings, segments);\n const entry = findLedgerEntry(ledger, HOST, filePath, patch.key);\n\n if (leaf.kind === \"blocked\") {\n changes.push({\n platform: this.id,\n action: \"warn\",\n path: filePath,\n detail:\n `${surfaceLabel} ${patch.key} skipped: \"${leaf.atPath}\" exists but is not an ` +\n `object — ${configPatchManualEdit(patch)}`,\n });\n continue;\n }\n\n if (leaf.kind === \"absent\") {\n // SET-IF-ABSENT: the one write path. Intermediates created only as needed.\n writeJsonLeaf(settings, segments, desired);\n fileMutated = true;\n if (entry) {\n // Stale ledger row (key was deleted out from under us): re-assert the\n // value, keep existing owners (they still rely on the key existing),\n // and record what was actually (re)written.\n entry.writtenValue = desired;\n entry.writtenValueHash = hashJsonValue(desired);\n addLedgerOwner(entry, connector.id, connector.version);\n } else {\n createLedgerEntry(ledger, {\n platform: HOST,\n file: filePath,\n key: patch.key,\n value: desired,\n connectorId: connector.id,\n connectorVersion: connector.version,\n });\n }\n ledgerMutated = true;\n changes.push({\n platform: this.id,\n action: \"create\",\n path: filePath,\n detail: `${surfaceLabel} ${patch.key}: <absent> → ${describeJsonValue(desired)} (${patch.reason})`,\n });\n continue;\n }\n\n // Key PRESENT — never overwrite; the only question is ownership/refcount.\n if (!entry) {\n // User- (or other-tool-) owned. No ownership is taken even when values\n // happen to match — uninstall must never delete a key we did not create.\n changes.push({\n platform: this.id,\n action: \"warn\",\n path: filePath,\n detail:\n `${surfaceLabel} ${patch.key} skipped: already set to ${describeJsonValue(leaf.value)} ` +\n `(not created by agent-connector; desired ${describeJsonValue(desired)}) — ` +\n configPatchManualEdit(patch),\n });\n continue;\n }\n\n if (!jsonDeepEquals(leaf.value, entry.writtenValue)) {\n // DRIFT: the user edited the value after we wrote it. Never revert —\n // sync re-asserts only ABSENT keys.\n changes.push({\n platform: this.id,\n action: \"warn\",\n path: filePath,\n detail:\n `${surfaceLabel} ${patch.key}: value changed since install ` +\n `(current ${describeJsonValue(leaf.value)}, wrote ${describeJsonValue(entry.writtenValue)}); ` +\n `leaving in place — ${configPatchManualEdit(patch)}`,\n });\n continue;\n }\n\n if (jsonDeepEquals(desired, leaf.value)) {\n // Same value we own: register as co-owner (refcount++) or plain\n // idempotent skip when this connector is already an owner.\n const owners = entry.owners.map((o) => o.connectorId);\n if (addLedgerOwner(entry, connector.id, connector.version)) {\n ledgerMutated = true;\n changes.push({\n platform: this.id,\n action: \"skip\",\n path: filePath,\n detail: `${surfaceLabel} ${patch.key} already installed; registered as co-owner (co-owned with ${owners.join(\", \")})`,\n });\n } else {\n changes.push({\n platform: this.id,\n action: \"skip\",\n path: filePath,\n detail: `${surfaceLabel} ${patch.key} already installed`,\n });\n }\n continue;\n }\n\n // FIRST-WRITER-WINS: another connector owns this key with a different value.\n changes.push({\n platform: this.id,\n action: \"warn\",\n path: filePath,\n detail:\n `${surfaceLabel} ${patch.key} skipped: already owned by ${entry.owners\n .map((o) => o.connectorId)\n .join(\", \")} with a different value ` +\n `(current ${describeJsonValue(leaf.value)}, desired ${describeJsonValue(desired)}) — ` +\n configPatchManualEdit(patch),\n });\n }\n\n if (fileMutated) this.writeJson(filePath, settings, ctx.dryRun);\n if (ledgerMutated && !ctx.dryRun) saveConfigPatchLedger(ctx.dataRoot, ledger);\n return changes;\n }\n\n override uninstallConfigPatches(ctx: InstallContext): ChangeRecord[] {\n const connectorId = ctx.connector.id;\n const ledger = loadConfigPatchLedger(ctx.dataRoot);\n // Keyed off the LEDGER (not the declaration): releases ownership for every\n // file/scope this connector ever patched, even when the uninstall context\n // is a minimal synthetic connector or the scope flag differs from install.\n // EXCLUDE the statusLine key — that surface releases via uninstallStatusline\n // (the installer runs both), so this never double-processes the same row.\n const owned = ledgerEntriesOwnedBy(ledger, HOST, connectorId).filter(\n (e) => e.key !== STATUSLINE_KEY,\n );\n const declared = ctx.connector.platforms[HOST]?.configPatch ?? [];\n const changes: ChangeRecord[] = [];\n\n // Declared patches with NO ownership record anywhere: never delete a key\n // we did not create (rule 1) — explicit skip so the outcome is never silent.\n const ownedKeys = new Set(owned.map((e) => e.key));\n for (const patch of declared) {\n if (!ownedKeys.has(patch.key)) {\n changes.push({\n platform: this.id,\n action: \"skip\",\n detail: `configPatch ${patch.key}: no ownership recorded; left untouched`,\n });\n }\n }\n if (owned.length === 0) return changes;\n changes.push(...this.releaseOwnedConfigPatches(ctx, ledger, owned));\n return changes;\n }\n\n /**\n * The shared last-owner-verified release loop behind BOTH\n * {@link uninstallConfigPatches} and {@link uninstallStatusline}: for each\n * already-selected owned ledger entry, drop this connector's ownership and\n * remove the key ONLY when last-owner ∧ value-unchanged ∧ prior-absent (else\n * skip-warn + leave the key). Saves the ledger when it mutated.\n */\n private releaseOwnedConfigPatches(\n ctx: InstallContext,\n ledger: ReturnType<typeof loadConfigPatchLedger>,\n owned: ConfigPatchLedgerEntry[],\n opts: { surfaceLabel?: \"configPatch\" | \"statusline\" } = {},\n ): ChangeRecord[] {\n const surfaceLabel = opts.surfaceLabel ?? \"configPatch\";\n const connectorId = ctx.connector.id;\n const changes: ChangeRecord[] = [];\n let ledgerMutated = false;\n const backedUp = new Set<string>();\n\n // Group by file (entries may span scopes/files).\n const byFile = new Map<string, ConfigPatchLedgerEntry[]>();\n for (const entry of owned) {\n const bucket = byFile.get(entry.file) ?? [];\n bucket.push(entry);\n byFile.set(entry.file, bucket);\n }\n\n for (const [filePath, entries] of byFile) {\n const unparseable = this.isPresentButUnparseable(filePath);\n const settings = unparseable\n ? null\n : this.readJson<Record<string, unknown>>(filePath);\n let fileMutated = false;\n\n for (const entry of entries) {\n const { lastOwner } = removeLedgerOwner(entry, connectorId);\n ledgerMutated = true;\n\n if (!lastOwner) {\n // The shared-flag case: A uninstalls, B still relies on the key.\n changes.push({\n platform: this.id,\n action: \"skip\",\n path: filePath,\n detail: `${surfaceLabel} ${entry.key} retained: still owned by ${entry.owners\n .map((o) => o.connectorId)\n .join(\", \")}`,\n });\n continue;\n }\n\n // Last owner out → the ledger row is dropped on every branch below;\n // the KEY is removed only on the fully-verified branch.\n dropLedgerEntry(ledger, entry);\n\n if (unparseable) {\n changes.push({\n platform: this.id,\n action: \"warn\",\n path: filePath,\n detail: `${surfaceLabel} ${entry.key}: ${filePath} is not parseable; key left in place (ownership released)`,\n });\n continue;\n }\n if (!settings || typeof settings !== \"object\" || Array.isArray(settings)) {\n changes.push({\n platform: this.id,\n action: \"skip\",\n path: filePath,\n detail: `${surfaceLabel} ${entry.key} already absent (no settings file); ownership record dropped`,\n });\n continue;\n }\n const leaf = readJsonLeaf(settings, entry.key.split(\".\"));\n if (leaf.kind !== \"present\") {\n changes.push({\n platform: this.id,\n action: \"skip\",\n path: filePath,\n detail: `${surfaceLabel} ${entry.key} already absent; ownership record dropped`,\n });\n continue;\n }\n if (entry.prior?.present !== false || !jsonDeepEquals(leaf.value, entry.writtenValue)) {\n // User edited the value after install (or the row predates the\n // set-if-absent guarantee): deleting would clobber them. Leave it.\n changes.push({\n platform: this.id,\n action: \"warn\",\n path: filePath,\n detail:\n `${surfaceLabel} ${entry.key}: value changed since install ` +\n `(current ${describeJsonValue(leaf.value)}, wrote ${describeJsonValue(entry.writtenValue)}); ` +\n `left in place`,\n });\n continue;\n }\n\n // VERIFIED: last owner + current === writtenValue + prior was absent.\n // Back up the exact file before its first mutation, then delete the\n // leaf key (intermediate objects we created are left in place).\n if (!ctx.dryRun && !backedUp.has(filePath) && existsSync(filePath)) {\n const backup = this.backupFileForConfigPatch(filePath);\n backedUp.add(filePath);\n if (backup) {\n changes.push({\n platform: this.id,\n action: \"create\",\n path: backup,\n detail: \"backed up settings before configPatch removal\",\n });\n }\n }\n deleteJsonLeaf(settings, entry.key.split(\".\"));\n fileMutated = true;\n changes.push({\n platform: this.id,\n action: \"remove\",\n path: filePath,\n detail: `${surfaceLabel} ${entry.key} removed (was ${describeJsonValue(entry.writtenValue)})`,\n });\n }\n\n if (fileMutated && settings) this.writeJson(filePath, settings, ctx.dryRun);\n }\n\n if (ledgerMutated && !ctx.dryRun) saveConfigPatchLedger(ctx.dataRoot, ledger);\n return changes;\n }\n\n // ── Statusline surface (a HUD/status line) ────────────────────────────────\n // Wires settings.json.statusLine = { type:\"command\", command:<home-bin\n // statusline cmd> } through the SAME ownership ledger as configPatch: a\n // synthetic ConfigPatchDef routed through applyConfigPatches, so the statusLine\n // inherits the full set-if-absent contract verbatim — never clobbers a\n // statusLine agent-connector does not own (skip-warn), records prior state +\n // owner, reversible. The home-bin command makes the host exec\n // `<homeBin> statusline claude-code --connector <id>` for every status refresh,\n // which re-imports the connector module and renders the line (runtime/\n // statusline-entrypoint). No telemetry in v1.\n\n /** The synthetic statusLine configPatch this connector would write. */\n private statuslineConfigPatch(ctx: InstallContext): ConfigPatchDef {\n const command = buildHomeBinStatuslineCommand(ctx.homeBinPath, HOST, ctx.connector.id);\n return {\n key: STATUSLINE_KEY,\n value: { type: \"command\", command },\n reason: \"agent-connector statusline surface\",\n };\n }\n\n override installStatusline(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n if (connector.statusline == null) {\n return [{ platform: this.id, action: \"skip\", detail: \"connector declares no statusline\" }];\n }\n if (connector.platforms[HOST]?.statusline === false) {\n return [{ platform: this.id, action: \"skip\", detail: \"statusline disabled for claude-code\" }];\n }\n // Reuse the configPatch apply path (set-if-absent, ownership ledger, skip-warn\n // on any non-AC statusLine). This is the SAME machinery installConfigPatches\n // uses on this exact file, so the ownership semantics are identical — only the\n // surface LABEL differs (statusLine is namespace-reserved against raw\n // configPatch; this internal path bypasses that guard and owns the key).\n return this.applyConfigPatches(ctx, [this.statuslineConfigPatch(ctx)], {\n surfaceLabel: \"statusline\",\n });\n }\n\n override uninstallStatusline(ctx: InstallContext): ChangeRecord[] {\n const ledger = loadConfigPatchLedger(ctx.dataRoot);\n // Release ONLY the statusLine ledger row this connector owns (keyed off the\n // ledger, not the declaration, so an id-only synthetic uninstall still\n // reclaims it). Same last-owner-verified delete as uninstallConfigPatches.\n const owned = ledgerEntriesOwnedBy(ledger, HOST, ctx.connector.id).filter(\n (e) => e.key === STATUSLINE_KEY,\n );\n if (owned.length === 0) {\n return [\n {\n platform: this.id,\n action: \"skip\",\n detail: \"statusline: no ownership recorded; left untouched\",\n },\n ];\n }\n return this.releaseOwnedConfigPatches(ctx, ledger, owned, {\n surfaceLabel: \"statusline\",\n });\n }\n\n /**\n * Parse Claude Code's statusLine stdin JSON into the normalized\n * {@link StatuslineContext}. Claude pipes a JSON object to the statusLine\n * command on stdin (model, workspace, cost, etc.); fields the payload omits\n * stay undefined. `raw` keeps the verbatim payload (incl. `version`).\n */\n parseStatusInput(raw: unknown): StatuslineContext {\n const input = (raw ?? {}) as ClaudeStatuslineInput;\n const model: { id?: string; displayName?: string } = {};\n if (typeof input.model?.id === \"string\") model.id = input.model.id;\n if (typeof input.model?.display_name === \"string\") {\n model.displayName = input.model.display_name;\n }\n const cwd =\n typeof input.cwd === \"string\"\n ? input.cwd\n : typeof input.workspace?.current_dir === \"string\"\n ? input.workspace.current_dir\n : undefined;\n\n const ctx: StatuslineContext = {\n host: HOST,\n capabilities: this.capabilities,\n raw,\n };\n if (typeof input.session_id === \"string\" && input.session_id !== \"\") {\n ctx.sessionId = input.session_id;\n }\n if (cwd !== undefined) ctx.cwd = cwd;\n if (model.id !== undefined || model.displayName !== undefined) ctx.model = model;\n if (typeof input.cost?.total_cost_usd === \"number\") {\n ctx.cost = { totalUsd: input.cost.total_cost_usd };\n }\n if (typeof input.transcript_path === \"string\") {\n ctx.transcriptPath = input.transcript_path;\n }\n return ctx;\n }\n\n /** Format the rendered status line into Claude's native reply: stdout = line, exit 0. */\n formatStatusOutput(rendered: string): HookReply {\n return { exitCode: 0, stdout: rendered };\n }\n\n /**\n * Back up ONE exact file (the ledger-recorded patch target, which may belong\n * to a different scope than the current ctx) into the standard backups dir.\n * Best-effort: a failed copy returns null and the caller proceeds — the\n * removal is already value-verified.\n */\n private backupFileForConfigPatch(filePath: string): string | null {\n try {\n ensureDir(backupsDir());\n const stamp = new Date().toISOString().replace(/[:.]/g, \"-\");\n const dest = join(backupsDir(), `${this.id}-${stamp}-${basename(filePath)}`);\n copyFileSync(filePath, dest);\n return dest;\n } catch {\n return null;\n }\n }\n\n /**\n * Doctor: per-ledger-entry configPatch state for this connector —\n * ok → key present and still exactly what we wrote;\n * drifted → user changed the value (we print the manual edit, NEVER\n * auto-fix — sync re-asserts only absent keys);\n * missing → key deleted by the user; sync will re-assert it;\n * orphaned → ledger row whose owners' connector records are all gone.\n * Plus a re-print of the manual edit for declared patches that hold no\n * ownership (skipped at install).\n */\n private configPatchDiagnostics(ctx: InstallContext): DiagnosticResult[] {\n const results: DiagnosticResult[] = [];\n const ledger = loadConfigPatchLedger(ctx.dataRoot);\n const connectorId = ctx.connector.id;\n // EXCLUDE the statusLine row: it is owned by the statusline surface and gets\n // its own dedicated health check in getHealthChecks. Reporting it here too\n // would double-report the key and (on a user edit) print a bogus configPatch\n // \"drifted\" hint to restore a configPatch the connector never declared.\n const platformEntries = ledger.entries.filter(\n (e) => e.platform === this.id && e.key !== STATUSLINE_KEY,\n );\n\n for (const entry of platformEntries) {\n const ownedByThis = entry.owners.some((o) => o.connectorId === connectorId);\n if (!ownedByThis) {\n // ORPHAN check (global hygiene): every owner's connector record is gone.\n const orphaned =\n entry.owners.length === 0 ||\n entry.owners.every((o) => readRegisteredMeta(o.connectorId) === null);\n if (orphaned) {\n results.push({\n check: `${this.name}: configPatch ${entry.key}`,\n status: \"warn\",\n message:\n `orphaned ledger entry in ${entry.file}: owning connector record(s) ` +\n `gone (${entry.owners.map((o) => o.connectorId).join(\", \") || \"none\"})`,\n fix:\n `re-run \\`agent-connector uninstall <owner-id>\\` to release it, or remove ` +\n `${entry.key} from ${entry.file} manually`,\n });\n }\n continue;\n }\n\n const state = this.configPatchState(entry);\n if (state.kind === \"ok\") {\n results.push({\n check: `${this.name}: configPatch ${entry.key}`,\n status: \"pass\",\n message: `ok — ${entry.key} = ${describeJsonValue(entry.writtenValue)} (${entry.file})`,\n });\n } else if (state.kind === \"missing\") {\n results.push({\n check: `${this.name}: configPatch ${entry.key}`,\n status: \"warn\",\n message: `missing — key deleted from ${entry.file} since install`,\n fix: `agent-connector install (sync) will re-assert it`,\n });\n } else {\n results.push({\n check: `${this.name}: configPatch ${entry.key}`,\n status: \"warn\",\n message:\n `drifted — value changed since install (current ${describeJsonValue(state.current)}, ` +\n `wrote ${describeJsonValue(entry.writtenValue)}); never auto-fixed`,\n fix: `manual edit if wanted: set ${entry.key} = ${describeJsonValue(entry.writtenValue)} in ${entry.file}`,\n });\n }\n }\n\n // Declared-but-unowned patches: re-print the manual edit (the patch was\n // skipped at install — conflict, denylist, or simply not installed yet).\n const declared = ctx.connector.platforms[HOST]?.configPatch ?? [];\n const ownedKeys = new Set(\n ledgerEntriesOwnedBy(ledger, HOST, connectorId).map((e) => e.key),\n );\n for (const patch of declared) {\n if (ownedKeys.has(patch.key)) continue;\n results.push({\n check: `${this.name}: configPatch ${patch.key}`,\n status: \"warn\",\n message: `declared but not owned (skipped at install or not yet installed)`,\n fix: configPatchManualEdit(patch),\n });\n }\n return results;\n }\n\n /** Current on-disk state of one owned ledger entry. */\n private configPatchState(\n entry: ConfigPatchLedgerEntry,\n ): { kind: \"ok\" } | { kind: \"missing\" } | { kind: \"drifted\"; current: JsonValue } {\n const settings = this.readJson<Record<string, unknown>>(entry.file);\n if (!settings || typeof settings !== \"object\" || Array.isArray(settings)) {\n return { kind: \"missing\" };\n }\n const leaf = readJsonLeaf(settings, entry.key.split(\".\"));\n if (leaf.kind !== \"present\") return { kind: \"missing\" };\n if (jsonDeepEquals(leaf.value, entry.writtenValue)) return { kind: \"ok\" };\n return { kind: \"drifted\", current: leaf.value };\n }\n\n override doctor(ctx: InstallContext): DiagnosticResult[] {\n const results = super.doctor(ctx);\n results.push(...this.configPatchDiagnostics(ctx));\n return results;\n }\n\n // ── Content surfaces: commands / skills / subagents ──────────────────────\n // CONTENT-ONLY: pure native-file writers under <configDir>/{commands,skills,\n // agents}. No runtime dispatch, no home-bin pointer, no telemetry wrap. Each\n // method is idempotent (byte-identical → skip) via BaseAdapter.writeContentFile\n // and reversible via removeContentFile. Honors platforms[\"claude-code\"]\n // per-surface false to skip.\n\n private commandsDir(ctx: InstallContext): string {\n return join(this.getConfigDir(ctx), \"commands\");\n }\n private skillsDir(ctx: InstallContext): string {\n return join(this.getConfigDir(ctx), \"skills\");\n }\n private agentsDir(ctx: InstallContext): string {\n return join(this.getConfigDir(ctx), \"agents\");\n }\n\n /** Native command file path: <configDir>/commands/<name>.md. */\n private commandPath(ctx: InstallContext, name: string): string {\n return join(this.commandsDir(ctx), `${name}.md`);\n }\n /** Native skill dir: <configDir>/skills/<name>. */\n private skillDir(ctx: InstallContext, name: string): string {\n return join(this.skillsDir(ctx), name);\n }\n /** Native subagent file path: <configDir>/agents/<name>.md. */\n private subagentPath(ctx: InstallContext, name: string): string {\n return join(this.agentsDir(ctx), `${name}.md`);\n }\n\n // ── Commands ──────────────────────────────────────────────────────────────\n\n override installCommands(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n if (connector.platforms[HOST]?.commands === false) {\n return [{ platform: this.id, action: \"skip\", detail: \"commands disabled for claude-code\" }];\n }\n if (connector.commands.length === 0) {\n return [{ platform: this.id, action: \"skip\", detail: \"connector declares no commands\" }];\n }\n return connector.commands.map((cmd) =>\n this.writeContentFile(\n this.commandPath(ctx, cmd.name),\n this.renderCommand(cmd),\n ctx.dryRun,\n ),\n );\n }\n\n override uninstallCommands(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n if (connector.commands.length === 0) {\n return [{ platform: this.id, action: \"skip\", detail: \"connector declares no commands\" }];\n }\n return connector.commands.map((cmd) =>\n this.removeContentFile(this.commandPath(ctx, cmd.name), ctx.dryRun),\n );\n }\n\n /** Render a command to md+frontmatter (delegates to the shared renderer). */\n private renderCommand(cmd: CommandDef): string {\n return renderCommandMd(cmd);\n }\n\n // ── Skills ────────────────────────────────────────────────────────────────\n\n override installSkills(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n if (connector.platforms[HOST]?.skills === false) {\n return [{ platform: this.id, action: \"skip\", detail: \"skills disabled for claude-code\" }];\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\"), this.renderSkill(skill), ctx.dryRun),\n );\n // Bundle any resource files beside SKILL.md (relative path → contents).\n // Defense-in-depth: skip+warn on any key that escapes the skill dir\n // (config-time validation already rejects these, but never trust input).\n for (const [rel, contents] of Object.entries(skill.resources ?? {})) {\n const target = this.resolveWithin(dir, rel);\n if (target === null) {\n changes.push({\n platform: this.id,\n action: \"warn\",\n detail: `skill resource \"${rel}\" escapes the skill dir; skipped`,\n });\n continue;\n }\n changes.push(this.writeContentFile(target, contents, ctx.dryRun));\n }\n }\n return changes;\n }\n\n override uninstallSkills(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n if (connector.skills.length === 0) {\n return [{ platform: this.id, action: \"skip\", detail: \"connector declares no skills\" }];\n }\n const changes: ChangeRecord[] = [];\n for (const skill of connector.skills) {\n const dir = this.skillDir(ctx, skill.name);\n // Remove only the files we wrote (SKILL.md + declared resources), then the\n // skill dir itself when we own its full contents.\n changes.push(this.removeContentFile(join(dir, \"SKILL.md\"), ctx.dryRun));\n for (const rel of Object.keys(skill.resources ?? {})) {\n const target = this.resolveWithin(dir, rel);\n if (target === null) continue; // never delete outside the skill dir\n changes.push(this.removeContentFile(target, ctx.dryRun));\n }\n // Only remove the skill dir when WE own its full contents — never rm -rf a\n // dir that still holds user-added / sibling-tool / shared files.\n changes.push(this.removeDirIfEmpty(dir, ctx.dryRun));\n }\n return changes;\n }\n\n /** Render a skill's SKILL.md (delegates to the shared renderer). */\n private renderSkill(skill: SkillDef): string {\n return renderSkillMd(skill);\n }\n\n // ── Subagents ───────────────────────────────────────────────────────────────\n\n override installSubagents(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n if (connector.platforms[HOST]?.subagents === false) {\n return [{ platform: this.id, action: \"skip\", detail: \"subagents disabled for claude-code\" }];\n }\n if (connector.subagents.length === 0) {\n return [{ platform: this.id, action: \"skip\", detail: \"connector declares no subagents\" }];\n }\n return connector.subagents.map((agent) =>\n this.writeContentFile(\n this.subagentPath(ctx, agent.name),\n this.renderSubagent(agent),\n ctx.dryRun,\n ),\n );\n }\n\n override uninstallSubagents(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n if (connector.subagents.length === 0) {\n return [{ platform: this.id, action: \"skip\", detail: \"connector declares no subagents\" }];\n }\n return connector.subagents.map((agent) =>\n this.removeContentFile(this.subagentPath(ctx, agent.name), ctx.dryRun),\n );\n }\n\n /** Render a subagent to md+frontmatter (delegates to the shared renderer). */\n private renderSubagent(agent: SubagentDef): string {\n return renderSubagentMd(agent);\n }\n\n // ── Memory surface: CLAUDE.md managed block + AGENTS.md interop ────────────\n // EXCEPTION host. Claude Code reads CLAUDE.md, NOT AGENTS.md (docs verbatim:\n // \"Claude Code reads CLAUDE.md, not AGENTS.md\"; no AGENTS.md support through\n // v2.1.172), so the base AGENTS.md-first default is overridden:\n // - mode \"block\" (default): the managed block goes straight into CLAUDE.md.\n // HTML-comment markers are CORRECT here — Claude strips HTML comments\n // from CLAUDE.md before context injection, so the markers and the\n // do-not-edit notice are INVISIBLE to the model while remaining fully\n // parseable by us for sync/doctor/uninstall.\n // - mode \"agents-import\" (opt-in via platforms[\"claude-code\"].memory.mode):\n // canonical block goes into AGENTS.md, plus a SHARED `@AGENTS.md` import\n // bridge block in CLAUDE.md (Anthropic's documented interop). Opt-in\n // because the import makes Claude read the ENTIRE AGENTS.md — a behavior\n // change agent-connector must not make silently.\n // - AUTO interop: when CLAUDE.md ALREADY imports `@AGENTS.md` (a line\n // outside code fences and outside our own blocks) or IS a symlink\n // resolving to AGENTS.md, the canonical block goes to AGENTS.md and\n // CLAUDE.md is NOT touched — the pre-existing user wiring is never\n // claimed as agent-connector-managed (prevents double-reads and writes\n // \"through\" a symlink). Order-independent: keyed off the import/symlink\n // existing, never off whether the AGENTS.md block was written yet.\n\n /** CLAUDE.md path: project `<projectDir>/CLAUDE.md`, user `~/.claude/CLAUDE.md`. */\n private claudeMdPath(ctx: InstallContext): string {\n return ctx.scope === \"project\"\n ? join(ctx.projectDir, \"CLAUDE.md\")\n : join(homedir(), \".claude\", \"CLAUDE.md\");\n }\n\n /** Sibling AGENTS.md at the same scope (agents-import / auto-interop target). */\n private agentsMdPath(ctx: InstallContext): string {\n return ctx.scope === \"project\"\n ? join(ctx.projectDir, \"AGENTS.md\")\n : join(homedir(), \".claude\", \"AGENTS.md\");\n }\n\n /**\n * True when the user ALREADY wired CLAUDE.md to AGENTS.md themselves:\n * an `@AGENTS.md` import line outside code fences and outside agent-connector\n * managed blocks (our own bridge must not count), or CLAUDE.md being a\n * symlink that resolves to the sibling AGENTS.md.\n */\n private claudeMdWiredToAgentsMd(ctx: InstallContext): boolean {\n const claudeMd = this.claudeMdPath(ctx);\n if (!existsSync(claudeMd)) return false;\n try {\n if (lstatSync(claudeMd).isSymbolicLink()) {\n const agentsMd = this.agentsMdPath(ctx);\n const resolved = realpathSync(claudeMd);\n const agentsResolved = existsSync(agentsMd) ? realpathSync(agentsMd) : agentsMd;\n if (resolved === agentsResolved) return true;\n }\n } catch {\n /* unreadable link — fall through to the content probe */\n }\n let raw: string;\n try {\n raw = readFileSync(claudeMd, \"utf8\");\n } catch {\n return false;\n }\n // Strip every agent-connector managed block first so OUR bridge import is\n // never mistaken for user wiring (idempotence across modes).\n const withoutBlocks = removeBlocksFromText(raw, { blockIdPrefix: \"\" }).text;\n const importRe = /(^|\\s)@(?:AGENTS\\.md|~\\/\\.claude\\/AGENTS\\.md)(\\s|$)/;\n return linesOutsideFences(withoutBlocks).some((line) => importRe.test(line));\n }\n\n /**\n * Effective memory mode for this install:\n * \"user-import\" — the user already wired CLAUDE.md→AGENTS.md (wins over\n * everything; we never write a duplicate or a second import);\n * \"agents-import\" — explicit opt-in via platforms[\"claude-code\"].memory.mode;\n * \"block\" — the default (managed block directly in CLAUDE.md).\n */\n private effectiveMemoryMode(ctx: InstallContext): \"block\" | \"agents-import\" | \"user-import\" {\n if (this.claudeMdWiredToAgentsMd(ctx)) return \"user-import\";\n return this.memoryOverride(ctx)?.mode === \"agents-import\" ? \"agents-import\" : \"block\";\n }\n\n protected override memoryTargets(ctx: InstallContext): MemoryTarget[] {\n // An explicit path override keeps the base resolution (escape hatch wins).\n if (this.memoryOverride(ctx)?.path) return super.memoryTargets(ctx);\n if (ctx.scope !== \"project\" && ctx.scope !== \"user\") return [];\n const mode = this.effectiveMemoryMode(ctx);\n if (mode === \"block\") {\n return [\n {\n path: this.claudeMdPath(ctx),\n reason:\n \"CLAUDE.md (Claude Code reads CLAUDE.md, not AGENTS.md; \" +\n \"HTML-comment markers are stripped from the model's context)\",\n },\n ];\n }\n return [\n {\n path: this.agentsMdPath(ctx),\n reason:\n mode === \"user-import\"\n ? \"AGENTS.md (CLAUDE.md already imports/symlinks it — user wiring respected)\"\n : \"AGENTS.md (agents-import mode; @AGENTS.md bridge managed in CLAUDE.md)\",\n },\n ];\n }\n\n override installMemory(ctx: InstallContext): ChangeRecord[] {\n const changes = super.installMemory(ctx);\n const { connector } = ctx;\n // Bridge management applies only when the generic path actually installed.\n if (connector.platforms[HOST]?.memory === false || (connector.memory ?? []).length === 0) {\n return changes;\n }\n if (ctx.scope !== \"project\" && ctx.scope !== \"user\") return changes;\n if (this.memoryOverride(ctx)?.path) return changes;\n\n const mode = this.effectiveMemoryMode(ctx);\n if (mode === \"user-import\") {\n changes.push({\n platform: this.id,\n action: \"skip\",\n path: this.claudeMdPath(ctx),\n detail:\n \"memory: CLAUDE.md already imports AGENTS.md; canonical block in AGENTS.md \" +\n \"suffices (pre-existing user import never claimed as managed)\",\n });\n return changes;\n }\n if (mode !== \"agents-import\") return changes;\n\n // agents-import: ensure the SHARED `@AGENTS.md` bridge block in CLAUDE.md.\n const claudeMd = this.claudeMdPath(ctx);\n const importLine = ctx.scope === \"project\" ? \"@AGENTS.md\" : \"@~/.claude/AGENTS.md\";\n const res = upsertManagedBlockFile(claudeMd, {\n blockId: CLAUDE_AGENTS_IMPORT_BLOCK_ID,\n connectorId: \"_shared\",\n content: importLine,\n notice:\n \"Managed by agent-connector (shared bridge). This import makes Claude Code read \" +\n \"AGENTS.md; it is removed automatically when the last agent-connector block \" +\n \"leaves AGENTS.md.\",\n force: ctx.force ?? false,\n dryRun: ctx.dryRun,\n });\n changes.push({\n platform: this.id,\n action: res.action,\n path: claudeMd,\n detail: `memory: ${res.detail} — @AGENTS.md import bridge (agents-import mode)`,\n });\n if (res.backupPath) {\n changes.push({\n platform: this.id,\n action: \"create\",\n path: res.backupPath,\n detail: \"backed up CLAUDE.md before destructive change\",\n });\n }\n if (res.action !== \"warn\" && !ctx.dryRun) {\n const ledger = loadMemoryLedger(connector.id);\n recordMemoryTarget(ledger, {\n platform: this.id,\n scope: ctx.scope,\n path: claudeMd,\n blockId: CLAUDE_AGENTS_IMPORT_BLOCK_ID,\n createdFile: res.createdFile,\n hash: res.hash,\n });\n saveMemoryLedger(connector.id, ledger);\n }\n return changes;\n }\n\n override uninstallMemory(ctx: InstallContext): ChangeRecord[] {\n // Capture bridge facts BEFORE super prunes this platform's ledger rows.\n const priorRows = loadMemoryLedger(ctx.connector.id).targets.filter(\n (t) => t.platform === this.id && t.blockId === CLAUDE_AGENTS_IMPORT_BLOCK_ID,\n );\n const changes = super.uninstallMemory(ctx);\n\n // Bridge candidates: the current-scope CLAUDE.md plus any CLAUDE.md the\n // ledger recorded a bridge in (scope drift between install and uninstall).\n const pairs = new Map<string, { agentsMd: string; createdFile: boolean }>();\n if (ctx.scope === \"project\" || ctx.scope === \"user\") {\n pairs.set(this.claudeMdPath(ctx), {\n agentsMd: this.agentsMdPath(ctx),\n createdFile: false,\n });\n }\n for (const row of priorRows) {\n const existing = pairs.get(row.path);\n pairs.set(row.path, {\n agentsMd: existing?.agentsMd ?? join(dirname(row.path), \"AGENTS.md\"),\n createdFile: (existing?.createdFile ?? false) || row.createdFile,\n });\n }\n for (const [claudeMd, { agentsMd, createdFile }] of pairs) {\n changes.push(...this.releaseAgentsImportBridge(ctx, claudeMd, agentsMd, createdFile));\n }\n return changes;\n }\n\n /**\n * Refcounted bridge release: remove the `_shared/claude-agents-import` block\n * from CLAUDE.md ONLY when the sibling AGENTS.md holds zero agent-connector\n * blocks from OTHER connectors (namespace-wide count, excluding this\n * connector's own blocks so the answer is identical on dry-run and real run).\n * A user-authored `@AGENTS.md` import (no markers) is NEVER touched.\n */\n private releaseAgentsImportBridge(\n ctx: InstallContext,\n claudeMd: string,\n agentsMd: string,\n createdFile: boolean,\n ): ChangeRecord[] {\n if (!existsSync(claudeMd)) return [];\n let raw: string;\n try {\n raw = readFileSync(claudeMd, \"utf8\");\n } catch {\n return [];\n }\n if (!listManagedBlocks(raw).some((b) => b.blockId === CLAUDE_AGENTS_IMPORT_BLOCK_ID)) {\n return []; // no managed bridge here (user wiring or block mode) — nothing to release\n }\n let remaining = 0;\n if (existsSync(agentsMd)) {\n try {\n remaining = listManagedBlocks(readFileSync(agentsMd, \"utf8\")).filter(\n (b) => !b.blockId.startsWith(`${ctx.connector.id}/`),\n ).length;\n } catch {\n remaining = 1; // unreadable → conservative: keep the bridge\n }\n }\n if (remaining > 0) {\n return [\n {\n platform: this.id,\n action: \"skip\",\n path: claudeMd,\n detail:\n `memory: @AGENTS.md import bridge retained — ${remaining} agent-connector ` +\n `block(s) from other connectors remain in ${agentsMd}`,\n },\n ];\n }\n return removeManagedBlocksFile(\n claudeMd,\n { blockId: CLAUDE_AGENTS_IMPORT_BLOCK_ID },\n { dryRun: ctx.dryRun, deleteFileIfCreated: createdFile },\n ).map((r) => ({\n platform: this.id,\n action: r.action,\n path: r.path,\n detail: `memory: ${r.detail}`,\n }));\n }\n\n /** True when a hook command references our home binary AND this connector id\n * (anchored so a shared-prefix id can't collide — see isHomeBinHookCommand). */\n private isOurCommand(command: string | undefined, ctx: InstallContext): boolean {\n return isHomeBinHookCommand(command, ctx.homeBinPath, ctx.connector.id);\n }\n\n // ── Diagnostics ──────────────────────────────────────────────────────────\n\n override getHealthChecks(ctx: InstallContext): readonly HealthCheck[] {\n const settingsPath = this.getHookConfigPath(ctx);\n const connectorId = ctx.connector.id;\n const homeBin = ctx.homeBinPath;\n const hookEvents = ctx.connector.hookEvents;\n // Native passthrough hooks count toward \"declares hooks\" ONLY when declared\n // for this platform (the serialized meta keeps the event-name keys, so this\n // works for doctor's handler-less meta-derived connectors too).\n const declaredHookCount =\n hookEvents.length +\n Object.keys(ctx.connector.platforms[HOST]?.nativeHooks ?? {}).length;\n const checks: HealthCheck[] = [\n {\n name: `${this.name}: settings.json present`,\n check: () => {\n // Same \"only assert what the connector declares\" rule as the\n // content-surface checks below: a hookless connector never writes\n // hooks into settings.json, so its absence is healthy, not a failure.\n if (declaredHookCount === 0) {\n return { status: \"OK\", detail: \"no hooks declared\" };\n }\n return existsSync(settingsPath)\n ? { status: \"OK\", detail: settingsPath }\n : { status: \"FAIL\", detail: `not found: ${settingsPath}` };\n },\n },\n {\n name: `${this.name}: hook command registered`,\n check: () => {\n if (declaredHookCount === 0) {\n return { status: \"OK\", detail: \"no hooks declared\" };\n }\n const settings = this.readJson<{ hooks?: Record<string, ClaudeHookEntry[]> }>(\n settingsPath,\n );\n if (!settings) return { status: \"FAIL\", detail: `cannot read ${settingsPath}` };\n const hooks = settings.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\" }\n : {\n status: \"FAIL\",\n detail: `no hook for ${connectorId} in ${settingsPath}`,\n };\n },\n },\n ];\n\n // Content-surface checks: only assert presence of the files this connector\n // declares (skip silently for surfaces it never asked for).\n for (const cmd of ctx.connector.commands) {\n const p = this.commandPath(ctx, cmd.name);\n checks.push({\n name: `${this.name}: command ${cmd.name} present`,\n check: () =>\n existsSync(p) ? { status: \"OK\", detail: p } : { status: \"FAIL\", detail: `not found: ${p}` },\n });\n }\n for (const skill of ctx.connector.skills) {\n const p = join(this.skillDir(ctx, skill.name), \"SKILL.md\");\n checks.push({\n name: `${this.name}: skill ${skill.name} present`,\n check: () =>\n existsSync(p) ? { status: \"OK\", detail: p } : { status: \"FAIL\", detail: `not found: ${p}` },\n });\n }\n for (const agent of ctx.connector.subagents) {\n const p = this.subagentPath(ctx, agent.name);\n checks.push({\n name: `${this.name}: subagent ${agent.name} present`,\n check: () =>\n existsSync(p) ? { status: \"OK\", detail: p } : { status: \"FAIL\", detail: `not found: ${p}` },\n });\n }\n\n // Statusline check: only assert it when the connector declares one AND it\n // is not disabled for this host. settings.json.statusLine.command must be OUR\n // home-bin statusline command (ok); present but not ours → drifted/skip-warn\n // (never our concern to fix); absent → missing.\n // Fire the check when the connector DECLARES a statusline (the live-config\n // doctor path) OR when the ownership ledger holds a statusLine row this\n // connector owns (the REGISTERED-connector path: connectorFromMeta can't\n // re-expose the render fn, so statusline comes back undefined — but the\n // ledger row proves the surface was wired). Mirrors uninstallStatusline,\n // which is also ledger-keyed; without this the wired statusLine has ZERO\n // doctor coverage in the registered path (configPatchDiagnostics excludes it).\n const statuslineLedgerOwned = ledgerEntriesOwnedBy(\n loadConfigPatchLedger(ctx.dataRoot),\n HOST,\n connectorId,\n ).some((e) => e.key === STATUSLINE_KEY);\n if (\n (ctx.connector.statusline != null || statuslineLedgerOwned) &&\n ctx.connector.platforms[HOST]?.statusline !== false\n ) {\n checks.push({\n name: `${this.name}: statusline wired`,\n check: () => {\n const settings = this.readJson<{ statusLine?: { command?: unknown } }>(settingsPath);\n const command = settings?.statusLine?.command;\n if (command === undefined) {\n return { status: \"FAIL\", detail: `statusLine not set in ${settingsPath}` };\n }\n if (\n typeof command === \"string\" &&\n isHomeBinStatuslineCommand(command, homeBin, connectorId)\n ) {\n return { status: \"OK\", detail: \"statusLine command present\" };\n }\n // Present but not ours — a non-AC statusLine we must never clobber.\n return {\n status: \"FAIL\",\n detail: `statusLine in ${settingsPath} is not agent-connector's (left untouched)`,\n };\n },\n });\n }\n return checks;\n }\n\n // ── Runtime: parse Claude stdin JSON → normalized event ──────────────────\n\n parseEvent(event: HookEventName, raw: unknown): NormalizedEvent {\n const input = (raw ?? {}) as ClaudeWireInput;\n const connectorId = typeof input.connector === \"string\" ? input.connector : \"\";\n const sessionId = extractSessionId(input);\n const projectDir = typeof input.cwd === \"string\" ? input.cwd : undefined;\n\n const base = {\n hostPlatform: HOST,\n connectorId,\n sessionId,\n raw,\n ...(projectDir !== undefined ? { projectDir } : {}),\n } as const;\n\n switch (event) {\n case \"PreToolUse\": {\n const ev: PreToolUseEvent = {\n ...base,\n toolName: input.tool_name ?? \"\",\n toolInput: input.tool_input ?? {},\n };\n return ev;\n }\n case \"PostToolUse\": {\n const ev: PostToolUseEvent = {\n ...base,\n toolName: input.tool_name ?? \"\",\n toolInput: input.tool_input ?? {},\n ...(toolResponseToString(input.tool_response) !== undefined\n ? { toolOutput: toolResponseToString(input.tool_response) }\n : {}),\n };\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 \"SessionEnd\": {\n const ev: SessionEndEvent = {\n ...base,\n ...(typeof input.reason === \"string\" ? { reason: input.reason } : {}),\n };\n return ev;\n }\n case \"UserPromptSubmit\": {\n const ev: UserPromptSubmitEvent = {\n ...base,\n prompt: typeof input.prompt === \"string\" ? input.prompt : \"\",\n };\n return ev;\n }\n case \"PreCompact\": {\n const ev: PreCompactEvent = {\n ...base,\n ...(input.trigger === \"auto\" || input.trigger === \"manual\"\n ? { trigger: input.trigger }\n : {}),\n };\n return ev;\n }\n case \"Stop\": {\n const ev: StopEvent = {\n ...base,\n ...(typeof input.stop_hook_active === \"boolean\"\n ? { stopHookActive: input.stop_hook_active }\n : {}),\n };\n return ev;\n }\n case \"Notification\": {\n const ev: NotificationEvent = {\n ...base,\n message: typeof input.message === \"string\" ? input.message : \"\",\n };\n return ev;\n }\n case \"PermissionRequest\": {\n const ev: PermissionRequestEvent = {\n ...base,\n toolName: input.tool_name ?? \"\",\n toolInput: input.tool_input ?? {},\n ...(Array.isArray(input.permission_suggestions)\n ? { permissionSuggestions: input.permission_suggestions }\n : {}),\n };\n return ev;\n }\n case \"PostToolUseFailure\": {\n const ev: PostToolUseFailureEvent = {\n ...base,\n toolName: input.tool_name ?? \"\",\n toolInput: input.tool_input ?? {},\n error: typeof input.error === \"string\" ? input.error : \"\",\n ...(typeof input.tool_use_id === \"string\"\n ? { toolUseId: input.tool_use_id }\n : {}),\n ...(typeof input.is_interrupt === \"boolean\"\n ? { isInterrupt: input.is_interrupt }\n : {}),\n ...(typeof input.duration_ms === \"number\"\n ? { durationMs: input.duration_ms }\n : {}),\n };\n return ev;\n }\n case \"SubagentStart\": {\n const ev: SubagentStartEvent = {\n ...base,\n ...(typeof input.agent_id === \"string\" ? { agentId: input.agent_id } : {}),\n ...(typeof input.agent_type === \"string\"\n ? { agentType: input.agent_type }\n : {}),\n };\n return ev;\n }\n case \"SubagentStop\": {\n // agent_id/agent_type stay optional — the SDK does not reliably\n // populate agent_type on SubagentStop (real-world quirk).\n const ev: SubagentStopEvent = {\n ...base,\n ...(typeof input.agent_id === \"string\" ? { agentId: input.agent_id } : {}),\n ...(typeof input.agent_type === \"string\"\n ? { agentType: input.agent_type }\n : {}),\n ...(typeof input.agent_transcript_path === \"string\"\n ? { agentTranscriptPath: input.agent_transcript_path }\n : {}),\n ...(typeof input.last_assistant_message === \"string\"\n ? { lastAssistantMessage: input.last_assistant_message }\n : {}),\n ...(typeof input.stop_hook_active === \"boolean\"\n ? { stopHookActive: input.stop_hook_active }\n : {}),\n };\n return ev;\n }\n default: {\n // Exhaustive guard — every HookEventName is handled above.\n const _never: never = event;\n throw new Error(`unsupported claude-code hook event: ${String(_never)}`);\n }\n }\n }\n\n // ── Runtime: normalized response → Claude native hook reply ──────────────\n\n formatReply(event: HookEventName, response: HookResponse): HookReply {\n const hookEventName = event as ClaudeHookEvent;\n const decision = response.decision ?? \"allow\";\n\n // PermissionRequest replies use Claude's nested decision{behavior} envelope\n // and are the ONE event where an EXPLICIT \"allow\" is an ACTIVE grant (it\n // suppresses the permission dialog) rather than passthrough:\n // allow → decision{behavior:\"allow\"} (+updatedInput when set);\n // Claude still enforces its own deny rules — an allow\n // never overrides a matching deny rule (host-enforced).\n // modify → an allow grant carrying updatedInput.\n // deny → decision{behavior:\"deny\", message} (shown to Claude).\n // ask/context/void → NO decision output: fall through to the native\n // dialog (the dialog IS the ask).\n if (event === \"PermissionRequest\") {\n if (response.decision === \"deny\") {\n return this.stdout({\n hookSpecificOutput: {\n hookEventName,\n decision: {\n behavior: \"deny\",\n message: response.reason ?? \"Blocked by hook\",\n },\n },\n });\n }\n if (\n response.decision === \"allow\" ||\n (response.decision === \"modify\" && response.updatedInput)\n ) {\n return this.stdout({\n hookSpecificOutput: {\n hookEventName,\n decision: {\n behavior: \"allow\",\n ...(response.updatedInput\n ? { updatedInput: response.updatedInput }\n : {}),\n },\n },\n });\n }\n return { exitCode: 0 };\n }\n\n // PostToolUseFailure (feedback beside the error) and SubagentStart (context\n // injected at the start of the SUBAGENT's conversation) are observe/context-\n // only on Claude: \"context\" emits additionalContext, and a \"deny\" DEGRADES\n // to the same shape carrying the reason (the tool already failed / the\n // spawn is not blockable). Everything else passes through.\n if (event === \"PostToolUseFailure\" || event === \"SubagentStart\") {\n const context =\n decision === \"context\"\n ? response.additionalContext\n : decision === \"deny\"\n ? response.reason ?? response.additionalContext\n : undefined;\n if (context) {\n return this.stdout({\n hookSpecificOutput: { hookEventName, additionalContext: context },\n });\n }\n return { exitCode: 0 };\n }\n\n // deny → block the action with a reason (exit 0; JSON carries the decision).\n // Claude's deny shape is EVENT-SPECIFIC: PreToolUse uses\n // hookSpecificOutput.permissionDecision, but Stop / SubagentStop /\n // UserPromptSubmit / PostToolUse honor only the TOP-LEVEL\n // {\"decision\":\"block\",\"reason\"} — rendering those as permissionDecision is\n // silently ignored by Claude (found porting oh-my-claudecode: its ralph\n // persistence loop denies the Stop event, which never blocked through the\n // old shape). A SubagentStop block keeps the subagent running with `reason`\n // as its next instruction (Stop semantics).\n if (decision === \"deny\") {\n if (\n event === \"Stop\" ||\n event === \"SubagentStop\" ||\n event === \"UserPromptSubmit\" ||\n event === \"PostToolUse\"\n ) {\n return this.stdout({\n decision: \"block\",\n reason: response.reason ?? \"Blocked by hook\",\n });\n }\n return this.stdout({\n hookSpecificOutput: {\n hookEventName,\n permissionDecision: \"deny\",\n permissionDecisionReason: response.reason ?? \"Blocked by hook\",\n },\n });\n }\n\n // ask → prompt the user to confirm.\n if (decision === \"ask\") {\n return this.stdout({\n hookSpecificOutput: {\n hookEventName,\n permissionDecision: \"ask\",\n permissionDecisionReason:\n response.reason ?? \"Confirmation required by hook\",\n },\n });\n }\n\n // modify → rewrite PreToolUse input (only where Claude supports it).\n if (decision === \"modify\") {\n if (event === \"PreToolUse\" && response.updatedInput) {\n return this.stdout({\n hookSpecificOutput: { hookEventName, updatedInput: response.updatedInput },\n });\n }\n // Output rewrite is unsupported on Claude; fall through to allow.\n }\n\n // context → inject soft guidance (also the SessionStart context path).\n if (decision === \"context\" && response.additionalContext) {\n return this.stdout({\n hookSpecificOutput: { hookEventName, additionalContext: response.additionalContext },\n });\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\n// ─────────────────────────────────────────────────────────────────────────\n// configPatch: sensitive-key denylist + JSON leaf-path helpers\n// ─────────────────────────────────────────────────────────────────────────\n\n/**\n * SENSITIVE-KEY DENYLIST (claude-code, v1) — THE documented list. configPatch\n * targeting any key below is HARD-REFUSED (warn ChangeRecord, never applied;\n * no override flag in v1). Rationale: configPatch writes bare host keys with\n * no inherent attribution, and these keys are security-relevant — permission\n * grants, tool allowlists, credential/auth helpers, login pinning, and any\n * env var that can reroute credentials or traffic. The OMC case\n * `env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS` passes; credential rerouting and\n * self-granted permissions do not. Reviewed whenever the host matrix updates.\n *\n * permissions, permissions.* — self-granted permission rules\n * allowedTools / disallowedTools (.*) — tool allowlist tampering\n * apiKey* (e.g. apiKeyHelper) — credential helpers\n * awsAuthRefresh / awsCredentialExport — AWS credential plumbing\n * forceLoginMethod / forceLoginOrgUUID — login/org pinning\n * otelHeadersHelper — telemetry-header (token) helper\n * hooks*, mcpServers* (+ enable/enabled/disabledMcpjsonServers)\n * — refused upstream by the\n * agent-connector NAMESPACE guard\n * env.ANTHROPIC_* — API key / base-URL rerouting\n * env.AWS_* — AWS credentials\n * env.*_PROXY — traffic interception\n * env.*TOKEN* / env.*KEY* / env.*SECRET* — generic credential patterns\n */\nconst SENSITIVE_KEY_RULES: ReadonlyArray<{ re: RegExp; label: string }> = [\n { re: /^permissions(\\.|$)/, label: \"permissions\" },\n { re: /^allowedTools(\\.|$)/, label: \"allowedTools\" },\n { re: /^disallowedTools(\\.|$)/, label: \"disallowedTools\" },\n { re: /^apiKey/i, label: \"apiKey*\" },\n { re: /^awsAuthRefresh$/, label: \"awsAuthRefresh\" },\n { re: /^awsCredentialExport$/, label: \"awsCredentialExport\" },\n { re: /^forceLoginMethod$/, label: \"forceLoginMethod\" },\n { re: /^forceLoginOrgUUID$/, label: \"forceLoginOrgUUID\" },\n { re: /^otelHeadersHelper$/, label: \"otelHeadersHelper\" },\n { re: /^env\\.ANTHROPIC_/, label: \"env.ANTHROPIC_*\" },\n { re: /^env\\.AWS_/, label: \"env.AWS_*\" },\n { re: /^env\\.[^.]*_PROXY(\\.|$)/i, label: \"env.*_PROXY\" },\n { re: /^env\\.[^.]*TOKEN/i, label: \"env.*TOKEN*\" },\n { re: /^env\\.[^.]*KEY/i, label: \"env.*KEY*\" },\n { re: /^env\\.[^.]*SECRET/i, label: \"env.*SECRET*\" },\n];\n\n/**\n * The matched denylist pattern label when `key` is sensitive on claude-code,\n * else null. Exported so tests and docs stay pinned to the real list.\n */\nexport function claudeSensitiveKeyViolation(key: string): string | null {\n for (const rule of SENSITIVE_KEY_RULES) {\n if (rule.re.test(key)) return rule.label;\n }\n return null;\n}\n\n/** Result of looking up a dotted leaf path in a parsed JSON object. */\ntype JsonLeafLookup =\n | { kind: \"absent\" }\n | { kind: \"present\"; value: JsonValue }\n | { kind: \"blocked\"; atPath: string };\n\n/**\n * Walk `segments` (a validated dotted leaf path) through `root`. \"blocked\"\n * reports the first intermediate that exists but is not a plain object —\n * the skip-warn case (we never replace a non-object intermediate).\n */\nfunction readJsonLeaf(root: Record<string, unknown>, segments: string[]): JsonLeafLookup {\n let node: Record<string, unknown> = root;\n for (let i = 0; i < segments.length - 1; i++) {\n const next = node[segments[i]!];\n if (next === undefined) return { kind: \"absent\" };\n if (next === null || typeof next !== \"object\" || Array.isArray(next)) {\n return { kind: \"blocked\", atPath: segments.slice(0, i + 1).join(\".\") };\n }\n node = next as Record<string, unknown>;\n }\n const leaf = node[segments[segments.length - 1]!];\n if (leaf === undefined) return { kind: \"absent\" };\n return { kind: \"present\", value: leaf as JsonValue };\n}\n\n/**\n * Write `value` at the leaf, creating ONLY absent intermediate objects along\n * the way (callers must have verified the path is not blocked).\n */\nfunction writeJsonLeaf(\n root: Record<string, unknown>,\n segments: string[],\n value: JsonValue,\n): void {\n let node: Record<string, unknown> = root;\n for (let i = 0; i < segments.length - 1; i++) {\n const seg = segments[i]!;\n const next = node[seg];\n if (next === undefined) {\n const created: Record<string, unknown> = {};\n node[seg] = created;\n node = created;\n } else {\n node = next as Record<string, unknown>;\n }\n }\n node[segments[segments.length - 1]!] = value;\n}\n\n/**\n * Delete the leaf key only. Intermediate objects — even ones we created — are\n * deliberately left in place (harmless; pruning risks collateral).\n */\nfunction deleteJsonLeaf(root: Record<string, unknown>, segments: string[]): void {\n let node: Record<string, unknown> = root;\n for (let i = 0; i < segments.length - 1; i++) {\n const next = node[segments[i]!];\n if (next === null || typeof next !== \"object\" || Array.isArray(next)) return;\n node = next as Record<string, unknown>;\n }\n delete node[segments[segments.length - 1]!];\n}\n\n/** Claude Code native interpolation token: `${env:VAR}` → `${VAR}`. */\nfunction claudeEnvToken(name: string): string {\n return `\\${${name}}`;\n}\n\nfunction normalizeSessionSource(source: string | undefined): SessionStartEvent[\"source\"] {\n switch (source) {\n case \"compact\":\n return \"compact\";\n case \"resume\":\n return \"resume\";\n case \"clear\":\n return \"clear\";\n default:\n return \"startup\";\n }\n}\n\nexport const adapter = new ClaudeCodeAdapter();\nexport default adapter;\n","/**\n * adapters/claude-code/wire — Claude Code hook wire protocol.\n *\n * Claude Code pipes a JSON object to a hook command on stdin and reads a JSON\n * object (or empty) from stdout, interpreting the exit code as well. This module\n * captures the exact stdin shape and the canonical reply shape so the adapter's\n * parse/format methods are a single source of truth.\n *\n * Stdin (documented Claude Code hook input):\n * {\n * session_id, transcript_path, cwd, hook_event_name,\n * tool_name, tool_input, tool_response, // tool events\n * permission_suggestions, // PermissionRequest\n * tool_use_id, error, is_interrupt, duration_ms, // PostToolUseFailure\n * agent_id, agent_type, // SubagentStart/Stop\n * agent_transcript_path, last_assistant_message, // SubagentStop\n * source, // SessionStart\n * reason, // SessionEnd\n * prompt, // UserPromptSubmit\n * trigger, // PreCompact\n * stop_hook_active, // Stop / SubagentStop\n * message // Notification\n * }\n *\n * Stdout (canonical reply): a `hookSpecificOutput` object keyed by\n * `hookEventName`, carrying `permissionDecision` (allow|deny|ask) +\n * `permissionDecisionReason`, `additionalContext`, and (PreToolUse)\n * `updatedInput`; PermissionRequest instead takes a nested\n * `decision: { behavior: \"allow\"|\"deny\", ... }`; Stop-class blocks\n * (Stop / SubagentStop / UserPromptSubmit / PostToolUse) take the TOP-LEVEL\n * `{\"decision\":\"block\",\"reason\"}`. Exit 0 = proceed; the JSON refines the\n * decision.\n */\n\n/** Canonical Claude Code hook event names (the values of `hook_event_name`). */\nexport const CLAUDE_HOOK_EVENTS = [\n \"PreToolUse\",\n \"PostToolUse\",\n \"PreCompact\",\n \"SessionStart\",\n \"SessionEnd\",\n \"UserPromptSubmit\",\n \"Stop\",\n \"Notification\",\n \"PermissionRequest\",\n \"PostToolUseFailure\",\n \"SubagentStart\",\n \"SubagentStop\",\n] as const;\n\nexport type ClaudeHookEvent = (typeof CLAUDE_HOOK_EVENTS)[number];\n\n/**\n * Raw Claude Code hook stdin payload. Every field is optional — a given event\n * only populates the subset relevant to it. `connector` is NOT a Claude field;\n * it is threaded in by the universal entrypoint so parseEvent can recover the\n * connector id (the home binary passes `--connector <id>` and may inject it).\n */\nexport interface ClaudeWireInput {\n session_id?: string;\n transcript_path?: string;\n cwd?: string;\n hook_event_name?: string;\n\n // tool events\n tool_name?: string;\n tool_input?: Record<string, unknown>;\n /** PostToolUse result payload (string or structured). */\n tool_response?: unknown;\n\n // PermissionRequest — permission-update entries the dialog would offer.\n // NOTE: the docs explicitly state PermissionRequest has NO tool_use_id.\n permission_suggestions?: unknown[];\n\n // PostToolUseFailure\n tool_use_id?: string;\n error?: string;\n is_interrupt?: boolean;\n duration_ms?: number;\n\n // SubagentStart / SubagentStop — agent_type is unreliable on SubagentStop\n // (the SDK may not populate it); treat both as optional everywhere.\n agent_id?: string;\n agent_type?: string;\n // SubagentStop — the subagent's OWN transcript (transcript_path stays the\n // parent session's) + the text of its final response.\n agent_transcript_path?: string;\n last_assistant_message?: string;\n\n // SessionStart\n source?: string;\n // SessionEnd\n reason?: string;\n // UserPromptSubmit\n prompt?: string;\n // PreCompact\n trigger?: string;\n // Stop / SubagentStop\n stop_hook_active?: boolean;\n // Notification\n message?: string;\n\n /** Injected by the entrypoint so the runtime knows which connector to dispatch. */\n connector?: string;\n}\n\n/**\n * Extract a stable session id from a Claude wire payload.\n * Priority mirrors the proven adapter: transcript UUID > session_id > \"\".\n * (The framework's normalized event uses \"\" when no id is available, per\n * core/types BaseEvent.sessionId docstring — no ppid fabrication here.)\n */\nexport function extractSessionId(input: ClaudeWireInput): string {\n if (typeof input.transcript_path === \"string\") {\n const m = input.transcript_path.match(/([a-f0-9-]{36})\\.jsonl$/);\n if (m && m[1]) return m[1];\n }\n if (typeof input.session_id === \"string\" && input.session_id !== \"\") {\n return input.session_id;\n }\n return \"\";\n}\n\n/** Coerce a Claude PostToolUse `tool_response` into a string for the normalized event. */\nexport function toolResponseToString(value: unknown): string | undefined {\n if (value == null) return undefined;\n if (typeof value === \"string\") return value;\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiBA,SAAS,cAAc,YAAY,WAAW,cAAc,oBAAoB;AAChF,SAAS,eAAe;AACxB,SAAS,UAAU,SAAS,YAAY;;;AC6FjC,SAAS,iBAAiB,OAAgC;AAC/D,MAAI,OAAO,MAAM,oBAAoB,UAAU;AAC7C,UAAM,IAAI,MAAM,gBAAgB,MAAM,yBAAyB;AAC/D,QAAI,KAAK,EAAE,CAAC,EAAG,QAAO,EAAE,CAAC;AAAA,EAC3B;AACA,MAAI,OAAO,MAAM,eAAe,YAAY,MAAM,eAAe,IAAI;AACnE,WAAO,MAAM;AAAA,EACf;AACA,SAAO;AACT;AAGO,SAAS,qBAAqB,OAAoC;AACvE,MAAI,SAAS,KAAM,QAAO;AAC1B,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,MAAI;AACF,WAAO,KAAK,UAAU,KAAK;AAAA,EAC7B,QAAQ;AACN,WAAO,OAAO,KAAK;AAAA,EACrB;AACF;;;ADhCA,IAAM,OAAmB;AACzB,IAAM,eAAe;AAQrB,IAAM,iBAAiB;AASvB,IAAM,gCAAgC;AAqC/B,IAAM,oBAAN,cAAgC,YAA+B;AAAA,EAC3D,KAAiB;AAAA,EACjB,O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