Ёмкость подписки (core/capacity.ts, по умолчанию 9, суперадмин меняет на набор 1–20); pickSubscription, ротация и ручной перевод агентов уважают ёмкость; без места задача ждёт в очереди и запускается сама по порядку доски (capacityQueueTick); команда растёт только в пределах ёмкости; экраны «Подписки», Главная, доска, страница задачи; ru/kk/en; тест subscription-capacity.test.ts; OpenSpec change archived. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
355 lines
19 KiB
TypeScript
355 lines
19 KiB
TypeScript
// PEP-107: development doesn't stop on a limit — what a pool looks like right now (which
|
||
// subscription is at work, when a limit resets), an early warning when a project is down to
|
||
// its last subscription, and a superadmin lending a spare subscription to someone's pool.
|
||
import { events, projects, sessions, settings, subscriptionPoolMembers, tasks, type Db } from "@peppa/db";
|
||
import { and, desc, eq, inArray, like } from "drizzle-orm";
|
||
import { m as tr, ruPlural } from "@peppa/shared/i18n";
|
||
import { logEvent } from "./audit.ts";
|
||
import { PeppaError } from "./errors.ts";
|
||
import { sendProjectMessage } from "./notifications.ts";
|
||
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
|
||
import { getPool, getSubscription, isUsable, listPools, listSubscriptions, requireSuperadmin, type Subscription, type SubscriptionPool } from "./subscriptions.ts";
|
||
import { capacityQueue, poolCapacities, defaultCapacity } from "./capacity.ts";
|
||
import { visibleSubscriptionName, type SubscriptionViewer } from "./subscription-names.ts";
|
||
import { listAccountUsage, type WindowView } from "./usage.ts";
|
||
import type { User } from "./users.ts";
|
||
|
||
export const warnThresholdPct = () => Number(process.env.PEPPA_ROTATE_THRESHOLD_PCT ?? 85);
|
||
|
||
const hhmm = (d: Date) => d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });
|
||
|
||
// ── loans ────────────────────────────────────────────────────────────────────────
|
||
|
||
export interface Loan {
|
||
poolId: number;
|
||
subscriptionId: number;
|
||
until: Date;
|
||
byLogin: string;
|
||
}
|
||
|
||
const LOAN_PREFIX = "subscription.loan:";
|
||
const loanKey = (poolId: number, subscriptionId: number) => `${LOAN_PREFIX}${poolId}:${subscriptionId}`;
|
||
interface LoanRow {
|
||
until: number;
|
||
by: string;
|
||
}
|
||
|
||
export async function listLoans(db: Db): Promise<Loan[]> {
|
||
const rows = await db.select().from(settings).where(like(settings.key, `${LOAN_PREFIX}%`));
|
||
return rows.map((r) => {
|
||
const [poolId, subscriptionId] = r.key.slice(LOAN_PREFIX.length).split(":").map(Number);
|
||
const v = r.value as LoanRow;
|
||
return { poolId: poolId!, subscriptionId: subscriptionId!, until: new Date(v.until), byLogin: v.by };
|
||
});
|
||
}
|
||
|
||
async function poolProjects(db: Db, poolId: number) {
|
||
return db.select({ id: projects.id, key: projects.key, name: projects.name }).from(projects).where(eq(projects.subscriptionPoolId, poolId));
|
||
}
|
||
|
||
async function tellPool(db: Db, poolId: number, type: string, payload: Record<string, unknown>, text: string, dedupe: string) {
|
||
for (const p of await poolProjects(db, poolId)) {
|
||
await logEvent(db, { projectId: p.id, type, payload });
|
||
await sendProjectMessage(db, p.id, text, `${dedupe}:p${p.id}`, { title: tr("Подписки"), url: `/p/${p.key}#subscription` });
|
||
}
|
||
}
|
||
|
||
/**
|
||
* A superadmin lends a subscription to a pool for `hours` (1..168): it joins the pool at once,
|
||
* and the watchdog takes it back when the time is up (`expireLoans`).
|
||
*/
|
||
export async function lendSubscription(db: Db, admin: Pick<User, "login">, o: { subscriptionId: number; poolId: number; hours: number; now?: Date; /** PEP-186: an exact end instead of `hours` from now. */ until?: Date; /** PEP-186: the caller tells the project itself. */ quiet?: boolean }): Promise<Loan> {
|
||
await requireSuperadmin(db, admin);
|
||
const hours = Math.floor(o.hours);
|
||
if (!(hours >= 1 && hours <= 168)) throw new PeppaError(tr("Срок займа — от 1 до 168 часов"));
|
||
const sub = await getSubscription(db, o.subscriptionId);
|
||
const pool = await getPool(db, o.poolId);
|
||
if (sub.status === "pending" || sub.status === "auth_error") throw new PeppaError(tr("Подписка «{name}» не подключена — одолжить можно только рабочую", { name: sub.name }));
|
||
const member = await db.select().from(subscriptionPoolMembers).where(and(eq(subscriptionPoolMembers.poolId, pool.id), eq(subscriptionPoolMembers.subscriptionId, sub.id)));
|
||
// glossary-ignore: пулами подписок управляет только суперадмин
|
||
if (member.length) throw new PeppaError(tr("Подписка уже в этом пуле"));
|
||
const until = o.until ?? new Date((o.now ?? new Date()).getTime() + hours * 3_600_000);
|
||
db.transaction((tx) => {
|
||
tx.insert(subscriptionPoolMembers).values({ poolId: pool.id, subscriptionId: sub.id }).run();
|
||
});
|
||
await setSetting(db, loanKey(pool.id, sub.id), { until: until.getTime(), by: admin.login } satisfies LoanRow);
|
||
if (o.quiet) {
|
||
for (const p of await poolProjects(db, pool.id)) await logEvent(db, { projectId: p.id, type: "subscription_lent", payload: { subscriptionId: sub.id, name: sub.name, until: until.toISOString(), login: admin.login } });
|
||
return { poolId: pool.id, subscriptionId: sub.id, until, byLogin: admin.login };
|
||
}
|
||
await tellPool(
|
||
db,
|
||
pool.id,
|
||
"subscription_lent",
|
||
{ subscriptionId: sub.id, name: sub.name, until: until.toISOString(), login: admin.login },
|
||
tr("🎁 Вам на время добавлена запасная подписка — до {time}. Если основная упрётся в лимит, агенты продолжат на запасной.", { time: hhmm(until) }),
|
||
`loan:${pool.id}:${sub.id}:${until.getTime()}`,
|
||
);
|
||
return { poolId: pool.id, subscriptionId: sub.id, until, byLogin: admin.login };
|
||
}
|
||
|
||
/** Takes a lent subscription back out of the pool. Runners already on it finish their run. */
|
||
export async function returnLoan(db: Db, poolId: number, subscriptionId: number, why: "expired" | "returned" = "returned", o: { quiet?: boolean } = {}): Promise<boolean> {
|
||
const loan = await getSetting<LoanRow>(db, loanKey(poolId, subscriptionId));
|
||
if (!loan) return false;
|
||
db.transaction((tx) => {
|
||
tx.delete(subscriptionPoolMembers).where(and(eq(subscriptionPoolMembers.poolId, poolId), eq(subscriptionPoolMembers.subscriptionId, subscriptionId))).run();
|
||
});
|
||
await deleteSetting(db, loanKey(poolId, subscriptionId));
|
||
const sub = await getSubscription(db, subscriptionId).catch(() => null);
|
||
if (o.quiet) {
|
||
for (const p of await poolProjects(db, poolId)) await logEvent(db, { projectId: p.id, type: "subscription_returned", payload: { subscriptionId, name: sub?.name ?? null, why } });
|
||
return true;
|
||
}
|
||
await tellPool(
|
||
db,
|
||
poolId,
|
||
"subscription_returned",
|
||
{ subscriptionId, name: sub?.name ?? null, why },
|
||
why === "expired"
|
||
? tr("Запасная подписка вернулась владельцу — срок займа кончился. Агенты, которые уже на ней, доработают текущий запуск.")
|
||
: tr("Запасная подписка вернулась владельцу. Агенты, которые уже на ней, доработают текущий запуск."),
|
||
`loanback:${poolId}:${subscriptionId}:${loan.until}`,
|
||
);
|
||
return true;
|
||
}
|
||
|
||
/** Superadmin's «Вернуть сейчас». */
|
||
export async function returnLoanNow(db: Db, admin: Pick<User, "login">, poolId: number, subscriptionId: number): Promise<void> {
|
||
await requireSuperadmin(db, admin);
|
||
if (!(await returnLoan(db, poolId, subscriptionId, "returned"))) throw new PeppaError(tr("Займа уже нет"));
|
||
}
|
||
|
||
/** Watchdog: loans whose time is up go back. Returns how many. */
|
||
export async function expireLoans(db: Db, now = new Date()): Promise<number> {
|
||
let n = 0;
|
||
for (const l of await listLoans(db)) if (l.until <= now && (await returnLoan(db, l.poolId, l.subscriptionId, "expired"))) n++;
|
||
return n;
|
||
}
|
||
|
||
// ── the pool at a glance ─────────────────────────────────────────────────────────
|
||
|
||
export interface PoolSubscriptionState {
|
||
id: number;
|
||
name: string;
|
||
provider: Subscription["provider"];
|
||
status: Subscription["status"];
|
||
createdBy: number | null;
|
||
usable: boolean;
|
||
/** Runners on it now (not finished). */
|
||
activeSessions: number;
|
||
limitedUntil: Date | null;
|
||
/** The fuller usage window (5 h / 7 d), when the CLI reports one (Claude). */
|
||
usage: (WindowView & { label: string }) | null;
|
||
loan: Loan | null;
|
||
/** PEP-170: the free subscription an agent of this pool moves to when its own runs out. */
|
||
next: boolean;
|
||
/** PEP-182: live runners it may hold (the set's value). */
|
||
capacity: number;
|
||
/** «агентов: 6 из 9». */
|
||
load: string;
|
||
/** PEP-177: whose subscription (the person's name); null when the viewer must not see it. */
|
||
ownerName: string | null;
|
||
/** PEP-178: the account e-mail; null when the viewer must not see it. */
|
||
accountEmail: string | null;
|
||
/** «в работе: 2 агента» / «свободна» / «лимит до 15:40» / «ждёт входа» / «ошибка входа». */
|
||
label: string;
|
||
}
|
||
|
||
export interface PoolOverview {
|
||
pool: SubscriptionPool;
|
||
projects: Array<{ id: number; key: string; name: string }>;
|
||
subscriptions: PoolSubscriptionState[];
|
||
usableCount: number;
|
||
/** Runners of the pool's subscriptions waiting for a limit reset. */
|
||
waiting: number;
|
||
/** PEP-170: the latest switches between this pool's subscriptions, newest first. */
|
||
switches: SubscriptionSwitch[];
|
||
/** PEP-182: live runners per subscription of the set; `live` of `total` (capacity × usable subscriptions). */
|
||
capacity: number;
|
||
live: number;
|
||
total: number;
|
||
/** Stories of the set's projects waiting for a free agent. */
|
||
queued: number;
|
||
}
|
||
|
||
export interface SubscriptionSwitch {
|
||
at: Date;
|
||
taskKey: string | null;
|
||
sessionId: number | null;
|
||
fromName: string;
|
||
toName: string;
|
||
reason: "limit" | "threshold" | "manual";
|
||
}
|
||
|
||
const atWork = (n: number) => tr(ruPlural(n, "в работе: {n} агент", "в работе: {n} агента", "в работе: {n} агентов"), { n });
|
||
|
||
const SWITCHES_SHOWN = 5;
|
||
const SWITCHES_WINDOW_MS = 7 * 86_400_000;
|
||
|
||
/** PEP-170: subscription switches of the last week (events written by rotateSession), newest first. */
|
||
async function recentSwitches(db: Db, now: Date) {
|
||
const rows = await db
|
||
.select({ at: events.createdAt, payload: events.payload, sessionId: events.sessionId, taskKey: tasks.number, projectKey: projects.key })
|
||
.from(events)
|
||
.innerJoin(projects, eq(events.projectId, projects.id))
|
||
.leftJoin(tasks, eq(events.taskId, tasks.id))
|
||
.where(eq(events.type, "subscription_switched"))
|
||
.orderBy(desc(events.createdAt))
|
||
.limit(200);
|
||
return rows
|
||
.filter((r) => r.at.getTime() > now.getTime() - SWITCHES_WINDOW_MS)
|
||
.map((r) => {
|
||
const p = (r.payload ?? {}) as { fromId?: number | null; fromName?: string | null; toId?: number; toName?: string; reason?: string };
|
||
return {
|
||
at: r.at,
|
||
taskKey: r.taskKey != null ? `${r.projectKey}-${r.taskKey}` : null,
|
||
sessionId: r.sessionId,
|
||
fromId: p.fromId ?? null,
|
||
fromName: p.fromName ?? "—",
|
||
toId: p.toId ?? -1,
|
||
toName: p.toName ?? "—",
|
||
reason: p.reason === "threshold" ? ("threshold" as const) : p.reason === "manual" ? ("manual" as const) : ("limit" as const),
|
||
};
|
||
});
|
||
}
|
||
|
||
function stateLabel(s: Omit<PoolSubscriptionState, "label" | "next" | "capacity" | "load">): string {
|
||
if (s.status === "pending") return tr("ждёт входа");
|
||
if (s.status === "auth_error") return tr("ошибка входа — подключите заново");
|
||
if (s.limitedUntil) return tr("лимит до {time}", { time: hhmm(s.limitedUntil) });
|
||
return s.activeSessions ? atWork(s.activeSessions) : tr("свободна");
|
||
}
|
||
|
||
/** `viewer` (PEP-121): whose eyes — names of subscriptions connected by others are neutral for a non-admin; omitted = real names (superadmin pages, the watchdog). */
|
||
export async function poolOverviews(db: Db, poolIds?: number[], now = new Date(), viewer?: SubscriptionViewer): Promise<PoolOverview[]> {
|
||
const pools = (await listPools(db)).filter((p) => !poolIds || poolIds.includes(p.id));
|
||
if (!pools.length) return [];
|
||
const subs = await listSubscriptions(db);
|
||
const ids = [...new Set(pools.flatMap((p) => p.subscriptionIds))];
|
||
const usage = new Map((await listAccountUsage(db, { subscriptionIds: ids, machine: false, now: now.getTime() })).map((u) => [u.subscriptionId, u]));
|
||
const loans = await listLoans(db);
|
||
const waitingRows = ids.length
|
||
? await db.select({ subscriptionId: sessions.subscriptionId }).from(sessions).where(and(eq(sessions.status, "rate_limited"), inArray(sessions.subscriptionId, ids)))
|
||
: [];
|
||
const allProjects = await db.select({ id: projects.id, key: projects.key, name: projects.name, poolId: projects.subscriptionPoolId }).from(projects);
|
||
const switches = await recentSwitches(db, now);
|
||
const caps = await poolCapacities(db);
|
||
const queue = await capacityQueue(db);
|
||
const nameOf = (id: number, fallback: string) => {
|
||
const s = subs.find((x) => x.id === id);
|
||
return s && viewer ? visibleSubscriptionName(s, viewer) : fallback;
|
||
};
|
||
return pools.map((p) => {
|
||
const capacity = caps.get(p.id) ?? defaultCapacity();
|
||
const list = p.subscriptionIds.map((id) => subs.find((s) => s.id === id)).filter((s): s is NonNullable<typeof s> => !!s);
|
||
const states = list.map((s) => {
|
||
const u = usage.get(s.id);
|
||
const w = [u?.fiveHour ? { ...u.fiveHour, label: tr("5 ч") } : null, u?.sevenDay ? { ...u.sevenDay, label: tr("7 д") } : null]
|
||
.filter((x): x is NonNullable<typeof x> => !!x && x.pct != null && !u?.stale)
|
||
.sort((a, b) => b.pct! - a.pct!)[0] ?? null;
|
||
const base = {
|
||
id: s.id,
|
||
name: viewer ? visibleSubscriptionName(s, viewer) : s.name,
|
||
// A neutral name for a non-admin hides whose it is too (PEP-121).
|
||
ownerName: viewer && visibleSubscriptionName(s, viewer) !== s.name ? null : s.ownerName,
|
||
accountEmail: viewer && visibleSubscriptionName(s, viewer) !== s.name ? null : s.accountEmail,
|
||
provider: s.provider,
|
||
status: s.status,
|
||
createdBy: s.createdBy,
|
||
usable: isUsable(s, now),
|
||
activeSessions: s.activeSessions,
|
||
limitedUntil: s.status === "limited" && s.limitedUntil && s.limitedUntil > now ? s.limitedUntil : null,
|
||
usage: w,
|
||
loan: loans.find((l) => l.poolId === p.id && l.subscriptionId === s.id) ?? null,
|
||
};
|
||
return { ...base, next: false, label: stateLabel(base), capacity, load: tr("агентов: {n} из {max}", { n: base.activeSessions, max: capacity }) };
|
||
});
|
||
// Mirrors rotationCandidate: a free usable subscription, the lowest id first.
|
||
const next = states.filter((x) => x.usable && !x.activeSessions).sort((a, b) => a.id - b.id)[0];
|
||
if (next && states.some((x) => x.id !== next.id && x.usable && x.activeSessions)) next.next = true;
|
||
const memberIds = new Set(p.subscriptionIds);
|
||
return {
|
||
pool: p,
|
||
projects: allProjects.filter((x) => x.poolId === p.id).map(({ id, key, name }) => ({ id, key, name })),
|
||
subscriptions: states,
|
||
usableCount: states.filter((s) => s.usable).length,
|
||
capacity,
|
||
live: states.reduce((n, s) => n + s.activeSessions, 0),
|
||
total: capacity * states.filter((s) => s.usable).length,
|
||
queued: queue.filter((q) => q.poolId === p.id).length,
|
||
waiting: waitingRows.filter((r) => r.subscriptionId != null && memberIds.has(r.subscriptionId)).length,
|
||
switches: switches.filter((x) => memberIds.has(x.toId) || (x.fromId != null && memberIds.has(x.fromId))).slice(0, SWITCHES_SHOWN).map((x) => ({
|
||
at: x.at,
|
||
taskKey: x.taskKey,
|
||
sessionId: x.sessionId,
|
||
reason: x.reason,
|
||
fromName: x.fromId != null ? nameOf(x.fromId, x.fromName) : x.fromName,
|
||
toName: nameOf(x.toId, x.toName),
|
||
})),
|
||
};
|
||
});
|
||
}
|
||
|
||
export async function poolOverview(db: Db, poolId: number, now = new Date(), viewer?: SubscriptionViewer): Promise<PoolOverview | null> {
|
||
return (await poolOverviews(db, [poolId], now, viewer))[0] ?? null;
|
||
}
|
||
|
||
// ── early warning ────────────────────────────────────────────────────────────────
|
||
|
||
const WARNED = (subscriptionId: number, poolId: number) => `subscription.warned:${subscriptionId}:${poolId}`;
|
||
const BANNER_REPEAT_MS = 5 * 3_600_000;
|
||
|
||
async function warnPool(db: Db, o: PoolOverview, sub: PoolSubscriptionState, mark: string, detail: string, now: Date): Promise<boolean> {
|
||
const prev = await getSetting<{ mark: string; at: number }>(db, WARNED(sub.id, o.pool.id));
|
||
if (prev?.mark === mark) return false;
|
||
await setSetting(db, WARNED(sub.id, o.pool.id), { mark, at: now.getTime() });
|
||
for (const p of o.projects) {
|
||
await logEvent(db, { projectId: p.id, type: "subscription_last_warning", payload: { subscriptionId: sub.id, name: sub.name, detail } });
|
||
await sendProjectMessage(
|
||
db,
|
||
p.id,
|
||
tr("⚠️ Осталась одна рабочая подписка, {detail}. Когда она упрётся в лимит, агенты встанут до сброса. Добавьте ещё одну подписку Claude или ChatGPT: «⋯ Настройки проекта → Подписки».", { detail }),
|
||
`subwarn:${sub.id}:${mark}:p${p.id}`,
|
||
{ title: tr("Скоро лимит подписки"), url: `/p/${p.key}#subscription` },
|
||
);
|
||
}
|
||
return true;
|
||
}
|
||
|
||
/**
|
||
* Watchdog: a pool of some project is down to one usable subscription and its usage window
|
||
* crossed the threshold → one warning per window to the pool's projects. Returns warnings sent.
|
||
*/
|
||
export async function subscriptionWarnTick(db: Db, now = new Date()): Promise<number> {
|
||
let n = 0;
|
||
for (const o of await poolOverviews(db, undefined, now)) {
|
||
if (!o.projects.length || o.usableCount !== 1) continue;
|
||
const sub = o.subscriptions.find((s) => s.usable)!;
|
||
const u = sub.usage;
|
||
if (!u || u.pct == null || u.pct < warnThresholdPct()) continue;
|
||
const pct = Math.round(u.pct);
|
||
const detail = u.resetsAt
|
||
? tr("использовано {pct}% (окно {window}, сброс в {time})", { pct, window: u.label, time: hhmm(u.resetsAt) })
|
||
: tr("использовано {pct}% (окно {window})", { pct, window: u.label });
|
||
if (await warnPool(db, o, sub, `w:${u.label}:${u.resetsAt?.getTime() ?? "?"}`, detail, now)) n++;
|
||
}
|
||
return n;
|
||
}
|
||
|
||
/**
|
||
* The CLI's own «approaching usage limit» banner on a subscription (Codex has no usage
|
||
* windows) and nowhere to rotate: the same warning, at most once per 5 hours per subscription.
|
||
*/
|
||
export async function warnLastSubscription(db: Db, subscriptionId: number, now = new Date()): Promise<boolean> {
|
||
let sent = false;
|
||
for (const o of await poolOverviews(db, undefined, now)) {
|
||
const sub = o.subscriptions.find((s) => s.id === subscriptionId);
|
||
if (!sub || !o.projects.length || o.usableCount > 1) continue;
|
||
const prev = await getSetting<{ mark: string; at: number }>(db, WARNED(subscriptionId, o.pool.id));
|
||
if (prev && now.getTime() - prev.at < BANNER_REPEAT_MS) continue;
|
||
sent = (await warnPool(db, o, sub, `b:${now.getTime()}`, tr("она подходит к лимиту"), now)) || sent;
|
||
}
|
||
return sent;
|
||
}
|