271 lines
13 KiB
TypeScript
271 lines
13 KiB
TypeScript
// 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. Rotation on limits and fairness — PEP-39.
|
||
import { projects, sessions, subscriptionPoolMembers, subscriptionPools, subscriptions, users, type Db } from "@peppa/db";
|
||
import { and, asc, count, 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 { 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;
|
||
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("Не найдено");
|
||
}
|
||
|
||
// ── subscriptions ────────────────────────────────────────────────────────────────
|
||
|
||
async function activeSessionCounts(db: Db): Promise<Map<number, number>> {
|
||
const rows = await db
|
||
.select({ id: sessions.subscriptionId, n: count() })
|
||
.from(sessions)
|
||
.where(notInArray(sessions.status, FINISHED_SESSION_STATUSES))
|
||
.groupBy(sessions.subscriptionId);
|
||
return new Map(rows.filter((r) => r.id != null).map((r) => [r.id!, r.n]));
|
||
}
|
||
|
||
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 counts = await activeSessionCounts(db);
|
||
const members = await db.select().from(subscriptionPoolMembers);
|
||
return rows.map((r) => ({
|
||
...r.s,
|
||
createdByLogin: r.login,
|
||
activeSessions: counts.get(r.s.id) ?? 0,
|
||
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(`Подписка #${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("Нужно название подписки");
|
||
if (s.provider === "opencode" && !(s.keyProvider && s.keyProvider in OPENCODE_KEY_ENV)) throw new PeppaError("Выберите провайдера ключа 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(`Подписка #${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));
|
||
if (!row) throw new PeppaError(`Пул #${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("Некоторых подписок уже нет");
|
||
return uniq;
|
||
}
|
||
|
||
export async function createPool(db: Db, p: { name: string; subscriptionIds: number[]; createdBy?: number | null }): Promise<SubscriptionPool> {
|
||
const name = p.name.trim();
|
||
if (!name) throw new PeppaError("Нужно название пула");
|
||
const [dup] = await db.select().from(subscriptionPools).where(eq(subscriptionPools.name, name));
|
||
if (dup) throw new PeppaError(`Пул «${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));
|
||
if (dup && dup.id !== id) throw new PeppaError(`Пул «${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));
|
||
}
|
||
|
||
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 is PEP-39). 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;
|
||
if (o.subscriptionIds?.length) {
|
||
candidates = await db.select().from(subscriptions).where(inArray(subscriptions.id, o.subscriptionIds)).orderBy(asc(subscriptions.id));
|
||
source = "отмеченных";
|
||
} 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;
|
||
const pool = await getPool(db, poolId);
|
||
candidates = await poolSubscriptions(db, poolId);
|
||
source = `пула «${pool.name}»`;
|
||
}
|
||
if (o.provider) {
|
||
candidates = candidates.filter((s) => s.provider === o.provider);
|
||
if (!candidates.length) throw new PeppaError(`Среди ${source} подписок нет подписок ${PROVIDER_NAMES[o.provider]}`);
|
||
}
|
||
const usable = candidates.filter((s) => isUsable(s, o.now));
|
||
if (!usable.length) throw new PeppaError(`Нет активных подписок среди ${source}${candidates.length ? "" : " (пул пуст)"} — проверьте их в «Подписках»`);
|
||
const counts = await activeSessionCounts(db);
|
||
return usable.reduce((best, s) => ((counts.get(s.id) ?? 0) < (counts.get(best.id) ?? 0) ? s : best));
|
||
}
|
||
|
||
/** 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;
|
||
}
|