PEP-241: Codex на ChatGPT начинает работу — доверие папке и модель только своему CLI

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
peppa-bot 2026-11-23 06:07:03 +00:00
parent 8ba72b0263
commit 09ac951d4d
19 changed files with 413 additions and 6 deletions

View File

@ -20,6 +20,7 @@
- Новая фраза Claude о лимите — в `parseResetTime` и таблицу limits.test.ts, иначе подписка зря считается свободной. Codex 0.169 без `--full-auto`: режим — `CODEX_DEFAULT_MODE` (providers.ts), срочно — `PEPPA_CODEX_MODE` в .env.
- Скорость: `apps/web/scripts/bench-pages.ts`, канал — `bench-live.ts` (копию базы сначала `peppa db migrate`: индексы PEP-214); N+1 — `workLineIndex`. `liveHub` на globalThis переживает HMR: правишь live.ts — перезапусти server.ts. Не `pkill -f next-server`.
- observe.db: схема — `MIGRATIONS` по `user_version` (core/observe.ts); напоминания (PEP-223) — `remindIncidents`; в тестах «бот днём» помечай outbox `sent`, иначе напоминание заменит прежнее.
- Скорость: замер `apps/web/scripts/bench-pages.ts`, канал — `bench-live.ts` (копию базы сначала `peppa db migrate`); N+1 по проектам — `workLineIndex`. `liveHub` на globalThis переживает HMR — после правок live.ts перезапусти server.ts. Не `pkill -f next-server` — убьёт живой веб.
- Хук грузит только лёгкий `runner/limit-delay.ts`, не flow.ts. В тесте хука PEPPA_GENERATION = поколение сессии (вставленной руками — 0).
- Память ветки при мерже main склеивается построчно и разрастается дублями — после конфликта в `.peppa/memory.md` убери повторы (тест project-memory-size.test.ts).
- SSRF-проверка в `lookup` — только с `agent: false` (keep-alive Node пропускает lookup, PEP-234).
@ -30,6 +31,9 @@
- Агент в контейнере не видит хост сервера, Mac и Cloudflare (PEP-231): инфраструктуру — скриптом в `scripts/server-move/` + шаги в docs/SERVER.md, выполнить просить суперадмина через `report_blocker`.
- Сервер (PEP-230): памятка — docs/SERVER.md. В контейнере агента нет глобального git: автор коммита — `gitRelayEnv` (GIT_AUTHOR_*); на старом образе — `git -c user.name=peppa-bot -c user.email=peppa-bot@telecom.quest commit`.
- Песочница раннера: нет tmux, openspec, Node 26 (есть 22). tmux — `.deb` с deb.debian.org (tmux_3.3a-3, libevent-core-2.1-7, libutempter0) → `dpkg-deb -x` + LD_LIBRARY_PATH; openspec — `npm i -g --prefix /tmp/os @fission-ai/openspec`; e2e на 22 — MIN_MAJOR в scripts/lib/require-node.mjs (не коммитить).
- Сервер (PEP-230): docs/SERVER.md. Нет глобального git в контейнере: автор — `gitRelayEnv`; иначе `git -c user.name=peppa-bot -c user.email=peppa-bot@telecom.quest commit`.
- Песочница раннера: нет tmux, openspec, Node 26 (есть 22). tmux — .deb с deb.debian.org (tmux_3.3a-3, libevent-core-2.1-7, libutempter0) → `dpkg-deb -x` + обёртка с LD_LIBRARY_PATH; openspec — `npm i -g --prefix /tmp/os @fission-ai/openspec`; тесты на 22 — MIN_MAJOR в scripts/lib/require-node.mjs (не коммитить).
- Codex (PEP-241): доверие папке — по корню основного репо worktree; `-c` режет ключ по точкам — пишем в config.toml CODEX_HOME (`codex-trust.ts`).
## Соглашения
- Специалисты (PEP-183): агент с непустым character — специалист; подбор — `runner/team-match.ts` (haiku, `PEPPA_TEAM_BIN`), результат `team.match:<taskId>`, порог ожидания `platform.team.waitMin`; в `ensureSessionAgent` порядок: прежний → свободный специалист по профилю → универсал → специалист без очереди.

View File

@ -0,0 +1,27 @@
# Design
## Доверие папке
Codex (`resolve_root_git_project_for_trust`) для worktree берёт корень основного репозитория:
`.git` worktree — файл `gitdir: <common>/worktrees/<name>`, в нём `commondir` → общий `.git`,
его родитель — корень. `codexTrustRoots(cwd)` возвращает `[cwd, корень]` без повторов; команда
получает `-c projects."<путь>".trust_level="trusted"` для каждого.
`-c` в Codex делит ключ по точкам без учёта кавычек, поэтому для путей с точкой (`~/.peppa/…`)
он не срабатывает. Надёжный путь — `config.toml` в CODEX_HOME подписки (он смонтирован в
контейнер по тому же пути): `trustCodexFolders(home, paths)` дописывает
`[projects."<путь>"]\ntrust_level = "trusted"`, если такого пути в файле ещё нет (не
переписываем чужие таблицы — дубль таблицы ломает разбор TOML). Только локально (не на
отдельном хосте) и только при CODEX_HOME подписки.
## Сторож
`codexTrustPrompt(screen)` — цифра пункта «Trust and continue» / «Yes, continue» при вопросе
«Trust this folder?» / «Do you trust the contents of this directory?», и абсолютные пути на
экране. Нажимаем, если путей нет или каждый — из разрешённых (`codexTrustRoots` рабочей
папки сессии и папки проекта). Иначе — не жмём (чужая папка). Событие `trust_dismissed`;
повтор — не чаще раза в 2 минуты (общий `menuAt`).
## Модель
`modelProvider(name)`: Claude-алиасы → claude, gpt/o\d/codex → codex, с «/» → opencode, иное — null.
Без `provider` в настройках модель идёт провайдеру `modelProvider(m) ?? "claude"`. Явный
`provider` — как раньше (только ему). Усилия (effort) общие — как раньше.
Альтернатива «только claude» сломала бы проекты, где без провайдера записана модель Codex.

View File

@ -0,0 +1,24 @@
# PEP-241: агенты на ChatGPT начинают работу
## Why
На сервере (Codex 0.171, контейнеры) агент на Codex не делает ни шага (QLFW-84, TPTIP-85):
1. Codex показывает экран «Folder access — Trust this folder?» и ждёт нажатия. Доверие через
`-c projects."<cwd>".trust_level` не помогает: для worktree Codex ищет доверие по корню
основного репозитория, а ключ `-c` с точкой в пути он режет по точкам. Сторож экрана такой
экран не знает — агент стоит, перезапуск даёт тот же экран.
2. `platform.agent = {model: "opus"}` без провайдера: `launchModelFor` отдавала модель любому
провайдеру, Codex получал `--model opus` и отклонял первое сообщение.
## What Changes
- Запуск Codex доверяет и рабочей папке, и корню основного репозитория worktree (`-c` и запись
в `config.toml` CODEX_HOME подписки).
- Сторож Codex узнаёт экран доверия (старый и 0.171) и жмёт «Trust and continue», только если
папка на экране — та, что Peppa дала агенту.
- Модель без провайдера идёт только «своему» провайдеру: по виду имени (opus/sonnet/haiku/claude-* —
Claude, gpt-*/o<N>/codex-* — Codex, `x/y` — OpenCode), непонятное — Claude (провайдер по
умолчанию). То же для `escalateModel`. Codex без своей модели — на модели по умолчанию.
- mock-codex: действие `trust` (экран 0.171) и отказ на модель Claude.
## Impact
- `packages/core/src/agent-model.ts`, `packages/runner/src/{providers,codex-screen,watchdog,sessions}.ts`
- testkit: `mock-agent.ts`, `scenario.ts`, тесты `codex-recovery`, `agent-smarts`.

View File

@ -0,0 +1,17 @@
## ADDED Requirements
### Requirement: Модель без провайдера — только своему CLI
Если в настройках агента провайдер не задан, модель (и `escalateModel`) SHALL передаваться
только провайдеру, которому она принадлежит по имени (opus/sonnet/haiku/claude-* — Claude,
gpt-*/o<N>/codex-* — Codex); имя без признаков — провайдеру по умолчанию Claude. Остальные
провайдеры запускаются на своей модели по умолчанию.
#### Scenario: Платформа указала opus, агент на ChatGPT
- **GIVEN** `platform.agent = {model: "opus"}` без провайдера
- **WHEN** агент запускается на Codex
- **THEN** команда Codex без `--model`
#### Scenario: Та же настройка, агент на Claude
- **GIVEN** `platform.agent = {model: "opus"}` без провайдера
- **WHEN** агент запускается на Claude
- **THEN** команда Claude содержит `--model opus`

View File

@ -0,0 +1,23 @@
## ADDED Requirements
### Requirement: Экран доверия папке не останавливает агента
Peppa SHALL запускать Codex с доверием к рабочей папке и к корню основного репозитория worktree
(и в команде, и в `config.toml` CODEX_HOME подписки). Если экран «Trust this folder?» всё же
появился, сторож SHALL выбрать «Trust and continue» — только когда папка на экране та, что
Peppa дала агенту.
#### Scenario: Экран доверия Codex 0.171
- **GIVEN** агент на Codex, на экране «Folder access — Trust this folder?» с рабочей папкой агента
- **WHEN** сторож делает проход
- **THEN** выбран пункт «Trust and continue», в журнале `trust_dismissed`
- **AND** агент выполняет первый ход
#### Scenario: Чужая папка на экране
- **GIVEN** на экране вопрос о доверии папке `/etc`
- **WHEN** сторож делает проход
- **THEN** ничего не нажато
#### Scenario: Worktree
- **GIVEN** рабочая папка — worktree репозитория `/w/repo`
- **WHEN** запускается агент на Codex
- **THEN** команда доверяет и папке worktree, и `/w/repo`

View File

@ -0,0 +1,12 @@
## 1. Модель
- [x] 1.1 `modelProvider` и `launchModelFor`: модель без провайдера — только своему провайдеру (и `escalateModel`)
- [x] 1.2 Тест в agent-smarts: `{model: opus}` без провайдера — Codex без `--model`, Claude с `--model opus`
## 2. Доверие папке
- [x] 2.1 `codexTrustRoots` + `-c` для каждого пути в `codexCommand`
- [x] 2.2 `trustCodexFolders` в CODEX_HOME подписки при запуске
- [x] 2.3 `codexTrustPrompt`/`dismissCodexTrust` и вызов в сторожe
- [x] 2.4 mock-codex: действие `trust`, отказ на модель Claude; тесты в codex-recovery
## 3. Завершение
- [x] 3.1 typecheck, lint, тесты; память; archive; PR

View File

@ -40,3 +40,19 @@
- **GIVEN** в пуле проекта подписка Claude «лимит до 18:00» и активная Codex, `fallbackProvider: codex`
- **WHEN** PM двигает стори в работу
- **THEN** раннер стартует на Codex, в журнале `provider_fallback`
### Requirement: Модель без провайдера — только своему CLI
Если в настройках агента провайдер не задан, модель (и `escalateModel`) SHALL передаваться
только провайдеру, которому она принадлежит по имени (opus/sonnet/haiku/claude-* — Claude,
gpt-*/o<N>/codex-* — Codex); имя без признаков — провайдеру по умолчанию Claude. Остальные
провайдеры запускаются на своей модели по умолчанию.
#### Scenario: Платформа указала opus, агент на ChatGPT
- **GIVEN** `platform.agent = {model: "opus"}` без провайдера
- **WHEN** агент запускается на Codex
- **THEN** команда Codex без `--model`
#### Scenario: Та же настройка, агент на Claude
- **GIVEN** `platform.agent = {model: "opus"}` без провайдера
- **WHEN** агент запускается на Claude
- **THEN** команда Claude содержит `--model opus`

View File

@ -48,3 +48,25 @@ Codex SHALL запускаться с `notice.hide_rate_limit_model_nudge=true`;
- **GIVEN** вход в аккаунт падает при каждом запуске
- **WHEN** проходят три повтора и четвёртый запуск
- **THEN** подписка в статусе `auth_error`, суперадмину одно сообщение, автоперезапуски не потрачены
### Requirement: Экран доверия папке не останавливает агента
Peppa SHALL запускать Codex с доверием к рабочей папке и к корню основного репозитория worktree
(и в команде, и в `config.toml` CODEX_HOME подписки). Если экран «Trust this folder?» всё же
появился, сторож SHALL выбрать «Trust and continue» — только когда папка на экране та, что
Peppa дала агенту.
#### Scenario: Экран доверия Codex 0.171
- **GIVEN** агент на Codex, на экране «Folder access — Trust this folder?» с рабочей папкой агента
- **WHEN** сторож делает проход
- **THEN** выбран пункт «Trust and continue», в журнале `trust_dismissed`
- **AND** агент выполняет первый ход
#### Scenario: Чужая папка на экране
- **GIVEN** на экране вопрос о доверии папке `/etc`
- **WHEN** сторож делает проход
- **THEN** ничего не нажато
#### Scenario: Worktree
- **GIVEN** рабочая папка — worktree репозитория `/w/repo`
- **WHEN** запускается агент на Codex
- **THEN** команда доверяет и папке worktree, и `/w/repo`

View File

@ -180,14 +180,37 @@ export interface LaunchModel {
escalated: boolean;
}
/**
* PEP-241: the CLI a model name belongs to — Claude aliases and `claude-*`, OpenAI `gpt-*`/`o<N>`/`codex-*`,
* OpenCode `provider/model`; null when the name says nothing.
*/
export function modelProvider(model: string): AgentProvider | null {
const m = model.trim().toLowerCase();
if (/^(opus|sonnet|haiku|opusplan|claude)([-\[.:]|$)/.test(m)) return "claude";
if (/^(gpt|codex)([-.]|$)|^o\d/.test(m)) return "codex";
if (m.includes("/")) return "opencode";
return null;
}
/**
* Does `model` go to `provider`? With the provider set in the settings — only to it; without one
* (PEP-241) — only to the CLI the name belongs to, an unknown name to the default one (Claude):
* `-m opus` makes Codex on a ChatGPT account refuse every message.
*/
function modelFits(model: string | null, provider: AgentProvider, configured: AgentProvider | null): boolean {
if (!model) return false;
if (configured) return configured === provider;
return (modelProvider(model) ?? "claude") === provider;
}
/**
* Model and effort for one launch on `provider`: the escalation model once the story is
* escalated; the fallback model on the fallback provider; the model only on its own provider.
*/
export function launchModelFor(s: AgentSettings, provider: AgentProvider, escalated: boolean): LaunchModel {
const own = s.provider == null || s.provider === provider;
if (own && escalated && s.escalateModel) return { model: s.escalateModel, effort: s.escalateEffort ?? s.effort, escalated: true };
if (own) return { model: s.model, effort: s.effort, escalated: false };
if (own && escalated && s.escalateModel && modelFits(s.escalateModel, provider, s.provider)) return { model: s.escalateModel, effort: s.escalateEffort ?? s.effort, escalated: true };
if (own) return { model: modelFits(s.model, provider, s.provider) ? s.model : null, effort: s.effort, escalated: false };
if (s.fallbackProvider === provider) return { model: s.fallbackModel, effort: null, escalated: false };
return { model: null, effort: null, escalated: false };
}

View File

@ -25,3 +25,37 @@ export async function dismissCodexMenu(pane: tmux.Pane, screen: string): Promise
/** The CLI could not read the account at start: a network hiccup on the way to the provider, not the agent's failure. */
export const CODEX_LOGIN_FAIL_RE = /account\/read failed|workspace routing discovery timed out/i;
/** PEP-241: «Trust this folder?» (0.169 «Do you trust the contents of this directory?», 0.171 «Folder access»). */
const TRUST_QUESTION_RE = /Trust this folder\?|Do you trust the contents of this directory\?/i;
const TRUST_YES_RE = /^\s*(?:›\s*)?(\d)\.\s*(?:Trust and continue|Yes, continue)\b/im;
export interface CodexTrustPrompt {
digit: string;
/** Absolute paths shown on the screen (the folder Codex asks about). */
paths: string[];
}
/** 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");
if (!TRUST_QUESTION_RE.test(tail)) return null;
const digit = TRUST_YES_RE.exec(tail)?.[1];
if (!digit) return null;
const paths = [...tail.matchAll(/(?:^|[\s(«"'`])(\/[^\s)»"'`]+)/g)].map((m) => m[1]!.replace(/[.,:;]+$/, "").replace(/(.)\/+$/, "$1"));
return { digit, paths: [...new Set(paths)] };
}
/**
* Answers «Trust and continue» — only for the folder Peppa gave the agent: every path on the screen
* must be one of `allowed` (a screen without a path is about the folder Codex was started in, `--cd`).
* Returns "sent", "foreign" (a folder that is not ours — nothing pressed) or null (no such screen).
*/
export async function dismissCodexTrust(pane: tmux.Pane, screen: string, allowed: string[]): Promise<"sent" | "foreign" | null> {
const prompt = codexTrustPrompt(screen);
if (!prompt) return null;
const ok = new Set(allowed.map((p) => p.replace(/(.)\/+$/, "$1")));
if (prompt.paths.some((p) => !ok.has(p))) return "foreign";
await tmux.sendKeys(pane, prompt.digit);
return "sent";
}

View File

@ -0,0 +1,48 @@
// PEP-241: Codex asks «Trust this folder?» for a folder it does not know and waits for a key. It looks
// the trust up by the git project root — for a worktree that is the root of the main repository, not
// the worktree folder. And its `-c a.b.c=…` override splits the key on every dot, quoted or not, so a
// path with a dot (`~/.peppa/…`) never matches through `-c`: the subscription's config.toml does.
import { appendFileSync, existsSync, readFileSync, statSync } from "node:fs";
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
/** The folders Codex may ask about for `cwd`: the folder itself and, for a worktree, the main repository's root. */
export function codexTrustRoots(cwd: string): string[] {
const roots = [cwd];
try {
const dotGit = join(cwd, ".git");
if (existsSync(dotGit) && statSync(dotGit).isFile()) {
const m = /^gitdir:\s*(.+)$/m.exec(readFileSync(dotGit, "utf8"));
if (m) {
const gitdir = resolve(cwd, m[1]!.trim());
const commonFile = join(gitdir, "commondir");
const common = existsSync(commonFile) ? resolve(gitdir, readFileSync(commonFile, "utf8").trim()) : resolve(gitdir, "../..");
const root = basename(common) === ".git" ? dirname(common) : common;
if (!roots.includes(root)) roots.push(root);
}
}
} catch {
/* not a git folder — the folder itself is enough */
}
return roots;
}
/**
* Marks the folders trusted in `<codexHome>/config.toml`. A folder already named in the file is left
* alone: a second `[projects."…"]` table would make the whole config unreadable for Codex.
*/
export function trustCodexFolders(codexHome: string, folders: string[]): string[] {
const file = join(codexHome, "config.toml");
const text = existsSync(file) ? readFileSync(file, "utf8") : "";
const added: string[] = [];
for (const f of folders) {
if (!isAbsolute(f)) continue;
const key = JSON.stringify(f);
if (text.includes(key)) continue;
added.push(f);
}
if (added.length) {
const block = added.map((f) => `[projects.${JSON.stringify(f)}]\ntrust_level = "trusted"\n`).join("\n");
appendFileSync(file, `${text && !text.endsWith("\n") ? "\n" : ""}${text ? "\n" : ""}${block}`, { mode: 0o600 });
}
return added;
}

View File

@ -78,3 +78,5 @@ export * from "./review-wanted.ts";
export * from "./review-wanted-state.ts";
export * from "./delay-actions.ts";
export * from "./edge-dns.ts";
export * from "./codex-trust.ts";
export * from "./codex-screen.ts";

View File

@ -3,6 +3,7 @@ import { basename, dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import type { Session } from "@peppa/core";
import { peppaRoot } from "@peppa/shared";
import { codexTrustRoots } from "./codex-trust.ts";
import { runDir, writeRunRules, writeRunSettings } from "./run-settings.ts";
/** PEP-17: inside the runner container the launch dir is mounted here (see sandbox.ts). */
@ -96,8 +97,8 @@ function codexCommand(c: LaunchContext): string[] {
c.cwd,
...codexModeArgs(c.permissionMode, process.env.PEPPA_CODEX_MODE),
// PEP-188: Codex 0.169 asks «Trust this folder?» on a first run and waits for a key.
"-c",
`projects.${toml(c.cwd)}.trust_level="trusted"`,
// PEP-241: for a worktree it asks about the main repository's root — trust both.
...codexTrustRoots(c.cwd).flatMap((dir) => ["-c", `projects.${toml(dir)}.trust_level="trusted"`]),
// PEP-205: near the limit Codex asks «Switch to <model>?» and waits for a key — never show it.
"-c",
"notice.hide_rate_limit_model_nudge=true",

View File

@ -48,6 +48,7 @@ import { loadEnv } from "@peppa/shared";
import { trustWorkspace } from "./claude-config.ts";
import { buildCommand, providerEnv, type Provider } from "./providers.ts";
import { subscriptionEnv } from "./subscriptions.ts";
import { codexTrustRoots, trustCodexFolders } from "./codex-trust.ts";
import { runDir } from "./run-settings.ts";
import * as tmux from "./tmux.ts";
import { onReleaseAnswer } from "./deploy.ts";
@ -402,6 +403,18 @@ async function launch(
};
script = `#!/bin/bash\n${preamble}exec ${argv.map(shq).join(" ")}\n`;
}
// PEP-241: Codex trusts folders from its CODEX_HOME config.toml — the `-c` in the command misses
// paths with a dot. Only here: on a host (PEP-40) the subscription's dir is the host's.
if (s.provider === "codex" && !s.host && sub) {
const home = subscriptionEnv(sub).CODEX_HOME;
if (home && existsSync(home)) {
try {
trustCodexFolders(home, codexTrustRoots(cwd));
} catch {
/* the watchdog answers the trust screen */
}
}
}
writeFileSync(launchScript, script);
chmodSync(launchScript, 0o700);
await updateSession(db, s.id, { generation, status: "starting", endedAt: null });

View File

@ -30,7 +30,9 @@ import {
subscriptionWarnTick,
warnLastSubscription,
} from "@peppa/core";
import type { Db } from "@peppa/db";
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, recordLimit } from "./limits.ts";
import { limitDelay, limitOver } from "./limit-delay.ts";
@ -65,7 +67,8 @@ import { productLinkTick } from "./product-link.ts";
import { pickQuestionTick } from "./pick-question.ts";
import { budgetTick } from "./budgets.ts";
import { getWatchdogSettings, idleStopTick, LOST_CONVERSATION_RE, onConversationLost, onLoginFailure, onRunnerCrash, patchWatch, remindTick, restartStalled, restartTick, type WatchdogSettings } from "./recovery.ts";
import { CODEX_LOGIN_FAIL_RE, codexModelMenu, dismissCodexMenu } from "./codex-screen.ts";
import { CODEX_LOGIN_FAIL_RE, codexModelMenu, codexTrustPrompt, dismissCodexMenu, dismissCodexTrust } from "./codex-screen.ts";
import { codexTrustRoots } from "./codex-trust.ts";
import { claudeCreditsDialog, dismissCreditsDialog } from "./claude-screen.ts";
import { serveRunnerCommands, type RunnerService } from "./runner-service.ts";
@ -291,6 +294,15 @@ async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, cfg:
else if (await dismissCodexMenu(tmux.sessionPane(s), screen).catch(() => false)) await logSessionEvent(db, s, "model_menu_dismissed", {});
await patchWatch(db, s, { menuAt: now });
}
// 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)) {
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", {});
else if (res === "foreign") await logSessionEvent(db, s, "trust_foreign", { paths: codexTrustPrompt(screen)?.paths ?? [] });
await patchWatch(db, s, { menuAt: now });
}
// 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") {
@ -469,3 +481,20 @@ async function resumeAfterLimit(db: Db, s: SessionView, now: Date, log: (m: stri
await limitOver(db, s);
log(`#${s.id} ${s.taskKey ?? ""}: limit reset, ${alive ? "nudged" : "relaunched"}`);
}
/** PEP-241: the folders Peppa gave this agent — its worktree, the project's copy and their repository roots. */
async function agentFolders(db: Db, s: SessionView): Promise<string[]> {
const [project] = await db.select({ path: projects.workspacePath }).from(projects).where(eq(projects.id, s.projectId));
const out = new Set<string>();
for (const p of [s.workspacePath, project?.path]) {
if (!p) continue;
out.add(p);
try {
const real = realpathSync(p);
for (const r of codexTrustRoots(real)) out.add(r);
} catch {
/* on a host the folder is not here */
}
}
return [...out];
}

View File

@ -95,6 +95,9 @@ if (provider === "codex" && argv[0] !== "exec" && argv[0] !== "login") {
}
}
const args = parseArgs();
// PEP-241: Codex on a ChatGPT account refuses a Claude model on the first message.
const codexModel = provider === "codex" ? argv.find((a, i) => argv[i - 1] === "--model" || argv[i - 1] === "-m") : undefined;
const codexModelRefused = !!codexModel && /^(opus|sonnet|haiku|claude)/i.test(codexModel);
if (!codexTrusted) {
process.stdout.write("Do you trust the contents of this directory?\n 1. Yes, continue\n 2. No, quit\nTrust this folder? Press enter to continue\n");
await new Promise(() => {});
@ -358,6 +361,16 @@ 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 ("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`);
const key = await dialog();
log("trust", { key });
if (key !== "1") {
log("exit", { code: 0, reason: "trust" });
process.exit(0);
}
mode = "busy";
} else if ("loginFail" in action) {
out("› Error: account/read failed: account/read failed: workspace routing discovery timed out (code -32603)\n");
log("exit", { code: 1, reason: "login" });
@ -486,6 +499,12 @@ async function main() {
let i = 0;
const run = async (prompt: string) => {
if (codexModelRefused) {
out(`■ The ${codexModel} model is not supported when using Codex with a ChatGPT account.\n\n> `);
log("model_refused", { model: codexModel });
mode = "prompt";
return;
}
let next = await turn(prompt, turns[i++]);
while (next) next = await turn(next, turns[i++], true);
};

View File

@ -18,6 +18,9 @@ export type Action =
// PEP-205 (codex): the «Switch to <model>?» menu near the limit — waits for a key (1–3, Esc), logs `menu` with it;
// `afterLimit` prints the limit line above it like the real screen
| { menu: true | { afterLimit?: boolean } }
// 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-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

@ -93,6 +93,31 @@ describe("PEP-41: модель и провайдер стори", () => {
assert.equal(core.launchModelFor({ ...s, fallbackModel: "gpt-5-codex" }, "codex", false).model, "gpt-5-codex");
});
test("PEP-241: модель без провайдера идёт только своему CLI — Codex на ChatGPT не получает opus", async () => {
const free = { ...core.DEFAULT_AGENT_SETTINGS, model: "opus", escalateModel: "opus" };
assert.equal(core.launchModelFor(free, "codex", false).model, null);
assert.equal(core.launchModelFor(free, "codex", true).model, null);
assert.equal(core.launchModelFor(free, "claude", false).model, "opus");
assert.equal(core.launchModelFor(free, "claude", true).model, "opus");
assert.equal(core.launchModelFor({ ...free, model: "gpt-5-codex" }, "codex", false).model, "gpt-5-codex");
assert.equal(core.launchModelFor({ ...free, model: "gpt-5-codex" }, "claude", false).model, null);
assert.equal(core.launchModelFor({ ...free, model: "my-model" }, "codex", false).model, null);
assert.equal(core.launchModelFor({ ...free, provider: "codex", model: "my-model" }, "codex", false).model, "my-model");
await core.setSystemAgentSettings(db, { model: "opus" });
try {
const p = await project({ turns: [[{ say: "ok" }]] });
const sid = await p.start({ provider: "codex" });
const argv = argvOf(await p.waitLog("started", (e) => e.ev === "start"));
assert.equal(flag(argv, "--model"), undefined, argv.join(" "));
await p.waitLog("turn finished", (e) => e.ev === "turn_end");
assert.equal(p.log().some((e) => e.ev === "model_refused"), false);
await runner.stopSession(db, sid);
} finally {
await core.setSystemAgentSettings(db, {});
}
});
test("Codex получает model_reasoning_effort", async () => {
const p = await project({ turns: [[{ say: "ok" }]] });
const proj = await core.getProject(db, p.key);

View File

@ -2,6 +2,11 @@
// make the watchdog think the agent hung or crashed.
import assert from "node:assert/strict";
import { after, before, describe, test } from "node:test";
import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { eq } from "drizzle-orm";
import { schema } from "@peppa/db";
import { core, db, project, runner, setDefaultOwner, superadmin, teardown, waitFor } from "./helpers.ts";
process.env.PEPPA_SECRET = "mock-secret-for-tests";
@ -121,6 +126,66 @@ describe("Меню «Switch to <model>?»", () => {
});
});
describe("PEP-241: экран доверия папке", () => {
test("Экран Codex 0.171 о рабочей папке агента — сторож жмёт «Trust and continue», агент работает", async () => {
const p = await project({ turns: [[{ trust: true }, { say: "Начал работу." }]] });
await atWork(p);
const sid = await p.start({ provider: "codex" });
await waitFor("trust answered", async () => {
await tickAt(new Date());
return p.log().find((e) => e.ev === "trust");
});
assert.equal(p.log().find((e) => e.ev === "trust")!.key, "1");
await p.waitLog("turn finished", (e) => e.ev === "turn_end");
const evs = await db.select().from(schema.events).where(eq(schema.events.sessionId, sid));
assert.ok(evs.some((e) => e.type === "trust_dismissed"));
await runner.stopSession(db, sid);
});
test("Вопрос о чужой папке — сторож ничего не нажимает", async () => {
const p = await project({ turns: [[{ trust: { path: "/etc" } }, { say: "не должно" }]] });
await atWork(p);
const sid = await p.start({ provider: "codex" });
await p.waitLog("trust screen", (e) => e.ev === "dialog");
for (let i = 0; i < 3; i++) await tickAt(new Date(Date.now() + i * 3 * MIN));
assert.equal(p.log().some((e) => e.ev === "trust"), false);
const evs = await db.select().from(schema.events).where(eq(schema.events.sessionId, sid));
assert.ok(evs.some((e) => e.type === "trust_foreign"));
await runner.stopSession(db, sid);
});
test("Экран узнаётся: старый и новый текст, пути на экране", () => {
const { codexTrustPrompt } = runner;
assert.deepEqual(codexTrustPrompt(" Folder access\n\n Trust this folder?\n /w/s1\n\n› 1. Trust and continue\n 2. Back to Agent Command Center\n"), { digit: "1", paths: ["/w/s1"] });
assert.equal(codexTrustPrompt("Do you trust the contents of this directory?\n 1. Yes, continue\n 2. No, quit\n")!.digit, "1");
assert.equal(codexTrustPrompt("• Working on /w/s1"), null);
});
test("Worktree: команда доверяет и папке, и корню основного репозитория; config.toml подписки дописывается один раз", () => {
const base = mkdtempSync(join(tmpdir(), "pep241-"));
const repo = join(base, "repo");
const wt = join(base, ".peppa", "wt");
mkdirSync(join(repo, ".git", "worktrees", "wt"), { recursive: true });
writeFileSync(join(repo, ".git", "worktrees", "wt", "commondir"), "../..\n");
mkdirSync(wt, { recursive: true });
writeFileSync(join(wt, ".git"), `gitdir: ${join(repo, ".git", "worktrees", "wt")}\n`);
assert.deepEqual(runner.codexTrustRoots(wt), [wt, repo]);
const cmd = buildCommand("codex", { sessionId: 1, generation: 1, cwd: wt, prompt: "p", rules: "r" });
assert.ok(cmd.includes(`projects.${JSON.stringify(wt)}.trust_level="trusted"`));
assert.ok(cmd.includes(`projects.${JSON.stringify(repo)}.trust_level="trusted"`));
const home = join(base, "codex");
mkdirSync(home);
writeFileSync(join(home, "config.toml"), 'model = "gpt-5"');
assert.deepEqual(runner.trustCodexFolders(home, [wt, repo]), [wt, repo]);
assert.deepEqual(runner.trustCodexFolders(home, [wt, repo]), []);
const toml = readFileSync(join(home, "config.toml"), "utf8");
assert.match(toml, /^model = "gpt-5"\n/);
assert.equal(toml.split(`[projects.${JSON.stringify(wt)}]`).length, 2);
assert.match(toml, /trust_level = "trusted"/);
});
});
describe("Сбой входа «account/read failed»", () => {
test("Три повтора с растущей паузой без расхода перезапусков; потом подписка помечена, суперадмину одно сообщение", async () => {
const sent = await superadmin();