// 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, 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"; /** 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"; export type RotateReason = "limit" | "threshold"; /** How the PM calls the providers (PEP-107 messages). */ const PROVIDER_LABEL: Record = { 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 { 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 { 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 { 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" ? "упёрся в лимит" : "подошёл к лимиту"}; разговор не перенесён. Восстанови контекст: 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" ? m("лимит до {time}", { time: hhmm(from.limitedUntil) }) : 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); } /** * 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 { 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(); }