peppa/packages/runner/src/rotation.ts

179 lines
10 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.

// Subscription rotation (PEP-39): a session that hit a usage limit — or got close to it —
// moves to another usable subscription of its pool at a turn boundary, continuing the same
// conversation where the CLI allows it. Decided by the watchdog; hooks only set flags.
import { m } from "@peppa/shared/i18n";
import {
expireSessionQuestions,
getSession,
getSubscription,
isUsable,
liveBySubscription,
subscriptionCapacities,
listSessions,
logSessionEvent,
PeppaError,
rotationCandidate,
sendProjectMessage,
updateSession,
type SessionView,
type Subscription,
} from "@peppa/core";
import { events, type Db } from "@peppa/db";
import { and, count, eq, gte } from "drizzle-orm";
import * as tmux from "./tmux.ts";
import { isRunnerClient, runnerCall } from "./runner-client.ts";
export const SWITCH_EVENT = "subscription_switched";
export const ROTATE_WINDOW_MS = 60 * 60_000;
export const maxRotationsPerHour = () => Number(process.env.PEPPA_ROTATE_MAX_PER_HOUR ?? 3);
export const rotateThresholdPct = () => Number(process.env.PEPPA_ROTATE_THRESHOLD_PCT ?? 85);
export const rotationEnabled = () => process.env.PEPPA_ROTATE !== "off" && process.env.PEPPA_LIMIT_AUTORESUME !== "off";
/** PEP-170: move early, at the usage-warning threshold — off by default (switch only when a subscription has run out). */
export const earlyRotationEnabled = () => process.env.PEPPA_ROTATE_EARLY === "on";
/** PEP-176: "manual" — the superadmin moved the agents by hand. */
/** PEP-205: "login" — the agent CLI could not sign in on the subscription three times in a row. */
export type RotateReason = "limit" | "threshold" | "manual" | "loan" | "login";
/** How the PM calls the providers (PEP-107 messages). */
const PROVIDER_LABEL: Record<Subscription["provider"], string> = { claude: "Claude", codex: "ChatGPT (Codex)", opencode: "OpenCode" };
/** Switches of this session within the last hour (events written by rotateSession). */
export async function rotationsLastHour(db: Db, sessionId: number, now = new Date()): Promise<number> {
const [row] = await db
.select({ n: count() })
.from(events)
.where(and(eq(events.sessionId, sessionId), eq(events.type, SWITCH_EVENT), gte(events.createdAt, new Date(now.getTime() - ROTATE_WINDOW_MS))));
return row?.n ?? 0;
}
/**
* The subscription the session would move to now, or null: rotation off, no subscription
* (this machine's login), no pool, nothing usable, or the hourly budget is spent.
*/
export async function planRotation(db: Db, s: SessionView, reason: RotateReason, now = new Date()): Promise<Subscription | null> {
if (!rotationEnabled() || s.subscriptionId == null) return null;
if ((await rotationsLastHour(db, s.id, now)) >= maxRotationsPerHour()) return null;
return rotationCandidate(db, s, { now, onlyIdle: reason === "threshold" });
}
const hhmm = (d: Date) => d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" });
/**
* Relaunches the session on `target`: Claude Code and OpenCode continue the same
* conversation (transcripts are local, only the login changes); Codex keeps its threads in
* the account's CODEX_HOME, so it starts afresh and rebuilds context from the story.
* Call only at a turn boundary — the agent process is killed.
*/
export async function rotateSession(db: Db, s: SessionView, target: Subscription, reason: RotateReason, now = new Date()): Promise<SessionView> {
const from = s.subscriptionId ? await getSubscription(db, s.subscriptionId).catch(() => null) : null;
// PEP-107: another provider (Claude ↔ Codex) — conversations don't move between CLIs.
const crossed = target.provider !== s.provider;
const carried = crossed || s.provider === "codex" || !s.conversationId ? "fresh" : "resume";
await (await import("./sessions.ts")).killRunner(s);
await expireSessionQuestions(db, s.id, m("(неактуально: агент переключён на другую подписку)"));
await updateSession(db, s.id, {
subscriptionId: target.id,
...(crossed ? { provider: target.provider } : {}),
rotateReason: null,
resumeAt: null,
limitProbeMin: null,
...(carried === "fresh" ? { conversationId: null } : {}),
});
await logSessionEvent(db, s, SWITCH_EVENT, {
fromId: from?.id ?? s.subscriptionId,
fromName: from?.name ?? s.subscriptionName,
toId: target.id,
toName: target.name,
reason,
carried,
limitedUntil: from?.status === "limited" ? from.limitedUntil : null,
...(crossed ? { fromProvider: s.provider, toProvider: target.provider } : {}),
});
const who = s.taskKey ?? m("Агент №{id}", { id: s.id });
const prompt =
carried === "fresh"
? `Предыдущий запуск${s.taskKey ? ` над стори ${s.taskKey}` : ""} шёл на другой подписке и ${reason === "limit" ? "упёрся в лимит" : reason === "manual" ? "был переключён администратором" : reason === "loan" ? "был на одолженной подписке, её срок кончился" : reason === "login" ? "не смог войти в аккаунт" : "подошёл к лимиту"}; разговор не перенесён. Восстанови контекст: peppa.get_task, tasks.md активного OpenSpec change, git status, git log и git diff в рабочей копии — и продолжай с того места.`
: `Раннер переключён на другую подписку (${reason === "limit" ? "на прежней лимит" : reason === "manual" ? "переключил администратор" : reason === "loan" ? "срок одолженной подписки кончился" : reason === "login" ? "на прежней не удался вход" : "прежняя подходит к лимиту"}). Продолжай с того места, где остановился.`;
// Loaded lazily: the hook process imports this module (via limits) and stays light.
const { resumeSession } = await import("./sessions.ts");
const resumed = await resumeSession(db, s.id, { prompt });
const why =
reason === "limit"
? from?.limitedUntil && from.status === "limited"
? m("лимит до {time}", { time: hhmm(from.limitedUntil) })
: m("лимит")
: reason === "manual"
? m("переключил администратор")
: reason === "loan"
? m("срок одолженной подписки кончился")
: reason === "login"
? m("на прежней не удался вход")
: m("подписка подходит к лимиту");
const how = crossed
? m("теперь работает на {provider} — начал заново по описанию задачи", { provider: PROVIDER_LABEL[target.provider] })
: carried === "resume"
? m("продолжает тот же разговор")
: m("ChatGPT не переносит разговор между подписками — начал заново по описанию задачи");
const vars = { who, why, how };
const text = crossed ? m("🔁 {who}: переехал на другую подписку ({why}), {how}.", vars) : m("🔁 {who}: перешёл на другую подписку ({why}), {how}.", vars);
await sendProjectMessage(db, s.projectId, text, `rot:${s.id}:g${resumed.generation}`, {
title: m("{who}: другая подписка", { who }),
url: s.taskKey ? `/t/${s.taskKey}` : `/runners?id=${s.id}`,
});
return getSession(db, s.id);
}
/**
* PEP-176: the superadmin moves every agent off a subscription — to `toId`, or each to the least
* busy working subscription of its pools (another provider if none of its own). The agent is
* relaunched at once (Claude continues the same conversation).
*/
export async function switchAgents(db: Db, o: { fromId: number; toId?: number | null; now?: Date }): Promise<{ moved: number; skipped: number }> {
// PEP-21: clients (web) hand it to the runner service — it kills and relaunches agents.
if (isRunnerClient()) return runnerCall(db, "switchAgents", { fromId: o.fromId, toId: o.toId ?? null }, { key: `subscription:${o.fromId}` });
const now = o.now ?? new Date();
const fixed = o.toId ? await getSubscription(db, o.toId) : null;
if (fixed && fixed.id === o.fromId) throw new PeppaError(m("Агенты уже на этой подписке"));
if (fixed && !isUsable(fixed, now)) throw new PeppaError(m("Подписка «{name}» сейчас не работает — выберите другую", { name: fixed.name }));
const sessions = (await listSessions(db, { active: true })).filter((s) => s.subscriptionId === o.fromId);
let moved = 0;
let skipped = 0;
// PEP-182: a chosen subscription takes agents only up to its capacity; the rest stay put.
let room = fixed ? (await subscriptionCapacities(db))(fixed.id) - ((await liveBySubscription(db)).get(fixed.id) ?? 0) : Infinity;
for (const s of sessions) {
const target = fixed ? (room > 0 ? fixed : null) : await rotationCandidate(db, s, { now });
if (fixed && target) room--;
if (!target) {
skipped++;
continue;
}
await rotateSession(db, s, target, "manual", now);
moved++;
}
return { moved, skipped };
}
/**
* The turn is over (Stop / StopFailure / limit banner): move the session if it waits for a
* rotation and somewhere to go exists. Returns true when the session was relaunched.
*/
export async function tryRotate(db: Db, s: SessionView, reason: RotateReason, now = new Date(), log: (m: string) => void = () => {}): Promise<boolean> {
const target = await planRotation(db, s, reason, now);
if (!target) return false;
await rotateSession(db, s, target, reason, now);
log(`#${s.id} ${s.taskKey ?? ""}: subscription ${s.subscriptionName ?? s.subscriptionId} → ${target.name} (${reason})`);
return true;
}
/** Usage warning on screen: "approaching usage limit", "used 90% of your weekly limit". */
const WARN_RE = /(approaching (?:your )?(?:usage )?limit|(\d{1,3})\s?% of your [^\n]{0,40}limit|used (\d{1,3})\s?%)/i;
/** True when the screen shows a usage warning at or above the threshold. */
export function usageWarning(screen: string): boolean {
const m = WARN_RE.exec(screen);
if (!m) return false;
const pct = Number(m[2] ?? m[3] ?? NaN);
return Number.isNaN(pct) || pct >= rotateThresholdPct();
}