peppa/packages/runner/src/sessions.ts
peppa-bot db1dd78a9e PEP-183: свежий main (PEP-179/182)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 17:00:54 +05:00

579 lines
30 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 { ensureTaskMatch } from "./team-match.ts";
import { fileURLToPath } from "node:url";
import { m } from "@peppa/shared/i18n";
import { chmodSync, existsSync, realpathSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import {
agentAutonomyNote,
copyTaskAttachments,
answerQuestion,
getAutonomy,
getBudgetState,
getSubscription,
mayUseMachineLogin,
pickSubscription,
createSession,
expireSessionQuestions,
FINISHED_SESSION_STATUSES,
getSession,
getQuestion,
listSessions,
loadSharedRules,
memoryContext,
agentPrompt,
ensureSessionAgent,
assertAgentAvailable,
checkEscalation,
launchModelFor,
resolveAgentSettings,
PeppaError,
resolveTask,
updateSession,
updateTask,
logSessionEvent,
activateRunnerTask,
enqueueRunnerTask,
finishRunnerTask,
resolveRunnerSettings,
type Project,
type Question,
type SessionView,
markSecretsUsed,
projectSecretEnv,
assertProjectActive,
} 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";
import { isRunnerClient, runnerCall } from "./runner-client.ts";
import { pickHost } from "@peppa/core";
import { containerEnv, containerName, dockerRunScript, prepareLocalHome, relayUrl, removeContainer, type Mount } from "./sandbox.ts";
import { ensureHostWorkspace, hostAgentHome, hostRunDir, pushRunDir } from "./hosts.ts";
export interface StartOptions {
/** Extra instructions appended to the default "work on <task>" prompt. */
prompt?: string;
permissionMode?: string;
/** PEP-41: explicit model/effort win over the agent settings. */
model?: string;
effort?: 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(m("Бюджет задачи исчерпан — ответьте на вопрос о бюджете или поменяйте бюджет в карточке задачи"));
}
const shq = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`;
/** Stops the runner's process: its tmux session and, in a sandbox, its container (PEP-17). */
export async function killRunner(s: SessionView): Promise<void> {
const pane = tmux.sessionPane(s);
if (await tmux.hasSession(pane)) await tmux.killSession(pane).catch(() => {});
if (s.container) await removeContainer(s.host, s.container);
}
/** 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);
await assertProjectActive(db, ref.project.id);
// PEP-21: web and bot only enqueue — the runner service starts the agent.
if (isRunnerClient()) {
const r = await runnerCall<{ sessionId: number }>(db, "start", { task: ref.key, opts }, { key: `task:${ref.task.id}` });
return getSession(db, r.sessionId);
}
// 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(m("Предел агентов проекта: {max} (сейчас работают {live})", { 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).
*/
/**
* PEP-172: the directory Peppa FACTORY itself runs from — the live copy (PEPPA_ROOT, else the
* checkout of this code). No agent works there: its branch switches and builds went live on 16.11.
*/
export function liveCheckout(): string | null {
try {
return realpathSync(process.env.PEPPA_ROOT ?? fileURLToPath(new URL("../../..", import.meta.url)));
} catch {
return null;
}
}
export function isLiveCheckout(dir: string): boolean {
const live = liveCheckout();
try {
return !!live && realpathSync(dir) === live;
} catch {
return false;
}
}
export async function startRunner(
db: Db,
project: Project,
task: { id: number; key: string } | null,
opts: StartOptions & { prompt: string },
): Promise<SessionView> {
// PEP-174: nothing starts in a project on pause.
await assertProjectActive(db, project.id);
// 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-40: runners of the project go to the least busy online host of its list.
const host = rs.hosts.length ? await pickHost(db, rs.hosts) : null;
if (rs.hosts.length && !host) throw new PeppaError(m("Агенту негде работать: все машины проекта недоступны или отключены"));
// PEP-17: a host always runs the agent in its container.
const sandboxed = rs.isolation === "container" || !!host;
// PEP-67: the first free active subscription of the chosen set decides the provider.
// PEP-41: the agent settings may ask for a provider; with none usable — the fallback one.
const agent = await resolveAgentSettings(db, project.id, task?.id);
const wanted = opts.provider ?? (opts.subscriptionIds?.length ? undefined : (agent.provider ?? undefined));
const pick = (provider: Provider | undefined) => pickSubscription(db, { projectId: project.id, subscriptionIds: opts.subscriptionIds, poolId: opts.poolId, provider });
let sub: Awaited<ReturnType<typeof pickSubscription>>;
let fallback: { from: Provider | null; reason: string } | null = null;
try {
sub = await pick(wanted);
} catch (e) {
const fb = agent.fallbackProvider;
if (!fb || opts.provider || opts.subscriptionIds?.length || fb === wanted) throw e;
sub = await pick(fb).catch(() => {
throw e;
});
fallback = { from: wanted ?? null, reason: (e as Error).message };
}
const provider = sub?.provider ?? wanted ?? (process.env.PEPPA_PROVIDER as Provider | undefined) ?? "claude";
// PEP-71: self-registered (eGov) users don't get this machine's login for free.
if (!sub && !sandboxed && !(await mayUseMachineLogin(db, project.ownerId))) {
throw new PeppaError(m("Подписка проекта не подключена — агенты не запустятся. Владелец подключает свою (Claude или ChatGPT) в «⋯ Настройки проекта → Подписки»"));
}
// The container has no login of this machine: the agent runs on its subscription.
if (sandboxed && !sub) throw new PeppaError(m("Для запуска агента в контейнере нужна подписка: подключите её в настройках проекта (раздел «Подписки»)"));
if (host && provider === "codex") throw new PeppaError(m("Codex на удалённом хосте пока не поддерживается — выберите подписку Claude или OpenCode"));
// PEP-182: no free persona and the team may not grow — the story waits for a free agent.
await assertAgentAvailable(db, sub?.id ?? null);
const session = await createSession(db, { projectId: project.id, taskId: task?.id ?? null, provider, subscriptionId: sub?.id ?? null, name: opts.name?.trim() || null });
if (fallback) await logSessionEvent(db, await getSession(db, session.id), "provider_fallback", { from: fallback.from, to: provider, subscriptionId: sub?.id ?? null, reason: fallback.reason });
const tmuxName = `peppa-${(task?.key ?? project.key).toLowerCase()}-s${session.id}`;
await updateSession(db, session.id, { tmuxName, hostId: host?.id ?? null, container: sandboxed ? containerName(session.id) : null });
if (task) await activateRunnerTask(db, session.id, task.id);
if (host) {
// The runner's own clone on the host, on the story's branch (through the relay: no token there).
try {
const ws = await ensureHostWorkspace(db, await getSession(db, session.id), project);
await updateSession(db, session.id, { workspacePath: ws.path });
await logSessionEvent(db, session, "host_workspace", { host: host.name, path: ws.path, branch: ws.branch });
} catch (e) {
await updateSession(db, session.id, { status: "failed", endedAt: new Date() });
throw new PeppaError(m("Не удалось подготовить рабочую копию на хосте {host}: {error}", { host: host.name, error: (e as Error).message }));
}
return launch(db, await getSession(db, session.id), (await getSession(db, session.id)).workspacePath!, opts);
}
let cwd = realpathSync(dir);
// PEP-172: a project kept in Peppa's own live copy (PEP) always gives its agents a worktree.
if (rs.workspace === "worktree" || isLiveCheckout(dir)) {
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(m("Не удалось подготовить рабочую копию для агента: {error}", { error: (e as Error).message }));
}
}
if (provider === "claude" && !sandboxed) trustWorkspace(cwd);
return launch(db, await getSession(db, session.id), cwd, opts);
}
/**
* PEP-159: the story's files copied into the runner's working copy (`.peppa/attachments/`);
* the note to append to a message typed into the live agent. Empty when there are none or the
* copy is on another host (`get_task` then says the files are on the site).
*/
export async function syncSessionAttachments(db: Db, sessionId: number): Promise<string> {
try {
const s = await getSession(db, sessionId);
if (!s.taskId || s.host) return "";
const files = await copyTaskAttachments(db, s.taskId, await runnerCwd(db, s));
return files.length ? `\n\nПриложенные файлы (в рабочей копии): ${files.map((f) => f.localPath).join(", ")}` : "";
} catch {
return "";
}
}
/** 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));
// PEP-40: the clone lives on the host (made again there if it was removed).
if (s.host) return (await ensureHostWorkspace(db, s, project!)).path;
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> {
if (isRunnerClient()) {
await runnerCall(db, "resume", { sessionId, opts }, { key: `session:${sessionId}` });
return getSession(db, sessionId);
}
const s = await getSession(db, sessionId);
await assertProjectActive(db, s.projectId);
await assertBudgetOpen(db, s.taskId);
if (await tmux.hasSession(tmux.sessionPane(s))) {
if (!(await tmux.paneState(tmux.sessionPane(s))).dead) throw new PeppaError(`Session #${s.id} is still running`);
}
await killRunner(s);
await expireSessionQuestions(db, s.id, m("(неактуально: агент перезапущен)"));
const cwd = await runnerCwd(db, s);
if (s.provider === "claude" && !s.container) 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);
await assertProjectActive(db, s.projectId);
await killRunner(s);
const cwd = await runnerCwd(db, s);
if (s.provider === "claude" && !s.container) 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> {
if (!s.host && isLiveCheckout(cwd)) {
await updateSession(db, s.id, { status: "failed", endedAt: new Date() });
throw new PeppaError(m("Агент не может работать в копии, из которой работает сама Peppa FACTORY ({dir}): ему нужна своя рабочая копия. Запустите агента заново — он получит её сам.", { dir: cwd }));
}
const generation = s.generation + 1;
const rules = await loadSharedRules();
// PEP-30: the project's memory and recent stories go with the shared rules.
// On a host (PEP-40) the working copy is not here: the project's own copy stands in.
const memDir = s.host ? (await db.select().from(projects).where(eq(projects.id, s.projectId)))[0]?.workspacePath ?? cwd : cwd;
const memory = await memoryContext(db, s.projectId, memDir).catch(() => "");
// PEP-75: the runner's persona (assigned on the first launch) — name and character in the prompt.
if (s.taskId && !s.agentId) await ensureTaskMatch(db, s.taskId).catch(() => null); // PEP-183
const persona = await ensureSessionAgent(db, s.id).catch(() => null);
// PEP-159: files attached to the story and its discussion lie in the working copy for the agent.
if (s.taskId && !s.host) await copyTaskAttachments(db, s.taskId, cwd).catch(() => []);
const extras = [memory, persona ? agentPrompt(persona) : ""].filter(Boolean).join("\n\n");
// 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;
// PEP-41: model and effort from the agent settings (escalated after failures of the story).
let model = opts.model;
let effort = opts.effort;
let escalated = false;
if (!model && !effort) {
const agent = await resolveAgentSettings(db, s.projectId, s.taskId);
const esc = s.taskId ? await checkEscalation(db, s.projectId, s.taskId) : null;
const lm = launchModelFor(agent, s.provider, !!esc?.escalation);
model = lm.model ?? undefined;
effort = lm.effort ?? undefined;
escalated = lm.escalated;
if (esc?.fresh && lm.escalated) await logSessionEvent(db, s, "model_escalated", { to: lm.model, failures: esc.escalation!.failures });
}
const sandbox = !!s.container;
const argv = buildCommand(s.provider, {
sessionId: s.id,
generation,
cwd,
prompt: opts.prompt,
rules: extras ? `${rules.text}\n\n${extras}` : rules.text,
resume: opts.resume,
permissionMode: opts.permissionMode,
model,
effort,
sandbox,
});
// 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, sandbox };
const localRun = runDir(s.id, generation);
const launchScript = join(localRun, "launch.sh");
let env: Record<string, string>;
let script: string;
let tmuxCommand = shq(launchScript);
// PEP-54: project secrets reach the agent as env through a 0600 file the script sources
// and deletes at once — never in the tmux argv (visible in `ps`) or a file left on disk.
// In a container (PEP-17) docker passes them on by name (`-e NAME`).
const secrets = await projectSecretEnv(db, s.projectId);
const secretNames = Object.keys(secrets.env);
let preamble = "";
if (secretNames.length) {
const secretsFile = join(localRun, "secrets.env");
writeFileSync(secretsFile, secretNames.map((k) => `export ${k}=${shq(secrets.env[k]!)}\n`).join(""), { mode: 0o600 });
// On a host the launch dir is copied there first: source it from the host's copy.
const at = s.host ? join(await hostRunDir(s.host, s.id, generation), "secrets.env") : secretsFile;
preamble = `. ${shq(at)}; rm -f ${shq(at)}\n`;
}
if (sandbox) {
// PEP-17: the agent in its container; only the run's own environment goes in.
const relay = relayUrl(s.host);
const subEnv = sub ? subscriptionEnv(sub) : {};
env = containerEnv({ sessionId: s.id, generation, relay }, { ...providerEnv(s.provider, ctx), ...subEnv });
const mounts: Mount[] = [];
let home: string;
let hostRun = localRun;
if (s.host) {
hostRun = await hostRunDir(s.host, s.id, generation);
home = await hostAgentHome(s.host, s.id, cwd);
} else {
home = prepareLocalHome(s.id, cwd);
// A worktree's .git file points into the project's .git: mount that too (only this project's).
if (s.workspacePath) {
const [project] = await db.select().from(projects).where(eq(projects.id, s.projectId));
const gitDir = join(realpathSync(project!.workspacePath), ".git");
if (existsSync(gitDir)) mounts.push({ src: gitDir, dst: gitDir });
}
// Codex keeps the subscription's login in its CODEX_HOME (PEP-67).
if (subEnv.CODEX_HOME) mounts.push({ src: subEnv.CODEX_HOME, dst: subEnv.CODEX_HOME });
}
script = dockerRunScript({ sessionId: s.id, generation, target: s.host, cwd, runDir: hostRun, home, mounts, relay, argv, env, passEnv: secretNames, preamble });
if (s.host) tmuxCommand = shq(join(hostRun, "launch.sh"));
} else {
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 } : {}),
...(process.env.PEPPA_HOOK_CAPTURE_DIR ? { PEPPA_HOOK_CAPTURE_DIR: process.env.PEPPA_HOOK_CAPTURE_DIR } : {}),
};
script = `#!/bin/bash\n${preamble}exec ${argv.map(shq).join(" ")}\n`;
}
writeFileSync(launchScript, script);
chmodSync(launchScript, 0o700);
await updateSession(db, s.id, { generation, status: "starting", endedAt: null });
try {
// PEP-40: the launch dir goes to the host (settings, rules, launch.sh; secrets.env 0600, removed by launch.sh).
if (s.host) await pushRunDir(s.host, localRun, await hostRunDir(s.host, s.id, generation));
await tmux.newSession({ name: s.tmuxName, host: s.host, cwd, command: tmuxCommand, env });
// The host has its copy now (sourced and removed by launch.sh); none stays here.
if (s.host) rmSync(join(localRun, "secrets.env"), { force: true });
} catch (e) {
rmSync(join(runDir(s.id, generation), "secrets.env"), { force: true });
await updateSession(db, s.id, { status: "failed", endedAt: new Date() });
throw new PeppaError(`tmux failed to start${s.host ? ` on ${s.host.name}` : ""}: ${(e as Error).message}`);
}
await updateSession(db, s.id, { status: "running", lastActivityAt: new Date() });
if (secretNames.length || secrets.unreadable.length) {
await markSecretsUsed(db, s.projectId, secretNames);
await logSessionEvent(db, s, "secrets_issued", { generation, names: secretNames, ...(secrets.unreadable.length ? { unreadable: secrets.unreadable } : {}) });
}
await logSessionEvent(db, s, opts.resume ? "resumed" : "started", {
generation,
tmuxName: s.tmuxName,
prompt: opts.prompt,
provider: s.provider,
subscriptionId: sub?.id ?? null,
model: model ?? null,
effort: effort ?? null,
...(escalated ? { escalated: true } : {}),
rulesSource: rules.source,
...(s.container ? { container: s.container } : {}),
...(s.host ? { host: s.host.name } : {}),
});
return getSession(db, s.id);
}
/** `o.person` (PEP-154): the text is a person's own message — it may answer an open question; Peppa's own words never do. */
export async function sendToSession(db: Db, sessionId: number, text: string, o: { person?: boolean } = {}): Promise<void> {
if (isRunnerClient()) return void (await runnerCall(db, "send", { sessionId, text, person: !!o.person }, { key: `session:${sessionId}` }));
const s = await getSession(db, sessionId);
if (!(await tmux.hasSession(tmux.sessionPane(s)))) 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", o.person ? { text, person: true } : { text });
await tmux.sendText(tmux.sessionPane(s), text);
await updateSession(db, s.id, { status: "running", lastActivityAt: new Date() });
}
export async function stopSession(db: Db, sessionId: number): Promise<void> {
if (isRunnerClient()) return void (await runnerCall(db, "stop", { sessionId }, { key: `session:${sessionId}` }));
const s = await getSession(db, sessionId);
await killRunner(s);
await expireSessionQuestions(db, s.id, m("(неактуально: агент остановлен)"));
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;
/**
* The key for the PM's answer in Claude Code's permission dialog. The menu differs by tool,
* by what is already allowed and by version — seen live on 2.1.323 (PEP-3): «1. Yes /
* 2. Yes, and always allow access to … / 3. Yes, and switch to auto mode … / 4. No», but also
* «1. Yes / 2. Yes, and switch to auto mode / 3. No» and «1. Yes / 2. Yes, and always allow … /
* 3. No». So the number is read off the screen; a fixed "2" could switch the session to auto
* mode and a fixed "3" could allow instead of deny. "always" without such a line = "Yes";
* "deny" without a "No" line = Escape (cancels the call).
*/
export function permissionKey(screen: string, answer: string): string | null {
const a = answer.trim().toLowerCase();
if (!["allow", "always", "deny"].includes(a)) return null;
// The dialog is the last menu on the screen: only look below its question.
const at = screen.lastIndexOf("Do you want to");
const lines = (at >= 0 ? screen.slice(at) : "").split("\n");
const opts = lines.map((l) => /^\s*(?:❯\s*)?(\d)\.\s+(.*)$/.exec(l)).filter((m): m is RegExpExecArray => !!m).map((m) => ({ key: m[1]!, text: m[2]!.trim() }));
const yes = opts.find((o) => /^Yes\s*$/i.test(o.text))?.key ?? "1";
if (a === "allow") return yes;
if (a === "always") return opts.find((o) => /^Yes, and (always|don't ask|do not ask)/i.test(o.text))?.key ?? yes;
return [...opts].reverse().find((o) => /^No\b/i.test(o.text))?.key ?? "Escape";
}
/** Typed after "No" in the dialog: Claude interrupts the turn there and waits silently (PEP-3). */
export const PERMISSION_DENIED_NOTE = "PM запретил это действие. Продолжай без него, а если без него никак — ask_pm и закончи ход.";
/**
* 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 }> {
if (isRunnerClient()) {
const pre = await getQuestion(db, questionId);
const key = pre.sessionId ? `session:${pre.sessionId}` : pre.taskId ? `task:${pre.taskId}` : null;
const r = await runnerCall<{ delivered: boolean; questionId: number }>(db, "answer", { questionId, answer, via }, { key });
return { delivered: r.delivered, question: await getQuestion(db, r.questionId) };
}
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(tmux.sessionPane(s)))) return { delivered: false, question: q };
if (q.kind === "permission") {
const key = permissionKey(await tmux.capturePane(tmux.sessionPane(s)).catch(() => ""), answer);
if (key) {
await tmux.sendKeys(tmux.sessionPane(s), key);
if (answer.trim().toLowerCase() === "deny") {
// The interrupted turn leaves an empty prompt; give the TUI a moment to draw it.
await new Promise((r) => setTimeout(r, Number(process.env.PEPPA_DENY_NOTE_DELAY_MS ?? 1500)));
await logSessionEvent(db, s, "input_sent", { text: PERMISSION_DENIED_NOTE });
await tmux.sendText(tmux.sessionPane(s), PERMISSION_DENIED_NOTE);
}
} else await tmux.sendText(tmux.sessionPane(s), answer);
} else {
await tmux.sendText(tmux.sessionPane(s), 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}`);
}