46 lines
2.9 KiB
TypeScript
46 lines
2.9 KiB
TypeScript
// PEP-76: the project owner's choice of what its agents run on — the platform's shared pool
|
||
// («Общая подписка Пеппы») or the owner's own Claude subscription (a `claude setup-token` token,
|
||
// kept encrypted like every subscription, in the owner's personal pool).
|
||
import { createPool, getPool, logEvent, ownPool, PeppaError, setProjectPool, sharedPool, updatePool, isSuperadmin, listPools, listSubscriptions, type Project, type User } from "@peppa/core";
|
||
import type { Db } from "@peppa/db";
|
||
import { addSubscription } from "./subscriptions.ts";
|
||
|
||
async function requireOwner(db: Db, user: User, project: Project): Promise<void> {
|
||
if (project.ownerId !== user.id && !(await isSuperadmin(db, user))) throw new PeppaError("Подписку проекта выбирает его владелец");
|
||
}
|
||
|
||
/** «Общая подписка Пеппы»: the project runs on the platform's shared pool. */
|
||
export async function chooseSharedSubscription(db: Db, user: User, project: Project): Promise<void> {
|
||
await requireOwner(db, user, project);
|
||
const pool = await sharedPool(db);
|
||
if (!pool) throw new PeppaError("Общая подписка не настроена — подключите свою или попросите администратора");
|
||
await setProjectPool(db, project.id, pool.id);
|
||
await logEvent(db, { projectId: project.id, type: "project_subscription", payload: { login: user.login, choice: "shared", poolId: pool.id } });
|
||
}
|
||
|
||
/**
|
||
* «Своя подписка»: with a token — a new Claude subscription of the user goes into their own
|
||
* pool (created on first use); without one — the project just moves to the pool they already have.
|
||
*/
|
||
export async function connectOwnSubscription(db: Db, user: User, project: Project, token: string): Promise<void> {
|
||
await requireOwner(db, user, project);
|
||
let pool = await ownPool(db, user.id);
|
||
if (token.trim()) {
|
||
const taken = new Set((await listSubscriptions(db)).map((s) => s.name));
|
||
let name = `Claude — ${user.login}`;
|
||
for (let n = 2; taken.has(name); n++) name = `Claude — ${user.login} ${n}`;
|
||
const sub = await addSubscription(db, { provider: "claude", name, method: "token", secret: token, createdBy: user.id });
|
||
if (pool) {
|
||
const cur = (await listPools(db)).find((p) => p.id === pool!.id);
|
||
await updatePool(db, pool.id, { subscriptionIds: [...(cur?.subscriptionIds ?? []), sub.id] });
|
||
} else {
|
||
pool = await createPool(db, { name: `Claude — ${user.login}`, subscriptionIds: [sub.id], createdBy: user.id });
|
||
}
|
||
} else if (!pool) {
|
||
throw new PeppaError("Вставьте токен: выполните `claude setup-token` на своём компьютере и скопируйте результат");
|
||
}
|
||
await getPool(db, pool.id);
|
||
await setProjectPool(db, project.id, pool.id);
|
||
await logEvent(db, { projectId: project.id, type: "project_subscription", payload: { login: user.login, choice: "own", poolId: pool.id } });
|
||
}
|