@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
279 lines • 13.7 kB
JavaScript
import { existsSync, readFileSync } from "node:fs";
import { formatResultText } from "../ask-user/format.js";
import { ASK_USER_ASKED_EVENT, ASK_USER_SETTLED_EVENT, } from "../ask-user/notify.js";
import { registerHooksCommand } from "./command.js";
import { loadHookConfigSources, loadHookConfigSourcesAsync } from "./config-loader.js";
import { dispatchHookEvent, runningHookHandlersStatusLabel } from "./dispatcher.js";
import { buildNotificationHookInput, buildPostCompactHookInput, buildPreCompactHookInput, buildSessionStartHookInput, dispatchLifecycleHookEvent, dispatchNotificationHookEvent, notificationResultDetails, postCompactResultDetails, preCompactResultDetails, recordLifecycleHookResult, sessionBeforeCompactResult, sessionStartResultDetails, } from "./lifecycle-adapter.js";
import { appendSystemMessages, buildUserPromptHookInput, formatPromptContextMessage, HOOK_CUSTOM_MESSAGE_TYPE, promptBlockReasonFromResult, promptContextFromResult, safeDiagnosticDetails, } from "./prompt-adapter.js";
import { registerStopLifecycle } from "./stop-lifecycle.js";
import { applyPostToolUseResult, applyPreToolUseResult, buildPostToolUseHookInput, buildPreToolUseHookInput, toolContextsFromResult, } from "./tool-adapter.js";
import { emptyHookTrustState } from "./trust.js";
import { FileHookStateStorage } from "./trust-storage.js";
export { parseHookConfig } from "./schema.js";
export default function hooksExtension(pi) {
const pendingPromptContexts = [];
const pendingPreToolContexts = new Map();
const refreshState = (ctx) => {
const sources = ctx.getLoadedHookSources?.() ?? fallbackHookSources(ctx.cwd);
const parsed = loadHookConfigSources({
agentDir: sources.agentDir,
cwd: sources.cwd,
fileSystem: {
readTextFile(path) {
return existsSync(path) ? readFileSync(path, "utf-8") : undefined;
},
},
globalHookSourcePaths: sources.globalHookSourcePaths,
globalHooksPath: sources.globalHooksPath,
globalSettingsHooks: sources.globalSettingsHooks,
preSessionHookSourcePaths: sources.preSessionHookSourcePaths,
projectHookSourcePaths: sources.projectHookSourcePaths,
projectHooksPath: sources.projectHooksPath,
projectSettingsHooks: sources.projectSettingsHooks,
runtimeHookSourcePaths: sources.runtimeHookSourcePaths,
});
const storage = new FileHookStateStorage({ agentDir: sources.agentDir, cwd: sources.cwd });
const trust = mergeTrustStates(storage.read("global"), ctx.isProjectTrusted() ? storage.read("project") : emptyHookTrustState());
return { parsed, trust, storage };
};
const stopLifecycle = registerStopLifecycle(pi, { refreshState });
for (const channel of [ASK_USER_ASKED_EVENT, ASK_USER_SETTLED_EVENT]) {
pi.events.on(channel, async (data) => {
const event = data;
const { ctx, request, variant } = event;
const response = "response" in event ? event.response : undefined;
const headers = request.questions.map((question) => question.header).join(", ");
// Capture session identity before asynchronous I/O or a session switch.
const input = buildNotificationHookInput({
kind: response === undefined
? "ask-user-asked"
: response.status === "timed_out"
? "ask-user-timeout"
: "ask-user-settled",
message: response === undefined
? `Question asked (${headers})`
: response.status === "timed_out"
? `Question timed out (${headers}): ${formatResultText(variant, response, request.questions, request.required === true)}`
: `Question ${response.status} (${headers})`,
requestId: request.requestId,
source: "ask-user",
status: response?.status ?? "pending",
title: headers,
}, ctx);
const sources = ctx.getLoadedHookSources?.() ?? fallbackHookSources(ctx.cwd);
const parsed = await loadHookConfigSourcesAsync(sources);
const handlers = parsed.executableHandlers.filter((handler) => handler.event === "Notification");
if (handlers.length === 0)
return;
const storage = new FileHookStateStorage({ agentDir: sources.agentDir, cwd: sources.cwd });
const [globalTrust, projectTrust] = await Promise.all([
storage.readAsync("global"),
ctx.isProjectTrusted() ? storage.readAsync("project") : emptyHookTrustState(),
]);
const result = await dispatchNotificationHookEvent({
cwd: ctx.cwd,
handlers,
input,
...(ctx.signal === undefined ? {} : { signal: ctx.signal }),
trustState: mergeTrustStates(globalTrust, projectTrust),
});
const details = notificationResultDetails(result);
recordLifecycleHookResult(pi, "Notification", {
...details,
diagnostics: [...parsed.diagnostics, ...details.diagnostics],
});
});
}
pi.on("session_start", async (event, ctx) => {
const state = refreshState(ctx);
const input = buildSessionStartHookInput(event, ctx);
const result = await dispatchLifecycleHookEvent({
cwd: ctx.cwd,
handlers: state.parsed.executableHandlers,
input,
matcherInputs: ["SessionStart", event.reason],
...(ctx.signal === undefined ? {} : { signal: ctx.signal }),
trustState: state.trust,
});
recordLifecycleHookResult(pi, "SessionStart", sessionStartResultDetails(result));
});
pi.on("input", async (event, ctx) => {
if (event.source === "extension")
return undefined;
stopLifecycle.resetTurn();
pendingPromptContexts.splice(0);
const state = refreshState(ctx);
const input = buildUserPromptHookInput({
cwd: ctx.cwd,
permissionMode: "default",
prompt: event.text,
sessionId: ctx.sessionManager.getSessionId(),
transcriptPath: ctx.sessionManager.getSessionFile(),
});
const result = await dispatchHookEvent({
cwd: ctx.cwd,
handlers: state.parsed.executableHandlers,
input,
signal: ctx.signal,
trustOptions: { platform: process.platform },
trustState: state.trust,
});
if (result.decision.kind === "block") {
const reason = promptBlockReasonFromResult(result);
ctx.ui.notify(reason, "warning");
pi.sendMessage({
customType: HOOK_CUSTOM_MESSAGE_TYPE,
content: reason,
display: false,
details: {
decision: "block",
event: "UserPromptSubmit",
sourcePath: result.decision.source.sourcePath,
},
}, { triggerTurn: false });
return { action: "handled" };
}
if (ctx.isIdle()) {
const pending = promptContextFromResult(result);
if (pending !== undefined) {
pendingPromptContexts.push(pending);
}
}
return { action: "continue" };
});
const onBeforeAgentStart = async (event) => {
// UserPromptSubmit context belongs to the prompt that queued it, never to a preview.
if (event.preview === true)
return undefined;
const pending = pendingPromptContexts.shift();
if (pending === undefined)
return undefined;
const messageContent = formatPromptContextMessage(pending);
const systemPrompt = appendSystemMessages(event.systemPrompt, pending.systemMessages);
if (messageContent === undefined && systemPrompt === event.systemPrompt)
return undefined;
const result = {};
if (messageContent !== undefined) {
result.message = {
customType: HOOK_CUSTOM_MESSAGE_TYPE,
content: messageContent,
display: false,
details: {
event: "UserPromptSubmit",
diagnostics: pending.diagnostics.map(safeDiagnosticDetails),
},
};
}
if (systemPrompt !== event.systemPrompt) {
result.systemPrompt = systemPrompt;
// Per-prompt hook output differs between turns and sessions; keep it behind the cached prefix (senpi#4447).
result.systemPromptCache = "volatile";
}
return result;
};
pi.on("before_agent_start", onBeforeAgentStart, { previewSafe: true });
pi.on("tool_call", async (event, ctx) => {
pendingPreToolContexts.delete(event.toolCallId);
const state = refreshState(ctx);
// A runtime without a session (a hand, S27a) cannot give tool hooks their session input; with any configured it
// refuses the call rather than run the tool past them (fail-closed). Forwarding them to the session is S29's.
if (ctx.sessionManager === undefined) {
const toolHooks = state.parsed.executableHandlers.filter((handler) => handler.event === "PreToolUse" || handler.event === "PostToolUse");
return toolHooks.length === 0
? undefined
: { block: true, reason: "Tool hooks are configured, and this runtime has no session to run them with." };
}
const result = await dispatchHookEvent({
cwd: ctx.cwd,
handlers: state.parsed.executableHandlers,
input: buildPreToolUseHookInput(event, ctx),
onRunningHandlersChange: (running) => {
if (running.length === 0)
return;
ctx.updateToolHookStatus?.(runningHookHandlersStatusLabel(running));
},
signal: ctx.signal,
trustOptions: { platform: process.platform },
trustState: state.trust,
});
const toolResult = applyPreToolUseResult(event, result);
if (toolResult?.block) {
pendingPreToolContexts.delete(event.toolCallId);
return toolResult;
}
const contexts = toolContextsFromResult(result);
if (contexts.length > 0) {
pendingPreToolContexts.set(event.toolCallId, contexts);
}
return toolResult;
});
pi.on("tool_result", async (event, ctx) => {
const preToolContexts = pendingPreToolContexts.get(event.toolCallId) ?? [];
pendingPreToolContexts.delete(event.toolCallId);
if (ctx.sessionManager === undefined)
return undefined;
const state = refreshState(ctx);
const result = await dispatchHookEvent({
cwd: ctx.cwd,
handlers: state.parsed.executableHandlers,
input: buildPostToolUseHookInput(event, ctx),
onRunningHandlersChange: (running) => {
if (running.length === 0)
return;
ctx.updateToolHookStatus?.(runningHookHandlersStatusLabel(running));
},
signal: ctx.signal,
trustOptions: { platform: process.platform },
trustState: state.trust,
});
return applyPostToolUseResult(event, result, preToolContexts);
});
pi.on("session_before_compact", async (event, ctx) => {
const state = refreshState(ctx);
const result = await dispatchLifecycleHookEvent({
cwd: ctx.cwd,
handlers: state.parsed.executableHandlers,
input: buildPreCompactHookInput(event, ctx),
matcherInputs: ["PreCompact", event.reason],
signal: event.signal,
trustState: state.trust,
});
const details = preCompactResultDetails(result);
recordLifecycleHookResult(pi, "PreCompact", details, { compactionRequestId: event.requestId });
return sessionBeforeCompactResult(details);
});
pi.on("session_compact", async (event, ctx) => {
if (!event.accepted)
return undefined;
const state = refreshState(ctx);
const result = await dispatchLifecycleHookEvent({
cwd: ctx.cwd,
handlers: state.parsed.executableHandlers,
input: buildPostCompactHookInput(event, ctx),
matcherInputs: ["PostCompact", event.reason],
...(ctx.signal === undefined ? {} : { signal: ctx.signal }),
trustState: state.trust,
});
recordLifecycleHookResult(pi, "PostCompact", postCompactResultDetails(result));
return undefined;
});
registerHooksCommand(pi, refreshState);
}
function mergeTrustStates(globalState, projectState) {
return { version: 1, hooks: { ...globalState.hooks, ...projectState.hooks } };
}
function fallbackHookSources(cwd) {
return {
agentDir: cwd,
cwd,
globalHookSourcePaths: [],
globalHooksPath: `${cwd}/hooks.json`,
preSessionHookSourcePaths: [],
projectHookSourcePaths: [],
projectHooksPath: `${cwd}/.senpi/hooks.json`,
runtimeHookSourcePaths: [],
};
}
export { SUPPORTED_HOOK_EVENTS, UNSUPPORTED_HANDLER_TYPES, UNSUPPORTED_KNOWN_HOOK_EVENTS, } from "./types.js";
//# sourceMappingURL=index.js.map