peppa/packages/runner/src/limit-delay.ts

76 lines
4.1 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.

// PEP-150: a usage limit with no subscription to switch to. Kept light — the hook process
// imports it (no runner flow behind it).
import { platformTime } from "@peppa/shared/time";
import { asIs, m } from "@peppa/shared/i18n";
import { answerQuestion, askPm, clearPlatformDelay, getSession, getSetting, listSessions, sessionDelay, setSetting, type SessionView, type TaskRef } from "@peppa/core";
import { projects, tasks, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { eq } from "drizzle-orm";
type Log = (m: string) => void;
/** «Продолжай» after a broken turn, at most this many times in a row. */
export const TURN_RETRY_MAX = 3;
export const LIMIT_ADD = m("Добавить подписку");
export const LIMIT_WAIT = m("Подождать");
/** PEP-186: the owner asks the superadmin to lend a subscription (handled in subscription-request.ts). */
export const LIMIT_REQUEST = m("Попросить подписку у администратора");
const LIMIT_CLOSED = m("(лимит сброшен — агенты продолжили сами)");
export interface LimitHint {
/** No second question before this (ms): one per limit window. */
until: number;
questionId: number | null;
}
export const limitHintKey = (projectId: number) => `limit.hint:${projectId}`;
/**
* The agent hit a usage limit and there is no subscription to switch to: the story shows the
* delay line, the superadmin gets one message per subscription and window. On the project's
* own subscription the owner is asked — once per window — whether to add another one: that
* is something only they can do.
*/
export async function limitDelay(db: Db, s: SessionView, text: string, o: { now?: Date; log?: Log } = {}): Promise<void> {
const now = o.now ?? new Date();
const fresh = await getSession(db, s.id).catch(() => s);
const resumeAt = fresh.resumeAt?.getTime() ?? null;
await sessionDelay(db, s, {
reason: "limit",
details: text,
state: resumeAt ? "waiting" : "stopped",
// No automatic continuation planned (switched off or today's cap reached): a person has to look.
exhausted: !resumeAt,
alertKey: resumeAt && s.subscriptionId != null ? `limit:sub${s.subscriptionId}:${Math.round(resumeAt / 3_600_000)}` : undefined,
now,
log: o.log,
});
if (!resumeAt || s.subscriptionId == null || !s.taskId) return;
const prev = await getSetting<LimitHint>(db, limitHintKey(s.projectId));
if (prev && prev.until > now.getTime()) return;
const [row] = await db.select({ task: tasks, project: projects }).from(tasks).innerJoin(projects, eq(tasks.projectId, projects.id)).where(eq(tasks.id, s.taskId));
if (!row) return;
const ref: TaskRef = { ...row, key: formatTaskKey(row.project.key, row.task.number) };
const time = platformTime(resumeAt);
const q = await askPm(db, ref, {
kind: "question",
options: [LIMIT_ADD, LIMIT_REQUEST, LIMIT_WAIT],
text: [
m("⏳ {project}: агенты продолжат в {time}. Чтобы не ждать, добавьте вторую подписку.", { project: asIs(ref.project.name), time }),
m("Добавить подписку Claude или ChatGPT: {url}", { url: `${process.env.PEPPA_WEB_URL ?? ""}/p/${ref.project.key}#subscription` }),
].join("\n"),
});
await setSetting(db, limitHintKey(s.projectId), { until: resumeAt, questionId: q.id } satisfies LimitHint);
}
/** The limit is over for a story: its delay line goes, and the owner's question once no agent of the project waits. */
export async function limitOver(db: Db, s: Pick<SessionView, "id" | "projectId" | "taskId">): Promise<void> {
if (s.taskId) await clearPlatformDelay(db, { projectId: s.projectId, taskId: s.taskId }, "limit");
const hint = await getSetting<LimitHint>(db, limitHintKey(s.projectId));
if (!hint?.questionId) return;
const waiting = (await listSessions(db, { active: true, projectId: s.projectId })).some((x) => x.id !== s.id && x.status === "rate_limited");
if (waiting) return;
await answerQuestion(db, hint.questionId, LIMIT_CLOSED, "system").catch(() => {});
await setSetting(db, limitHintKey(s.projectId), { ...hint, questionId: null });
}