import { chmodSync, existsSync, realpathSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { answerQuestion, claudeTokenForProject, createSession, expireSessionQuestions, getSession, 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"; export interface StartOptions { /** Extra instructions appended to the default "work on " 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 { 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 { 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 { 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 { 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 { 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 = { 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, ): 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}`; } 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}`); }