// PEP-10/27: runner settings (system → project → story) and a runner's story history/queue. import { m as tr } from "@peppa/shared/i18n"; import { runnerTasks, tasks, type Db } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; import { and, asc, desc, eq, inArray } from "drizzle-orm"; import { PeppaError } from "./errors.ts"; import { deleteSetting, getSetting, setSetting } from "./settings.ts"; import { projects } from "@peppa/db"; export const RUNNER_MODES = ["story", "queue"] as const; export const RUNNER_CONTEXTS = ["fresh", "continue"] as const; export const RUNNER_WORKSPACES = ["shared", "worktree"] as const; export const RUNNER_ISOLATIONS = ["none", "container"] as const; export type RunnerIsolation = (typeof RUNNER_ISOLATIONS)[number]; export type RunnerMode = (typeof RUNNER_MODES)[number]; export type RunnerContext = (typeof RUNNER_CONTEXTS)[number]; export type RunnerWorkspace = (typeof RUNNER_WORKSPACES)[number]; export interface RunnerSettings { /** story — one runner per story (default, as before PEP-10); queue — a runner takes the next story. */ mode: RunnerMode; /** fresh — new conversation for the next story (same tmux and working copy); continue — same conversation. */ context: RunnerContext; /** shared — the project's working copy (default); worktree — a git worktree per runner (PEP-27). */ workspace: RunnerWorkspace; /** Live runners per project; null = no limit. */ maxRunners: number | null; /** PEP-17: none — the agent runs directly in tmux (default); container — in the runner image. */ isolation: RunnerIsolation; /** PEP-40: hosts runners go to (least busy online one); empty — Peppa's own machine. */ hosts: number[]; } export type RunnerSettingsPatch = Partial; /** Which settings a story may override. */ export type TaskRunnerPatch = Partial>; export const DEFAULT_RUNNER_SETTINGS: RunnerSettings = { mode: "story", context: "fresh", workspace: "shared", maxRunners: null, isolation: "none", hosts: [] }; export const RUNNER_MODE_RU: Record = { story: tr("Один раннер на стори"), queue: tr("Раннер ведёт очередь стори") }; export const RUNNER_CONTEXT_RU: Record = { fresh: tr("Свежий контекст на стори"), continue: tr("Один разговор на все стори") }; export const RUNNER_WORKSPACE_RU: Record = { shared: tr("Общая рабочая копия"), worktree: tr("Свой git worktree на раннер") }; export const RUNNER_ISOLATION_RU: Record = { none: tr("Без изоляции (агент на машине)"), container: tr("Контейнер на раннер (docker)") }; const validHosts = (v: unknown): v is number[] => Array.isArray(v) && v.length <= 50 && v.every((n) => Number.isInteger(n) && n > 0); const SYSTEM_KEY = "platform.runner"; const projectKey = (projectId: number) => `project.runner:${projectId}`; const taskKey = (taskId: number) => `task.runner:${taskId}`; /** Drops unknown/invalid fields; null for maxRunners means "no limit", undefined "inherit". */ function clean(p: Record | null, allow: Array): RunnerSettingsPatch { const out: RunnerSettingsPatch = {}; if (!p) return out; if (allow.includes("mode") && RUNNER_MODES.includes(p.mode as RunnerMode)) out.mode = p.mode as RunnerMode; if (allow.includes("context") && RUNNER_CONTEXTS.includes(p.context as RunnerContext)) out.context = p.context as RunnerContext; if (allow.includes("workspace") && RUNNER_WORKSPACES.includes(p.workspace as RunnerWorkspace)) out.workspace = p.workspace as RunnerWorkspace; if (allow.includes("isolation") && RUNNER_ISOLATIONS.includes(p.isolation as RunnerIsolation)) out.isolation = p.isolation as RunnerIsolation; if (allow.includes("hosts") && validHosts(p.hosts)) out.hosts = [...new Set(p.hosts)]; if (allow.includes("maxRunners") && "maxRunners" in p) { const n = p.maxRunners; if (n === null) out.maxRunners = null; else if (Number.isInteger(n) && (n as number) >= 1 && (n as number) <= 50) out.maxRunners = n as number; } return out; } const ALL: Array = ["mode", "context", "workspace", "maxRunners", "isolation", "hosts"]; const TASK: Array = ["mode", "context"]; export async function getSystemRunnerSettings(db: Db): Promise { return clean(await getSetting(db, SYSTEM_KEY), ALL); } export async function getProjectRunnerSettings(db: Db, projectId: number): Promise { return clean(await getSetting(db, projectKey(projectId)), ALL); } export async function getTaskRunnerSettings(db: Db, taskId: number): Promise { return clean(await getSetting(db, taskKey(taskId)), TASK); } /** Effective settings: defaults ← system ← project ← story. */ export async function resolveRunnerSettings(db: Db, projectId: number, taskId?: number | null): Promise { return { ...DEFAULT_RUNNER_SETTINGS, ...(await getSystemRunnerSettings(db)), ...(await getProjectRunnerSettings(db, projectId)), ...(taskId ? await getTaskRunnerSettings(db, taskId) : {}), }; } /** Replaces the stored overrides at one level; an empty patch removes the row (= inherit). */ async function store(db: Db, key: string, patch: Record, allow: Array) { for (const [k, v] of Object.entries(patch)) { if (v === undefined) continue; if (!allow.includes(k as keyof RunnerSettings)) throw new PeppaError(tr("Неизвестная настройка раннеров: {k}", { k })); if (k === "maxRunners" && v !== null && !(Number.isInteger(v) && (v as number) >= 1 && (v as number) <= 50)) throw new PeppaError(tr("Лимит раннеров — от 1 до 50 или без лимита")); if (k === "hosts" && !validHosts(v)) throw new PeppaError(tr("Хосты — список номеров хостов")); if (k !== "maxRunners" && k !== "hosts" && !clean({ [k]: v }, allow)[k as keyof RunnerSettings]) throw new PeppaError(tr("Недопустимое значение {k}: {v}", { k, v: String(v) })); } const value = clean(patch, allow); if (Object.keys(value).length) await setSetting(db, key, value); else await deleteSetting(db, key); return value; } export const setSystemRunnerSettings = (db: Db, patch: RunnerSettingsPatch) => store(db, SYSTEM_KEY, patch, ALL); export const setProjectRunnerSettings = (db: Db, projectId: number, patch: RunnerSettingsPatch) => store(db, projectKey(projectId), patch, ALL); export const setTaskRunnerSettings = (db: Db, taskId: number, patch: TaskRunnerPatch) => store(db, taskKey(taskId), patch, TASK); // ── history and queue ────────────────────────────────────────────────────────── export type RunnerTask = typeof runnerTasks.$inferSelect; export interface RunnerTaskView extends RunnerTask { taskKey: string; taskTitle: string; taskStatus: string; } function rtQuery(db: Db) { return db .select({ rt: runnerTasks, key: projects.key, number: tasks.number, title: tasks.title, status: tasks.status }) .from(runnerTasks) .innerJoin(tasks, eq(runnerTasks.taskId, tasks.id)) .innerJoin(projects, eq(tasks.projectId, projects.id)); } const rtView = (r: { rt: RunnerTask; key: string; number: number; title: string; status: string }): RunnerTaskView => ({ ...r.rt, taskKey: formatTaskKey(r.key, r.number), taskTitle: r.title, taskStatus: r.status, }); /** A runner's stories: active and done (newest first), then the queue in pick order. */ export async function runnerStories(db: Db, sessionId: number): Promise<{ history: RunnerTaskView[]; queue: RunnerTaskView[] }> { const rows = (await rtQuery(db).where(eq(runnerTasks.sessionId, sessionId)).orderBy(desc(runnerTasks.id))).map(rtView); const queue = rows.filter((r) => r.status === "queued").sort(queueOrder); return { history: rows.filter((r) => r.status !== "queued"), queue }; } const queueOrder = (a: RunnerTask, b: RunnerTask) => Number(b.front) - Number(a.front) || (a.front ? b.id - a.id : a.id - b.id); /** The next story a runner takes (front items, newest first; then the oldest queued). */ export async function nextQueued(db: Db, sessionId: number): Promise { const rows = await db.select().from(runnerTasks).where(and(eq(runnerTasks.sessionId, sessionId), eq(runnerTasks.status, "queued"))).orderBy(asc(runnerTasks.id)); return rows.sort(queueOrder)[0] ?? null; } export async function queuedItems(db: Db, opts: { sessionIds?: number[]; taskId?: number } = {}): Promise { if (opts.sessionIds && !opts.sessionIds.length) return []; return db .select() .from(runnerTasks) .where( and( eq(runnerTasks.status, "queued"), opts.sessionIds ? inArray(runnerTasks.sessionId, opts.sessionIds) : undefined, opts.taskId != null ? eq(runnerTasks.taskId, opts.taskId) : undefined, ), ); } /** Puts a story into a runner's queue (once: an existing queued item is updated). */ export async function enqueueRunnerTask(db: Db, sessionId: number, taskId: number, opts: { prompt?: string | null; front?: boolean } = {}): Promise { await db.delete(runnerTasks).where(and(eq(runnerTasks.taskId, taskId), eq(runnerTasks.status, "queued"))); const [row] = await db .insert(runnerTasks) .values({ sessionId, taskId, status: "queued", prompt: opts.prompt ?? null, front: !!opts.front }) .returning(); return row!; } export async function dropQueuedTask(db: Db, taskId: number): Promise { const rows = await db.delete(runnerTasks).where(and(eq(runnerTasks.taskId, taskId), eq(runnerTasks.status, "queued"))).returning(); return rows.length; } /** The runner now works on `taskId`: its active row is closed, a new active row is written. */ export async function activateRunnerTask(db: Db, sessionId: number, taskId: number, queuedId?: number): Promise { const now = new Date(); await finishRunnerTask(db, sessionId); if (queuedId) await db.update(runnerTasks).set({ status: "active", startedAt: now }).where(eq(runnerTasks.id, queuedId)); else await db.insert(runnerTasks).values({ sessionId, taskId, status: "active", startedAt: now }); } /** Closes the runner's active story row (optionally only for one story). */ export async function finishRunnerTask(db: Db, sessionId: number, taskId?: number): Promise { await db .update(runnerTasks) .set({ status: "done", endedAt: new Date() }) .where(and(eq(runnerTasks.sessionId, sessionId), eq(runnerTasks.status, "active"), taskId != null ? eq(runnerTasks.taskId, taskId) : undefined)); }