Заход приёмки 27.11: PEP-303 поверх main и принятых перед ней [skip ci]

This commit is contained in:
peppa-bot 2026-11-27 10:06:37 +05:00
commit 22136ea160
17 changed files with 431 additions and 26 deletions

4
.peppa/memory/pep-303.md Normal file
View File

@ -0,0 +1,4 @@
# Память: PEP-303
## Грабли
- Сторож экрана (PEP-303): строки — через `screen-lines.ts` (`isQuotedLine`/`ownLines`), фразу CLI якорить к началу строки, нажимать только на неизменном экране (`still`). Мок `say` печатает «⏺ » перед текстом.

View File

@ -0,0 +1,17 @@
## Context
Сторожа экрана (PEP-205, PEP-227, PEP-241, PEP-265, PEP-56/166/300) ищут фразы регулярными выражениями в хвосте экрана целиком. Экран работающего агента содержит вывод его инструментов: diff (Claude: ` 447 + код`, Codex: `447 +код`), вывод grep (`путь:12:текст`), `cat` файлов, ответы агента. Платформа FORGE делается своими же агентами, и в её коде эти фразы есть в комментариях, тестах и моках.
## Decisions
1. **«Чужая» строка** — `isQuotedLine` (runner/screen-lines.ts): номер строки с `+`/`-` или широким отступом после него (diff, `cat -n`), `число:` в начале (grep -n), строка, начинающаяся с `+`/`-`/`@@` (diff без номеров), `путь:число` (grep). Значок вывода инструмента (`⎿ └ │ ├`) перед ними не спасает. Номер варианта «1. …» не подходит ни под одно правило (после цифры — точка).
2. **Плашка лимита — положительный якорь**, а не поиск фразы где угодно: `LIMIT_LINE_RE` требует, чтобы строка начиналась с фразы лимита, допуская один значок CLI (не `+ - < > | :` и не рамку), `API Error:`, `Claude (AI)`, `5-hour/weekly/Opus weekly`. Без значка — отступ не больше двух пробелов (продолжение вывода инструмента идёт с отступом 5). `LIMIT_SCREEN_RE` остаётся фразой (её используют `parseResetTime` и тесты), но экран читается только через `limitLines`/`isLimitLine`; мёртвое окно — тоже через `limitLines`.
3. **Диалог кредитов — структура**: снизу вверх пропускаются подсказки клавиш, рамки и пустые строки, затем блок вариантов `N. текст` (минимум два, по порядку с 1), над ним (до 8 строк) — строка с фразой, которая начинается с названия модели и не «чужая». Строки в рамке `│ … │` разворачиваются. Приглашение ввода `>` под вариантами означает, что диалог уже не ждёт — `null`.
4. **Неизменность экрана**: вачдог сравнивает хэш экрана с сохранённым в `watch_state.screen` до обновления. Нажатия (кредиты, меню Codex, доверие папке) и сообщение о кредитах — только если экран тот же, что на прошлом проходе: настоящий диалог стоит, работающий агент меняет экран. Это добавляет к реакции один проход вачдога (~30 с) — приемлемо: диалог ждёт сколько угодно.
5. **Остальные сторожа**: `startQuestion` и `usageWarning` читают экран без «чужих» строк (`ownLines`). Плашку лимита в истории разговора после resume по-прежнему считает база PEP-166, срок — PEP-300.
6. Мок: действие `credits` (`{ switch?: boolean }`) — настоящий диалог с ожиданием клавиши, как `menu` у Codex; тесты диалога переведены на него (раньше это была реплика `say`, после которой мок печатал приглашение `>` — такой экран теперь, правильно, не диалог).
## Risks
- Настоящие экраны диалога кредитов не сняты (PEP-227) — правило структуры терпимо к рамке, подсказкам и описанию между вопросом и вариантами. Если CLI напишет вопрос с префиксом, которого нет в правиле, будет пропуск диалога; тогда сработает зависание на старте (PEP-265) или «завис» — не ложная тревога.
- Плашка, которую CLI когда-нибудь напечатает с непредусмотренным префиксом, не будет узнана экраном — но у Claude лимит приходит и хуком StopFailure.

View File

@ -0,0 +1,20 @@
## Why
26.11 вачдог дважды принял текст из работы агента за экран самого CLI. В 12:57 суперадмину ушло «агент ждёт на экране выбора модели — модель просит отдельные кредиты»: агент PEP-268 правил watchdog.ts, где эта фраза стоит в комментарии. В 22:25 строка мока `out(`■ You’ve hit your usage limit…`)` в diff стала «плашкой лимита»: подписку пометили «лимит», работающего агента остановили и перезапустили на другой подписке. Агенты FORGE правят код платформы, где все эти фразы написаны, — сторожа экрана должны отличать экран CLI от вывода инструментов.
## What Changes
- Диалог «модель просит кредиты» (Claude) — только экран, который ждёт выбора: строка-вопрос (не строка diff/grep/кода), под ней пронумерованные варианты 1…N внизу экрана (ниже — только подсказки клавиш и рамки), и экран не изменился с прошлого прохода вачдога. Тогда — нажатие «Switch to Opus…» или одно сообщение суперадмину, как раньше.
- Меню модели Codex и вопрос о доверии папке: вопрос и варианты ищутся только в строках, которые не похожи на diff, вывод grep или код; нажатие — только на неизменившемся экране.
- Плашка лимита (Claude и Codex, живое и мёртвое окно): строка должна начинаться с фразы лимита (допускаются значок CLI `■ ⎿ ⏺ …`, «API Error:», «Claude (AI)», «5-hour/weekly»). Строка diff (номер, «+»/«-»), вывод grep (`путь:строка:`), код и комментарии плашкой не считаются.
- Вопросы на старте (PEP-265) и предупреждение о пороге подписки читают только «свои» строки экрана.
- Выбор подписки, переключение и учёт срока лимита (PEP-300) не меняются.
## Capabilities
### Modified Capabilities
- `session-watchdog`: распознавание экрана CLI отделено от текста в выводе агента.
## Impact
`packages/runner/src/screen-lines.ts` (новый), `claude-screen.ts`, `codex-screen.ts`, `start-screen.ts`, `limits.ts`, `rotation.ts` (`usageWarning`), `watchdog.ts`; мок `credits` в `packages/testkit` (`mock-agent.ts`, `scenario.ts`); тест `screen-watchers.test.ts`, правки `lost-conversation.test.ts`.

View File

@ -0,0 +1,38 @@
## ADDED Requirements
### Requirement: Экран CLI отличается от вывода агента
Сторожа экрана вачдога (плашка лимита, диалог кредитов модели Claude, меню модели и доверие папке Codex, вопросы на старте, предупреждение о пороге подписки) SHALL реагировать только на строки, которые печатает сам CLI. Строки diff (номер строки, «+» или «-» перед текстом), вывод grep (`путь:строка:`), код и комментарии SHALL NOT считаться экраном CLI. Диалог, ждущий выбора, SHALL распознаваться только когда под вопросом внизу экрана стоят пронумерованные варианты и экран не изменился с прошлого прохода вачдога; только тогда вачдог нажимает клавишу или сообщает суперадмину.
#### Scenario: Фраза диалога в diff и выводе grep
- **GIVEN** агент Claude работает над задачей
- **AND** на его экране diff со строкой «331 + // «<model> now uses usage credits»» и вывод grep «docs/a.md:3:1. Switch to Opus 5.5»
- **WHEN** вачдог проходит по экрану два раза подряд
- **THEN** суперадмину не уходит сообщение о кредитах
- **AND** в окно агента не нажата ни одна клавиша
#### Scenario: Настоящий диалог кредитов
- **GIVEN** агент Claude стоит на экране «Fable 5.2 now uses usage credits» с вариантами «1. Use usage credits», «2. Switch to Opus 5.5», «3. Exit»
- **WHEN** вачдог видит этот экран второй проход подряд
- **THEN** в окно агента нажата клавиша «2»
- **AND** в журнале сессии событие `model_dialog_dismissed`
#### Scenario: Строка лимита внутри diff
- **GIVEN** агент Codex работает на подписке №1
- **AND** на его экране строка diff «447 + out(`■ You’ve hit your usage limit. Try again at 8:47 PM.`)»
- **WHEN** вачдог проходит по экрану
- **THEN** события `usage_limit` нет
- **AND** подписка №1 не помечена «лимит»
- **AND** агент продолжает работать
#### Scenario Outline: Настоящая плашка лимита
- **GIVEN** агент <cli> на подписке, у которой кончился лимит
- **AND** CLI печатает «<строка>»
- **WHEN** вачдог проходит по экрану (<окно>)
- **THEN** в журнале событие `usage_limit` с этой строкой
| cli | строка | окно |
|---|---|---|
| Codex | ■ You’ve hit your usage limit. Try again at 8:47 PM. | живое |
| Claude | ⎿ Claude usage limit reached. Your limit will reset at 9pm. | живое |
| Codex | ■ You’ve hit your usage limit. Try again at 8:47 PM. | мёртвое |

View File

@ -0,0 +1,17 @@
## 1. Распознавание экрана
- [x] 1.1 `screen-lines.ts`: `isQuotedLine`, `ownLines`, `unbox`
- [x] 1.2 Плашка лимита: `LIMIT_LINE_RE`/`isLimitLine`, `limitLines` через неё; мёртвое окно в вачдоге — через `limitLines`
- [x] 1.3 Диалог кредитов: структура «вопрос → варианты внизу»
- [x] 1.4 Меню модели и доверие папке Codex, `startQuestion`, `usageWarning` — только «свои» строки
- [x] 1.5 Вачдог: нажатия и сообщение о кредитах — только на неизменившемся экране
## 2. Тесты
- [x] 2.1 Мок `credits`; тесты диалога в `lost-conversation.test.ts` — на нём
- [x] 2.2 `screen-watchers.test.ts`: diff/grep с фразой и «1. Switch to Opus» — нет тревоги и нажатия; строка лимита в diff — нет `usage_limit`, подписка не помечена, агент не остановлен; настоящие плашки Claude/Codex на живом и мёртвом окне узнаются
- [x] 2.3 Проверить, что новые тесты падают на старом коде; прогнать связанные тесты (limits, codex-recovery, start-hang, lost-conversation, subscription-*)
## 3. Завершение
- [x] 3.1 Память, archive, PR

View File

@ -67,3 +67,40 @@
- **WHEN** на экране появляется «Usage limit reached · resets 3pm»
- **THEN** сессия `rate_limited` со временем продолжения 15:00
- **AND** на следующих проходах в том же поколении повторной обработки нет
### Requirement: Экран CLI отличается от вывода агента
Сторожа экрана вачдога (плашка лимита, диалог кредитов модели Claude, меню модели и доверие папке Codex, вопросы на старте, предупреждение о пороге подписки) SHALL реагировать только на строки, которые печатает сам CLI. Строки diff (номер строки, «+» или «-» перед текстом), вывод grep (`путь:строка:`), код и комментарии SHALL NOT считаться экраном CLI. Диалог, ждущий выбора, SHALL распознаваться только когда под вопросом внизу экрана стоят пронумерованные варианты и экран не изменился с прошлого прохода вачдога; только тогда вачдог нажимает клавишу или сообщает суперадмину.
#### Scenario: Фраза диалога в diff и выводе grep
- **GIVEN** агент Claude работает над задачей
- **AND** на его экране diff со строкой «331 + // «<model> now uses usage credits»» и вывод grep «docs/a.md:3:1. Switch to Opus 5.5»
- **WHEN** вачдог проходит по экрану два раза подряд
- **THEN** суперадмину не уходит сообщение о кредитах
- **AND** в окно агента не нажата ни одна клавиша
#### Scenario: Настоящий диалог кредитов
- **GIVEN** агент Claude стоит на экране «Fable 5.2 now uses usage credits» с вариантами «1. Use usage credits», «2. Switch to Opus 5.5», «3. Exit»
- **WHEN** вачдог видит этот экран второй проход подряд
- **THEN** в окно агента нажата клавиша «2»
- **AND** в журнале сессии событие `model_dialog_dismissed`
#### Scenario: Строка лимита внутри diff
- **GIVEN** агент Codex работает на подписке №1
- **AND** на его экране строка diff «447 + out(`■ You’ve hit your usage limit. Try again at 8:47 PM.`)»
- **WHEN** вачдог проходит по экрану
- **THEN** события `usage_limit` нет
- **AND** подписка №1 не помечена «лимит»
- **AND** агент продолжает работать
#### Scenario Outline: Настоящая плашка лимита
- **GIVEN** агент <cli> на подписке, у которой кончился лимит
- **AND** CLI печатает «<строка>»
- **WHEN** вачдог проходит по экрану (<окно>)
- **THEN** в журнале событие `usage_limit` с этой строкой
| cli | строка | окно |
|---|---|---|
| Codex | ■ You’ve hit your usage limit. Try again at 8:47 PM. | живое |
| Claude | ⎿ Claude usage limit reached. Your limit will reset at 9pm. | живое |
| Codex | ■ You’ve hit your usage limit. Try again at 8:47 PM. | мёртвое |

View File

@ -1,18 +1,41 @@
// PEP-227: what the Claude CLI shows on its screen when it is not the agent's work that stopped it —
// the «<model> now uses usage credits» dialog (20.11: Fable 5.2 began to need separate credits and
// agents without a model in their settings hung on it). The real screen is not captured yet, so the
// patterns are lenient: the question anywhere near the bottom, a numbered «Switch to Opus…» choice.
// patterns are lenient about wording, strict about shape (PEP-303): a question, choices at the bottom.
import * as tmux from "./tmux.ts";
import { isQuotedLine, screenBottom, unbox } from "./screen-lines.ts";
const CREDITS_RE = /now uses (?:usage )?credits/i;
const SWITCH_RE = /^\s*(?:[›❯>]\s*)?(\d)[.)]\s*Switch to Opus\b/im;
// PEP-303: the question line begins with the model's name («Fable 5.2 now uses usage credits») after at
// most one glyph of the CLI — not a comment, a string in code or a sentence that quotes it.
const CREDITS_LINE_RE = /^\s*(?:[^\w\s"'`«(\[{<>|:+\-#*\/]\s*)?[\w .-]{0,40}?\bnow uses (?:usage )?credits\b/iu;
const CHOICE_RE = /^\s*(?:[›❯>]\s*)?(\d)[.)]\s+(\S.*)$/;
const SWITCH_RE = /^Switch to Opus\b/i;
/** Below a waiting dialog: blank rows, its frame and key hints («Enter to confirm · Esc to cancel»). */
const FOOTER_RE = /^\s*$|^[\s─━═╭╮╰╯┌┐└┘]+$|\b(?:enter|esc|tab)\b|↑|↓|to (?:select|confirm|cancel|navigate)/i;
/** The credits dialog is on screen: `{ digit }` of «Switch to Opus…» (null when there is no such choice), else null. */
/**
* The credits dialog waits on screen: `{ digit }` of «Switch to Opus…» (null when there is no such
* choice), else null. PEP-303: a dialog is the question, numbered choices 1…N under it at the bottom
* of the screen and nothing below them but key hints — a diff, grep output or the agent's answer
* that mentions the phrase is not one (the caller also wants the screen unchanged between two passes).
*/
export function claudeCreditsDialog(screen: string): { digit: string | null } | null {
// The pane is padded with blank rows below the text.
const tail = screen.trimEnd().split("\n").slice(-30).join("\n");
if (!CREDITS_RE.test(tail)) return null;
return { digit: SWITCH_RE.exec(tail)?.[1] ?? null };
const lines = screenBottom(screen, 30).map(unbox);
let end = lines.length;
while (end > 0 && !CHOICE_RE.test(lines[end - 1]!) && FOOTER_RE.test(lines[end - 1]!)) end--;
// The choices block, bottom up (blank rows between choices are allowed).
const choices: { n: number; text: string }[] = [];
let i = end - 1;
for (; i >= 0; i--) {
const c = CHOICE_RE.exec(lines[i]!);
if (c && !isQuotedLine(lines[i]!)) choices.unshift({ n: Number(c[1]), text: c[2]!.trim() });
else if (!lines[i]!.trim() && choices.length) continue;
else break;
}
if (choices.length < 2 || choices.some((c, k) => c.n !== k + 1)) return null;
const question = lines.slice(Math.max(0, i - 7), i + 1).some((l) => CREDITS_LINE_RE.test(l) && !isQuotedLine(l));
if (!question) return null;
return { digit: String(choices.find((c) => SWITCH_RE.test(c.text))?.n ?? "") || null };
}
/** Picks «Switch to Opus…» in the credits dialog. Returns true when a key was sent. */

View File

@ -2,6 +2,7 @@
// the «Switch to <model>?» menu near the limit and a sign-in hiccup. Kept apart from the watchdog so
// the texts can be checked on real screens (packages/testkit/fixtures).
import * as tmux from "./tmux.ts";
import { ownLines, screenBottom } from "./screen-lines.ts";
/** «Switch to gpt-… for lower credit usage?» with its three choices. */
const MENU_QUESTION_RE = /Switch to \S+.*\?/;
@ -9,8 +10,8 @@ const MENU_KEEP_RE = /^\s*(?:›\s*)?(\d)\.\s*Keep current model\s*$/m;
/** The digit of «Keep current model» when the model menu is on screen, else null. */
export function codexModelMenu(screen: string): string | null {
// The pane is padded with blank rows below the text.
const tail = screen.trimEnd().split("\n").slice(-25).join("\n");
// PEP-303: a diff or grep output that quotes the menu is not the menu.
const tail = ownLines(screenBottom(screen, 25).join("\n"));
if (!MENU_QUESTION_RE.test(tail) || !/enter select/i.test(tail)) return null;
return MENU_KEEP_RE.exec(tail)?.[1] ?? null;
}
@ -38,7 +39,7 @@ export interface CodexTrustPrompt {
/** The trust question on Codex's screen: the digit of «Trust and continue» and the folders it names. */
export function codexTrustPrompt(screen: string): CodexTrustPrompt | null {
const tail = screen.trimEnd().split("\n").slice(-30).join("\n");
const tail = ownLines(screenBottom(screen, 30).join("\n"));
if (!TRUST_QUESTION_RE.test(tail)) return null;
const digit = TRUST_YES_RE.exec(tail)?.[1];
if (!digit) return null;

View File

@ -3,6 +3,7 @@ import { m } from "@peppa/shared/i18n";
import { markSubscriptionLimited, updateSession, type SessionView } from "@peppa/core";
import type { Db } from "@peppa/db";
import { planRotation } from "./rotation.ts";
import { isQuotedLine } from "./screen-lines.ts";
/** PEP-107: what to do so agents don't wait for a reset next time. */
export const ADD_SUBSCRIPTION_HINT = m("Чтобы агенты не ждали — добавьте ещё одну подписку Claude или ChatGPT: «Настройки проекта → Подписки».");
@ -16,8 +17,19 @@ const REPEAT_WINDOW_MS = 5 * 60_000;
// PEP-205: Codex prints a typographic apostrophe — «You’ve hit your usage limit … try again at 8:47 PM».
export const LIMIT_SCREEN_RE = /(usage limit reached|limit reached.{0,40}reset|you[’'`]ve hit your (usage )?limit|out of extra usage)/i;
// PEP-303: a banner is a line the CLI printed, so it *begins* with the limit phrase — after at most two
// glyphs of the CLI («■ ⎿ ⏺ ● ✗ ⚠ ·»; not «+ - < > | : # * /» nor a frame) and the words it puts in front
// («API Error:», «Claude (AI)», «5-hour», «weekly»). A diff line («447 + out(`■ You’ve hit…`)»), grep
// output, code or a comment that quotes the phrase is not a banner. Without a glyph the line may be
// indented by two spaces at most: the continuation lines of a tool's output are indented by five.
const LIMIT_LINE_RE =
/^(?:(?:\s*[^\w\s"'`(\[{<>|:+\-#*\/─-╿]️?){1,2}\s*|\s{0,2})(?:API Error:\s*)?(?:Claude(?: AI)?\s+|(?:\d+-hour|(?:opus\s+)?weekly)\s+)?(?:you[’'`]re\s+)?(?:usage limit reached|limit reached.{0,40}reset|you[’'`]ve hit your (?:usage )?limit|out of extra usage)/iu;
/** One screen line is the CLI's limit banner (see LIMIT_LINE_RE), not a quote of it. */
export const isLimitLine = (line: string): boolean => LIMIT_LINE_RE.test(line) && !isQuotedLine(line);
/** Limit banner lines on a captured screen, top to bottom. */
export const limitLines = (screen: string): string[] => screen.split("\n").filter((l) => LIMIT_SCREEN_RE.test(l)).map((l) => l.trim());
export const limitLines = (screen: string): string[] => screen.split("\n").filter(isLimitLine).map((l) => l.trim());
/**
* PEP-166: is there a limit banner that was not on the screen when this generation started?

View File

@ -22,6 +22,7 @@ import { events, type Db } from "@peppa/db";
import { and, count, eq, gte } from "drizzle-orm";
import * as tmux from "./tmux.ts";
import { isRunnerClient, runnerCall } from "./runner-client.ts";
import { ownLines } from "./screen-lines.ts";
export const SWITCH_EVENT = "subscription_switched";
export const ROTATE_WINDOW_MS = 60 * 60_000;
@ -171,7 +172,8 @@ const WARN_RE = /(approaching (?:your )?(?:usage )?limit|(\d{1,3})\s?% of your [
/** True when the screen shows a usage warning at or above the threshold. */
export function usageWarning(screen: string): boolean {
const m = WARN_RE.exec(screen);
// PEP-303: not a warning quoted by a diff or grep output.
const m = WARN_RE.exec(ownLines(screen));
if (!m) return false;
const pct = Number(m[2] ?? m[3] ?? NaN);
return Number.isNaN(pct) || pct >= rotateThresholdPct();

View File

@ -0,0 +1,36 @@
// PEP-303: the watchdog's screen guards look for phrases the agent CLI prints (a limit banner, a
// model dialog, a trust question). FORGE agents edit FORGE's own code, where these phrases stand in
// comments, tests and mocks — and a diff, a grep hit or a `cat` of such a file lands on the agent's
// screen. These helpers tell the CLI's own lines from text quoted by the agent's tools.
/** A tool-output gutter glyph that may precede a quoted line: Claude «⎿», Codex «└ │ ├». */
const GUTTER = String.raw`(?:[⎿└│├]\s*)?`;
const QUOTED: RegExp[] = [
// A diff or `cat -n` with line numbers: « 447 + code», «447 -x», « 12 context», grep -n «12:text».
new RegExp(String.raw`^\s*${GUTTER}\d+(?:\s+[+-]|\s{2,}\S|:\S)`),
// A diff without numbers: «+code», «- code», «@@ -1,3 +1,4 @@».
new RegExp(String.raw`^\s*${GUTTER}(?:[+-]|@@)`),
// grep / compiler output: «path/to/file.ts:12:text», «file.md:3-…».
new RegExp(String.raw`^\s*${GUTTER}[^\s:]+:\d+[:-]`),
];
/** True when the line is text the agent's tools quoted (a diff, grep output, numbered source), not the CLI's own UI. */
export function isQuotedLine(line: string): boolean {
return QUOTED.some((re) => re.test(line));
}
/** A line of a boxed dialog without its frame: «│ Do you trust…? │» → «Do you trust…?». */
export function unbox(line: string): string {
return line.replace(/^\s*[│┃]\s?/, "").replace(/\s*[│┃]\s*$/, "").trimEnd();
}
/** The screen without quoted lines (see `isQuotedLine`). */
export function ownLines(screen: string): string {
return screen.split("\n").filter((l) => !isQuotedLine(l)).join("\n");
}
/** The last `n` rows of a pane, without the blank rows that pad it below the text. */
export function screenBottom(screen: string, n: number): string[] {
return screen.trimEnd().split("\n").slice(-n);
}

View File

@ -4,26 +4,30 @@
// read, and the watchdog asks only while the agent has made no action yet.
import { claudeCreditsDialog } from "./claude-screen.ts";
import { codexModelMenu, codexTrustPrompt } from "./codex-screen.ts";
import { ownLines, screenBottom } from "./screen-lines.ts";
export type StartQuestion = "trust" | "model" | "login" | "setup";
const CLAUDE: [StartQuestion, RegExp][] = [
["trust", /Do you trust the files in this folder\?|Is this a project you (?:created|trust)|Quick safety check|Yes, I trust this folder|Yes, proceed\b/i],
["model", /now uses (?:usage )?credits|Select model\b|Choose (?:a|the|your) model/i],
// PEP-303: the credits dialog — only by its shape (`claudeCreditsDialog`), the phrase alone may be quoted.
["model", /Select model\b|Choose (?:a|the|your) model/i],
["login", /Select login method|Please run \/login|Invalid API key|Not logged in|OAuth token has expired|Paste code here/i],
["setup", /Choose the text style|Bypass Permissions mode|Yes, I accept|Use Claude Code's terminal setup|Press Enter to continue/i],
];
const CODEX: [StartQuestion, RegExp][] = [
["trust", /Trust this folder\?|Do you trust the contents of this directory\?|Folder access/i],
["model", /Switch to \S+.*\?|Choose (?:a|the|your) model/i],
// PEP-303: the «Switch to …?» menu — only by its shape (`codexModelMenu`).
["model", /Choose (?:a|the|your) model/i],
["login", /Sign in with ChatGPT|Provide your own API key|Finish signing in|Login with ChatGPT/i],
["setup", /Approval mode|Allow Codex to work in this folder|Press enter to continue/i],
];
/** Which question the CLI waits on (null — none recognized). `provider`: "claude" | "codex". */
export function startQuestion(provider: string, screen: string): StartQuestion | null {
const tail = screen.trimEnd().split("\n").slice(-30).join("\n");
// PEP-303: a resumed conversation shows its history — quoted diffs and grep output are not questions.
const tail = ownLines(screenBottom(screen, 30).join("\n"));
if (!tail.trim()) return null;
if (provider === "codex") {
if (codexTrustPrompt(tail)) return "trust";

View File

@ -35,7 +35,7 @@ import { projects, type Db } from "@peppa/db";
import { eq } from "drizzle-orm";
import { realpathSync } from "node:fs";
import * as tmux from "./tmux.ts";
import { ADD_SUBSCRIPTION_HINT, freshLimitLine, LIMIT_SCREEN_RE, limitLines, passedReset, recordLimit } from "./limits.ts";
import { ADD_SUBSCRIPTION_HINT, freshLimitLine, limitLines, passedReset, recordLimit } from "./limits.ts";
import { limitDelay, limitOver } from "./limit-delay.ts";
import { checksQueueTick, platformDelayTick } from "./platform-delays.ts";
import { readyDigestTick } from "./ready-digest.ts";
@ -272,7 +272,7 @@ async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, cfg:
await logSessionEvent(db, s, "exited", { exitStatus: pane.exitStatus, tail });
await killRunner(s).catch(() => {});
if (ok) await updateSession(db, s.id, { status: "done", endedAt: new Date() });
else if (LIMIT_SCREEN_RE.test(tail) && !passedReset(limitLines(tail).at(-1)!, nowDate)) {
else if (limitLines(tail).length && !passedReset(limitLines(tail).at(-1)!, nowDate)) {
// PEP-205: the CLI gave up on a usage limit — that is a limit, not a crash: another subscription
// or a pause until the reset, no automatic restart is spent.
const line = limitLines(tail).at(-1)!;
@ -298,6 +298,9 @@ async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, cfg:
const hash = createHash("sha1").update(screen).digest("hex");
const now = (opts.now ?? new Date()).getTime();
let last = s.lastActivityAt?.getTime() ?? now;
// PEP-303: a dialog waits — its screen stands still between two passes; a working agent's screen
// moves (and may well show the dialog's phrase in a diff). Keys and alerts only on a still screen.
const still = s.watchState?.screen === hash;
// PEP-28: the screen hash lives in the DB — a restarted watchdog does not see "new activity".
if (s.watchState?.screen !== hash) {
last = now;
@ -311,7 +314,7 @@ async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, cfg:
// PEP-205: Codex's «Switch to <model>?» menu waits for a key and swallows whatever is typed next —
// answer «Keep current model» (the digit, then Enter if the menu is still there a tick later).
if (s.provider === "codex" && codexModelMenu(screen)) {
if (still && s.provider === "codex" && codexModelMenu(screen)) {
const again = !!s.watchState?.menuAt && now - s.watchState.menuAt < 120_000;
if (again) await tmux.sendKeys(tmux.sessionPane(s), "Enter").catch(() => {});
else if (await dismissCodexMenu(tmux.sessionPane(s), screen).catch(() => false)) await logSessionEvent(db, s, "model_menu_dismissed", {});
@ -319,7 +322,7 @@ async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, cfg:
}
// PEP-241: «Trust this folder?» waits for a key before the first turn — answer «Trust and continue»,
// only for the folder Peppa gave the agent (its worktree, the project's copy and their repository roots).
if (s.provider === "codex" && codexTrustPrompt(screen) && !(s.watchState?.menuAt && now - s.watchState.menuAt < 120_000)) {
if (still && s.provider === "codex" && codexTrustPrompt(screen) && !(s.watchState?.menuAt && now - s.watchState.menuAt < 120_000)) {
const allowed = await agentFolders(db, s);
const res = await dismissCodexTrust(tmux.sessionPane(s), screen, allowed).catch(() => null);
if (res === "sent") await logSessionEvent(db, s, "trust_dismissed", {});
@ -328,7 +331,7 @@ async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, cfg:
}
// PEP-227: Claude's «<model> now uses usage credits» dialog waits for a choice — pick «Switch to Opus…»;
// without such a choice the superadmin hears once per generation.
if (s.provider === "claude") {
if (still && s.provider === "claude") {
const dialog = claudeCreditsDialog(screen);
if (dialog?.digit) {
const again = !!s.watchState?.menuAt && now - s.watchState.menuAt < 120_000;

View File

@ -414,6 +414,14 @@ async function run(action: Action): Promise<boolean> {
log("menu", { key });
out(key === "1" ? "• Switched to gpt-6-luna\n" : "• Keeping the current model\n");
mode = "busy";
} else if ("credits" in action) {
const spec = typeof action.credits === "object" ? action.credits : {};
const choices = spec.switch === false ? ["Continue", "Exit"] : ["Use usage credits", "Switch to Opus 5.5", "Exit"];
out(`\n Fable 5.2 now uses usage credits\n\n${choices.map((c, i) => `${i ? " " : "❯ "}${i + 1}. ${c}`).join("\n")}\n\n Enter to confirm · Esc to cancel\n`);
const key = await dialog();
log("credits", { key });
out(`⏺ ${key === "2" && spec.switch !== false ? "Switched to Opus 5.5" : "Continuing"}\n`);
mode = "busy";
} else if ("trust" in action) {
const spec = typeof action.trust === "object" ? action.trust : {};
out(` Folder access\n\n Trust this folder?\n ${spec.path ?? cwd}\n\n› 1. Trust and continue\n 2. Back to Agent Command Center\n\n enter select · esc back\n`);
@ -447,6 +455,11 @@ async function run(action: Action): Promise<boolean> {
out(`■ You’ve hit your usage limit.${spec.reset === "unknown" ? "" : ` Try again at ${at}.`}\n`);
}
log("limit");
// PEP-303: the CLI gives up on the limit — the banner stays in a dead window.
if (spec.exit != null) {
log("exit", { code: spec.exit, reason: "limit" });
process.exit(spec.exit);
}
return false;
} else if ("hang" in action) {
log("hang");

View File

@ -10,8 +10,9 @@ export type Action =
| { permission: { tool: string; input: Record<string, unknown> } } // claude: PermissionRequest
| { ask: Array<{ question: string; options?: string[] }> } // claude: AskUserQuestion
// usage limit: StopFailure (claude) / banner only (codex); resetInSec → "resets at HH:MM";
// exit → the CLI quits with this code after the banner (PEP-303);
// credential → only when the run's login (Claude token, Codex auth.json, OpenCode key) contains it
| { limit: true | { resetInSec?: number; reset?: "unknown"; credential?: string } }
| { limit: true | { resetInSec?: number; reset?: "unknown"; credential?: string; exit?: number } }
// PEP-5: an assistant message with this token usage in the transcript, then (claude) the
// statusLine command with cost / context / limit windows (pct, reset in N seconds)
| { usage: { input?: number; output?: number; cacheRead?: number; cacheWrite?: number; model?: string; costUsd?: number; context?: { used: number; size: number }; fiveHour?: number; sevenDay?: number; resetInSec?: number } }
@ -21,6 +22,9 @@ export type Action =
// PEP-241 (codex 0.171): «Folder access — Trust this folder?» about `path` (default: the cwd) — waits
// for a key, logs `trust` with it; «2» (back) ends the run
| { trust: true | { path?: string } }
// PEP-227/303 (claude): «Fable 5.2 now uses usage credits» with numbered choices — waits for a key, logs
// `credits` with it; `switch: false` — no «Switch to Opus…» choice
| { credits: true | { switch?: boolean } }
// PEP-205 (codex): the CLI cannot sign in — «account/read failed … timed out», exit 1
| { loginFail: true }
| { warn: number } // usage warning banner: "You've used N% of your weekly limit"

View File

@ -110,11 +110,12 @@ describe("Диалог кредитов модели не держит аген
});
test("Есть пункт перехода на Opus", async () => {
const p = await storyAtWork({ turns: [[{ say: DIALOG }]] });
const p = await storyAtWork({ turns: [[{ credits: true }]] });
const sid = await p.start();
await p.waitLog("turn 0", (e) => e.ev === "prompt");
await p.waitLog("dialog", (e) => e.ev === "dialog");
const [ev] = await waitFor("dismissed", async () => (await tickAt(new Date()), (await eventsOf(sid, "model_dialog_dismissed")).length ? await eventsOf(sid, "model_dialog_dismissed") : null));
assert.equal((ev!.payload as any).choice, "2");
assert.equal((await p.waitLog("key", (e) => e.ev === "credits")).key, "2");
await tickAt(new Date());
assert.equal((await eventsOf(sid, "model_dialog_dismissed")).length, 1, "not pressed again at once");
await runner.stopSession(db, sid);
@ -122,9 +123,9 @@ describe("Диалог кредитов модели не держит аген
test("Пункта нет", async () => {
const sent = await superadmin();
const p = await storyAtWork({ turns: [[{ say: "Fable 5.2 now uses usage credits\n 1. Continue\n 2. Exit" }]] });
const p = await storyAtWork({ turns: [[{ credits: { switch: false } }]] });
const sid = await p.start();
await p.waitLog("turn 0", (e) => e.ev === "prompt");
await p.waitLog("dialog", (e) => e.ev === "dialog");
const text = await waitFor("superadmin told", async () => (await tickAt(new Date()), (await sent())[0]));
assert.match(text, /просит отдельные кредиты/);
await tickAt(new Date());

View File

@ -0,0 +1,173 @@
// PEP-303: the watchdog's screen guards react to what the agent CLI itself prints, not to the same
// phrases quoted by the agent's tools — FORGE agents edit FORGE's code, where these phrases stand.
import assert from "node:assert/strict";
import { after, before, describe, test } from "node:test";
import { and, eq } from "drizzle-orm";
process.env.PEPPA_SECRET ??= "mock-secret-for-tests";
import { core, db, project, runner, setDefaultOwner, superadmin, teardown, waitFor } from "./helpers.ts";
const { events } = await import("@peppa/db");
const { claudeCreditsDialog } = await import("../../runner/src/claude-screen.ts");
const { codexModelMenu, codexTrustPrompt } = await import("../../runner/src/codex-screen.ts");
const { startQuestion } = await import("../../runner/src/start-screen.ts");
const { isQuotedLine } = await import("../../runner/src/screen-lines.ts");
type User = Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
let pm: User;
before(async () => {
pm = await core.upsertUserFromGitea(db, { id: 303, login: "mock-pm-303" }, { access_token: "x" });
setDefaultOwner(pm.id);
});
after(teardown);
const sess = (id: number) => core.getSession(db, id);
const tickAt = (now: Date) => runner.tick(db, { intervalMs: 0, stallMs: 3_600_000, now });
const eventsOf = async (sid: number, type: string) => db.select().from(events).where(and(eq(events.sessionId, sid), eq(events.type, type)));
const atWork = async (p: { taskKey: string }) => core.updateTask(db, await core.resolveTask(db, p.taskKey), { status: "in_progress" });
/** 26.11, 12:57: the agent of PEP-268 edits watchdog.ts and greps the docs — the phrase is in its tool output. */
const EDIT_AND_GREP = [
"Update(packages/runner/src/watchdog.ts)",
" ⎿ Updated packages/runner/src/watchdog.ts with 2 additions",
" 331 + // PEP-227: Claude's «<model> now uses usage credits» dialog waits for a choice",
" 332 + // 1. Switch to Opus 5.5",
"⏺ Bash(grep -rn \"now uses usage credits\" docs)",
" ⎿ docs/a.md:3:Fable 5.2 now uses usage credits",
" docs/a.md:4:1. Switch to Opus 5.5",
" 1. Switch to Opus 5.5",
].join("\n");
/** 26.11, 22:25: the agent of PEP-268 looks at a diff of the mock — a limit line of code with its number. */
const LIMIT_IN_DIFF = [
"• Edited packages/testkit/src/mock-agent.ts (+1 -1)",
" 446 } else {",
" 447 + out(`■ You’ve hit your usage limit.${spec.reset === \"unknown\" ? \"\" : ` Try again at 8:47 PM.`}\\n`);",
" 448 - out(`■ You’ve hit your usage limit.`);",
"packages/testkit/src/mock-agent.ts:411: if (spec.afterLimit) out(\"■ You’ve hit your usage limit. Try again at 8:47 PM.\")",
" // PEP-205: Codex prints «You’ve hit your usage limit … try again at 8:47 PM».",
].join("\n");
describe("Разбор экрана: строки CLI и цитаты", () => {
test("Строки diff, grep и cat -n — цитаты; варианты и плашки — нет", () => {
for (const l of [" 331 + // now uses usage credits", "447 +code", " 448 - old", " 12 context", "docs/a.md:4:1. Switch to Opus 5.5", " ⎿ docs/a.md:3:x", "+ added", "@@ -1,3 +1,4 @@", "12:text"]) assert.ok(isQuotedLine(l), l);
for (const l of ["❯ 1. Use usage credits", " 2. Switch to Opus 5.5", "■ You’ve hit your usage limit.", "5-hour limit reached ∙ resets 3am", "Fable 5.2 now uses usage credits"]) assert.equal(isQuotedLine(l), false, l);
});
test("Фраза кредитов и «1. Switch to Opus» в diff и выводе grep — не диалог", () => {
assert.equal(claudeCreditsDialog(EDIT_AND_GREP), null);
assert.equal(claudeCreditsDialog(`${EDIT_AND_GREP}\n\n✻ Working… (12s · esc to interrupt)\n`), null);
assert.equal(claudeCreditsDialog(`${EDIT_AND_GREP}\n\n> \n`), null);
// The agent's answer that names the dialog is not the dialog either.
assert.equal(claudeCreditsDialog("⏺ Сторож ловит «Fable 5.2 now uses usage credits» и жмёт:\n 1. Switch to Opus 5.5\n 2. Exit\n\n> "), null);
assert.equal(startQuestion("claude", EDIT_AND_GREP), null);
});
test("Настоящий диалог узнаётся как раньше, в рамке тоже", () => {
const dialog = "Fable 5.2 now uses usage credits\n\n❯ 1. Use usage credits\n 2. Switch to Opus 5.5\n 3. Exit";
assert.deepEqual(claudeCreditsDialog(`${EDIT_AND_GREP}\n\n${dialog}\n\n Enter to confirm · Esc to cancel\n\n\n`), { digit: "2" });
const boxed = ["╭──────────────────────────────────────╮", "│ Fable 5.2 now uses usage credits │", "│ │", "│ ❯ 1. Use usage credits │", "│ 2. Switch to Opus 5.5 │", "│ 3. Exit │", "╰──────────────────────────────────────╯", " Enter to confirm · Esc to cancel"].join("\n");
assert.deepEqual(claudeCreditsDialog(boxed), { digit: "2" });
assert.deepEqual(claudeCreditsDialog("Fable 5.2 now uses usage credits\n 1. Continue\n 2. Exit"), { digit: null });
assert.equal(startQuestion("claude", dialog), "model");
});
test("Меню модели и доверие папке Codex в diff — не вопрос", () => {
const menu = " Switch to gpt-6-luna for lower credit usage?\n› 1. Switch to gpt-6-luna\n 2. Keep current model\n 3. Keep current model (never show again)\n\n enter select · esc back";
const quoted = menu.split("\n").map((l, i) => ` ${410 + i} +${l}`).join("\n");
assert.equal(codexModelMenu(quoted), null);
assert.equal(codexModelMenu(menu), "2", "the real menu");
const trust = " Trust this folder?\n /w/s1\n\n› 1. Trust and continue\n 2. Back\n\n enter select · esc back";
assert.equal(codexTrustPrompt(trust.split("\n").map((l, i) => `src/mock-agent.ts:${420 + i}:${l}`).join("\n")), null);
assert.equal(codexTrustPrompt(trust)?.digit, "1", "the real question");
assert.equal(startQuestion("codex", quoted), null);
});
test("Строка лимита в diff, grep и коде — не плашка; настоящие плашки — плашки", () => {
assert.deepEqual(runner.limitLines(LIMIT_IN_DIFF), []);
assert.equal(runner.freshLimitLine(LIMIT_IN_DIFF, 0), null);
for (const banner of [
"■ You’ve hit your usage limit. Upgrade to Pro (https://chatgpt.com/explore/pro) or try again at 8:47 PM.",
"⎿ Claude usage limit reached. Your limit will reset at 9pm.",
" ⎿ API Error: Claude usage limit reached. Your limit will reset at 9pm.",
"⏺ Usage limit reached · resets 9pm",
"Claude AI usage limit reached|1700000000",
"5-hour limit reached ∙ resets 3am",
]) assert.deepEqual(runner.limitLines(`${LIMIT_IN_DIFF}\n${banner}\n Approaching rate limits`), [banner.trim()], banner);
assert.equal(runner.usageWarning(" 90 + out(\"You've used 95% of your weekly limit\")"), false);
});
});
describe("Вачдог не трогает работающего агента из-за текста в его выводе", () => {
test("Claude: фраза кредитов в diff и grep — ни сообщения, ни нажатия", async () => {
const sent = await superadmin();
const p = await project({ turns: [[{ say: EDIT_AND_GREP }]] });
await atWork(p);
const sid = await p.start();
await p.waitLog("turn 0", (e) => e.ev === "turn_end");
for (let i = 0; i < 3; i++) await tickAt(new Date());
assert.equal((await eventsOf(sid, "model_dialog_dismissed")).length, 0, "no key pressed");
assert.deepEqual((await sent()).filter((t) => /кредит/.test(t)), [], "no alert");
await runner.stopSession(db, sid);
});
test("Claude: настоящий диалог — «Switch to Opus» нажат", async () => {
const p = await project({ turns: [[{ credits: true }, { say: "Продолжаю на Opus." }]] });
await atWork(p);
const sid = await p.start();
await p.waitLog("dialog", (e) => e.ev === "dialog");
const key = await waitFor("dialog answered", async () => (await tickAt(new Date()), p.log().find((e) => e.ev === "credits")));
assert.equal(key.key, "2");
assert.equal((await eventsOf(sid, "model_dialog_dismissed")).length, 1);
await runner.stopSession(db, sid);
});
test("Codex: строка лимита в diff — нет usage_limit, подписка не помечена, агент работает", async () => {
const sub = await runner.addSubscription(db, { provider: "codex", name: "Codex 303", method: "api_key", secret: "mock-openai-key-303", createdBy: pm.id });
const pool = await core.createPool(db, { name: "Пул 303", subscriptionIds: [sub.id] });
const p = await project({ turns: [[{ say: LIMIT_IN_DIFF }]] });
await core.setProjectPool(db, (await core.getProject(db, p.key)).id, pool.id);
await atWork(p);
const sid = await p.start({ provider: "codex" });
await p.waitLog("turn 0", (e) => e.ev === "turn_end");
for (let i = 0; i < 3; i++) await tickAt(new Date());
assert.equal((await eventsOf(sid, "usage_limit")).length, 0, "no limit event");
const s = await sess(sid);
assert.notEqual(s.status, "rate_limited");
assert.equal(s.subscriptionId, sub.id, "not moved to another subscription");
assert.equal((await core.getSubscription(db, sub.id)).status, "active", "the subscription is not marked limited");
assert.equal((await eventsOf(sid, "exited")).length, 0, "the agent was not stopped");
await runner.stopSession(db, sid);
});
test("Codex: настоящая плашка в живом окне — лимит", async () => {
const p = await project({ turns: [[{ say: LIMIT_IN_DIFF }, { limit: { resetInSec: 600 } }]] });
await atWork(p);
const sid = await p.start({ provider: "codex" });
await waitFor("rate limited", async () => (await tickAt(new Date()), (await sess(sid)).status === "rate_limited"));
const [ev] = await eventsOf(sid, "usage_limit");
assert.match((ev!.payload as any).line, /^■ You’ve hit your usage limit\. Try again at/);
await runner.stopSession(db, sid);
});
test("Codex: настоящая плашка в мёртвом окне — лимит, а не падение", async () => {
const p = await project({ turns: [[{ say: LIMIT_IN_DIFF }, { limit: { resetInSec: 600, exit: 1 } }]] });
await atWork(p);
const sid = await p.start({ provider: "codex" });
await p.waitLog("exited", (e) => e.ev === "exit");
const [ev] = await waitFor("limit seen", async () => (await tickAt(new Date()), (await eventsOf(sid, "usage_limit")).length ? await eventsOf(sid, "usage_limit") : null));
assert.equal((ev!.payload as any).exited, true);
assert.match((ev!.payload as any).line, /^■ You’ve hit your usage limit\. Try again at/);
assert.deepEqual((await sess(sid)).watchState?.restarts ?? [], [], "not a crash");
await runner.stopSession(db, sid);
});
test("Codex: строка лимита в diff в мёртвом окне — обычное падение", async () => {
const p = await project({ turns: [[{ say: LIMIT_IN_DIFF }, { crash: 1 }]] });
await atWork(p);
const sid = await p.start({ provider: "codex" });
await p.waitLog("exited", (e) => e.ev === "exit");
await waitFor("exit seen", async () => (await tickAt(new Date()), (await eventsOf(sid, "exited")).length));
assert.equal((await eventsOf(sid, "usage_limit")).length, 0);
await runner.stopSession(db, sid);
});
});