318 lines
18 KiB
TypeScript
318 lines
18 KiB
TypeScript
import { m } from "@peppa/shared/i18n";
|
||
import { actorColumns, getAgentLimits, listTasks } from "@peppa/core";
|
||
// PEP-10/27/53: a runner (tmux session with an agent) as a long-lived thing — a queue of
|
||
// stories, fresh context or one conversation between them, its own worktree, free runners.
|
||
import { existsSync } from "node:fs";
|
||
import {
|
||
activateRunnerTask,
|
||
agentAutonomyNote,
|
||
createTask,
|
||
dropQueuedTask,
|
||
enqueueRunnerTask,
|
||
finishRunnerTask,
|
||
FINISHED_SESSION_STATUSES,
|
||
getAutonomy,
|
||
getSession,
|
||
isNoCapacity,
|
||
waitForCapacity,
|
||
listSessions,
|
||
logEvent,
|
||
logSessionEvent,
|
||
nextQueued,
|
||
PeppaError,
|
||
pendingSessionQuestions,
|
||
queuedItems,
|
||
clearPlatformDelay,
|
||
platformDelay,
|
||
resolveTask,
|
||
resolveRunnerSettings,
|
||
updateSession,
|
||
updateTask,
|
||
type SessionView,
|
||
type TaskRef,
|
||
} from "@peppa/core";
|
||
import { events, projects, type Db } from "@peppa/db";
|
||
import { and, eq } from "drizzle-orm";
|
||
import * as tmux from "./tmux.ts";
|
||
import { relaunchFresh, resolveTaskById, resumeSession, sendToSession, startRunner, startSession, type StartOptions } from "./sessions.ts";
|
||
import { removeWorktree, switchWorktreeStory } from "./worktree.ts";
|
||
import { clearReviewRelease, resumeReleased } from "./review-release.ts";
|
||
import { isRunnerClient, runnerCall } from "./runner-client.ts";
|
||
|
||
/** Task statuses of the "in progress" board column: the runner is busy with the story. */
|
||
const WORKING = ["proposing", "awaiting_approval", "in_progress", "blocked"];
|
||
const isWorking = (status: string | null) => status != null && WORKING.includes(status);
|
||
/** The agent's turn is over (nothing is being typed or generated). */
|
||
const turnOver = (s: SessionView) => s.status === "idle" || s.status === "waiting_input";
|
||
|
||
async function projectOf(db: Db, projectId: number) {
|
||
const [p] = await db.select().from(projects).where(eq(projects.id, projectId));
|
||
if (!p) throw new PeppaError(`Project #${projectId} not found`);
|
||
return p;
|
||
}
|
||
|
||
/**
|
||
* A live queue runner that can take a story now: it has worked on stories (free runners
|
||
* belong to the person in the terminal), its story left work, its turn is over and it is
|
||
* not about to switch subscriptions.
|
||
*/
|
||
async function canTakeNow(db: Db, s: SessionView): Promise<boolean> {
|
||
if (FINISHED_SESSION_STATUSES.includes(s.status) || s.tmuxName.startsWith("pending-") || s.rotateReason) return false;
|
||
if (s.taskId == null || isWorking(s.taskStatus) || !turnOver(s)) return false;
|
||
return (await resolveRunnerSettings(db, s.projectId, s.taskId)).mode === "queue";
|
||
}
|
||
|
||
export interface AssignResult {
|
||
/** A new runner was started for the story. */
|
||
started?: number;
|
||
/** An existing runner took the story (now or from its queue). */
|
||
runner?: number;
|
||
queued?: boolean;
|
||
/** PEP-182: no room on the subscriptions — the story waits «В очереди» for a free agent. */
|
||
waiting?: boolean;
|
||
}
|
||
|
||
/** A new runner for the story; no room on the subscriptions (PEP-182) → the story waits in the queue. */
|
||
async function startOrWait(db: Db, ref: TaskRef, opts: StartOptions): Promise<AssignResult> {
|
||
// PEP-205: stories of one repository edit the same files — past the project's limit the story waits for a free place.
|
||
const inRepo = (await getAgentLimits(db, ref.project.id)).inRepo;
|
||
if (inRepo > 0) {
|
||
const working = (await listTasks(db, { projectId: ref.project.id, statuses: ["proposing", "in_progress"] })).filter((t) => t.id !== ref.task.id);
|
||
const busy = (await listSessions(db, { active: true, projectId: ref.project.id })).filter((s) => s.taskId != null && s.taskId !== ref.task.id && working.some((t) => t.id === s.taskId));
|
||
if (busy.length >= inRepo) {
|
||
await waitForCapacity(db, ref.task.id, opts.prompt);
|
||
await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, type: "capacity_wait", payload: { key: ref.key, why: "repo_limit", limit: inRepo } });
|
||
return { queued: true, waiting: true };
|
||
}
|
||
}
|
||
// PEP-299: the agent that gave its place while the story was in review continues its conversation.
|
||
const resumed = await resumeReleased(db, ref, opts.prompt);
|
||
if (resumed) return { started: resumed };
|
||
try {
|
||
const started = (await startSession(db, ref.key, opts)).id;
|
||
await clearReviewRelease(db, ref.task.id);
|
||
return { started };
|
||
} catch (e) {
|
||
if (!isNoCapacity(e)) throw e;
|
||
await waitForCapacity(db, ref.task.id, opts.prompt);
|
||
await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, type: "capacity_wait", payload: { key: ref.key } });
|
||
return { queued: true, waiting: true };
|
||
}
|
||
}
|
||
|
||
/**
|
||
* The story goes into work (board, dispatcher, CI, reviewer): by the runner settings —
|
||
* "story": a new runner (as before PEP-10); "queue": a free live runner of the project
|
||
* takes it, else a new runner while the limit allows, else the shortest queue.
|
||
*/
|
||
export async function startTaskOnRunner(db: Db, ref: TaskRef, opts: StartOptions = {}): Promise<AssignResult> {
|
||
if (isRunnerClient()) return runnerCall<AssignResult>(db, "assign", { task: ref.key, opts }, { key: `task:${ref.task.id}` });
|
||
const rs = await resolveRunnerSettings(db, ref.project.id, ref.task.id);
|
||
if (rs.mode === "story") return startOrWait(db, ref, opts);
|
||
if ((await queuedItems(db, { taskId: ref.task.id })).length) return { queued: true };
|
||
const live = await listSessions(db, { active: true, projectId: ref.project.id });
|
||
for (const s of live) {
|
||
if (!(await canTakeNow(db, s))) continue;
|
||
await enqueueRunnerTask(db, s.id, ref.task.id, { prompt: opts.prompt });
|
||
await advanceRunner(db, s.id);
|
||
return { runner: s.id, queued: false };
|
||
}
|
||
if (rs.maxRunners == null || live.length < rs.maxRunners) return startOrWait(db, ref, opts);
|
||
const hosts = live.filter((s) => s.taskId != null && !s.tmuxName.startsWith("pending-"));
|
||
if (!hosts.length) throw new PeppaError(m("Предел агентов проекта: {max}, очередь вести некому", { max: rs.maxRunners }));
|
||
const queues = await queuedItems(db, { sessionIds: hosts.map((s) => s.id) });
|
||
const load = (id: number) => queues.filter((q) => q.sessionId === id).length;
|
||
const host = hosts.sort((a, b) => load(a.id) - load(b.id) || a.id - b.id)[0]!;
|
||
await enqueueRunnerTask(db, host.id, ref.task.id, { prompt: opts.prompt });
|
||
await logSessionEvent(db, host, "task_queued", { taskId: ref.task.id, key: ref.key });
|
||
return { runner: host.id, queued: true };
|
||
}
|
||
|
||
/** PM puts a story into a runner's queue explicitly (web, CLI); taken when the runner is free. */
|
||
export async function queueTaskOnRunner(db: Db, sessionId: number, ref: TaskRef, prompt?: string): Promise<void> {
|
||
if (isRunnerClient()) return void (await runnerCall(db, "queue", { sessionId, task: ref.key, prompt }, { key: `session:${sessionId}` }));
|
||
const s = await getSession(db, sessionId);
|
||
if (s.projectId !== ref.project.id) throw new PeppaError(m("Агент из другого проекта"));
|
||
if (FINISHED_SESSION_STATUSES.includes(s.status)) throw new PeppaError(m("Агент #{id} не работает", { id: s.id }));
|
||
if (s.taskId === ref.task.id) throw new PeppaError(m("Агент #{id} уже ведёт {key}", { id: s.id, key: ref.key }));
|
||
if ((await listSessions(db, { active: true, taskId: ref.task.id })).length) throw new PeppaError(m("{key} уже ведёт другой агент", { key: ref.key }));
|
||
await enqueueRunnerTask(db, s.id, ref.task.id, { prompt });
|
||
await logSessionEvent(db, s, "task_queued", { taskId: ref.task.id, key: ref.key });
|
||
await advanceRunner(db, s.id);
|
||
}
|
||
|
||
/**
|
||
* "Done" in queue mode: the runner is released instead of stopped — it takes the next
|
||
* story of its queue, or stays idle without bothering the PM.
|
||
*/
|
||
export async function releaseRunner(db: Db, sessionId: number, taskId: number): Promise<void> {
|
||
const s = await getSession(db, sessionId);
|
||
await finishRunnerTask(db, s.id, taskId);
|
||
await logSessionEvent(db, s, "task_released", { taskId });
|
||
if (s.status === "waiting_input" && (await pendingSessionQuestions(db, s.id)).length === 0) await updateSession(db, s.id, { status: "idle" });
|
||
await advanceRunner(db, s.id);
|
||
}
|
||
|
||
/** True when the runner should leave its story for the next one (by its own settings). */
|
||
export async function runnerFollowsQueue(db: Db, s: SessionView): Promise<boolean> {
|
||
return (await resolveRunnerSettings(db, s.projectId, s.taskId)).mode === "queue";
|
||
}
|
||
|
||
/**
|
||
* Moves a free runner to the next story of its queue. Fresh context: a new run of the agent
|
||
* in the same tmux session and working copy; one conversation: a message to the live agent.
|
||
* In its own worktree the runner first switches to the story's branch (clean tree only).
|
||
*/
|
||
export async function advanceRunner(db: Db, sessionId: number, log: (m: string) => void = () => {}): Promise<boolean> {
|
||
let s = await getSession(db, sessionId);
|
||
if (FINISHED_SESSION_STATUSES.includes(s.status) || s.rotateReason || !turnOver(s) || isWorking(s.taskStatus)) return false;
|
||
for (;;) {
|
||
const item = await nextQueued(db, s.id);
|
||
if (!item) return false;
|
||
const ref = await resolveTaskById(db, item.taskId).catch(() => null);
|
||
if (!ref || ref.task.status === "done" || (await listSessions(db, { active: true, taskId: item.taskId })).some((x) => x.id !== s.id)) {
|
||
await dropQueuedTask(db, item.taskId);
|
||
continue;
|
||
}
|
||
const project = await projectOf(db, s.projectId);
|
||
let branch: string | null = null;
|
||
if (s.workspacePath && existsSync(s.workspacePath)) {
|
||
const sw = await switchWorktreeStory(project, s.workspacePath, ref.key);
|
||
if (!sw.ok) {
|
||
const told = await db.select().from(events).where(and(eq(events.sessionId, s.id), eq(events.type, "switch_blocked"), eq(events.taskId, ref.task.id)));
|
||
if (!told.length) {
|
||
await db.insert(events).values({ projectId: s.projectId, taskId: ref.task.id, sessionId: s.id, type: "switch_blocked", payload: { reason: sw.reason }, ...actorColumns(s.id) });
|
||
// PEP-150: a working copy that is not clean is not the owner's to fix.
|
||
await platformDelay(db, { projectId: s.projectId, taskId: ref.task.id, sessionId: s.id }, { reason: "switch", details: m("Агент не может перейти к {key}: {reason}. Сохраните или уберите эти изменения — агент возьмёт задачу сам.", { key: ref.key, reason: sw.reason }), log });
|
||
}
|
||
log(`#${s.id}: switch to ${ref.key} blocked — ${sw.reason}`);
|
||
return false;
|
||
}
|
||
branch = sw.branch;
|
||
await clearPlatformDelay(db, { projectId: s.projectId, taskId: ref.task.id }, "switch");
|
||
}
|
||
const from = s.taskKey;
|
||
if (!isWorking(ref.task.status)) await updateTask(db, ref, { status: "in_progress" });
|
||
await activateRunnerTask(db, s.id, ref.task.id, item.id);
|
||
await updateSession(db, s.id, { taskId: ref.task.id, autoNudges: 0 });
|
||
const rs = await resolveRunnerSettings(db, s.projectId, ref.task.id);
|
||
const note = agentAutonomyNote(await getAutonomy(db, s.projectId));
|
||
const work = [`Работай над стори ${ref.key} по правилам AGENTS.md.`, note, item.prompt].filter(Boolean).join("\n\n");
|
||
s = await getSession(db, s.id);
|
||
const alive = (await tmux.hasSession(tmux.sessionPane(s))) && !(await tmux.paneState(tmux.sessionPane(s))).dead;
|
||
if (rs.context === "continue") {
|
||
const text = `${from ? `Стори ${from} закончена. ` : ""}Следующая стори в этом же разговоре. ${work}`;
|
||
if (alive) await sendToSession(db, s.id, text);
|
||
else await resumeSession(db, s.id, { prompt: text });
|
||
} else {
|
||
await relaunchFresh(db, s.id, work);
|
||
}
|
||
await logSessionEvent(db, await getSession(db, s.id), "task_switched", { from, to: ref.key, context: rs.context, branch });
|
||
log(`#${s.id}: ${from ?? "—"} → ${ref.key} (${rs.context})`);
|
||
return true;
|
||
}
|
||
}
|
||
|
||
const keptLogged = new Set<number>();
|
||
|
||
/**
|
||
* Watchdog part (PEP-10/27): free queue runners take their next story; stories queued on a
|
||
* runner that died move to another/new one; finished runners' worktrees are removed when
|
||
* nothing would be lost.
|
||
*/
|
||
export async function runnerTick(db: Db, opts: { log?: (m: string) => void } = {}): Promise<void> {
|
||
const log = opts.log ?? (() => {});
|
||
const all = await listSessions(db);
|
||
const live = all.filter((s) => !FINISHED_SESSION_STATUSES.includes(s.status));
|
||
const liveIds = new Set(live.map((s) => s.id));
|
||
const queued = await queuedItems(db);
|
||
for (const id of new Set(queued.filter((q) => liveIds.has(q.sessionId)).map((q) => q.sessionId))) {
|
||
await advanceRunner(db, id, log).catch((e) => log(`runner #${id}: ${(e as Error).message}`));
|
||
}
|
||
// Orphans: the runner is gone — the story is assigned again (a new or another runner).
|
||
for (const q of queued.filter((q) => !liveIds.has(q.sessionId))) {
|
||
const ref = await resolveTaskById(db, q.taskId).catch(() => null);
|
||
if (!ref || !isWorking(ref.task.status)) {
|
||
await dropQueuedTask(db, q.taskId);
|
||
continue;
|
||
}
|
||
try {
|
||
await dropQueuedTask(db, q.taskId);
|
||
const r = await startTaskOnRunner(db, ref, { prompt: q.prompt ?? undefined });
|
||
log(`${ref.key}: runner #${q.sessionId} is gone, reassigned (${r.started ? `new #${r.started}` : `#${r.runner}`})`);
|
||
} catch (e) {
|
||
await enqueueRunnerTask(db, q.sessionId, q.taskId, { prompt: q.prompt, front: q.front });
|
||
log(`${ref.key}: reassign failed — ${(e as Error).message}`);
|
||
}
|
||
}
|
||
// PEP-27: worktrees of finished runners.
|
||
for (const s of all.filter((s) => FINISHED_SESSION_STATUSES.includes(s.status) && s.workspacePath && existsSync(s.workspacePath))) {
|
||
await cleanupWorktree(db, s, log).catch((e) => log(`worktree #${s.id}: ${(e as Error).message}`));
|
||
}
|
||
}
|
||
|
||
/** Removes a finished runner's worktree; logs `worktree_kept` once if something would be lost. */
|
||
export async function cleanupWorktree(db: Db, s: SessionView, log: (m: string) => void = () => {}): Promise<boolean> {
|
||
if (!s.workspacePath || !existsSync(s.workspacePath)) return true;
|
||
const project = await projectOf(db, s.projectId);
|
||
const r = await removeWorktree(project, s.workspacePath);
|
||
if (r.removed) {
|
||
await logSessionEvent(db, s, "worktree_removed", { path: s.workspacePath });
|
||
log(`#${s.id}: worktree removed`);
|
||
return true;
|
||
}
|
||
if (!keptLogged.has(s.id)) {
|
||
keptLogged.add(s.id);
|
||
const told = await db.select().from(events).where(and(eq(events.sessionId, s.id), eq(events.type, "worktree_kept")));
|
||
if (!told.length) await logSessionEvent(db, s, "worktree_kept", { path: s.workspacePath, reason: r.reason });
|
||
}
|
||
return false;
|
||
}
|
||
|
||
// ── PEP-53: free runners ─────────────────────────────────────────────────────
|
||
|
||
export interface FreeRunnerOptions extends Pick<StartOptions, "provider" | "subscriptionIds" | "poolId" | "model" | "permissionMode"> {
|
||
name?: string;
|
||
prompt?: string;
|
||
}
|
||
|
||
/** «Новый терминал»: a runner in the project without a story, driven by a person. */
|
||
export async function startFreeRunner(db: Db, projectId: number, opts: FreeRunnerOptions = {}): Promise<SessionView> {
|
||
if (isRunnerClient()) {
|
||
const r = await runnerCall<{ sessionId: number }>(db, "startFree", { projectId, opts }, { key: `project:${projectId}` });
|
||
return getSession(db, r.sessionId);
|
||
}
|
||
const project = await projectOf(db, projectId);
|
||
const intro = `Это свободный раннер в проекте ${project.key} без стори: работай по просьбам человека в терминале, правила FORGE (AGENTS.md) в силе. Стори, OpenSpec и PR — только если попросят.`;
|
||
const prompt = opts.prompt?.trim() ? `${intro}\n\n${opts.prompt.trim()}` : `${intro}\n\nПока просто жди указаний.`;
|
||
// glossary-ignore: свободный агент с терминалом есть только в виде «Инженер»
|
||
return startRunner(db, project, null, { ...opts, name: opts.name?.trim() || m("Новый терминал"), prompt });
|
||
}
|
||
|
||
export async function renameRunner(db: Db, sessionId: number, name: string): Promise<void> {
|
||
const s = await getSession(db, sessionId);
|
||
const clean = name.trim().slice(0, 80);
|
||
await updateSession(db, s.id, { name: clean || null });
|
||
await logSessionEvent(db, s, "renamed", { name: clean || null });
|
||
}
|
||
|
||
/**
|
||
* «Оформить стори»: a story is created from the free runner's work and goes into work on
|
||
* that runner; the agent is told to carry on by Peppa's rules.
|
||
*/
|
||
export async function promoteRunner(db: Db, sessionId: number, t: { title: string; description?: string; goalId?: number | null }): Promise<TaskRef> {
|
||
if (isRunnerClient()) return resolveTask(db, (await runnerCall<{ key: string }>(db, "promote", { sessionId, story: t }, { key: `session:${sessionId}` })).key);
|
||
const s = await getSession(db, sessionId);
|
||
if (s.taskId) throw new PeppaError(m("Агент #{id} уже ведёт задачу {key}", { id: s.id, key: s.taskKey }));
|
||
if (t.title.trim().length < 3) throw new PeppaError(m("Нужно название задачи"));
|
||
const created = await createTask(db, { projectId: s.projectId, title: t.title.trim(), description: t.description?.trim() || `Оформлено из раннера #${s.id}${s.name ? ` «${s.name}»` : ""}.`, goalId: t.goalId ?? undefined });
|
||
const ref: TaskRef = { ...created, task: await updateTask(db, created, { status: "in_progress" }, s.id) };
|
||
await updateSession(db, s.id, { taskId: ref.task.id, autoNudges: 0 });
|
||
await activateRunnerTask(db, s.id, ref.task.id);
|
||
await logSessionEvent(db, await getSession(db, s.id), "task_promoted", { key: ref.key });
|
||
if (!FINISHED_SESSION_STATUSES.includes(s.status) && (await tmux.hasSession(tmux.sessionPane(s)))) {
|
||
await sendToSession(db, s.id, `Эта работа оформлена как стори ${ref.key} «${ref.task.title}». Дальше веди её по правилам FORGE (peppa.get_task, OpenSpec change, PR, update_task(status: review)).`);
|
||
}
|
||
return ref;
|
||
}
|