peppa/packages/runner/src/rotation.ts
Асель ca57f9543b PEP-17/40: agent sandbox per runner (docker + agent relay) and runner hosts over SSH
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 07:57:28 +05:00

114 lines
6.3 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 {
expireSessionQuestions,
getSession,
getSubscription,
logSessionEvent,
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";
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";
export type RotateReason = "limit" | "threshold";
/** 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;
const carried = s.provider === "codex" || !s.conversationId ? "fresh" : "resume";
await (await import("./sessions.ts")).killRunner(s);
await expireSessionQuestions(db, s.id, "(неактуально: раннер переключён на другую подписку)");
await updateSession(db, s.id, {
subscriptionId: target.id,
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,
});
const who = s.taskKey ?? `Раннер ${s.id}`;
const prompt =
carried === "fresh"
? `Предыдущий запуск${s.taskKey ? ` над стори ${s.taskKey}` : ""} шёл на другой подписке и ${reason === "limit" ? "упёрся в лимит" : "подошёл к лимиту"}; разговор не перенесён. Восстанови контекст: peppa.get_task, tasks.md активного OpenSpec change, git status, git log и git diff в рабочей копии — и продолжай с того места.`
: `Раннер переключён на другую подписку (${reason === "limit" ? "на прежней лимит" : "прежняя подходит к лимиту"}). Продолжай с того места, где остановился.`;
// 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" ? ` до ${hhmm(from.limitedUntil)}` : ""}` : "подписка подходит к лимиту";
const how = carried === "resume" ? "продолжает тот же разговор" : "Codex не переносит разговор между аккаунтами — начал заново с контекстом из стори";
await sendProjectMessage(db, s.projectId, `🔁 ${who}: переключил с подписки «${from?.name ?? "?"}» на «${target.name}» (${why}), ${how}.`, `rot:${s.id}:g${resumed.generation}`, {
title: `${who}: другая подписка`,
url: s.taskKey ? `/t/${s.taskKey}` : `/runners?id=${s.id}`,
});
return getSession(db, s.id);
}
/**
* 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();
}