peppa/packages/runner/src/hook.ts
2026-11-16 13:30:48 +05:00

436 lines
20 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// peppa-hook <event>: called by the Claude Code hooks in the per-run settings file
// (run-settings.ts), and as Codex's notify program (`peppa-hook codex-notify <json>`). Reads the hook JSON from stdin and updates the Peppa session that
// PEPPA_SESSION_ID / PEPPA_GENERATION point to. Must never break the Claude session:
// always exits 0, errors go to ~/.peppa/hook.log, and blocking hooks fall back to
// Claude's own terminal dialog when the PM doesn't answer in time.
import { asIs, m } from "@peppa/shared/i18n";
import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import {
answerQuestion,
describeStep,
recordStep,
describeUsage,
getAutonomy,
getBudgetState,
parseStatusLine,
recordStatusLine,
recordTranscriptUsage,
setDefaultActor,
transcriptUsage,
usageTotals,
getQuestion,
getReviewSettings,
latestReview,
pendingReview,
getPendingAccept,
sendReviewCard,
reviewNote,
reviewPreview,
reviewPreviewNote,
demoNote,
reviewRejections,
getSession,
getProject,
needsPerson,
reportProgress,
logSessionEvent,
peppaInputSentAt,
pendingSessionQuestions,
raiseSessionQuestion,
releaseHookQuestion,
updateSession,
type Question,
type SessionView,
} from "@peppa/core";
import { createDb, projects, tasks, type Db } from "@peppa/db";
import { eq } from "drizzle-orm";
import { peppaHome } from "@peppa/shared";
import { HOOK_WAIT_SEC, MAX_AUTO_NUDGES } from "./run-settings.ts";
import { recordLimit } from "./limits.ts";
interface HookInput {
session_id?: string;
transcript_path?: string;
hook_event_name?: string;
message?: string;
notification_type?: string;
prompt?: string;
reason?: string;
source?: string;
error?: string;
error_details?: string;
last_assistant_message?: string;
tool_name?: string;
tool_input?: Record<string, unknown>;
cwd?: string;
permission_suggestions?: unknown[];
}
interface AskQuestionItem {
question: string;
header?: string;
options?: Array<{ label: string; description?: string }>;
multiSelect?: boolean;
}
const LOG = join(peppaHome(), "hook.log");
const log = (msg: string) => {
try {
appendFileSync(LOG, `${new Date().toISOString()} ${msg}\n`);
} catch {}
};
const clip = (s: string, n = 1500) => (s.length > n ? `${s.slice(0, n)}…` : s);
const output = (o: unknown) => process.stdout.write(JSON.stringify(o));
/** Last assistant text from the transcript JSONL — fallback when the hook omits it. */
export function lastAssistantText(transcriptPath?: string): string | null {
if (!transcriptPath) return null;
try {
const lines = readFileSync(transcriptPath, "utf8").trimEnd().split("\n");
for (let i = lines.length - 1; i >= 0; i--) {
const entry = JSON.parse(lines[i]!);
if (entry.type !== "assistant") continue;
const content = entry.message?.content;
const text = Array.isArray(content)
? content.filter((c: { type: string }) => c.type === "text").map((c: { text: string }) => c.text).join("\n")
: typeof content === "string"
? content
: "";
if (text.trim()) return text.trim();
}
} catch (e) {
log(`transcript read failed: ${(e as Error).message}`);
}
return null;
}
/** Polls until every question is answered, or returns null after HOOK_WAIT_SEC. */
async function waitForAnswers(db: Db, ids: number[]): Promise<Question[] | null> {
const deadline = Date.now() + HOOK_WAIT_SEC * 1000;
while (Date.now() < deadline) {
const qs = await Promise.all(ids.map((id) => getQuestion(db, id)));
if (qs.every((q) => q.answeredAt)) return qs;
await new Promise((r) => setTimeout(r, 1500));
}
// Give up: answers that still arrive go to the terminal instead.
const settled = await Promise.all(ids.map((id) => releaseHookQuestion(db, id)));
return settled.every(Boolean) ? (settled as Question[]) : null;
}
function describeTool(name = "?", input: Record<string, unknown> = {}): string {
const main = input.command ?? input.file_path ?? input.url ?? input.pattern ?? input.prompt;
const detail = typeof main === "string" ? main : JSON.stringify(input);
return `${name}: ${clip(detail, 600)}${typeof input.description === "string" ? `\n(${input.description})` : ""}`;
}
async function permissionRequest(db: Db, s: SessionView, input: HookInput) {
await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() });
const q = await raiseSessionQuestion(
db,
s,
"permission",
m("Разрешить {tool}", { tool: describeTool(input.tool_name, input.tool_input) }),
["allow", "always", "deny"],
true,
);
const [answered] = (await waitForAnswers(db, [q.id])) ?? [];
if (!answered) return log(`permission #${q.id}: no answer in ${HOOK_WAIT_SEC}s, falling back to terminal`);
const a = answered.answer!.trim().toLowerCase();
await updateSession(db, s.id, { status: "running", lastActivityAt: new Date() });
if (a === "allow" || a === "always") {
output({
hookSpecificOutput: {
hookEventName: "PermissionRequest",
decision: {
behavior: "allow",
...(a === "always" && input.permission_suggestions?.length ? { updatedPermissions: input.permission_suggestions } : {}),
},
},
});
} else {
const reason = a === "deny" ? "PM запретил это действие." : `PM запретил это действие: ${answered.answer}`;
output({ hookSpecificOutput: { hookEventName: "PermissionRequest", decision: { behavior: "deny", message: reason } } });
}
}
/** Routes Claude's built-in AskUserQuestion to the PM and fills in the answers. */
async function askQuestion(db: Db, s: SessionView, input: HookInput) {
const items = (input.tool_input?.questions as AskQuestionItem[] | undefined) ?? [];
if (!items.length) return;
await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() });
const qs: Question[] = [];
for (const item of items) {
const opts = item.options?.map((o) => o.label);
const text = [item.question, ...(item.options ?? []).map((o) => `• ${o.label}${o.description ? ` — ${o.description}` : ""}`)].join("\n");
qs.push(await raiseSessionQuestion(db, s, "question", text, opts, true));
}
const answered = await waitForAnswers(db, qs.map((q) => q.id));
if (!answered) {
// The questions stay pending; the PM's answer will be typed into the terminal.
output({
hookSpecificOutput: {
hookEventName: "PreToolUse",
permissionDecision: "deny",
permissionDecisionReason: `Вопрос переслан PM через Пеппу (${qs.map((q) => `#${q.id}`).join(", ")}). Закончи ход — ответ придёт следующим сообщением.`,
},
});
return;
}
await updateSession(db, s.id, { status: "running", lastActivityAt: new Date() });
const answers = Object.fromEntries(items.map((item, i) => [item.question, answered[i]!.answer ?? ""]));
output({
hookSpecificOutput: {
hookEventName: "PreToolUse",
permissionDecision: "allow",
updatedInput: { ...input.tool_input, answers },
},
});
}
const NUDGE = (key: string) =>
`Продолжай работу над ${key} по tasks.md и правилам Пеппы, не жди PM. Когда стори готова — PR и update_task(status: review). Ждёшь проверок, ревьюера или мержа — просто закончи ход: Пеппа разбудит тебя сама, PM об этом писать не нужно. Не можешь продолжать — report_blocker (что мешает, что пробовал) и закончи ход.`;
/**
* The agent finished a turn. Pending question → PM already has it. Task in review →
* "ready for review" (accept / comment). Task still in work → ask the agent to keep going
* (Claude only, via the Stop hook's block decision), at most MAX_AUTO_NUDGES in a row.
* Otherwise (PEP-149) the last reply becomes a `progress` record — the person is not woken.
* Returns the Stop-hook output to print, if any.
*/
async function turnEnd(db: Db, s: SessionView, text: string | null, canContinue: boolean): Promise<unknown> {
await logSessionEvent(db, s, "turn_end", { text });
// PEP-43: the story's budget is spent — the PM was asked; don't push the agent further.
if (s.taskId && (await getBudgetState(db, s.taskId))) {
await logSessionEvent(db, s, "budget_hold", {});
await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() });
return null;
}
// PEP-39: the subscription is near its limit — end the turn here (no nudge, no ping);
// the watchdog moves the session to a free subscription at this boundary.
if (s.rotateReason && (await pendingSessionQuestions(db, s.id)).length === 0) {
await updateSession(db, s.id, { status: "idle", lastActivityAt: new Date() });
return null;
}
// PEP-149: only what a person must answer holds the agent; a factory message does not.
if ((await pendingSessionQuestions(db, s.id)).some((q) => needsPerson(q, s.taskStatus))) {
await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() });
return null;
}
// PEP-53: a free runner belongs to the person in the terminal — no nudge, no ping.
if (!s.taskId) {
await updateSession(db, s.id, { status: "idle", lastActivityAt: new Date() });
return null;
}
const [task] = await db.select().from(tasks).where(eq(tasks.id, s.taskId));
// PEP-10: the story is done — a queue runner waits for its next one without a ping.
if (task?.status === "done") {
await updateSession(db, s.id, { status: "idle", lastActivityAt: new Date() });
return null;
}
if (task?.status === "review" && (await getPendingAccept(db, task.id))) {
// PEP-127: the PM accepted already — the watchdog merges after green checks, no new review message.
await logSessionEvent(db, s, "awaiting_accept_merge", { pr: task.prUrl });
await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() });
return null;
}
if (task?.status === "review" && (await getAutonomy(db, task.projectId)).merge === "auto") {
// PEP-25: Peppa merges this PR itself (watchdog); the PM hears only if it can't.
await logSessionEvent(db, s, "awaiting_automerge", { pr: task.prUrl });
await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() });
return null;
}
if (task?.status === "review") {
// PEP-26: what the reviewer agent said (approved, findings left after the limit, failed).
const settings = await getReviewSettings(db, task.projectId);
const note = settings.enabled ? reviewNote(await latestReview(db, task.id), (await reviewRejections(db, task.id)) >= settings.maxIterations) : "";
// PEP-44: the preview stand, the diff and the checks — the PM reviews without a terminal.
const [project] = await db.select().from(projects).where(eq(projects.id, task.projectId));
const look = project ? [reviewPreviewNote(await reviewPreview(db, { project, task, key: s.taskKey ?? "" }).catch(() => ({ previewUrl: null, releaseId: null, sha: null, diffUrl: null, checks: "", screenshots: [], issueUrl: null }))), await demoNote(db, project.id, project.key)].filter(Boolean).join("\n") : "";
const card = clip(`${m("✅ Задача {key} готова к ревью", { key: s.taskKey })}${task.prUrl ? ` · ${m("Результат: {url}", { url: task.prUrl })}` : ""}\n\n${look ? `${look}\n\n` : ""}${note ? `${note}\n\n` : ""}${asIs(text?.trim())}`.trim());
// PEP-127: the PM gets it only when the PR can be merged now; otherwise the watchdog sends it later.
if (project) await sendReviewCard(db, { project, task, key: s.taskKey ?? "" }, card, s);
else await raiseSessionQuestion(db, s, "attention", card);
await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() });
return null;
}
const working = task && ["proposing", "in_progress"].includes(task.status);
// PEP-26: the reviewer agent is checking the PR — its result comes to the agent or the PM by itself.
if (working && (await pendingReview(db, task.id))) {
await logSessionEvent(db, s, "awaiting_review", {});
await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() });
return null;
}
if (canContinue && working && s.autoNudges < MAX_AUTO_NUDGES) {
await updateSession(db, s.id, { autoNudges: s.autoNudges + 1, status: "running", lastActivityAt: new Date() });
await logSessionEvent(db, s, "auto_continue", { n: s.autoNudges + 1 });
return { decision: "block", reason: NUDGE(s.taskKey ?? "стори") };
}
// PEP-149: the end of a turn is progress, not a question — a record in the story thread
// («События агентов»); nobody is woken. Peppa wakes the agent when there is something to do
// (checks passed or failed, the reviewer, a rebase, a comment of the person).
if (text && task) await reportProgress(db, { project: await getProject(db, s.projectKey), task, key: s.taskKey ?? "" }, clip(text), s.id);
await updateSession(db, s.id, { status: "idle", lastActivityAt: new Date() });
return null;
}
/** PEP-5: token totals of the conversation, from its transcript. */
function saveTranscriptUsage(db: Db, s: SessionView, input: HookInput) {
const u = transcriptUsage(input.transcript_path);
const conv = input.session_id ?? s.conversationId;
if (u && conv) recordTranscriptUsage(db, s.id, conv, u);
}
/**
* PEP-5: Claude's statusLine command. Prints the status line (one line, must be quick) and
* records cost / context / limit windows. Never throws: a broken status line is still a line.
*/
async function statusLine(input: Record<string, unknown>): Promise<void> {
const sessionId = Number(process.env.PEPPA_SESSION_ID);
const data = parseStatusLine(input);
let line = "Peppa FACTORY";
try {
if (sessionId) {
const db = createDb();
const s = await getSession(db, sessionId);
if (Number(process.env.PEPPA_GENERATION) === s.generation) {
await recordStatusLine(db, s, data);
line = `Peppa FACTORY ${s.taskKey ?? `#${s.id}`}`;
const fresh = await getSession(db, sessionId);
if (usageTotals(fresh.usage).hasData) line += ` · ${describeUsage(fresh.usage)}`;
}
}
} catch (e) {
log(`statusline session=${sessionId}: ${(e as Error).message}`);
}
const w = data.windows;
if (w.fiveHour) line += ` · 5ч ${Math.round(w.fiveHour.pct)}%`;
if (w.sevenDay) line += ` · 7д ${Math.round(w.sevenDay.pct)}%`;
process.stdout.write(`${line}\n`);
}
async function handle(event: string, input: HookInput): Promise<void> {
const sessionId = Number(process.env.PEPPA_SESSION_ID);
if (!sessionId) return; // manual `claude`, not started by Peppa
const db = createDb();
const s = await getSession(db, sessionId);
// A hook from an earlier run of this session (before a resume) is stale.
if (Number(process.env.PEPPA_GENERATION) !== s.generation) {
return log(`${event}: stale generation ${process.env.PEPPA_GENERATION} != ${s.generation} for session #${s.id}`);
}
const now = new Date();
switch (event) {
case "session-start":
// Also fires after /clear and /resume, with a new Claude session id.
await updateSession(db, s.id, { conversationId: input.session_id ?? null, status: "running", lastActivityAt: now });
await logSessionEvent(db, s, "claude_session", { source: input.source, conversationId: input.session_id });
break;
case "prompt":
// Someone typed into the terminal (or Peppa pasted an answer): anything still
// pending for this session is now answered — except hook-held questions, and,
// when Peppa typed this text itself, questions raised after it did (e.g. a CI
// failure pasted while the PM is being asked about the next one).
const sentAt = input.prompt ? await peppaInputSentAt(db, s.id, input.prompt) : null;
for (const q of await pendingSessionQuestions(db, s.id, { excludeHook: true, createdBefore: sentAt ?? undefined })) {
await answerQuestion(db, q.id, input.prompt ?? "", "terminal").catch(() => {});
}
await updateSession(db, s.id, { status: "running", autoNudges: 0, lastActivityAt: now });
break;
case "permission-request":
await permissionRequest(db, s, input);
break;
case "ask-question":
await askQuestion(db, s, input);
break;
case "tool-use": {
// PEP-33: one step of the live feed (PostToolUse / PostToolUseFailure, async hook).
const d = describeStep(input.tool_name ?? "", input.tool_input, input.cwd);
if (d) await recordStep(db, s, { tool: input.tool_name!, ...d, ok: input.hook_event_name !== "PostToolUseFailure" }, now);
break;
}
case "notification":
await logSessionEvent(db, s, "notification", { type: input.notification_type, message: input.message });
break;
case "stop": {
saveTranscriptUsage(db, s, input);
const res = await turnEnd(db, s, input.last_assistant_message?.trim() || lastAssistantText(input.transcript_path), true);
if (res) output(res);
break;
}
case "codex-notify": {
// Codex passes one JSON argument; only completed turns are reported.
const n = JSON.parse(process.argv[3] ?? "{}") as Record<string, unknown>;
if (n.type !== "agent-turn-complete") break;
const thread = typeof n["thread-id"] === "string" ? n["thread-id"] : null;
if (thread && thread !== s.conversationId) await updateSession(db, s.id, { conversationId: thread });
await turnEnd(db, s, String(n["last-assistant-message"] ?? "").slice(0, 8000).trim() || null, false);
break;
}
case "stop-failure": {
const limited = input.error === "rate_limit";
await logSessionEvent(db, s, "stop_failure", { error: input.error, details: input.error_details });
if (limited) {
// Stores when to continue; the watchdog resumes the runner then (PEP-56).
// PEP-39: null = another subscription of the pool is free, the watchdog switches to it.
const msg = await recordLimit(db, s, input.error_details ?? input.last_assistant_message ?? "");
if (msg) await raiseSessionQuestion(db, s, "attention", msg);
break;
}
await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: now });
await raiseSessionQuestion(
db,
s,
"attention",
`${m("{who}: ход оборвался с ошибкой {error}.", { who: s.taskKey ?? m("Агент #{id}", { id: s.id }), error: input.error ?? "unknown" })}${input.error_details ? `\n${asIs(clip(input.error_details, 400))}` : ""}`,
);
break;
}
case "session-end":
saveTranscriptUsage(db, s, input);
// /clear and /resume end a Claude session inside a live process, so this is not
// the process exiting; the watchdog decides that from the tmux pane.
await logSessionEvent(db, s, "claude_session_end", { reason: input.reason });
break;
default:
log(`unknown event ${event}`);
}
}
const event = process.argv[2] ?? "";
let raw = "";
// Codex notify passes its payload as an argument and may leave stdin attached to the tty.
if (event !== "codex-notify") {
try {
raw = readFileSync(0, "utf8");
} catch {}
}
// PEP-3: raw payloads as the CLI sent them, for checking the contract against a live Claude Code.
if (process.env.PEPPA_HOOK_CAPTURE_DIR && raw) {
try {
mkdirSync(process.env.PEPPA_HOOK_CAPTURE_DIR, { recursive: true });
writeFileSync(join(process.env.PEPPA_HOOK_CAPTURE_DIR, `${Date.now()}-${process.pid}-${event}.json`), raw);
} catch (e) {
log(`capture ${event}: ${(e as Error).message}`);
}
}
// PEP-48: hooks act as the session's agent (answers typed into the terminal are a person's).
setDefaultActor({ kind: "agent", channel: "hook" });
try {
if (event === "statusline") await statusLine(raw ? JSON.parse(raw) : {});
else await handle(event, raw ? (JSON.parse(raw) as HookInput) : {});
} catch (e) {
log(`${event} session=${process.env.PEPPA_SESSION_ID}: ${(e as Error).stack ?? e}`);
}
process.exit(0);