PEP-150: limit question offers «Попросить подписку у администратора» (PEP-186); keep main's deploy hook

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
peppa-bot 2026-11-17 02:43:59 +05:00
parent 8c6cea7465
commit e0df98d1af
6 changed files with 40 additions and 12 deletions

View File

@ -13,6 +13,8 @@ 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 {
@ -51,7 +53,7 @@ export async function limitDelay(db: Db, s: SessionView, text: string, o: { now?
const time = new Date(resumeAt).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" });
const q = await askPm(db, ref, {
kind: "question",
options: [LIMIT_ADD, LIMIT_WAIT],
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` }),

View File

@ -28,18 +28,20 @@ import { settings, type Db } from "@peppa/db";
import { like } from "drizzle-orm";
import { wakeOnGreen } from "./ci-feedback.ts";
import { moveTask } from "./flow.ts";
import { limitHintKey, limitOver, TURN_RETRY_MAX, type LimitHint } from "./limit-delay.ts";
import { LIMIT_REQUEST, limitHintKey, limitOver, TURN_RETRY_MAX, type LimitHint } from "./limit-delay.ts";
import { onAnswer, resolveTaskById, sendToSession } from "./sessions.ts";
import { requestFromLimitAnswer } from "./subscription-request.ts";
type Log = (m: string) => void;
// ── usage limit: the owner's answer ────────────────────────────────────────────────
/** The owner's answer is theirs to act on: nothing is typed to the agent. */
async function onLimitHintAnswer(db: Db, q: Question): Promise<boolean> {
async function onLimitHintAnswer(db: Db, q: Question, answer: string): Promise<boolean> {
const hint = await getSetting<LimitHint>(db, limitHintKey(q.projectId));
if (!hint || hint.questionId !== q.id) return false;
await setSetting(db, limitHintKey(q.projectId), { ...hint, questionId: null });
if (answer.trim() === LIMIT_REQUEST) await requestFromLimitAnswer(db, q.projectId);
return true;
}
onAnswer(onLimitHintAnswer);

View File

@ -286,6 +286,22 @@ export async function onSubscriptionRequestAnswer(db: Db, q: Question, answer: s
}
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!;

View File

@ -259,7 +259,7 @@ describe("Лимит подписки — вопрос только о дейс
const qs = await asked(proj.id);
assert.equal(qs.length, 1, "one question per limit window");
assert.equal(qs[0]!.kind, "question");
assert.deepEqual(qs[0]!.options, [runner.LIMIT_ADD, runner.LIMIT_WAIT]);
assert.deepEqual(qs[0]!.options, [runner.LIMIT_ADD, runner.LIMIT_REQUEST, runner.LIMIT_WAIT]);
assert.equal(await core.taskDelayed(db, await taskId(tp)), true);
assert.equal((await sentTo(ADMIN_CHAT)).filter((x) => x.includes(tp.taskKey)).length, 1, "one message for the superadmin");

View File

@ -56,12 +56,17 @@ describe("Попросить подписку у администратора (P
await p.waitStatus(sid, "rate_limited");
assert.equal(await runner.subscriptionRequestOffer(db, owner, proj.id), "can");
// Telegram: the limit message has the button right there.
const limitMsg = await p.waitQuestion(sid, "attention");
const tg = renderQuestion(limitMsg, { taskKey: p.taskKey, taskTitle: null, session: await core.getSession(db, sid), webUrl: "http://peppa.test" });
assert.ok(tg.buttons.flat().some((b) => b.callback_data === `s:${sid}:ask`), "«Попросить подписку» under the limit message");
// The owner's limit question (PEP-150) offers it as an answer — a button in Telegram too.
let limitQ: Awaited<ReturnType<typeof core.pendingQuestions>>[number] | undefined;
for (let i = 0; i < 50 && !limitQ; i++) {
limitQ = (await core.pendingQuestions(db, proj.id)).find((q) => q.options?.includes(runner.LIMIT_REQUEST));
if (!limitQ) await new Promise((r) => setTimeout(r, 200));
}
assert.ok(limitQ, "the limit question offers «Попросить подписку у администратора»");
const tg = renderQuestion(limitQ!, { taskKey: p.taskKey, taskTitle: null, session: await core.getSession(db, sid), webUrl: "http://peppa.test" });
assert.ok(tg.buttons.flat().some((b) => b.text.includes("Попросить подписку")), "a button under the limit message");
assert.equal(await runner.subscriptionRequestOffer(db, admin, proj.id), null, "a superadmin lends himself");
await runner.requestSubscription(db, owner, proj);
await core.runAsActor({ kind: "user", userId: owner.id, channel: "telegram" }, () => runner.answerAndDeliver(db, limitQ!.id, runner.LIMIT_REQUEST, "telegram"));
assert.equal(await runner.subscriptionRequestOffer(db, owner, proj.id), "sent");
const [q] = await adminQuestions();
assert.ok(q, "the superadmin got a question");

View File

@ -46,13 +46,16 @@ REPO="${GITEA_PLATFORM_REPO:-peppa/peppa}"
# The live copy refuses commits from now on (agents must work in worktrees).
HOOK="$(git rev-parse --git-path hooks)/pre-commit"
if ! grep -q "PEP-172" "$HOOK" 2>/dev/null; then
if ! grep -q "PEP-172/182" "$HOOK" 2>/dev/null; then
mkdir -p "$(dirname "$HOOK")"
cat >"$HOOK" <<'H'
#!/bin/sh
# PEP-172: this is the copy the live site runs from — no commits here. Work in a worktree:
# git worktree add ~/.peppa/worktrees/peppa/<name> -b task/<key> origin/main
# PEP-172/182: this repository's own working copy is the one the live site runs from — no commits
# there. Worktrees (agents, coordinator) share this hooks directory and must keep committing.
[ -n "$PEPPA_LIVE_COMMIT_OK" ] && exit 0
top=$(git rev-parse --show-toplevel 2>/dev/null)
live=$(cd "$(git rev-parse --git-common-dir)/.." && pwd -P)
[ "$(cd "$top" && pwd -P)" = "$live" ] || exit 0
echo "Peppa FACTORY: в этой копии работает живой сайт — коммиты здесь запрещены. Работайте в git worktree." >&2
exit 1
H