@ken-jo/agent-connector 0.2.0 → 0.3.0

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 (84) hide show
  1. package/README.md +9 -2
  2. package/dist/chunk-44HUXXC6.js +284 -0
  3. package/dist/chunk-44HUXXC6.js.map +1 -0
  4. package/dist/{chunk-AKJGNTU3.js → chunk-DS3LUFVN.js} +21 -21
  5. package/dist/chunk-DS3LUFVN.js.map +1 -0
  6. package/dist/{chunk-KHO5WNTP.js → chunk-KVAAFYRR.js} +18 -2
  7. package/dist/chunk-KVAAFYRR.js.map +1 -0
  8. package/dist/{chunk-O2SBA5KR.js → chunk-NJU275US.js} +9 -9
  9. package/dist/{chunk-WCETQWWK.js → chunk-OP4KBXUO.js} +1 -17
  10. package/dist/chunk-OP4KBXUO.js.map +1 -0
  11. package/dist/chunk-QADSG2JY.js +1989 -0
  12. package/dist/chunk-QADSG2JY.js.map +1 -0
  13. package/dist/{package-O63K4S7T.js → chunk-WNREHWKL.js} +20 -114
  14. package/dist/chunk-WNREHWKL.js.map +1 -0
  15. package/dist/{chunk-4ML7SZ7R.js → chunk-ZAM4M7LI.js} +7 -7
  16. package/dist/cli/sdk.js +1 -1
  17. package/dist/cli.js +1 -1
  18. package/dist/{detect-JK7T46N6.js → detect-MNDHGLSV.js} +3 -3
  19. package/dist/{doctor-62BHIXOR.js → doctor-N5KZDD55.js} +35 -5
  20. package/dist/doctor-N5KZDD55.js.map +1 -0
  21. package/dist/{hook-AC7APC66.js → hook-7LUOKIXH.js} +6 -6
  22. package/dist/{install-DMW2C7SV.js → install-TQTT4F3I.js} +31 -7
  23. package/dist/install-TQTT4F3I.js.map +1 -0
  24. package/dist/kilo-PKAJCWPX.js +852 -0
  25. package/dist/kilo-PKAJCWPX.js.map +1 -0
  26. package/dist/{kilo-cli-2RNODHWY.js → kilo-cli-QWUVXG2O.js} +157 -6
  27. package/dist/kilo-cli-QWUVXG2O.js.map +1 -0
  28. package/dist/{kimi-Q5RG7CYT.js → kimi-EVD7YKXS.js} +79 -4
  29. package/dist/kimi-EVD7YKXS.js.map +1 -0
  30. package/dist/{kiro-EKTRW424.js → kiro-UQRY6EIO.js} +68 -3
  31. package/dist/kiro-UQRY6EIO.js.map +1 -0
  32. package/dist/{leaderboard-R5HRJHNU.js → leaderboard-MUJ7DURM.js} +2 -2
  33. package/dist/package-SYPA5POO.js +130 -0
  34. package/dist/package-SYPA5POO.js.map +1 -0
  35. package/dist/{pi-SJPIL4VE.js → pi-WMTUX6ES.js} +102 -23
  36. package/dist/pi-WMTUX6ES.js.map +1 -0
  37. package/dist/{qwen-code-IFCM6BJY.js → qwen-code-MRRIUQ3P.js} +78 -5
  38. package/dist/qwen-code-MRRIUQ3P.js.map +1 -0
  39. package/dist/runtime/index.js +4 -4
  40. package/dist/{serve-LFOUSZAD.js → serve-XJOSA7BY.js} +6 -6
  41. package/dist/{status-M7JLZVLC.js → status-DYSS6BOR.js} +16 -7
  42. package/dist/status-DYSS6BOR.js.map +1 -0
  43. package/dist/{telemetry-3NVEXPYX.js → telemetry-IJ4GP2Q3.js} +2 -2
  44. package/dist/uninstall-3DXIBRCV.js +162 -0
  45. package/dist/uninstall-3DXIBRCV.js.map +1 -0
  46. package/dist/{upgrade-76BQZBMA.js → upgrade-GJEB3ITY.js} +26 -8
  47. package/dist/upgrade-GJEB3ITY.js.map +1 -0
  48. package/dist/{usage-G3GSCX23.js → usage-2BJLM3GJ.js} +2 -2
  49. package/dist/{usage-event-QUTMNBS5.js → usage-event-472X3DOY.js} +5 -5
  50. package/dist/{warp-LLOSXR7A.js → warp-X6MB67NT.js} +81 -3
  51. package/dist/warp-X6MB67NT.js.map +1 -0
  52. package/dist/{zed-HYOITK7F.js → zed-NTCYW4V2.js} +68 -3
  53. package/dist/zed-NTCYW4V2.js.map +1 -0
  54. package/package.json +1 -1
  55. package/dist/chunk-AKJGNTU3.js.map +0 -1
  56. package/dist/chunk-KHO5WNTP.js.map +0 -1
  57. package/dist/chunk-WCETQWWK.js.map +0 -1
  58. package/dist/chunk-Z2BVYKZL.js +0 -369
  59. package/dist/chunk-Z2BVYKZL.js.map +0 -1
  60. package/dist/doctor-62BHIXOR.js.map +0 -1
  61. package/dist/install-DMW2C7SV.js.map +0 -1
  62. package/dist/kilo-ISR5FBBJ.js +0 -408
  63. package/dist/kilo-ISR5FBBJ.js.map +0 -1
  64. package/dist/kilo-cli-2RNODHWY.js.map +0 -1
  65. package/dist/kimi-Q5RG7CYT.js.map +0 -1
  66. package/dist/kiro-EKTRW424.js.map +0 -1
  67. package/dist/package-O63K4S7T.js.map +0 -1
  68. package/dist/pi-SJPIL4VE.js.map +0 -1
  69. package/dist/qwen-code-IFCM6BJY.js.map +0 -1
  70. package/dist/status-M7JLZVLC.js.map +0 -1
  71. package/dist/uninstall-H6FGMIHN.js +0 -73
  72. package/dist/uninstall-H6FGMIHN.js.map +0 -1
  73. package/dist/upgrade-76BQZBMA.js.map +0 -1
  74. package/dist/warp-LLOSXR7A.js.map +0 -1
  75. package/dist/zed-HYOITK7F.js.map +0 -1
  76. /package/dist/{chunk-O2SBA5KR.js.map → chunk-NJU275US.js.map} +0 -0
  77. /package/dist/{chunk-4ML7SZ7R.js.map → chunk-ZAM4M7LI.js.map} +0 -0
  78. /package/dist/{detect-JK7T46N6.js.map → detect-MNDHGLSV.js.map} +0 -0
  79. /package/dist/{hook-AC7APC66.js.map → hook-7LUOKIXH.js.map} +0 -0
  80. /package/dist/{leaderboard-R5HRJHNU.js.map → leaderboard-MUJ7DURM.js.map} +0 -0
  81. /package/dist/{serve-LFOUSZAD.js.map → serve-XJOSA7BY.js.map} +0 -0
  82. /package/dist/{telemetry-3NVEXPYX.js.map → telemetry-IJ4GP2Q3.js.map} +0 -0
  83. /package/dist/{usage-G3GSCX23.js.map → usage-2BJLM3GJ.js.map} +0 -0
  84. /package/dist/{usage-event-QUTMNBS5.js.map → usage-event-472X3DOY.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/adapters/kilo-cli/index.ts"],"sourcesContent":["/**\n * adapters/kilo-cli — Kilo CLI platform adapter for agent-connector.\n *\n * The Kilo CLI (the `kilo` binary) is a **live-confirmed OpenCode fork**: a\n * SQLite-backed command-line agent (storage `~/.local/share/kilo/kilo.db`) that\n * loads `@kilocode/plugin` modules. It is DISTINCT from the Kilo Code VS Code\n * extension (adapter id \"kilo\", a Roo/Cline fork) — the two products carry\n * different platformIds so their config and usage never merge.\n *\n * Paradigm — **ts-plugin** (mirrors the OpenCode adapter):\n * The fork has no JSON hook table. Instead it loads JS/TS plugin modules whose\n * default export is a `@kilocode/plugin` PluginModule:\n * { id?, server: async (input) => Hooks }\n * where the returned `Hooks` object is keyed by the fork's event names\n * (\"tool.execute.before\", \"tool.execute.after\", a session/system event). The\n * `server` factory runs in-process inside Kilo and is handed mutable args/output\n * objects; it throws to block a tool call.\n *\n * Why we BRIDGE instead of importing handlers (identical rationale to OpenCode):\n * the connector's hook handlers are arbitrary developer code we must not import\n * into Kilo's runtime (wrong cwd, wrong deps, version skew). So instead of\n * importing handlers we synthesize a tiny, fully self-contained ESM plugin\n * module that imports NOTHING from agent-connector and, on each hook firing,\n * shells out to the ONE stable home binary's universal entrypoint\n * <homeBin> hook kilo-cli <event> --connector <id>\n * feeding the event payload on stdin and JSON.parsing the normalized\n * HookResponse back from stdout. Fail-open: any bridge error → no-op.\n *\n * Registration (the key difference from OpenCode):\n * OpenCode auto-discovers every file in its plugin dir, so writing the file is\n * enough. This fork does NOT auto-discover by directory — it reads an explicit\n * `plugin` ARRAY in kilo.jsonc (module file paths). So installHooks must BOTH\n * synthesize the module AND register its path in that `plugin` array; uninstall\n * reverses both.\n *\n * Plugin module location (project | user):\n * user → ~/.config/kilo/plugin/<id>.js\n * project → <projectDir>/.kilo/plugin/<id>.js\n *\n * MCP config (the CLI's new-gen dialect — already correct, KEPT verbatim):\n * - user scope → ~/.config/kilo/kilo.jsonc\n * - project scope → <projectDir>/.kilo/kilo.jsonc (project overrides global)\n * Both are JSON/JSONC; we write plain JSON, which is valid JSONC. The root key\n * is \"mcp\" (NOT the extension's \"mcpServers\").\n *\n * Server entry shape (mirrors OpenCode's new-gen dialect):\n * - stdio → { type: \"local\", command: [exe, ...args], environment: {...} }\n * NOTE the command is a single ARRAY (exe + args together), unlike\n * Claude/Cursor's scalar `command` + `args[]` split.\n * - remote → { type: \"remote\", url }\n *\n * The Kilo CLI documents no native `${env:VAR}` interpolation token, so env/url\n * refs are resolved to literals at install time (the no-native-token path).\n *\n * Content surfaces: the Kilo CLI exposes no confirmed writable command/skill/\n * subagent dir (the `.kilocode/` tree belongs to the VS Code extension, served\n * by the \"kilo\" adapter), so those inherit the BaseAdapter warn/skip.\n *\n * Capability degradations (documented, never thrown):\n * - The fork has no \"ask\" gate. A decision of \"ask\" degrades to a block (throw\n * with the reason) in tool.execute.before — the safe direction.\n */\n\nimport {\n chmodSync,\n existsSync,\n mkdirSync,\n readFileSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nimport { BaseAdapter } from \"../base.js\";\nimport type {\n Adapter,\n GeneratedPluginFile,\n HookReply,\n InstallContext,\n MemoryTarget,\n NormalizedEvent,\n} from \"../spi.js\";\nimport type {\n ChangeRecord,\n DetectedPlatform,\n HealthCheck,\n HookEventName,\n HookParadigm,\n HookResponse,\n PlatformCapabilities,\n PlatformId,\n PostToolUseEvent,\n PreToolUseEvent,\n ServerDef,\n SessionStartEvent,\n Transport,\n} from \"../../core/types.js\";\nimport { resolveEnvRefsDeep } from \"../../core/interpolate.js\";\nimport {\n buildServeWrapperCommand,\n shouldWrapForTelemetry,\n} from \"../../core/spawn.js\";\n\nconst HOST: PlatformId = \"kilo-cli\";\n/** New-generation root key for MCP servers — \"mcp\", not the extension's \"mcpServers\". */\nconst MCP_ROOT_KEY = \"mcp\";\n/** kilo.jsonc array of plugin module paths the fork loads (NOT auto-discovery). */\nconst PLUGIN_ARRAY_KEY = \"plugin\";\n/** New-generation config filename (JSON/JSONC). */\nconst CONFIG_FILE = \"kilo.jsonc\";\n/** The Kilo CLI's SQLite session store — a CLI-exclusive detection marker. */\nconst CLI_DB_RELPATH = [\".local\", \"share\", \"kilo\", \"kilo.db\"] as const;\n\n/**\n * Canonical → Kilo (OpenCode-fork) event name map. A connector hook event is\n * only emitted by the generated plugin when it appears here AND is declared by\n * the connector.\n *\n * The fork inherits OpenCode's tool-execution events; like OpenCode it has no\n * real SessionStart hook, so SessionStart maps to the same system-prompt\n * transform surrogate (the verified context-injection point) — we inject\n * additionalContext into the system prompt there.\n */\nconst EVENT_TO_KILO: Partial<Record<HookEventName, string>> = {\n PreToolUse: \"tool.execute.before\",\n PostToolUse: \"tool.execute.after\",\n SessionStart: \"experimental.chat.system.transform\",\n};\n\n/** Raw payload the generated plugin posts to the universal hook entrypoint. */\ninterface KiloBridgePayload {\n toolName?: string;\n toolInput?: Record<string, unknown>;\n toolOutput?: string;\n isError?: boolean;\n sessionId?: string;\n projectDir?: string;\n}\n\n/**\n * Native MCP server entry shapes the Kilo CLI's new-gen config accepts under\n * `mcp`. QUIRK: a local (stdio) server keys its whole invocation as\n * `command: [...]` — a single array of [executable, ...args] — and env as\n * `environment`.\n */\ninterface KiloLocalServer {\n type: \"local\";\n command: string[];\n environment?: Record<string, string>;\n}\ninterface KiloRemoteServer {\n type: \"remote\";\n url: string;\n}\n\nexport class KiloCliAdapter extends BaseAdapter implements Adapter {\n readonly id: PlatformId = HOST;\n readonly name = \"Kilo CLI\";\n readonly paradigm: HookParadigm = \"ts-plugin\";\n\n readonly capabilities: PlatformCapabilities = {\n // Memory surface: AGENTS.md-first managed block (project <projectDir>/AGENTS.md\n // via the base default; user scope → ~/.kilocode/rules/agent-connector.md below).\n supportsMemory: true,\n // Matches the OpenCode capability surface — the fork inherits its plugin\n // event model.\n preToolUse: true,\n postToolUse: true,\n // The fork's compaction hook is experimental and not wired here.\n preCompact: false,\n sessionStart: true,\n sessionEnd: false,\n userPromptSubmit: false,\n stop: false,\n notification: false,\n // Newer events: like OpenCode, the fork ships a decision-capable\n // `permission.ask` plugin hook upstream, but it is NOT wired here (E1\n // keeps this adapter degrade-only); subagents run as child sessions (bus\n // events only) and tool failure is merged into tool.execute.after /\n // session.error. permissionRequest / postToolUseFailure / subagentStart /\n // subagentStop stay unset — the generated bridge never references them and\n // install reports them as \"unsupported here\".\n // tool.execute.before mutates output.args → input rewrite supported.\n canModifyArgs: true,\n // tool.execute.after mutates output.output → output rewrite supported.\n canModifyOutput: true,\n // injected via the system-prompt transform at session start.\n canInjectSessionContext: true,\n // The Kilo CLI registers stdio (local), SSE, and Streamable HTTP MCP servers.\n transports: [\"stdio\", \"sse\", \"http\"],\n // No confirmed CLI content surface — these inherit the BaseAdapter warn/skip.\n supportsCommands: false,\n supportsSkills: false,\n supportsSubagents: false,\n };\n\n // ── Detection ────────────────────────────────────────────────────────────\n\n detectInstalled(projectDir: string): DetectedPlatform {\n const userDir = join(homedir(), \".config\", \"kilo\");\n const userConfig = join(userDir, CONFIG_FILE);\n const projectConfig = join(projectDir, \".kilo\", CONFIG_FILE);\n // The SQLite session DB is a CLI-exclusive marker (the VS Code extension\n // never writes it), so it disambiguates the CLI from the \"kilo\" extension\n // even when neither writes a kilo.jsonc yet.\n const cliDb = join(homedir(), ...CLI_DB_RELPATH);\n const userInstalled = existsSync(userDir) || existsSync(cliDb);\n const projInstalled = existsSync(projectConfig);\n const installed = userInstalled || projInstalled;\n // Report the scope/path/reason for the marker that actually matched, so a\n // project-only install isn't misreported as a (non-existent) user install.\n const scope = projInstalled && !userInstalled ? \"project\" : \"user\";\n const configPath = scope === \"project\" ? projectConfig : userConfig;\n return {\n id: this.id,\n name: this.name,\n installed,\n paradigm: this.paradigm,\n capabilities: this.capabilities,\n configPath,\n scope,\n reason: installed\n ? scope === \"project\"\n ? `found project Kilo CLI config at ${projectConfig}`\n : existsSync(cliDb)\n ? `found Kilo CLI session store at ${cliDb}`\n : `found Kilo CLI config under ${userDir}`\n : `no Kilo CLI config at ${userDir} or session store at ${cliDb}`,\n confidence: installed ? \"high\" : \"low\",\n };\n }\n\n // ── Memory surface: global rules dir at user scope ──────────────────────\n // Project scope stays on the AGENTS.md base default. User scope targets a\n // dedicated agent-connector.md in the legacy-compatible ~/.kilocode/rules/\n // dir (always loaded; avoids JSONC `instructions` edits in kilo.jsonc; the\n // AC-created file is cleanly deletable on uninstall). Shared backend with\n // the kilo extension — the convergent write dedupes via the content hash.\n protected override memoryTargets(ctx: InstallContext): MemoryTarget[] {\n if (this.memoryOverride(ctx)?.path || ctx.scope !== \"user\") {\n return super.memoryTargets(ctx);\n }\n return [\n {\n path: join(homedir(), \".kilocode\", \"rules\", \"agent-connector.md\"),\n reason: \"kilo global rules dir (~/.kilocode/rules; agent-connector-owned file)\",\n },\n ];\n }\n\n // ── Native paths ─────────────────────────────────────────────────────────\n\n getConfigDir(ctx: InstallContext): string {\n return ctx.scope === \"project\"\n ? join(ctx.projectDir, \".kilo\")\n : join(homedir(), \".config\", \"kilo\");\n }\n\n getServerConfigPath(ctx: InstallContext): string {\n return join(this.getConfigDir(ctx), CONFIG_FILE);\n }\n\n /**\n * For ts-plugin hosts the \"hook config path\" is the generated plugin FILE.\n * Unlike OpenCode, writing the file is NOT sufficient: the fork loads only the\n * module paths listed in kilo.jsonc's `plugin` array, so installHooks also\n * registers this path there.\n */\n getHookConfigPath(ctx: InstallContext): string {\n return join(this.pluginDir(ctx), this.pluginFileName(ctx));\n }\n\n /** Plugin directory the synthesized module is written into, per scope. */\n private pluginDir(ctx: InstallContext): string {\n return ctx.scope === \"project\"\n ? join(ctx.projectDir, \".kilo\", \"plugin\")\n : join(homedir(), \".config\", \"kilo\", \"plugin\");\n }\n\n /** Plugin module file name (one per connector, kebab-case id). */\n private pluginFileName(ctx: InstallContext): string {\n return `${ctx.connector.id}.js`;\n }\n\n // ── MCP server install / uninstall ───────────────────────────────────────\n\n installServer(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n const override = connector.platforms[HOST]?.server;\n if (!connector.server || override === false) {\n return [\n {\n platform: this.id,\n action: \"skip\",\n detail: connector.server\n ? \"server registration disabled for kilo-cli\"\n : \"connector declares no MCP server\",\n },\n ];\n }\n\n // Shallow-merge any per-platform server override into the base ServerDef.\n const server: ServerDef =\n override && typeof override === \"object\"\n ? { ...connector.server, ...override }\n : connector.server;\n\n const serverPath = this.getServerConfigPath(ctx);\n const entry = this.renderServerEntry(ctx, server);\n\n return [\n this.upsertServerInJson(serverPath, MCP_ROOT_KEY, connector.id, entry, ctx.dryRun),\n ];\n }\n\n uninstallServer(ctx: InstallContext): ChangeRecord[] {\n const serverPath = this.getServerConfigPath(ctx);\n return [\n this.removeServerFromJson(serverPath, MCP_ROOT_KEY, ctx.connector.id, ctx.dryRun),\n ];\n }\n\n /** Render a normalized ServerDef into the Kilo CLI's new-gen `mcp` entry. */\n private renderServerEntry(\n ctx: InstallContext,\n server: ServerDef,\n ): KiloLocalServer | KiloRemoteServer {\n const transport: Transport = server.transport;\n\n if (transport === \"stdio\") {\n let command = server.command ?? \"\";\n let args = [...(server.args ?? [])];\n\n // Transparent telemetry wrapping: route the real command through\n // `<homeBin> serve --connector <id> -- <command> <args...>`.\n 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 // QUIRK: the Kilo CLI's new-gen local server keys its whole invocation as\n // a single `command` ARRAY (executable + args together), like OpenCode.\n // The CLI has no documented native interpolation token, so resolve every\n // ${env:VAR} to a literal at install time.\n const entry: KiloLocalServer = {\n type: \"local\",\n command: resolveEnvRefsDeep([command, ...args]),\n };\n const env = this.renderEnv(server.env);\n if (env) entry.environment = env;\n return entry;\n }\n\n // sse / http (and any other remote transport) — the Kilo CLI registers a URL.\n const entry: KiloRemoteServer = {\n type: \"remote\",\n url: resolveEnvRefsDeep(server.url ?? \"\"),\n };\n return entry;\n }\n\n /**\n * Render env values. The Kilo CLI documents no native interpolation token, so\n * resolve `${env:VAR}` references to literals at install time.\n */\n private renderEnv(\n env: Record<string, string> | undefined,\n ): Record<string, string> | undefined {\n if (!env || Object.keys(env).length === 0) return undefined;\n return resolveEnvRefsDeep({ ...env });\n }\n\n // ── Hook install / uninstall (ts-plugin + explicit `plugin` array) ────────\n\n installHooks(ctx: InstallContext): ChangeRecord[] {\n const pluginPath = this.getHookConfigPath(ctx);\n const configPath = this.getServerConfigPath(ctx);\n\n if (ctx.connector.platforms[HOST]?.hooks === false) {\n return [\n { platform: this.id, action: \"skip\", path: pluginPath, detail: \"hooks disabled for kilo-cli\" },\n ];\n }\n if (ctx.connector.hookEvents.length === 0) {\n return [\n { platform: this.id, action: \"skip\", path: pluginPath, detail: \"connector declares no hooks\" },\n ];\n }\n\n const changes: ChangeRecord[] = [];\n\n // 1. Write the synthesized plugin module.\n for (const file of this.synthesizePlugin(ctx)) {\n const before = existsSync(file.path) ? this.safeRead(file.path) : undefined;\n let action: ChangeRecord[\"action\"];\n if (before === undefined) action = \"create\";\n else if (before === file.contents) action = \"skip\";\n else action = \"update\";\n\n if (action !== \"skip\" && !ctx.dryRun) {\n ensureDir(dirname(file.path));\n writeFileSync(file.path, file.contents, \"utf8\");\n chmodSync(file.path, file.executable ? 0o755 : 0o644);\n }\n changes.push({\n platform: this.id,\n action,\n path: file.path,\n detail: `kilo plugin module (${this.hookDetail(ctx)})`,\n });\n }\n\n // 2. Register the module path in kilo.jsonc's `plugin` array (the fork does\n // NOT auto-discover by directory — it reads this array).\n changes.push(this.upsertPluginInArray(configPath, pluginPath, ctx.dryRun));\n\n return changes;\n }\n\n /**\n * Human-facing summary of which declared events the synthesized module ACTUALLY\n * wires. Only events present in EVENT_TO_KILO are mapped/wired; any declared\n * event with no Kilo mapping is reported separately as \"unsupported here\" so\n * the detail never overstates coverage.\n */\n private hookDetail(ctx: InstallContext): string {\n const declared = ctx.connector.hookEvents;\n const mapped = declared.filter((e) => EVENT_TO_KILO[e] !== undefined);\n const unsupported = declared.filter((e) => EVENT_TO_KILO[e] === undefined);\n const base = mapped.join(\",\");\n return unsupported.length > 0\n ? `${base}; unsupported here: ${unsupported.join(\",\")}`\n : base;\n }\n\n uninstallHooks(ctx: InstallContext): ChangeRecord[] {\n const pluginPath = this.getHookConfigPath(ctx);\n const configPath = this.getServerConfigPath(ctx);\n const changes: ChangeRecord[] = [];\n\n // 1. Deregister the module path from kilo.jsonc's `plugin` array.\n changes.push(this.removePluginFromArray(configPath, pluginPath, ctx.dryRun));\n\n // 2. Remove the plugin module on disk.\n if (existsSync(pluginPath)) {\n if (!ctx.dryRun) rmSync(pluginPath, { force: true });\n changes.push({\n platform: this.id,\n action: \"remove\",\n path: pluginPath,\n detail: \"kilo plugin module\",\n });\n } else {\n changes.push({\n platform: this.id,\n action: \"skip\",\n path: pluginPath,\n detail: \"no kilo plugin module present\",\n });\n }\n\n // 3. Drop the now-empty plugin dir (only if WE own its full contents).\n changes.push(this.removeDirIfEmpty(this.pluginDir(ctx), ctx.dryRun));\n\n return changes;\n }\n\n /** Upsert the module path into kilo.jsonc's top-level `plugin` array (idempotent). */\n private upsertPluginInArray(\n configPath: string,\n modulePath: string,\n dryRun: boolean,\n ): ChangeRecord {\n // OVERWRITE GUARD: never blank a present-but-unparseable kilo.jsonc.\n if (this.isPresentButUnparseable(configPath)) {\n return {\n platform: this.id,\n action: \"warn\",\n path: configPath,\n detail: `existing ${configPath} is not parseable; left untouched (back it up / fix it, then re-run)`,\n };\n }\n const cfg = this.readJson<Record<string, unknown>>(configPath) ?? {};\n const plugins = this.pluginArrayBucket(cfg);\n if (plugins.includes(modulePath)) {\n return {\n platform: this.id,\n action: \"skip\",\n path: configPath,\n detail: `${PLUGIN_ARRAY_KEY}[] already includes module`,\n };\n }\n plugins.push(modulePath);\n this.writeJson(configPath, cfg, dryRun);\n return {\n platform: this.id,\n action: \"create\",\n path: configPath,\n detail: `${PLUGIN_ARRAY_KEY}[] += module`,\n };\n }\n\n /** Remove the module path from kilo.jsonc's `plugin` array. */\n private removePluginFromArray(\n configPath: string,\n modulePath: string,\n dryRun: boolean,\n ): ChangeRecord {\n // OVERWRITE GUARD: a present-but-unparseable file would round-trip to `{}`.\n if (this.isPresentButUnparseable(configPath)) {\n return {\n platform: this.id,\n action: \"warn\",\n path: configPath,\n detail: `existing ${configPath} is not parseable; left untouched (back it up / fix it, then re-run)`,\n };\n }\n const cfg = this.readJson<Record<string, unknown>>(configPath);\n const raw = cfg?.[PLUGIN_ARRAY_KEY];\n const plugins = Array.isArray(raw) ? (raw as unknown[]) : undefined;\n const idx = plugins ? plugins.indexOf(modulePath) : -1;\n if (!cfg || !plugins || idx < 0) {\n return {\n platform: this.id,\n action: \"skip\",\n path: configPath,\n detail: `${PLUGIN_ARRAY_KEY}[] does not include module`,\n };\n }\n plugins.splice(idx, 1);\n this.writeJson(configPath, cfg, dryRun);\n return {\n platform: this.id,\n action: \"remove\",\n path: configPath,\n detail: `${PLUGIN_ARRAY_KEY}[] -= module`,\n };\n }\n\n /** Get-or-create the top-level `plugin` array as a mutable string array. */\n private pluginArrayBucket(cfg: Record<string, unknown>): string[] {\n const existing = cfg[PLUGIN_ARRAY_KEY];\n // Normalize to a fresh string[] (drop any non-string a user may have placed\n // here) and write it back so the caller mutates the live array.\n const plugins = Array.isArray(existing)\n ? existing.filter((p): p is string => typeof p === \"string\")\n : [];\n cfg[PLUGIN_ARRAY_KEY] = plugins;\n return plugins;\n }\n\n // ── ts-plugin synthesis ────────────────────────────────────────────────\n\n /**\n * Build ONE self-contained ESM plugin module for the Kilo CLI fork.\n *\n * The module imports nothing from agent-connector. It embeds two constants\n * (the absolute home-bin path and the connector id) and a `bridge()` helper\n * that shells out to the universal hook entrypoint via execFileSync, feeding\n * the Kilo payload on stdin and JSON.parsing the normalized HookResponse back\n * from stdout (fail-open: any error → null). Its default export is the\n * `@kilocode/plugin` PluginModule shape — { id, server: async (input) =>\n * ({ \"tool.execute.before\": …, \"tool.execute.after\": …, … }) } — keyed only by\n * the fork event names for the events this connector actually declares.\n */\n synthesizePlugin(ctx: InstallContext): GeneratedPluginFile[] {\n const path = this.getHookConfigPath(ctx);\n const contents = this.buildPluginSource(ctx);\n return [{ path, contents, executable: false }];\n }\n\n /** Compose the generated plugin source with plain string concatenation. */\n private buildPluginSource(ctx: InstallContext): string {\n const homeBin = JSON.stringify(ctx.homeBinPath);\n const connectorId = JSON.stringify(ctx.connector.id);\n\n // The Kilo event keys this connector declares (and that we can map).\n const events = ctx.connector.hookEvents.filter(\n (e): e is HookEventName => EVENT_TO_KILO[e] !== undefined,\n );\n const has = (e: HookEventName) => events.includes(e);\n\n const header = `/**\n * AUTO-GENERATED by agent-connector — DO NOT EDIT.\n *\n * Self-contained Kilo CLI plugin bridge for connector ${ctx.connector.id}.\n * It imports nothing from agent-connector: every hook invocation shells out to\n * the stable home binary's universal entrypoint and JSON-parses the normalized\n * response. Fail-open: any bridge error degrades to \"allow\".\n *\n * Default export is the @kilocode/plugin PluginModule shape\n * ({ id, server: async (input) => Hooks }); the fork loads it because its path\n * is registered in kilo.jsonc's \"plugin\" array.\n */\nimport { execFileSync, execSync } from \"node:child_process\";\n\nconst HOME_BIN = ${homeBin};\nconst CONNECTOR_ID = ${connectorId};\n\n/**\n * Invoke the universal hook entrypoint for one event.\n * @param {string} event canonical event name (PreToolUse|PostToolUse|SessionStart)\n * @param {object} payload Kilo-shaped payload posted on stdin\n * @returns {object|null} normalized HookResponse, or null on any failure\n */\nfunction bridge(event, payload) {\n try {\n // On Windows HOME_BIN is the agent-connector.cmd launcher: Node cannot\n // execFile a batch file, and shell+args is deprecated (DEP0190), so run one\n // quoted command line via a shell. POSIX keeps the direct execFile (no shell).\n const args = [\"hook\", \"kilo-cli\", 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 // Fail-open — never wedge a tool call on a bridge error.\n return null;\n }\n}\n`;\n\n const handlers: string[] = [];\n\n if (has(\"PreToolUse\")) {\n handlers.push(` // PreToolUse → block (throw) / rewrite args (mutate output.args).\n \"tool.execute.before\": async (input, output) => {\n const payload = {\n toolName: input.tool ?? \"\",\n toolInput: (output && output.args) ?? {},\n sessionId: input.sessionID ?? \"\",\n projectDir: PROJECT_DIR,\n };\n const res = bridge(\"PreToolUse\", payload);\n if (!res) return;\n // Kilo has no \"ask\" gate — degrade \"ask\" to a block (safe direction).\n if (res.decision === \"deny\" || res.decision === \"ask\") {\n throw new Error(res.reason || \"Blocked by ${ctx.connector.id}\");\n }\n if (res.updatedInput && output && output.args) {\n Object.assign(output.args, res.updatedInput);\n }\n },`);\n }\n\n if (has(\"PostToolUse\")) {\n handlers.push(` // PostToolUse → observe / rewrite tool output (mutate output.output).\n \"tool.execute.after\": async (input, output) => {\n const payload = {\n toolName: input.tool ?? \"\",\n toolInput: input.args ?? {},\n toolOutput: output ? output.output : undefined,\n sessionId: input.sessionID ?? \"\",\n projectDir: PROJECT_DIR,\n };\n const res = bridge(\"PostToolUse\", payload);\n if (!res) return;\n if (typeof res.updatedOutput === \"string\" && output) {\n output.output = res.updatedOutput;\n }\n },`);\n }\n\n if (has(\"SessionStart\")) {\n handlers.push(` // SessionStart surrogate → inject context into the system prompt.\n // The fork has no real SessionStart hook; the system-prompt transform is the\n // verified injection point (mirrors OpenCode).\n \"experimental.chat.system.transform\": async (input, output) => {\n const payload = {\n sessionId: (input && input.sessionID) ?? \"\",\n projectDir: PROJECT_DIR,\n };\n const res = bridge(\"SessionStart\", payload);\n if (!res) return;\n if (res.additionalContext && output && Array.isArray(output.system)) {\n // Insert at index 1 (after the header) to preserve the prompt-cache fold\n // (header must remain system[0]).\n output.system.splice(1, 0, res.additionalContext);\n }\n },`);\n }\n\n const definition = `\nconst plugin = {\n id: CONNECTOR_ID,\n // @kilocode/plugin PluginModule: server(input) returns the Hooks object keyed\n // by the fork's event names. ctx.directory is the project root; fall back to cwd.\n server: async (input) => {\n const PROJECT_DIR =\n (input && (input.directory || (input.worktree && input.worktree.path))) ||\n process.cwd();\n\n return {\n${handlers.join(\"\\n\")}\n };\n },\n};\n\nexport default plugin;\n`;\n\n return header + definition;\n }\n\n // ── Runtime: parse OUR bridge payload → normalized event ───────────────\n\n /**\n * `raw` is the payload OUR generated plugin posts (NOT a host-native shape):\n * { toolName, toolInput, toolOutput?, isError?, sessionId, projectDir }\n * so this maps straight through.\n */\n parseEvent(event: HookEventName, raw: unknown): NormalizedEvent {\n const input = (raw ?? {}) as KiloBridgePayload;\n const base = {\n hostPlatform: HOST,\n connectorId: \"\",\n sessionId: typeof input.sessionId === \"string\" ? input.sessionId : \"\",\n raw,\n ...(typeof input.projectDir === \"string\" ? { projectDir: input.projectDir } : {}),\n } as const;\n\n switch (event) {\n case \"PreToolUse\": {\n const ev: PreToolUseEvent = {\n ...base,\n toolName: input.toolName ?? \"\",\n toolInput: input.toolInput ?? {},\n };\n return ev;\n }\n case \"PostToolUse\": {\n const ev: PostToolUseEvent = {\n ...base,\n toolName: input.toolName ?? \"\",\n toolInput: input.toolInput ?? {},\n ...(typeof input.toolOutput === \"string\" ? { toolOutput: input.toolOutput } : {}),\n ...(typeof input.isError === \"boolean\" ? { isError: input.isError } : {}),\n };\n return ev;\n }\n case \"SessionStart\": {\n const ev: SessionStartEvent = { ...base, source: \"startup\" };\n return ev;\n }\n default:\n // Other canonical events are not surfaced by Kilo; treat as a\n // session-start-shaped no-op so the dispatcher fails open gracefully.\n return { ...base, source: \"startup\" } satisfies SessionStartEvent;\n }\n }\n\n // ── Runtime: normalized response → reply the generated bridge parses ───\n\n /**\n * Unlike json-stdio hosts (whose reply is the host's NATIVE control payload),\n * OUR generated bridge consumes this stdout directly. So the reply body is the\n * NORMALIZED HookResponse itself — the bridge JSON.parses it and reads\n * decision / updatedInput / updatedOutput / additionalContext.\n */\n formatReply(_event: HookEventName, response: HookResponse): HookReply {\n return {\n exitCode: 0,\n stdout: JSON.stringify(response ?? { decision: \"allow\" }),\n };\n }\n\n // ── Diagnostics ──────────────────────────────────────────────────────────\n\n override getHealthChecks(ctx: InstallContext): readonly HealthCheck[] {\n const configPath = this.getServerConfigPath(ctx);\n const pluginPath = this.getHookConfigPath(ctx);\n const connectorId = ctx.connector.id;\n const hasHooks = ctx.connector.hookEvents.length > 0;\n\n return [\n {\n name: `${this.name}: ${CONFIG_FILE} present`,\n check: () =>\n existsSync(configPath)\n ? { status: \"OK\", detail: configPath }\n : { status: \"FAIL\", detail: `not found: ${configPath}` },\n },\n {\n name: `${this.name}: server entry registered`,\n check: () => {\n if (!ctx.connector.server) {\n return { status: \"OK\", detail: \"no MCP server declared\" };\n }\n const cfg = this.readJson<{ [k: string]: Record<string, unknown> }>(configPath);\n const bucket = cfg?.[MCP_ROOT_KEY];\n if (!cfg || !bucket) {\n return { status: \"FAIL\", detail: `no ${MCP_ROOT_KEY} in ${configPath}` };\n }\n return connectorId in bucket\n ? { status: \"OK\", detail: `${MCP_ROOT_KEY}.${connectorId} present` }\n : {\n status: \"FAIL\",\n detail: `no ${MCP_ROOT_KEY}.${connectorId} in ${configPath}`,\n };\n },\n },\n {\n name: `${this.name}: plugin module present`,\n check: () => {\n if (!hasHooks) return { status: \"OK\", detail: \"no hooks declared\" };\n return existsSync(pluginPath)\n ? { status: \"OK\", detail: pluginPath }\n : { status: \"FAIL\", detail: `not found: ${pluginPath}` };\n },\n },\n {\n name: `${this.name}: plugin registered in ${PLUGIN_ARRAY_KEY}[]`,\n check: () => {\n if (!hasHooks) return { status: \"OK\", detail: \"no hooks declared\" };\n const cfg = this.readJson<Record<string, unknown>>(configPath);\n const raw = cfg?.[PLUGIN_ARRAY_KEY];\n const plugins = Array.isArray(raw) ? (raw as unknown[]) : undefined;\n return plugins && plugins.includes(pluginPath)\n ? { status: \"OK\", detail: `${PLUGIN_ARRAY_KEY}[] includes module` }\n : {\n status: \"FAIL\",\n detail: `module not in ${PLUGIN_ARRAY_KEY}[] of ${configPath} (fork will not load it)`,\n };\n },\n },\n ];\n }\n\n /** Read a file, returning undefined on any error (idempotency compare). */\n private safeRead(path: string): string | undefined {\n try {\n return readFileSync(path, \"utf8\");\n } catch {\n return undefined;\n }\n }\n}\n\n/** Create a directory (recursive) if it does not already exist. */\nfunction ensureDir(dir: string): void {\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true });\n}\n\nexport const adapter = new KiloCliAdapter();\nexport default adapter;\n"],"mappings":";;;;;;;;;;;;;;;;AA+DA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,eAAe;AACxB,SAAS,SAAS,YAAY;AAgC9B,IAAM,OAAmB;AAEzB,IAAM,eAAe;AAErB,IAAM,mBAAmB;AAEzB,IAAM,cAAc;AAEpB,IAAM,iBAAiB,CAAC,UAAU,SAAS,QAAQ,SAAS;AAY5D,IAAM,gBAAwD;AAAA,EAC5D,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,cAAc;AAChB;AA4BO,IAAM,iBAAN,cAA6B,YAA+B;AAAA,EACxD,KAAiB;AAAA,EACjB,OAAO;AAAA,EACP,WAAyB;AAAA,EAEzB,eAAqC;AAAA;AAAA;AAAA,IAG5C,gBAAgB;AAAA;AAAA;AAAA,IAGhB,YAAY;AAAA,IACZ,aAAa;AAAA;AAAA,IAEb,YAAY;AAAA,IACZ,cAAc;AAAA,IACd,YAAY;AAAA,IACZ,kBAAkB;AAAA,IAClB,MAAM;AAAA,IACN,cAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IASd,eAAe;AAAA;AAAA,IAEf,iBAAiB;AAAA;AAAA,IAEjB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MACA;AAAA,QACE,MAAM,GAAG,KAAK,IAAI,0BAA0B,gBAAgB;AAAA,QAC5D,OAAO,MAAM;AACX,cAAI,CAAC,SAAU,QAAO,EAAE,QAAQ,MAAM,QAAQ,oBAAoB;AAClE,gBAAM,MAAM,KAAK,SAAkC,UAAU;AAC7D,gBAAM,MAAM,MAAM,gBAAgB;AAClC,gBAAM,UAAU,MAAM,QAAQ,GAAG,IAAK,MAAoB;AAC1D,iBAAO,WAAW,QAAQ,SAAS,UAAU,IACzC,EAAE,QAAQ,MAAM,QAAQ,GAAG,gBAAgB,qBAAqB,IAChE;AAAA,YACE,QAAQ;AAAA,YACR,QAAQ,iBAAiB,gBAAgB,SAAS,UAAU;AAAA,UAC9D;AAAA,QACN;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAAA;AAAA,EAGQ,SAAS,MAAkC;AACjD,QAAI;AACF,aAAO,aAAa,MAAM,MAAM;AAAA,IAClC,QAAQ;AACN,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAGA,SAAS,UAAU,KAAmB;AACpC,MAAI,CAAC,WAAW,GAAG,EAAG,WAAU,KAAK,EAAE,WAAW,KAAK,CAAC;AAC1D;AAEO,IAAM,UAAU,IAAI,eAAe;AAC1C,IAAO,mBAAQ;","names":["entry"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/adapters/kimi/index.ts"],"sourcesContent":["/**\n * adapters/kimi — Kimi CLI (Moonshot) platform adapter for agent-connector.\n *\n * Kimi CLI is a json-stdio host: the runner pipes a JSON payload to a command on\n * stdin and reads an exit code (and optional reason) back. Two native config\n * files live under the Kimi base dir (`$KIMI_HOME` || `$KIMI_CODE_HOME` || `~/.kimi`):\n * - mcp.json → `mcpServers.<id>` MCP registration (JSON, stdio shape:\n * {command,args,env}). Handled via BaseAdapter's JSON helpers.\n * - config.toml → `[[hooks]]` array-of-tables (TOML), each table\n * { event, matcher, command }. Parsed/serialized with @iarna/toml: every\n * config VALUE (unrelated sections, sibling hooks, scalars) is preserved,\n * but a parse→stringify round-trip does NOT preserve user COMMENTS or the\n * original key ordering/formatting in config.toml (values survive; comments\n * and layout do not).\n *\n * Hook surface is intentionally narrow: Kimi CLI only honors a PreToolUse DENY.\n * It cannot rewrite tool args, rewrite tool output, or inject session context —\n * so every other decision degrades to a silent allow (exit 0). Kimi Code uses\n * the Claude/Codex reply shape: a PreToolUse deny is signalled with EXIT 0 plus\n * a `hookSpecificOutput` JSON object on stdout carrying\n * permissionDecision:\"deny\" + permissionDecisionReason — that is how Kimi's\n * runner blocks the pending tool call. An allow is exit 0 with empty stdout.\n *\n * E1 extension events (verified against moonshotai.github.io/kimi-cli hooks):\n * - PostToolUseFailure — native (tool_name, tool_input, error; tool-name\n * matcher). Feedback-only: Kimi's exit-0 protocol adds non-empty stdout to\n * context, so \"context\" (and a degraded \"deny\") emit plain-text stdout.\n * - SubagentStart / SubagentStop — native, but with Kimi-specific wire\n * fields: agent_name (→ normalized agentType; there is no agent_id) plus\n * prompt (start) / response (stop → lastAssistantMessage). SubagentStop\n * deny uses Kimi's generic block protocol: EXIT 2 with the reason on\n * stderr (fed back to the model as correction).\n * - PermissionRequest — NO Kimi analog (the permission prompt is only\n * observable as a Notification); declared hooks for it warn-skip at\n * install and the capability flag stays unset.\n *\n * Path confidence: the `~/.kimi` base + mcp.json (`mcpServers`) layout is\n * LIVE-CONFIRMED against the real Moonshot Kimi CLI (v1.46.0, `pip install\n * kimi-cli`) via a `kimi mcp` probe. We still install + doctor-report presence\n * so a future path move surfaces as a FAIL rather than silently misbehaving.\n *\n * FUTURE COVERAGE (non-functional note — no behavior change here): beyond the\n * wired PreToolUse + PostToolUseFailure + SubagentStart/SubagentStop, Kimi CLI\n * supports a wider event surface — Stop, StopFailure, UserPromptSubmit,\n * PostToolUse, SessionStart, SessionEnd, PreCompact, PostCompact and\n * Notification. Kimi also has a PLUGIN system (plugins live at\n * `<base>/plugins/<name>/kimi.plugin.json`) and a SKILLS surface\n * (`~/.kimi/skills/`). None of these are covered yet; they are flagged here\n * as candidates for a future events/plugins/skills expansion of the adapter.\n */\n\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nimport TOML from \"@iarna/toml\";\n\nimport { BaseAdapter } from \"../base.js\";\nimport type { Adapter, HookReply, InstallContext, NormalizedEvent } from \"../spi.js\";\nimport type {\n ChangeRecord,\n DetectedPlatform,\n HealthCheck,\n HookEventName,\n HookParadigm,\n HookResponse,\n NotificationEvent,\n PermissionRequestEvent,\n PlatformCapabilities,\n PlatformId,\n PostToolUseEvent,\n PostToolUseFailureEvent,\n PreCompactEvent,\n PreToolUseEvent,\n SessionEndEvent,\n SessionStartEvent,\n ServerDef,\n StopEvent,\n SubagentStartEvent,\n SubagentStopEvent,\n Transport,\n UserPromptSubmitEvent,\n} from \"../../core/types.js\";\nimport { ensureDir } from \"../../core/paths.js\";\nimport { resolveEnvRefsDeep } from \"../../core/interpolate.js\";\nimport {\n buildHomeBinHookCommand,\n buildServeWrapperCommand,\n isHomeBinHookCommand,\n shouldWrapForTelemetry,\n} from \"../../core/spawn.js\";\n\nconst HOST: PlatformId = \"kimi\";\nconst MCP_ROOT_KEY = \"mcpServers\";\n\n// ─────────────────────────────────────────────────────────────────────────\n// Native shapes\n// ─────────────────────────────────────────────────────────────────────────\n\n/** Raw Kimi CLI hook payload (Claude-style: PascalCase event, snake_case fields). */\ninterface KimiHookInput {\n tool_name?: string;\n tool_input?: Record<string, unknown>;\n tool_response?: unknown;\n session_id?: string;\n cwd?: string;\n hook_event_name?: string;\n source?: string;\n prompt?: string;\n is_error?: boolean;\n stop_hook_active?: boolean;\n trigger?: string;\n message?: string;\n reason?: string;\n // PostToolUseFailure — the failure message.\n error?: string;\n // SubagentStart / SubagentStop — Kimi sends agent_name (NOT agent_id /\n // agent_type) plus prompt (start) / response (stop).\n agent_name?: string;\n response?: string;\n connector?: string;\n}\n\n/** One `[[hooks]]` array-of-tables entry as Kimi stores it in config.toml. */\ninterface KimiTomlHook {\n event: string;\n matcher?: string;\n command: string;\n [key: string]: unknown;\n}\n\n/** Parsed config.toml shape we care about (rest preserved verbatim). */\ninterface KimiConfigToml {\n hooks?: KimiTomlHook[];\n [key: string]: unknown;\n}\n\n/** Native stdio MCP server entry under `mcpServers`. */\ninterface KimiStdioServer {\n command: string;\n args?: string[];\n env?: Record<string, string>;\n}\n\n/** Native remote MCP server entry under `mcpServers`. */\ninterface KimiHttpServer {\n url: string;\n headers?: Record<string, string>;\n}\n\n/**\n * Kimi CLI hook events agent-connector registers: the PreToolUse deny gate plus\n * the E1 extension events Kimi fires natively (PostToolUseFailure +\n * SubagentStart/SubagentStop). The matcher below is charset-clean (Rust-regex\n * safe: no look-around) so Kimi's matcher accepts it. Copied in spirit from the\n * Codex/context-mode matchers.\n */\nconst KIMI_HOOK_EVENTS = [\n \"PreToolUse\",\n \"PostToolUseFailure\",\n \"SubagentStart\",\n \"SubagentStop\",\n] as const;\ntype KimiHookEventName = (typeof KIMI_HOOK_EVENTS)[number];\n\n/**\n * Newer canonical events with NO Kimi analog: there is no permission-dialog\n * hook (the prompt is only observable via Notification). Declared hooks for\n * these warn-skip at install so the degradation is reported, never silent.\n * (The legacy silent drop of host-supported-but-unwired events — SessionStart,\n * Stop, … — predates this convention and is deliberately left untouched; see\n * the FUTURE COVERAGE header note.)\n */\nconst WARN_SKIP_EVENTS: ReadonlySet<HookEventName> = new Set([\"PermissionRequest\"]);\n\nconst PRE_TOOL_USE_MATCHER =\n \"Bash|Shell|shell|exec_command|Read|Edit|Write|WebFetch|Agent|mcp__\";\n\n// ─────────────────────────────────────────────────────────────────────────\n// Adapter\n// ─────────────────────────────────────────────────────────────────────────\n\nexport class KimiAdapter extends BaseAdapter implements Adapter {\n readonly id: PlatformId = HOST;\n readonly name = \"Kimi CLI\";\n readonly paradigm: HookParadigm = \"json-stdio\";\n\n readonly capabilities: PlatformCapabilities = {\n // Memory surface: AGENTS.md-first managed block via the BaseAdapter default\n // (memoryTargets: project <projectDir>/AGENTS.md; user scope where documented).\n supportsMemory: true,\n // PreToolUse deny is the only honored hook decision on Kimi CLI.\n preToolUse: true,\n postToolUse: false,\n preCompact: false,\n sessionStart: false,\n sessionEnd: false,\n userPromptSubmit: false,\n stop: false,\n notification: false,\n // E1 events Kimi fires natively. permissionRequest stays unset — Kimi has\n // no permission-dialog hook, so a declared hook for it warn-skips at install.\n postToolUseFailure: true,\n subagentStart: true,\n subagentStop: true,\n // Kimi cannot rewrite args/output nor inject session context — deny-only.\n canModifyArgs: false,\n canModifyOutput: false,\n canInjectSessionContext: false,\n transports: [\"stdio\", \"http\"],\n };\n\n // ── Detection ────────────────────────────────────────────────────────────\n\n detectInstalled(_projectDir: string): DetectedPlatform {\n const baseDir = this.baseDir();\n const mcpPath = join(baseDir, \"mcp.json\");\n const configPath = join(baseDir, \"config.toml\");\n const installed = existsSync(baseDir) || existsSync(mcpPath) || existsSync(configPath);\n return {\n id: this.id,\n name: this.name,\n installed,\n paradigm: this.paradigm,\n capabilities: this.capabilities,\n configPath: mcpPath,\n scope: \"user\",\n reason: installed\n ? `found Kimi CLI config under ${baseDir}`\n : `no Kimi CLI config at ${baseDir}`,\n // Path confidence is medium even when present: the ~/.kimi-code layout is the\n // documented shape but less battle-tested than Claude/Codex.\n confidence: \"medium\",\n };\n }\n\n // ── Native paths ───────────────────────────────────────────────────────\n\n getConfigDir(_ctx: InstallContext): string {\n return this.baseDir();\n }\n\n /** MCP registration file (JSON). */\n getServerConfigPath(ctx: InstallContext): string {\n return join(this.getConfigDir(ctx), \"mcp.json\");\n }\n\n /** Hook registration file (TOML) — distinct from the MCP file. */\n getHookConfigPath(ctx: InstallContext): string {\n return join(this.getConfigDir(ctx), \"config.toml\");\n }\n\n /**\n * `$KIMI_HOME` || `$KIMI_CODE_HOME` (with `~` expansion) || `~/.kimi`.\n * The real Moonshot Kimi CLI (v1.46.0) keeps its config under `~/.kimi`\n * (mcp.json · mcpServers) — verified by a live `kimi mcp` probe; the legacy\n * `~/.kimi-code` guess was wrong. `$KIMI_CODE_HOME` is still honored as an\n * override for back-compat alongside the newer `$KIMI_HOME`.\n */\n private baseDir(): string {\n const env = process.env.KIMI_HOME ?? process.env.KIMI_CODE_HOME;\n if (env && env.trim() !== \"\") {\n if (env.startsWith(\"~\")) {\n return join(homedir(), env.replace(/^~[/\\\\]?/, \"\"));\n }\n return env;\n }\n return join(homedir(), \".kimi\");\n }\n\n // ── MCP server install / uninstall (mcp.json → mcpServers.<id>) ──────────\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 kimi\"\n : \"connector declares no MCP server\",\n },\n ];\n }\n\n const server: ServerDef =\n override && typeof override === \"object\"\n ? { ...connector.server, ...override }\n : connector.server;\n\n const serverPath = this.getServerConfigPath(ctx);\n const entry = this.renderServerEntry(ctx, server);\n\n return [\n this.upsertServerInJson(serverPath, MCP_ROOT_KEY, connector.id, entry, ctx.dryRun),\n ];\n }\n\n uninstallServer(ctx: InstallContext): ChangeRecord[] {\n const serverPath = this.getServerConfigPath(ctx);\n return [\n this.removeServerFromJson(serverPath, MCP_ROOT_KEY, ctx.connector.id, ctx.dryRun),\n ];\n }\n\n /**\n * Render a normalized ServerDef into Kimi's native mcpServers entry. Kimi's\n * mcp.json has no documented native interpolation, so `${env:VAR}` refs are\n * resolved to literals at install time (same posture as the TOML hosts).\n */\n private renderServerEntry(\n ctx: InstallContext,\n server: ServerDef,\n ): KimiStdioServer | KimiHttpServer {\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 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 command = resolveEnvRefsDeep(command);\n args = resolveEnvRefsDeep(args);\n\n const entry: KimiStdioServer = { command };\n if (args.length > 0) entry.args = args;\n const env = this.renderEnv(server.env);\n if (env) entry.env = env;\n return entry;\n }\n\n // http (and any other remote transport) — Kimi registers a URL entry.\n const entry: KimiHttpServer = { url: resolveEnvRefsDeep(server.url ?? \"\") };\n const headers = this.renderEnv(server.headers);\n if (headers) entry.headers = headers;\n return entry;\n }\n\n /** Resolve env/header values to literals (no native interpolation on Kimi). */\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(resolveEnvRefsDeep(env))) {\n out[k] = String(v);\n }\n return out;\n }\n\n // ── Hook install / uninstall (config.toml → [[hooks]]) ───────────────────\n\n installHooks(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n if (connector.platforms[HOST]?.hooks === false) {\n return [{ platform: this.id, action: \"skip\", detail: \"hooks disabled for kimi\" }];\n }\n\n const events = this.effectiveHookEvents(ctx);\n const dropped = this.warnSkipHookEvents(ctx);\n const path = this.getHookConfigPath(ctx);\n\n if (events.length === 0 && dropped.length === 0) {\n return [{ platform: this.id, action: \"skip\", path, detail: \"no hooks declared\" }];\n }\n\n const cfg = this.readToml(path);\n const hooks = (cfg.hooks ??= []);\n const changes: ChangeRecord[] = [];\n let mutated = false;\n\n // Declared events Kimi cannot fire are reported, never silently dropped.\n for (const event of dropped) {\n changes.push({\n platform: this.id,\n action: \"warn\",\n path,\n detail: `${event} has no Kimi CLI hook equivalent — skipped`,\n });\n }\n\n for (const event of events) {\n const desired = this.renderHook(ctx, event);\n // Match our entry FOR THIS EVENT — isOurHook alone would find whichever\n // of our entries comes first and clobber a sibling event's registration.\n const idx = hooks.findIndex((h) => this.isOurHook(ctx, h) && h?.event === event);\n if (idx < 0) {\n hooks.push(desired);\n changes.push({ platform: this.id, action: \"create\", path, detail: `hooks.${event}` });\n mutated = true;\n } else if (JSON.stringify(hooks[idx]) !== JSON.stringify(desired)) {\n hooks[idx] = desired;\n changes.push({ platform: this.id, action: \"update\", path, detail: `hooks.${event}` });\n mutated = true;\n } else {\n changes.push({ platform: this.id, action: \"skip\", path, detail: `hooks.${event}` });\n }\n }\n\n if (mutated) this.writeToml(path, cfg, ctx.dryRun);\n return changes;\n }\n\n uninstallHooks(ctx: InstallContext): ChangeRecord[] {\n const path = this.getHookConfigPath(ctx);\n if (!existsSync(path)) {\n return [{ platform: this.id, action: \"skip\", path, detail: \"no config.toml\" }];\n }\n const cfg = this.readToml(path);\n const hooks = cfg.hooks;\n if (!Array.isArray(hooks) || hooks.length === 0) {\n return [{ platform: this.id, action: \"skip\", path, detail: \"no hooks present\" }];\n }\n\n const kept = hooks.filter((h) => !this.isOurHook(ctx, h));\n const removed = hooks.length - kept.length;\n if (removed === 0) {\n return [{ platform: this.id, action: \"skip\", path, detail: \"no agent-connector hooks present\" }];\n }\n\n if (kept.length > 0) cfg.hooks = kept;\n else delete cfg.hooks;\n this.writeToml(path, cfg, ctx.dryRun);\n return [{ platform: this.id, action: \"remove\", path, detail: `hooks (${removed})` }];\n }\n\n // ── Diagnostics ──────────────────────────────────────────────────────────\n\n override getHealthChecks(ctx: InstallContext): readonly HealthCheck[] {\n const serverPath = this.getServerConfigPath(ctx);\n const hookPath = this.getHookConfigPath(ctx);\n const connectorId = ctx.connector.id;\n const homeBin = ctx.homeBinPath;\n const hookEvents = this.effectiveHookEvents(ctx);\n return [\n {\n name: `${this.name}: mcp.json present`,\n check: () =>\n existsSync(serverPath)\n ? { status: \"OK\", detail: serverPath }\n : { status: \"FAIL\", detail: `not found: ${serverPath}` },\n },\n {\n name: `${this.name}: mcpServers.${connectorId} registered`,\n check: () => {\n if (!ctx.connector.server) {\n return { status: \"OK\", detail: \"no MCP server declared\" };\n }\n const cfg = this.readJson<Record<string, Record<string, unknown>>>(serverPath);\n const bucket = cfg?.[MCP_ROOT_KEY];\n const present =\n typeof bucket === \"object\" && bucket !== null && connectorId in bucket;\n return present\n ? { status: \"OK\", detail: `mcpServers.${connectorId}` }\n : { status: \"FAIL\", detail: `mcpServers.${connectorId} not found in ${serverPath}` };\n },\n },\n {\n name: `${this.name}: hook command registered`,\n check: () => {\n if (hookEvents.length === 0) {\n return { status: \"OK\", detail: \"no hooks declared\" };\n }\n if (!existsSync(hookPath)) {\n return { status: \"FAIL\", detail: `not found: ${hookPath}` };\n }\n const cfg = this.readToml(hookPath);\n const registered = (cfg.hooks ?? []).some((h) =>\n isHomeBinHookCommand(h?.command, homeBin, connectorId),\n );\n return registered\n ? { status: \"OK\", detail: \"hook command present\" }\n : { status: \"FAIL\", detail: `no hook for ${connectorId} in ${hookPath}` };\n },\n },\n ];\n }\n\n // ── Runtime: parse Kimi stdin JSON → normalized event ────────────────────\n\n parseEvent(event: HookEventName, raw: unknown): NormalizedEvent {\n const input = (raw ?? {}) as KimiHookInput;\n const connectorId = typeof input.connector === \"string\" ? input.connector : \"\";\n const sessionId = input.session_id ?? `pid-${process.ppid}`;\n const projectDir = input.cwd ?? process.env.KIMI_PROJECT_DIR ?? process.cwd();\n\n const base = {\n hostPlatform: HOST,\n connectorId,\n sessionId,\n projectDir,\n raw,\n } as const;\n\n switch (event) {\n case \"PreToolUse\": {\n const ev: PreToolUseEvent = {\n ...base,\n toolName: input.tool_name ?? \"\",\n toolInput: input.tool_input ?? {},\n };\n return ev;\n }\n case \"PostToolUse\": {\n const ev: PostToolUseEvent = {\n ...base,\n toolName: input.tool_name ?? \"\",\n toolInput: input.tool_input ?? {},\n ...(toolResponseToString(input.tool_response) !== undefined\n ? { toolOutput: toolResponseToString(input.tool_response) }\n : {}),\n isError: input.is_error ?? false,\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.message === \"string\" ? { reason: input.message } : {}),\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 // No Kimi analog — never fired natively (install warn-skips it). Parsed\n // generically so a manual dispatch still normalizes instead of throwing.\n const ev: PermissionRequestEvent = {\n ...base,\n toolName: input.tool_name ?? \"\",\n toolInput: input.tool_input ?? {},\n };\n return ev;\n }\n case \"PostToolUseFailure\": {\n // Kimi documents tool_name/tool_input/error only (no tool_use_id /\n // is_interrupt / duration_ms) — the optionals stay unset.\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 };\n return ev;\n }\n case \"SubagentStart\": {\n // Kimi sends agent_name (the matcher subject) — normalize it as\n // agentType; there is no agent_id. The start prompt rides in `raw`.\n const ev: SubagentStartEvent = {\n ...base,\n ...(typeof input.agent_name === \"string\"\n ? { agentType: input.agent_name }\n : {}),\n };\n return ev;\n }\n case \"SubagentStop\": {\n const ev: SubagentStopEvent = {\n ...base,\n ...(typeof input.agent_name === \"string\"\n ? { agentType: input.agent_name }\n : {}),\n ...(typeof input.response === \"string\"\n ? { lastAssistantMessage: input.response }\n : {}),\n };\n return ev;\n }\n default: {\n const _never: never = event;\n throw new Error(`unsupported kimi hook event: ${String(_never)}`);\n }\n }\n }\n\n // ── Runtime: normalized response → Kimi native hook reply ────────────────\n\n formatReply(event: HookEventName, response: HookResponse): HookReply {\n const decision = response.decision ?? \"allow\";\n\n // deny → block the pending tool call. Kimi Code uses the Claude/Codex reply\n // shape: EXIT 0 + a `hookSpecificOutput` JSON object on stdout carrying\n // permissionDecision:\"deny\". Only PreToolUse deny is honored; every other\n // event (or decision) degrades to a silent allow.\n if (decision === \"deny\" && event === \"PreToolUse\") {\n return {\n exitCode: 0,\n stdout: JSON.stringify({\n hookSpecificOutput: {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"deny\",\n permissionDecisionReason: response.reason ?? \"Blocked by hook\",\n },\n }),\n };\n }\n\n // PostToolUseFailure (feedback beside the error) and SubagentStart (context\n // for the subagent) are observe/context-only: Kimi's documented protocol\n // adds non-empty stdout on exit 0 to context, so \"context\" emits the text\n // PLAIN (no JSON envelope) and a \"deny\" DEGRADES to the same shape carrying\n // the reason (the tool already failed / the spawn is not blockable).\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) return { exitCode: 0, stdout: context };\n return { exitCode: 0 };\n }\n\n // SubagentStop = Stop semantics via Kimi's generic block protocol: EXIT 2\n // with the reason on stderr keeps the subagent going (stderr is fed back to\n // the model as correction). \"context\" rides the exit-0 stdout channel.\n if (event === \"SubagentStop\") {\n if (decision === \"deny\") {\n return { exitCode: 2, stderr: response.reason ?? \"Blocked by hook\" };\n }\n if (decision === \"context\" && response.additionalContext) {\n return { exitCode: 0, stdout: response.additionalContext };\n }\n return { exitCode: 0 };\n }\n\n // allow / modify / context / ask / unsupported-event → passthrough (exit 0,\n // empty stdout). Kimi cannot rewrite args/output or inject context, so those\n // are dropped.\n return { exitCode: 0 };\n }\n\n // ── Internal helpers ───────────────────────────────────────────────────\n\n /** Which canonical hook events to register for Kimi, honoring overrides. */\n private effectiveHookEvents(ctx: InstallContext): KimiHookEventName[] {\n if (ctx.connector.platforms[HOST]?.hooks === false) return [];\n return KIMI_HOOK_EVENTS.filter((e) => ctx.connector.hookEvents.includes(e));\n }\n\n /** Declared events Kimi has no analog for — install reports a warn-skip. */\n private warnSkipHookEvents(ctx: InstallContext): HookEventName[] {\n if (ctx.connector.platforms[HOST]?.hooks === false) return [];\n return ctx.connector.hookEvents.filter((e) => WARN_SKIP_EVENTS.has(e));\n }\n\n /**\n * Render one `[[hooks]]` entry pointing at the stable home binary. Only the\n * PreToolUse deny gate carries the native tool matcher; the E1 events register\n * \"\" (match every tool failure / agent name) and the universal entrypoint\n * applies the connector's own matcher at runtime.\n */\n private renderHook(ctx: InstallContext, event: KimiHookEventName): KimiTomlHook {\n const command = buildHomeBinHookCommand(ctx.homeBinPath, HOST, event, ctx.connector.id);\n return {\n event,\n matcher: event === \"PreToolUse\" ? PRE_TOOL_USE_MATCHER : \"\",\n command,\n };\n }\n\n /**\n * Does this `[[hooks]]` entry belong to this connector? Anchored on the\n * home-bin + connector-id token (isHomeBinHookCommand) so uninstalling a\n * shared-prefix connector id never strips a sibling's hook.\n */\n private isOurHook(ctx: InstallContext, hook: KimiTomlHook | undefined): boolean {\n if (!hook || typeof hook !== \"object\") return false;\n return isHomeBinHookCommand(hook.command, ctx.homeBinPath, ctx.connector.id);\n }\n\n // ── TOML config IO (config.toml is TOML; MCP stays JSON via BaseAdapter) ──\n\n private readToml(path: string): KimiConfigToml {\n if (!existsSync(path)) return {};\n try {\n return TOML.parse(readFileSync(path, \"utf8\")) as unknown as KimiConfigToml;\n } catch {\n return {};\n }\n }\n\n private writeToml(path: string, data: KimiConfigToml, dryRun: boolean): void {\n if (dryRun) return;\n ensureDir(dirname(path));\n // NOTE: a @iarna/toml parse→stringify round-trip preserves config VALUES but\n // NOT user comments or the original key ordering/formatting in config.toml.\n // Values are safe; comments authored by the user are not preserved.\n writeFileSync(path, TOML.stringify(data as never), \"utf8\");\n }\n}\n\n/** Best-effort stringify of Kimi's tool_response into a normalized toolOutput. */\nfunction toolResponseToString(value: unknown): string | undefined {\n if (value === undefined || value === null) return undefined;\n if (typeof value === \"string\") return value;\n try {\n return JSON.stringify(value);\n } catch {\n return undefined;\n }\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 KimiAdapter();\nexport default adapter;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAmDA,SAAS,YAAY,cAAc,qBAAqB;AACxD,SAAS,eAAe;AACxB,SAAS,SAAS,YAAY;AAE9B,OAAO,UAAU;AAqCjB,IAAM,OAAmB;AACzB,IAAM,eAAe;AAgErB,IAAM,mBAAmB;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAWA,IAAM,mBAA+C,oBAAI,IAAI,CAAC,mBAAmB,CAAC;AAElF,IAAM,uBACJ;AAMK,IAAM,cAAN,cAA0B,YAA+B;AAAA,EACrD,KAAiB;AAAA,EACjB,OAAO;AAAA,EACP,WAAyB;AAAA,EAEzB,eAAqC;AAAA;AAAA;AAAA,IAG5C,gBAAgB;AAAA;AAAA,IAEhB,YAAY;AAAA,IACZ,aAAa;AAAA,IACb,YAAY;AAAA,IACZ,cAAc;AAAA,IACd,YAAY;AAAA,IACZ,kBAAkB;AAAA,IAClB,MAAM;AAAA,IACN,cAAc;AAAA;AAAA;AAAA,IAGd,oBAAoB;AAAA,IACpB,eAAe;AAAA,IACf,cAAc;AAAA;AAAA,IAEd,eAAe;AAAA,IACf,iBAAiB;AAAA,IACjB,yBAAyB;AAAA,IACzB,YAAY,CAAC,SAAS,MAAM;AAAA,EAC9B;AAAA;AAAA,EAIA,gBAAgB,aAAuC;AACrD,UAAM,UAAU,KAAK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;AACF,aAAO,KAAK,MAAM,aAAa,MAAM,MAAM,CAAC;AAAA,IAC9C,QAAQ;AACN,aAAO,CAAC;AAAA,IACV;AAAA,EACF;AAAA,EAEQ,UAAU,MAAc,MAAsB,QAAuB;AAC3E,QAAI,OAAQ;AACZ,cAAU,QAAQ,IAAI,CAAC;AAIvB,kBAAc,MAAM,KAAK,UAAU,IAAa,GAAG,MAAM;AAAA,EAC3D;AACF;AAGA,SAAS,qBAAqB,OAAoC;AAChE,MAAI,UAAU,UAAa,UAAU,KAAM,QAAO;AAClD,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,MAAI;AACF,WAAO,KAAK,UAAU,KAAK;AAAA,EAC7B,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,SAAS,uBAAuB,QAAyD;AACvF,UAAQ,QAAQ;AAAA,IACd,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT;AACE,aAAO;AAAA,EACX;AACF;AAEO,IAAM,UAAU,IAAI,YAAY;AACvC,IAAO,eAAQ;","names":["entry"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/adapters/kiro/index.ts"],"sourcesContent":["/**\n * adapters/kiro — Kiro (AWS) platform adapter for agent-connector.\n *\n * Kiro is a json-stdio host with TWO native config surfaces that live in\n * DIFFERENT files (so getServerConfigPath ≠ getHookConfigPath):\n *\n * 1. MCP servers — `mcp.json` under `~/.kiro/settings/` (user) or\n * `<projectDir>/.kiro/settings/` (project). The file is JSONC; we WRITE\n * plain JSON (valid JSONC), mirroring the other JSON-config adapters. Root\n * key `mcpServers`; a stdio server is `{ command, args, env }`.\n * Ref: https://kiro.dev/docs/mcp/configuration/\n *\n * 2. Hooks — NOT a settings file but an AGENT file:\n * `~/.kiro/agents/kiro_default.json`. Kiro auto-loads the built-in default\n * agent `kiro_default` for a new chat session, so hooks must register on\n * THAT agent (a file literally named `default.json` would define an inactive\n * custom agent the user must `/agent`-swap to). We merge a `hooks` key into\n * the existing agent JSON, creating a minimal agent object if absent.\n * Ref: kiro.dev/docs/cli/custom-agents/configuration-reference#hooks-field\n *\n * Hook protocol is EXIT-CODE based (unlike Claude's JSON-decision wrapper):\n * - exit 0 → allow the action.\n * - exit 2 → block the action; the reason is written to stderr.\n * - agentSpawn (≈ SessionStart) context injection → exit 0 + stdout JSON\n * `{ hookSpecificOutput: { additionalContext } }`.\n * Kiro CANNOT rewrite tool arguments or output (exit codes only), so\n * canModifyArgs / canModifyOutput are false; `modify` degrades to allow.\n *\n * Native hook event vocabulary differs from the canonical names and is mapped:\n * PreToolUse → preToolUse\n * PostToolUse → postToolUse\n * SessionStart → agentSpawn (Kiro's session-start equivalent)\n * UserPromptSubmit → userPromptSubmit\n * Stop → stop (documented Kiro hook)\n * Kiro has no equivalent for PreCompact / SessionEnd / Notification; those are\n * reported as a warn/skip at install time.\n *\n * Env handling: Kiro documents no `${env:VAR}` token of the framework's syntax,\n * so env/header/url refs are resolved to literals at install time via\n * resolveEnvRefsDeep — the safe default matching the Gemini/Codex adapters.\n *\n * Grounded in context-mode's proven Kiro adapter (src/adapters/kiro/*).\n */\n\nimport { existsSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nimport { BaseAdapter } from \"../base.js\";\nimport type { Adapter, HookReply, InstallContext, MemoryTarget, NormalizedEvent } from \"../spi.js\";\nimport type {\n ChangeRecord,\n DetectedPlatform,\n HealthCheck,\n HookEventName,\n HookParadigm,\n HookResponse,\n PlatformCapabilities,\n PlatformId,\n PostToolUseEvent,\n PreToolUseEvent,\n ServerDef,\n SessionStartEvent,\n StopEvent,\n Transport,\n UserPromptSubmitEvent,\n} from \"../../core/types.js\";\nimport { resolveEnvRefsDeep } from \"../../core/interpolate.js\";\nimport {\n buildHomeBinHookCommand,\n buildServeWrapperCommand,\n isHomeBinHookCommand,\n shouldWrapForTelemetry,\n} from \"../../core/spawn.js\";\n\nconst HOST: PlatformId = \"kiro\";\nconst MCP_ROOT_KEY = \"mcpServers\";\n\n/** The built-in agent Kiro auto-loads for a new chat session. */\nconst DEFAULT_AGENT_FILE = \"kiro_default.json\";\n\n/**\n * Kiro-native hook event names (the keys under an agent file's `hooks` object).\n * Only the events Kiro actually fires for the json-stdio command paradigm.\n */\nconst KIRO_EVENT = {\n preToolUse: \"preToolUse\",\n postToolUse: \"postToolUse\",\n agentSpawn: \"agentSpawn\",\n userPromptSubmit: \"userPromptSubmit\",\n stop: \"stop\",\n} as const;\n\n/**\n * Map canonical event names → Kiro's native hook event names. Only the events\n * Kiro supports are present; PreCompact / SessionEnd / Notification have no Kiro\n * equivalent and are reported as a warn/skip at install time.\n */\nconst EVENT_MAP: Partial<Record<HookEventName, string>> = {\n PreToolUse: KIRO_EVENT.preToolUse,\n PostToolUse: KIRO_EVENT.postToolUse,\n SessionStart: KIRO_EVENT.agentSpawn,\n UserPromptSubmit: KIRO_EVENT.userPromptSubmit,\n Stop: KIRO_EVENT.stop,\n};\n\n/** A single Kiro native hook registration entry (Claude-shaped, nested). */\ninterface KiroHookEntry {\n matcher: string;\n hooks: Array<{ type: \"command\"; command: string }>;\n}\n\n/** The shape of a Kiro agent file (only the parts we touch). */\ninterface KiroAgentFile {\n hooks?: Record<string, KiroHookEntry[]>;\n [key: string]: unknown;\n}\n\n/** The shape of Kiro's mcp.json (only the parts we touch). */\ninterface KiroMcpFile {\n mcpServers?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\n/** Native MCP server entry shapes Kiro accepts under `mcpServers`. */\ninterface KiroStdioServer {\n command: string;\n args?: string[];\n env?: Record<string, string>;\n cwd?: string;\n}\ninterface KiroHttpServer {\n url: string;\n headers?: Record<string, string>;\n}\n\n/** Raw Kiro CLI hook stdin payload (snake_case wire fields). */\ninterface KiroWireInput {\n connector?: unknown;\n hook_event_name?: string;\n cwd?: string;\n session_id?: string;\n tool_name?: string;\n tool_input?: Record<string, unknown>;\n tool_response?: unknown;\n source?: string;\n prompt?: string;\n stop_hook_active?: boolean;\n}\n\nexport class KiroAdapter extends BaseAdapter implements Adapter {\n readonly id: PlatformId = HOST;\n readonly name = \"Kiro\";\n readonly paradigm: HookParadigm = \"json-stdio\";\n\n readonly capabilities: PlatformCapabilities = {\n // Memory surface: AGENTS.md-first managed block (project <projectDir>/AGENTS.md\n // via the base default — always included, no inclusion modes; user scope →\n // ~/.kiro/steering/agent-connector.md below).\n supportsMemory: true,\n preToolUse: true,\n postToolUse: true,\n preCompact: false,\n sessionStart: true,\n sessionEnd: false,\n // Kiro fires userPromptSubmit and stop, but it has no PreCompact /\n // SessionEnd / Notification equivalent.\n userPromptSubmit: true,\n stop: true,\n notification: false,\n // Newer events: Kiro's native set (agentSpawn / userPromptSubmit /\n // preToolUse / postToolUse / stop) has no permission-dialog, tool-failure,\n // or subagent lifecycle events, so permissionRequest / postToolUseFailure /\n // subagentStart / subagentStop stay unset — install reports the standard\n // skip-warn for them.\n // Kiro's hook protocol is exit-code only — a hook can allow (0), block (2),\n // or inject agentSpawn context, but it CANNOT rewrite tool args or output.\n canModifyArgs: false,\n canModifyOutput: false,\n // agentSpawn returns additionalContext via JSON stdout.\n canInjectSessionContext: true,\n transports: [\"stdio\", \"http\"],\n };\n\n // ── Detection ────────────────────────────────────────────────────────────\n\n detectInstalled(projectDir: string): DetectedPlatform {\n const userDir = join(homedir(), \".kiro\");\n const userMcp = this.userMcpPath();\n const projectDirKiro = join(projectDir, \".kiro\");\n const projectMcp = this.projectMcpPath(projectDir);\n\n const userInstalled = existsSync(userDir) || existsSync(userMcp);\n const projInstalled = existsSync(projectDirKiro) || existsSync(projectMcp);\n const installed = userInstalled || projInstalled;\n // Report the scope/path that actually matched, so a project-only install\n // isn't misreported as a (non-existent) user install.\n const scope = projInstalled && !userInstalled ? \"project\" : \"user\";\n const configPath = scope === \"project\" ? projectMcp : userMcp;\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 Kiro config at ${projectMcp}`\n : `found Kiro config under ${userDir}`\n : `no Kiro config at ${userDir}`,\n confidence: installed ? \"high\" : \"low\",\n };\n }\n\n // ── Memory surface: global steering dir at user scope ───────────────────\n // Project scope stays on the AGENTS.md base default (workspace-root\n // AGENTS.md is always included, with no inclusion modes). User scope targets\n // a dedicated agent-connector.md in Kiro's documented ~/.kiro/steering/ dir\n // (default-always inclusion; AC-created → cleanly deletable on uninstall).\n protected override memoryTargets(ctx: InstallContext): MemoryTarget[] {\n if (this.memoryOverride(ctx)?.path || ctx.scope !== \"user\") {\n return super.memoryTargets(ctx);\n }\n return [\n {\n path: join(homedir(), \".kiro\", \"steering\", \"agent-connector.md\"),\n reason: \"kiro global steering dir (~/.kiro/steering; agent-connector-owned file)\",\n },\n ];\n }\n\n // ── Native paths ─────────────────────────────────────────────────────────\n\n getConfigDir(ctx: InstallContext): string {\n return ctx.scope === \"project\"\n ? join(ctx.projectDir, \".kiro\")\n : join(homedir(), \".kiro\");\n }\n\n /** MCP servers live in mcp.json under the scope's `.kiro/settings/`. */\n getServerConfigPath(ctx: InstallContext): string {\n return ctx.scope === \"project\"\n ? this.projectMcpPath(ctx.projectDir)\n : this.userMcpPath();\n }\n\n /**\n * Hooks live in an AGENT file, NOT a settings file. Kiro auto-loads the\n * built-in default agent (`kiro_default`) for a new chat session, so we always\n * register hooks on the user-scope default agent — that is the agent Kiro\n * actually loads regardless of install scope.\n */\n getHookConfigPath(_ctx: InstallContext): string {\n return join(homedir(), \".kiro\", \"agents\", DEFAULT_AGENT_FILE);\n }\n\n private userMcpPath(): string {\n return join(homedir(), \".kiro\", \"settings\", \"mcp.json\");\n }\n\n private projectMcpPath(projectDir: string): string {\n return join(projectDir, \".kiro\", \"settings\", \"mcp.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 kiro\"\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 Kiro's native mcpServers entry. */\n private renderServerEntry(\n ctx: InstallContext,\n server: ServerDef,\n ): KiroStdioServer | KiroHttpServer {\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 // Kiro documents no native interpolation token, so resolve every\n // ${env:VAR} to a literal at install time.\n const entry: KiroStdioServer = { command: resolveEnvRefsDeep(command) };\n if (args.length > 0) entry.args = resolveEnvRefsDeep(args);\n const env = this.renderEnv(server.env);\n if (env) entry.env = env;\n if (server.cwd) entry.cwd = resolveEnvRefsDeep(server.cwd);\n return entry;\n }\n\n // http (and any other remote transport) — Kiro registers a URL.\n const entry: KiroHttpServer = { url: resolveEnvRefsDeep(server.url ?? \"\") };\n const headers = this.renderEnv(server.headers);\n if (headers) entry.headers = headers;\n return entry;\n }\n\n /**\n * Render env/header values. Kiro documents no native interpolation token, so\n * resolve `${env:VAR}` references to literals at install time.\n */\n private renderEnv(\n env: Record<string, string> | undefined,\n ): Record<string, string> | undefined {\n if (!env || Object.keys(env).length === 0) return undefined;\n return resolveEnvRefsDeep({ ...env });\n }\n\n // ── Hook install / uninstall (merge into the agent file) ─────────────────\n\n installHooks(ctx: InstallContext): ChangeRecord[] {\n const { connector } = ctx;\n if (connector.platforms[HOST]?.hooks === false) {\n return [{ platform: this.id, action: \"skip\", detail: \"hooks disabled for kiro\" }];\n }\n if (connector.hookEvents.length === 0) {\n return [{ platform: this.id, action: \"skip\", detail: \"connector declares no hooks\" }];\n }\n\n const agentPath = this.getHookConfigPath(ctx);\n // Merge into the existing agent JSON; create a minimal agent object if absent.\n const agent = this.readJson<KiroAgentFile>(agentPath) ?? {};\n const hooks = (agent.hooks ??= {});\n\n const changes: ChangeRecord[] = [];\n let mutated = false;\n\n for (const event of connector.hookEvents) {\n const kiroEvent = EVENT_MAP[event];\n if (!kiroEvent) {\n // No Kiro equivalent for this canonical event — report and continue.\n changes.push({\n platform: this.id,\n action: \"warn\",\n path: agentPath,\n detail: `${event} has no Kiro hook equivalent — skipped`,\n });\n continue;\n }\n\n const command = buildHomeBinHookCommand(ctx.homeBinPath, HOST, event, connector.id);\n const matcher = connector.hooks[event]?.matcher ?? \"\";\n const entry: KiroHookEntry = {\n matcher,\n hooks: [{ type: \"command\", command }],\n };\n\n const bucket = (hooks[kiroEvent] ??= []);\n const existingIdx = bucket.findIndex((e) => this.entryHasOurCommand(e, ctx));\n\n if (existingIdx >= 0) {\n if (JSON.stringify(bucket[existingIdx]) === JSON.stringify(entry)) {\n changes.push({\n platform: this.id,\n action: \"skip\",\n path: agentPath,\n detail: `hooks.${kiroEvent} already registered`,\n });\n continue;\n }\n bucket[existingIdx] = entry;\n changes.push({\n platform: this.id,\n action: \"update\",\n path: agentPath,\n detail: `hooks.${kiroEvent}`,\n });\n } else {\n bucket.push(entry);\n changes.push({\n platform: this.id,\n action: \"create\",\n path: agentPath,\n detail: `hooks.${kiroEvent}`,\n });\n }\n mutated = true;\n }\n\n if (mutated) this.writeJson(agentPath, agent, ctx.dryRun);\n return changes;\n }\n\n uninstallHooks(ctx: InstallContext): ChangeRecord[] {\n const agentPath = this.getHookConfigPath(ctx);\n const agent = this.readJson<KiroAgentFile>(agentPath);\n const hooks = agent?.hooks;\n if (!agent || !hooks) {\n return [\n {\n platform: this.id,\n action: \"skip\",\n path: agentPath,\n detail: \"no hooks section present\",\n },\n ];\n }\n\n const changes: ChangeRecord[] = [];\n let mutated = false;\n\n for (const kiroEvent of Object.keys(hooks)) {\n const bucket = hooks[kiroEvent];\n if (!Array.isArray(bucket)) continue;\n\n // Strip our hook command from each entry; drop entries left empty so we\n // never remove another connector's (or the user's own) hook commands.\n const next: KiroHookEntry[] = [];\n let removed = 0;\n for (const e of bucket) {\n const innerBefore = e.hooks?.length ?? 0;\n const inner = (e.hooks ?? []).filter((h) => !this.isOurCommand(h.command, ctx));\n removed += innerBefore - inner.length;\n if (inner.length > 0) next.push({ matcher: e.matcher ?? \"\", hooks: inner });\n }\n\n if (removed > 0) {\n if (next.length > 0) hooks[kiroEvent] = next;\n else delete hooks[kiroEvent];\n changes.push({\n platform: this.id,\n action: \"remove\",\n path: agentPath,\n detail: `hooks.${kiroEvent} (${removed})`,\n });\n mutated = true;\n }\n }\n\n if (mutated) this.writeJson(agentPath, agent, ctx.dryRun);\n if (changes.length === 0) {\n changes.push({\n platform: this.id,\n action: \"skip\",\n path: agentPath,\n detail: \"no matching hook entries\",\n });\n }\n return changes;\n }\n\n private entryHasOurCommand(entry: KiroHookEntry, ctx: InstallContext): boolean {\n return (entry.hooks ?? []).some((h) => this.isOurCommand(h.command, ctx));\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 mcpPath = this.getServerConfigPath(ctx);\n const agentPath = this.getHookConfigPath(ctx);\n const connectorId = ctx.connector.id;\n const homeBin = ctx.homeBinPath;\n const hookEvents = ctx.connector.hookEvents;\n return [\n {\n name: `${this.name}: mcp.json present`,\n check: () =>\n existsSync(mcpPath)\n ? { status: \"OK\", detail: mcpPath }\n : { status: \"FAIL\", detail: `not found: ${mcpPath}` },\n },\n {\n name: `${this.name}: server entry registered`,\n check: () => {\n // Only assert what the connector declares (same rule as the hook\n // check below): a server-less connector never writes an mcpServers\n // entry, so its absence is healthy.\n if (!ctx.connector.server) {\n return { status: \"OK\", detail: \"no MCP server declared\" };\n }\n const cfg = this.readJson<KiroMcpFile>(mcpPath);\n const bucket = cfg?.mcpServers;\n if (!cfg || !bucket) {\n return { status: \"FAIL\", detail: `no ${MCP_ROOT_KEY} in ${mcpPath}` };\n }\n return connectorId in bucket\n ? { status: \"OK\", detail: `${MCP_ROOT_KEY}.${connectorId} present` }\n : { status: \"FAIL\", detail: `no ${MCP_ROOT_KEY}.${connectorId} in ${mcpPath}` };\n },\n },\n {\n name: `${this.name}: hook command registered`,\n check: () => {\n if (hookEvents.length === 0) {\n return { status: \"OK\", detail: \"no hooks declared\" };\n }\n const agent = this.readJson<KiroAgentFile>(agentPath);\n if (!agent) return { status: \"FAIL\", detail: `cannot read ${agentPath}` };\n const hooks = agent.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 : { status: \"FAIL\", detail: `no hook for ${connectorId} in ${agentPath}` };\n },\n },\n ];\n }\n\n // ── Runtime: parse Kiro stdin JSON → normalized event ────────────────────\n\n parseEvent(event: HookEventName, raw: unknown): NormalizedEvent {\n const input = (raw ?? {}) as KiroWireInput;\n const connectorId = typeof input.connector === \"string\" ? input.connector : \"\";\n const sessionId = typeof input.session_id === \"string\" ? input.session_id : \"\";\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 \"UserPromptSubmit\": {\n const ev: UserPromptSubmitEvent = {\n ...base,\n prompt: typeof input.prompt === \"string\" ? input.prompt : \"\",\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 default: {\n // Kiro never delivers PreCompact / SessionEnd / Notification nor the\n // newer PermissionRequest / PostToolUseFailure / SubagentStart /\n // SubagentStop (no native equivalents). If the runtime dispatches one\n // anyway, surface it loudly rather than silently mis-parse.\n throw new Error(`unsupported kiro hook event: ${String(event)}`);\n }\n }\n }\n\n // ── Runtime: normalized response → Kiro native (exit-code) hook reply ─────\n\n formatReply(event: HookEventName, response: HookResponse): HookReply {\n const decision = response.decision ?? \"allow\";\n\n // deny → block the action: exit 2 with the reason on stderr.\n if (decision === \"deny\") {\n return { exitCode: 2, stderr: response.reason ?? \"Blocked by hook\" };\n }\n\n // ask → Kiro has no native \"ask\"; degrade to deny (exit 2) to stay fail-safe.\n if (decision === \"ask\") {\n return {\n exitCode: 2,\n stderr: response.reason ?? \"Action requires user confirmation (security policy)\",\n };\n }\n\n // Stop → exit-code only (deny already handled above as exit 2). There is no\n // context/additionalContext channel on a Stop hook, so anything non-deny\n // passes through with exit 0 (do not fall into the agentSpawn branch).\n if (event === \"Stop\") {\n return { exitCode: 0 };\n }\n\n // context → inject soft guidance. Kiro reads agentSpawn additionalContext\n // from stdout JSON (mirrors the Claude SessionStart shape). exit 0 = allow.\n if (decision === \"context\" && response.additionalContext) {\n return {\n exitCode: 0,\n stdout: JSON.stringify({\n hookSpecificOutput: {\n hookEventName: KIRO_EVENT.agentSpawn,\n additionalContext: response.additionalContext,\n },\n }),\n };\n }\n\n // modify is unsupported on Kiro (exit-code protocol — cannot rewrite\n // args/output); allow / void → pass through with exit 0.\n return { exitCode: 0 };\n }\n}\n\n/** Coerce a Kiro PostToolUse `tool_response` into a string for the normalized event. */\nfunction toolResponseToString(value: unknown): string | undefined {\n if (value == null) return undefined;\n if (typeof value === \"string\") return value;\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\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 KiroAdapter();\nexport default adapter;\n"],"mappings":";;;;;;;;;;;;;;;;;;AA4CA,SAAS,kBAAkB;AAC3B,SAAS,eAAe;AACxB,SAAS,YAAY;AA6BrB,IAAM,OAAmB;AACzB,IAAM,eAAe;AAGrB,IAAM,qBAAqB;AAM3B,IAAM,aAAa;AAAA,EACjB,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,YAAY;AAAA,EACZ,kBAAkB;AAAA,EAClB,MAAM;AACR;AAOA,IAAM,YAAoD;AAAA,EACxD,YAAY,WAAW;AAAA,EACvB,aAAa,WAAW;AAAA,EACxB,cA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,YAAY;AACvC,IAAO,eAAQ;","names":["entry"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/cli/commands/package.ts","../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 * cli/commands/package — emit a marketplace/extension-installable connector bundle.\n *\n * Resolves the connector config (--connector <path>, else findConnectorConfig\n * walking up from the project dir, exactly like install.ts), packages it for the\n * requested --format into --out (default <cwd>/dist-plugin), then prints the\n * emitted file tree plus per-format install instructions.\n *\n * `--format <x>` accepts the full union; `--format all` emits EVERY feasible\n * format, each into <out>/<format>/..., printing install instructions per format.\n * Default --format claude-plugin.\n */\n\nimport { parseArgs } from \"node:util\";\nimport { join, relative } from \"node:path\";\n\nimport { findConnectorConfig, loadConnectorFromPath } from \"../../core/load-connector.js\";\nimport {\n ALL_FORMATS,\n FEASIBLE_FORMATS,\n isPackageFormat,\n packageConnector,\n packageConnectorAll,\n type PackageFormat,\n type PackageResult,\n} from \"../../core/package.js\";\nimport { fail, print } from \"../app.js\";\n\nconst HELP = `agent-connector package — emit a plugin/extension/marketplace bundle.\n\nusage: agent-connector package [flags]\n\nflags:\n --connector <path> Connector config to package (else auto-discovered).\n --format <fmt> Output format (default: claude-plugin). One of:\n ${ALL_FORMATS.join(\", \")}\n or \"all\" to emit every feasible format into <out>/<fmt>/.\n --out <dir> Output directory. Default: <cwd>/dist-plugin.\n --project <dir> Project root for connector discovery (default: cwd).\n --dry-run Compute the file tree without writing anything.\n --help Show this help.`;\n\n/** Print the file tree + the per-format install instructions for one bundle. */\nfunction printFormatResult(\n format: PackageFormat,\n connectorId: string,\n outDir: string,\n result: PackageResult,\n): void {\n print(` pluginDir: ${result.pluginDir}`);\n if (result.marketplacePath) {\n print(` marketplace: ${relative(outDir, result.marketplacePath)}`);\n }\n print(\" emitted files:\");\n for (const f of result.files) {\n print(` + ${relative(outDir, f)}`);\n }\n if (result.notes && result.notes.length > 0) {\n print(\" notes:\");\n for (const n of result.notes) print(` ! ${n}`);\n }\n print(\" install:\");\n for (const line of installInstructions(format, connectorId, outDir)) {\n print(` ${line}`);\n }\n print(\"\");\n}\n\n/** Per-format install commands (the accurate two-step add+install where applicable). */\nfunction 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\nexport async function run(argv: string[]): Promise<number> {\n const { values } = parseArgs({\n args: argv,\n options: {\n connector: { type: \"string\" },\n format: { type: \"string\", default: \"claude-plugin\" },\n out: { type: \"string\" },\n project: { type: \"string\" },\n \"dry-run\": { type: \"boolean\", default: false },\n help: { type: \"boolean\", default: false },\n },\n allowPositionals: false,\n });\n\n if (values.help) {\n print(HELP);\n return 0;\n }\n\n const formatArg = values.format ?? \"claude-plugin\";\n const isAll = formatArg === \"all\";\n if (!isAll && !isPackageFormat(formatArg)) {\n return fail(\n `invalid --format \"${formatArg}\" (expected one of: ${ALL_FORMATS.join(\", \")}, or \"all\")`,\n );\n }\n\n const projectDir = values.project ?? process.cwd();\n const configPath = values.connector ?? findConnectorConfig(projectDir);\n if (!configPath) {\n return fail(\n \"no connector config found. Pass --connector <path> or add an \" +\n \"agent-connector.config.{mjs,js,json} to your project.\",\n );\n }\n\n const outDir = values.out ?? `${process.cwd()}/dist-plugin`;\n const dryRun = values[\"dry-run\"];\n const mode = dryRun ? \" (dry-run — nothing written)\" : \"\";\n\n const { connector } = await loadConnectorFromPath(configPath);\n\n if (isAll) {\n print(`package \"${connector.id}\" → all formats${mode}`);\n print(` outDir: ${outDir}`);\n print(\"\");\n const results = packageConnectorAll(connector, { outDir, dryRun });\n for (const { format, result } of results) {\n const formatOut = join(outDir, format);\n print(`── ${format} ──`);\n printFormatResult(format, connector.id, formatOut, result);\n }\n print(`emitted ${results.length} formats: ${FEASIBLE_FORMATS.join(\", \")}`);\n return 0;\n }\n\n const format: PackageFormat = formatArg;\n let result: PackageResult;\n try {\n result = packageConnector(connector, { outDir, format, dryRun });\n } catch (err) {\n // Emitter validation errors (e.g. mcp-server-json without\n // publish.registryNamespace) are actionable one-liners — print them as a\n // normal CLI error, never a stack trace.\n const message = err instanceof Error ? err.message : String(err);\n return fail(message);\n }\n\n print(`package \"${connector.id}\" → ${format}${mode}`);\n print(` outDir: ${outDir}`);\n print(\"\");\n printFormatResult(format, connector.id, outDir, result);\n return 0;\n}\n","/**\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 { 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/** 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>/.codex-plugin/marketplace.json (same object-owner catalog).\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: { dir: \".codex-plugin\", file: \"marketplace.json\", shape: \"claude\" },\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/hooks.json keyed { hooks:{ <Event>:[{matcher,hooks:[{type,command}]}] } }.\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/hooks.json ──────────────────────────────────────────────────────\n const hooksJson = buildClaudeHooksJson(connector, ctx.homeBinPath, PLATFORM);\n if (hooksJson) emit(join(pluginDir, \"hooks\", \"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 \"## 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(ctx.outDir, \"README.md\"), recipeReadme(connector));\n return { files: emitter.files, pluginDir: ctx.outDir, notes };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaA,SAAS,iBAAiB;AAC1B,SAAS,QAAAA,OAAM,YAAAC,iBAAgB;;;ACa/B,SAAS,cAAAC,aAAY,oBAAoB;AACzC,SAAS,WAAAC,gBAAe;;;ACTxB,SAAS,YAAY;;;ACFrB,SAAS,SAAS,UAAU,SAAS,WAAW;AAChD,SAAS,qBAAqB;AAuDvB,SAAS,cAAc,QAA0B;AACtD,QAAM,QAAkB,CAAC;AACzB,SAAO;AAAA,IACL;AAAA,IACA,KAAK,MAAc,UAAwB;AACzC,UAAI,CAAC,QAAQ;AACX,kB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kBA,SAAQ,UAAU,IAAI,WAAWC,OAAM;AAAA,IAC3D;AACA,UAAM,WAAW,QAAQ,MAAM,aAAa,iBAAiB,KAAK,IAAI,CAAC,EAAE;AACzE,WAAO;AAAA,EACT;AAEA,QAAM,SAAwB;AAC9B,MAAI;AACJ,MAAI;AACF,aAAS,iBAAiB,WAAW,EAAE,QAAQ,QAAQ,OAAO,CAAC;AAAA,EACjE,SAAS,KAAK;AAIZ,UAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC/D,WAAO,KAAK,OAAO;AAAA,EACrB;AAEA,QAAM,YAAY,UAAU,EAAE,YAAO,MAAM,GAAG,IAAI,EAAE;AACpD,QAAM,aAAa,MAAM,EAAE;AAC3B,QAAM,EAAE;AACR,oBAAkB,QAAQ,UAAU,IAAI,QAAQ,MAAM;AACtD,SAAO;AACT;","names":["join","relative","existsSync","resolve","join","buildManifest","buildMarketplace","join","join","SPECS","buildManifest","join","join","PLATFORM","buildManifest","join","join","PLATFORM","buildManifest","join","join","join","resolve","resolve","resolve","resolve","resolve","relative","join","format","result"]}