387 lines
21 KiB
TypeScript
387 lines
21 KiB
TypeScript
// PEP-186: the project's subscription ran out (a limit, a broken sign-in) — its owner asks the
|
||
// superadmin for one. The superadmin gets a question with buttons in the platform project; «lend»
|
||
// puts a free subscription of the factory into the project's pool for a while (PEP-107 loans),
|
||
// the waiting agents move onto it at once, and when the time is up it goes back.
|
||
import { asIs, m } from "@peppa/shared/i18n";
|
||
import {
|
||
answerQuestion,
|
||
askPmProject,
|
||
currentActor,
|
||
deleteSetting,
|
||
getProject,
|
||
getSetting,
|
||
getUser,
|
||
getUserByLogin,
|
||
isSuperadmin,
|
||
isUsable,
|
||
lendSubscription,
|
||
listAccountUsage,
|
||
listLoans,
|
||
listSessions,
|
||
listSubscriptions,
|
||
logEvent,
|
||
logSessionEvent,
|
||
PeppaError,
|
||
platformAdmins,
|
||
platformProjectKey,
|
||
poolSubscriptions,
|
||
projectPool,
|
||
projectPoolExhausted,
|
||
returnLoan,
|
||
rotationCandidate,
|
||
setSetting,
|
||
sharedPool,
|
||
updateSession,
|
||
userProjectIds,
|
||
type Project,
|
||
type Question,
|
||
type SessionView,
|
||
type Subscription,
|
||
type User,
|
||
} from "@peppa/core";
|
||
import { projects, settings, type Db } from "@peppa/db";
|
||
import { eq, like } from "drizzle-orm";
|
||
import { onAnswer } from "./sessions.ts";
|
||
import { isRunnerClient } from "./runner-client.ts";
|
||
|
||
export const LEND_UNTIL_RESET = m("Одолжить до сброса");
|
||
export const LEND_DAY = m("Одолжить на сутки");
|
||
export const REQUEST_DENY = m("Отказать");
|
||
export const REQUEST_REMIND = m("Напомнить позже");
|
||
export const REQUEST_SENT_TEXT = m("Запрос отправлен — ждём ответа администратора");
|
||
|
||
/** PEP-182: a subscription carries at most this many agents at once. */
|
||
export const LOAN_MAX_AGENTS = 9;
|
||
export const MAX_REQUESTS_PER_DAY = 3;
|
||
const DAY_MS = 86_400_000;
|
||
const REMIND_MS = 3_600_000;
|
||
const MIN_LOAN_MS = 30 * 60_000;
|
||
const usageLimitPct = () => Number(process.env.PEPPA_ROTATE_THRESHOLD_PCT ?? 85);
|
||
|
||
export interface SubscriptionRequest {
|
||
userId: number;
|
||
login: string;
|
||
at: number;
|
||
status: "open" | "lent";
|
||
questionId: number | null;
|
||
remindAt?: number | null;
|
||
until?: number;
|
||
subscriptionId?: number;
|
||
poolId?: number;
|
||
}
|
||
|
||
const PREFIX = "subscription.request:";
|
||
const requestKey = (projectId: number) => `${PREFIX}${projectId}`;
|
||
const questionKey = (questionId: number) => `subscription.request.q:${questionId}`;
|
||
const logKey = (userId: number) => `subscription.request.log:${userId}`;
|
||
|
||
const hhmm = (d: Date) => d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });
|
||
|
||
export async function subscriptionRequest(db: Db, projectId: number): Promise<SubscriptionRequest | null> {
|
||
return getSetting<SubscriptionRequest>(db, requestKey(projectId));
|
||
}
|
||
|
||
async function allRequests(db: Db): Promise<Array<{ projectId: number; req: SubscriptionRequest }>> {
|
||
const rows = await db.select().from(settings).where(like(settings.key, `${PREFIX}%`));
|
||
return rows.map((r) => ({ projectId: Number(r.key.slice(PREFIX.length)), req: r.value as SubscriptionRequest })).filter((x) => Number.isFinite(x.projectId));
|
||
}
|
||
|
||
async function clearRequest(db: Db, projectId: number, req: SubscriptionRequest | null) {
|
||
if (req?.questionId) await deleteSetting(db, questionKey(req.questionId));
|
||
await deleteSetting(db, requestKey(projectId));
|
||
}
|
||
|
||
/** Agents of the project waiting for a limit reset. */
|
||
async function waitingSessions(db: Db, projectId: number): Promise<SessionView[]> {
|
||
return (await listSessions(db, { active: true, projectId })).filter((s) => s.status === "rate_limited");
|
||
}
|
||
|
||
/** True when the project's agents stand: some wait for a limit, or its pool has no working subscription. */
|
||
export async function projectNeedsSubscription(db: Db, projectId: number, now = new Date()): Promise<boolean> {
|
||
const pool = await projectPool(db, projectId);
|
||
if (!pool) return false;
|
||
if ((await waitingSessions(db, projectId)).length) return true;
|
||
return projectPoolExhausted(db, projectId, now);
|
||
}
|
||
|
||
/** Until when the agents stand: the nearest limit reset of the waiting agents or of the pool, or null. */
|
||
export async function projectWaitUntil(db: Db, projectId: number, now = new Date()): Promise<Date | null> {
|
||
const later = (d: Date | null | undefined): d is Date => !!d && d.getTime() > now.getTime();
|
||
const first = (ds: Array<Date | null | undefined>) => ds.filter(later).sort((a, b) => a.getTime() - b.getTime())[0] ?? null;
|
||
const fromAgents = first((await waitingSessions(db, projectId)).map((s) => s.resumeAt));
|
||
if (fromAgents) return fromAgents;
|
||
const pool = await projectPool(db, projectId);
|
||
if (!pool) return null;
|
||
return first((await poolSubscriptions(db, pool.id)).map((s) => (s.status === "limited" ? s.limitedUntil : null)));
|
||
}
|
||
|
||
/**
|
||
* The subscription the factory would lend the project now: a working subscription of a superadmin
|
||
* or of the shared pool, outside the project's pool, with room (fewer than 9 agents) and usage
|
||
* below the threshold. The pool's own provider first, then the least busy.
|
||
*/
|
||
export async function loanCandidate(db: Db, projectId: number, now = new Date()): Promise<Subscription | null> {
|
||
const pool = await projectPool(db, projectId);
|
||
const own = pool ? await poolSubscriptions(db, pool.id) : [];
|
||
const ownIds = new Set(own.map((s) => s.id));
|
||
const providers = new Set(own.map((s) => s.provider));
|
||
const adminIds = new Set<number>();
|
||
for (const login of await platformAdmins(db)) {
|
||
const u = await getUserByLogin(db, login);
|
||
if (u) adminIds.add(u.id);
|
||
}
|
||
const shared = await sharedPool(db);
|
||
const subs = await listSubscriptions(db);
|
||
const usage = new Map((await listAccountUsage(db, { subscriptionIds: subs.map((s) => s.id), machine: false, now: now.getTime() })).map((u) => [u.subscriptionId, u]));
|
||
const list = subs.filter((s) => {
|
||
if (ownIds.has(s.id) || !isUsable(s, now) || s.activeSessions >= LOAN_MAX_AGENTS) return false;
|
||
if (!((s.createdBy != null && adminIds.has(s.createdBy)) || (shared && s.poolIds.includes(shared.id)))) return false;
|
||
const u = usage.get(s.id);
|
||
const pct = u && !u.stale ? Math.max(u.fiveHour?.pct ?? 0, u.sevenDay?.pct ?? 0) : 0;
|
||
return pct < usageLimitPct();
|
||
});
|
||
list.sort((a, b) => Number(!providers.has(a.provider)) - Number(!providers.has(b.provider)) || a.activeSessions - b.activeSessions || a.id - b.id);
|
||
return list[0] ?? null;
|
||
}
|
||
|
||
export type RequestOffer = "can" | "sent";
|
||
|
||
/** The project's pool already holds a lent subscription (another project of the same pool asked). */
|
||
async function poolHasLoan(db: Db, projectId: number): Promise<boolean> {
|
||
const pool = await projectPool(db, projectId);
|
||
return !!pool && (await listLoans(db)).some((l) => l.poolId === pool.id);
|
||
}
|
||
|
||
/**
|
||
* Whether the user sees «Попросить подписку у администратора» on this project: an owner or a
|
||
* member (not a superadmin — they lend themselves), the agents stand. "sent" — a request waits.
|
||
*/
|
||
export async function subscriptionRequestOffer(db: Db, user: Pick<User, "id" | "login">, projectId: number, now = new Date()): Promise<RequestOffer | null> {
|
||
if (await isSuperadmin(db, user)) return null;
|
||
if (!(await userProjectIds(db, user.id)).includes(projectId)) return null;
|
||
const req = await subscriptionRequest(db, projectId);
|
||
if (req?.status === "open") return "sent";
|
||
if (req?.status === "lent" || (await poolHasLoan(db, projectId))) return null;
|
||
return (await projectNeedsSubscription(db, projectId, now)) ? "can" : null;
|
||
}
|
||
|
||
/** Projects of the user whose agents stand and where a request is possible or sent (the strip over the pages). */
|
||
export async function subscriptionRequestOffers(db: Db, user: Pick<User, "id" | "login">, now = new Date()): Promise<Array<{ projectId: number; key: string; name: string; offer: RequestOffer }>> {
|
||
if (await isSuperadmin(db, user)) return [];
|
||
const out: Array<{ projectId: number; key: string; name: string; offer: RequestOffer }> = [];
|
||
for (const id of await userProjectIds(db, user.id)) {
|
||
const offer = await subscriptionRequestOffer(db, user, id, now);
|
||
if (!offer) continue;
|
||
const [p] = await db.select({ key: projects.key, name: projects.name }).from(projects).where(eq(projects.id, id));
|
||
if (p) out.push({ projectId: id, key: p.key, name: p.name, offer });
|
||
}
|
||
return out;
|
||
}
|
||
|
||
async function askAdmin(db: Db, project: Project, req: SubscriptionRequest, now: Date): Promise<Question> {
|
||
const platform = await getProject(db, platformProjectKey()).catch(() => null);
|
||
if (!platform) throw new PeppaError(m("Сейчас некому одолжить подписку — агенты продолжат, когда лимит сбросится"));
|
||
const until = await projectWaitUntil(db, project.id, now);
|
||
const candidate = await loanCandidate(db, project.id, now);
|
||
const vars = { login: asIs(req.login), project: asIs(project.name), time: until ? hhmm(until) : "" };
|
||
const head = until ? m("🙋 {login} просит подписку для проекта «{project}»: агенты стоят до {time}.", vars) : m("🙋 {login} просит подписку для проекта «{project}»: агенты стоят, время сброса неизвестно.", vars);
|
||
const text = candidate
|
||
? `${head}\n${m("Фабрика одолжит свободную подписку сама — выберите срок.")}`
|
||
: `${head}\n${m("Свободной подписки сейчас нет.")}`;
|
||
const options = candidate ? [LEND_UNTIL_RESET, LEND_DAY, REQUEST_DENY] : [REQUEST_REMIND, REQUEST_DENY];
|
||
return askPmProject(db, platform, { kind: "question", msgType: "question", options, defaultOption: options[0], text });
|
||
}
|
||
|
||
/** «Попросить подписку у администратора». One open request per project, 3 per user a day. */
|
||
export async function requestSubscription(db: Db, user: User, project: Project, now = new Date()): Promise<SubscriptionRequest> {
|
||
if (await isSuperadmin(db, user)) throw new PeppaError(m("Вы администратор — одолжите подписку сами в разделе «Подписки»"));
|
||
if (!(await userProjectIds(db, user.id)).includes(project.id)) throw new PeppaError(m("Проект не найден"));
|
||
const prev = await subscriptionRequest(db, project.id);
|
||
if (prev?.status === "open") throw new PeppaError(REQUEST_SENT_TEXT);
|
||
if (prev?.status === "lent" || (await poolHasLoan(db, project.id))) throw new PeppaError(m("Администратор уже одолжил подписку этому проекту"));
|
||
if (!(await projectNeedsSubscription(db, project.id, now))) throw new PeppaError(m("Агенты проекта сейчас работают — подписка не нужна"));
|
||
const log = ((await getSetting<number[]>(db, logKey(user.id))) ?? []).filter((t) => t > now.getTime() - DAY_MS);
|
||
if (log.length >= MAX_REQUESTS_PER_DAY) throw new PeppaError(m("Сегодня вы уже просили подписку {n} раза — попробуйте завтра", { n: MAX_REQUESTS_PER_DAY }));
|
||
const req: SubscriptionRequest = { userId: user.id, login: user.login, at: now.getTime(), status: "open", questionId: null };
|
||
const q = await askAdmin(db, project, req, now);
|
||
req.questionId = q.id;
|
||
await setSetting(db, requestKey(project.id), req);
|
||
await setSetting(db, questionKey(q.id), project.id);
|
||
await setSetting(db, logKey(user.id), [...log, now.getTime()]);
|
||
await logEvent(db, { projectId: project.id, type: "subscription_requested", payload: { login: user.login, questionId: q.id } });
|
||
return req;
|
||
}
|
||
|
||
async function tellUser(db: Db, project: Project, text: string) {
|
||
await askPmProject(db, project, { kind: "attention", text });
|
||
}
|
||
|
||
/** Who lends: the superadmin who answered, else the first superadmin. */
|
||
async function lenderLogin(db: Db): Promise<string | null> {
|
||
const id = currentActor()?.userId;
|
||
const u = id != null ? await getUser(db, id) : null;
|
||
if (u && (await isSuperadmin(db, u))) return u.login;
|
||
return (await platformAdmins(db))[0] ?? null;
|
||
}
|
||
|
||
/** The waiting agents of the project move onto the lent subscription now (the runner service; clients leave it to the watchdog). */
|
||
async function moveWaiting(db: Db, projectId: number, now: Date) {
|
||
if (isRunnerClient()) return;
|
||
const { tryRotate } = await import("./rotation.ts");
|
||
for (const s of await waitingSessions(db, projectId)) await tryRotate(db, s, "limit", now).catch(() => false);
|
||
}
|
||
|
||
/** The superadmin answered (Home, Telegram, «Подписки»). */
|
||
export async function onSubscriptionRequestAnswer(db: Db, q: Question, answer: string, now = new Date()): Promise<boolean> {
|
||
if (q.taskId || q.sessionId) return false;
|
||
const projectId = await getSetting<number>(db, questionKey(q.id));
|
||
if (projectId == null) return false;
|
||
const req = await subscriptionRequest(db, projectId);
|
||
await deleteSetting(db, questionKey(q.id));
|
||
const [project] = await db.select().from(projects).where(eq(projects.id, projectId));
|
||
if (!project || !req || req.status !== "open" || req.questionId !== q.id) return true;
|
||
const said = answer.trim();
|
||
if (said === REQUEST_REMIND) {
|
||
await setSetting(db, requestKey(projectId), { ...req, questionId: null, remindAt: now.getTime() + REMIND_MS } satisfies SubscriptionRequest);
|
||
return true;
|
||
}
|
||
if (said === LEND_UNTIL_RESET || said === LEND_DAY) {
|
||
const sub = await loanCandidate(db, projectId, now);
|
||
const pool = await projectPool(db, projectId);
|
||
const login = await lenderLogin(db);
|
||
if (!sub || !pool || !login) {
|
||
await clearRequest(db, projectId, null);
|
||
const until = await projectWaitUntil(db, projectId, now);
|
||
await tellUser(
|
||
db,
|
||
project,
|
||
until
|
||
? m("{project}: администратор согласился, но свободной подписки сейчас нет. Агенты продолжат в {time}, когда сбросится лимит.", { project: asIs(project.name), time: hhmm(until) })
|
||
: m("{project}: администратор согласился, но свободной подписки сейчас нет. Попросите ещё раз позже.", { project: asIs(project.name) }),
|
||
);
|
||
return true;
|
||
}
|
||
const reset = said === LEND_UNTIL_RESET ? await projectWaitUntil(db, projectId, now) : null;
|
||
let until = reset ?? new Date(now.getTime() + DAY_MS);
|
||
if (until.getTime() - now.getTime() < MIN_LOAN_MS) until = new Date(now.getTime() + MIN_LOAN_MS);
|
||
const hours = Math.min(168, Math.max(1, Math.ceil((until.getTime() - now.getTime()) / 3_600_000)));
|
||
await lendSubscription(db, { login }, { subscriptionId: sub.id, poolId: pool.id, hours, until, now, quiet: true });
|
||
await setSetting(db, requestKey(projectId), { ...req, status: "lent", questionId: null, until: until.getTime(), subscriptionId: sub.id, poolId: pool.id } satisfies SubscriptionRequest);
|
||
await tellUser(db, project, m("✅ {project}: администратор одолжил подписку до {time} — агенты продолжают.", { project: asIs(project.name), time: hhmm(until) }));
|
||
await moveWaiting(db, projectId, now);
|
||
return true;
|
||
}
|
||
// «Отказать» or the superadmin's own words (= the reason).
|
||
await clearRequest(db, projectId, null);
|
||
await logEvent(db, { projectId, type: "subscription_request_denied", payload: { login: req.login } });
|
||
const reason = said && said !== REQUEST_DENY ? said : "";
|
||
await tellUser(
|
||
db,
|
||
project,
|
||
reason
|
||
? m("{project}: администратор отказал в подписке: {reason}", { project: asIs(project.name), reason: asIs(reason) })
|
||
: m("{project}: администратор отказал в подписке. Агенты продолжат, когда сбросится лимит.", { project: asIs(project.name) }),
|
||
);
|
||
return true;
|
||
}
|
||
onAnswer((db, q, answer) => onSubscriptionRequestAnswer(db, q, answer));
|
||
|
||
/** PEP-150 × PEP-186: the owner chose «Попросить подписку у администратора» under the limit question
|
||
* (called by the limit question's own answer handler in platform-delays.ts). */
|
||
export async function requestFromLimitAnswer(db: Db, projectId: number, now = new Date()): Promise<void> {
|
||
const [project] = await db.select().from(projects).where(eq(projects.id, projectId));
|
||
if (!project) return;
|
||
const id = currentActor()?.userId ?? project.ownerId;
|
||
const user = id != null ? await getUser(db, id) : null;
|
||
if (!user) return;
|
||
try {
|
||
await requestSubscription(db, user, project, now);
|
||
} catch (e) {
|
||
if (e instanceof PeppaError) await tellUser(db, project, e.message);
|
||
else throw e;
|
||
}
|
||
}
|
||
|
||
/** The loan is over: agents of the project on it go to their own working subscription, or wait for its reset. */
|
||
async function endLoan(db: Db, project: Project, req: SubscriptionRequest, now: Date) {
|
||
const lent = req.subscriptionId!;
|
||
await returnLoan(db, req.poolId!, lent, "expired", { quiet: true });
|
||
const { rotateSession } = await import("./rotation.ts");
|
||
const { killRunner } = await import("./sessions.ts");
|
||
const own = await poolSubscriptions(db, req.poolId!);
|
||
let waiting: Date | null = null;
|
||
for (const s of (await listSessions(db, { active: true, projectId: project.id })).filter((x) => x.subscriptionId === lent)) {
|
||
const target = await rotationCandidate(db, s, { now });
|
||
if (target) {
|
||
await rotateSession(db, s, target, "loan", now);
|
||
continue;
|
||
}
|
||
// Nowhere to go: the agent stops and waits for its own subscription's reset.
|
||
const back = own.filter((x) => x.provider === s.provider).sort((a, b) => (a.limitedUntil?.getTime() ?? Infinity) - (b.limitedUntil?.getTime() ?? Infinity))[0] ?? own[0];
|
||
const resumeAt = back?.limitedUntil && back.limitedUntil > now ? back.limitedUntil : new Date(now.getTime() + MIN_LOAN_MS);
|
||
await killRunner(s);
|
||
await updateSession(db, s.id, { status: "rate_limited", resumeAt, subscriptionId: back?.id ?? s.subscriptionId, ...(back && back.provider !== s.provider ? { provider: back.provider, conversationId: null } : {}), rotateReason: null, limitProbeMin: null });
|
||
await logSessionEvent(db, s, "loan_ended", { subscriptionId: lent, resumeAt: resumeAt.toISOString() });
|
||
if (!waiting || resumeAt < waiting) waiting = resumeAt;
|
||
}
|
||
await clearRequest(db, project.id, req);
|
||
await tellUser(
|
||
db,
|
||
project,
|
||
waiting
|
||
? m("{project}: срок одолженной подписки кончился. Агенты продолжат в {time}, когда сбросится лимит вашей подписки.", { project: asIs(project.name), time: hhmm(waiting) })
|
||
: m("{project}: срок одолженной подписки кончился — агенты продолжают на вашей подписке.", { project: asIs(project.name) }),
|
||
);
|
||
}
|
||
|
||
/**
|
||
* Watchdog (before `expireLoans`): lent subscriptions whose time is up go back, «Напомнить позже»
|
||
* asks again after an hour, an open request whose agents run again by themselves is closed.
|
||
*/
|
||
export async function subscriptionRequestTick(db: Db, now = new Date()): Promise<number> {
|
||
let n = 0;
|
||
const loans = await listLoans(db);
|
||
for (const { projectId, req } of await allRequests(db)) {
|
||
const [project] = await db.select().from(projects).where(eq(projects.id, projectId));
|
||
if (!project || project.deletedAt) {
|
||
await clearRequest(db, projectId, req);
|
||
continue;
|
||
}
|
||
if (req.status === "lent") {
|
||
if (!loans.some((l) => l.poolId === req.poolId && l.subscriptionId === req.subscriptionId)) {
|
||
await clearRequest(db, projectId, req); // returned by hand
|
||
continue;
|
||
}
|
||
if (req.until != null && req.until <= now.getTime()) {
|
||
await endLoan(db, project, req, now);
|
||
n++;
|
||
}
|
||
continue;
|
||
}
|
||
if (!(await projectNeedsSubscription(db, projectId, now))) {
|
||
if (req.questionId) await answerQuestion(db, req.questionId, m("(неактуально: агенты проекта снова работают)"), "system").catch(() => {});
|
||
await clearRequest(db, projectId, req);
|
||
n++;
|
||
continue;
|
||
}
|
||
if (!req.questionId && req.remindAt != null && req.remindAt <= now.getTime()) {
|
||
const q = await askAdmin(db, project, req, now);
|
||
await setSetting(db, requestKey(projectId), { ...req, questionId: q.id, remindAt: null } satisfies SubscriptionRequest);
|
||
await setSetting(db, questionKey(q.id), projectId);
|
||
n++;
|
||
}
|
||
}
|
||
return n;
|
||
}
|
||
|
||
/** Open requests with their question (the superadmin's «Нужно ваше внимание»). */
|
||
export async function openSubscriptionRequests(db: Db): Promise<Array<{ projectId: number; key: string; name: string; login: string; questionId: number | null; remindAt: Date | null }>> {
|
||
const out = [];
|
||
for (const { projectId, req } of await allRequests(db)) {
|
||
if (req.status !== "open") continue;
|
||
const [p] = await db.select({ key: projects.key, name: projects.name }).from(projects).where(eq(projects.id, projectId));
|
||
if (p) out.push({ projectId, key: p.key, name: p.name, login: req.login, questionId: req.questionId, remindAt: req.remindAt ? new Date(req.remindAt) : null });
|
||
}
|
||
return out;
|
||
}
|