peppa/packages/runner/src/budgets.ts
2026-11-15 14:47:50 +05:00

125 lines
6.0 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.

// PEP-43: a story over its budget is paused — the current turn is interrupted (the process
// and the conversation stay), the agent is not pushed or relaunched automatically, and the
// PM decides: extend ×2, remove the limit, or stop. Nothing is killed silently.
import { m } from "@peppa/shared/i18n";
import {
answerQuestion,
askPm,
budgetOver,
describeBudget,
effectiveBudget,
extendBudget,
getBudgetState,
hasLimits,
listSessions,
logSessionEvent,
PeppaError,
setBudgetState,
setTaskBudget,
taskSpend,
updateSession,
BUDGET_LABELS,
type Question,
type SessionView,
} from "@peppa/core";
import { tasks, type Db } from "@peppa/db";
import { eq } from "drizzle-orm";
import * as tmux from "./tmux.ts";
import { onAnswer, resolveTaskById, sendToSession, stopSession } from "./sessions.ts";
export const BUDGET_EXTEND = m("➕ Продлить ×2");
export const BUDGET_UNLIMIT = m("♾ Снять лимит");
export const BUDGET_STOP = m("⏹ Остановить");
/** Watchdog: stories with a live runner that reached a budget limit get paused. */
export async function budgetTick(db: Db, o: { now?: Date; log?: (m: string) => void } = {}): Promise<number> {
const now = (o.now ?? new Date()).getTime();
const live = await listSessions(db, { active: true });
const byTask = new Map<number, SessionView[]>();
for (const s of live) if (s.taskId != null && !s.tmuxName.startsWith("pending-")) byTask.set(s.taskId, [...(byTask.get(s.taskId) ?? []), s]);
let paused = 0;
for (const [taskId, ss] of byTask) {
if (await getBudgetState(db, taskId)) continue;
const [task] = await db.select({ id: tasks.id, projectId: tasks.projectId }).from(tasks).where(eq(tasks.id, taskId));
if (!task) continue;
const { budget } = await effectiveBudget(db, task);
if (!hasLimits(budget)) continue;
const spend = await taskSpend(db, taskId, now);
const over = budgetOver(budget, spend);
if (!over.length) continue;
await pauseStory(db, taskId, ss, over, describeBudget({ budget, spend }), now);
o.log?.(`${ss[0]!.taskKey}: budget reached (${over.join(", ")}), paused`);
paused++;
}
return paused;
}
async function pauseStory(db: Db, taskId: number, ss: SessionView[], over: string[], summary: string, now: number) {
// Recorded first: a Stop hook firing right after the interrupt must already see the pause.
await setBudgetState(db, taskId, { pausedAt: now, over: over as never, questionId: null });
for (const s of ss) {
// Escape interrupts the agent's turn; the process and the conversation stay for «extend».
if (s.status === "running" || s.status === "starting" || s.status === "stalled") await tmux.sendKeys(tmux.sessionPane(s), "Escape").catch(() => {});
await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date(now) });
await logSessionEvent(db, s, "budget_paused", { over, summary });
}
const ref = await resolveTaskById(db, taskId);
const names = over.map((k) => BUDGET_LABELS[k as keyof typeof BUDGET_LABELS] ?? k).join(", ");
const q = await askPm(db, ref, {
kind: "question",
text: `${m("💸 {key}: исчерпан бюджет ({names}). Агент на паузе — ход прерван, разговор сохранён.", { key: ref.key, names })}\n\n${summary}`,
options: [BUDGET_EXTEND, BUDGET_UNLIMIT, BUDGET_STOP],
});
await setBudgetState(db, taskId, { pausedAt: now, over: over as never, questionId: q.id });
}
/** Resumes paused live runners of the story with a message. */
async function continueStory(db: Db, taskId: number, text: string) {
for (const s of await listSessions(db, { active: true, taskId })) {
if (!(await tmux.hasSession(tmux.sessionPane(s)))) continue;
await sendToSession(db, s.id, text).catch(() => {});
}
}
/** The PM's answer to a budget question (`onAnswer` registry). */
export async function onBudgetAnswer(db: Db, q: Question, answer: string): Promise<boolean> {
if (!q.taskId) return false;
const st = await getBudgetState(db, q.taskId);
if (!st || st.questionId !== q.id) return false;
const ref = await resolveTaskById(db, q.taskId);
const text = answer.trim();
await setBudgetState(db, q.taskId, null);
if (text.startsWith(BUDGET_EXTEND) || /^продл/i.test(text)) {
const { budget } = await effectiveBudget(db, ref.task);
const next = extendBudget(budget, await taskSpend(db, ref.task.id));
await setTaskBudget(db, ref.task.id, next);
await continueStory(db, ref.task.id, `Бюджет ${ref.key} продлён PM (${describeBudget({ budget: next, spend: await taskSpend(db, ref.task.id) })}). Продолжай работу с того места, где остановился.`);
return true;
}
if (text.startsWith(BUDGET_UNLIMIT) || /^сн(ять|яли|ими)/i.test(text)) {
await setTaskBudget(db, ref.task.id, {});
await continueStory(db, ref.task.id, `PM снял лимит бюджета ${ref.key}. Продолжай работу с того места, где остановился.`);
return true;
}
for (const s of await listSessions(db, { active: true, taskId: ref.task.id })) await stopSession(db, s.id);
return true;
}
onAnswer(onBudgetAnswer);
/**
* The PM changed the story's budget in the card: a pause the new budget no longer
* justifies is lifted (its question closed) and the runner continues.
*/
export async function budgetChanged(db: Db, taskId: number): Promise<void> {
const st = await getBudgetState(db, taskId);
if (!st) return;
const ref = await resolveTaskById(db, taskId);
const { budget } = await effectiveBudget(db, ref.task);
if (budgetOver(budget, await taskSpend(db, taskId)).length) return;
await setBudgetState(db, taskId, null);
if (st.questionId) {
await answerQuestion(db, st.questionId, m("(бюджет изменён в карточке)"), "system").catch(() => {});
}
await continueStory(db, taskId, `Бюджет ${ref.key} изменён PM. Продолжай работу с того места, где остановился.`);
}