peppa/packages/runner/src/sessions.ts
Асель 14916079bc PEP-5/43/47/48: usage and limits, story budgets, factory metrics, audit journal
- PEP-5: statusLine hook (cost, context, 5h/7d limit windows), transcript tokens,
  sessions.usage, usage strip over every page, runner usage, bot /status, MCP get_usage
- PEP-43: project/story budgets in settings, watchdog pause (Escape, question to the PM:
  extend x2 / remove limit / stop), start/resume guard, budget on the story card
- PEP-47: project metrics tab (cycle time, first pass, review returns, questions, runner
  hours, PM wait, limits, spend by week/agent/epic), MCP get_metrics
- PEP-48: event authors (actor columns, AsyncLocalStorage context), question_answered,
  /journal for superadmins, project journal tab, authors in the story feed
- Migration 0007_usage_audit; OpenSpec changes archived

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 06:52:13 +05:00

331 lines
15 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 {
agentAutonomyNote,
answerQuestion,
getAutonomy,
getBudgetState,
getSubscription,
pickSubscription,
createSession,
expireSessionQuestions,
FINISHED_SESSION_STATUSES,
getSession,
listSessions,
loadSharedRules,
PeppaError,
resolveTask,
updateSession,
updateTask,
logSessionEvent,
activateRunnerTask,
enqueueRunnerTask,
finishRunnerTask,
resolveRunnerSettings,
type Project,
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, providerEnv, type Provider } from "./providers.ts";
import { subscriptionEnv } from "./subscriptions.ts";
import { runDir } from "./run-settings.ts";
import * as tmux from "./tmux.ts";
import { onReleaseAnswer } from "./deploy.ts";
import { ensureWorktree } from "./worktree.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;
/** PEP-67: subscriptions ticked at launch (multiple choice); else `poolId`; else the project's pool. */
subscriptionIds?: number[];
poolId?: number | null;
/** PEP-10/53: the runner's name. */
name?: string;
}
/** PEP-43: a story paused by its budget is not started or resumed until the PM decides. */
export async function assertBudgetOpen(db: Db, taskId: number | null | undefined): Promise<void> {
if (taskId == null) return;
if (await getBudgetState(db, taskId)) throw new PeppaError("Бюджет стори исчерпан — ответьте на вопрос о бюджете или поменяйте бюджет в карточке стори");
}
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);
// PEP-23: the project's autonomy (PM approves proposals, Peppa merges) goes into the prompt.
const note = agentAutonomyNote(await getAutonomy(db, ref.project.id));
const prompt = [`Работай над стори ${ref.key} по правилам AGENTS.md.`, note, opts.prompt].filter(Boolean).join("\n\n");
return startRunner(db, ref.project, { id: ref.task.id, key: ref.key }, { ...opts, prompt });
}
/** PEP-10: live runners of a project count against its `maxRunners`. */
export async function assertRunnerSlot(db: Db, projectId: number, max: number | null): Promise<void> {
if (max == null) return;
const live = (await listSessions(db, { active: true, projectId })).length;
if (live >= max) throw new PeppaError(`Лимит раннеров проекта: ${max} (сейчас работают ${live})`);
}
/**
* Starts a runner of the project: for a story (`task`) or a free one (PEP-53, task null).
* Working copy by the runner settings: the project's, or its own git worktree (PEP-27).
*/
export async function startRunner(
db: Db,
project: Project,
task: { id: number; key: string } | null,
opts: StartOptions & { prompt: string },
): Promise<SessionView> {
// PEP-43: a story paused by its budget waits for the PM.
await assertBudgetOpen(db, task?.id);
const dir = project.workspacePath;
if (!existsSync(dir)) throw new PeppaError(`Workspace ${dir} does not exist — bootstrap the project first`);
const rs = await resolveRunnerSettings(db, project.id, task?.id);
await assertRunnerSlot(db, project.id, rs.maxRunners);
// PEP-67: the first free active subscription of the chosen set decides the provider.
const sub = await pickSubscription(db, { projectId: project.id, subscriptionIds: opts.subscriptionIds, poolId: opts.poolId, provider: opts.provider });
const provider = sub?.provider ?? opts.provider ?? (process.env.PEPPA_PROVIDER as Provider | undefined) ?? "claude";
const session = await createSession(db, { projectId: project.id, taskId: task?.id ?? null, provider, subscriptionId: sub?.id ?? null, name: opts.name?.trim() || null });
const tmuxName = `peppa-${(task?.key ?? project.key).toLowerCase()}-s${session.id}`;
await updateSession(db, session.id, { tmuxName });
if (task) await activateRunnerTask(db, session.id, task.id);
let cwd = realpathSync(dir);
if (rs.workspace === "worktree") {
try {
const wt = await ensureWorktree(project, session.id, task?.key ?? null);
cwd = realpathSync(wt.path);
await updateSession(db, session.id, { workspacePath: cwd });
await logSessionEvent(db, session, "worktree_created", { path: cwd, branch: wt.branch, note: wt.note });
} catch (e) {
await updateSession(db, session.id, { status: "failed", endedAt: new Date() });
throw new PeppaError(`Не удалось создать git worktree раннера: ${(e as Error).message}`);
}
}
if (provider === "claude") trustWorkspace(cwd);
return launch(db, await getSession(db, session.id), cwd, opts);
}
/** The runner's working copy: its own worktree (recreated if gone, PEP-27) or the project's. */
export async function runnerCwd(db: Db, s: SessionView): Promise<string> {
const [project] = await db.select().from(projects).where(eq(projects.id, s.projectId));
if (!s.workspacePath) return realpathSync(project!.workspacePath);
if (!existsSync(s.workspacePath)) {
const wt = await ensureWorktree(project!, s.id, s.taskKey);
await logSessionEvent(db, s, "worktree_created", { path: wt.path, branch: wt.branch, note: wt.note, recreated: true });
}
return realpathSync(s.workspacePath);
}
/**
* 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);
await assertBudgetOpen(db, s.taskId);
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 cwd = await runnerCwd(db, s);
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 });
}
/**
* PEP-10: the runner starts a new conversation in the same tmux session and working copy
* (next story with a fresh context). Open questions of the previous run stay (a review
* message is still answerable); a new generation makes its hooks the only live ones.
*/
export async function relaunchFresh(db: Db, sessionId: number, prompt: string): Promise<SessionView> {
const s = await getSession(db, sessionId);
if (await tmux.hasSession(s.tmuxName)) await tmux.killSession(s.tmuxName);
const cwd = await runnerCwd(db, s);
if (s.provider === "claude") trustWorkspace(cwd);
await updateSession(db, s.id, { conversationId: null, autoNudges: 0 });
return launch(db, await getSession(db, s.id), cwd, { prompt });
}
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();
// The session's subscription (rotation changes it beforehand, PEP-39); none = this machine's login.
const sub = s.subscriptionId ? await getSubscription(db, s.subscriptionId).catch(() => null) : 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 ctx = { sessionId: s.id, generation };
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.
PEPPA_DB: loadEnv().PEPPA_DB,
...(process.env.PEPPA_HOME ? { PEPPA_HOME: process.env.PEPPA_HOME } : {}),
...providerEnv(s.provider, ctx),
// The subscription's login (PEP-67): Claude token, CODEX_HOME or an OpenCode key.
...(sub ? subscriptionEnv(sub) : {}),
...(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,
subscriptionId: sub?.id ?? null,
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 finishRunnerTask(db, s.id);
await logSessionEvent(db, s, "stopped");
}
/** Handlers that consume an answer themselves (true = handled, not typed into a session). */
export type AnswerHandler = (db: Db, q: Question, answer: string) => Promise<boolean>;
const answerHandlers: AnswerHandler[] = [];
export function onAnswer(h: AnswerHandler) {
answerHandlers.push(h);
}
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}`;
}
// Other answer handlers (PEP-24: "agents are idle" push).
for (const h of answerHandlers) if (await h(db, q, answer)) return { delivered: true, question: q };
// "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 };
let s = await getSession(db, sessionId);
// PEP-10: a queue runner already moved on to another story — the answer (e.g. review
// comments) must not land in that conversation: to the story's runner if there is one,
// else the story goes first into this runner's queue.
if (q.taskId && s.taskId !== q.taskId) {
const other = (await listSessions(db, { active: true, taskId: q.taskId }))[0];
if (other) s = other;
else {
if (FINISHED_SESSION_STATUSES.includes(s.status)) return { delivered: false, question: q };
await enqueueRunnerTask(db, s.id, q.taskId, { prompt: message, front: true });
await logSessionEvent(db, s, "task_queued", { taskId: q.taskId, reason: "answer" });
return { delivered: true, question: q };
}
}
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 };
}
export 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}`);
}