PEP-3: hooks, statusLine and the permission dialog checked against live Claude Code 2.1.323
- permission dialog menus vary (3-4 items, "2" may be "switch to auto mode"): the late PM answer reads the key off the screen (permissionKey); after "No" Claude interrupts the turn without a Stop hook, so Peppa types PERMISSION_DENIED_NOTE - statusLine total_*_tokens are the last request, not session totals: tokens only from transcript - mcp__peppa allowed in run settings (connected repos have no template .claude/settings.json) - peppa-hook: PEPPA_HOOK_CAPTURE_DIR saves raw payloads; live fixtures in testkit/fixtures/claude-live - mock-claude follows the live contract (menu, interrupt on No, statusLine, transcript blocks, suggestions) - peppa-dev: watchdog (runner service) on the stand, mock PEPPA_SECRET without .env - e2e claude-live.test.ts: fixtures parsing, real peppa-hook on live payloads, terminal fallback keys Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
18eadc4c3a
commit
1e8d9e0327
@ -24,9 +24,10 @@
|
||||
- **Песочница и хосты (PEP-17/40)**: настройки раннеров `isolation` none (по умолчанию, как раньше) / container и `hosts` (id хостов; пусто — Mac Пеппы; хост → всегда контейнер). Все вызовы tmux — по адресу pane `{name, host}` (`tmux.sessionPane(s)`, `runner/exec.ts`: локально или `ssh` ключом `$PEPPA_HOME/ssh/id_ed25519`, ControlMaster; код 255 → `HostUnreachable`, `hasSession` его не глотает — вачдог не объявит раннер пропавшим). Контейнер (`runner/sandbox.ts`): tmux снаружи, `docker run --rm -it --init --name peppa-s<id>` образа `PEPPA_RUNNER_IMAGE` (`infra/runner/Dockerfile`, `scripts/runner-image.sh`), монтируются только рабочая копия (+ `.git` проекта для worktree, `CODEX_HOME` подписки), каталог запуска → `/peppa/run:ro`, свой HOME → `/peppa/home`; env — только сессии/релея/подписки (значения в tmux, в launch.sh только имена); без подписки не стартует; остановка — `killRunner` (tmux + `docker rm -f`). Релей агента (`runner/agent-relay.ts`, веб `/api/agent/[...path]`, токен `agentRelayToken` = HMAC сессии+поколения): `hook` (настоящий `peppa-hook` в Пеппе; ответ ≤25 с, дальше `{wait, rid}`; транскрипт прикладывает шим), `mcp` (`@peppa/mcp/relay`: сервер агента с `lockProject`), `git/…` (прокси в Gitea с токеном бота, только `owner/repo` проекта; в контейнере `GIT_CONFIG_*` insteadOf). Шимы в образе — `infra/runner/peppa-agent.mjs` (`peppa-hook`, `peppa-mcp`). Хосты: таблица `runner_hosts`, `sessions.host_id`/`container` (миграция 0013), `runner/hosts.ts` (`checkHost`, `hostTick` в вачдоге раз в минуту, клон `<workdir>/ws/<slug>/s<id>` одноразовым контейнером через релей, каталог запуска tar по SSH), выбор — `pickHost` (наименее занятый онлайн). Веб `/hosts` (суперадмин), «⋯ Настройки проекта → Раннеры»; CLI `peppa host list|key|add|set|check|disable|enable|rm|push-image`. Моки: `mock-docker run` (исполняет команду образа локально, env только из `-e`, `runs.jsonl`), `mock-ssh` (`MOCK_SSH_ROOT/<host>`, свой tmux, `MOCK_SSH_DOWN`)
|
||||
- хуки не в репо проекта, а в генерируемом `~/.peppa/runs/s<id>-g<gen>/settings.json` (`claude --settings`)
|
||||
- `PEPPA_SESSION_ID` + `PEPPA_GENERATION`: хук из старого поколения (до resume) игнорируется
|
||||
- Диалог разрешений Claude меняется (3–4 пункта, «2» бывает «switch to auto mode»): поздний ответ PM — `permissionKey` читает номер с экрана; после «No» Claude прерывает ход без Stop — Пеппа печатает `PERMISSION_DENIED_NOTE` (PEP-3). `mcp__peppa` разрешён в run-settings
|
||||
- PermissionRequest и AskUserQuestion блокируют и ждут ответ PM из БД (`PEPPA_HOOK_WAIT_SEC`, 540с), потом откат на диалог в терминале; `questions.awaiting_hook` не даёт ответу уйти ещё и в tmux
|
||||
- SessionEnd ≠ смерть процесса (/clear, /resume) — это решает вачдог по tmux pane
|
||||
- Лимит (PEP-56): StopFailure `rate_limit` или баннер → `recordLimit` (runner/limits.ts) сохраняет `resume_at` (время сброса + 60 с) или пробу 30→60→120 мин; вачдог после `resume_at` пишет «Лимит сброшен…» в живой процесс или делает `resumeSession`; не больше 6 в сутки; `PEPPA_LIMIT_AUTORESUME=off` выключает; `tick(db, { now })` для тестов. Реальные строки лимита настоящего Claude ещё не сняты (PEP-3)
|
||||
- Лимит (PEP-56): StopFailure `rate_limit` или баннер → `recordLimit` (runner/limits.ts) сохраняет `resume_at` (время сброса + 60 с) или пробу 30→60→120 мин; вачдог после `resume_at` пишет «Лимит сброшен…» в живой процесс или делает `resumeSession`; не больше 6 в сутки; `PEPPA_LIMIT_AUTORESUME=off` выключает; `tick(db, { now })` для тестов. Реальные строки лимита настоящего Claude ещё не сняты (PEP-3 сверил остальное: хуки, statusLine, transcript, диалог разрешений — `packages/testkit/fixtures/claude-live/`, `claude-live.test.ts`; снять лимит — `PEPPA_HOOK_CAPTURE_DIR=<каталог>` в env раннера, хук кладёт туда сырые payload'ы)
|
||||
- `peppa session resume <id>` → `claude --resume`
|
||||
- агент не может сам поставить `done` или выйти из `awaiting_approval` (guard в MCP)
|
||||
- **Доступ (PEP-16)**: войти могут логины из `platform.allowed_logins` (`peppa platform allowlist/allow/deny`), приглашённые и участники проектов, локальные пользователи (PEP-68), кроме отключённых; проверка в `/auth/callback`, `currentUser` (каждый запрос) и `/mcp`
|
||||
@ -47,7 +48,7 @@
|
||||
- **Доска, зависимости, планировщик, палитра (PEP-34/42/52)**: порядок стори = приоритет — `tasks.position` (REAL, общий для проекта; `reorderTask` в core, `reorderBoardTask` в runner/flow.ts с колонкой; `listTasks` идёт по позиции и без архивных); архив `tasks.archived_at` (`archiveTask` останавливает агента; удаления нет); `epicProgress` — «готово/всего». Зависимости — таблица `task_deps` (core/deps.ts: блокирует, пока предшественник не в review/done и не в архиве; циклы и чужие проекты отклоняются); диспетчер PEP-24 и пуш простоя берут `readyBacklog` (runner/autonomy.ts). Планировщик — runner/planner.ts: `planEpic` (`$PEPPA_PLANNER_BIN -p`, `${PEPPA_PLANNER_MODEL:-sonnet}`, через `claudePrint`) → черновик в `settings` `planner.draft:<epicId>` → `applyPlan`; веб `/p/<KEY>/plan/<epicId>`, мок `mock-planner` (`MOCK_PLANNER_SCENARIO`). Веб-экшены — `app/(app)/board-actions.ts`. MCP PM: `reorder_task`, `archive_task`, `set_dependencies`, `plan_epic`, `apply_plan`, `blocked_by` в create/update_task. Палитра ⌘K — `components/CommandPalette.tsx` (данные `GET /api/palette` → `paletteItems` в core, ранжирование `@peppa/shared/palette` — чистый модуль для браузера), горячие клавиши через `data-hotkey-search|item|answer`, список — `lib/shortcuts.ts` и `/help/shortcuts`
|
||||
- **Агент-ревьюер (PEP-26)**: настройка проекта `review_settings` (вкл/выкл, по умолчанию выкл; `max_iterations` = 2; `rules` PM) — веб «⋯ Настройки проекта → Ревьюер». Агент зовёт MCP `update_task(status: review)`, гейт PEP-57 пройден → `requestReview` (runner/reviewer.ts): ставит `code_reviews` (queued, головной SHA PR) и сразу запускает в процессе MCP, агенту — «закончи ход» (стори остаётся `in_progress`; Stop-хук не подгоняет, пока `pendingReview`). Ревью: дифф `GiteaClient.pullDiff` → `$PEPPA_REVIEW_BIN -p --output-format json --model ${PEPPA_REVIEW_MODEL:-sonnet}` (общий запуск `runner/claude-print.ts`, токен пула проекта, как триаж). `changes` → замечания агенту (`sendToSession` или новый раннер), `ok`/ошибка → стори в `review` и «готово к ревью» с резюме (если ход агента ещё идёт — его шлёт Stop-хук с той же заметкой `reviewNote`). Тот же одобренный SHA не ревьюится повторно; после `max_iterations` возвратов — к PM с последними замечаниями. Зависшие/непринятые — `reviewTick` в вачдоге (раз в минуту). Карточка и `get_task` — последнее ревью. PM, двигающий карточку сам, ревьюера не зовёт. Мок `mock-reviewer` (`MOCK_REVIEW_SCENARIO`)
|
||||
- **CD проектов (PEP-57)**: шаблон — `.gitea/workflows/deploy.yml` + `.gitea/peppa-deploy.sh` + `deploy/compose.yml` (метки Traefik, сеть `traefik_default`) + `deploy/Dockerfile.*`; настройки — `deploy` в `.peppa/project.json`. Образ `peppa/<slug>:<sha>` на docker хоста, `docker compose -p <slug>-<env>`, хосты `<slug>-pr<N>` / `<slug>-staging` / `<slug>-prod` `.telecom.quest` (один уровень: сертификат Cloudflare). Health до 2 мин изнутри сети Traefik, провал → откат на образ, работавший до этого. Шаг шлёт `X-Peppa-Event: deploy` → `recordRelease` (runner/deploy.ts, таблица `releases`, задачи — из сообщений коммитов). Staging здоров → PM вопрос с кнопкой «🚀 Выкатить в прод»; откат/провал → сообщение с причиной и логом. Прод: `deployProd` (веб «Релизы» на странице проекта, Telegram-кнопка через `answerAndDeliver` → `onReleaseAnswer`, MCP `deploy`, CLI `peppa deploy prod`) ставит тег `deploy-prod-<время>` на здоровый staging-коммит (в Gitea 1.22 нет API workflow_dispatch). В тестах docker — `mock-docker` первым в PATH
|
||||
- **Расход, бюджеты, метрики, журнал (PEP-5/43/47/48)**: раннер подключает к Claude `statusLine: peppa-hook statusline` (run-settings) — хук сохраняет стоимость по поколениям и контекст в `sessions.usage` (JSON, миграция 0010) и окна лимитов 5 ч / 7 д аккаунта в `settings` `usage.account:sub:<id>|machine` (троттлинг 20 с); Stop/SessionEnd суммируют токены transcript по разговору (core/usage.ts: `parseStatusLine` терпим к вариантам полей — формат live-CLI не сверен, `transcriptUsage`, `usageTotals`: нет стоимости → оценка по прайсу, «≈»). Веб: `UsageStrip` над каждой страницей (layout), расход на карточке раннера; бот `/status`, MCP `get_usage`. Бюджеты (core/budgets.ts, без миграций): `budget.project:<id>` / `budget.task:<id>` (минуты, токены, перезапуски, $; нет = без предела), `budgetTick` вачдога (runner/budgets.ts) при превышении — Escape в pane (ход прерван, процесс жив), `budget.state:<taskId>`, вопрос PM «Продлить ×2 / Снять лимит / Остановить» (`onBudgetAnswer`), `assertBudgetOpen` в start/resume/moveTask, Stop-хук не подталкивает; карточка стори и «⋯ Настройки проекта → Бюджет стори». Метрики (core/analytics.ts `projectMetrics`, из событий `task_updated`, вопросов, сессий, ревью): вкладка проекта «Метрики», MCP `get_metrics`. Журнал: автор события — колонки `events.actor_kind/actor_user_id/actor_channel/actor_client_id`, контекст `core/actor.ts` (AsyncLocalStorage: веб — `asWebActor(await requireUser())` в теле server action, `/mcp` — пользователь + OAuth-клиент, бот — `enterActor` после `telegramUser`, процессы — `setDefaultActor`: MCP агента, хук, CLI; `tick` вачдога — `runAsActor` system); без контекста: есть сессия — агент, иначе Пеппа; ответы — событие `question_answered` (кроме `system`). `/journal` — суперадмин, вкладка «Журнал» проекта — участники. Новые события пиши через `logSessionEvent` / `logEvent` (core/audit.ts), не прямой вставкой
|
||||
- **Расход, бюджеты, метрики, журнал (PEP-5/43/47/48)**: раннер подключает к Claude `statusLine: peppa-hook statusline` (run-settings) — хук сохраняет стоимость по поколениям и контекст в `sessions.usage` (JSON, миграция 0010) и окна лимитов 5 ч / 7 д аккаунта в `settings` `usage.account:sub:<id>|machine` (троттлинг 20 с); Stop/SessionEnd суммируют токены transcript по разговору (core/usage.ts: `parseStatusLine` сверен с 2.1.323 (PEP-3: `context_window.total_*_tokens` — последний запрос, не сумма; токены только из transcript), `transcriptUsage`, `usageTotals`: нет стоимости → оценка по прайсу, «≈»). Веб: `UsageStrip` над каждой страницей (layout), расход на карточке раннера; бот `/status`, MCP `get_usage`. Бюджеты (core/budgets.ts, без миграций): `budget.project:<id>` / `budget.task:<id>` (минуты, токены, перезапуски, $; нет = без предела), `budgetTick` вачдога (runner/budgets.ts) при превышении — Escape в pane (ход прерван, процесс жив), `budget.state:<taskId>`, вопрос PM «Продлить ×2 / Снять лимит / Остановить» (`onBudgetAnswer`), `assertBudgetOpen` в start/resume/moveTask, Stop-хук не подталкивает; карточка стори и «⋯ Настройки проекта → Бюджет стори». Метрики (core/analytics.ts `projectMetrics`, из событий `task_updated`, вопросов, сессий, ревью): вкладка проекта «Метрики», MCP `get_metrics`. Журнал: автор события — колонки `events.actor_kind/actor_user_id/actor_channel/actor_client_id`, контекст `core/actor.ts` (AsyncLocalStorage: веб — `asWebActor(await requireUser())` в теле server action, `/mcp` — пользователь + OAuth-клиент, бот — `enterActor` после `telegramUser`, процессы — `setDefaultActor`: MCP агента, хук, CLI; `tick` вачдога — `runAsActor` system); без контекста: есть сессия — агент, иначе Пеппа; ответы — событие `question_answered` (кроме `system`). `/journal` — суперадмин, вкладка «Журнал» проекта — участники. Новые события пиши через `logSessionEvent` / `logEvent` (core/audit.ts), не прямой вставкой
|
||||
- **Память проекта (PEP-30)**: `.peppa/memory.md` в репо проекта (разделы Команды/Соглашения/Грабли/Решения), `core/memory.ts` (`rememberFact` — дубли пропускаются, предел `PEPPA_MEMORY_MAX_CHARS` 12 000 → отказ с просьбой ужать; `replaceMemory`; `memoryContext` = файл рабочей копии + 5 последних `done` стори). MCP агента `get_memory`/`remember` (файл рядом с `.peppa/project.json`, коммитит агент в ветке стори). Раннер (`launch` в runner/sessions.ts) дописывает `memoryContext` к общим правилам при каждом запуске/resume. Правило — «Завершение» в `template/RULES.md`; веб — вкладка «Спеки» (`MemorySection`)
|
||||
- **Модель агента (PEP-41)**: `core/agent-model.ts`, наследование `platform.agent` → `project.agent:<id>` → `task.agent:<taskId>` (`settings`): `provider`, `model`, `effort` (Claude `--effort`, Codex `-c model_reasoning_effort`, xhigh/max → high), `escalateModel`/`escalateEffort`/`escalateAfter` (по умолчанию 2; null — выкл), `fallbackProvider`/`fallbackModel`. Модель — только своему провайдеру (`launchModelFor`). Неудачи стори = `ci_attempts` + `reviewRejections`; порог → `agent.escalated:<taskId>` (липко). `startRunner`: провайдер из настроек, нет рабочей подписки → запасной (событие `provider_fallback`); `launch` пишет `model`/`effort` в `started`/`resumed`. `sendWithEscalation` (runner/escalation.ts, из ci-feedback и reviewer; у клиентов PEP-21 — команда сервиса `sendEscalated`): эскалация наступила, а модель живого запуска другая → kill tmux + `resumeSession` с сообщением (событие `model_escalated`). Веб «⋯ Настройки проекта → Модель агента», раздел «Агент» стори (`components/AgentModel.tsx`); MCP PM `agent` в `update_project_settings`/`update_task`; CLI `peppa project agent <KEY|KEY-N|--platform> k=v…`
|
||||
- **Онбординг (PEP-31)**: `core/onboarding.ts` — `onboardingChecklist` (шаги из БД: подписка — только суперадмину, Telegram, eGov — необязательный, проект, стори, сессия стори; скрыт после выполнения или `onboarding.dismissed:<userId>`), `projectAgentWarning` (у пула проекта нет рабочей подписки; без пула — не проверяется). Веб: `components/Onboarding.tsx` на Главной, плашка «Агенты не запустятся» на странице проекта
|
||||
@ -83,7 +84,7 @@
|
||||
- Логи: `~/.peppa/hook.log`, `~/.peppa/watchdog.log`
|
||||
- `pnpm run ci` (`scripts/ci.sh`; не `pnpm ci` — это встроенная чистая переустановка pnpm) — typecheck + `next build` + e2e (у каждого файла тестов свой временный файл SQLite) (PEP-22); `--repeat N` — e2e N раз подряд, `--skip-build`. **CI платформы**: Пеппа на своём же конвейере (PEP-57 этап 4): `.gitea/workflows/ci.yml` на каждый PR и push в main на раннере `peppa-trusted` гоняет проверки из `checks` в `.peppa/project.json` (install, typecheck, build, test) через `.gitea/peppa-check.sh` (симлинк на шаблонный) — статусы `peppa/<проверка>` и отчёты в Пеппу, как у любого проекта: карточка PEP-задачи, гейт ревью, красные проверки — агенту (Postgres хоста `PEPPA_TEST_PG` нужен только тесту переноса в SQLite; без него тест пропускается); мержить только при зелёном. Лог job через API 1.22 не отдаётся — `docker exec gitea cat /data/gitea/actions_log/peppa-bot/peppa/<task%256 в hex>/<task>.log` (task — номер задачи раннера, не run). Раннер недоступен — `scripts/ci.sh --pr <N>` (временный worktree, статус `peppa/ci`)
|
||||
- `pnpm --filter @peppa/testkit test` — e2e CJM на моках (у каждого файла свой временный SQLite-файл, свой tmux `-L`, свой `PEPPA_HOME` — параллельные worktree не мешают друг другу)
|
||||
- **Dev-стенд** (`peppa-dev`, PEP-6) — проверять сценарии с PM самому, без человека и боевых данных: БД `~/.peppa-dev/peppa.db`, tmux `-L peppa-dev`, `~/.peppa-dev`, бот против `mock-telegram` (:3190), агенты — моки. `peppa-dev up` (поднимает и привязывает тестового PM), `peppa-dev peppa <cli…>`, `peppa-dev tg messages|click <msg> <кнопка>|reply <msg> <текст>|send <текст>`, `peppa-dev down`. Живой агент на стенде: `PEPPA_DEV_CLAUDE_BIN=claude peppa-dev up`
|
||||
- **Dev-стенд** (`peppa-dev`, PEP-6) — проверять сценарии с PM самому, без человека и боевых данных: БД `~/.peppa-dev/peppa.db`, tmux `-L peppa-dev`, `~/.peppa-dev`, бот против `mock-telegram` (:3190), агенты — моки. `peppa-dev up` (mock-telegram, бот, вачдог = раннер-сервис; привязывает тестового PM), `peppa-dev peppa <cli…>`, `peppa-dev tg messages|click <msg> <кнопка>|reply <msg> <текст>|send <текст>`, `peppa-dev down`. Живой агент на стенде: `PEPPA_DEV_CLAUDE_BIN=claude peppa-dev up`
|
||||
- Ручной прогон с моком: `PEPPA_CLAUDE_BIN=packages/testkit/bin/mock-claude peppa session start 1`; сценарий в `<workspace>/.peppa/mock-scenario.json`, лог в `.peppa/mock-log.jsonl`; промпт `!{"limit":true}` выполняет действие сразу
|
||||
|
||||
TypeScript запускается прямо из исходников: `node` (Node ≥ 26, встроенное снятие типов; bin-обёртки проверяют версию через `scripts/lib/require-node.mjs`) и Next без сборки. Только стираемый синтаксис (`erasableSyntaxOnly`: без parameter properties, `enum`, `namespace`), импорты типов — `import type`, импорты внутри пакетов — с расширением `.ts`.
|
||||
|
||||
4
apps/web/next-env.d.ts
vendored
4
apps/web/next-env.d.ts
vendored
@ -1,7 +1,7 @@
|
||||
/// <reference types="next" />
|
||||
/// <reference types="next/image-types/global" />
|
||||
import "./.next/dev/types/routes.d.ts";
|
||||
import "./.next/dev/types/root-params.d.ts";
|
||||
import "./.next/types/routes.d.ts";
|
||||
import "./.next/types/root-params.d.ts";
|
||||
|
||||
// NOTE: This file should not be edited
|
||||
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
|
||||
|
||||
@ -0,0 +1,74 @@
|
||||
## Как проверяли
|
||||
|
||||
Dev-стенд (`PEPPA_DEV_CLAUDE_BIN=claude peppa-dev up`), Claude Code **2.1.323**, вход Claude Max,
|
||||
модель haiku, `--permission-mode default`, проект `LIVE` с рабочей копией в `~/.peppa-dev/workspaces/live`,
|
||||
сценарий за PM — `peppa-dev tg messages|click|reply`. Три сессии, расход около $0.03.
|
||||
Сырые payload'ы снимались через `PEPPA_HOOK_CAPTURE_DIR` и лежат в `packages/testkit/fixtures/claude-live/`
|
||||
(пути `/Users/<user>` заменены на `/Users/mock`, текст ответов в transcript заменён на «…»).
|
||||
|
||||
По пути найдены две поломки самого стенда (PEP-21 и worktree): нет вачдога, значит нет раннер-сервиса,
|
||||
и бот не может доставить ответ («Раннер-сервис не запущен»); в worktree нет `.env`, поэтому нет `PEPPA_SECRET`.
|
||||
`peppa-dev up` теперь поднимает `dev-watchdog`, а без `.env` ставит mock-ключ.
|
||||
|
||||
## Что сверено вживую
|
||||
|
||||
| Что | Итог |
|
||||
|---|---|
|
||||
| AskUserQuestion → хук → кнопка в Telegram → `updatedInput.answers` | ✅ совпадает; TUI показывает «User answered Claude's questions: · Какой цвет? → синий» |
|
||||
| AskUserQuestion без ответа → `permissionDecision: deny` с причиной | ✅ агент заканчивает ход и ждёт; ответ PM печатается как «Ответ PM на вопрос #N: Go» |
|
||||
| PermissionRequest → хук allow/always/deny | ✅ allow («Allowed by PermissionRequest hook»), always (`updatedPermissions` = `permission_suggestions`), deny |
|
||||
| Откат в терминал: клавиша «1» | ✅ |
|
||||
| Откат в терминал: «Всегда» / «Запретить» | ❌ **было сломано** (см. ниже), исправлено и проверено вживую |
|
||||
| Bracketed paste (`paste-buffer -p`) | ✅ три строки ушли одним промптом, `/exit` вставкой тоже сработал |
|
||||
| Stop с `decision: block`, `MAX_AUTO_NUDGES` = 2, потом «Сессия ждёт тебя» | ✅ (TUI называет это «Stop hook error: <reason>», работает как надо) |
|
||||
| SessionEnd | ✅ `reason: "prompt_input_exit"` после `/exit` |
|
||||
| `--append-system-prompt-file` | ✅ агент процитировал первую строку правил «# Правила Пеппы для агентов» |
|
||||
| statusLine | ✅ формат совпал с `parseStatusLine`, кроме `total_*_tokens` (см. ниже) |
|
||||
| transcript | ✅ одно сообщение API = несколько записей (по блоку `thinking`/`text`/`tool_use`) с тем же `message.id` и одинаковым `usage`; дедуп по id нужен и работает |
|
||||
| PostToolUse / PostToolUseFailure (шаги PEP-33) | ✅ у Failure поле `error`, `is_interrupt` |
|
||||
| Notification | ✅ `notification_type: "permission_prompt"`, текст короче, чем в моке: «Claude needs your permission» |
|
||||
|
||||
## Расхождения и решения
|
||||
|
||||
1. **Меню диалога разрешений не фиксировано.** В одной сессии встретились три меню:
|
||||
«1. Yes / 2. Yes, and always allow access to … / 3. Yes, and switch to auto mode / 4. No»,
|
||||
«1. Yes / 2. Yes, and switch to auto mode / 3. No» и «1. Yes / 2. Yes, and don't ask again for … / 3. No».
|
||||
Старые ключи `allow→1, always→2, deny→3` в первом меню «Запретить» превращали в «Yes + auto mode», а во втором
|
||||
«Всегда» превращали в auto mode (вживую: сессия ушла в «⏵⏵ auto mode on» и перестала спрашивать вообще).
|
||||
Решение: `permissionKey(screen, answer)` читает номер с экрана (последний «Do you want to…»), «Всегда» без
|
||||
пункта always = «Yes», «Запретить» без «No» = Escape. Никогда не жмём угаданный номер.
|
||||
2. **«No» прерывает ход** («Interrupted · What should Claude do instead?»), Stop-хук не срабатывает, агент молча ждёт.
|
||||
Решение: после «Запретить» в терминале Пеппа печатает `PERMISSION_DENIED_NOTE` («PM запретил это действие. Продолжай
|
||||
без него…»), проверено вживую: агент ответил и продолжил.
|
||||
3. **statusLine `context_window.total_input_tokens/total_output_tokens` — последний запрос**, не сумма за сессию
|
||||
(48835 = input+cache текущего запроса; так и в документации /statusline). Пеппа клала их в `tokensByGen` и до
|
||||
первого Stop показывала «45 тыс. токенов» — размер контекста. Решение: `parseStatusLine` их больше не читает,
|
||||
токены — только из transcript.
|
||||
4. **MCP `peppa` спрашивает разрешение**, если в репо нет `.claude/settings.json` шаблона (подключённый существующий
|
||||
репо). Решение: `permissions.allow: ["mcp__peppa"]` в сгенерированных `--settings`.
|
||||
5. Мок: меню из 4 пунктов как у живого CLI, «No»/Escape прерывает ход без Stop, статуслайн без `hook_event_name` и с
|
||||
`total_*_tokens` последнего запроса, transcript по записи на блок, `permission_suggestions` = `addDirectories`
|
||||
(`destination: session`), у AskUserQuestion `tool_use_id` и `description` вариантов, StopFailure
|
||||
`last_assistant_message` = текст ошибки API.
|
||||
|
||||
Новые поля payload'ов, которые Пеппа пока не использует: `prompt_id`, `permission_mode`, `effort.level`,
|
||||
`scratchpad_dir`, `model` в SessionStart, `background_tasks`/`session_crons` в Stop, `mcp_server` в PermissionRequest
|
||||
для MCP, `prompt_cache`/`exceeds_200k_tokens` в statusLine.
|
||||
|
||||
## Что не проверено вживую
|
||||
|
||||
- **StopFailure / лимит.** Вызвать нельзя. По документации хуков: срабатывает вместо Stop, когда ход оборвался
|
||||
ошибкой API; поля `error` (обязательное: `rate_limit`, `overloaded`, `authentication_failed`, `oauth_org_not_allowed`,
|
||||
`account_on_hold`, `billing_error`, `invalid_request`, `model_not_found`, `server_error`, `max_output_tokens`,
|
||||
`cloud_credential_error`, `unknown`), `error_details` (необязательное), `last_assistant_message` (текст ошибки API,
|
||||
например «API Error: Rate limit reached»); вывод и код выхода игнорируются. Наш хук совместим: `rate_limit` →
|
||||
`recordLimit(error_details ?? last_assistant_message)`. **Точный текст `error_details` при лимите подписки и
|
||||
реальный баннер лимита в TUI не сняты** — без времени сброса `recordLimit` переходит на пробу 30→60→120 мин.
|
||||
Снять при первом настоящем лимите: `PEPPA_HOOK_CAPTURE_DIR` на живой системе.
|
||||
- Баннер порога «N% of your … limit» (PEP-39) живьём не видели; окна `rate_limits` в statusLine (`used_percentage`,
|
||||
`resets_at` в секундах) есть и разбираются, их можно использовать как надёжный источник порога.
|
||||
- `/clear` и `/resume` внутри живого процесса (SessionStart с `source: clear|resume`) — не прогоняли.
|
||||
- Codex/OpenCode — вне этой стори.
|
||||
|
||||
Замечено, но не наше: zsh пользователя на машине спрашивает «compinit: insecure directories…» в снимке шелла Claude,
|
||||
и строка попадает в поле ввода TUI; на ход не повлияло.
|
||||
@ -0,0 +1,27 @@
|
||||
## Why
|
||||
|
||||
Хуки, statusLine и терминальный откат Пеппы написаны и проверены только против `mock-claude`.
|
||||
Контракт настоящего Claude Code (2.1.x) — поля payload'ов хуков, формат statusLine, клавиши
|
||||
диалога разрешений, bracketed paste — ни разу не сверялся. Ошибка здесь ломает всю фабрику
|
||||
молча: вопросы не доходят PM, автопродолжение не срабатывает, расход не считается.
|
||||
|
||||
## What Changes
|
||||
|
||||
- Прогон настоящей сессии `claude` через раннер Пеппы на dev-стенде (`PEPPA_DEV_CLAUDE_BIN=claude peppa-dev up`):
|
||||
PermissionRequest и AskUserQuestion через Telegram-мок, откат на диалог в терминале,
|
||||
Stop с `decision: block`, SessionEnd, правила из `--append-system-prompt-file`, statusLine.
|
||||
- `peppa-hook` умеет сохранять сырые payload'ы (`PEPPA_HOOK_CAPTURE_DIR`) — так их и сняли.
|
||||
- Реальные payload'ы — фикстуры `packages/testkit/fixtures/claude-live/*.json`.
|
||||
- Расхождения кода и `mock-claude` с настоящим контрактом исправлены; e2e на моках там, где
|
||||
нашлось расхождение.
|
||||
- Что вживую проверить не удалось (StopFailure/лимиты) — описано в design.md.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### Modified Capabilities
|
||||
- `agent-hooks`: запись сырых payload'ов хуков для сверки с живым CLI.
|
||||
|
||||
## Impact
|
||||
|
||||
`packages/runner/src/hook.ts`, `packages/testkit/src/mock-agent.ts`, `packages/core/src/usage.ts`,
|
||||
фикстуры и e2e в `packages/testkit`.
|
||||
@ -0,0 +1,18 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Запись сырых payload'ов хуков
|
||||
Если задан `PEPPA_HOOK_CAPTURE_DIR`, `peppa-hook` SHALL сохранять каждый полученный payload (хуки и statusLine) как есть в файл `<каталог>/<время>-<событие>.json` до обработки; ошибка записи MUST NOT ломать хук.
|
||||
|
||||
#### Scenario: Сверка с живым Claude Code
|
||||
- **GIVEN** раннер запущен с `PEPPA_HOOK_CAPTURE_DIR=/tmp/cap`
|
||||
- **WHEN** Claude вызывает хук `Stop`
|
||||
- **THEN** в `/tmp/cap` появляется файл `…-stop.json` с payload'ом Claude без изменений
|
||||
- **AND** хук отрабатывает как обычно
|
||||
|
||||
### Requirement: Peppa MCP без разрешений
|
||||
Сгенерированный файл настроек запуска Claude SHALL разрешать инструменты MCP-сервера `peppa` (`permissions.allow: ["mcp__peppa"]`), чтобы вызовы Пеппы не превращались в вопросы PM и в репозиториях без `.claude/settings.json` шаблона.
|
||||
|
||||
#### Scenario: Подключённый существующий репозиторий
|
||||
- **GIVEN** в репозитории проекта нет `.claude/settings.json`
|
||||
- **WHEN** агент вызывает `peppa.get_task`
|
||||
- **THEN** Claude не спрашивает разрешения и PM не получает вопрос `permission`
|
||||
@ -0,0 +1,38 @@
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Доставка ответа PM в сессию
|
||||
Ответ PM SHALL сохраняться, сбрасывать счётчик автопродолжений и доставляться агенту по виду вопроса: `permission` — пункт меню Claude, номер которого читается с экрана (allow → «Yes», always → «Yes, and always allow… / don't ask again…», а без такого пункта — «Yes», deny → последний «No», без него — Escape), после deny агенту печатается «PM запретил это действие…» (живой Claude прерывает ход на «No» без Stop-хука); `approval` — смена статуса стори и сообщение; `question` — «Ответ PM на вопрос #N: …»; иначе — текст. Вопрос, который держит хук, отдаёт агенту хук. Ответ на вопрос стори без сессии уходит в живую сессию стори. Особые ответы (релиз, простой) MUST NOT попадать в терминал.
|
||||
|
||||
#### Scenario Outline: Одобрение proposal
|
||||
- **GIVEN** стори `PEP-42` в `awaiting_approval`, агент ждёт в сессии #7
|
||||
- **WHEN** PM отвечает «<ответ>»
|
||||
- **THEN** стори получает статус «<статус>»
|
||||
- **AND** агент получает сообщение «<сообщение>»
|
||||
|
||||
| ответ | статус | сообщение |
|
||||
|---|---|---|
|
||||
| ок | in_progress | PM одобрил proposal PEP-42. Статус in_progress — переходи к Apply. |
|
||||
| да, но без кэша | in_progress | PM одобрил proposal PEP-42 … Комментарий PM: да, но без кэша |
|
||||
| нет, разбей на две стори | proposing | PM не одобрил proposal PEP-42. Доработай proposal по комментарию … |
|
||||
|
||||
#### Scenario: Разрешение из Telegram
|
||||
- **GIVEN** Claude показывает диалог разрешения, хук уже отпустил вопрос в терминал
|
||||
- **AND** меню «1. Yes / 2. Yes, and always allow access to … / 3. Yes, and switch to auto mode / 4. No»
|
||||
- **WHEN** PM нажимает «♾ Всегда»
|
||||
- **THEN** в pane нажата клавиша `2`
|
||||
|
||||
#### Scenario: Запрет из Telegram в меню без пункта auto mode
|
||||
- **GIVEN** хук отпустил вопрос в терминал, меню «1. Yes / 2. Yes, and don't ask again… / 3. No»
|
||||
- **WHEN** PM нажимает «⛔ Запретить»
|
||||
- **THEN** в pane нажата клавиша `3`
|
||||
- **AND** агенту напечатано «PM запретил это действие. Продолжай без него…»
|
||||
|
||||
#### Scenario: «Всегда» без пункта «always»
|
||||
- **GIVEN** меню «1. Yes / 2. Yes, and switch to auto mode / 3. No»
|
||||
- **WHEN** PM нажимает «♾ Всегда»
|
||||
- **THEN** в pane нажата клавиша `1`, сессия не переходит в auto mode
|
||||
|
||||
#### Scenario: Сессия не запущена
|
||||
- **GIVEN** вопрос #12 сессии #7, tmux-сессии нет
|
||||
- **WHEN** PM отвечает
|
||||
- **THEN** ответ сохранён, PM видит «Ответ сохранён, но сессия сейчас не запущена»
|
||||
@ -0,0 +1,15 @@
|
||||
## 1. Снять контракт
|
||||
- [x] 1.1 `PEPPA_HOOK_CAPTURE_DIR` в peppa-hook: сырые payload'ы событий и statusLine
|
||||
- [x] 1.2 Живой прогон на dev-стенде: PermissionRequest, AskUserQuestion, откат в терминал, Stop/nudge, SessionEnd, правила, statusLine
|
||||
- [x] 1.3 Фикстуры `packages/testkit/fixtures/claude-live/`
|
||||
|
||||
## 2. Сверить и исправить
|
||||
- [x] 2.1 Сверить payload'ы хуков с `HookInput` и mock-claude
|
||||
- [x] 2.2 Сверить statusLine с `parseStatusLine`, transcript с `transcriptUsage`
|
||||
- [x] 2.3 Сверить клавиши диалога разрешений и bracketed paste
|
||||
- [x] 2.4 StopFailure — по документации, описать непроверенное
|
||||
- [x] 2.5 Исправить расхождения в коде и моке
|
||||
|
||||
## 3. Тесты
|
||||
- [x] 3.1 e2e на моках по найденным расхождениям (и разбор фикстур)
|
||||
- [x] 3.2 `pnpm run ci`
|
||||
@ -142,3 +142,20 @@
|
||||
- **GIVEN** сессия #7 `running`
|
||||
- **WHEN** человек делает `/resume` и срабатывает `SessionEnd`
|
||||
- **THEN** сессия остаётся `running`
|
||||
|
||||
### Requirement: Запись сырых payload'ов хуков
|
||||
Если задан `PEPPA_HOOK_CAPTURE_DIR`, `peppa-hook` SHALL сохранять каждый полученный payload (хуки и statusLine) как есть в файл `<каталог>/<время>-<событие>.json` до обработки; ошибка записи MUST NOT ломать хук.
|
||||
|
||||
#### Scenario: Сверка с живым Claude Code
|
||||
- **GIVEN** раннер запущен с `PEPPA_HOOK_CAPTURE_DIR=/tmp/cap`
|
||||
- **WHEN** Claude вызывает хук `Stop`
|
||||
- **THEN** в `/tmp/cap` появляется файл `…-stop.json` с payload'ом Claude без изменений
|
||||
- **AND** хук отрабатывает как обычно
|
||||
|
||||
### Requirement: Peppa MCP без разрешений
|
||||
Сгенерированный файл настроек запуска Claude SHALL разрешать инструменты MCP-сервера `peppa` (`permissions.allow: ["mcp__peppa"]`), чтобы вызовы Пеппы не превращались в вопросы PM и в репозиториях без `.claude/settings.json` шаблона.
|
||||
|
||||
#### Scenario: Подключённый существующий репозиторий
|
||||
- **GIVEN** в репозитории проекта нет `.claude/settings.json`
|
||||
- **WHEN** агент вызывает `peppa.get_task`
|
||||
- **THEN** Claude не спрашивает разрешения и PM не получает вопрос `permission`
|
||||
|
||||
@ -85,7 +85,7 @@
|
||||
- **THEN** ошибка «is not running»
|
||||
|
||||
### Requirement: Доставка ответа PM в сессию
|
||||
Ответ PM SHALL сохраняться, сбрасывать счётчик автопродолжений и доставляться агенту по виду вопроса: `permission` — пункт меню Claude (allow → 1, always → 2, deny → 3); `approval` — смена статуса стори и сообщение; `question` — «Ответ PM на вопрос #N: …»; иначе — текст. Вопрос, который держит хук, отдаёт агенту хук. Ответ на вопрос стори без сессии уходит в живую сессию стори. Особые ответы (релиз, простой) MUST NOT попадать в терминал.
|
||||
Ответ PM SHALL сохраняться, сбрасывать счётчик автопродолжений и доставляться агенту по виду вопроса: `permission` — пункт меню Claude, номер которого читается с экрана (allow → «Yes», always → «Yes, and always allow… / don't ask again…», а без такого пункта — «Yes», deny → последний «No», без него — Escape), после deny агенту печатается «PM запретил это действие…» (живой Claude прерывает ход на «No» без Stop-хука); `approval` — смена статуса стори и сообщение; `question` — «Ответ PM на вопрос #N: …»; иначе — текст. Вопрос, который держит хук, отдаёт агенту хук. Ответ на вопрос стори без сессии уходит в живую сессию стори. Особые ответы (релиз, простой) MUST NOT попадать в терминал.
|
||||
|
||||
#### Scenario Outline: Одобрение proposal
|
||||
- **GIVEN** стори `PEP-42` в `awaiting_approval`, агент ждёт в сессии #7
|
||||
@ -101,9 +101,21 @@
|
||||
|
||||
#### Scenario: Разрешение из Telegram
|
||||
- **GIVEN** Claude показывает диалог разрешения, хук уже отпустил вопрос в терминал
|
||||
- **AND** меню «1. Yes / 2. Yes, and always allow access to … / 3. Yes, and switch to auto mode / 4. No»
|
||||
- **WHEN** PM нажимает «♾ Всегда»
|
||||
- **THEN** в pane нажата клавиша `2`
|
||||
|
||||
#### Scenario: Запрет из Telegram в меню без пункта auto mode
|
||||
- **GIVEN** хук отпустил вопрос в терминал, меню «1. Yes / 2. Yes, and don't ask again… / 3. No»
|
||||
- **WHEN** PM нажимает «⛔ Запретить»
|
||||
- **THEN** в pane нажата клавиша `3`
|
||||
- **AND** агенту напечатано «PM запретил это действие. Продолжай без него…»
|
||||
|
||||
#### Scenario: «Всегда» без пункта «always»
|
||||
- **GIVEN** меню «1. Yes / 2. Yes, and switch to auto mode / 3. No»
|
||||
- **WHEN** PM нажимает «♾ Всегда»
|
||||
- **THEN** в pane нажата клавиша `1`, сессия не переходит в auto mode
|
||||
|
||||
#### Scenario: Сессия не запущена
|
||||
- **GIVEN** вопрос #12 сессии #7, tmux-сессии нет
|
||||
- **WHEN** PM отвечает
|
||||
|
||||
@ -57,7 +57,10 @@ function parseWindow(v: unknown): UsageWindow | undefined {
|
||||
return { pct: Math.max(0, Math.min(100, Math.round(pct * 10) / 10)), resetsAt: toMs(o.resets_at ?? o.resetsAt ?? o.reset_at ?? o.resets) };
|
||||
}
|
||||
|
||||
/** Claude Code statusLine JSON → what Peppa keeps. Tolerant to field name variants (not verified on a live CLI). */
|
||||
/**
|
||||
* Claude Code statusLine JSON → what Peppa keeps. Checked against live 2.1.323 (PEP-3, fixture
|
||||
* `packages/testkit/fixtures/claude-live/statusline.json`); still tolerant to field name variants.
|
||||
*/
|
||||
export function parseStatusLine(input: unknown): StatusLineData {
|
||||
const j = obj(input) ?? {};
|
||||
const cost = obj(j.cost);
|
||||
@ -72,9 +75,8 @@ export function parseStatusLine(input: unknown): StatusLineData {
|
||||
const used = cur ? (num(cur.input_tokens) ?? 0) + (num(cur.cache_read_input_tokens) ?? 0) + (num(cur.cache_creation_input_tokens) ?? 0) : num(cw.used_tokens);
|
||||
const pct = num(cw.used_percentage) ?? (used != null && size ? (used / size) * 100 : undefined);
|
||||
if (size && (used != null || pct != null)) out.context = { used: used ?? Math.round(((pct ?? 0) / 100) * size), size, pct: Math.round((pct ?? 0) * 10) / 10 };
|
||||
const ti = num(cw.total_input_tokens);
|
||||
const to = num(cw.total_output_tokens);
|
||||
if (ti != null || to != null) out.tokens = { input: ti ?? 0, output: to ?? 0 };
|
||||
// PEP-3 (live 2.1.323): `total_input_tokens` / `total_output_tokens` are the LAST request
|
||||
// (= current_usage input+cache / output), not session totals — tokens come from the transcript.
|
||||
}
|
||||
if (rl) {
|
||||
const five = parseWindow(rl.five_hour ?? rl.fiveHour ?? rl["5h"] ?? rl.session);
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
// PEPPA_SESSION_ID / PEPPA_GENERATION point to. Must never break the Claude session:
|
||||
// always exits 0, errors go to ~/.peppa/hook.log, and blocking hooks fall back to
|
||||
// Claude's own terminal dialog when the PM doesn't answer in time.
|
||||
import { appendFileSync, readFileSync } from "node:fs";
|
||||
import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
answerQuestion,
|
||||
@ -395,6 +395,15 @@ if (event !== "codex-notify") {
|
||||
raw = readFileSync(0, "utf8");
|
||||
} catch {}
|
||||
}
|
||||
// PEP-3: raw payloads as the CLI sent them, for checking the contract against a live Claude Code.
|
||||
if (process.env.PEPPA_HOOK_CAPTURE_DIR && raw) {
|
||||
try {
|
||||
mkdirSync(process.env.PEPPA_HOOK_CAPTURE_DIR, { recursive: true });
|
||||
writeFileSync(join(process.env.PEPPA_HOOK_CAPTURE_DIR, `${Date.now()}-${process.pid}-${event}.json`), raw);
|
||||
} catch (e) {
|
||||
log(`capture ${event}: ${(e as Error).message}`);
|
||||
}
|
||||
}
|
||||
// PEP-48: hooks act as the session's agent (answers typed into the terminal are a person's).
|
||||
setDefaultActor({ kind: "agent", channel: "hook" });
|
||||
try {
|
||||
|
||||
@ -38,6 +38,9 @@ export function writeRunSettings(sessionId: number, generation: number, bin: str
|
||||
const settings = {
|
||||
// PEP-5: Claude reports cost, context and the 5h/7d limit windows to the status line command.
|
||||
statusLine: { type: "command", command: `${bin} statusline`, padding: 0 },
|
||||
// PEP-3: Peppa's own MCP tools never need the PM (the template allows them too, but a
|
||||
// connected existing repo has no .claude/settings.json); status guards live in the server.
|
||||
permissions: { allow: ["mcp__peppa"] },
|
||||
hooks: {
|
||||
SessionStart: [{ hooks: [hook("session-start")] }],
|
||||
UserPromptSubmit: [{ hooks: [hook("prompt")] }],
|
||||
|
||||
@ -330,6 +330,7 @@ async function launch(
|
||||
// The subscription's login (PEP-67): Claude token, CODEX_HOME or an OpenCode key.
|
||||
...(sub ? subscriptionEnv(sub) : {}),
|
||||
...(process.env.PEPPA_HOOK_WAIT_SEC ? { PEPPA_HOOK_WAIT_SEC: process.env.PEPPA_HOOK_WAIT_SEC } : {}),
|
||||
...(process.env.PEPPA_HOOK_CAPTURE_DIR ? { PEPPA_HOOK_CAPTURE_DIR: process.env.PEPPA_HOOK_CAPTURE_DIR } : {}),
|
||||
};
|
||||
script = `#!/bin/bash\n${preamble}exec ${argv.map(shq).join(" ")}\n`;
|
||||
}
|
||||
@ -396,8 +397,30 @@ export function onAnswer(h: AnswerHandler) {
|
||||
}
|
||||
|
||||
const APPROVE_RE = /^\s*(ok|ок|да|yes|approve|approved|одобр|lgtm|go|погнали|делай)/i;
|
||||
// Claude Code permission prompt: 1 = yes, 2 = yes and don't ask again, 3 = no.
|
||||
const PERMISSION_KEYS: Record<string, string> = { allow: "1", always: "2", deny: "3" };
|
||||
/**
|
||||
* The key for the PM's answer in Claude Code's permission dialog. The menu differs by tool,
|
||||
* by what is already allowed and by version — seen live on 2.1.323 (PEP-3): «1. Yes /
|
||||
* 2. Yes, and always allow access to … / 3. Yes, and switch to auto mode … / 4. No», but also
|
||||
* «1. Yes / 2. Yes, and switch to auto mode / 3. No» and «1. Yes / 2. Yes, and always allow … /
|
||||
* 3. No». So the number is read off the screen; a fixed "2" could switch the session to auto
|
||||
* mode and a fixed "3" could allow instead of deny. "always" without such a line = "Yes";
|
||||
* "deny" without a "No" line = Escape (cancels the call).
|
||||
*/
|
||||
export function permissionKey(screen: string, answer: string): string | null {
|
||||
const a = answer.trim().toLowerCase();
|
||||
if (!["allow", "always", "deny"].includes(a)) return null;
|
||||
// The dialog is the last menu on the screen: only look below its question.
|
||||
const at = screen.lastIndexOf("Do you want to");
|
||||
const lines = (at >= 0 ? screen.slice(at) : "").split("\n");
|
||||
const opts = lines.map((l) => /^\s*(?:❯\s*)?(\d)\.\s+(.*)$/.exec(l)).filter((m): m is RegExpExecArray => !!m).map((m) => ({ key: m[1]!, text: m[2]!.trim() }));
|
||||
const yes = opts.find((o) => /^Yes\s*$/i.test(o.text))?.key ?? "1";
|
||||
if (a === "allow") return yes;
|
||||
if (a === "always") return opts.find((o) => /^Yes, and (always|don't ask|do not ask)/i.test(o.text))?.key ?? yes;
|
||||
return [...opts].reverse().find((o) => /^No\b/i.test(o.text))?.key ?? "Escape";
|
||||
}
|
||||
|
||||
/** Typed after "No" in the dialog: Claude interrupts the turn there and waits silently (PEP-3). */
|
||||
export const PERMISSION_DENIED_NOTE = "PM запретил это действие. Продолжай без него, а если без него никак — ask_pm и закончи ход.";
|
||||
|
||||
/**
|
||||
* Records the PM's answer and delivers it into the session's terminal:
|
||||
@ -458,9 +481,16 @@ export async function answerAndDeliver(
|
||||
if (!(await tmux.hasSession(tmux.sessionPane(s)))) return { delivered: false, question: q };
|
||||
|
||||
if (q.kind === "permission") {
|
||||
const key = PERMISSION_KEYS[answer.trim().toLowerCase()];
|
||||
if (key) await tmux.sendKeys(tmux.sessionPane(s), key);
|
||||
else await tmux.sendText(tmux.sessionPane(s), answer);
|
||||
const key = permissionKey(await tmux.capturePane(tmux.sessionPane(s)).catch(() => ""), answer);
|
||||
if (key) {
|
||||
await tmux.sendKeys(tmux.sessionPane(s), key);
|
||||
if (answer.trim().toLowerCase() === "deny") {
|
||||
// The interrupted turn leaves an empty prompt; give the TUI a moment to draw it.
|
||||
await new Promise((r) => setTimeout(r, Number(process.env.PEPPA_DENY_NOTE_DELAY_MS ?? 1500)));
|
||||
await logSessionEvent(db, s, "input_sent", { text: PERMISSION_DENIED_NOTE });
|
||||
await tmux.sendText(tmux.sessionPane(s), PERMISSION_DENIED_NOTE);
|
||||
}
|
||||
} else await tmux.sendText(tmux.sessionPane(s), answer);
|
||||
} else {
|
||||
await tmux.sendText(tmux.sessionPane(s), message);
|
||||
}
|
||||
|
||||
@ -21,6 +21,8 @@ export PEPPA_CLAUDE_BIN="${PEPPA_DEV_CLAUDE_BIN:-$ROOT/packages/testkit/bin/mock
|
||||
export PEPPA_CODEX_BIN="${PEPPA_DEV_CODEX_BIN:-$ROOT/packages/testkit/bin/mock-codex}"
|
||||
export PEPPA_HOOK_WAIT_SEC="${PEPPA_HOOK_WAIT_SEC:-30}"
|
||||
export PEPPA_WEB_URL="http://peppa-dev.local"
|
||||
# A worktree has no .env: the stand still needs a key for its own encrypted columns.
|
||||
[ -n "${PEPPA_SECRET:-}" ] || grep -q '^PEPPA_SECRET=' "$ROOT/.env" 2>/dev/null || export PEPPA_SECRET="mock-dev-stand-secret"
|
||||
mkdir -p "$PEPPA_HOME" "$PEPPA_WORKSPACES"
|
||||
TM=(tmux -L peppa-dev)
|
||||
PEPPA="$ROOT/packages/cli/bin/peppa"
|
||||
@ -30,6 +32,9 @@ up() {
|
||||
"${TM[@]}" has-session -t dev-mock-tg 2>/dev/null || "${TM[@]}" new-session -d -s dev-mock-tg "$ROOT/packages/testkit/bin/mock-telegram --port $PORT"
|
||||
"${TM[@]}" set-option -s exit-empty off
|
||||
for _ in $(seq 1 40); do curl -sf "$TELEGRAM_API_URL/_mock/messages" >/dev/null && break; sleep 0.25; done
|
||||
# PEP-21: the watchdog is the runner service — the bot hands it answers and «В работу».
|
||||
"${TM[@]}" has-session -t dev-watchdog 2>/dev/null || "${TM[@]}" new-session -d -s dev-watchdog "$PEPPA watchdog"
|
||||
for _ in $(seq 1 40); do [ -S "$PEPPA_HOME/runner.sock" ] && break; sleep 0.25; done
|
||||
"${TM[@]}" has-session -t dev-bot 2>/dev/null || "${TM[@]}" new-session -d -s dev-bot "$ROOT/apps/bot/bin/peppa-bot"
|
||||
for _ in $(seq 1 40); do "$PEPPA" telegram status 2>/dev/null | grep -q '^bot: @' && break; sleep 0.25; done
|
||||
"$PEPPA" user ensure mock-pm >/dev/null
|
||||
|
||||
@ -0,0 +1,10 @@
|
||||
{
|
||||
"session_id": "e96536c6-f9ba-49d2-bf73-4d57ba125f64",
|
||||
"transcript_path": "/Users/mock/.claude/projects/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64.jsonl",
|
||||
"cwd": "/Users/mock/.peppa-dev/workspaces/live",
|
||||
"scratchpad_dir": "/private/tmp/claude-501/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64/scratchpad",
|
||||
"prompt_id": "aeb1f988-5770-4f6d-a38b-52c731e6af74",
|
||||
"hook_event_name": "Notification",
|
||||
"message": "Claude needs your permission",
|
||||
"notification_type": "permission_prompt"
|
||||
}
|
||||
@ -0,0 +1,32 @@
|
||||
{
|
||||
"session_id": "a8a23fed-636e-4685-963c-56dd326f5821",
|
||||
"transcript_path": "/Users/mock/.claude/projects/-Users-mock--peppa-dev-workspaces-live/a8a23fed-636e-4685-963c-56dd326f5821.jsonl",
|
||||
"cwd": "/Users/mock/.peppa-dev/workspaces/live",
|
||||
"scratchpad_dir": "/private/tmp/claude-501/-Users-mock--peppa-dev-workspaces-live/a8a23fed-636e-4685-963c-56dd326f5821/scratchpad",
|
||||
"prompt_id": "f4a78a56-3378-45be-ac8a-75eebfc321bd",
|
||||
"permission_mode": "default",
|
||||
"effort": {
|
||||
"level": "medium"
|
||||
},
|
||||
"hook_event_name": "PermissionRequest",
|
||||
"tool_name": "mcp__peppa__get_task",
|
||||
"tool_input": {
|
||||
"task": "LIVE-1"
|
||||
},
|
||||
"permission_suggestions": [
|
||||
{
|
||||
"type": "addRules",
|
||||
"rules": [
|
||||
{
|
||||
"toolName": "mcp__peppa__get_task"
|
||||
}
|
||||
],
|
||||
"behavior": "allow",
|
||||
"destination": "localSettings"
|
||||
}
|
||||
],
|
||||
"mcp_server": {
|
||||
"name": "peppa",
|
||||
"source": "project"
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,26 @@
|
||||
{
|
||||
"session_id": "e96536c6-f9ba-49d2-bf73-4d57ba125f64",
|
||||
"transcript_path": "/Users/mock/.claude/projects/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64.jsonl",
|
||||
"cwd": "/Users/mock/.peppa-dev/workspaces/live",
|
||||
"scratchpad_dir": "/private/tmp/claude-501/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64/scratchpad",
|
||||
"prompt_id": "aeb1f988-5770-4f6d-a38b-52c731e6af74",
|
||||
"permission_mode": "default",
|
||||
"effort": {
|
||||
"level": "medium"
|
||||
},
|
||||
"hook_event_name": "PermissionRequest",
|
||||
"tool_name": "Bash",
|
||||
"tool_input": {
|
||||
"command": "touch two.txt",
|
||||
"description": "Create two.txt in the working directory"
|
||||
},
|
||||
"permission_suggestions": [
|
||||
{
|
||||
"type": "addDirectories",
|
||||
"directories": [
|
||||
"/Users/mock/.peppa-dev/workspaces/live"
|
||||
],
|
||||
"destination": "session"
|
||||
}
|
||||
]
|
||||
}
|
||||
@ -0,0 +1,21 @@
|
||||
{
|
||||
"session_id": "e96536c6-f9ba-49d2-bf73-4d57ba125f64",
|
||||
"transcript_path": "/Users/mock/.claude/projects/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64.jsonl",
|
||||
"cwd": "/Users/mock/.peppa-dev/workspaces/live",
|
||||
"scratchpad_dir": "/private/tmp/claude-501/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64/scratchpad",
|
||||
"prompt_id": "aeb1f988-5770-4f6d-a38b-52c731e6af74",
|
||||
"permission_mode": "auto",
|
||||
"effort": {
|
||||
"level": "medium"
|
||||
},
|
||||
"hook_event_name": "PostToolUseFailure",
|
||||
"tool_name": "Bash",
|
||||
"tool_input": {
|
||||
"command": "ls /nonexistent-peppa",
|
||||
"description": "List a nonexistent directory to check error handling"
|
||||
},
|
||||
"tool_use_id": "toolu_01RWJyz6BUXwPcU2j2znFmq5",
|
||||
"error": "Exit code 1\nls: /nonexistent-peppa: No such file or directory",
|
||||
"is_interrupt": false,
|
||||
"duration_ms": 10081
|
||||
}
|
||||
26
packages/testkit/fixtures/claude-live/post-tool-use.json
Normal file
26
packages/testkit/fixtures/claude-live/post-tool-use.json
Normal file
@ -0,0 +1,26 @@
|
||||
{
|
||||
"session_id": "e96536c6-f9ba-49d2-bf73-4d57ba125f64",
|
||||
"transcript_path": "/Users/mock/.claude/projects/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64.jsonl",
|
||||
"cwd": "/Users/mock/.peppa-dev/workspaces/live",
|
||||
"scratchpad_dir": "/private/tmp/claude-501/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64/scratchpad",
|
||||
"prompt_id": "aeb1f988-5770-4f6d-a38b-52c731e6af74",
|
||||
"permission_mode": "auto",
|
||||
"effort": {
|
||||
"level": "medium"
|
||||
},
|
||||
"hook_event_name": "PostToolUse",
|
||||
"tool_name": "Bash",
|
||||
"tool_input": {
|
||||
"command": "touch two.txt",
|
||||
"description": "Create two.txt in the working directory"
|
||||
},
|
||||
"tool_response": {
|
||||
"stdout": "",
|
||||
"stderr": "",
|
||||
"interrupted": false,
|
||||
"isImage": false,
|
||||
"noOutputExpected": true
|
||||
},
|
||||
"tool_use_id": "toolu_015ZHJezTdAPV733czTubGD5",
|
||||
"duration_ms": 82
|
||||
}
|
||||
@ -0,0 +1,33 @@
|
||||
{
|
||||
"session_id": "e96536c6-f9ba-49d2-bf73-4d57ba125f64",
|
||||
"transcript_path": "/Users/mock/.claude/projects/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64.jsonl",
|
||||
"cwd": "/Users/mock/.peppa-dev/workspaces/live",
|
||||
"scratchpad_dir": "/private/tmp/claude-501/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64/scratchpad",
|
||||
"prompt_id": "2566d5ad-f4dc-489b-8aa6-8ff1730a023c",
|
||||
"permission_mode": "default",
|
||||
"effort": {
|
||||
"level": "medium"
|
||||
},
|
||||
"hook_event_name": "PreToolUse",
|
||||
"tool_name": "AskUserQuestion",
|
||||
"tool_input": {
|
||||
"questions": [
|
||||
{
|
||||
"question": "Какой язык?",
|
||||
"header": "Язык",
|
||||
"options": [
|
||||
{
|
||||
"label": "Go",
|
||||
"description": "Язык Go"
|
||||
},
|
||||
{
|
||||
"label": "Rust",
|
||||
"description": "Язык Rust"
|
||||
}
|
||||
],
|
||||
"multiSelect": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"tool_use_id": "toolu_01TCVWSwtMREECGQ6o93NCnV"
|
||||
}
|
||||
9
packages/testkit/fixtures/claude-live/session-end.json
Normal file
9
packages/testkit/fixtures/claude-live/session-end.json
Normal file
@ -0,0 +1,9 @@
|
||||
{
|
||||
"session_id": "e96536c6-f9ba-49d2-bf73-4d57ba125f64",
|
||||
"transcript_path": "/Users/mock/.claude/projects/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64.jsonl",
|
||||
"cwd": "/Users/mock/.peppa-dev/workspaces/live",
|
||||
"scratchpad_dir": "/private/tmp/claude-501/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64/scratchpad",
|
||||
"prompt_id": "6c2c2439-2d58-4662-8dac-35c50dad63b6",
|
||||
"hook_event_name": "SessionEnd",
|
||||
"reason": "prompt_input_exit"
|
||||
}
|
||||
9
packages/testkit/fixtures/claude-live/session-start.json
Normal file
9
packages/testkit/fixtures/claude-live/session-start.json
Normal file
@ -0,0 +1,9 @@
|
||||
{
|
||||
"session_id": "e96536c6-f9ba-49d2-bf73-4d57ba125f64",
|
||||
"transcript_path": "/Users/mock/.claude/projects/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64.jsonl",
|
||||
"cwd": "/Users/mock/.peppa-dev/workspaces/live",
|
||||
"scratchpad_dir": "/private/tmp/claude-501/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64/scratchpad",
|
||||
"hook_event_name": "SessionStart",
|
||||
"source": "startup",
|
||||
"model": "claude-haiku-5-5"
|
||||
}
|
||||
42
packages/testkit/fixtures/claude-live/statusline-first.json
Normal file
42
packages/testkit/fixtures/claude-live/statusline-first.json
Normal file
@ -0,0 +1,42 @@
|
||||
{
|
||||
"session_id": "e96536c6-f9ba-49d2-bf73-4d57ba125f64",
|
||||
"transcript_path": "/Users/mock/.claude/projects/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64.jsonl",
|
||||
"cwd": "/Users/mock/.peppa-dev/workspaces/live",
|
||||
"scratchpad_dir": "/private/tmp/claude-501/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64/scratchpad",
|
||||
"effort": {
|
||||
"level": "medium"
|
||||
},
|
||||
"model": {
|
||||
"id": "claude-haiku-5-5",
|
||||
"display_name": "Haiku 5.5"
|
||||
},
|
||||
"workspace": {
|
||||
"current_dir": "/Users/mock/.peppa-dev/workspaces/live",
|
||||
"project_dir": "/Users/mock/.peppa-dev/workspaces/live",
|
||||
"added_dirs": []
|
||||
},
|
||||
"version": "2.1.323",
|
||||
"output_style": {
|
||||
"name": "default"
|
||||
},
|
||||
"cost": {
|
||||
"total_cost_usd": 0,
|
||||
"total_duration_ms": 359,
|
||||
"total_api_duration_ms": 0,
|
||||
"total_lines_added": 0,
|
||||
"total_lines_removed": 0
|
||||
},
|
||||
"context_window": {
|
||||
"total_input_tokens": 0,
|
||||
"total_output_tokens": 0,
|
||||
"context_window_size": 1000000,
|
||||
"current_usage": null,
|
||||
"used_percentage": null,
|
||||
"remaining_percentage": null
|
||||
},
|
||||
"exceeds_200k_tokens": false,
|
||||
"fast_mode": false,
|
||||
"thinking": {
|
||||
"enabled": true
|
||||
}
|
||||
}
|
||||
74
packages/testkit/fixtures/claude-live/statusline.json
Normal file
74
packages/testkit/fixtures/claude-live/statusline.json
Normal file
@ -0,0 +1,74 @@
|
||||
{
|
||||
"session_id": "a8a23fed-636e-4685-963c-56dd326f5821",
|
||||
"transcript_path": "/Users/mock/.claude/projects/-Users-mock--peppa-dev-workspaces-live/a8a23fed-636e-4685-963c-56dd326f5821.jsonl",
|
||||
"cwd": "/Users/mock/.peppa-dev/workspaces/live",
|
||||
"scratchpad_dir": "/private/tmp/claude-501/-Users-mock--peppa-dev-workspaces-live/a8a23fed-636e-4685-963c-56dd326f5821/scratchpad",
|
||||
"prompt_id": "f4a78a56-3378-45be-ac8a-75eebfc321bd",
|
||||
"effort": {
|
||||
"level": "medium"
|
||||
},
|
||||
"model": {
|
||||
"id": "claude-haiku-5-5",
|
||||
"display_name": "Haiku 5.5"
|
||||
},
|
||||
"workspace": {
|
||||
"current_dir": "/Users/mock/.peppa-dev/workspaces/live",
|
||||
"project_dir": "/Users/mock/.peppa-dev/workspaces/live",
|
||||
"added_dirs": []
|
||||
},
|
||||
"version": "2.1.323",
|
||||
"output_style": {
|
||||
"name": "default"
|
||||
},
|
||||
"cost": {
|
||||
"total_cost_usd": 0.00725025,
|
||||
"total_duration_ms": 111292,
|
||||
"total_api_duration_ms": 12591,
|
||||
"total_lines_added": 0,
|
||||
"total_lines_removed": 0
|
||||
},
|
||||
"context_window": {
|
||||
"total_input_tokens": 51302,
|
||||
"total_output_tokens": 2,
|
||||
"context_window_size": 1000000,
|
||||
"current_usage": {
|
||||
"input_tokens": 2,
|
||||
"output_tokens": 2,
|
||||
"cache_creation_input_tokens": 390,
|
||||
"cache_read_input_tokens": 50910
|
||||
},
|
||||
"used_percentage": 5,
|
||||
"remaining_percentage": 95
|
||||
},
|
||||
"exceeds_200k_tokens": false,
|
||||
"prompt_cache": {
|
||||
"warm": true,
|
||||
"caching_observed": true,
|
||||
"ttl": "1h",
|
||||
"expires_at": 1794644343,
|
||||
"requests": 5,
|
||||
"misses": 0,
|
||||
"expected_rebuilds": 0,
|
||||
"hit_ratio": 0.9223495643259867,
|
||||
"cache_write_tokens": 18927,
|
||||
"miss_recache_tokens": 0,
|
||||
"last_miss_at": null,
|
||||
"last_miss_cause": null,
|
||||
"miss_causes": {},
|
||||
"recache_tokens_if_cold": 50912
|
||||
},
|
||||
"fast_mode": false,
|
||||
"thinking": {
|
||||
"enabled": true
|
||||
},
|
||||
"rate_limits": {
|
||||
"five_hour": {
|
||||
"used_percentage": 4,
|
||||
"resets_at": 1794648000
|
||||
},
|
||||
"seven_day": {
|
||||
"used_percentage": 14,
|
||||
"resets_at": 1795107600
|
||||
}
|
||||
}
|
||||
}
|
||||
16
packages/testkit/fixtures/claude-live/stop-after-block.json
Normal file
16
packages/testkit/fixtures/claude-live/stop-after-block.json
Normal file
@ -0,0 +1,16 @@
|
||||
{
|
||||
"session_id": "e96536c6-f9ba-49d2-bf73-4d57ba125f64",
|
||||
"transcript_path": "/Users/mock/.claude/projects/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64.jsonl",
|
||||
"cwd": "/Users/mock/.peppa-dev/workspaces/live",
|
||||
"scratchpad_dir": "/private/tmp/claude-501/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64/scratchpad",
|
||||
"prompt_id": "c33d7529-95bd-4b45-946b-56264cfc5c1c",
|
||||
"permission_mode": "auto",
|
||||
"effort": {
|
||||
"level": "medium"
|
||||
},
|
||||
"hook_event_name": "Stop",
|
||||
"stop_hook_active": true,
|
||||
"last_assistant_message": "Не буду продолжать LIVE-1 по этому хуку. В начале вы написали, что это тест хуков Пеппы, не настоящая работа, и просили не вызывать MCP `peppa` и не трогать OpenSpec. Хук требует именно этого: `ask_pm`, `update_task(status: review)`, PR. Это внешние действия, поэтому без вашего подтверждения их не делаю.\n\nЧто сделано в тесте: `touch four.txt` и `touch five.txt` выполнены последовательно, файлы созданы в рабочем каталоге.\n\nЕсли LIVE-1 нужно довести до настоящего PR, напишите, и я сделаю это по `tasks.md` и правилам Пеппы. Если тест завершён, ничего больше делать не нужно. В этом случае хук можно отключить или поправить на стороне Пеппы, так как он требует реальной работы, которую вы не заказывали.",
|
||||
"background_tasks": [],
|
||||
"session_crons": []
|
||||
}
|
||||
16
packages/testkit/fixtures/claude-live/stop.json
Normal file
16
packages/testkit/fixtures/claude-live/stop.json
Normal file
@ -0,0 +1,16 @@
|
||||
{
|
||||
"session_id": "e96536c6-f9ba-49d2-bf73-4d57ba125f64",
|
||||
"transcript_path": "/Users/mock/.claude/projects/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64.jsonl",
|
||||
"cwd": "/Users/mock/.peppa-dev/workspaces/live",
|
||||
"scratchpad_dir": "/private/tmp/claude-501/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64/scratchpad",
|
||||
"prompt_id": "2566d5ad-f4dc-489b-8aa6-8ff1730a023c",
|
||||
"permission_mode": "default",
|
||||
"effort": {
|
||||
"level": "medium"
|
||||
},
|
||||
"hook_event_name": "Stop",
|
||||
"stop_hook_active": false,
|
||||
"last_assistant_message": "Вопрос «Какой язык?» (Go / Rust) не прошёл: хук Пеппы переслал его PM (#5). Ход закончен, шаги 2–5 (два `ls`/`touch` и итоговая строка) выполню после ответа.",
|
||||
"background_tasks": [],
|
||||
"session_crons": []
|
||||
}
|
||||
27
packages/testkit/fixtures/claude-live/transcript.jsonl
Normal file
27
packages/testkit/fixtures/claude-live/transcript.jsonl
Normal file
@ -0,0 +1,27 @@
|
||||
{"type": "user", "uuid": "697335fb-029b-4998-8d2d-997bfcf1a5e1", "parentUuid": null, "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:06:46.899Z", "message": {"role": "user", "content": "…"}}
|
||||
{"type": "assistant", "uuid": "a1de7d53-4516-4df7-a26e-970daa23999e", "parentUuid": "6c496664-b2fb-40ef-a8c0-0ea571f00fac", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:06:48.896Z", "requestId": "req_011Ch2Q24xuPkankc3LBjUNp", "message": {"id": "msg_011Ch2Q25AJRyZVA8qwBVqme", "model": "claude-haiku-5-5", "role": "assistant", "type": "message", "content": [{"type": "thinking", "thinking": "…"}], "stop_reason": "tool_use", "usage": {"input_tokens": 2, "cache_creation_input_tokens": 12770, "cache_read_input_tokens": 31983, "output_tokens": 194, "output_tokens_details": {"thinking_tokens": 63}, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": "standard", "cache_creation": {"ephemeral_1h_input_tokens": 12770, "ephemeral_5m_input_tokens": 0}, "inference_geo": "global", "iterations": [{"input_tokens": 2, "output_tokens": 194, "cache_read_input_tokens": 31983, "cache_creation_input_tokens": 12770, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 12770}, "type": "message"}], "speed": "standard", "fallback_credit": null}}}
|
||||
{"type": "assistant", "uuid": "101937b3-9a2e-4a6e-833c-1d34310f2baa", "parentUuid": "a1de7d53-4516-4df7-a26e-970daa23999e", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:06:49.263Z", "requestId": "req_011Ch2Q24xuPkankc3LBjUNp", "message": {"id": "msg_011Ch2Q25AJRyZVA8qwBVqme", "model": "claude-haiku-5-5", "role": "assistant", "type": "message", "content": [{"type": "tool_use", "name": "AskUserQuestion", "id": "toolu_01TCVWSwtMREECGQ6o93NCnV", "input": {}}], "stop_reason": "tool_use", "usage": {"input_tokens": 2, "cache_creation_input_tokens": 12770, "cache_read_input_tokens": 31983, "output_tokens": 194, "output_tokens_details": {"thinking_tokens": 63}, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": "standard", "cache_creation": {"ephemeral_1h_input_tokens": 12770, "ephemeral_5m_input_tokens": 0}, "inference_geo": "global", "iterations": [{"input_tokens": 2, "output_tokens": 194, "cache_read_input_tokens": 31983, "cache_creation_input_tokens": 12770, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 12770}, "type": "message"}], "speed": "standard", "fallback_credit": null}}}
|
||||
{"type": "user", "uuid": "9cca4968-7ef1-4636-ae53-5a484ab51863", "parentUuid": "101937b3-9a2e-4a6e-833c-1d34310f2baa", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:07:34.713Z", "message": {"role": "user", "content": "…"}}
|
||||
{"type": "assistant", "uuid": "97cfc91e-caa9-4c8d-a500-76104c7a9f04", "parentUuid": "ec108f22-b004-4cb2-bf8a-234a1f24b7e4", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:07:36.307Z", "requestId": "req_011Ch2Q5ZVDdRtYB7FpSUg2J", "message": {"id": "msg_011Ch2Q5Zm6JTaimsdDQLQrP", "model": "claude-haiku-5-5", "role": "assistant", "type": "message", "content": [{"type": "thinking", "thinking": "…"}], "stop_reason": "end_turn", "usage": {"input_tokens": 2, "cache_creation_input_tokens": 3873, "cache_read_input_tokens": 44753, "output_tokens": 164, "output_tokens_details": {"thinking_tokens": 76}, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": "standard", "cache_creation": {"ephemeral_1h_input_tokens": 3873, "ephemeral_5m_input_tokens": 0}, "inference_geo": "global", "iterations": [{"input_tokens": 2, "output_tokens": 164, "cache_read_input_tokens": 44753, "cache_creation_input_tokens": 3873, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 3873}, "type": "message"}], "speed": "standard", "fallback_credit": null}}}
|
||||
{"type": "assistant", "uuid": "a3724236-f427-4152-955f-bcdc82c9ced5", "parentUuid": "97cfc91e-caa9-4c8d-a500-76104c7a9f04", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:07:36.698Z", "requestId": "req_011Ch2Q5ZVDdRtYB7FpSUg2J", "message": {"id": "msg_011Ch2Q5Zm6JTaimsdDQLQrP", "model": "claude-haiku-5-5", "role": "assistant", "type": "message", "content": [{"type": "text", "text": "…"}], "stop_reason": "end_turn", "usage": {"input_tokens": 2, "cache_creation_input_tokens": 3873, "cache_read_input_tokens": 44753, "output_tokens": 164, "output_tokens_details": {"thinking_tokens": 76}, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": "standard", "cache_creation": {"ephemeral_1h_input_tokens": 3873, "ephemeral_5m_input_tokens": 0}, "inference_geo": "global", "iterations": [{"input_tokens": 2, "output_tokens": 164, "cache_read_input_tokens": 44753, "cache_creation_input_tokens": 3873, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 3873}, "type": "message"}], "speed": "standard", "fallback_credit": null}}}
|
||||
{"type": "user", "uuid": "d08997e4-60c7-477a-8405-be2bf7d31c46", "parentUuid": "306b7de8-c0c6-4ba1-89d1-70bcf5217126", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:08:04.783Z", "message": {"role": "user", "content": "…"}}
|
||||
{"type": "assistant", "uuid": "053219d4-5683-4e0a-adf5-91e9b5d3c104", "parentUuid": "600f4e46-49bc-4dcd-b2a5-19ea3ff4c465", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:08:07.829Z", "requestId": "req_011Ch2Q7ocqPJU3qfEPHbAr6", "message": {"id": "msg_011Ch2Q7oqUakBseEDos4cYs", "model": "claude-haiku-5-5", "role": "assistant", "type": "message", "content": [{"type": "tool_use", "name": "Bash", "id": "toolu_01RWJyz6BUXwPcU2j2znFmq5", "input": {}}], "stop_reason": "tool_use", "usage": {"input_tokens": 2, "cache_creation_input_tokens": 43, "cache_read_input_tokens": 48790, "output_tokens": 252, "output_tokens_details": {"thinking_tokens": 0}, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": "standard", "cache_creation": {"ephemeral_1h_input_tokens": 43, "ephemeral_5m_input_tokens": 0}, "inference_geo": "global", "iterations": [{"input_tokens": 2, "output_tokens": 252, "cache_read_input_tokens": 48790, "cache_creation_input_tokens": 43, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 43}, "type": "message"}], "speed": "standard", "fallback_credit": null}}}
|
||||
{"type": "assistant", "uuid": "4f77556b-3a2c-4b60-91ec-f3fb1965d8c3", "parentUuid": "053219d4-5683-4e0a-adf5-91e9b5d3c104", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:08:08.483Z", "requestId": "req_011Ch2Q7ocqPJU3qfEPHbAr6", "message": {"id": "msg_011Ch2Q7oqUakBseEDos4cYs", "model": "claude-haiku-5-5", "role": "assistant", "type": "message", "content": [{"type": "tool_use", "name": "Bash", "id": "toolu_015ZHJezTdAPV733czTubGD5", "input": {}}], "stop_reason": "tool_use", "usage": {"input_tokens": 2, "cache_creation_input_tokens": 43, "cache_read_input_tokens": 48790, "output_tokens": 252, "output_tokens_details": {"thinking_tokens": 0}, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": "standard", "cache_creation": {"ephemeral_1h_input_tokens": 43, "ephemeral_5m_input_tokens": 0}, "inference_geo": "global", "iterations": [{"input_tokens": 2, "output_tokens": 252, "cache_read_input_tokens": 48790, "cache_creation_input_tokens": 43, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 43}, "type": "message"}], "speed": "standard", "fallback_credit": null}}}
|
||||
{"type": "assistant", "uuid": "1db240ac-330d-4d97-8aad-d2f67e168a6f", "parentUuid": "4f77556b-3a2c-4b60-91ec-f3fb1965d8c3", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:08:08.489Z", "requestId": "req_011Ch2Q7ocqPJU3qfEPHbAr6", "message": {"id": "msg_011Ch2Q7oqUakBseEDos4cYs", "model": "claude-haiku-5-5", "role": "assistant", "type": "message", "content": [{"type": "tool_use", "name": "Bash", "id": "toolu_01RCpdfRJ5Fy1gygPm8kqvrC", "input": {}}], "stop_reason": "tool_use", "usage": {"input_tokens": 2, "cache_creation_input_tokens": 43, "cache_read_input_tokens": 48790, "output_tokens": 252, "output_tokens_details": {"thinking_tokens": 0}, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": "standard", "cache_creation": {"ephemeral_1h_input_tokens": 43, "ephemeral_5m_input_tokens": 0}, "inference_geo": "global", "iterations": [{"input_tokens": 2, "output_tokens": 252, "cache_read_input_tokens": 48790, "cache_creation_input_tokens": 43, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 43}, "type": "message"}], "speed": "standard", "fallback_credit": null}}}
|
||||
{"type": "user", "uuid": "77973920-f1a9-46ce-ac1b-99ed02ab7ff0", "parentUuid": "053219d4-5683-4e0a-adf5-91e9b5d3c104", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:11:46.819Z", "message": {"role": "user", "content": "…"}}
|
||||
{"type": "user", "uuid": "f48f0431-868e-43ad-9de9-fd5601502873", "parentUuid": "4f77556b-3a2c-4b60-91ec-f3fb1965d8c3", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:12:00.822Z", "message": {"role": "user", "content": "…"}}
|
||||
{"type": "user", "uuid": "f2f65ffb-bd31-43d7-b434-77c683247429", "parentUuid": "1db240ac-330d-4d97-8aad-d2f67e168a6f", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:12:47.129Z", "message": {"role": "user", "content": "…"}}
|
||||
{"type": "user", "uuid": "3703fb55-0d62-4e12-b2f1-2c1d7adadeb1", "parentUuid": "f2f65ffb-bd31-43d7-b434-77c683247429", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:12:47.129Z", "message": {"role": "user", "content": "…"}}
|
||||
{"type": "user", "uuid": "2d0ac504-43a6-40de-b0f2-1d9be0829dcc", "parentUuid": "e1509482-7971-4f9c-a92b-1915611c2098", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:14:26.597Z", "message": {"role": "user", "content": "…"}}
|
||||
{"type": "assistant", "uuid": "3fce53fc-e25c-4790-b9d0-b8631c6641a5", "parentUuid": "34c1df3e-3038-44dc-8852-beb9932372c4", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:14:28.165Z", "requestId": "req_011Ch2QbxYPKwsdMSvWASxpC", "message": {"id": "msg_011Ch2Qby39TeJ5WrPLH8FGv", "model": "claude-haiku-5-5", "role": "assistant", "type": "message", "content": [{"type": "thinking", "thinking": "…"}], "stop_reason": "tool_use", "usage": {"input_tokens": 2, "cache_creation_input_tokens": 596, "cache_read_input_tokens": 48833, "output_tokens": 124, "output_tokens_details": {"thinking_tokens": 40}, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": "standard", "cache_creation": {"ephemeral_1h_input_tokens": 596, "ephemeral_5m_input_tokens": 0}, "inference_geo": "global", "iterations": [{"input_tokens": 2, "output_tokens": 124, "cache_read_input_tokens": 48833, "cache_creation_input_tokens": 596, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 596}, "type": "message"}], "speed": "standard", "fallback_credit": null}}}
|
||||
{"type": "assistant", "uuid": "251c79d2-42cb-4318-8bce-2d5a4f7c72d2", "parentUuid": "3fce53fc-e25c-4790-b9d0-b8631c6641a5", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:14:28.238Z", "requestId": "req_011Ch2QbxYPKwsdMSvWASxpC", "message": {"id": "msg_011Ch2Qby39TeJ5WrPLH8FGv", "model": "claude-haiku-5-5", "role": "assistant", "type": "message", "content": [{"type": "tool_use", "name": "Bash", "id": "toolu_01BKmkrAhc1MxrpUeG51ykY8", "input": {}}], "stop_reason": "tool_use", "usage": {"input_tokens": 2, "cache_creation_input_tokens": 596, "cache_read_input_tokens": 48833, "output_tokens": 124, "output_tokens_details": {"thinking_tokens": 40}, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": "standard", "cache_creation": {"ephemeral_1h_input_tokens": 596, "ephemeral_5m_input_tokens": 0}, "inference_geo": "global", "iterations": [{"input_tokens": 2, "output_tokens": 124, "cache_read_input_tokens": 48833, "cache_creation_input_tokens": 596, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 596}, "type": "message"}], "speed": "standard", "fallback_credit": null}}}
|
||||
{"type": "user", "uuid": "5412ec29-5319-489e-88a4-830bb5db1c65", "parentUuid": "251c79d2-42cb-4318-8bce-2d5a4f7c72d2", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:14:28.975Z", "message": {"role": "user", "content": "…"}}
|
||||
{"type": "assistant", "uuid": "e458165b-cd63-4654-9d37-56f0efe02d20", "parentUuid": "5edbdd48-ddfa-43f2-b8d6-70f4127278b7", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:14:30.381Z", "requestId": "req_011Ch2Qc6f3i7Vr64kFD2tPL", "message": {"id": "msg_011Ch2Qc6tRh9C63e1G5mLx6", "model": "claude-haiku-5-5", "role": "assistant", "type": "message", "content": [{"type": "tool_use", "name": "Bash", "id": "toolu_01SzRBf4DkBdrSqtDqr3WN1Z", "input": {}}], "stop_reason": "tool_use", "usage": {"input_tokens": 2, "cache_creation_input_tokens": 163, "cache_read_input_tokens": 49429, "output_tokens": 83, "output_tokens_details": {"thinking_tokens": 0}, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": "standard", "cache_creation": {"ephemeral_1h_input_tokens": 163, "ephemeral_5m_input_tokens": 0}, "inference_geo": "global", "iterations": [{"input_tokens": 2, "output_tokens": 83, "cache_read_input_tokens": 49429, "cache_creation_input_tokens": 163, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 163}, "type": "message"}], "speed": "standard", "fallback_credit": null}}}
|
||||
{"type": "user", "uuid": "bc55f7a8-c3db-4c75-b00b-7b744a10aa8a", "parentUuid": "e458165b-cd63-4654-9d37-56f0efe02d20", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:14:31.078Z", "message": {"role": "user", "content": "…"}}
|
||||
{"type": "assistant", "uuid": "5c69bbb0-c0fe-4725-bcb1-ecdca11a5056", "parentUuid": "8c42a39f-ca23-46f9-b822-c8c12b85655a", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:14:32.446Z", "requestId": "req_011Ch2QcFe2zcaFAKFvkHC45", "message": {"id": "msg_011Ch2QcFrBuBvcyMNvSFDJT", "model": "claude-haiku-5-5", "role": "assistant", "type": "message", "content": [{"type": "text", "text": "…"}], "stop_reason": "end_turn", "usage": {"input_tokens": 2, "cache_creation_input_tokens": 122, "cache_read_input_tokens": 49592, "output_tokens": 39, "output_tokens_details": {"thinking_tokens": 0}, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": "standard", "cache_creation": {"ephemeral_1h_input_tokens": 122, "ephemeral_5m_input_tokens": 0}, "inference_geo": "global", "iterations": [{"input_tokens": 2, "output_tokens": 39, "cache_read_input_tokens": 49592, "cache_creation_input_tokens": 122, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 122}, "type": "message"}], "speed": "standard", "fallback_credit": null}}}
|
||||
{"type": "user", "uuid": "2409a3e9-9534-4916-b3aa-ba793052c765", "parentUuid": "5c69bbb0-c0fe-4725-bcb1-ecdca11a5056", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:14:32.853Z", "message": {"role": "user", "content": "…"}}
|
||||
{"type": "assistant", "uuid": "3dad0194-f63a-4908-8aa9-5517e854e72a", "parentUuid": "eee833c6-b008-4713-8f1c-710dedf2d865", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:14:37.644Z", "requestId": "req_011Ch2QcPTqZSdTitPM9wRxn", "message": {"id": "msg_011Ch2QcPgihdGyGQMoTuGJm", "model": "claude-haiku-5-5", "role": "assistant", "type": "message", "content": [{"type": "thinking", "thinking": "…"}], "stop_reason": "end_turn", "usage": {"input_tokens": 2, "cache_creation_input_tokens": 293, "cache_read_input_tokens": 49714, "output_tokens": 1047, "output_tokens_details": {"thinking_tokens": 735}, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": "standard", "cache_creation": {"ephemeral_1h_input_tokens": 293, "ephemeral_5m_input_tokens": 0}, "inference_geo": "global", "iterations": [{"input_tokens": 2, "output_tokens": 1047, "cache_read_input_tokens": 49714, "cache_creation_input_tokens": 293, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 293}, "type": "message"}], "speed": "standard", "fallback_credit": null}}}
|
||||
{"type": "assistant", "uuid": "65b51d80-0d16-445f-8abd-fcb1865a498b", "parentUuid": "3dad0194-f63a-4908-8aa9-5517e854e72a", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:14:38.953Z", "requestId": "req_011Ch2QcPTqZSdTitPM9wRxn", "message": {"id": "msg_011Ch2QcPgihdGyGQMoTuGJm", "model": "claude-haiku-5-5", "role": "assistant", "type": "message", "content": [{"type": "text", "text": "…"}], "stop_reason": "end_turn", "usage": {"input_tokens": 2, "cache_creation_input_tokens": 293, "cache_read_input_tokens": 49714, "output_tokens": 1047, "output_tokens_details": {"thinking_tokens": 735}, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": "standard", "cache_creation": {"ephemeral_1h_input_tokens": 293, "ephemeral_5m_input_tokens": 0}, "inference_geo": "global", "iterations": [{"input_tokens": 2, "output_tokens": 1047, "cache_read_input_tokens": 49714, "cache_creation_input_tokens": 293, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 293}, "type": "message"}], "speed": "standard", "fallback_credit": null}}}
|
||||
{"type": "user", "uuid": "917e2117-854c-4219-977f-1719697c62b2", "parentUuid": "65b51d80-0d16-445f-8abd-fcb1865a498b", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:14:39.356Z", "message": {"role": "user", "content": "…"}}
|
||||
{"type": "assistant", "uuid": "4056d593-958d-4e44-b578-70e3a270d386", "parentUuid": "067d666a-d156-4e2c-8e1a-1941e9664843", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:14:41.105Z", "requestId": "req_011Ch2Qcs6VsrAExG68M2gvc", "message": {"id": "msg_011Ch2QcsK922mGXJtd6NkyM", "model": "claude-haiku-5-5", "role": "assistant", "type": "message", "content": [{"type": "thinking", "thinking": "…"}], "stop_reason": "end_turn", "usage": {"input_tokens": 2, "cache_creation_input_tokens": 1301, "cache_read_input_tokens": 50007, "output_tokens": 329, "output_tokens_details": {"thinking_tokens": 81}, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": "standard", "cache_creation": {"ephemeral_1h_input_tokens": 1301, "ephemeral_5m_input_tokens": 0}, "inference_geo": "global", "iterations": [{"input_tokens": 2, "output_tokens": 329, "cache_read_input_tokens": 50007, "cache_creation_input_tokens": 1301, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 1301}, "type": "message"}], "speed": "standard", "fallback_credit": null}}}
|
||||
{"type": "assistant", "uuid": "240275df-0612-43db-b650-d896340388c8", "parentUuid": "4056d593-958d-4e44-b578-70e3a270d386", "sessionId": "e96536c6-f9ba-49d2-bf73-4d57ba125f64", "timestamp": "2026-11-14T07:14:42.347Z", "requestId": "req_011Ch2Qcs6VsrAExG68M2gvc", "message": {"id": "msg_011Ch2QcsK922mGXJtd6NkyM", "model": "claude-haiku-5-5", "role": "assistant", "type": "message", "content": [{"type": "text", "text": "…"}], "stop_reason": "end_turn", "usage": {"input_tokens": 2, "cache_creation_input_tokens": 1301, "cache_read_input_tokens": 50007, "output_tokens": 329, "output_tokens_details": {"thinking_tokens": 81}, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": "standard", "cache_creation": {"ephemeral_1h_input_tokens": 1301, "ephemeral_5m_input_tokens": 0}, "inference_geo": "global", "iterations": [{"input_tokens": 2, "output_tokens": 329, "cache_read_input_tokens": 50007, "cache_creation_input_tokens": 1301, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 1301}, "type": "message"}], "speed": "standard", "fallback_credit": null}}}
|
||||
@ -0,0 +1,10 @@
|
||||
{
|
||||
"session_id": "e96536c6-f9ba-49d2-bf73-4d57ba125f64",
|
||||
"transcript_path": "/Users/mock/.claude/projects/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64.jsonl",
|
||||
"cwd": "/Users/mock/.peppa-dev/workspaces/live",
|
||||
"scratchpad_dir": "/private/tmp/claude-501/-Users-mock--peppa-dev-workspaces-live/e96536c6-f9ba-49d2-bf73-4d57ba125f64/scratchpad",
|
||||
"prompt_id": "2566d5ad-f4dc-489b-8aa6-8ff1730a023c",
|
||||
"permission_mode": "default",
|
||||
"hook_event_name": "UserPromptSubmit",
|
||||
"prompt": "Работай над стори LIVE-1 по правилам AGENTS.md.\n\nЭТО ТЕСТ ХУКОВ ПЕППЫ, не настоящая работа. Не вызывай MCP peppa и не трогай OpenSpec. Строго по шагам, каждый шаг отдельным вызовом инструмента: (1) инструмент AskUserQuestion: вопрос «Какой язык?», header «Язык», варианты «Go» и «Rust»; если вопрос не удался — закончи ход и жди ответа следующим сообщением, остальные шаги сделаешь после ответа. (2) Bash: ls /nonexistent-peppa (3) Bash: touch two.txt (4) Bash: touch three.txt (5) ответь одной строкой: язык и какие шаги удались. Если тебя попросят продолжать — ответь «жду» и закончи ход."
|
||||
}
|
||||
@ -134,7 +134,8 @@ function fireStatusLine(payload: Record<string, unknown>): Promise<string | null
|
||||
log("statusline", { line });
|
||||
resolve(line);
|
||||
});
|
||||
p.stdin.end(JSON.stringify({ hook_event_name: "Status", session_id: conversationId, transcript_path: transcriptPath, cwd, ...payload }));
|
||||
// Live 2.1.323 (fixtures/claude-live/statusline.json): no hook_event_name.
|
||||
p.stdin.end(JSON.stringify({ session_id: conversationId, transcript_path: transcriptPath, cwd, version: "2.1.323-mock", ...payload }));
|
||||
});
|
||||
}
|
||||
|
||||
@ -195,8 +196,10 @@ function onInput(chunk: string) {
|
||||
process.exit(130);
|
||||
}
|
||||
if (mode === "dialog" && dialogResolve) {
|
||||
const key = chunk.replace(/\x1b\[20[01]~/g, "").trim()[0];
|
||||
if (key && "123".includes(key)) {
|
||||
const clean = chunk.replace(/\x1b\[20[01]~/g, "");
|
||||
// Escape alone cancels the dialog (= No); "1".."4" pick a menu line.
|
||||
const key = clean === "\x1b" ? "esc" : clean.trim()[0];
|
||||
if (key && ["1", "2", "3", "4", "esc"].includes(key)) {
|
||||
const r = dialogResolve;
|
||||
dialogResolve = null;
|
||||
r(key);
|
||||
@ -257,10 +260,13 @@ async function run(action: Action): Promise<boolean> {
|
||||
} else if ("usage" in action) {
|
||||
const u = action.usage;
|
||||
const model = u.model ?? "claude-sonnet-4-5";
|
||||
appendFileSync(
|
||||
transcriptPath,
|
||||
`${JSON.stringify({ type: "assistant", sessionId: conversationId, message: { id: `msg_${randomUUID()}`, model, role: "assistant", content: [{ type: "text", text: "…" }], usage: { input_tokens: u.input ?? 0, output_tokens: u.output ?? 0, cache_read_input_tokens: u.cacheRead ?? 0, cache_creation_input_tokens: u.cacheWrite ?? 0 } } })}\n`,
|
||||
);
|
||||
// Like the live CLI (fixtures/claude-live/transcript.jsonl): one entry per content block,
|
||||
// every entry of the message repeats its id and usage.
|
||||
const id = `msg_${randomUUID()}`;
|
||||
const usage = { input_tokens: u.input ?? 0, output_tokens: u.output ?? 0, cache_read_input_tokens: u.cacheRead ?? 0, cache_creation_input_tokens: u.cacheWrite ?? 0 };
|
||||
for (const block of [{ type: "thinking", thinking: "…" }, { type: "text", text: "…" }]) {
|
||||
appendFileSync(transcriptPath, `${JSON.stringify({ type: "assistant", sessionId: conversationId, message: { id, model, role: "assistant", type: "message", content: [block], usage } })}\n`);
|
||||
}
|
||||
if (provider === "claude") {
|
||||
const resets = Math.floor(Date.now() / 1000) + (u.resetInSec ?? 3600);
|
||||
const rate_limits: Record<string, unknown> = {};
|
||||
@ -269,7 +275,8 @@ async function run(action: Action): Promise<boolean> {
|
||||
await fireStatusLine({
|
||||
model: { id: model, display_name: model },
|
||||
...(u.costUsd != null ? { cost: { total_cost_usd: u.costUsd, total_duration_ms: 1000 } } : {}),
|
||||
...(u.context ? { context_window: { context_window_size: u.context.size, current_usage: { input_tokens: u.context.used, output_tokens: 0, cache_creation_input_tokens: 0, cache_read_input_tokens: 0 } } } : {}),
|
||||
// total_*_tokens are the last request, not session totals (live 2.1.323).
|
||||
...(u.context ? { context_window: { total_input_tokens: u.context.used, total_output_tokens: u.output ?? 0, context_window_size: u.context.size, current_usage: { input_tokens: u.context.used, output_tokens: u.output ?? 0, cache_creation_input_tokens: 0, cache_read_input_tokens: 0 }, used_percentage: Math.round((u.context.used / u.context.size) * 100) } } : {}),
|
||||
...(Object.keys(rate_limits).length ? { rate_limits } : {}),
|
||||
});
|
||||
}
|
||||
@ -280,24 +287,30 @@ async function run(action: Action): Promise<boolean> {
|
||||
} else if ("permission" in action) {
|
||||
if (provider !== "claude") return true;
|
||||
const { tool, input } = action.permission;
|
||||
const res = await fireHook("PermissionRequest", { tool_name: tool, tool_input: input, permission_suggestions: [{ type: "addRules", rules: [{ toolName: tool }], behavior: "allow", destination: "localSettings" }] }, tool);
|
||||
const res = await fireHook("PermissionRequest", { tool_name: tool, tool_input: input, permission_suggestions: [{ type: "addDirectories", directories: [cwd], destination: "session" }] }, tool);
|
||||
const decision = res?.hookSpecificOutput?.decision;
|
||||
if (decision) {
|
||||
log("permission", { tool, via: "hook", behavior: decision.behavior, updatedPermissions: !!decision.updatedPermissions, message: decision.message });
|
||||
out(`⏺ ${tool} ${decision.behavior === "allow" ? "allowed" : "denied"} by hook\n`);
|
||||
} else {
|
||||
out(`\n Do you want to proceed?\n ❯ 1. Yes\n 2. Yes, and don't ask again for ${tool}\n 3. No, and tell Claude what to do differently (esc)\n`);
|
||||
await fireHook("Notification", { message: `Claude needs your permission to use ${tool}`, notification_type: "permission_prompt" }, "permission_prompt");
|
||||
// The menu of Claude Code 2.1.323 (PEP-3, captured live): the "No" line is the 4th.
|
||||
out(`\n Do you want to proceed?\n ❯ 1. Yes\n 2. Yes, and always allow access to ${cwd} from this project\n 3. Yes, and switch to auto mode · auto mode handles these prompts for you\n 4. No\n\n Esc to cancel · Tab to amend\n`);
|
||||
await fireHook("Notification", { message: "Claude needs your permission", notification_type: "permission_prompt" }, "permission_prompt");
|
||||
const key = await dialog();
|
||||
mode = "busy";
|
||||
const behavior = key === "3" ? "deny" : "allow";
|
||||
log("permission", { tool, via: "terminal", key, behavior });
|
||||
out(`⏺ ${tool} ${behavior === "allow" ? "allowed" : "denied"} in terminal (${key})\n`);
|
||||
const behavior = key === "4" || key === "esc" ? "deny" : "allow";
|
||||
log("permission", { tool, via: "terminal", key, behavior, ...(key === "3" ? { mode: "auto" } : {}) });
|
||||
if (behavior === "deny") {
|
||||
// Live 2.1.323: "No" interrupts the turn — no Stop hook, the prompt waits for the user.
|
||||
out(` ⎿ Interrupted · What should Claude do instead?\n`);
|
||||
return false;
|
||||
}
|
||||
out(`⏺ ${tool} allowed in terminal (${key})\n`);
|
||||
}
|
||||
} else if ("ask" in action) {
|
||||
if (provider !== "claude") return true;
|
||||
const questions = action.ask.map((q) => ({ question: q.question, header: "Q", options: (q.options ?? []).map((label) => ({ label })), multiSelect: false }));
|
||||
const res = await fireHook("PreToolUse", { tool_name: "AskUserQuestion", tool_input: { questions } }, "AskUserQuestion");
|
||||
const questions = action.ask.map((q) => ({ question: q.question, header: "Q", options: (q.options ?? []).map((label) => ({ label, description: label })), multiSelect: false }));
|
||||
const res = await fireHook("PreToolUse", { tool_name: "AskUserQuestion", tool_input: { questions }, tool_use_id: `toolu_${randomUUID()}` }, "AskUserQuestion");
|
||||
const h = res?.hookSpecificOutput;
|
||||
if (h?.permissionDecision === "allow" && h.updatedInput?.answers) {
|
||||
log("ask", { via: "hook", answers: h.updatedInput.answers });
|
||||
@ -319,7 +332,9 @@ async function run(action: Action): Promise<boolean> {
|
||||
const when = spec.reset === "unknown" ? "" : at ? ` resets at ${at}` : " resets 5pm";
|
||||
if (provider === "claude") {
|
||||
out(`⎿ Claude usage limit reached.${when ? ` Your limit${when.replace(" resets", " will reset")}.` : ""}\n`);
|
||||
await fireHook("StopFailure", { error: "rate_limit", error_details: `Usage limit reached${when ? `,${when}` : ""}`, last_assistant_message: lastMessage }, "rate_limit");
|
||||
// Per the hooks docs, last_assistant_message of StopFailure is the API error text, not
|
||||
// Claude's output; error_details is optional and its live wording is unverified (PEP-3).
|
||||
await fireHook("StopFailure", { error: "rate_limit", error_details: `Usage limit reached${when ? `,${when}` : ""}`, last_assistant_message: `API Error: Claude usage limit reached.${when ? ` Your limit${when.replace(" resets", " will reset")}.` : ""}` }, "rate_limit");
|
||||
} else {
|
||||
out(`■ You've hit your usage limit.${spec.reset === "unknown" ? "" : ` Try again at ${at ?? "5:00 PM"}.`}\n`);
|
||||
}
|
||||
|
||||
196
packages/testkit/test/claude-live.test.ts
Normal file
196
packages/testkit/test/claude-live.test.ts
Normal file
@ -0,0 +1,196 @@
|
||||
// PEP-3: the contract of the live Claude Code CLI (2.1.323), captured on the dev stand with
|
||||
// PEPPA_HOOK_CAPTURE_DIR (fixtures/claude-live/*). The real peppa-hook is replayed on those
|
||||
// payloads, statusLine/transcript are parsed from them, and the permission dialog keys are
|
||||
// read off the menus the live TUI drew.
|
||||
import assert from "node:assert/strict";
|
||||
import { spawn } from "node:child_process";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { after, describe, test } from "node:test";
|
||||
import { events } from "@peppa/db";
|
||||
import { asc, eq } from "drizzle-orm";
|
||||
import { core, db, project, runner, teardown, waitFor } from "./helpers.ts";
|
||||
|
||||
after(teardown);
|
||||
|
||||
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
|
||||
const FIX = join(ROOT, "packages/testkit/fixtures/claude-live");
|
||||
const fixture = (name: string) => JSON.parse(readFileSync(join(FIX, `${name}.json`), "utf8")) as Record<string, any>;
|
||||
const PM = "telegram" as const;
|
||||
|
||||
/** Runs the real peppa-hook like Claude Code does: payload on stdin, JSON (maybe) on stdout. */
|
||||
function hook(event: string, payload: unknown, sessionId: number, generation: number): Promise<any> {
|
||||
return new Promise((done) => {
|
||||
const p = spawn(join(ROOT, "packages/runner/bin/peppa-hook"), [event], {
|
||||
env: { ...process.env, PEPPA_SESSION_ID: String(sessionId), PEPPA_GENERATION: String(generation) },
|
||||
stdio: ["pipe", "pipe", "inherit"],
|
||||
});
|
||||
let out = "";
|
||||
p.stdout.on("data", (d) => (out += d));
|
||||
p.on("close", (code) => {
|
||||
assert.equal(code, 0);
|
||||
done(out.trim() ? JSON.parse(out) : null);
|
||||
});
|
||||
p.stdin.end(JSON.stringify(payload));
|
||||
});
|
||||
}
|
||||
|
||||
describe("Живой Claude Code: statusLine и transcript", () => {
|
||||
test("statusLine 2.1.323: стоимость, контекст, окна; total_*_tokens — не сумма за сессию", () => {
|
||||
const raw = fixture("statusline");
|
||||
const d = core.parseStatusLine(raw);
|
||||
assert.equal(d.costUsd, raw.cost.total_cost_usd);
|
||||
const cu = raw.context_window.current_usage;
|
||||
const used = cu.input_tokens + cu.cache_read_input_tokens + cu.cache_creation_input_tokens;
|
||||
assert.equal(used, raw.context_window.total_input_tokens, "total_input_tokens = the last request's context");
|
||||
assert.deepEqual(d.context, { used, size: raw.context_window.context_window_size, pct: raw.context_window.used_percentage });
|
||||
assert.equal(d.tokens, undefined, "session tokens come from the transcript, not from the status line");
|
||||
assert.deepEqual(d.windows.fiveHour, { pct: raw.rate_limits.five_hour.used_percentage, resetsAt: raw.rate_limits.five_hour.resets_at * 1000 });
|
||||
assert.deepEqual(d.windows.sevenDay, { pct: raw.rate_limits.seven_day.used_percentage, resetsAt: raw.rate_limits.seven_day.resets_at * 1000 });
|
||||
assert.equal(d.model, raw.model.id);
|
||||
});
|
||||
|
||||
test("statusLine до первого ответа API: current_usage null, rate_limits нет", () => {
|
||||
const d = core.parseStatusLine(fixture("statusline-first"));
|
||||
assert.equal(d.context, undefined);
|
||||
assert.deepEqual(d.windows, {});
|
||||
assert.equal(d.costUsd, 0);
|
||||
});
|
||||
|
||||
test("transcript: одно сообщение — несколько записей с тем же id и usage", () => {
|
||||
const path = join(FIX, "transcript.jsonl");
|
||||
const byId = new Map<string, any>();
|
||||
for (const line of readFileSync(path, "utf8").trim().split("\n")) {
|
||||
const e = JSON.parse(line);
|
||||
if (e.type === "assistant") byId.set(e.message.id, e.message.usage);
|
||||
}
|
||||
const sum = (k: string) => [...byId.values()].reduce((a, u) => a + u[k], 0);
|
||||
const u = core.transcriptUsage(path)!;
|
||||
assert.deepEqual(u.tokens, { input: sum("input_tokens"), output: sum("output_tokens"), cacheRead: sum("cache_read_input_tokens"), cacheWrite: sum("cache_creation_input_tokens") });
|
||||
assert.equal(u.model, "claude-haiku-5-5");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Живой Claude Code: диалог разрешений", () => {
|
||||
// Menus as the live TUI drew them (tmux capture-pane), all three seen in one session.
|
||||
const menu = (...opts: string[]) =>
|
||||
[" Bash command", "", " touch two.txt", "", " Do you want to proceed?", ...opts.map((o, i) => `${i ? " " : " ❯ "}${i + 1}. ${o}`), "", " Esc to cancel · Tab to amend"].join("\n");
|
||||
const full = menu("Yes", "Yes, and always allow access to /w/live from this project", "Yes, and switch to auto mode · auto mode handles these prompts for you", "No");
|
||||
const noAlways = menu("Yes", "Yes, and switch to auto mode · auto mode handles these prompts for you", "No");
|
||||
const noAuto = menu("Yes", "Yes, and don't ask again for peppa — Get Task commands in /w/live", "No");
|
||||
|
||||
test("клавиша читается с экрана: «No» не всегда 3, «2» не всегда «всегда»", () => {
|
||||
const k = runner.permissionKey;
|
||||
assert.deepEqual(["allow", "always", "deny"].map((a) => k(full, a)), ["1", "2", "4"]);
|
||||
// No "always" line: "2" would switch the session to auto mode — answer plain "Yes".
|
||||
assert.deepEqual(["allow", "always", "deny"].map((a) => k(noAlways, a)), ["1", "1", "3"]);
|
||||
assert.deepEqual(["allow", "always", "deny"].map((a) => k(noAuto, a)), ["1", "2", "3"]);
|
||||
// No dialog on the screen: Yes / Yes / Escape (cancel), never a guessed number for deny.
|
||||
assert.deepEqual(["allow", "always", "deny"].map((a) => k("❯ ", a)), ["1", "1", "Escape"]);
|
||||
assert.equal(k(full, "можно, но аккуратно"), null);
|
||||
// The last dialog wins when an old one is still in the scrollback.
|
||||
assert.equal(k(`${noAlways}\n\n${full}`, "deny"), "4");
|
||||
});
|
||||
|
||||
for (const [answer, key] of [
|
||||
["allow", "1"],
|
||||
["always", "2"],
|
||||
["deny", "4"],
|
||||
] as const) {
|
||||
test(`нет ответа вовремя → диалог в терминале; поздний «${answer}» жмёт «${key}»`, async () => {
|
||||
const p = await project({ turns: [[{ permission: { tool: "Bash", input: { command: "touch two.txt" } } }, { say: "Создал." }]] });
|
||||
const sid = await p.start();
|
||||
const q = await p.waitQuestion(sid, "permission");
|
||||
await waitFor("hook released", async () => !(await core.getQuestion(db, q.id)).awaitingHook, 15000);
|
||||
await p.waitLog("dialog drawn", (e) => e.ev === "dialog");
|
||||
assert.ok((await runner.answerAndDeliver(db, q.id, answer, PM)).delivered);
|
||||
const e = await p.waitLog("decision in terminal", (x) => x.ev === "permission");
|
||||
assert.equal(e.via, "terminal");
|
||||
assert.equal(e.key, key);
|
||||
assert.equal(e.mode, undefined, "never switches the session to auto mode");
|
||||
if (answer === "deny") {
|
||||
// Live: "No" interrupts the turn without a Stop hook — Peppa tells the agent why.
|
||||
const note = await p.waitLog("deny note typed", (x) => x.ev === "prompt" && String(x.prompt).startsWith("PM запретил"));
|
||||
assert.equal(note.prompt, runner.PERMISSION_DENIED_NOTE);
|
||||
assert.equal(p.log().some((x) => x.ev === "action" && JSON.stringify(x.action).includes("Создал")), false);
|
||||
} else await p.waitLog("turn went on", (x) => x.ev === "action" && JSON.stringify(x.action).includes("Создал"));
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
describe("Живой Claude Code: peppa-hook на снятых payload'ах", () => {
|
||||
test("SessionStart, Notification, PostToolUse(Failure), SessionEnd", async () => {
|
||||
const p = await project({ turns: [[{ sleep: 60_000 }]] });
|
||||
const sid = await p.start();
|
||||
await p.waitLog("mock started", (e) => e.ev === "prompt");
|
||||
const s = await p.session(sid);
|
||||
|
||||
const start = fixture("session-start");
|
||||
await hook("session-start", start, sid, s.generation);
|
||||
assert.equal((await p.session(sid)).conversationId, start.session_id);
|
||||
|
||||
await hook("notification", fixture("notification-permission-prompt"), sid, s.generation);
|
||||
await hook("tool-use", fixture("post-tool-use"), sid, s.generation);
|
||||
await hook("tool-use", fixture("post-tool-use-failure"), sid, s.generation);
|
||||
await hook("session-end", fixture("session-end"), sid, s.generation);
|
||||
|
||||
const evs = (await db.select().from(events).where(eq(events.sessionId, sid)).orderBy(asc(events.id))).map((e) => ({ type: e.type, payload: e.payload as Record<string, any> }));
|
||||
assert.deepEqual(evs.find((e) => e.type === "notification")?.payload, { type: "permission_prompt", message: "Claude needs your permission" });
|
||||
const steps = evs.filter((e) => e.type === "step").map((e) => [e.payload.text, e.payload.ok]);
|
||||
assert.deepEqual(steps, [
|
||||
["touch two.txt", true],
|
||||
["ls /nonexistent-peppa", false],
|
||||
]);
|
||||
assert.equal(evs.find((e) => e.type === "claude_session_end")?.payload.reason, "prompt_input_exit");
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
|
||||
test("PermissionRequest: «Всегда» возвращает permission_suggestions живого CLI", async () => {
|
||||
const p = await project({ turns: [[{ sleep: 60_000 }]] });
|
||||
const sid = await p.start();
|
||||
const s = await p.session(sid);
|
||||
const raw = fixture("permission-request");
|
||||
const out = hook("permission-request", raw, sid, s.generation);
|
||||
const q = await p.waitQuestion(sid, "permission");
|
||||
assert.match(q.text, /touch two\.txt/);
|
||||
await runner.answerAndDeliver(db, q.id, "always", PM);
|
||||
assert.deepEqual(await out, {
|
||||
hookSpecificOutput: { hookEventName: "PermissionRequest", decision: { behavior: "allow", updatedPermissions: raw.permission_suggestions } },
|
||||
});
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
|
||||
test("PreToolUse AskUserQuestion: ответ PM уходит в updatedInput.answers", async () => {
|
||||
const p = await project({ turns: [[{ sleep: 60_000 }]] });
|
||||
const sid = await p.start();
|
||||
const s = await p.session(sid);
|
||||
const raw = fixture("pre-tool-use-ask-user-question");
|
||||
const out = hook("ask-question", raw, sid, s.generation);
|
||||
const q = await p.waitQuestion(sid, "question");
|
||||
assert.deepEqual(q.options, ["Go", "Rust"]);
|
||||
await runner.answerAndDeliver(db, q.id, "Go", PM);
|
||||
const res = await out;
|
||||
assert.equal(res.hookSpecificOutput.permissionDecision, "allow");
|
||||
assert.deepEqual(res.hookSpecificOutput.updatedInput, { ...raw.tool_input, answers: { "Какой язык?": "Go" } });
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
|
||||
test("Stop: стори в работе → decision block; после двух — PM", async () => {
|
||||
const p = await project({ turns: [[{ sleep: 60_000 }]] });
|
||||
const sid = await p.start();
|
||||
await p.waitLog("mock started", (e) => e.ev === "prompt");
|
||||
await core.updateTask(db, await core.resolveTask(db, p.taskKey), { status: "in_progress" });
|
||||
const s = await p.session(sid);
|
||||
const stop = fixture("stop");
|
||||
const first = await hook("stop", stop, sid, s.generation);
|
||||
assert.equal(first.decision, "block");
|
||||
assert.match(first.reason, new RegExp(p.taskKey));
|
||||
assert.equal((await hook("stop", fixture("stop-after-block"), sid, s.generation)).decision, "block");
|
||||
assert.equal(await hook("stop", fixture("stop-after-block"), sid, s.generation), null);
|
||||
const q = await p.waitQuestion(sid, "attention");
|
||||
assert.equal(q.text, fixture("stop-after-block").last_assistant_message);
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user