{"version":3,"file":"hooks-bridge.d.ts","sourceRoot":"","sources":["../../../../src/core/extensions/plugins/hooks-bridge.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAGH,OAAO,KAAK,EAAE,YAAY,EAAkC,MAAM,aAAa,CAAC;AAChF,OAAO,KAAK,EAA6C,iBAAiB,EAAE,MAAM,eAAe,CAAC;AA4FlG;;;GAGG;AACH,wBAAgB,kBAAkB,CACjC,GAAG,EAAE,YAAY,EACjB,KAAK,EAAE,iBAAiB,EACxB,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAC5B,OAAO,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,GAChC,IAAI,CAoGN","sourcesContent":["/**\n * Hooks bridge — runs Claude Code / native-plugin shell hooks against hoocode events.\n *\n * Claude Code hooks are shell commands wired to named events and matched by tool\n * name. hoocode hooks are TypeScript handlers on the {@link ExtensionEvent} union.\n * This bridge registers handlers that shell out per the hook protocol and translate\n * stdin JSON + exit codes + stdout JSON back into hoocode result objects.\n *\n * Protocol (faithful to Claude Code):\n *  - Input: a JSON object on stdin describing the event.\n *  - Exit 0: success. stdout may carry a JSON decision; for prompt/session events\n *    plain stdout is treated as additional context.\n *  - Exit 2: blocking error. stderr (or JSON `reason`) is the block reason.\n *  - Other non-zero: non-blocking error (logged, not surfaced to the model).\n *  - Optional stdout JSON: `{ decision: \"block\"|\"approve\", reason, permissionDecision }`.\n */\n\nimport { spawn } from \"node:child_process\";\nimport type { ExtensionAPI, ToolCallEvent, ToolResultEvent } from \"../types.js\";\nimport type { PluginHookCommand, PluginHookMatcherGroup, PluginHooksConfig } from \"./manifest.js\";\n\nconst DEFAULT_TIMEOUT_MS = 60_000;\n\ninterface HookRunResult {\n\texitCode: number;\n\tstdout: string;\n\tstderr: string;\n\tjson: { decision?: string; reason?: string; permissionDecision?: string; continue?: boolean } | undefined;\n}\n\n/** Run one shell hook command, piping `input` as JSON on stdin. */\nfunction runHookCommand(\n\tcmd: PluginHookCommand,\n\tinput: unknown,\n\troot: string,\n\tvars: Record<string, string>,\n): Promise<HookRunResult> {\n\treturn new Promise((resolve) => {\n\t\tconst child = spawn(cmd.command, {\n\t\t\tshell: true,\n\t\t\t// Every vendor spelling, so a hook written for either agent resolves:\n\t\t\t// the shell expands these, which is the hook-side equivalent of the\n\t\t\t// string substitution MCP configs get.\n\t\t\tenv: { ...process.env, ...vars },\n\t\t\tcwd: root,\n\t\t});\n\n\t\tlet stdout = \"\";\n\t\tlet stderr = \"\";\n\t\tconst timer = setTimeout(() => child.kill(\"SIGTERM\"), (cmd.timeout ?? DEFAULT_TIMEOUT_MS / 1000) * 1000);\n\t\ttimer.unref?.();\n\n\t\tchild.stdout.on(\"data\", (d) => {\n\t\t\tstdout += d.toString();\n\t\t});\n\t\tchild.stderr.on(\"data\", (d) => {\n\t\t\tstderr += d.toString();\n\t\t});\n\t\t// A hook that exits without draining stdin (block.sh, `exit 2`, any script\n\t\t// that ignores its input) makes the payload write below fail asynchronously.\n\t\t// stdin then emits EPIPE, which is fatal to the process if unhandled.\n\t\tchild.stdin.on(\"error\", () => {});\n\t\tchild.on(\"error\", () => {\n\t\t\tclearTimeout(timer);\n\t\t\tresolve({ exitCode: 1, stdout, stderr, json: undefined });\n\t\t});\n\t\tchild.on(\"close\", (code) => {\n\t\t\tclearTimeout(timer);\n\t\t\tlet json: HookRunResult[\"json\"];\n\t\t\tconst trimmed = stdout.trim();\n\t\t\tif (trimmed.startsWith(\"{\")) {\n\t\t\t\ttry {\n\t\t\t\t\tjson = JSON.parse(trimmed);\n\t\t\t\t} catch {\n\t\t\t\t\tjson = undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t\tresolve({ exitCode: code ?? 0, stdout, stderr, json });\n\t\t});\n\n\t\ttry {\n\t\t\tchild.stdin.write(JSON.stringify(input));\n\t\t\tchild.stdin.end();\n\t\t} catch {\n\t\t\t/* child already exited: the payload is best-effort, the exit code is not */\n\t\t}\n\t});\n}\n\n/** Empty / \"*\" matcher matches everything; otherwise treat as an anchored regex on the tool name. */\nfunction matcherMatches(matcher: string | undefined, toolName: string): boolean {\n\tif (!matcher || matcher === \"*\") return true;\n\ttry {\n\t\treturn new RegExp(`^(?:${matcher})$`).test(toolName);\n\t} catch {\n\t\treturn matcher === toolName;\n\t}\n}\n\nfunction groupsForTool(groups: PluginHookMatcherGroup[], toolName: string): PluginHookCommand[] {\n\tconst cmds: PluginHookCommand[] = [];\n\tfor (const g of groups) {\n\t\tif (matcherMatches(g.matcher, toolName)) cmds.push(...g.hooks);\n\t}\n\treturn cmds;\n}\n\nfunction allCommands(groups: PluginHookMatcherGroup[]): PluginHookCommand[] {\n\treturn groups.flatMap((g) => g.hooks);\n}\n\n/**\n * Register all hook events for one plugin against the ExtensionAPI.\n * `onError` reports non-blocking failures (kept off the model's path).\n */\nexport function installPluginHooks(\n\thoo: ExtensionAPI,\n\thooks: PluginHooksConfig,\n\troot: string,\n\tvars: Record<string, string>,\n\tonError: (message: string) => void,\n): void {\n\t// ── PreToolUse → tool_call (blocking) ────────────────────────────────────\n\tconst preGroups = hooks.PreToolUse;\n\tif (preGroups?.length) {\n\t\thoo.on(\"tool_call\", async (event: ToolCallEvent) => {\n\t\t\tconst cmds = groupsForTool(preGroups, event.toolName);\n\t\t\tfor (const cmd of cmds) {\n\t\t\t\tconst res = await runHookCommand(\n\t\t\t\t\tcmd,\n\t\t\t\t\t{ hook_event_name: \"PreToolUse\", tool_name: event.toolName, tool_input: event.input },\n\t\t\t\t\troot,\n\t\t\t\t\tvars,\n\t\t\t\t);\n\t\t\t\tconst decision = res.json?.decision ?? res.json?.permissionDecision;\n\t\t\t\tif (res.exitCode === 2 || decision === \"block\" || decision === \"deny\") {\n\t\t\t\t\treturn { block: true, reason: res.json?.reason || res.stderr.trim() || \"Blocked by plugin hook\" };\n\t\t\t\t}\n\t\t\t\tif (res.exitCode !== 0) onError(`PreToolUse hook failed (${res.exitCode}): ${res.stderr.trim()}`);\n\t\t\t}\n\t\t});\n\t}\n\n\t// ── PostToolUse → tool_result (best-effort) ──────────────────────────────\n\tconst postGroups = hooks.PostToolUse;\n\tif (postGroups?.length) {\n\t\thoo.on(\"tool_result\", async (event: ToolResultEvent) => {\n\t\t\tconst cmds = groupsForTool(postGroups, event.toolName);\n\t\t\tfor (const cmd of cmds) {\n\t\t\t\tconst res = await runHookCommand(\n\t\t\t\t\tcmd,\n\t\t\t\t\t{\n\t\t\t\t\t\thook_event_name: \"PostToolUse\",\n\t\t\t\t\t\ttool_name: event.toolName,\n\t\t\t\t\t\ttool_input: event.input,\n\t\t\t\t\t\ttool_response: event.content,\n\t\t\t\t\t},\n\t\t\t\t\troot,\n\t\t\t\t\tvars,\n\t\t\t\t);\n\t\t\t\tif (res.exitCode === 2 || res.json?.decision === \"block\") {\n\t\t\t\t\tconst reason = res.json?.reason || res.stderr.trim() || \"Flagged by plugin hook\";\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [...event.content, { type: \"text\" as const, text: `\\n[plugin hook] ${reason}` }],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (res.exitCode !== 0) onError(`PostToolUse hook failed (${res.exitCode}): ${res.stderr.trim()}`);\n\t\t\t}\n\t\t});\n\t}\n\n\t// ── UserPromptSubmit → before_agent_start (adds context) ─────────────────\n\tconst promptGroups = hooks.UserPromptSubmit;\n\tif (promptGroups?.length) {\n\t\thoo.on(\"before_agent_start\", async (event) => {\n\t\t\tlet systemPrompt = event.systemPrompt;\n\t\t\tfor (const cmd of allCommands(promptGroups)) {\n\t\t\t\tconst res = await runHookCommand(\n\t\t\t\t\tcmd,\n\t\t\t\t\t{ hook_event_name: \"UserPromptSubmit\", prompt: event.prompt },\n\t\t\t\t\troot,\n\t\t\t\t\tvars,\n\t\t\t\t);\n\t\t\t\tif (res.exitCode !== 0 && res.exitCode !== 2) {\n\t\t\t\t\tonError(`UserPromptSubmit hook failed (${res.exitCode}): ${res.stderr.trim()}`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst extra = res.exitCode === 2 ? res.stderr.trim() : res.json?.reason || res.stdout.trim();\n\t\t\t\tif (extra) systemPrompt = `${systemPrompt}\\n\\n<!-- plugin hook -->\\n${extra}`;\n\t\t\t}\n\t\t\treturn systemPrompt === event.systemPrompt ? undefined : { systemPrompt };\n\t\t});\n\t}\n\n\t// ── SessionStart → session_start (side effects) ──────────────────────────\n\tconst sessionGroups = hooks.SessionStart;\n\tif (sessionGroups?.length) {\n\t\thoo.on(\"session_start\", async (event) => {\n\t\t\tfor (const cmd of allCommands(sessionGroups)) {\n\t\t\t\tconst res = await runHookCommand(\n\t\t\t\t\tcmd,\n\t\t\t\t\t{ hook_event_name: \"SessionStart\", source: event.reason },\n\t\t\t\t\troot,\n\t\t\t\t\tvars,\n\t\t\t\t);\n\t\t\t\tif (res.exitCode !== 0) onError(`SessionStart hook failed (${res.exitCode}): ${res.stderr.trim()}`);\n\t\t\t}\n\t\t});\n\t}\n\n\t// ── Stop → agent_end (side effects) ──────────────────────────────────────\n\tconst stopGroups = hooks.Stop;\n\tif (stopGroups?.length) {\n\t\thoo.on(\"agent_end\", async () => {\n\t\t\tfor (const cmd of allCommands(stopGroups)) {\n\t\t\t\tconst res = await runHookCommand(cmd, { hook_event_name: \"Stop\" }, root, vars);\n\t\t\t\tif (res.exitCode !== 0) onError(`Stop hook failed (${res.exitCode}): ${res.stderr.trim()}`);\n\t\t\t}\n\t\t});\n\t}\n}\n"]}