peppa/packages/runner/src/sessions.ts
Асель 07e2caa393 PEP-57: PM question on red CI is not closed by the agent's prompts
After three red runs Peppa asked the PM with the session attached, then pasted
"wait for the PM" into that session — its prompt hook closed the question as
answered in the terminal. The question is now task-only; answers to task
questions without a session go to the task's active session.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 16:59:04 +05:00

215 lines
9.6 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 { chmodSync, existsSync, realpathSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import {
answerQuestion,
claudeTokenForProject,
createSession,
expireSessionQuestions,
getSession,
listSessions,
loadSharedRules,
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 { loadEnv } from "@peppa/shared";
import { trustWorkspace } from "./claude-config.ts";
import { buildCommand, type Provider } from "./providers.ts";
import { runDir } from "./run-settings.ts";
import * as tmux from "./tmux.ts";
import { onReleaseAnswer } from "./deploy.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;
provider?: Provider;
}
const shq = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`;
/** Starts an interactive agent session (Claude Code or Codex) 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);
const provider = opts.provider ?? (process.env.PEPPA_PROVIDER as Provider | undefined) ?? "claude";
if (provider === "claude") trustWorkspace(cwd);
const session = await createSession(db, { projectId: ref.project.id, taskId: ref.task.id, provider });
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");
return launch(db, await getSession(db, session.id), cwd, { ...opts, prompt });
}
/**
* Relaunches a finished/failed/rate-limited session in a new generation, continuing
* the same conversation (claude --resume / codex resume) when its id is known.
*/
export async function resumeSession(db: Db, sessionId: number, opts: StartOptions = {}): Promise<SessionView> {
const s = await getSession(db, sessionId);
if (await tmux.hasSession(s.tmuxName)) {
if (!(await tmux.paneState(s.tmuxName)).dead) throw new PeppaError(`Session #${s.id} is still running`);
await tmux.killSession(s.tmuxName);
}
await expireSessionQuestions(db, s.id, "(неактуально: сессия перезапущена)");
const [project] = await db.select().from(projects).where(eq(projects.id, s.projectId));
const cwd = realpathSync(project!.workspacePath);
if (s.provider === "claude") trustWorkspace(cwd);
const prompt = [
`Продолжай работу${s.taskKey ? ` над задачей ${s.taskKey}` : ""}: сессия была прервана. Сверься с peppa.get_task и tasks.md.`,
opts.prompt,
]
.filter(Boolean)
.join("\n\n");
return launch(db, s, cwd, { ...opts, prompt, resume: s.conversationId ?? undefined });
}
async function launch(
db: Db,
s: SessionView,
cwd: string,
opts: StartOptions & { prompt: string; resume?: string },
): Promise<SessionView> {
const generation = s.generation + 1;
const rules = await loadSharedRules();
const [owner] = await db.select({ ownerId: projects.ownerId }).from(projects).where(eq(projects.id, s.projectId));
const claudeToken = s.provider === "claude" && owner ? await claudeTokenForProject(db, owner) : null;
const argv = buildCommand(s.provider, {
sessionId: s.id,
generation,
cwd,
prompt: opts.prompt,
rules: rules.text,
resume: opts.resume,
permissionMode: opts.permissionMode,
model: opts.model,
});
// tmux runs a tiny launch script: keeps long argv (rules, prompts) out of the tmux
// command line, and leaves a record of exactly what was started.
const launchScript = join(runDir(s.id, generation), "launch.sh");
writeFileSync(launchScript, `#!/bin/bash\nexec ${argv.map(shq).join(" ")}\n`);
chmodSync(launchScript, 0o700);
await updateSession(db, s.id, { generation, status: "starting", endedAt: null });
try {
await tmux.newSession({
name: s.tmuxName,
cwd,
command: shq(launchScript),
env: {
PEPPA_SESSION_ID: String(s.id),
PEPPA_GENERATION: String(generation),
PEPPA_PROJECT_DIR: cwd,
// Hooks and the MCP server must talk to the same DB / state dir as the runner.
DATABASE_URL: loadEnv().DATABASE_URL,
...(process.env.PEPPA_HOME ? { PEPPA_HOME: process.env.PEPPA_HOME } : {}),
// The project owner's own Claude subscription, if they connected it (PEP-13).
...(claudeToken ? { CLAUDE_CODE_OAUTH_TOKEN: claudeToken } : {}),
...(process.env.PEPPA_HOOK_WAIT_SEC ? { PEPPA_HOOK_WAIT_SEC: process.env.PEPPA_HOOK_WAIT_SEC } : {}),
},
});
} catch (e) {
await updateSession(db, s.id, { status: "failed", endedAt: new Date() });
throw new PeppaError(`tmux failed to start: ${(e as Error).message}`);
}
await updateSession(db, s.id, { status: "running", lastActivityAt: new Date() });
await logSessionEvent(db, s, opts.resume ? "resumed" : "started", {
generation,
tmuxName: s.tmuxName,
prompt: opts.prompt,
provider: s.provider,
rulesSource: rules.source,
});
return getSession(db, s.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`);
// Recorded before typing: the prompt hook answers only questions older than this input.
await logSessionEvent(db, s, "input_sent", { text });
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 expireSessionQuestions(db, s.id, "(неактуально: сессия остановлена)");
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);
// A human answered: the agent may again continue on its own a couple of times.
if (q.sessionId) await updateSession(db, q.sessionId, { autoNudges: 0 });
// A blocking hook is polling for this answer and hands it to Claude itself.
if (q.awaitingHook) return { delivered: true, question: q };
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}`;
}
// "Deploy to prod" on a "staging updated" message (PEP-57).
if (await onReleaseAnswer(db, q, answer, `PM (${via})`)) return { delivered: true, question: q };
// A task question asked outside a session (red CI, a manual session) goes to the agent
// working on the task now, if any.
const sessionId = q.sessionId ?? (q.taskId ? (await listSessions(db, { active: true, taskId: q.taskId }))[0]?.id : undefined);
if (!sessionId) return { delivered: false, question: q };
const s = await getSession(db, 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}`);
}