313 lines
14 KiB
TypeScript
313 lines
14 KiB
TypeScript
// 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 { appendFileSync, readFileSync } from "node:fs";
|
||
import { join } from "node:path";
|
||
import {
|
||
answerQuestion,
|
||
getQuestion,
|
||
getReviewSettings,
|
||
latestReview,
|
||
pendingReview,
|
||
reviewNote,
|
||
reviewRejections,
|
||
getSession,
|
||
logSessionEvent,
|
||
peppaInputSentAt,
|
||
pendingSessionQuestions,
|
||
raiseSessionQuestion,
|
||
releaseHookQuestion,
|
||
updateSession,
|
||
type Question,
|
||
type SessionView,
|
||
} from "@peppa/core";
|
||
import { createDb, 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>;
|
||
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",
|
||
`Разрешить ${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. Если упёрся в архитектурный стоппер — ask_pm и закончи ход. Когда стори готова — PR и update_task(status: review).`;
|
||
|
||
/**
|
||
* 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 the PM gets "the session is waiting for you".
|
||
* 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 });
|
||
if ((await pendingSessionQuestions(db, s.id)).length > 0) {
|
||
await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() });
|
||
return null;
|
||
}
|
||
const [task] = s.taskId ? await db.select().from(tasks).where(eq(tasks.id, s.taskId)) : [];
|
||
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) : "";
|
||
await raiseSessionQuestion(db, s, "attention", clip(`✅ Стори ${s.taskKey} готова к ревью${task.prUrl ? ` · PR: ${task.prUrl}` : ""}\n\n${note ? `${note}\n\n` : ""}${text ?? ""}`.trim()));
|
||
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 ?? "стори") };
|
||
}
|
||
await raiseSessionQuestion(db, s, "attention", clip(text ?? "Сессия закончила ход и ждёт ввода."));
|
||
await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() });
|
||
return null;
|
||
}
|
||
|
||
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 "notification":
|
||
await logSessionEvent(db, s, "notification", { type: input.notification_type, message: input.message });
|
||
break;
|
||
|
||
case "stop": {
|
||
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).
|
||
await raiseSessionQuestion(db, s, "attention", await recordLimit(db, s, input.error_details ?? input.last_assistant_message ?? ""));
|
||
break;
|
||
}
|
||
await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: now });
|
||
await raiseSessionQuestion(
|
||
db,
|
||
s,
|
||
"attention",
|
||
`${s.taskKey ?? `Сессия ${s.id}`}: ход оборвался с ошибкой ${input.error ?? "unknown"}.${input.error_details ? `\n${clip(input.error_details, 400)}` : ""}`,
|
||
);
|
||
break;
|
||
}
|
||
|
||
case "session-end":
|
||
// /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 {}
|
||
}
|
||
try {
|
||
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);
|