UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

195 lines • 7.98 kB
import { stripAnsi } from "../../../../utils/ansi.js"; import { runCommandHook } from "./command-runner.js"; import { matchingHookHandlers } from "./matcher.js"; import { parseHookOutput } from "./output-parser.js"; import { validateHookHandlerSafety } from "./safety.js"; import { listHookTrustRecords } from "./trust.js"; export async function dispatchHookEvent(options) { const match = matchingHookHandlers(options.input, options.handlers); const ordered = declarationOrdered(match.handlers); const selected = selectExecutableHandlers(ordered, options.trustState, options.trustOptions); let nextCompletionIndex = 0; const runner = options.runCommand ?? runCommandHook; const notifyRunningChange = options.onRunningHandlersChange; const runningHandlers = []; const completed = await Promise.all(selected.runnable.map(async ({ handler, declarationIndex }) => { if (notifyRunningChange !== undefined) { runningHandlers.push(handler); notifyRunningChange([...runningHandlers]); } try { const run = await runner(handler, options.input, { cwd: options.cwd, ...(options.envPassthrough === undefined ? {} : { envPassthrough: options.envPassthrough }), ...(options.outputPolicy === undefined ? {} : { outputPolicy: options.outputPolicy }), ...(options.signal === undefined ? {} : { signal: options.signal }), ...(options.sourceEnv === undefined ? {} : { sourceEnv: options.sourceEnv }), }); const parsed = parseHookOutput({ event: options.input.event, exitCode: run.exitCode ?? 1, source: handler.source, stderr: run.stderr, stdout: run.stdout, }); const completionIndex = nextCompletionIndex; nextCompletionIndex += 1; return { completionIndex, declarationIndex, handler, parsed, run }; } finally { if (notifyRunningChange !== undefined) { const runningIndex = runningHandlers.indexOf(handler); if (runningIndex !== -1) { runningHandlers.splice(runningIndex, 1); } notifyRunningChange([...runningHandlers]); } } })); const declarationSummaries = completed .toSorted((left, right) => left.declarationIndex - right.declarationIndex) .map((run) => ({ completionIndex: run.completionIndex, diagnostics: run.parsed.diagnostics, handler: run.handler, output: run.parsed.output, run: run.run, })); const diagnostics = [ ...match.diagnostics, ...selected.skipped.flatMap((skip) => skip.diagnostics), ...declarationSummaries.flatMap((summary) => summary.diagnostics), ]; return { decision: aggregateDecision(options.input.event, declarationSummaries), diagnostics, executableHandlers: selected.runnable.map((item) => item.handler), matchedHandlers: ordered.map((item) => item.handler), skipped: selected.skipped, summaries: declarationSummaries, }; } export function runningHookHandlersStatusLabel(handlers, platform = process.platform) { const label = handlers.map((handler) => hookHandlerStatusLabel(handler, platform)).join(" · "); return label.length <= 79 ? label : `${label.slice(0, 76)}...`; } function hookHandlerStatusLabel(handler, platform) { const raw = handler.config.statusMessage ?? (platform === "win32" && handler.config.commandWindows !== undefined ? handler.config.commandWindows : handler.config.command); return stripAnsi(raw) .replace(/[\r\n\t]+/g, " ") .replace(/[\u0000-\u001f\u007f]+/g, "") .replace(/\s+/g, " ") .trim(); } function declarationOrdered(handlers) { return handlers .map((handler, index) => ({ declarationIndex: index, handler })) .toSorted((left, right) => compareHandlers(left.handler, right.handler) || left.declarationIndex - right.declarationIndex); } function compareHandlers(left, right) { return (left.source.displayOrder - right.source.displayOrder || left.groupIndex - right.groupIndex || left.handlerIndex - right.handlerIndex); } function selectExecutableHandlers(handlers, trustState, trustOptions) { const records = listHookTrustRecords(handlers.map((item) => item.handler), trustState, trustOptions); const runnable = []; const skipped = []; for (const [index, item] of handlers.entries()) { const record = records[index]; if (record === undefined) continue; const safetyDiagnostics = validateHookHandlerSafety(item.handler); const unsafe = safetyDiagnostics.some((diagnostic) => diagnostic.severity === "error"); if (unsafe) { skipped.push({ diagnostics: safetyDiagnostics, handler: item.handler, reason: "unsafe", record }); continue; } if (!record.enabled) { skipped.push({ diagnostics: [], handler: item.handler, reason: "disabled", record }); continue; } if (!record.trusted) { skipped.push({ diagnostics: [], handler: item.handler, reason: "untrusted", record }); continue; } runnable.push({ ...item, record }); } return { runnable, skipped }; } function aggregateDecision(event, summaries) { switch (event) { case "PreToolUse": return aggregatePreToolUseDecision(summaries); case "PostToolUse": case "UserPromptSubmit": case "SessionStart": case "PreCompact": case "PostCompact": case "Stop": case "Notification": return aggregateBlockingDecision(summaries); } } function aggregatePreToolUseDecision(summaries) { const blocker = summaries.find(hasBlockingDecision); if (blocker !== undefined) { return decisionWithSource("block", blocker, blocker.output.reason); } const ask = summaries.find((summary) => summary.output.decision === "ask"); if (ask !== undefined) { const reason = ask.output.reason ?? "Hook requested manual approval."; return { fallback: { kind: "block", reason }, kind: "ask", nativeRepresentable: false, ...reasonField(ask.output.reason), source: ask.handler.source, sourceCommand: ask.handler.config.command, }; } let allowSummary; for (const summary of summaries) { if (summary.output.decision === "allow" || summary.output.decision === "approve") allowSummary = summary; } if (allowSummary !== undefined) { return decisionWithSource("allow", allowSummary, undefined, allowSummary.output.updatedInput); } return { kind: "none" }; } function aggregateBlockingDecision(summaries) { const blocker = summaries.find(hasBlockingDecision); if (blocker !== undefined) { return decisionWithSource("block", blocker, blocker.output.reason ?? blocker.output.stopReason); } return { kind: "none" }; } function hasBlockingDecision(summary) { return summary.output.decision === "block" || summary.output.decision === "deny"; } function decisionWithSource(kind, summary, reason, updatedInput) { return { kind, ...reasonField(reason), source: summary.handler.source, sourceCommand: summary.handler.config.command, ...updatedInputField(updatedInput), }; } function reasonField(reason) { if (reason === undefined) { return {}; } return { reason }; } function updatedInputField(updatedInput) { if (updatedInput === undefined) { return {}; } return { updatedInput }; } //# sourceMappingURL=dispatcher.js.map