peppa/packages/core/src/subscriptions.ts
2026-11-16 09:52:35 +05:00

428 lines
22 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.

// Agent subscriptions and pools (PEP-67): superadmins keep the accounts agents run on
// (Claude Code, Codex, OpenCode) and group them into pools; a runner takes the first free
// active subscription of the chosen set. PEP-39: a limit marks the subscription, the
// watchdog moves the session to another usable subscription of the pool (rotation), with a
// simple fairness rule between projects sharing a pool.
import { m as tr } from "@peppa/shared/i18n";
import { projects, sessions, subscriptionPoolMembers, subscriptionPools, subscriptions, users, type Db } from "@peppa/db";
import { and, asc, eq, inArray, notInArray } from "drizzle-orm";
import { decrypt, encrypt } from "./crypto.ts";
import { PeppaError } from "./errors.ts";
import { isSuperadmin } from "./monitor.ts";
import type { Project } from "./projects.ts";
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
import { FINISHED_SESSION_STATUSES } from "./sessions.ts";
import type { User } from "./users.ts";
export type Subscription = typeof subscriptions.$inferSelect;
export type SubscriptionProvider = Subscription["provider"];
export type SubscriptionStatus = Subscription["status"];
export type SubscriptionPool = typeof subscriptionPools.$inferSelect;
export const PROVIDER_NAMES: Record<SubscriptionProvider, string> = { claude: "Claude Code", codex: "Codex", opencode: "OpenCode" };
/** OpenCode model providers a key can belong to, and the env variable it goes into. */
export const OPENCODE_KEY_ENV: Record<string, string> = {
anthropic: "ANTHROPIC_API_KEY",
openai: "OPENAI_API_KEY",
openrouter: "OPENROUTER_API_KEY",
};
export interface SubscriptionView extends Subscription {
createdByLogin: string | null;
activeSessions: number;
/** PEP-39: active sessions on it per project. */
projectSessions: Array<{ key: string; n: number }>;
poolIds: number[];
}
export interface PoolView extends SubscriptionPool {
subscriptionIds: number[];
projectKeys: string[];
}
/** Throws "not found" unless the user is a superadmin: the section doesn't exist for others. */
export async function requireSuperadmin(db: Db, user: Pick<User, "login"> | null | undefined): Promise<void> {
if (!(await isSuperadmin(db, user))) throw new PeppaError(tr("Не найдено"));
}
// ── subscriptions ────────────────────────────────────────────────────────────────
interface ActiveRow {
sessionId: number;
subscriptionId: number | null;
projectId: number;
projectKey: string;
status: (typeof sessions.$inferSelect)["status"];
resumeAt: Date | null;
}
/** Sessions not finished yet, with their subscription and project. */
async function activeRows(db: Db): Promise<ActiveRow[]> {
return db
.select({ sessionId: sessions.id, subscriptionId: sessions.subscriptionId, projectId: sessions.projectId, projectKey: projects.key, status: sessions.status, resumeAt: sessions.resumeAt })
.from(sessions)
.innerJoin(projects, eq(sessions.projectId, projects.id))
.where(notInArray(sessions.status, FINISHED_SESSION_STATUSES));
}
function countBySubscription(rows: ActiveRow[]): Map<number, number> {
const m = new Map<number, number>();
for (const r of rows) if (r.subscriptionId != null) m.set(r.subscriptionId, (m.get(r.subscriptionId) ?? 0) + 1);
return m;
}
export async function listSubscriptions(db: Db): Promise<SubscriptionView[]> {
const rows = await db
.select({ s: subscriptions, login: users.login })
.from(subscriptions)
.leftJoin(users, eq(subscriptions.createdBy, users.id))
.orderBy(asc(subscriptions.id));
const active = await activeRows(db);
const counts = countBySubscription(active);
const members = await db.select().from(subscriptionPoolMembers);
const perProject = (id: number) => {
const m = new Map<string, number>();
for (const a of active) if (a.subscriptionId === id) m.set(a.projectKey, (m.get(a.projectKey) ?? 0) + 1);
return [...m].map(([key, n]) => ({ key, n })).sort((a, b) => a.key.localeCompare(b.key));
};
return rows.map((r) => ({
...r.s,
createdByLogin: r.login,
activeSessions: counts.get(r.s.id) ?? 0,
projectSessions: perProject(r.s.id),
poolIds: members.filter((m) => m.subscriptionId === r.s.id).map((m) => m.poolId),
}));
}
export async function getSubscription(db: Db, id: number): Promise<Subscription> {
const [row] = await db.select().from(subscriptions).where(eq(subscriptions.id, id));
if (!row) throw new PeppaError(tr("Подписка #{id} не найдена", { id }));
return row;
}
export async function createSubscription(
db: Db,
s: { provider: SubscriptionProvider; name: string; authKind: Subscription["authKind"]; secret?: string | null; keyProvider?: string | null; createdBy?: number | null },
): Promise<Subscription> {
const name = s.name.trim();
if (!name) throw new PeppaError(tr("Нужно название подписки"));
// glossary-ignore: пулами подписок управляет только суперадмин
if (s.provider === "opencode" && !(s.keyProvider && s.keyProvider in OPENCODE_KEY_ENV)) throw new PeppaError(tr("Выберите провайдера ключа OpenCode"));
const [row] = await db
.insert(subscriptions)
.values({
provider: s.provider,
name,
authKind: s.authKind,
secretEnc: s.secret ? encrypt(s.secret) : null,
keyProvider: s.keyProvider ?? null,
createdBy: s.createdBy ?? null,
})
.returning();
return row!;
}
export async function updateSubscription(
db: Db,
id: number,
patch: Partial<Pick<Subscription, "name" | "status" | "limitedUntil" | "lastError" | "checkedAt" | "authKind">> & { secret?: string | null },
): Promise<Subscription> {
const { secret, ...rest } = patch;
const set: Partial<Subscription> = { ...rest };
if (secret !== undefined) set.secretEnc = secret ? encrypt(secret) : null;
if (patch.status === "active") {
set.limitedUntil = null;
set.lastError = null;
const cur = await getSubscription(db, id);
if (!cur.activatedAt) set.activatedAt = new Date();
}
const [row] = await db.update(subscriptions).set(set).where(eq(subscriptions.id, id)).returning();
if (!row) throw new PeppaError(tr("Подписка #{id} не найдена", { id }));
return row;
}
/** Removes a subscription; its sessions keep running but forget it. The runner wipes its login dir. */
export async function deleteSubscription(db: Db, id: number): Promise<void> {
db.transaction((tx) => {
tx.update(sessions).set({ subscriptionId: null }).where(eq(sessions.subscriptionId, id)).run();
tx.delete(subscriptions).where(eq(subscriptions.id, id)).run();
});
}
/** The decrypted secret (Claude token / OpenCode key); null if the subscription has none. */
export function subscriptionSecret(s: Pick<Subscription, "secretEnc">): string | null {
return s.secretEnc ? decrypt(s.secretEnc) : null;
}
/** Active now: `active`, or `limited` whose reset time has passed. */
export function isUsable(s: Pick<Subscription, "status" | "limitedUntil">, now = new Date()): boolean {
return s.status === "active" || (s.status === "limited" && !!s.limitedUntil && s.limitedUntil <= now);
}
// ── pools ────────────────────────────────────────────────────────────────────────
export async function listPools(db: Db): Promise<PoolView[]> {
const pools = await db.select().from(subscriptionPools).orderBy(asc(subscriptionPools.name));
const members = await db.select().from(subscriptionPoolMembers);
const used = await db.select({ key: projects.key, poolId: projects.subscriptionPoolId }).from(projects);
return pools.map((p) => ({
...p,
subscriptionIds: members.filter((m) => m.poolId === p.id).map((m) => m.subscriptionId).sort((a, b) => a - b),
projectKeys: used.filter((u) => u.poolId === p.id).map((u) => u.key),
}));
}
export async function getPool(db: Db, id: number): Promise<SubscriptionPool> {
const [row] = await db.select().from(subscriptionPools).where(eq(subscriptionPools.id, id));
// glossary-ignore: пулами подписок управляет только суперадмин
if (!row) throw new PeppaError(tr("Пул #{id} не найден", { id }));
return row;
}
async function checkSubscriptionIds(db: Db, ids: number[]): Promise<number[]> {
const uniq = [...new Set(ids.filter((n) => Number.isInteger(n) && n > 0))];
if (!uniq.length) return [];
const found = await db.select({ id: subscriptions.id }).from(subscriptions).where(inArray(subscriptions.id, uniq));
if (found.length !== uniq.length) throw new PeppaError(tr("Некоторых подписок уже нет"));
return uniq;
}
export async function createPool(db: Db, p: { name: string; subscriptionIds: number[]; createdBy?: number | null }): Promise<SubscriptionPool> {
const name = p.name.trim();
// glossary-ignore: пулами подписок управляет только суперадмин
if (!name) throw new PeppaError(tr("Нужно название пула"));
const [dup] = await db.select().from(subscriptionPools).where(eq(subscriptionPools.name, name));
// glossary-ignore: пулами подписок управляет только суперадмин
if (dup) throw new PeppaError(tr("Пул «{name}» уже есть", { name }));
const ids = await checkSubscriptionIds(db, p.subscriptionIds);
return db.transaction((tx) => {
const row = tx.insert(subscriptionPools).values({ name, createdBy: p.createdBy ?? null }).returning().get();
for (const id of ids) tx.insert(subscriptionPoolMembers).values({ poolId: row.id, subscriptionId: id }).run();
return row;
});
}
export async function updatePool(db: Db, id: number, p: { name?: string; subscriptionIds?: number[] }): Promise<void> {
await getPool(db, id);
const ids = p.subscriptionIds ? await checkSubscriptionIds(db, p.subscriptionIds) : null;
const name = p.name?.trim();
if (name) {
const [dup] = await db.select().from(subscriptionPools).where(eq(subscriptionPools.name, name));
// glossary-ignore: пулами подписок управляет только суперадмин
if (dup && dup.id !== id) throw new PeppaError(tr("Пул «{name}» уже есть", { name }));
}
db.transaction((tx) => {
if (name) tx.update(subscriptionPools).set({ name }).where(eq(subscriptionPools.id, id)).run();
if (ids) {
tx.delete(subscriptionPoolMembers).where(eq(subscriptionPoolMembers.poolId, id)).run();
for (const sid of ids) tx.insert(subscriptionPoolMembers).values({ poolId: id, subscriptionId: sid }).run();
}
});
}
/** Deletes a pool; projects that used it as default go back to "no pool". */
export async function deletePool(db: Db, id: number): Promise<void> {
db.transaction((tx) => {
tx.update(projects).set({ subscriptionPoolId: null }).where(eq(projects.subscriptionPoolId, id)).run();
tx.delete(subscriptionPools).where(eq(subscriptionPools.id, id)).run();
});
}
export async function setProjectPool(db: Db, projectId: number, poolId: number | null): Promise<void> {
if (poolId != null) await getPool(db, poolId);
await db.update(projects).set({ subscriptionPoolId: poolId }).where(eq(projects.id, projectId));
}
export async function poolSubscriptions(db: Db, poolId: number): Promise<Subscription[]> {
const rows = await db
.select({ s: subscriptions })
.from(subscriptionPoolMembers)
.innerJoin(subscriptions, eq(subscriptionPoolMembers.subscriptionId, subscriptions.id))
.where(eq(subscriptionPoolMembers.poolId, poolId))
.orderBy(asc(subscriptions.id));
return rows.map((r) => r.s);
}
// ── choosing a subscription for a runner ─────────────────────────────────────────
export interface PickOptions {
projectId: number;
/** Subscriptions ticked in the launch form (multiple choice). */
subscriptionIds?: number[];
/** A pool chosen in the launch form instead of the project's default. */
poolId?: number | null;
provider?: SubscriptionProvider;
now?: Date;
}
/**
* The subscription a new runner starts on: the first free usable one of the chosen set
* (ticked subscriptions, else the chosen pool, else the project's pool), by id; if all are
* busy — the least busy one (the runner never waits); fairness: poolRestricted. Null when nothing
* is chosen and the project has no pool: the agent runs on this machine's own login.
*/
export async function pickSubscription(db: Db, o: PickOptions): Promise<Subscription | null> {
let candidates: Subscription[];
let source: string;
let poolIdUsed: number | null = null;
if (o.subscriptionIds?.length) {
candidates = await db.select().from(subscriptions).where(inArray(subscriptions.id, o.subscriptionIds)).orderBy(asc(subscriptions.id));
source = tr("отмеченных");
} else {
const poolId = o.poolId ?? (await db.select({ id: projects.subscriptionPoolId }).from(projects).where(eq(projects.id, o.projectId)))[0]?.id;
if (poolId == null) return null;
await getPool(db, poolId); // throws when the pool is gone
candidates = await poolSubscriptions(db, poolId);
poolIdUsed = poolId;
// The name of the pool is not shown: a product manager reads this when an agent cannot start.
source = tr("подключённых к проекту");
}
if (o.provider) {
candidates = candidates.filter((s) => s.provider === o.provider);
if (!candidates.length) throw new PeppaError(tr("Среди {source} подписок нет подписок {provider}", { source, provider: PROVIDER_NAMES[o.provider] }));
}
const usable = candidates.filter((s) => isUsable(s, o.now));
if (!usable.length) throw new PeppaError(candidates.length ? tr("Нет активных подписок среди {source} — проверьте их в «Подписках»", { source }) : tr("Нет активных подписок среди {source} (ни одной не подключено) — проверьте их в «Подписках»", { source }));
const active = await activeRows(db);
const counts = countBySubscription(active);
// Fairness (PEP-39): a project already holding K subscriptions of the pool while another
// project waits for a limit reset shares a busy subscription instead of taking a free one.
if (poolIdUsed != null && (await poolRestricted(db, poolIdUsed, o.projectId, active))) {
const shared = usable.filter((s) => (counts.get(s.id) ?? 0) > 0);
if (shared.length) return leastBusy(shared, counts);
}
return leastBusy(usable, counts);
}
const leastBusy = (list: Subscription[], counts: Map<number, number>) =>
list.reduce((best, s) => ((counts.get(s.id) ?? 0) < (counts.get(best.id) ?? 0) ? s : best));
/** K for the fairness rule: subscriptions of one pool a project may hold while others wait. */
export const poolProjectMax = () => Number(process.env.PEPPA_POOL_PROJECT_MAX ?? 2);
/**
* True when the project already holds ≥ K distinct subscriptions of the pool and the pool
* has a queue: a session of another project waits for a limit reset on one of its
* subscriptions (rate_limited with an automatic resume time).
*/
async function poolRestricted(db: Db, poolId: number, projectId: number, active: ActiveRow[]): Promise<boolean> {
const memberIds = new Set((await db.select().from(subscriptionPoolMembers).where(eq(subscriptionPoolMembers.poolId, poolId))).map((m) => m.subscriptionId));
const held = new Set(active.filter((a) => a.projectId === projectId && a.subscriptionId != null && memberIds.has(a.subscriptionId)).map((a) => a.subscriptionId));
if (held.size < poolProjectMax()) return false;
return active.some((a) => a.projectId !== projectId && a.status === "rate_limited" && a.resumeAt != null && a.subscriptionId != null && memberIds.has(a.subscriptionId));
}
/** A limit hit on the subscription: «лимит до …» until it resets (PEP-39). */
export async function markSubscriptionLimited(db: Db, id: number, until: Date, note?: string | null): Promise<void> {
const cur = await getSubscription(db, id).catch(() => null);
if (!cur || cur.status === "pending" || cur.status === "auth_error") return;
// Never shorten a known later reset (two sessions report the same limit).
if (cur.status === "limited" && cur.limitedUntil && cur.limitedUntil > until) return;
await updateSubscription(db, id, { status: "limited", limitedUntil: until, lastError: note ? note.slice(0, 300) : cur.lastError });
}
export interface RotationOptions {
now?: Date;
/** Threshold rotation: only subscriptions nobody runs on. */
onlyIdle?: boolean;
/** PEP-107: allow a subscription of another provider (Claude ↔ Codex) when the same one has none. Default: PEPPA_ROTATE_CROSS !== "off". */
crossProvider?: boolean;
}
/** Providers a session may move between (PEP-107): OpenCode has no hooks or turn status — not part of it. */
const CROSS_PROVIDERS: SubscriptionProvider[] = ["claude", "codex"];
export const crossRotationEnabled = () => process.env.PEPPA_ROTATE_CROSS !== "off";
/** The pools a session's rotation looks in: the project's pool, else the pools holding its subscription. */
async function rotationPools(db: Db, projectId: number, subscriptionId: number): Promise<number[]> {
const [p] = await db.select({ poolId: projects.subscriptionPoolId }).from(projects).where(eq(projects.id, projectId));
if (p?.poolId != null) return [p.poolId];
return (await db.select().from(subscriptionPoolMembers).where(eq(subscriptionPoolMembers.subscriptionId, subscriptionId))).map((m) => m.poolId);
}
/**
* Where a session may move (PEP-39): another usable subscription of the same provider in
* the project's pool — or, without one, in the pools holding the session's subscription —
* the least busy one (free first), honouring the fairness rule. PEP-107: none of the same
* provider → one of the other provider (Claude ↔ Codex). Null: nowhere to go.
*/
export async function rotationCandidate(
db: Db,
s: { projectId: number; provider: SubscriptionProvider; subscriptionId: number | null },
o: RotationOptions = {},
): Promise<Subscription | null> {
if (s.subscriptionId == null) return null;
const poolIds = await rotationPools(db, s.projectId, s.subscriptionId);
if (!poolIds.length) return null;
const active = await activeRows(db);
const counts = countBySubscription(active);
const pick = async (ok: (x: Subscription) => boolean): Promise<Subscription | null> => {
const found = new Map<number, Subscription>();
for (const poolId of poolIds) {
let list = (await poolSubscriptions(db, poolId)).filter((x) => ok(x) && x.id !== s.subscriptionId && isUsable(x, o.now));
if (o.onlyIdle) list = list.filter((x) => !counts.get(x.id));
// Fair share: a project over K while others wait gets no free subscription here.
if (list.length && (await poolRestricted(db, poolId, s.projectId, active))) list = list.filter((x) => (counts.get(x.id) ?? 0) > 0);
for (const x of list) found.set(x.id, x);
}
const list = [...found.values()].sort((a, b) => a.id - b.id);
return list.length ? leastBusy(list, counts) : null;
};
const same = await pick((x) => x.provider === s.provider);
if (same) return same;
if (!(o.crossProvider ?? crossRotationEnabled()) || !CROSS_PROVIDERS.includes(s.provider)) return null;
return pick((x) => x.provider !== s.provider && CROSS_PROVIDERS.includes(x.provider));
}
/** Claude token for one-off calls on behalf of a project (incident triage): the project's pool. */
export async function claudeTokenForProject(db: Db, project: Pick<Project, "id">): Promise<string | null> {
const [p] = await db.select({ poolId: projects.subscriptionPoolId }).from(projects).where(eq(projects.id, project.id));
if (p?.poolId == null) return null;
const s = (await poolSubscriptions(db, p.poolId)).find((x) => x.provider === "claude" && isUsable(x) && x.secretEnc);
return s ? subscriptionSecret(s) : null;
}
/** Pool name of a project (for the project settings), or null. */
export async function projectPool(db: Db, projectId: number): Promise<SubscriptionPool | null> {
const [row] = await db
.select({ pool: subscriptionPools })
.from(projects)
.innerJoin(subscriptionPools, eq(projects.subscriptionPoolId, subscriptionPools.id))
.where(and(eq(projects.id, projectId)));
return row?.pool ?? null;
}
/**
* PEP-24: true when the project's pool has no usable subscription right now (all limited or
* broken) — the dispatcher neither starts agents nor offers stories then. No pool = false.
*/
export async function projectPoolExhausted(db: Db, projectId: number, now = new Date()): Promise<boolean> {
const [p] = await db.select({ poolId: projects.subscriptionPoolId }).from(projects).where(eq(projects.id, projectId));
if (p?.poolId == null) return false;
return !(await poolSubscriptions(db, p.poolId)).some((s) => isUsable(s, now));
}
// ── PEP-76: the platform's shared pool and the owner's choice ───────────────────────
const SHARED_POOL = "platform.shared_pool";
/** The pool any project owner may pick as «Общая подписка Пеппы» (set by a superadmin), or null. */
export async function sharedPool(db: Db): Promise<SubscriptionPool | null> {
const id = await getSetting<number>(db, SHARED_POOL);
if (id == null) return null;
const [p] = await db.select().from(subscriptionPools).where(eq(subscriptionPools.id, id));
return p ?? null;
}
export async function setSharedPool(db: Db, poolId: number | null): Promise<void> {
if (poolId == null) return deleteSetting(db, SHARED_POOL);
await getPool(db, poolId);
await setSetting(db, SHARED_POOL, poolId);
}
/** The user's own pool (the first one they created that is not the shared pool), or null. */
export async function ownPool(db: Db, userId: number): Promise<SubscriptionPool | null> {
const shared = await sharedPool(db);
const rows = await db.select().from(subscriptionPools).where(eq(subscriptionPools.createdBy, userId)).orderBy(asc(subscriptionPools.id));
return rows.find((p) => p.id !== shared?.id) ?? null;
}