peppa/packages/runner/src/sessions.ts
Асель 967f70ac09 Add runner: tmux sessions, Claude hook ingestion and watchdog
- startSession: trusts the workspace in ~/.claude.json, runs interactive
  claude in tmux with PEPPA_SESSION_ID, remain-on-exit for crash status
- answerAndDeliver: PM answers go into the terminal (permission menu keys,
  approval -> task status + instruction, free text via bracketed paste)
- peppa-hook: session-start/prompt/notification/stop/session-end update
  session status and raise PM questions; never fails the Claude session
- watchdog: detects dead panes, vanished sessions, stalls, usage limits;
  launchd agent under caffeinate (scripts/install-launchd.sh)
- CLI: peppa session start|list|send|attach|stop, peppa watchdog

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 19:28:07 +05:00

131 lines
5.5 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.

import { existsSync, realpathSync } from "node:fs";
import {
answerQuestion,
createSession,
getSession,
PeppaError,
resolveTask,
updateSession,
updateTask,
logSessionEvent,
type Question,
type SessionView,
} from "@peppa/core";
import { projects, tasks, type Db } from "@peppa/db";
import { eq } from "drizzle-orm";
import { trustWorkspace } from "./claude-config.ts";
import * as tmux from "./tmux.ts";
export interface StartOptions {
/** Extra instructions appended to the default "work on <task>" prompt. */
prompt?: string;
permissionMode?: string;
model?: string;
/** Project for a bare task number ("42"). */
defaultProjectKey?: string;
}
const shq = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`;
/** Starts an interactive Claude Code session for a task in a detached tmux session. */
export async function startSession(db: Db, taskInput: string, opts: StartOptions = {}): Promise<SessionView> {
const ref = await resolveTask(db, taskInput, opts.defaultProjectKey);
const dir = ref.project.workspacePath;
if (!existsSync(dir)) throw new PeppaError(`Workspace ${dir} does not exist — bootstrap the project first`);
const cwd = realpathSync(dir);
trustWorkspace(cwd);
const session = await createSession(db, { projectId: ref.project.id, taskId: ref.task.id });
const tmuxName = `peppa-${ref.key.toLowerCase()}-s${session.id}`;
await updateSession(db, session.id, { tmuxName });
const prompt = [`Работай над задачей ${ref.key} по правилам AGENTS.md.`, opts.prompt].filter(Boolean).join("\n\n");
const claude = process.env.PEPPA_CLAUDE_BIN ?? "claude";
const args = [
`--permission-mode ${shq(opts.permissionMode ?? process.env.PEPPA_PERMISSION_MODE ?? "acceptEdits")}`,
opts.model ? `--model ${shq(opts.model)}` : "",
shq(prompt),
];
try {
await tmux.newSession({
name: tmuxName,
cwd,
command: `${claude} ${args.filter(Boolean).join(" ")}`,
env: { PEPPA_SESSION_ID: String(session.id), PEPPA_PROJECT_DIR: cwd },
});
} catch (e) {
await updateSession(db, session.id, { status: "failed", endedAt: new Date() });
throw new PeppaError(`tmux failed to start: ${(e as Error).message}`);
}
await updateSession(db, session.id, { status: "running", lastActivityAt: new Date() });
await logSessionEvent(db, session, "started", { tmuxName, prompt });
return getSession(db, session.id);
}
export async function sendToSession(db: Db, sessionId: number, text: string): Promise<void> {
const s = await getSession(db, sessionId);
if (!(await tmux.hasSession(s.tmuxName))) throw new PeppaError(`Session #${s.id} (${s.tmuxName}) is not running`);
await tmux.sendText(s.tmuxName, text);
await updateSession(db, s.id, { status: "running", lastActivityAt: new Date() });
}
export async function stopSession(db: Db, sessionId: number): Promise<void> {
const s = await getSession(db, sessionId);
if (await tmux.hasSession(s.tmuxName)) await tmux.killSession(s.tmuxName);
await updateSession(db, s.id, { status: "done", endedAt: new Date() });
await logSessionEvent(db, s, "stopped");
}
const APPROVE_RE = /^\s*(ok|ок|да|yes|approve|approved|одобр|lgtm|go|погнали|делай)/i;
// Claude Code permission prompt: 1 = yes, 2 = yes and don't ask again, 3 = no.
const PERMISSION_KEYS: Record<string, string> = { allow: "1", always: "2", deny: "3" };
/**
* Records the PM's answer and delivers it into the session's terminal:
* permission → menu choice; approval → status change + message; otherwise the text.
*/
export async function answerAndDeliver(
db: Db,
questionId: number,
answer: string,
via: NonNullable<Question["answeredVia"]>,
): Promise<{ delivered: boolean; question: Question }> {
const q = await answerQuestion(db, questionId, answer, via);
let message = answer;
if (q.kind === "approval" && q.taskId) {
const approved = APPROVE_RE.test(answer);
const ref = await resolveTaskById(db, q.taskId);
await updateTask(db, ref, { status: approved ? "in_progress" : "proposing" }, q.sessionId ?? undefined);
message = approved
? `PM одобрил proposal ${ref.key}. Статус in_progress — переходи к Apply.${answer.trim().length > 4 ? `\n\nКомментарий PM: ${answer}` : ""}`
: `PM не одобрил proposal ${ref.key}. Доработай proposal по комментарию и снова запроси одобрение.\n\nКомментарий PM: ${answer}`;
} else if (q.kind === "question") {
message = `Ответ PM на вопрос #${q.id}: ${answer}`;
}
if (!q.sessionId) return { delivered: false, question: q };
const s = await getSession(db, q.sessionId);
if (!(await tmux.hasSession(s.tmuxName))) return { delivered: false, question: q };
if (q.kind === "permission") {
const key = PERMISSION_KEYS[answer.trim().toLowerCase()];
if (key) await tmux.sendKeys(s.tmuxName, key);
else await tmux.sendText(s.tmuxName, answer);
} else {
await tmux.sendText(s.tmuxName, message);
}
await updateSession(db, s.id, { status: "running", lastActivityAt: new Date() });
return { delivered: true, question: q };
}
async function resolveTaskById(db: Db, taskId: number) {
const [row] = await db
.select({ key: projects.key, number: tasks.number })
.from(tasks)
.innerJoin(projects, eq(tasks.projectId, projects.id))
.where(eq(tasks.id, taskId));
if (!row) throw new PeppaError(`Task #${taskId} not found`);
return resolveTask(db, `${row.key}-${row.number}`);
}