From 11778d98bde6e9b7140fedec189c2376cf833862 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sat, 14 Nov 2026 03:17:12 +0500 Subject: [PATCH 1/5] PEP-67: OpenSpec change pep-67-subscriptions Co-Authored-By: Claude Opus 5.5 --- .../changes/pep-67-subscriptions/design.md | 113 ++++++++++++++++++ .../changes/pep-67-subscriptions/proposal.md | 50 ++++++++ .../specs/agent-credentials/spec.md | 110 +++++++++++++++++ .../specs/web-workspace/spec.md | 18 +++ .../changes/pep-67-subscriptions/tasks.md | 26 ++++ 5 files changed, 317 insertions(+) create mode 100644 openspec/changes/pep-67-subscriptions/design.md create mode 100644 openspec/changes/pep-67-subscriptions/proposal.md create mode 100644 openspec/changes/pep-67-subscriptions/specs/agent-credentials/spec.md create mode 100644 openspec/changes/pep-67-subscriptions/specs/web-workspace/spec.md create mode 100644 openspec/changes/pep-67-subscriptions/tasks.md diff --git a/openspec/changes/pep-67-subscriptions/design.md b/openspec/changes/pep-67-subscriptions/design.md new file mode 100644 index 00000000..824bce3c --- /dev/null +++ b/openspec/changes/pep-67-subscriptions/design.md @@ -0,0 +1,113 @@ +# Design: PEP-67 — подписки + +## Суперадмин +`isSuperadmin(db, user)` (core/access.ts) = логин в `platformAdmins(db)` (`platform.admins`, +по умолчанию allowlist). Отдельную настройку `platform.superadmins` пока не заводим: сейчас +это одни и те же люди (asel, admin), а получатели алертов и права — одна роль «админ +платформы». Отделить можно позже, поменяв только тело helper'а. Тот же helper делает PEP-68 — +при слиянии остаётся один. + +Доступ: страница `/subscriptions` вызывает `notFound()` для не-суперадмина; все server +actions подписок проверяют `requireSuperadmin()` (иначе ошибка «Не найдено»). + +## Модель данных +- `subscriptions`: `provider` (claude|codex|opencode), `name`, `auth_kind` + (oauth|api_key|device), `secret_enc` (токен Claude / ключ OpenCode, AES-GCM `encrypt`), + `opencode_provider` (anthropic|openai|openrouter — какой env-ключ отдать), `status` + (pending|active|limited|auth_error), `limited_until`, `last_error`, `checked_at`, + `created_by` → users, `created_at`. +- `subscription_pools` (`name` уникальное, `created_by`), `subscription_pool_members` + (pool_id, subscription_id — PK, каскад). +- `projects.subscription_pool_id` → пулы (`set null`), `sessions.subscription_id` → + подписки (`set null`), `sessions.provider` += `opencode` (enum только в TS). +- Колонки `users.claude_token_enc/_set_at` остаются в схеме (дроп колонки в SQLite — + пересоздание таблицы, рискованно рядом с параллельными миграциями), но миграция их + обнуляет после переноса и код их больше не читает. + +### Миграция данных +Для каждого пользователя с `claude_token_enc`: подписка Claude «Claude — » +(`auth_kind=oauth`, тот же шифротекст — ключ тот же), пул «Claude — » с ней, и этот +пул — по умолчанию у проектов, где пользователь владелец. Так сессии его проектов после +миграции работают на той же подписке, что и раньше. Затем токен у пользователя обнуляется. + +## Где хранится вход Codex / OpenCode +Codex держит вход (ChatGPT OAuth с обновлением токена или ключ) в `$CODEX_HOME/auth.json` +и сам его обновляет, поэтому зашифрованная копия в БД быстро устареет. Решение: у каждой +подписки Codex свой каталог `$PEPPA_HOME/subscriptions/s/codex` (права 0700), так же +как сам Codex хранит `~/.codex`. API-ключ Codex тоже уходит туда через +`codex login --with-api-key` (ключ на stdin, в argv и логи не попадает), в БД ключ не +храним. Удаление подписки удаляет каталог. + +OpenCode — подписка только по API-ключу провайдера модели: ключ зашифрован в БД и при +запуске отдаётся как `ANTHROPIC_API_KEY` / `OPENAI_API_KEY` / `OPENROUTER_API_KEY`. +Интерактивный `opencode auth login` (выбор провайдера в TUI) из веба не ведём — это следующий +шаг, если понадобится подписка, а не ключ. + +## Вход +Общий механизм `runner/subscriptions.ts` поверх tmux (`peppa-auth-sub`), состояние +входа — `settings` `subscription.login:` (10 мин): +- Claude: `claude setup-token` (как PEP-13, `claude-auth.ts` переписан на подписку): + ссылка → код в форму → токен из вывода → `secret_enc`, статус `active`, tmux убивается + (стирает токен из буфера). Либо вставить готовый токен `sk-ant-oat…` руками. +- Codex device auth: `codex login --device-auth` с `CODEX_HOME` подписки → со страницы + парсим ссылку и одноразовый код, показываем; страница опрашивает (`AutoRefresh`), раннер + смотрит: процесс завершился с успехом и есть `auth.json` → `active`; умер с ошибкой → + `auth_error`. +- Новая подписка создаётся в статусе `pending`; отмена входа удаляет её, если она ни разу не + была активной. + +## «Проверить» +Короткий запуск CLI без tmux (`execFile`, таймаут 60 с) в пустом каталоге: +claude `-p "Ответь одним словом: ok" --max-turns 1`, codex `exec --skip-git-repo-check …`, +opencode `run …` — с окружением подписки. Код 0 → `active`; в выводе лимит +(`usage limit`, `rate limit`, `limit reached`, `resets …`) → `limited` (+ `limited_until`, если +время сброса распознано, иначе +1 ч); иначе `auth_error` с хвостом вывода (секреты маскируются). + +## Выбор подписки раннером +`startSession(…, { subscriptionIds?, poolId?, provider? })`: +1. кандидаты = `subscriptionIds`, иначе подписки `poolId`, иначе пула проекта; +2. если задан `provider` — только его подписки; +3. пусто и ничего не выбрано явно → как раньше, без подписки (вход машины); + набор задан явно (или пул проекта есть), но подходящих нет → ошибка с объяснением; +4. из `active` (и `limited`, у которых `limited_until` прошёл) — первая без активных сессий + (порядок: id); если все заняты — с наименьшим числом активных сессий (раннер не + блокируется, а PEP-39 решит справедливость); +5. нет активных → ошибка «Нет активных подписок…». +Провайдер сессии = провайдер подписки. `resumeSession` берёт подписку сессии (если её удалили — +без подписки). Триаж инцидентов (`claudeTokenForProject`) берёт первую активную подписку +Claude из пула проекта. + +Ротации и учёта лимита по подписке нет: при лимите сессия ведёт себя как раньше (PEP-56). +Отметку `limited` у подписки ставит только «Проверить» — автоматику делает PEP-39. + +## OpenCode как провайдер раннера +`opencode [cwd] --prompt [--model m] [--session ]` в tmux. Правила и MCP — +через сгенерированный `opencode.json` в каталоге запуска (`OPENCODE_CONFIG`): +`instructions: [rules.md]`, `mcp.peppa = { type: "local", command: [peppa-mcp] }`. +Хуков, совместимых с Claude, у OpenCode нет (есть JS-плагины с событиями, контракт для нас не +снят), поэтому этап минимальный, как у Codex без notify: статус сессии по процессу/экрану — +вачдог (живой pane, смерть, зависание). Вопросы-разрешения в Telegram не ходят. Хуки через +плагин OpenCode — отдельная задача. + +## Веб +- Меню: «Подписки» (иконка KeyRound) только при `isSuperadmin`. +- `/subscriptions`: список подписок (провайдер, название, кто добавил, статус, сессии сейчас, + «Проверить», «Удалить», «Переподключить» для Claude), блоки «+ Claude Code», «+ Codex», + «+ OpenCode»; пулы — создать (название + отметки подписок), изменить состав, удалить. +- «⋯ Настройки проекта» → «Подписки»: пул по умолчанию (select для суперадмина, текст для + остальных). +- Страница стори → «Запустить агента»: суперадмин выбирает пул или отмечает подписки + (checkbox, multiple choice); остальные — провайдер, как раньше, и пул проекта. +- «Раннеры»: строка и детали показывают подписку сессии. +- «Настройки → Claude» убрано, вместо него — подсказка, что подписки ведёт суперадмин. + +## Моки +- `mock-claude setup-token` (было), `mock-claude -p` (пробный запуск: токен с `bad` → + ошибка входа, с `limit` → баннер лимита); +- `mock-codex login --device-auth` (печатает ссылку и код, ждёт файл + `$CODEX_HOME/mock-device-approved` или `…-denied`, пишет `auth.json`), + `mock-codex login --with-api-key` (ключ со stdin, `mock-bad…` → ошибка), `mock-codex exec`; +- `mock-opencode` (TUI-сессия по сценарию через `mock-agent.ts opencode`, `run` для проверки). + +Для реальной интеграции нужны: настоящие подписки (вход суперадмина), проверка вывода +настоящего `codex login --device-auth` (регэкспы ссылки и кода) и `opencode` на машине. diff --git a/openspec/changes/pep-67-subscriptions/proposal.md b/openspec/changes/pep-67-subscriptions/proposal.md new file mode 100644 index 00000000..41b8776b --- /dev/null +++ b/openspec/changes/pep-67-subscriptions/proposal.md @@ -0,0 +1,50 @@ +# Proposal: PEP-67 — подписки и пулы для ротации + +Задача Пеппы: **PEP-67** (первый этап PEP-39). + +## Why + +Агенты сейчас работают либо на входе машины, либо на токене Claude владельца проекта +(«Настройки → Claude», PEP-13). Подписок у фабрики несколько (Claude Max, ChatGPT/Codex, +ключи для OpenCode), и чтобы раннеры не упирались в лимит одной подписки, нужно вести их +в одном месте и раздавать раннерам из пулов. Это база для ротации при лимите (PEP-39). + +## What Changes + +- Новый раздел веба **«Подписки»** (`/subscriptions`) — только для суперадмина: пункта меню + у остальных нет, прямой URL отвечает 404. Суперадмин = `platform.admins` (helper + `isSuperadmin(db, user)` в core). +- **Подписка**: провайдер (Claude Code / Codex / OpenCode), название, кто добавил, статус + (ожидает входа / активна / лимит до … / ошибка входа), сколько сессий на ней сейчас, + кнопка «Проверить» (короткий пробный запуск CLI). + - Claude Code — `claude setup-token` в tmux: ссылка → код → токен (как PEP-13), либо + вставить готовый токен. + - Codex — `codex login --device-auth` (подписка ChatGPT: ссылка + одноразовый код) или + API-ключ (`codex login --with-api-key`); у каждой подписки свой `CODEX_HOME`. + - OpenCode — новый провайдер раннера, подписка по API-ключу провайдера модели. + - Секреты — только зашифрованно (`PEPPA_SECRET`), не в логах. +- **Пулы** — именованные наборы подписок (подписка может быть в нескольких пулах). + У проекта — пул по умолчанию («⋯ Настройки проекта», меняет только суперадмин). +- **Раннер**: при старте берёт первую свободную активную подписку из выбранного набора + (подписки/пул из формы запуска, иначе пул проекта), провайдер сессии = провайдер + подписки; сессия запоминает подписку (видно в «Раннерах»), resume идёт на ней же. + Ротации при лимите нет — это PEP-39. +- «Настройки → Claude» убирается; миграция переносит токены `users.claude_token_enc` в + подписки Claude и делает пул владельца пулом его проектов (поведение сессий не меняется). +- Моки: `mock-claude setup-token` / `-p`, `mock-codex login` / `exec`, новый `mock-opencode`. + +## Capabilities + +### Modified Capabilities +- `agent-credentials` — вместо токена Claude у пользователя: подписки, пулы, выбор + подписки раннером, раздел суперадмина. +- `web-workspace` — запуск агента с выбором пула/подписок, подписка в «Раннерах». + +## Impact + +- БД: таблицы `subscriptions`, `subscription_pools`, `subscription_pool_members`; колонки + `projects.subscription_pool_id`, `sessions.subscription_id`, провайдер `opencode`. + Миграция данных токенов Claude. **На живой базе нужна `peppa db backup && peppa db migrate`.** +- runner: `subscriptions.ts` (вход, проверка, выбор), `providers.ts` (OpenCode), + `sessions.ts`; `claude-auth.ts` теперь работает на подписку, а не на пользователя. +- web: `/subscriptions`, меню, настройки проекта, форма запуска, «Раннеры», «Настройки». diff --git a/openspec/changes/pep-67-subscriptions/specs/agent-credentials/spec.md b/openspec/changes/pep-67-subscriptions/specs/agent-credentials/spec.md new file mode 100644 index 00000000..96a3d017 --- /dev/null +++ b/openspec/changes/pep-67-subscriptions/specs/agent-credentials/spec.md @@ -0,0 +1,110 @@ +# Spec Delta: agent-credentials + +## ADDED Requirements + +### Requirement: Раздел «Подписки» только для суперадмина +Раздел «Подписки» SHALL быть виден и доступен только суперадмину (логин из +`platform.admins`): у остальных пункта меню нет, `/subscriptions` отвечает 404, действия +раздела отклоняются. + +#### Scenario: Пользователь без прав суперадмина +- **GIVEN** пользователь «dana» не входит в `platform.admins` +- **WHEN** он открывает Пеппу и затем `/subscriptions` +- **THEN** пункта «Подписки» в меню нет, а `/subscriptions` отвечает 404 + +#### Scenario: Суперадмин +- **GIVEN** `platform.admins` = asel, admin +- **WHEN** «asel» открывает Пеппу +- **THEN** в меню есть «Подписки», страница показывает подписки и пулы + +### Requirement: Подписка агента +Суперадмин SHALL добавлять подписки Claude Code, Codex и OpenCode. Подписка хранит +провайдера, название, кто добавил, статус (ожидает входа / активна / лимит до … / ошибка +входа) и показывает число сессий на ней сейчас. Секреты SHALL храниться только +зашифрованно (или в закрытом каталоге входа CLI) и не показываться. + +#### Scenario: Суперадмин добавляет подписку Claude +- **GIVEN** суперадмин открыл «Подписки» +- **WHEN** он выбирает «+ Claude Code» с названием «Claude Max — asel», входит по ссылке и вставляет код +- **THEN** подписка «Claude Max — asel» появляется в списке со статусом «активна», токен хранится зашифрованным + +#### Scenario: Неверный код Claude +- **GIVEN** суперадмин начал вход новой подписки Claude +- **WHEN** Claude не принимает вставленный код +- **THEN** суперадмин видит ошибку, подписка не становится активной + +#### Scenario: Codex через ChatGPT +- **GIVEN** суперадмин выбрал «+ Codex» и вход через ChatGPT +- **WHEN** он открывает показанную ссылку и вводит показанный одноразовый код на своём устройстве +- **THEN** подписка Codex становится активной, вход хранится в её собственном `CODEX_HOME` + +#### Scenario: OpenCode по ключу +- **WHEN** суперадмин добавляет подписку OpenCode с ключом провайдера «anthropic» +- **THEN** подписка активна, ключ хранится зашифрованным + +### Requirement: Проверка подписки +Кнопка «Проверить» SHALL делать короткий пробный запуск CLI с этой подпиской и обновлять +её статус. + +#### Scenario: Подписка упёрлась в лимит +- **GIVEN** у подписки Claude исчерпан лимит +- **WHEN** суперадмин нажимает «Проверить» +- **THEN** статус подписки — «лимит до …» + +#### Scenario: Отозванный вход +- **WHEN** пробный запуск завершился ошибкой авторизации +- **THEN** статус подписки — «ошибка входа» с текстом ошибки без секретов + +### Requirement: Пулы подписок +Суперадмин SHALL создавать пулы — именованные наборы подписок (подписка может быть в +нескольких пулах) — и назначать проекту пул по умолчанию. Пул проекта меняет только +суперадмин. + +#### Scenario: Пул для ротации +- **GIVEN** есть две активные подписки Claude и одна Codex +- **WHEN** суперадмин создаёт пул «Основной» из этих трёх подписок и назначает его проекту по умолчанию +- **THEN** новые раннеры проекта стартуют на свободной подписке из этого пула + +#### Scenario: Не суперадмин меняет пул проекта +- **GIVEN** «dana» — участник проекта, но не суперадмин +- **WHEN** она пытается сменить пул проекта +- **THEN** изменение отклонено + +### Requirement: Подписка сессии +Раннер SHALL при старте брать первую свободную активную подписку из выбранного набора +(отмеченные подписки или пул из формы запуска, иначе пул проекта) и запоминать её у сессии; +провайдер сессии — провайдер подписки, процесс агента получает вход этой подписки. Resume +SHALL идти на той же подписке. Без пула и выбора сессия запускается на входе машины. + +#### Scenario: Свободная подписка +- **GIVEN** в пуле проекта подписки «A» и «B», на «A» уже работает сессия +- **WHEN** запускается новый раннер проекта +- **THEN** он стартует на подписке «B» + +#### Scenario: Нет активных подписок +- **GIVEN** у всех подписок пула проекта статус «ошибка входа» +- **WHEN** запускается новый раннер +- **THEN** запуск отклонён с сообщением «Нет активных подписок» + +### Requirement: Перенос токена Claude из настроек +Миграция SHALL переносить подключённые токены Claude пользователей (PEP-13) в подписки +Claude и делать пул с этой подпиской пулом по умолчанию проектов владельца. + +#### Scenario: Был подключён Claude +- **GIVEN** у «asel» в настройках был подключён Claude и он владелец проекта PEP +- **WHEN** применяется миграция +- **THEN** есть активная подписка «Claude — asel» с тем же токеном, у PEP пул «Claude — asel», а у пользователя токена больше нет + +## REMOVED Requirements + +### Requirement: Подключение Claude из веба +**Reason**: вход Claude переехал в подписки суперадмина. +**Migration**: токен переносится в подписку миграцией; новые — «Подписки → + Claude Code». + +### Requirement: Хранение и отключение +**Reason**: заменено требованием «Подписка агента» (удаление подписки). +**Migration**: удалить подписку в «Подписках». + +### Requirement: Токен в сессиях +**Reason**: заменено требованием «Подписка сессии». +**Migration**: миграция назначает проектам владельца пул с его подпиской. diff --git a/openspec/changes/pep-67-subscriptions/specs/web-workspace/spec.md b/openspec/changes/pep-67-subscriptions/specs/web-workspace/spec.md new file mode 100644 index 00000000..3cec17da --- /dev/null +++ b/openspec/changes/pep-67-subscriptions/specs/web-workspace/spec.md @@ -0,0 +1,18 @@ +# Spec Delta: web-workspace + +## ADDED Requirements + +### Requirement: Выбор подписок при запуске агента +Форма «Запустить агента» SHALL давать суперадмину выбрать пул или отметить несколько +подписок (по умолчанию — пул проекта); остальные запускают на пуле проекта. «Раннеры» +SHALL показывать, на какой подписке работает сессия. + +#### Scenario: Выбор при запуске +- **GIVEN** суперадмин на странице стори, есть подписки «Claude A», «Claude B», «Codex C» +- **WHEN** он отмечает «Claude B» и «Codex C» и запускает агента +- **THEN** раннер стартует на одной из них, и в «Раннерах» видно, на какой + +#### Scenario: Отмеченная подписка неактивна +- **GIVEN** у отмеченной подписки статус «ошибка входа», других не отмечено +- **WHEN** суперадмин запускает агента +- **THEN** запуск отклонён с сообщением «Нет активных подписок» diff --git a/openspec/changes/pep-67-subscriptions/tasks.md b/openspec/changes/pep-67-subscriptions/tasks.md new file mode 100644 index 00000000..ead0113c --- /dev/null +++ b/openspec/changes/pep-67-subscriptions/tasks.md @@ -0,0 +1,26 @@ +# Tasks: PEP-67 + +## 1. Данные +- [ ] 1.1 Схема: subscriptions, subscription_pools, subscription_pool_members, projects.subscription_pool_id, sessions.subscription_id, provider opencode +- [ ] 1.2 Миграция (drizzle-kit generate) + перенос users.claude_token_enc в подписки и пулы +- [ ] 1.3 core: isSuperadmin, CRUD подписок и пулов, пул проекта, выбор подписки, claudeTokenForProject из пула + +## 2. Раннер +- [ ] 2.1 Вход: Claude setup-token на подписку, ручной токен; Codex device auth и API-ключ (CODEX_HOME); OpenCode ключ +- [ ] 2.2 «Проверить» (пробный запуск) и статусы +- [ ] 2.3 Провайдер OpenCode (providers.ts, opencode.json, env) +- [ ] 2.4 startSession/resumeSession: выбор подписки, env подписки, sessions.subscription_id + +## 3. Моки +- [ ] 3.1 mock-claude -p, mock-codex login/exec, mock-opencode + +## 4. Веб +- [ ] 4.1 Меню «Подписки» только суперадмину, /subscriptions (404 остальным) +- [ ] 4.2 Страница подписок: список, добавление трёх провайдеров, проверка, удаление, пулы +- [ ] 4.3 Настройки проекта: пул по умолчанию; форма запуска: пул/подписки; «Раннеры»: подписка +- [ ] 4.4 Убрать «Настройки → Claude», обновить Помощь + +## 5. Тесты и документация +- [ ] 5.1 testkit: subscriptions.test.ts (сценарии спеки), перенос claude-auth.test.ts, миграция токенов +- [ ] 5.2 AGENTS.md +- [ ] 5.3 pnpm run ci зелёный From 9054774f96372618d714d8ff26fedf3d386bc65c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sat, 14 Nov 2026 03:23:46 +0500 Subject: [PATCH 2/5] PEP-67: subscriptions and pools in core/db, sign-in and checks in runner, OpenCode provider, mocks, tests Co-Authored-By: Claude Opus 5.5 --- .../changes/pep-67-subscriptions/design.md | 2 +- .../changes/pep-67-subscriptions/proposal.md | 2 +- packages/cli/src/index.ts | 2 +- packages/core/src/index.ts | 1 + packages/core/src/sessions.ts | 16 +- packages/core/src/subscriptions.ts | 270 ++ packages/core/src/users.ts | 14 - packages/db/migrations/0003_subscriptions.sql | 54 + .../db/migrations/meta/0003_snapshot.json | 2570 +++++++++++++++++ packages/db/migrations/meta/_journal.json | 7 + packages/db/src/schema.ts | 57 +- packages/runner/src/claude-auth.ts | 90 - packages/runner/src/index.ts | 3 +- packages/runner/src/providers.ts | 43 +- packages/runner/src/sessions.ts | 26 +- packages/runner/src/subscription-login.ts | 242 ++ packages/runner/src/subscriptions.ts | 128 + packages/runner/src/triage.ts | 2 +- packages/testkit/bin/mock-opencode | 4 + packages/testkit/src/mock-agent.ts | 96 +- packages/testkit/test/claude-auth.test.ts | 54 - packages/testkit/test/helpers.ts | 5 +- packages/testkit/test/subscriptions.test.ts | 253 ++ 23 files changed, 3748 insertions(+), 193 deletions(-) create mode 100644 packages/core/src/subscriptions.ts create mode 100644 packages/db/migrations/0003_subscriptions.sql create mode 100644 packages/db/migrations/meta/0003_snapshot.json delete mode 100644 packages/runner/src/claude-auth.ts create mode 100644 packages/runner/src/subscription-login.ts create mode 100644 packages/runner/src/subscriptions.ts create mode 100755 packages/testkit/bin/mock-opencode delete mode 100644 packages/testkit/test/claude-auth.test.ts create mode 100644 packages/testkit/test/subscriptions.test.ts diff --git a/openspec/changes/pep-67-subscriptions/design.md b/openspec/changes/pep-67-subscriptions/design.md index 824bce3c..df14cddb 100644 --- a/openspec/changes/pep-67-subscriptions/design.md +++ b/openspec/changes/pep-67-subscriptions/design.md @@ -46,7 +46,7 @@ OpenCode — подписка только по API-ключу провайде ## Вход Общий механизм `runner/subscriptions.ts` поверх tmux (`peppa-auth-sub`), состояние входа — `settings` `subscription.login:` (10 мин): -- Claude: `claude setup-token` (как PEP-13, `claude-auth.ts` переписан на подписку): +- Claude: `claude setup-token` (как PEP-13, `claude-auth.ts` → `subscription-login.ts`, на подписку): ссылка → код в форму → токен из вывода → `secret_enc`, статус `active`, tmux убивается (стирает токен из буфера). Либо вставить готовый токен `sk-ant-oat…` руками. - Codex device auth: `codex login --device-auth` с `CODEX_HOME` подписки → со страницы diff --git a/openspec/changes/pep-67-subscriptions/proposal.md b/openspec/changes/pep-67-subscriptions/proposal.md index 41b8776b..2fe8d503 100644 --- a/openspec/changes/pep-67-subscriptions/proposal.md +++ b/openspec/changes/pep-67-subscriptions/proposal.md @@ -46,5 +46,5 @@ `projects.subscription_pool_id`, `sessions.subscription_id`, провайдер `opencode`. Миграция данных токенов Claude. **На живой базе нужна `peppa db backup && peppa db migrate`.** - runner: `subscriptions.ts` (вход, проверка, выбор), `providers.ts` (OpenCode), - `sessions.ts`; `claude-auth.ts` теперь работает на подписку, а не на пользователя. + `sessions.ts`; `claude-auth.ts` → `subscription-login.ts`: вход на подписку, а не на пользователя. - web: `/subscriptions`, меню, настройки проекта, форма запуска, «Раннеры», «Настройки». diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 660d5184..a79cf379 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -73,7 +73,7 @@ const USAGE = `peppa — Peppa software factory CLI peppa task set -s peppa q list [KEY] peppa q answer (delivered into the session's terminal) - peppa session start [--provider claude|codex] [-p ] [--mode ] [--model ] + peppa session start [--provider claude|codex|opencode] [-p ] [--mode ] [--model ] peppa session list [--all] peppa session send peppa session attach diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 5182e36a..840698bf 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -20,3 +20,4 @@ export * from "./ci.ts"; export * from "./egov.ts"; export * from "./local-users.ts"; export * from "./specs.ts"; +export * from "./subscriptions.ts"; diff --git a/packages/core/src/sessions.ts b/packages/core/src/sessions.ts index ad19e314..6be52088 100644 --- a/packages/core/src/sessions.ts +++ b/packages/core/src/sessions.ts @@ -1,4 +1,4 @@ -import { events, projects, questions, sessions, sessionStatus, tasks, type Db } from "@peppa/db"; +import { events, projects, questions, sessions, sessionStatus, subscriptions, tasks, type Db } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; import { and, desc, eq, inArray, isNull, lte, notInArray } from "drizzle-orm"; import { PeppaError } from "./errors.ts"; @@ -14,11 +14,13 @@ export interface SessionView extends Session { projectKey: string; taskKey: string | null; taskTitle: string | null; + /** PEP-67: name of the subscription the session runs on. */ + subscriptionName: string | null; } export async function createSession( db: Db, - s: { projectId: number; taskId?: number; provider?: Session["provider"] }, + s: { projectId: number; taskId?: number; provider?: Session["provider"]; subscriptionId?: number | null }, ): Promise { // tmux name needs the id, so insert with a unique placeholder first. const [row] = await db @@ -69,7 +71,7 @@ export async function listUserSessions(db: Db, userId: number, opts: { filter?: export async function updateSession( db: Db, id: number, - patch: Partial>, + patch: Partial>, ): Promise { const [row] = await db.update(sessions).set(patch).where(eq(sessions.id, id)).returning(); if (!row) throw new PeppaError(`Session #${id} not found`); @@ -160,18 +162,20 @@ export async function raiseSessionQuestion( function sessionQuery(db: Db) { return db - .select({ session: sessions, projectKey: projects.key, taskNumber: tasks.number, taskTitle: tasks.title }) + .select({ session: sessions, projectKey: projects.key, taskNumber: tasks.number, taskTitle: tasks.title, subscriptionName: subscriptions.name }) .from(sessions) .innerJoin(projects, eq(sessions.projectId, projects.id)) - .leftJoin(tasks, eq(sessions.taskId, tasks.id)); + .leftJoin(tasks, eq(sessions.taskId, tasks.id)) + .leftJoin(subscriptions, eq(sessions.subscriptionId, subscriptions.id)); } -function toView(r: { session: Session; projectKey: string; taskNumber: number | null; taskTitle: string | null }): SessionView { +function toView(r: { session: Session; projectKey: string; taskNumber: number | null; taskTitle: string | null; subscriptionName: string | null }): SessionView { return { ...r.session, projectKey: r.projectKey, taskKey: r.taskNumber != null ? formatTaskKey(r.projectKey, r.taskNumber) : null, taskTitle: r.taskTitle, + subscriptionName: r.subscriptionName, }; } diff --git a/packages/core/src/subscriptions.ts b/packages/core/src/subscriptions.ts new file mode 100644 index 00000000..5b8d8e45 --- /dev/null +++ b/packages/core/src/subscriptions.ts @@ -0,0 +1,270 @@ +// Agent subscriptions and pools (PEP-67): superadmins keep the accounts agents run on +// (Claude Code, Codex, OpenCode) and group them into pools; a runner takes the first free +// active subscription of the chosen set. Rotation on limits and fairness — PEP-39. +import { projects, sessions, subscriptionPoolMembers, subscriptionPools, subscriptions, users, type Db } from "@peppa/db"; +import { and, asc, count, eq, inArray, notInArray } from "drizzle-orm"; +import { decrypt, encrypt } from "./crypto.ts"; +import { PeppaError } from "./errors.ts"; +import { isSuperadmin } from "./monitor.ts"; +import type { Project } from "./projects.ts"; +import { FINISHED_SESSION_STATUSES } from "./sessions.ts"; +import type { User } from "./users.ts"; + +export type Subscription = typeof subscriptions.$inferSelect; +export type SubscriptionProvider = Subscription["provider"]; +export type SubscriptionStatus = Subscription["status"]; +export type SubscriptionPool = typeof subscriptionPools.$inferSelect; + +export const PROVIDER_NAMES: Record = { claude: "Claude Code", codex: "Codex", opencode: "OpenCode" }; +/** OpenCode model providers a key can belong to, and the env variable it goes into. */ +export const OPENCODE_KEY_ENV: Record = { + anthropic: "ANTHROPIC_API_KEY", + openai: "OPENAI_API_KEY", + openrouter: "OPENROUTER_API_KEY", +}; + +export interface SubscriptionView extends Subscription { + createdByLogin: string | null; + activeSessions: number; + poolIds: number[]; +} + +export interface PoolView extends SubscriptionPool { + subscriptionIds: number[]; + projectKeys: string[]; +} + +/** Throws "not found" unless the user is a superadmin: the section doesn't exist for others. */ +export async function requireSuperadmin(db: Db, user: Pick | null | undefined): Promise { + if (!(await isSuperadmin(db, user))) throw new PeppaError("Не найдено"); +} + +// ── subscriptions ──────────────────────────────────────────────────────────────── + +async function activeSessionCounts(db: Db): Promise> { + const rows = await db + .select({ id: sessions.subscriptionId, n: count() }) + .from(sessions) + .where(notInArray(sessions.status, FINISHED_SESSION_STATUSES)) + .groupBy(sessions.subscriptionId); + return new Map(rows.filter((r) => r.id != null).map((r) => [r.id!, r.n])); +} + +export async function listSubscriptions(db: Db): Promise { + const rows = await db + .select({ s: subscriptions, login: users.login }) + .from(subscriptions) + .leftJoin(users, eq(subscriptions.createdBy, users.id)) + .orderBy(asc(subscriptions.id)); + const counts = await activeSessionCounts(db); + const members = await db.select().from(subscriptionPoolMembers); + return rows.map((r) => ({ + ...r.s, + createdByLogin: r.login, + activeSessions: counts.get(r.s.id) ?? 0, + poolIds: members.filter((m) => m.subscriptionId === r.s.id).map((m) => m.poolId), + })); +} + +export async function getSubscription(db: Db, id: number): Promise { + const [row] = await db.select().from(subscriptions).where(eq(subscriptions.id, id)); + if (!row) throw new PeppaError(`Подписка #${id} не найдена`); + return row; +} + +export async function createSubscription( + db: Db, + s: { provider: SubscriptionProvider; name: string; authKind: Subscription["authKind"]; secret?: string | null; keyProvider?: string | null; createdBy?: number | null }, +): Promise { + const name = s.name.trim(); + if (!name) throw new PeppaError("Нужно название подписки"); + if (s.provider === "opencode" && !(s.keyProvider && s.keyProvider in OPENCODE_KEY_ENV)) throw new PeppaError("Выберите провайдера ключа OpenCode"); + const [row] = await db + .insert(subscriptions) + .values({ + provider: s.provider, + name, + authKind: s.authKind, + secretEnc: s.secret ? encrypt(s.secret) : null, + keyProvider: s.keyProvider ?? null, + createdBy: s.createdBy ?? null, + }) + .returning(); + return row!; +} + +export async function updateSubscription( + db: Db, + id: number, + patch: Partial> & { secret?: string | null }, +): Promise { + const { secret, ...rest } = patch; + const set: Partial = { ...rest }; + if (secret !== undefined) set.secretEnc = secret ? encrypt(secret) : null; + if (patch.status === "active") { + set.limitedUntil = null; + set.lastError = null; + const cur = await getSubscription(db, id); + if (!cur.activatedAt) set.activatedAt = new Date(); + } + const [row] = await db.update(subscriptions).set(set).where(eq(subscriptions.id, id)).returning(); + if (!row) throw new PeppaError(`Подписка #${id} не найдена`); + return row; +} + +/** Removes a subscription; its sessions keep running but forget it. The runner wipes its login dir. */ +export async function deleteSubscription(db: Db, id: number): Promise { + db.transaction((tx) => { + tx.update(sessions).set({ subscriptionId: null }).where(eq(sessions.subscriptionId, id)).run(); + tx.delete(subscriptions).where(eq(subscriptions.id, id)).run(); + }); +} + +/** The decrypted secret (Claude token / OpenCode key); null if the subscription has none. */ +export function subscriptionSecret(s: Pick): string | null { + return s.secretEnc ? decrypt(s.secretEnc) : null; +} + +/** Active now: `active`, or `limited` whose reset time has passed. */ +export function isUsable(s: Pick, now = new Date()): boolean { + return s.status === "active" || (s.status === "limited" && !!s.limitedUntil && s.limitedUntil <= now); +} + +// ── pools ──────────────────────────────────────────────────────────────────────── + +export async function listPools(db: Db): Promise { + const pools = await db.select().from(subscriptionPools).orderBy(asc(subscriptionPools.name)); + const members = await db.select().from(subscriptionPoolMembers); + const used = await db.select({ key: projects.key, poolId: projects.subscriptionPoolId }).from(projects); + return pools.map((p) => ({ + ...p, + subscriptionIds: members.filter((m) => m.poolId === p.id).map((m) => m.subscriptionId).sort((a, b) => a - b), + projectKeys: used.filter((u) => u.poolId === p.id).map((u) => u.key), + })); +} + +export async function getPool(db: Db, id: number): Promise { + const [row] = await db.select().from(subscriptionPools).where(eq(subscriptionPools.id, id)); + if (!row) throw new PeppaError(`Пул #${id} не найден`); + return row; +} + +async function checkSubscriptionIds(db: Db, ids: number[]): Promise { + const uniq = [...new Set(ids.filter((n) => Number.isInteger(n) && n > 0))]; + if (!uniq.length) return []; + const found = await db.select({ id: subscriptions.id }).from(subscriptions).where(inArray(subscriptions.id, uniq)); + if (found.length !== uniq.length) throw new PeppaError("Некоторых подписок уже нет"); + return uniq; +} + +export async function createPool(db: Db, p: { name: string; subscriptionIds: number[]; createdBy?: number | null }): Promise { + const name = p.name.trim(); + if (!name) throw new PeppaError("Нужно название пула"); + const [dup] = await db.select().from(subscriptionPools).where(eq(subscriptionPools.name, name)); + if (dup) throw new PeppaError(`Пул «${name}» уже есть`); + const ids = await checkSubscriptionIds(db, p.subscriptionIds); + return db.transaction((tx) => { + const row = tx.insert(subscriptionPools).values({ name, createdBy: p.createdBy ?? null }).returning().get(); + for (const id of ids) tx.insert(subscriptionPoolMembers).values({ poolId: row.id, subscriptionId: id }).run(); + return row; + }); +} + +export async function updatePool(db: Db, id: number, p: { name?: string; subscriptionIds?: number[] }): Promise { + await getPool(db, id); + const ids = p.subscriptionIds ? await checkSubscriptionIds(db, p.subscriptionIds) : null; + const name = p.name?.trim(); + if (name) { + const [dup] = await db.select().from(subscriptionPools).where(eq(subscriptionPools.name, name)); + if (dup && dup.id !== id) throw new PeppaError(`Пул «${name}» уже есть`); + } + db.transaction((tx) => { + if (name) tx.update(subscriptionPools).set({ name }).where(eq(subscriptionPools.id, id)).run(); + if (ids) { + tx.delete(subscriptionPoolMembers).where(eq(subscriptionPoolMembers.poolId, id)).run(); + for (const sid of ids) tx.insert(subscriptionPoolMembers).values({ poolId: id, subscriptionId: sid }).run(); + } + }); +} + +/** Deletes a pool; projects that used it as default go back to "no pool". */ +export async function deletePool(db: Db, id: number): Promise { + db.transaction((tx) => { + tx.update(projects).set({ subscriptionPoolId: null }).where(eq(projects.subscriptionPoolId, id)).run(); + tx.delete(subscriptionPools).where(eq(subscriptionPools.id, id)).run(); + }); +} + +export async function setProjectPool(db: Db, projectId: number, poolId: number | null): Promise { + if (poolId != null) await getPool(db, poolId); + await db.update(projects).set({ subscriptionPoolId: poolId }).where(eq(projects.id, projectId)); +} + +async function poolSubscriptions(db: Db, poolId: number): Promise { + const rows = await db + .select({ s: subscriptions }) + .from(subscriptionPoolMembers) + .innerJoin(subscriptions, eq(subscriptionPoolMembers.subscriptionId, subscriptions.id)) + .where(eq(subscriptionPoolMembers.poolId, poolId)) + .orderBy(asc(subscriptions.id)); + return rows.map((r) => r.s); +} + +// ── choosing a subscription for a runner ───────────────────────────────────────── + +export interface PickOptions { + projectId: number; + /** Subscriptions ticked in the launch form (multiple choice). */ + subscriptionIds?: number[]; + /** A pool chosen in the launch form instead of the project's default. */ + poolId?: number | null; + provider?: SubscriptionProvider; + now?: Date; +} + +/** + * The subscription a new runner starts on: the first free usable one of the chosen set + * (ticked subscriptions, else the chosen pool, else the project's pool), by id; if all are + * busy — the least busy one (the runner never waits; fairness is PEP-39). Null when nothing + * is chosen and the project has no pool: the agent runs on this machine's own login. + */ +export async function pickSubscription(db: Db, o: PickOptions): Promise { + let candidates: Subscription[]; + let source: string; + if (o.subscriptionIds?.length) { + candidates = await db.select().from(subscriptions).where(inArray(subscriptions.id, o.subscriptionIds)).orderBy(asc(subscriptions.id)); + source = "отмеченных"; + } else { + const poolId = o.poolId ?? (await db.select({ id: projects.subscriptionPoolId }).from(projects).where(eq(projects.id, o.projectId)))[0]?.id; + if (poolId == null) return null; + const pool = await getPool(db, poolId); + candidates = await poolSubscriptions(db, poolId); + source = `пула «${pool.name}»`; + } + if (o.provider) { + candidates = candidates.filter((s) => s.provider === o.provider); + if (!candidates.length) throw new PeppaError(`Среди ${source} подписок нет подписок ${PROVIDER_NAMES[o.provider]}`); + } + const usable = candidates.filter((s) => isUsable(s, o.now)); + if (!usable.length) throw new PeppaError(`Нет активных подписок среди ${source}${candidates.length ? "" : " (пул пуст)"} — проверьте их в «Подписках»`); + const counts = await activeSessionCounts(db); + return usable.reduce((best, s) => ((counts.get(s.id) ?? 0) < (counts.get(best.id) ?? 0) ? s : best)); +} + +/** Claude token for one-off calls on behalf of a project (incident triage): the project's pool. */ +export async function claudeTokenForProject(db: Db, project: Pick): Promise { + const [p] = await db.select({ poolId: projects.subscriptionPoolId }).from(projects).where(eq(projects.id, project.id)); + if (p?.poolId == null) return null; + const s = (await poolSubscriptions(db, p.poolId)).find((x) => x.provider === "claude" && isUsable(x) && x.secretEnc); + return s ? subscriptionSecret(s) : null; +} + +/** Pool name of a project (for the project settings), or null. */ +export async function projectPool(db: Db, projectId: number): Promise { + const [row] = await db + .select({ pool: subscriptionPools }) + .from(projects) + .innerJoin(subscriptionPools, eq(projects.subscriptionPoolId, subscriptionPools.id)) + .where(and(eq(projects.id, projectId))); + return row?.pool ?? null; +} diff --git a/packages/core/src/users.ts b/packages/core/src/users.ts index 3eb7cb18..f23b25a6 100644 --- a/packages/core/src/users.ts +++ b/packages/core/src/users.ts @@ -179,20 +179,6 @@ export async function consumeLoginLink(db: Db, code: string): Promise { - await db - .update(users) - .set({ claudeTokenEnc: token ? encrypt(token) : null, claudeTokenSetAt: token ? new Date() : null }) - .where(eq(users.id, userId)); -} - -/** The decrypted Claude token of a project's owner, if they connected Claude. */ -export async function claudeTokenForProject(db: Db, project: Pick): Promise { - if (!project.ownerId) return null; - const u = await getUser(db, project.ownerId); - return u?.claudeTokenEnc ? decrypt(u.claudeTokenEnc) : null; -} - export async function listUsers(db: Db): Promise { return db.select().from(users).orderBy(asc(users.login)); } diff --git a/packages/db/migrations/0003_subscriptions.sql b/packages/db/migrations/0003_subscriptions.sql new file mode 100644 index 00000000..246d1b12 --- /dev/null +++ b/packages/db/migrations/0003_subscriptions.sql @@ -0,0 +1,54 @@ +CREATE TABLE `subscription_pool_members` ( + `pool_id` integer NOT NULL, + `subscription_id` integer NOT NULL, + PRIMARY KEY(`pool_id`, `subscription_id`), + FOREIGN KEY (`pool_id`) REFERENCES `subscription_pools`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`subscription_id`) REFERENCES `subscriptions`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE TABLE `subscription_pools` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `name` text NOT NULL, + `created_by` integer, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + FOREIGN KEY (`created_by`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +CREATE UNIQUE INDEX `subscription_pools_name_unique` ON `subscription_pools` (`name`);--> statement-breakpoint +CREATE TABLE `subscriptions` ( + `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, + `provider` text NOT NULL, + `name` text NOT NULL, + `auth_kind` text NOT NULL, + `secret_enc` text, + `key_provider` text, + `status` text DEFAULT 'pending' NOT NULL, + `limited_until` integer, + `last_error` text, + `checked_at` integer, + `activated_at` integer, + `created_by` integer, + `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL, + FOREIGN KEY (`created_by`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null +); +--> statement-breakpoint +ALTER TABLE `projects` ADD `subscription_pool_id` integer REFERENCES subscription_pools(id) ON DELETE set null;--> statement-breakpoint +ALTER TABLE `sessions` ADD `subscription_id` integer REFERENCES subscriptions(id) ON DELETE set null;--> statement-breakpoint +-- PEP-67 data: the PEP-13 Claude token of every user becomes a subscription «Claude — » +-- (same ciphertext: same PEPPA_SECRET key), a pool of the same name, and the default pool of the +-- projects that user owns — sessions keep running on the same account. Then the token is cleared. +INSERT INTO `subscriptions` (`provider`, `name`, `auth_kind`, `secret_enc`, `status`, `activated_at`, `created_by`) +SELECT 'claude', 'Claude — ' || `login`, 'oauth', `claude_token_enc`, 'active', coalesce(`claude_token_set_at`, cast(unixepoch('subsec') * 1000 as integer)), `id` +FROM `users` WHERE `claude_token_enc` IS NOT NULL;--> statement-breakpoint +INSERT OR IGNORE INTO `subscription_pools` (`name`, `created_by`) +SELECT 'Claude — ' || `login`, `id` FROM `users` WHERE `claude_token_enc` IS NOT NULL;--> statement-breakpoint +INSERT OR IGNORE INTO `subscription_pool_members` (`pool_id`, `subscription_id`) +SELECT p.`id`, s.`id` FROM `users` u +JOIN `subscription_pools` p ON p.`name` = 'Claude — ' || u.`login` +JOIN `subscriptions` s ON s.`name` = 'Claude — ' || u.`login` AND s.`created_by` = u.`id` AND s.`provider` = 'claude' +WHERE u.`claude_token_enc` IS NOT NULL;--> statement-breakpoint +UPDATE `projects` SET `subscription_pool_id` = ( + SELECT p.`id` FROM `users` u JOIN `subscription_pools` p ON p.`name` = 'Claude — ' || u.`login` + WHERE u.`id` = `projects`.`owner_id` AND u.`claude_token_enc` IS NOT NULL +) WHERE `subscription_pool_id` IS NULL AND `owner_id` IN (SELECT `id` FROM `users` WHERE `claude_token_enc` IS NOT NULL);--> statement-breakpoint +UPDATE `users` SET `claude_token_enc` = NULL, `claude_token_set_at` = NULL WHERE `claude_token_enc` IS NOT NULL; \ No newline at end of file diff --git a/packages/db/migrations/meta/0003_snapshot.json b/packages/db/migrations/meta/0003_snapshot.json new file mode 100644 index 00000000..ac8894f5 --- /dev/null +++ b/packages/db/migrations/meta/0003_snapshot.json @@ -0,0 +1,2570 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "922324fb-4f7c-4dd7-9cb7-7cb03780a882", + "prevId": "8c480919-f0f0-4006-b448-49eff5f43062", + "tables": { + "check_runs": { + "name": "check_runs", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "branch": { + "name": "branch", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "check": { + "name": "check", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "run_url": { + "name": "run_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "log_tail": { + "name": "log_tail", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "duration_sec": { + "name": "duration_sec", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'report'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "check_runs_project_sha_check": { + "name": "check_runs_project_sha_check", + "columns": [ + "project_id", + "sha", + "check" + ], + "isUnique": true + } + }, + "foreignKeys": { + "check_runs_project_id_projects_id_fk": { + "name": "check_runs_project_id_projects_id_fk", + "tableFrom": "check_runs", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "check_runs_task_id_tasks_id_fk": { + "name": "check_runs_task_id_tasks_id_fk", + "tableFrom": "check_runs", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "error_sources": { + "name": "error_sources", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "bugsink_project_id": { + "name": "bugsink_project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "dsn": { + "name": "dsn", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "error_sources_bugsink_project_id_unique": { + "name": "error_sources_bugsink_project_id_unique", + "columns": [ + "bugsink_project_id" + ], + "isUnique": true + }, + "error_sources_project_kind": { + "name": "error_sources_project_kind", + "columns": [ + "project_id", + "kind" + ], + "isUnique": true + } + }, + "foreignKeys": { + "error_sources_project_id_projects_id_fk": { + "name": "error_sources_project_id_projects_id_fk", + "tableFrom": "error_sources", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "events": { + "name": "events", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "payload": { + "name": "payload", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "events_project_id_projects_id_fk": { + "name": "events_project_id_projects_id_fk", + "tableFrom": "events", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_task_id_tasks_id_fk": { + "name": "events_task_id_tasks_id_fk", + "tableFrom": "events", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_session_id_sessions_id_fk": { + "name": "events_session_id_sessions_id_fk", + "tableFrom": "events", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "goals": { + "name": "goals", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'open'" + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "goals_project_id_projects_id_fk": { + "name": "goals_project_id_projects_id_fk", + "tableFrom": "goals", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "incident_settings": { + "name": "incident_settings", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "hook_secret": { + "name": "hook_secret", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "policy": { + "name": "policy", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'backlog'" + }, + "triage_prompt": { + "name": "triage_prompt", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "environments": { + "name": "environments", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[\"prod\",\"production\"]'" + }, + "daily_limit": { + "name": "daily_limit", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 5 + }, + "ignore_pattern": { + "name": "ignore_pattern", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "webhook_auto": { + "name": "webhook_auto", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "incident_settings_hook_secret_unique": { + "name": "incident_settings_hook_secret_unique", + "columns": [ + "hook_secret" + ], + "isUnique": true + } + }, + "foreignKeys": { + "incident_settings_project_id_projects_id_fk": { + "name": "incident_settings_project_id_projects_id_fk", + "tableFrom": "incident_settings", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "incident_settings_goal_id_goals_id_fk": { + "name": "incident_settings_goal_id_goals_id_fk", + "tableFrom": "incident_settings", + "tableTo": "goals", + "columnsFrom": [ + "goal_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "incidents": { + "name": "incidents", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "bugsink_issue_id": { + "name": "bugsink_issue_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "friendly_id": { + "name": "friendly_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "culprit": { + "name": "culprit", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "level": { + "name": "level", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "environment": { + "name": "environment", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "first_release": { + "name": "first_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_release": { + "name": "last_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "events": { + "name": "events", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "first_seen": { + "name": "first_seen", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_seen": { + "name": "last_seen", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "stack": { + "name": "stack", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'new'" + }, + "decision": { + "name": "decision", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decided_by": { + "name": "decided_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "decision_reason": { + "name": "decision_reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "task_created_at": { + "name": "task_created_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resolved_release": { + "name": "resolved_release", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "resolved_at": { + "name": "resolved_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "regressions": { + "name": "regressions", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "incidents_bugsink_issue_id_unique": { + "name": "incidents_bugsink_issue_id_unique", + "columns": [ + "bugsink_issue_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "incidents_project_id_projects_id_fk": { + "name": "incidents_project_id_projects_id_fk", + "tableFrom": "incidents", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "incidents_task_id_tasks_id_fk": { + "name": "incidents_task_id_tasks_id_fk", + "tableFrom": "incidents", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_clients": { + "name": "oauth_clients", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirect_uris": { + "name": "redirect_uris", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_codes": { + "name": "oauth_codes", + "columns": { + "code_hash": { + "name": "code_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "redirect_uri": { + "name": "redirect_uri", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "code_challenge": { + "name": "code_challenge", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "used_at": { + "name": "used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_codes_client_id_oauth_clients_id_fk": { + "name": "oauth_codes_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_codes_user_id_users_id_fk": { + "name": "oauth_codes_user_id_users_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "oauth_tokens": { + "name": "oauth_tokens", + "columns": { + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "revoked_at": { + "name": "revoked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_used_at": { + "name": "last_used_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_tokens_client_id_oauth_clients_id_fk": { + "name": "oauth_tokens_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_tokens_user_id_users_id_fk": { + "name": "oauth_tokens_user_id_users_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_invites": { + "name": "project_invites", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "invited_by": { + "name": "invited_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "project_invites_project_id_projects_id_fk": { + "name": "project_invites_project_id_projects_id_fk", + "tableFrom": "project_invites", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_invites_invited_by_users_id_fk": { + "name": "project_invites_invited_by_users_id_fk", + "tableFrom": "project_invites", + "tableTo": "users", + "columnsFrom": [ + "invited_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "project_invites_project_id_login_pk": { + "columns": [ + "project_id", + "login" + ], + "name": "project_invites_project_id_login_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "project_members": { + "name": "project_members", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "added_by": { + "name": "added_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "project_members_project_id_projects_id_fk": { + "name": "project_members_project_id_projects_id_fk", + "tableFrom": "project_members", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_members_user_id_users_id_fk": { + "name": "project_members_user_id_users_id_fk", + "tableFrom": "project_members", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_members_added_by_users_id_fk": { + "name": "project_members_added_by_users_id_fk", + "tableFrom": "project_members", + "tableTo": "users", + "columnsFrom": [ + "added_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "project_members_project_id_user_id_pk": { + "columns": [ + "project_id", + "user_id" + ], + "name": "project_members_project_id_user_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "projects": { + "name": "projects", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "gitea_owner": { + "name": "gitea_owner", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "gitea_repo": { + "name": "gitea_repo", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "default_branch": { + "name": "default_branch", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'main'" + }, + "workspace_path": { + "name": "workspace_path", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "owner_id": { + "name": "owner_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "next_task_number": { + "name": "next_task_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "subscription_pool_id": { + "name": "subscription_pool_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "projects_slug_unique": { + "name": "projects_slug_unique", + "columns": [ + "slug" + ], + "isUnique": true + }, + "projects_key_unique": { + "name": "projects_key_unique", + "columns": [ + "key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "projects_owner_id_users_id_fk": { + "name": "projects_owner_id_users_id_fk", + "tableFrom": "projects", + "tableTo": "users", + "columnsFrom": [ + "owner_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "projects_subscription_pool_id_subscription_pools_id_fk": { + "name": "projects_subscription_pool_id_subscription_pools_id_fk", + "tableFrom": "projects", + "tableTo": "subscription_pools", + "columnsFrom": [ + "subscription_pool_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "questions": { + "name": "questions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "options": { + "name": "options", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "answer": { + "name": "answer", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "answered_via": { + "name": "answered_via", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "awaiting_hook": { + "name": "awaiting_hook", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "answered_at": { + "name": "answered_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "questions_project_id_projects_id_fk": { + "name": "questions_project_id_projects_id_fk", + "tableFrom": "questions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_task_id_tasks_id_fk": { + "name": "questions_task_id_tasks_id_fk", + "tableFrom": "questions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_session_id_sessions_id_fk": { + "name": "questions_session_id_sessions_id_fk", + "tableFrom": "questions", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "releases": { + "name": "releases", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "env": { + "name": "env", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sha": { + "name": "sha", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "previous_sha": { + "name": "previous_sha", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "host": { + "name": "host", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tasks": { + "name": "tasks", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'deploying'" + }, + "deployed_by": { + "name": "deployed_by", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'ci'" + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "run_url": { + "name": "run_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "log_tail": { + "name": "log_tail", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "releases_project_id_projects_id_fk": { + "name": "releases_project_id_projects_id_fk", + "tableFrom": "releases", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "sessions": { + "name": "sessions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tmux_name": { + "name": "tmux_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'claude'" + }, + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_session_id": { + "name": "claude_session_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "auto_nudges": { + "name": "auto_nudges", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "resume_at": { + "name": "resume_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_probe_min": { + "name": "limit_probe_min", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_resumes": { + "name": "limit_resumes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "limit_resumes_day": { + "name": "limit_resumes_day", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "limit_resumed_at": { + "name": "limit_resumed_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'starting'" + }, + "last_activity_at": { + "name": "last_activity_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "ended_at": { + "name": "ended_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "sessions_tmux_name_unique": { + "name": "sessions_tmux_name_unique", + "columns": [ + "tmux_name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "sessions_project_id_projects_id_fk": { + "name": "sessions_project_id_projects_id_fk", + "tableFrom": "sessions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "sessions_task_id_tasks_id_fk": { + "name": "sessions_task_id_tasks_id_fk", + "tableFrom": "sessions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "sessions_subscription_id_subscriptions_id_fk": { + "name": "sessions_subscription_id_subscriptions_id_fk", + "tableFrom": "sessions", + "tableTo": "subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "settings": { + "name": "settings", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscription_pool_members": { + "name": "subscription_pool_members", + "columns": { + "pool_id": { + "name": "pool_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "subscription_id": { + "name": "subscription_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "subscription_pool_members_pool_id_subscription_pools_id_fk": { + "name": "subscription_pool_members_pool_id_subscription_pools_id_fk", + "tableFrom": "subscription_pool_members", + "tableTo": "subscription_pools", + "columnsFrom": [ + "pool_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "subscription_pool_members_subscription_id_subscriptions_id_fk": { + "name": "subscription_pool_members_subscription_id_subscriptions_id_fk", + "tableFrom": "subscription_pool_members", + "tableTo": "subscriptions", + "columnsFrom": [ + "subscription_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "subscription_pool_members_pool_id_subscription_id_pk": { + "columns": [ + "pool_id", + "subscription_id" + ], + "name": "subscription_pool_members_pool_id_subscription_id_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscription_pools": { + "name": "subscription_pools", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "subscription_pools_name_unique": { + "name": "subscription_pools_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": { + "subscription_pools_created_by_users_id_fk": { + "name": "subscription_pools_created_by_users_id_fk", + "tableFrom": "subscription_pools", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "subscriptions": { + "name": "subscriptions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "auth_kind": { + "name": "auth_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "secret_enc": { + "name": "secret_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "key_provider": { + "name": "key_provider", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "limited_until": { + "name": "limited_until", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_error": { + "name": "last_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "checked_at": { + "name": "checked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "activated_at": { + "name": "activated_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": { + "subscriptions_created_by_users_id_fk": { + "name": "subscriptions_created_by_users_id_fk", + "tableFrom": "subscriptions", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "tasks": { + "name": "tasks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "number": { + "name": "number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'backlog'" + }, + "openspec_change": { + "name": "openspec_change", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pr_url": { + "name": "pr_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ci_attempts": { + "name": "ci_attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "ci_failed_sha": { + "name": "ci_failed_sha", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": { + "tasks_project_number": { + "name": "tasks_project_number", + "columns": [ + "project_id", + "number" + ], + "isUnique": true + } + }, + "foreignKeys": { + "tasks_project_id_projects_id_fk": { + "name": "tasks_project_id_projects_id_fk", + "tableFrom": "tasks", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tasks_goal_id_goals_id_fk": { + "name": "tasks_goal_id_goals_id_fk", + "tableFrom": "tasks", + "tableTo": "goals", + "columnsFrom": [ + "goal_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "telegram_outbox": { + "name": "telegram_outbox", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "method": { + "name": "method", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "params": { + "name": "params", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "question_id": { + "name": "question_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "sent_at": { + "name": "sent_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "telegram_outbox_dedupe_key_unique": { + "name": "telegram_outbox_dedupe_key_unique", + "columns": [ + "dedupe_key" + ], + "isUnique": true + } + }, + "foreignKeys": { + "telegram_outbox_question_id_questions_id_fk": { + "name": "telegram_outbox_question_id_questions_id_fk", + "tableFrom": "telegram_outbox", + "tableTo": "questions", + "columnsFrom": [ + "question_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "telegram_updates": { + "name": "telegram_updates", + "columns": { + "update_id": { + "name": "update_id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "users": { + "name": "users", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "gitea_id": { + "name": "gitea_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "avatar_url": { + "name": "avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "access_token_enc": { + "name": "access_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "refresh_token_enc": { + "name": "refresh_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "token_expires_at": { + "name": "token_expires_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_token_enc": { + "name": "claude_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "claude_token_set_at": { + "name": "claude_token_set_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_chat_id": { + "name": "telegram_chat_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_user_id": { + "name": "telegram_user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_username": { + "name": "telegram_username", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "telegram_paired_at": { + "name": "telegram_paired_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "egov_iin": { + "name": "egov_iin", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "egov_linked_at": { + "name": "egov_linked_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "password_hash": { + "name": "password_hash", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "password_set_at": { + "name": "password_set_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "disabled_at": { + "name": "disabled_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(cast(unixepoch('subsec') * 1000 as integer))" + }, + "last_login_at": { + "name": "last_login_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "users_gitea_id_unique": { + "name": "users_gitea_id_unique", + "columns": [ + "gitea_id" + ], + "isUnique": true + }, + "users_login_unique": { + "name": "users_login_unique", + "columns": [ + "login" + ], + "isUnique": true + }, + "users_telegram_chat_id_unique": { + "name": "users_telegram_chat_id_unique", + "columns": [ + "telegram_chat_id" + ], + "isUnique": true + }, + "users_egov_iin_unique": { + "name": "users_egov_iin_unique", + "columns": [ + "egov_iin" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json index 5d4b60ba..bee3921a 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -22,6 +22,13 @@ "when": 1794608096959, "tag": "0002_local_users", "breakpoints": true + }, + { + "idx": 3, + "version": "6", + "when": 1794608984819, + "tag": "0003_subscriptions", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index d2efad7a..a7e88503 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -1,6 +1,6 @@ import { relations } from "drizzle-orm"; import { sql } from "drizzle-orm"; -import { integer, primaryKey, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core"; +import { integer, primaryKey, sqliteTable, text, uniqueIndex, type AnySQLiteColumn } from "drizzle-orm/sqlite-core"; // SQLite (PEP-36): timestamps are epoch milliseconds (drizzle maps them to Date), JSON is // text (mapped to objects), booleans are 0/1, enums are checked by TypeScript only. @@ -22,8 +22,8 @@ export const users = sqliteTable("users", { accessTokenEnc: text("access_token_enc"), refreshTokenEnc: text("refresh_token_enc"), tokenExpiresAt: integer("token_expires_at", { mode: "timestamp_ms" }), - // Long-lived Claude Code token from `claude setup-token` (encrypted); used for the - // Claude sessions of this user's projects. + // Deprecated (PEP-67): the PEP-13 Claude token moved to `subscriptions`; the migration + // copies it there and clears these columns. Not read by the code any more. claudeTokenEnc: text("claude_token_enc"), claudeTokenSetAt: integer("claude_token_set_at", { mode: "timestamp_ms" }), // Telegram chat paired from Settings; agent questions of this user's projects go there. @@ -58,6 +58,8 @@ export const projects = sqliteTable("projects", { ownerId: integer("owner_id").references(() => users.id, { onDelete: "set null" }), // Next task number to hand out; bumped atomically on task creation. nextTaskNumber: integer("next_task_number").notNull().default(1), + // PEP-67: default subscription pool for the project's runners (set by a superadmin). + subscriptionPoolId: integer("subscription_pool_id").references((): AnySQLiteColumn => subscriptionPools.id, { onDelete: "set null" }), createdAt: createdAt(), updatedAt: updatedAt(), }); @@ -187,13 +189,58 @@ export const sessionStatus = { enumValues: [ "failed", ] as const }; -/** An agent CLI session (Claude Code or Codex) running in tmux on this machine. */ +export const agentProviders = { enumValues: ["claude", "codex", "opencode"] as const }; + +/** + * PEP-67: an agent subscription (Claude Code / Codex / OpenCode) managed by superadmins. + * Claude: OAuth token from `claude setup-token` in `secret_enc`; Codex: the login lives in + * its own CODEX_HOME ($PEPPA_HOME/subscriptions/s/codex); OpenCode: a model provider + * API key in `secret_enc`. Secrets are AES-256-GCM encrypted with PEPPA_SECRET. + */ +export const subscriptions = sqliteTable("subscriptions", { + id: integer("id").primaryKey({ autoIncrement: true }), + provider: text("provider", { enum: agentProviders.enumValues }).notNull(), + name: text("name").notNull(), + authKind: text("auth_kind", { enum: ["oauth", "api_key", "device"] }).notNull(), + secretEnc: text("secret_enc"), + // OpenCode: which model provider the key belongs to (anthropic | openai | openrouter). + keyProvider: text("key_provider"), + status: text("status", { enum: ["pending", "active", "limited", "auth_error"] }).notNull().default("pending"), + limitedUntil: integer("limited_until", { mode: "timestamp_ms" }), + lastError: text("last_error"), + checkedAt: integer("checked_at", { mode: "timestamp_ms" }), + // Became active at least once (a cancelled first login deletes the row). + activatedAt: integer("activated_at", { mode: "timestamp_ms" }), + createdBy: integer("created_by").references(() => users.id, { onDelete: "set null" }), + createdAt: createdAt(), +}); + +/** PEP-67: a named set of subscriptions runners take from (rotation within it — PEP-39). */ +export const subscriptionPools = sqliteTable("subscription_pools", { + id: integer("id").primaryKey({ autoIncrement: true }), + name: text("name").notNull().unique(), + createdBy: integer("created_by").references(() => users.id, { onDelete: "set null" }), + createdAt: createdAt(), +}); + +export const subscriptionPoolMembers = sqliteTable( + "subscription_pool_members", + { + poolId: integer("pool_id").notNull().references(() => subscriptionPools.id, { onDelete: "cascade" }), + subscriptionId: integer("subscription_id").notNull().references(() => subscriptions.id, { onDelete: "cascade" }), + }, + (t) => [primaryKey({ columns: [t.poolId, t.subscriptionId] })], +); + +/** An agent CLI session (Claude Code, Codex or OpenCode) running in tmux on this machine. */ export const sessions = sqliteTable("sessions", { id: integer("id").primaryKey({ autoIncrement: true }), projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), taskId: integer("task_id").references(() => tasks.id, { onDelete: "set null" }), tmuxName: text("tmux_name").notNull().unique(), - provider: text("provider", { enum: ["claude", "codex"] }).notNull().default("claude"), + provider: text("provider", { enum: agentProviders.enumValues }).notNull().default("claude"), + // PEP-67: the subscription the session runs on (null = this machine's own login). + subscriptionId: integer("subscription_id").references(() => subscriptions.id, { onDelete: "set null" }), // Claude session id or Codex thread id — the resume target. conversationId: text("claude_session_id"), // Bumped on every launch/resume; hooks from an older generation are ignored. diff --git a/packages/runner/src/claude-auth.ts b/packages/runner/src/claude-auth.ts deleted file mode 100644 index 8221df0e..00000000 --- a/packages/runner/src/claude-auth.ts +++ /dev/null @@ -1,90 +0,0 @@ -// "Connect Claude" from the web: runs `claude setup-token` on this machine in a tmux -// session, hands the sign-in URL to the user, types back the code they paste into the -// web form, and stores the resulting long-lived token (encrypted) on the user. -import { homedir } from "node:os"; -import { deleteSetting, getSetting, PeppaError, setClaudeToken, setSetting } from "@peppa/core"; -import type { Db } from "@peppa/db"; -import * as tmux from "./tmux.ts"; - -const SETUP_TTL_MS = 10 * 60_000; -const URL_RE = /https:\/\/\S+\/oauth\/authorize\?\S+/; -const TOKEN_RE = /sk-ant-oat\d{2}-[A-Za-z0-9_-]{20,}/; -const ERROR_RE = /(error|invalid|failed|expired)/i; - -const sessionName = (userId: number) => `peppa-auth-u${userId}`; -const settingKey = (userId: number) => `claude.setup.u${userId}`; -const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); - -export interface ClaudeSetup { - url: string; - startedAt: number; -} - -/** Pending setup of this user (null if none or expired). */ -export async function pendingClaudeSetup(db: Db, userId: number): Promise { - const s = await getSetting(db, settingKey(userId)); - if (!s) return null; - if (Date.now() - s.startedAt > SETUP_TTL_MS || !(await tmux.hasSession(sessionName(userId)))) { - await cancelClaudeSetup(db, userId); - return null; - } - return s; -} - -export async function cancelClaudeSetup(db: Db, userId: number): Promise { - await deleteSetting(db, settingKey(userId)); - if (await tmux.hasSession(sessionName(userId))) await tmux.killSession(sessionName(userId)).catch(() => {}); -} - -/** Starts `claude setup-token` and returns the sign-in URL to show the user. */ -export async function startClaudeSetup(db: Db, userId: number): Promise { - await cancelClaudeSetup(db, userId); - await tmux.newSession({ - name: sessionName(userId), - cwd: homedir(), - command: `${process.env.PEPPA_CLAUDE_BIN ?? "claude"} setup-token`, - env: { BROWSER: "/usr/bin/true" }, // don't open a browser on this machine - width: 1000, - }); - for (let i = 0; i < 60; i++) { - await sleep(500); - const url = URL_RE.exec(await tmux.capturePane(sessionName(userId)))?.[0]; - if (url) { - const setup = { url, startedAt: Date.now() }; - await setSetting(db, settingKey(userId), setup); - return setup; - } - } - const tail = await tmux.capturePane(sessionName(userId)).catch(() => ""); - await cancelClaudeSetup(db, userId); - throw new PeppaError(`claude setup-token не показал ссылку входа${tail.trim() ? `: ${tail.trim().split("\n").slice(-3).join(" ")}` : ""}`); -} - -/** Types the user's code into setup-token and stores the token it prints. */ -export async function finishClaudeSetup(db: Db, userId: number, code: string): Promise { - const c = code.trim(); - if (!c || /\s/.test(c)) throw new PeppaError("Вставьте код целиком, без пробелов"); - if (!(await pendingClaudeSetup(db, userId))) throw new PeppaError("Подключение не начато или истекло — нажмите «Подключить Claude» ещё раз"); - const name = sessionName(userId); - const before = await tmux.capturePane(name); - await tmux.sendText(name, c); - for (let i = 0; i < 60; i++) { - await sleep(500); - const screen = await tmux.capturePane(name, 200); - const token = TOKEN_RE.exec(screen)?.[0]; - if (token) { - await setClaudeToken(db, userId, token); - await cancelClaudeSetup(db, userId); // also wipes the token from the tmux scrollback - return; - } - const after = screen.slice(screen.indexOf(c) >= 0 ? screen.indexOf(c) + c.length : before.length); - const dead = (await tmux.paneState(name)).dead; - if (dead || ERROR_RE.test(after)) { - const msg = after.replace(TOKEN_RE, "…").trim().split("\n").filter(Boolean).slice(-2).join(" "); - await cancelClaudeSetup(db, userId); - throw new PeppaError(`Claude не принял код${msg ? `: ${msg.slice(0, 200)}` : ""}. Начните заново.`); - } - } - await cancelClaudeSetup(db, userId); - throw new PeppaError("Claude не ответил на код за 30 секунд. Начните заново."); -} diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts index ec96a83e..3112ece5 100644 --- a/packages/runner/src/index.ts +++ b/packages/runner/src/index.ts @@ -6,7 +6,8 @@ export * from "./run-settings.ts"; export * from "./providers.ts"; export * from "./provision.ts"; export * from "./flow.ts"; -export * from "./claude-auth.ts"; +export * from "./subscription-login.ts"; +export * from "./subscriptions.ts"; export * from "./share.ts"; export * from "./limits.ts"; export * from "./monitor.ts"; diff --git a/packages/runner/src/providers.ts b/packages/runner/src/providers.ts index 35ce0cce..1219278c 100644 --- a/packages/runner/src/providers.ts +++ b/packages/runner/src/providers.ts @@ -1,11 +1,12 @@ -import { dirname, resolve } from "node:path"; +import { writeFileSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import type { Session } from "@peppa/core"; import { peppaRoot } from "@peppa/shared"; -import { writeRunRules, writeRunSettings } from "./run-settings.ts"; +import { runDir, writeRunRules, writeRunSettings } from "./run-settings.ts"; export type Provider = Session["provider"]; -export const PROVIDERS: Provider[] = ["claude", "codex"]; +export const PROVIDERS: Provider[] = ["claude", "codex", "opencode"]; // PEPPA_ROOT first: inside a Next.js build import.meta.url points into .next/. const ROOT = () => peppaRoot(resolve(dirname(fileURLToPath(import.meta.url)), "../../..")); @@ -25,7 +26,12 @@ export interface LaunchContext { /** argv for one run of the agent CLI (executable first). */ export function buildCommand(provider: Provider, c: LaunchContext): string[] { - return provider === "codex" ? codexCommand(c) : claudeCommand(c); + return provider === "codex" ? codexCommand(c) : provider === "opencode" ? opencodeCommand(c) : claudeCommand(c); +} + +/** Extra environment the provider's CLI needs for this run (OpenCode reads its config from a file). */ +export function providerEnv(provider: Provider, c: Pick): Record { + return provider === "opencode" ? { OPENCODE_CONFIG: join(runDir(c.sessionId, c.generation), "opencode.json") } : {}; } function claudeCommand(c: LaunchContext): string[] { @@ -69,3 +75,32 @@ function codexCommand(c: LaunchContext): string[] { c.prompt, ]; } + +/** + * OpenCode (PEP-67): TUI in tmux; rules and the peppa MCP server come from a generated + * opencode.json (OPENCODE_CONFIG, see providerEnv). It has no Claude-style hooks — the + * watchdog follows the process (alive, dead, stalled); hooks via an OpenCode plugin later. + */ +function opencodeCommand(c: LaunchContext): string[] { + const dir = runDir(c.sessionId, c.generation); + writeFileSync( + join(dir, "opencode.json"), + JSON.stringify( + { + $schema: "https://opencode.ai/config.json", + instructions: [writeRunRules(c.sessionId, c.generation, c.rules)], + mcp: { peppa: { type: "local", command: [MCP_BIN()], enabled: true } }, + }, + null, + 2, + ), + ); + return [ + process.env.PEPPA_OPENCODE_BIN ?? "opencode", + c.cwd, + ...(c.model ? ["--model", c.model] : []), + ...(c.resume ? ["--session", c.resume] : []), + "--prompt", + c.prompt, + ]; +} diff --git a/packages/runner/src/sessions.ts b/packages/runner/src/sessions.ts index 8e999444..7668e4df 100644 --- a/packages/runner/src/sessions.ts +++ b/packages/runner/src/sessions.ts @@ -2,7 +2,8 @@ import { chmodSync, existsSync, realpathSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { answerQuestion, - claudeTokenForProject, + getSubscription, + pickSubscription, createSession, expireSessionQuestions, getSession, @@ -20,7 +21,8 @@ import { projects, tasks, type Db } from "@peppa/db"; import { eq } from "drizzle-orm"; import { loadEnv } from "@peppa/shared"; import { trustWorkspace } from "./claude-config.ts"; -import { buildCommand, type Provider } from "./providers.ts"; +import { buildCommand, providerEnv, type Provider } from "./providers.ts"; +import { subscriptionEnv } from "./subscriptions.ts"; import { runDir } from "./run-settings.ts"; import * as tmux from "./tmux.ts"; import { onReleaseAnswer } from "./deploy.ts"; @@ -33,6 +35,9 @@ export interface StartOptions { /** Project for a bare task number ("42"). */ defaultProjectKey?: string; provider?: Provider; + /** PEP-67: subscriptions ticked at launch (multiple choice); else `poolId`; else the project's pool. */ + subscriptionIds?: number[]; + poolId?: number | null; } const shq = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`; @@ -44,9 +49,11 @@ export async function startSession(db: Db, taskInput: string, opts: StartOptions if (!existsSync(dir)) throw new PeppaError(`Workspace ${dir} does not exist — bootstrap the project first`); const cwd = realpathSync(dir); - const provider = opts.provider ?? (process.env.PEPPA_PROVIDER as Provider | undefined) ?? "claude"; + // PEP-67: the first free active subscription of the chosen set decides the provider. + const sub = await pickSubscription(db, { projectId: ref.project.id, subscriptionIds: opts.subscriptionIds, poolId: opts.poolId, provider: opts.provider }); + const provider = sub?.provider ?? opts.provider ?? (process.env.PEPPA_PROVIDER as Provider | undefined) ?? "claude"; if (provider === "claude") trustWorkspace(cwd); - const session = await createSession(db, { projectId: ref.project.id, taskId: ref.task.id, provider }); + const session = await createSession(db, { projectId: ref.project.id, taskId: ref.task.id, provider, subscriptionId: sub?.id ?? null }); const tmuxName = `peppa-${ref.key.toLowerCase()}-s${session.id}`; await updateSession(db, session.id, { tmuxName }); const prompt = [`Работай над стори ${ref.key} по правилам AGENTS.md.`, opts.prompt].filter(Boolean).join("\n\n"); @@ -84,8 +91,8 @@ async function launch( ): Promise { const generation = s.generation + 1; const rules = await loadSharedRules(); - const [owner] = await db.select({ ownerId: projects.ownerId }).from(projects).where(eq(projects.id, s.projectId)); - const claudeToken = s.provider === "claude" && owner ? await claudeTokenForProject(db, owner) : null; + // The session's subscription (no rotation on resume — PEP-39); none = this machine's login. + const sub = s.subscriptionId ? await getSubscription(db, s.subscriptionId).catch(() => null) : null; const argv = buildCommand(s.provider, { sessionId: s.id, generation, @@ -98,6 +105,7 @@ async function launch( }); // tmux runs a tiny launch script: keeps long argv (rules, prompts) out of the tmux // command line, and leaves a record of exactly what was started. + const ctx = { sessionId: s.id, generation }; const launchScript = join(runDir(s.id, generation), "launch.sh"); writeFileSync(launchScript, `#!/bin/bash\nexec ${argv.map(shq).join(" ")}\n`); chmodSync(launchScript, 0o700); @@ -114,8 +122,9 @@ async function launch( // Hooks and the MCP server must talk to the same DB / state dir as the runner. PEPPA_DB: loadEnv().PEPPA_DB, ...(process.env.PEPPA_HOME ? { PEPPA_HOME: process.env.PEPPA_HOME } : {}), - // The project owner's own Claude subscription, if they connected it (PEP-13). - ...(claudeToken ? { CLAUDE_CODE_OAUTH_TOKEN: claudeToken } : {}), + ...providerEnv(s.provider, ctx), + // 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 } : {}), }, }); @@ -129,6 +138,7 @@ async function launch( tmuxName: s.tmuxName, prompt: opts.prompt, provider: s.provider, + subscriptionId: sub?.id ?? null, rulesSource: rules.source, }); return getSession(db, s.id); diff --git a/packages/runner/src/subscription-login.ts b/packages/runner/src/subscription-login.ts new file mode 100644 index 00000000..1ff6a4c6 --- /dev/null +++ b/packages/runner/src/subscription-login.ts @@ -0,0 +1,242 @@ +// Sign-in of agent subscriptions from the web (PEP-13 → PEP-67): the agent CLI's own login +// runs on this machine in a tmux session (`peppa-auth-sub`); the superadmin opens the +// link on their device and, for Claude, pastes the code back into the web form. +// Claude — `claude setup-token`: URL → code → long-lived token, stored encrypted. +// Codex — `codex login --device-auth` with the subscription's own CODEX_HOME: URL + one-time +// code; Codex itself writes auth.json there when the user confirms on their device. +import { execFile } from "node:child_process"; +import { existsSync, mkdirSync, rmSync } from "node:fs"; +import { homedir } from "node:os"; +import { join } from "node:path"; +import { + deleteSetting, + deleteSubscription, + getSetting, + getSubscription, + PeppaError, + setSetting, + updateSubscription, + type Subscription, +} from "@peppa/core"; +import type { Db } from "@peppa/db"; +import { peppaHome } from "@peppa/shared"; +import * as tmux from "./tmux.ts"; + +const LOGIN_TTL_MS = 10 * 60_000; +const CLAUDE_URL_RE = /https:\/\/\S+\/oauth\/authorize\?\S+/; +const TOKEN_RE = /sk-ant-oat\d{2}-[A-Za-z0-9_-]{20,}/; +const ERROR_RE = /(error|invalid|failed|expired)/i; +const CODEX_URL_RE = /https:\/\/\S+/; +const CODEX_CODE_RE = /\b[A-Z0-9]{4,5}-[A-Z0-9]{4,5}\b/; + +const sessionName = (id: number) => `peppa-auth-sub${id}`; +const settingKey = (id: number) => `subscription.login:${id}`; +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); + +/** Login dir of a subscription (Codex: CODEX_HOME). Private: the CLI keeps credentials there. */ +export function subscriptionDir(id: number): string { + return join(peppaHome(), "subscriptions", `s${id}`); +} +export function codexHome(id: number): string { + const dir = join(subscriptionDir(id), "codex"); + mkdirSync(dir, { recursive: true, mode: 0o700 }); + return dir; +} + +export interface PendingLogin { + kind: "claude" | "codex"; + url: string; + /** Codex device auth: the one-time code to enter on the device. */ + code?: string; + startedAt: number; +} + +/** Pending sign-in of a subscription (null if none or expired). */ +export async function pendingLogin(db: Db, id: number): Promise { + const s = await getSetting(db, settingKey(id)); + if (!s) return null; + if (Date.now() - s.startedAt > LOGIN_TTL_MS || !(await tmux.hasSession(sessionName(id)))) { + await endLogin(db, id); + return null; + } + return s; +} + +async function endLogin(db: Db, id: number): Promise { + await deleteSetting(db, settingKey(id)); + if (await tmux.hasSession(sessionName(id))) await tmux.killSession(sessionName(id)).catch(() => {}); +} + +/** Cancels a sign-in; a subscription that was never active disappears with it. */ +export async function cancelLogin(db: Db, id: number): Promise { + await endLogin(db, id); + const s = await getSubscription(db, id).catch(() => null); + if (s && !s.activatedAt) await removeSubscription(db, id); +} + +/** Deletes a subscription with its login dir (and any sign-in in progress). */ +export async function removeSubscription(db: Db, id: number): Promise { + await endLogin(db, id); + await deleteSubscription(db, id); + rmSync(subscriptionDir(id), { recursive: true, force: true }); +} + +async function waitForScreen(id: number, re: RegExp, what: string): Promise { + for (let i = 0; i < 60; i++) { + await sleep(500); + const screen = await tmux.capturePane(sessionName(id), 200).catch(() => ""); + if (re.test(screen)) return screen; + if ((await tmux.paneState(sessionName(id)).catch(() => ({ dead: true }))).dead) break; + } + const tail = (await tmux.capturePane(sessionName(id)).catch(() => "")).trim(); + throw new PeppaError(`${what} не показал ссылку входа${tail ? `: ${tail.split("\n").slice(-3).join(" ").slice(0, 200)}` : ""}`); +} + +// ── Claude ─────────────────────────────────────────────────────────────────────── + +/** Starts `claude setup-token` for a Claude subscription and returns the sign-in URL. */ +export async function startClaudeLogin(db: Db, id: number): Promise { + const sub = await getSubscription(db, id); + if (sub.provider !== "claude") throw new PeppaError("Это не подписка Claude"); + await endLogin(db, id); + await tmux.newSession({ + name: sessionName(id), + cwd: homedir(), + command: `${process.env.PEPPA_CLAUDE_BIN ?? "claude"} setup-token`, + env: { BROWSER: "/usr/bin/true" }, // don't open a browser on this machine + width: 1000, + }); + try { + const url = CLAUDE_URL_RE.exec(await waitForScreen(id, CLAUDE_URL_RE, "claude setup-token"))![0]; + const login: PendingLogin = { kind: "claude", url, startedAt: Date.now() }; + await setSetting(db, settingKey(id), login); + return login; + } catch (e) { + await endLogin(db, id); + throw e; + } +} + +/** Types the code into setup-token and stores the token it prints on the subscription. */ +export async function finishClaudeLogin(db: Db, id: number, code: string): Promise { + const c = code.trim(); + if (!c || /\s/.test(c)) throw new PeppaError("Вставьте код целиком, без пробелов"); + const login = await pendingLogin(db, id); + if (login?.kind !== "claude") throw new PeppaError("Вход не начат или истёк — начните заново"); + const name = sessionName(id); + const before = await tmux.capturePane(name); + await tmux.sendText(name, c); + for (let i = 0; i < 60; i++) { + await sleep(500); + const screen = await tmux.capturePane(name, 200); + const token = TOKEN_RE.exec(screen)?.[0]; + if (token) { + await updateSubscription(db, id, { secret: token, authKind: "oauth", status: "active", checkedAt: new Date() }); + await endLogin(db, id); // also wipes the token from the tmux scrollback + return; + } + const after = screen.slice(screen.indexOf(c) >= 0 ? screen.indexOf(c) + c.length : before.length); + const dead = (await tmux.paneState(name)).dead; + if (dead || ERROR_RE.test(after)) { + const msg = after.replace(TOKEN_RE, "…").trim().split("\n").filter(Boolean).slice(-2).join(" "); + await endLogin(db, id); + throw new PeppaError(`Claude не принял код${msg ? `: ${msg.slice(0, 200)}` : ""}. Начните заново.`); + } + } + await endLogin(db, id); + throw new PeppaError("Claude не ответил на код за 30 секунд. Начните заново."); +} + +/** A ready token pasted by hand (from `claude setup-token` run elsewhere). */ +export async function setClaudeSubscriptionToken(db: Db, id: number, token: string): Promise { + const t = token.trim(); + if (!TOKEN_RE.test(t) || TOKEN_RE.exec(t)![0] !== t) throw new PeppaError("Это не похоже на токен Claude (sk-ant-oat…)"); + await endLogin(db, id); + await updateSubscription(db, id, { secret: t, authKind: "oauth", status: "active", checkedAt: new Date() }); +} + +// ── Codex ──────────────────────────────────────────────────────────────────────── + +/** Starts `codex login --device-auth` with the subscription's CODEX_HOME: URL + one-time code. */ +export async function startCodexLogin(db: Db, id: number): Promise { + const sub = await getSubscription(db, id); + if (sub.provider !== "codex") throw new PeppaError("Это не подписка Codex"); + await endLogin(db, id); + await tmux.newSession({ + name: sessionName(id), + cwd: homedir(), + command: `${process.env.PEPPA_CODEX_BIN ?? "codex"} login --device-auth`, + env: { CODEX_HOME: codexHome(id), BROWSER: "/usr/bin/true" }, + width: 300, + }); + try { + const screen = await waitForScreen(id, CODEX_CODE_RE, "codex login"); + const url = CODEX_URL_RE.exec(screen)?.[0]; + if (!url) throw new PeppaError("codex login не показал ссылку входа"); + const login: PendingLogin = { kind: "codex", url, code: CODEX_CODE_RE.exec(screen)![0], startedAt: Date.now() }; + await setSetting(db, settingKey(id), login); + await updateSubscription(db, id, { authKind: "device" }); + return login; + } catch (e) { + await endLogin(db, id); + throw e; + } +} + +/** + * Where a Codex device sign-in stands: still waiting for the user, done (auth.json written, + * subscription active) or failed. Called by the page while it shows the code. + */ +export async function pollCodexLogin(db: Db, id: number): Promise<"pending" | "active" | "failed" | "none"> { + const login = await getSetting(db, settingKey(id)); + if (login?.kind !== "codex") return "none"; + const name = sessionName(id); + const state = (await tmux.hasSession(name)) ? await tmux.paneState(name) : { dead: true, exitStatus: null }; + if (!state.dead) { + if (Date.now() - login.startedAt > LOGIN_TTL_MS) { + await endLogin(db, id); + await updateSubscription(db, id, { status: "auth_error", lastError: "вход не подтверждён за 10 минут" }); + return "failed"; + } + return "pending"; + } + const screen = await tmux.capturePane(name, 200).catch(() => ""); + await endLogin(db, id); + if (state.exitStatus === 0 && existsSync(join(codexHome(id), "auth.json"))) { + await updateSubscription(db, id, { status: "active", checkedAt: new Date() }); + return "active"; + } + const msg = screen.trim().split("\n").filter(Boolean).slice(-2).join(" ").slice(0, 200); + await updateSubscription(db, id, { status: "auth_error", lastError: msg || `codex login завершился с кодом ${state.exitStatus}` }); + return "failed"; +} + +/** API key for Codex: `codex login --with-api-key` (key on stdin, never in argv or logs). */ +export async function setCodexApiKey(db: Db, id: number, key: string): Promise { + const k = key.trim(); + if (!k || /\s/.test(k)) throw new PeppaError("Вставьте ключ целиком, без пробелов"); + await endLogin(db, id); + const out = await new Promise<{ code: number | null; text: string }>((resolve) => { + const child = execFile( + process.env.PEPPA_CODEX_BIN ?? "codex", + ["login", "--with-api-key"], + { env: { ...process.env, CODEX_HOME: codexHome(id) }, timeout: 60_000 }, + (err, stdout, stderr) => resolve({ code: err ? ((err as { code?: number }).code ?? 1) : 0, text: `${stdout}${stderr}` }), + ); + child.stdin?.end(`${k}\n`); + }); + if (out.code !== 0) { + await updateSubscription(db, id, { status: "auth_error", authKind: "api_key", lastError: mask(out.text, [k]).trim().slice(-200) }); + throw new PeppaError(`Codex не принял ключ: ${mask(out.text, [k]).trim().split("\n").slice(-1)[0]?.slice(0, 200) ?? ""}`); + } + await updateSubscription(db, id, { status: "active", authKind: "api_key", checkedAt: new Date() }); +} + +/** Removes secrets from CLI output before it is stored or shown. */ +export function mask(text: string, secrets: Array): string { + let t = text.replace(TOKEN_RE, "sk-ant-…").replace(/\bsk-[A-Za-z0-9_-]{16,}/g, "sk-…"); + for (const s of secrets) if (s && s.length > 6) t = t.split(s).join("…"); + return t; +} + +export type { Subscription }; diff --git a/packages/runner/src/subscriptions.ts b/packages/runner/src/subscriptions.ts new file mode 100644 index 00000000..54571810 --- /dev/null +++ b/packages/runner/src/subscriptions.ts @@ -0,0 +1,128 @@ +// Agent subscriptions on this machine (PEP-67): the environment an agent CLI gets for a +// subscription, and «Проверить» — a short trial run that updates the subscription's status. +import { spawn } from "node:child_process"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createSubscription, getSubscription, OPENCODE_KEY_ENV, PeppaError, subscriptionSecret, updateSubscription, type Subscription } from "@peppa/core"; +import type { Db } from "@peppa/db"; +import { parseResetTime } from "./limits.ts"; +import { codexHome, mask, removeSubscription, setClaudeSubscriptionToken, setCodexApiKey, startClaudeLogin, startCodexLogin } from "./subscription-login.ts"; + +/** Environment for the agent CLI running on this subscription. */ +export function subscriptionEnv(s: Subscription): Record { + switch (s.provider) { + case "claude": { + const token = subscriptionSecret(s); + return token ? { CLAUDE_CODE_OAUTH_TOKEN: token } : {}; + } + case "codex": + return { CODEX_HOME: codexHome(s.id) }; + case "opencode": { + const key = subscriptionSecret(s); + const env = s.keyProvider ? OPENCODE_KEY_ENV[s.keyProvider] : undefined; + return key && env ? { [env]: key } : {}; + } + } +} + +export interface NewSubscription { + provider: Subscription["provider"]; + name: string; + /** claude: "login" (setup-token) | "token"; codex: "device" | "api_key"; opencode: key. */ + method: string; + secret?: string; + keyProvider?: string; + createdBy: number; +} + +/** + * Adds a subscription the way the superadmin chose: Claude/Codex sign-in starts right away + * (the page then shows the link), a pasted token or key makes it active at once. + */ +export async function addSubscription(db: Db, n: NewSubscription): Promise { + if (n.provider === "opencode") { + if (!n.secret?.trim()) throw new PeppaError("Вставьте ключ провайдера"); + const s = await createSubscription(db, { provider: "opencode", name: n.name, authKind: "api_key", secret: n.secret.trim(), keyProvider: n.keyProvider, createdBy: n.createdBy }); + return updateSubscription(db, s.id, { status: "active" }); + } + const authKind = n.method === "api_key" ? "api_key" : n.method === "device" ? "device" : "oauth"; + const s = await createSubscription(db, { provider: n.provider, name: n.name, authKind, createdBy: n.createdBy }); + try { + if (n.provider === "claude" && n.method === "token") await setClaudeSubscriptionToken(db, s.id, n.secret ?? ""); + else if (n.provider === "claude") await startClaudeLogin(db, s.id); + else if (n.method === "api_key") await setCodexApiKey(db, s.id, n.secret ?? ""); + else await startCodexLogin(db, s.id); + } catch (e) { + await removeSubscription(db, s.id); + throw e; + } + return getSubscription(db, s.id); +} + +const LIMIT_RE = /(usage limit|rate limit|limit reached|hit your limit|limit will reset|quota exceeded|too many requests|\b429\b)/i; +const PROBE_PROMPT = "Ответь одним словом: ok"; + +function probeArgs(s: Subscription): { bin: string; args: string[] } { + switch (s.provider) { + case "claude": + return { bin: process.env.PEPPA_CLAUDE_BIN ?? "claude", args: ["-p", PROBE_PROMPT, "--max-turns", "1"] }; + case "codex": + return { bin: process.env.PEPPA_CODEX_BIN ?? "codex", args: ["exec", "--skip-git-repo-check", PROBE_PROMPT] }; + case "opencode": + return { bin: process.env.PEPPA_OPENCODE_BIN ?? "opencode", args: ["run", PROBE_PROMPT] }; + } +} + +export interface CheckResult { + status: Subscription["status"]; + message: string; +} + +/** + * «Проверить»: a short non-interactive run of the CLI on this subscription in an empty dir. + * Exit 0 → active; a limit message → limited (until the reset time, else for an hour); + * anything else → auth error with the CLI's last lines (secrets masked). + */ +export async function checkSubscription(db: Db, id: number, now = new Date()): Promise { + const s = await getSubscription(db, id); + if (s.status === "pending") throw new PeppaError("Сначала завершите вход"); + const { bin, args } = probeArgs(s); + const env = subscriptionEnv(s); + const timeoutMs = Number(process.env.PEPPA_SUBSCRIPTION_CHECK_TIMEOUT_MS ?? 60_000); + const cwd = mkdtempSync(join(tmpdir(), "peppa-sub-check-")); + let out: { code: number | null; text: string }; + try { + out = await new Promise((resolve) => { + const child = spawn(bin, args, { cwd, env: { ...process.env, ...env }, stdio: ["ignore", "pipe", "pipe"], detached: true }); + let text = ""; + const timer = setTimeout(() => { + try { + process.kill(-child.pid!, "SIGKILL"); + } catch { + child.kill("SIGKILL"); + } + resolve({ code: null, text: `${text}\nне ответил за ${Math.round(timeoutMs / 1000)} с` }); + }, timeoutMs); + child.stdout.on("data", (d) => (text += d)); + child.stderr.on("data", (d) => (text += d)); + child.on("error", (e) => (clearTimeout(timer), resolve({ code: 127, text: e.message }))); + child.on("close", (code) => (clearTimeout(timer), resolve({ code, text }))); + }); + } finally { + rmSync(cwd, { recursive: true, force: true }); + } + const text = mask(out.text, Object.values(env)).trim(); + const tail = text.split("\n").filter(Boolean).slice(-2).join(" ").slice(0, 300); + if (LIMIT_RE.test(out.text)) { + const until = parseResetTime(out.text, now) ?? new Date(now.getTime() + 60 * 60_000); + await updateSubscription(db, id, { status: "limited", limitedUntil: until, lastError: tail, checkedAt: now }); + return { status: "limited", message: tail }; + } + if (out.code === 0) { + await updateSubscription(db, id, { status: "active", checkedAt: now }); + return { status: "active", message: tail }; + } + await updateSubscription(db, id, { status: "auth_error", lastError: tail || `код ${out.code}`, checkedAt: now }); + return { status: "auth_error", message: tail }; +} diff --git a/packages/runner/src/triage.ts b/packages/runner/src/triage.ts index fe42a8b2..0d804496 100644 --- a/packages/runner/src/triage.ts +++ b/packages/runner/src/triage.ts @@ -65,7 +65,7 @@ export function parseTriageOutput(stdout: string): TriageDecision | null { } } -/** Runs `$PEPPA_TRIAGE_BIN -p` (default `claude`) on the project owner's Claude subscription. */ +/** Runs `$PEPPA_TRIAGE_BIN -p` (default `claude`) on a Claude subscription of the project's pool (PEP-67). */ export async function runTriage(db: Db, project: Project, i: Incident, pmPrompt: string): Promise { const bin = process.env.PEPPA_TRIAGE_BIN ?? "claude"; const TIMEOUT_MS = Number(process.env.PEPPA_TRIAGE_TIMEOUT_MS ?? 90_000); diff --git a/packages/testkit/bin/mock-opencode b/packages/testkit/bin/mock-opencode new file mode 100755 index 00000000..065ab78c --- /dev/null +++ b/packages/testkit/bin/mock-opencode @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +# Mock opencode CLI for Peppa tests and manual runs (see packages/testkit/src/mock-agent.ts). +ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)" +exec "${PEPPA_NODE:-node}" --import "$ROOT/scripts/lib/require-node.mjs" "$ROOT/packages/testkit/src/mock-agent.ts" opencode "$@" diff --git a/packages/testkit/src/mock-agent.ts b/packages/testkit/src/mock-agent.ts index f283efd0..9d19f8e5 100644 --- a/packages/testkit/src/mock-agent.ts +++ b/packages/testkit/src/mock-agent.ts @@ -4,17 +4,22 @@ // paste, single-key permission dialog). Behaviour comes from a scenario file, so tests can // drive every customer journey: approvals, questions, permissions, limits, hangs, crashes. // -// Usage: mock-agent.ts [cli args...] +// OpenCode (PEP-67): `opencode --prompt

[--session ]` with rules and the MCP +// server from $OPENCODE_CONFIG; no hooks. Subcommands for subscription sign-in and checks: +// `claude setup-token`, `claude -p`, `codex login --device-auth|--with-api-key`, `codex exec`, +// `opencode run`. +// +// Usage: mock-agent.ts [cli args...] // Typing "!{json action}" as a prompt runs that action — handy for manual runs. import { spawn } from "node:child_process"; import { randomUUID } from "node:crypto"; -import { appendFileSync, existsSync, readFileSync } from "node:fs"; +import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; import type { Action, Scenario } from "./scenario.ts"; -type Provider = "claude" | "codex"; +type Provider = "claude" | "codex" | "opencode"; const provider = process.argv[2] as Provider; const argv = process.argv.slice(3); const cwd = process.cwd(); @@ -50,6 +55,10 @@ function parseArgs(): Args { else if (x === "--append-system-prompt-file") a.rulesFile = argv[++i]; else if (x === "--resume") a.resume = argv[++i]; else if (x === "resume") a.resume = argv[++i]; + else if (provider === "opencode" && x === "--session") a.resume = argv[++i]; + else if (provider === "opencode" && x === "--prompt") { + a.prompt = argv[++i]; + } else if (provider === "opencode" && x === "--model") i++; else if (x === "-c") { const [k, ...v] = argv[++i]!.split("="); const val = JSON.parse(v.join("=")); @@ -62,6 +71,12 @@ function parseArgs(): Args { } const args = parseArgs(); +// OpenCode: rules (instructions) and the peppa MCP server come from the generated config. +if (provider === "opencode" && process.env.OPENCODE_CONFIG && existsSync(process.env.OPENCODE_CONFIG)) { + const cfg = JSON.parse(readFileSync(process.env.OPENCODE_CONFIG, "utf8")); + args.rulesFile = cfg.instructions?.[0]; + args.mcpCommand = cfg.mcp?.peppa?.command?.[0]; +} const conversationId = args.resume ?? randomUUID(); let lastMessage = ""; @@ -340,13 +355,15 @@ async function main() { rulesChars: rules.length, rulesHead: rules.split("\n")[0], oauthToken: process.env.CLAUDE_CODE_OAUTH_TOKEN ? `…${process.env.CLAUDE_CODE_OAUTH_TOKEN.slice(-4)}` : null, + codexHome: process.env.CODEX_HOME ?? null, + apiKey: apiKey() ? `…${apiKey()!.slice(-4)}` : null, }); if (process.stdin.isTTY) process.stdin.setRawMode(true); process.stdin.setEncoding("utf8"); process.stdin.on("data", onInput); process.stdout.write("\x1b[?2004h"); // ask the terminal for bracketed paste - out(`${provider === "claude" ? "✻ Mock Claude Code" : ">_ Mock Codex"} — ${cwd}${args.resume ? ` (resumed ${args.resume})` : ""}\n`); + out(`${provider === "claude" ? "✻ Mock Claude Code" : provider === "opencode" ? "▣ Mock OpenCode" : ">_ Mock Codex"} — ${cwd}${args.resume ? ` (resumed ${args.resume})` : ""}\n`); if (provider === "claude") await fireHook("SessionStart", { source: args.resume ? "resume" : "startup" }, args.resume ? "resume" : "startup"); @@ -386,7 +403,76 @@ async function setupToken() { process.exit(1); } -(argv[0] === "setup-token" ? setupToken() : main()).catch((e) => { +const apiKey = () => process.env.ANTHROPIC_API_KEY ?? process.env.OPENAI_API_KEY ?? process.env.OPENROUTER_API_KEY; + +/** + * Trial runs for «Проверить» (`claude -p`, `codex exec`, `opencode run`): the credential's + * text decides — "bad" → auth error, "limit" → usage limit banner with a reset time, else ok. + */ +function probe(): never { + const fail = (msg: string) => (process.stderr.write(`${msg}\n`), process.exit(1)); + let cred: string | undefined; + if (provider === "claude") cred = process.env.CLAUDE_CODE_OAUTH_TOKEN ?? "mock-machine-login"; + else if (provider === "opencode") cred = apiKey(); + else { + const auth = join(process.env.CODEX_HOME ?? join(process.env.HOME ?? "", ".codex"), "auth.json"); + cred = existsSync(auth) ? readFileSync(auth, "utf8") : undefined; + } + if (!cred) fail(provider === "codex" ? "Not logged in. Run `codex login`." : "Error: no API key configured"); + if (cred!.includes("bad")) fail(provider === "claude" ? "Invalid API key · Please run /login" : "Error: 401 Unauthorized: invalid credentials"); + if (cred!.includes("limit")) fail(provider === "claude" ? "Claude AI usage limit reached. Your limit resets 5pm" : "You've hit your usage limit. Try again at 5:00 PM."); + process.stdout.write("ok\n"); + process.exit(0); +} + +/** + * `codex login --device-auth`: prints the device URL and a one-time code like the real CLI, + * then waits until the test "confirms on the device" ($CODEX_HOME/mock-device-approved or + * …-denied) and writes auth.json. `codex login --with-api-key`: key on stdin. + */ +async function codexLogin() { + const home = process.env.CODEX_HOME ?? join(process.env.HOME ?? "", ".codex"); + mkdirSync(home, { recursive: true }); + if (argv.includes("--with-api-key")) { + let key = ""; + for await (const chunk of process.stdin) key += chunk; + key = key.trim(); + if (!key || key.startsWith("mock-bad")) { + process.stderr.write("Error: invalid API key\n"); + process.exit(1); + } + writeFileSync(join(home, "auth.json"), JSON.stringify({ OPENAI_API_KEY: key })); + process.stdout.write("Successfully logged in\n"); + process.exit(0); + } + const code = `MOCK-${randomUUID().slice(0, 4).toUpperCase().replace(/[^A-Z0-9]/g, "Q")}`; + out("\nWelcome to Codex [mock]\nFollow these steps to sign in with ChatGPT using device code authorization:\n\n"); + out("1. Open this link in your browser and sign in to your account\n https://auth.openai.com/codex/device\n\n"); + out(`2. Enter this one-time code (expires in 15 minutes)\n ${code}\n\n`); + for (;;) { + await sleep(200); + if (existsSync(join(home, "mock-device-denied"))) { + out("Error logging in with device code: device authorization was denied\n"); + process.exit(1); + } + if (existsSync(join(home, "mock-device-approved"))) { + const extra = readFileSync(join(home, "mock-device-approved"), "utf8"); + writeFileSync(join(home, "auth.json"), JSON.stringify({ auth_mode: "chatgpt", tokens: { access_token: `mock-chatgpt-${randomUUID()}${extra.trim()}` } })); + out("Successfully logged in\n"); + process.exit(0); + } + } +} + +const sub = + provider === "claude" && argv[0] === "setup-token" + ? setupToken() + : (provider === "claude" && argv[0] === "-p") || (provider === "codex" && argv[0] === "exec") || (provider === "opencode" && argv[0] === "run") + ? Promise.resolve(probe()) + : provider === "codex" && argv[0] === "login" + ? codexLogin() + : main(); +sub.catch((e) => { log("fatal", { error: String(e?.stack ?? e) }); process.exit(1); }); diff --git a/packages/testkit/test/claude-auth.test.ts b/packages/testkit/test/claude-auth.test.ts deleted file mode 100644 index 83d47458..00000000 --- a/packages/testkit/test/claude-auth.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -// PEP-13: connect Claude from the web (setup-token in tmux) and use the token in sessions. -import assert from "node:assert/strict"; -import { after, before, describe, test } from "node:test"; -import { core, db, project, runner, teardown } from "./helpers.ts"; - -process.env.PEPPA_SECRET = "mock-secret-for-tests"; - -let user: Awaited>; -before(async () => { - user = await core.upsertUserFromGitea(db, { id: 31, login: "mock-claude-user" }, { access_token: "x" }); -}); -after(teardown); - -describe("connect Claude", () => { - test("wrong code → error, nothing stored; right code → encrypted token", async () => { - const s1 = await runner.startClaudeSetup(db, user.id); - assert.match(s1.url, /^https:\/\/claude\.com\/cai\/oauth\/authorize\?/); - assert.deepEqual((await runner.pendingClaudeSetup(db, user.id))?.url, s1.url); - await assert.rejects(runner.finishClaudeSetup(db, user.id, "mock-bad-code"), /не принял код/); - assert.equal((await core.getUser(db, user.id))?.claudeTokenEnc, null); - assert.equal(await runner.pendingClaudeSetup(db, user.id), null, "failed setup is cleaned up"); - await assert.rejects(runner.finishClaudeSetup(db, user.id, "mock-good-1"), /не начато/); - - await runner.startClaudeSetup(db, user.id); - await runner.finishClaudeSetup(db, user.id, "mock-good-1"); - const u = (await core.getUser(db, user.id))!; - assert.ok(u.claudeTokenEnc && !u.claudeTokenEnc.includes("sk-ant"), "stored encrypted"); - assert.match(core.decrypt(u.claudeTokenEnc), /^sk-ant-oat01-mock/); - assert.ok(u.claudeTokenSetAt); - assert.equal(await runner.pendingClaudeSetup(db, user.id), null); - }); - - test("sessions of the owner's projects get the token; other projects and disconnect don't", async () => { - const token = core.decrypt((await core.getUser(db, user.id))!.claudeTokenEnc!); - const mine = await project({ turns: [[{ say: "ok" }]] }); - await core.setProjectOwner(db, (await core.getProject(db, mine.key)).id, user.id); - const sid = await mine.start(); - const start = await mine.waitLog("started", (e) => e.ev === "start"); - assert.equal(start.oauthToken, `…${token.slice(-4)}`); - await runner.stopSession(db, sid); - - const other = await project({ turns: [[{ say: "ok" }]] }); - const sid2 = await other.start(); - assert.equal((await other.waitLog("started", (e) => e.ev === "start")).oauthToken, null); - await runner.stopSession(db, sid2); - - await core.setClaudeToken(db, user.id, null); - const again = await project({ turns: [[{ say: "ok" }]] }); - await core.setProjectOwner(db, (await core.getProject(db, again.key)).id, user.id); - const sid3 = await again.start(); - assert.equal((await again.waitLog("started", (e) => e.ev === "start")).oauthToken, null); - await runner.stopSession(db, sid3); - }); -}); diff --git a/packages/testkit/test/helpers.ts b/packages/testkit/test/helpers.ts index 547ae835..d8431cfa 100644 --- a/packages/testkit/test/helpers.ts +++ b/packages/testkit/test/helpers.ts @@ -20,6 +20,7 @@ Object.assign(process.env, { PEPPA_TMUX_SOCKET: `peppa-test-${process.pid}`, PEPPA_CLAUDE_BIN: join(ROOT, "packages/testkit/bin/mock-claude"), PEPPA_CODEX_BIN: join(ROOT, "packages/testkit/bin/mock-codex"), + PEPPA_OPENCODE_BIN: join(ROOT, "packages/testkit/bin/mock-opencode"), PEPPA_MOCK_MCP_BIN: join(ROOT, "packages/mcp/bin/peppa-mcp"), PEPPA_CLAUDE_CONFIG: join(TMP, "claude.json"), PEPPA_HOOK_WAIT_SEC: "4", @@ -74,7 +75,7 @@ export interface TestProject { key: string; dir: string; taskKey: string; - start(opts?: { provider?: "claude" | "codex" }): Promise; + start(opts?: { provider?: "claude" | "codex" | "opencode"; subscriptionIds?: number[]; poolId?: number | null }): Promise; log(): MockLogEntry[]; waitLog(label: string, pred: (e: MockLogEntry) => boolean, timeoutMs?: number): Promise; session(id: number): ReturnType; @@ -105,7 +106,7 @@ export async function project(scenario: Scenario): Promise { dir, taskKey: ref.key, async start(opts = {}) { - const s = await runner.startSession(db, ref.key, { provider: opts.provider }); + const s = await runner.startSession(db, ref.key, opts); return s.id; }, log, diff --git a/packages/testkit/test/subscriptions.test.ts b/packages/testkit/test/subscriptions.test.ts new file mode 100644 index 00000000..102d1a3c --- /dev/null +++ b/packages/testkit/test/subscriptions.test.ts @@ -0,0 +1,253 @@ +// PEP-67: agent subscriptions (Claude Code / Codex / OpenCode), pools and the subscription a +// runner starts on. Sign-in and trial runs go through the mock CLIs (mock-claude, mock-codex, +// mock-opencode) with the real contracts: setup-token, device auth, --with-api-key, -p/exec/run. +import assert from "node:assert/strict"; +import { existsSync, readFileSync, writeFileSync } from "node:fs"; +import { join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { after, before, describe, test } from "node:test"; +import { core, db, project, runner, teardown, waitFor } from "./helpers.ts"; + +process.env.PEPPA_SECRET = "mock-secret-for-tests"; +const ROOT = resolve(fileURLToPath(import.meta.url), "../../../.."); + +type User = Awaited>; +let asel: User; +let dana: User; +before(async () => { + asel = await core.upsertUserFromGitea(db, { id: 41, login: "asel" }, { access_token: "x" }); + dana = await core.upsertUserFromGitea(db, { id: 42, login: "mock-dana" }, { access_token: "x" }); + await core.setPlatformAdmins(db, ["asel", "admin"]); +}); +after(teardown); + +const TOKEN = (tag: string) => `sk-ant-oat01-mock${"x".repeat(24)}${tag.replace(/[^A-Za-z0-9]/g, "")}`; +const claudeSub = (name: string, tag = name) => + runner.addSubscription(db, { provider: "claude", name, method: "token", secret: TOKEN(tag), createdBy: asel.id }); +const sub = (id: number) => core.getSubscription(db, id); + +describe("Раздел «Подписки» только для суперадмина", () => { + test("суперадмин — логин из platform.admins, остальным раздела нет", async () => { + assert.equal(await core.isSuperadmin(db, asel), true); + assert.equal(await core.isSuperadmin(db, { login: "ADMIN" }), true); + assert.equal(await core.isSuperadmin(db, dana), false); + assert.equal(await core.isSuperadmin(db, null), false); + await assert.rejects(core.requireSuperadmin(db, dana), /Не найдено/); + await core.requireSuperadmin(db, asel); + }); +}); + +describe("Подписка агента", () => { + test("суперадмин добавляет подписку Claude: ссылка → код → активна, токен зашифрован", async () => { + const s = await runner.addSubscription(db, { provider: "claude", name: "Claude Max — asel", method: "login", createdBy: asel.id }); + assert.equal(s.status, "pending"); + const login = await runner.pendingLogin(db, s.id); + assert.match(login!.url, /^https:\/\/claude\.com\/cai\/oauth\/authorize\?/); + await runner.finishClaudeLogin(db, s.id, "mock-good-1"); + const got = await sub(s.id); + assert.equal(got.status, "active"); + assert.ok(got.secretEnc && !got.secretEnc.includes("sk-ant"), "stored encrypted"); + assert.match(core.decrypt(got.secretEnc), /^sk-ant-oat01-mock/); + assert.equal(await runner.pendingLogin(db, s.id), null); + const listed = (await core.listSubscriptions(db)).find((x) => x.id === s.id)!; + assert.equal(listed.createdByLogin, "asel"); + assert.equal(listed.activeSessions, 0); + }); + + test("неверный код Claude: ошибка, подписка не активна; отмена удаляет новую подписку", async () => { + const s = await runner.addSubscription(db, { provider: "claude", name: "Claude bad", method: "login", createdBy: asel.id }); + await assert.rejects(runner.finishClaudeLogin(db, s.id, "mock-bad-code"), /не принял код/); + assert.equal((await sub(s.id)).status, "pending"); + assert.equal((await sub(s.id)).secretEnc, null); + await assert.rejects(runner.finishClaudeLogin(db, s.id, "mock-good-1"), /не начат/); + await runner.cancelLogin(db, s.id); + await assert.rejects(sub(s.id), /не найдена/); + }); + + test("Codex через ChatGPT: ссылка и одноразовый код, вход в собственном CODEX_HOME", async () => { + const s = await runner.addSubscription(db, { provider: "codex", name: "ChatGPT Pro", method: "device", createdBy: asel.id }); + const login = (await runner.pendingLogin(db, s.id))!; + assert.equal(login.url, "https://auth.openai.com/codex/device"); + assert.match(login.code!, /^MOCK-[A-Z0-9]{4}$/); + assert.equal(await runner.pollCodexLogin(db, s.id), "pending"); + writeFileSync(join(runner.codexHome(s.id), "mock-device-approved"), ""); + await waitFor("codex login done", async () => (await runner.pollCodexLogin(db, s.id)) === "active"); + assert.equal((await sub(s.id)).status, "active"); + assert.ok(existsSync(join(runner.codexHome(s.id), "auth.json"))); + assert.ok(runner.codexHome(s.id).startsWith(process.env.PEPPA_HOME!)); + }); + + test("Codex: отказ на устройстве → ошибка входа", async () => { + const s = await runner.addSubscription(db, { provider: "codex", name: "ChatGPT denied", method: "device", createdBy: asel.id }); + writeFileSync(join(runner.codexHome(s.id), "mock-device-denied"), ""); + await waitFor("codex login failed", async () => (await runner.pollCodexLogin(db, s.id)) === "failed"); + const got = await sub(s.id); + assert.equal(got.status, "auth_error"); + assert.match(got.lastError!, /denied/); + }); + + test("Codex по API-ключу: неверный ключ отклонён, верный — активна, ключа нет в БД", async () => { + await assert.rejects( + runner.addSubscription(db, { provider: "codex", name: "Codex bad key", method: "api_key", secret: "mock-bad-key-123", createdBy: asel.id }), + /не принял ключ/, + ); + assert.equal((await core.listSubscriptions(db)).some((x) => x.name === "Codex bad key"), false); + const s = await runner.addSubscription(db, { provider: "codex", name: "Codex key", method: "api_key", secret: "mock-openai-key-123", createdBy: asel.id }); + assert.equal(s.status, "active"); + assert.equal(s.secretEnc, null); + assert.match(readFileSync(join(runner.codexHome(s.id), "auth.json"), "utf8"), /mock-openai-key-123/); + }); + + test("OpenCode по ключу провайдера: активна, ключ зашифрован", async () => { + await assert.rejects(runner.addSubscription(db, { provider: "opencode", name: "OC", method: "api_key", secret: "k", keyProvider: "nope", createdBy: asel.id }), /провайдера/); + const s = await runner.addSubscription(db, { provider: "opencode", name: "OpenCode Anthropic", method: "api_key", secret: "mock-anthropic-key-1", keyProvider: "anthropic", createdBy: asel.id }); + assert.equal(s.status, "active"); + assert.equal(core.subscriptionSecret(s), "mock-anthropic-key-1"); + assert.ok(!s.secretEnc!.includes("mock-anthropic")); + }); +}); + +describe("Проверка подписки", () => { + test("лимит → «лимит до …», отозванный вход → «ошибка входа» без секрета, рабочая → активна", async () => { + const now = new Date("2026-11-14T10:00:00"); + const limited = await claudeSub("Claude limited", "limit"); + const r1 = await runner.checkSubscription(db, limited.id, now); + assert.equal(r1.status, "limited"); + const l = await sub(limited.id); + assert.equal(l.status, "limited"); + assert.equal(l.limitedUntil!.getHours(), 17, "reset time from the banner (5pm)"); + + const bad = await claudeSub("Claude revoked", "bad"); + assert.equal((await runner.checkSubscription(db, bad.id, now)).status, "auth_error"); + const b = await sub(bad.id); + assert.match(b.lastError!, /Invalid API key/); + assert.ok(!b.lastError!.includes(TOKEN("bad"))); + + const ok = await claudeSub("Claude ok", "fine"); + assert.equal((await runner.checkSubscription(db, ok.id, now)).status, "active"); + + const codexLimited = await runner.addSubscription(db, { provider: "codex", name: "Codex limited", method: "api_key", secret: "mock-limit-key-1", createdBy: asel.id }); + assert.equal((await runner.checkSubscription(db, codexLimited.id, now)).status, "limited"); + const oc = await runner.addSubscription(db, { provider: "opencode", name: "OC bad", method: "api_key", secret: "mock-bad-oc-key", keyProvider: "openai", createdBy: asel.id }); + assert.equal((await runner.checkSubscription(db, oc.id, now)).status, "auth_error"); + }); +}); + +describe("Пулы и подписка сессии", () => { + test("пул для ротации: раннеры проекта стартуют на свободной подписке пула", async () => { + const a = await claudeSub("Claude A"); + const b = await claudeSub("Claude B"); + const c = await runner.addSubscription(db, { provider: "codex", name: "Codex C", method: "api_key", secret: "mock-openai-key-c", createdBy: asel.id }); + const pool = await core.createPool(db, { name: "Основной", subscriptionIds: [a.id, b.id, c.id], createdBy: asel.id }); + assert.deepEqual((await core.listPools(db)).find((p) => p.id === pool.id)!.subscriptionIds, [a.id, b.id, c.id]); + + const p1 = await project({ turns: [[{ say: "ok" }]] }); + const p2 = await project({ turns: [[{ say: "ok" }]] }); + for (const p of [p1, p2]) await core.setProjectPool(db, (await core.getProject(db, p.key)).id, pool.id); + + const s1 = await p1.start(); + assert.equal((await p1.session(s1)).subscriptionId, a.id); + assert.equal((await p1.session(s1)).subscriptionName, "Claude A"); + assert.equal((await p1.waitLog("started", (e) => e.ev === "start")).oauthToken, `…${TOKEN("Claude A").slice(-4)}`); + const s2 = await p2.start(); + assert.equal((await p2.session(s2)).subscriptionId, b.id, "A is busy → B"); + assert.equal((await core.listSubscriptions(db)).find((x) => x.id === a.id)!.activeSessions, 1); + + // Provider asked explicitly: only the pool's Codex subscription, with its CODEX_HOME. + const p3 = await project({ turns: [[{ say: "ok" }]] }); + await core.setProjectPool(db, (await core.getProject(db, p3.key)).id, pool.id); + const s3 = await p3.start({ provider: "codex" }); + assert.equal((await p3.session(s3)).provider, "codex"); + assert.equal((await p3.waitLog("started", (e) => e.ev === "start")).codexHome, runner.codexHome(c.id)); + + // Resume stays on the session's subscription. + await runner.stopSession(db, s1); + await runner.resumeSession(db, s1); + await waitFor("resumed run", async () => p1.log().filter((e) => e.ev === "start").length === 2); + assert.equal(p1.log().filter((e) => e.ev === "start")[1]!.oauthToken, `…${TOKEN("Claude A").slice(-4)}`); + for (const id of [s1, s2, s3]) await runner.stopSession(db, id); + }); + + test("выбор при запуске: раннер стартует на одной из отмеченных подписок", async () => { + const [x, y] = [await claudeSub("Pick X"), await claudeSub("Pick Y")]; + const p = await project({ turns: [[{ say: "ok" }]] }); + const s = await p.start({ subscriptionIds: [y.id, x.id] }); + assert.equal((await p.session(s)).subscriptionId, x.id, "first free by id among the ticked"); + await runner.stopSession(db, s); + }); + + test("нет активных подписок → запуск отклонён; без пула — вход машины", async () => { + const bad = await claudeSub("Only bad", "bad"); + await runner.checkSubscription(db, bad.id); + const pool = await core.createPool(db, { name: "Сломанный", subscriptionIds: [bad.id] }); + const p = await project({ turns: [[{ say: "ok" }]] }); + await core.setProjectPool(db, (await core.getProject(db, p.key)).id, pool.id); + await assert.rejects(p.start(), /Нет активных подписок/); + await assert.rejects(p.start({ subscriptionIds: [bad.id] }), /Нет активных подписок/); + await assert.rejects(core.createPool(db, { name: "Сломанный", subscriptionIds: [] }), /уже есть/); + + const free = await project({ turns: [[{ say: "ok" }]] }); + const s = await free.start(); + assert.equal((await free.session(s)).subscriptionId, null); + assert.equal((await free.waitLog("started", (e) => e.ev === "start")).oauthToken, null); + await runner.stopSession(db, s); + }); + + test("OpenCode: сессия в tmux с правилами из opencode.json и ключом подписки", async () => { + const oc = await runner.addSubscription(db, { provider: "opencode", name: "OC session", method: "api_key", secret: "mock-or-key-777", keyProvider: "openrouter", createdBy: asel.id }); + const p = await project({ turns: [[{ say: "ok" }]] }); + const s = await p.start({ subscriptionIds: [oc.id] }); + const start = await p.waitLog("started", (e) => e.ev === "start"); + assert.equal(start.provider, "opencode"); + assert.equal(start.apiKey, "…-777"); + assert.ok((start.rulesChars as number) > 100, "rules from opencode.json instructions"); + assert.equal((await p.session(s)).provider, "opencode"); + await runner.stopSession(db, s); + }); + + test("удаление подписки и пула: сессии и проекты их забывают, каталог входа удалён", async () => { + const c = await runner.addSubscription(db, { provider: "codex", name: "To delete", method: "api_key", secret: "mock-openai-del", createdBy: asel.id }); + const pool = await core.createPool(db, { name: "Временный", subscriptionIds: [c.id] }); + const p = await project({ turns: [[{ say: "ok" }]] }); + const pid = (await core.getProject(db, p.key)).id; + await core.setProjectPool(db, pid, pool.id); + const s = await p.start(); + assert.equal((await core.projectPool(db, pid))?.name, "Временный"); + await runner.removeSubscription(db, c.id); + assert.equal((await p.session(s)).subscriptionId, null); + assert.ok(!existsSync(runner.subscriptionDir(c.id))); + assert.deepEqual((await core.listPools(db)).find((x) => x.id === pool.id)!.subscriptionIds, []); + await core.deletePool(db, pool.id); + assert.equal(await core.projectPool(db, pid), null); + await runner.stopSession(db, s); + }); +}); + +describe("Перенос токена Claude из настроек", () => { + test("миграция: подписка «Claude — » с тем же токеном, пул у проектов владельца", async () => { + const legacy = TOKEN("legacy"); + const u = await core.upsertUserFromGitea(db, { id: 43, login: "mock-legacy" }, { access_token: "x" }); + db.$client.prepare("UPDATE users SET claude_token_enc = ?, claude_token_set_at = ? WHERE id = ?").run(core.encrypt(legacy), Date.now(), u.id); + const p = await project({ turns: [[{ say: "ok" }]] }); + const pid = (await core.getProject(db, p.key)).id; + await core.setProjectOwner(db, pid, u.id); + + // Re-run the data part of migration 0003 on this database. + const sql = readFileSync(join(ROOT, "packages/db/migrations/0003_subscriptions.sql"), "utf8"); + const data = sql.split("--> statement-breakpoint").map((x) => x.trim()).filter((x) => /^(--.*\n)*\s*(INSERT|UPDATE)/.test(x)); + assert.equal(data.length, 5); + for (const stmt of data) db.$client.exec(stmt); + + const s = (await core.listSubscriptions(db)).find((x) => x.name === "Claude — mock-legacy")!; + assert.equal(s.status, "active"); + assert.equal(s.provider, "claude"); + assert.equal(core.subscriptionSecret(s), legacy); + assert.equal((await core.projectPool(db, pid))?.name, "Claude — mock-legacy"); + assert.equal((await core.getUser(db, u.id))!.claudeTokenEnc, null); + assert.equal(await core.claudeTokenForProject(db, { id: pid }), legacy); + + const sid = await p.start(); + assert.equal((await p.waitLog("started", (e) => e.ev === "start")).oauthToken, `…${legacy.slice(-4)}`); + await runner.stopSession(db, sid); + }); +}); From 6116b4740337d17902ca5dad662dcf7b31b91e2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sat, 14 Nov 2026 03:28:59 +0500 Subject: [PATCH 3/5] =?UTF-8?q?PEP-67:=20web=20=E2=80=94=20superadmin=20?= =?UTF-8?q?=C2=AB=D0=9F=D0=BE=D0=B4=D0=BF=D0=B8=D1=81=D0=BA=D0=B8=C2=BB=20?= =?UTF-8?q?section,=20project=20pool,=20subscription=20choice=20at=20launc?= =?UTF-8?q?h,=20subscription=20in=20Runners;=20Settings=20=E2=86=92=20Clau?= =?UTF-8?q?de=20removed?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 6 +- apps/web/app/(app)/actions.ts | 40 +-- apps/web/app/(app)/help/page.tsx | 6 +- apps/web/app/(app)/p/[key]/page.tsx | 26 +- apps/web/app/(app)/settings/page.tsx | 77 +----- apps/web/app/(app)/subscriptions/actions.ts | 122 +++++++++ apps/web/app/(app)/subscriptions/page.tsx | 257 ++++++++++++++++++ apps/web/app/(app)/t/[key]/page.tsx | 34 ++- apps/web/components/AutoRefresh.tsx | 4 +- apps/web/components/RunnerConsole.tsx | 8 +- apps/web/components/Sidebar.tsx | 5 +- .../changes/pep-67-subscriptions/tasks.md | 30 +- 12 files changed, 489 insertions(+), 126 deletions(-) create mode 100644 apps/web/app/(app)/subscriptions/actions.ts create mode 100644 apps/web/app/(app)/subscriptions/page.tsx diff --git a/AGENTS.md b/AGENTS.md index f6459652..bbd7fe41 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,14 +6,14 @@ Текущее состояние и порядок работ: `docs/HANDOFF.md`. ## Структура -- `apps/web` — Next.js платформа (порт 3100, https://peppa.telecom.quest): UI-пульт (PEP-38): Tailwind v4 + компоненты shadcn/ui в `components/ui/*` (исходники в репо), lucide-react, шрифты `geist`, токены темы в `app/app.css` (тёмная по умолчанию, cookie `peppa_theme`); раскладка — `Sidebar` слева (счётчики «ждут тебя» из `navCounts`), страница рисует центр и правую панель через `` (по умолчанию `ActivityAside`); демо-данные для проверки UI — `apps/web/scripts/mock-ui-seed.ts` в отдельную БД; вход через Gitea OAuth2 (`/auth/start` → `/auth/callback`, подписанная cookie `peppa_session`), всё за входом через route group `(app)`; меню Главная (вопросы, активные раннеры, проекты) · Проекты · Раннеры (`/runners`, `core.listUserSessions`) · Помощь; проект как в GitHub (PEP-66): вкладки Доска (фильтр `?epic=`) · Код (`repoOverview`: README, ветки, коммиты из Gitea, кэш минута) · Спеки (`listSpecs`, `openspec/specs` рабочей копии) · PR (`openPulls` + `taskCiSummary`) · Релизы · Баги · Сессии (`?tab=`), «+ Стори» и «⋯ Настройки проекта» (репозиторий, эпики, настройки багов, участники); стори (артефакты OpenSpec из рабочей копии, вопросы, сессии), новый проект. **Слова**: задачи Пеппы в интерфейсе — «стори» (одна стори = один OpenSpec change; «задачи» — пункты tasks.md), цели — «эпики» (метки стори; хранятся в таблице `goals`, `tasks.goal_id`; MCP `*_epic(s)`/`epic_id`, `*_goal(s)`/`goal_id` — алиасы); имена MCP-инструментов и кода (`create_task`, `tasks`) не меняем. Server actions в `app/(app)/actions.ts` — тонкие обёртки над core/runner с проверкой владельца. До запуска веб — `next dev` из рабочей копии (ниже) +- `apps/web` — Next.js платформа (порт 3100, https://peppa.telecom.quest): UI-пульт (PEP-38): Tailwind v4 + компоненты shadcn/ui в `components/ui/*` (исходники в репо), lucide-react, шрифты `geist`, токены темы в `app/app.css` (тёмная по умолчанию, cookie `peppa_theme`); раскладка — `Sidebar` слева (счётчики «ждут тебя» из `navCounts`), страница рисует центр и правую панель через `` (по умолчанию `ActivityAside`); демо-данные для проверки UI — `apps/web/scripts/mock-ui-seed.ts` в отдельную БД; вход через Gitea OAuth2 (`/auth/start` → `/auth/callback`, подписанная cookie `peppa_session`), всё за входом через route group `(app)`; меню Главная (вопросы, активные раннеры, проекты) · Проекты · Раннеры (`/runners`, `core.listUserSessions`) · Подписки (только суперадмин) · Помощь; проект как в GitHub (PEP-66): вкладки Доска (фильтр `?epic=`) · Код (`repoOverview`: README, ветки, коммиты из Gitea, кэш минута) · Спеки (`listSpecs`, `openspec/specs` рабочей копии) · PR (`openPulls` + `taskCiSummary`) · Релизы · Баги · Сессии (`?tab=`), «+ Стори» и «⋯ Настройки проекта» (репозиторий, эпики, настройки багов, участники); стори (артефакты OpenSpec из рабочей копии, вопросы, сессии), новый проект. **Слова**: задачи Пеппы в интерфейсе — «стори» (одна стори = один OpenSpec change; «задачи» — пункты tasks.md), цели — «эпики» (метки стори; хранятся в таблице `goals`, `tasks.goal_id`; MCP `*_epic(s)`/`epic_id`, `*_goal(s)`/`goal_id` — алиасы); имена MCP-инструментов и кода (`create_task`, `tasks`) не меняем. Server actions в `app/(app)/actions.ts` — тонкие обёртки над core/runner с проверкой владельца. До запуска веб — `next dev` из рабочей копии (ниже) - `apps/bot` — Telegram-бот (`peppa-bot`, launchd `quest.telecom.peppa.bot`): свой мини-клиент Bot API (`TELEGRAM_API_URL` для мока), long polling с сохранённым offset, `telegram_updates` фиксирует update до действия (без повторов после рестарта), durable outbox с ретраями (429 retry_after, 5xx), привязка у каждого пользователя своя: веб «Настройки → Telegram» (или `peppa telegram pair `), вопросы проекта получают владелец и участники с привязкой, ответ принимается только от имеющих доступ к проекту (PEP-2). Отвечает только на конкретный вопрос (кнопки/реплай) и умеет resume/stop сессии из алерта - `packages/db` — Drizzle-схема и клиент: **SQLite** (`node:sqlite`, WAL) в файле `PEPPA_DB` (по умолчанию `~/.peppa/peppa.db`); каждый процесс открывает файл сам (`busy_timeout` первой командой, `BEGIN IMMEDIATE`). Прослойка `src/client.ts` даёт сессии drizzle `better-sqlite3` API `node:sqlite`. **Транзакции только синхронные** (`db.transaction((tx) => …)` без `await`; async-колбэк драйвер отклоняет). JSON-поля — `json_extract`/`json_each`, не `->>`/`@>`. Миграции — `drizzle-kit generate` (`packages/db/migrations`, база 0000), применение — `peppa db migrate` (PEP-36) - `packages/shared` — env, ключи задач (`PEP-42`) - `packages/core` — доменная логика (проекты, цели, задачи, вопросы PM); живые обновления — `notify()` будит подписчика (бота) через unix-сокет `$PEPPA_HOME/bot.events.sock`, бот вдобавок раз в секунду смотрит `PRAGMA data_version`; ежедневная копия базы (`backupDb`, `VACUUM INTO`, `~/.peppa/backups`, 7 штук) из вачдога; всё ходит через неё - `packages/mcp` — MCP-сервер `peppa` (бинарь `peppa-mcp`) для сессий в проектах; проект берётся из `.peppa/project.json` в cwd. `@peppa/mcp/manager` — инструменты PM для удалённых клиентов - **Удалённый MCP (PEP-8)**: `https://peppa.telecom.quest/mcp` (Streamable HTTP, stateless, Bearer). Пеппа — OAuth 2.1 сервер: `/.well-known/oauth-authorization-server`, `/.well-known/oauth-protected-resource`, DCR `/oauth/register`, `/oauth/authorize` (вход через Gitea + экран согласия), `/oauth/token` (PKCE S256, refresh с ротацией). Токены — хэши в `oauth_tokens`, отзыв в вебе «Настройки». Инструменты: list_projects, create_project, list_goals, create_goal, update_goal, list_tasks, get_task, create_task, update_task (название/описание/цель, без запуска агента), move_task (как доска — запускает агента), list_inbox, answer_question; `instructions` сервера объясняют модель клиенту. Пользовательская документация — `/help` в вебе (держать в актуальном состоянии при изменении инструментов) -- `packages/testkit` — `mock-claude` / `mock-codex`, `mock-telegram` (мок Bot API) (моки CLI агентов по сценариям: хуки, notify, MCP, лимиты, зависания, падения) и e2e-набор CJM +- `packages/testkit` — `mock-claude` / `mock-codex` / `mock-opencode`, `mock-telegram` (мок Bot API) (моки CLI агентов по сценариям: хуки, notify, MCP, лимиты, зависания, падения) и e2e-набор CJM - `packages/cli` — CLI `peppa` (project/goal/task/q), пока нет веба - `packages/runner` — запуск claude в tmux (`peppa--s`), вачдог, `peppa-hook` - хуки не в репо проекта, а в генерируемом `~/.peppa/runs/s-g/settings.json` (`claude --settings`) @@ -29,7 +29,7 @@ - **Ошибки из прода (PEP-58)**: Bugsink 2.6 в docker `peppa-bugsink` (сервис `bugsink` в `infra/docker-compose.yml`, `scripts/bugsink-up.sh`, база `bugsink` в Postgres (контейнер `peppa-postgres` остался только ради неё, перевод — PEP-63), `bugsink.telecom.quest`, API на 127.0.0.1:3180, env `BUGSINK_*` в `.env`). Адаптер `packages/bugsink` (API + JSON custom-вебхука). Проект подключается в вебе («Подключить отслеживание ошибок» → два проекта Bugsink `-web`/`-api`, цель «Стабильность», `incident_settings`, `error_sources`). Входы: `POST /api/hooks/bugsink/` (`receiveBugsinkWebhook` → `processIncidents` в `after()`) и опрос раз в 2 мин в `tick` вачдога (`pollBugsink`); оба → `ingestIssue` (идемпотентно по issue). Политика проекта (runner/incidents.ts): `notify` / `backlog` (по умолчанию) / `start` / `ask` (кнопки `i::backlog|start|ignore` в боте) / `triage` (runner/triage.ts: `$PEPPA_TRIAGE_BIN -p --output-format json --model haiku` с токеном владельца, не уверен → `ask`); окружения, игнор-регэксп, предел задач в сутки. «Исправлено» вручную (`resolveIncident`) до PEP-57, `REGRESSED` → задача обратно в бэклог. Моки: `mock-bugsink`, `mock-triage` - **Вход через eGov QR (PEP-65)**: relay KazEDS `sign.aitu.uz` (`KAZEDS_RELAY_BASE`, уже доверенный в eGov), `EGOV_ORGANISATION_NAME`/`EGOV_ORGANISATION_BIN` (БИН сгенерирован). `core/egov.ts`: `startEgovFlow` (документ ``, поток в `settings` `egov.flow:`, 5 мин) → `egovFlowStatus` → `completeEgovFlow` (сверка challenge+nonce, ИИН из сертификата — свой разбор DER, `users.egov_iin`). **Подпись XMLDSig не проверяется — доверяем relay (решение PM)**. Веб: `/auth/egov/{start,status,complete}`, handle только в httpOnly cookie `peppa_egov`; `EgovSign` на странице входа и в «Настройках → eGov» (привязать/отвязать). Войти может только пользователь с привязанным ИИН и доступом (PEP-16). CLI `peppa user egov <ИИН|->`. Мок `mock-kazeds-relay` (testkit; подписывает на 3-м опросе поддельным сертификатом). Пример интеграции от PM — `docs/egov-reference/` - **Локальные пользователи (PEP-68)**: `users.gitea_id < 0`, вход по логину и паролю (`POST /auth/password` → `passwordLogin` в `core/local-users.ts`: scrypt `users.password_hash`, одна ошибка «Неверный логин или пароль», 5 неудач на логин / 20 на IP за 15 мин → пауза 15 мин, счётчики в `settings` `auth.fail:*`). Суперадмин = `platform.admins` (`isSuperadmin(db, user)` в core/monitor.ts): раздел `/users` — создать (временный пароль), сбросить пароль, отключить/включить (`users.disabled_at`: `isUserAllowed` → false для любого пользователя, сессии веба и MCP гаснут сразу); смена своего пароля — «Настройки». Вход через Gitea с логином локального пользователя отклоняется (`giteaLoginRefusal`), привязки Gitea к локальному аккаунту нет. Проект локального — в пространстве peppa-bot (`projectNamespace` в runner/provision.ts), участником он добавляется без соавторства в Gitea. CLI `peppa user add [--admin] [--name]`, `peppa user passwd|disable|enable ` (пароль из stdin или сгенерированный) -- **Подключить Claude (PEP-13)**: «Настройки → Claude» запускает `claude setup-token` в tmux `peppa-auth-u` (runner/claude-auth.ts), пользователь входит по ссылке на своём устройстве и вставляет код в форму; токен шифруется в `users.claude_token_enc` и идёт в сессии проектов владельца как `CLAUDE_CODE_OAUTH_TOKEN`; без токена — вход машины +- **Подписки (PEP-67)**: раздел `/subscriptions` только для суперадмина (`isSuperadmin(db, user)` в core/monitor.ts = логин из `platform.admins`; остальным пункта меню нет, URL → 404, actions в `app/(app)/subscriptions/actions.ts` через `requireSuperadmin`). Таблицы `subscriptions` (claude|codex|opencode, статус pending/active/limited/auth_error), `subscription_pools` + `subscription_pool_members`, `projects.subscription_pool_id` (пул проекта, «⋯ Настройки проекта»), `sessions.subscription_id`. Вход — runner/subscription-login.ts в tmux `peppa-auth-sub`: Claude `claude setup-token` (ссылка → код → токен в `secret_enc`) или готовый токен; Codex `codex login --device-auth` (ссылка + код, страница опрашивает) или `--with-api-key`, вход живёт в своём `CODEX_HOME` = `$PEPPA_HOME/subscriptions/s/codex` (0700); OpenCode — ключ провайдера (anthropic/openai/openrouter) зашифрован. «Проверить» — `checkSubscription` (runner/subscriptions.ts: `claude -p` / `codex exec` / `opencode run`). Раннер: `startSession(…, { subscriptionIds, poolId, provider })` → `pickSubscription` (отмеченные → пул → пул проекта; первая свободная активная, иначе наименее занятая; нет пула — вход машины), провайдер сессии = провайдер подписки, env подписки (`CLAUDE_CODE_OAUTH_TOKEN` / `CODEX_HOME` / ключ), resume — на той же. Ротации при лимите нет (PEP-39). Провайдер OpenCode (`providers.ts`): `opencode

--prompt`, правила и MCP из `OPENCODE_CONFIG` (opencode.json в каталоге запуска), хуков нет — статус по процессу. Миграция 0003 перенесла токены `users.claude_token_enc` (PEP-13, колонки больше не читаются) в подписки «Claude — » и пулы проектов владельца. Моки: `mock-claude setup-token|-p`, `mock-codex login|exec`, `mock-opencode` - **Мониторинг (PEP-20)**: веб (`instrumentation.ts`, раз в минуту), бот и вачдог (каждые 30 с) пишут heartbeat в `settings` (`heartbeat:`); вачдог проверяет бота и веб, бот — вачдог и веб (`checkServices` в core/monitor.ts). Молчит дольше `PEPPA_MONITOR_STALE_MIN` (5) мин → алерт админам платформы в Telegram через outbox (`platform.admins`, по умолчанию `platform.allowed_logins`; без привязки — в лог), потом «снова на связи»; напоминание раз в час, кулдаун 15 мин, дедуп ключом `mon::…`. Упал бот — вачдог шлёт алерт прямо в Bot API. `GET /api/health` (БД, версия, сервисы; 503 без БД), `peppa status`, `peppa platform admins [логины|-]` - **CI проектов (PEP-57)**: Gitea Actions + `act_runner` в docker (сервис `act-runner` в `infra/docker-compose.yml`, конфиг `infra/act-runner/`, контейнер `peppa-act-runner`, метка `peppa-trusted`, docker.sock хоста). Раннер регистрируется только на репо проектов: один раз на репо peppa-bot (`scripts/ci-runner-register.sh`), на репо чужого пространства — `setupCi` (runner/ci.ts) при создании проекта или `peppa ci connect ` (ещё PR с workflow из шаблона). Контракт: `.gitea/workflows/ci.yml` + `.gitea/peppa-check.sh` из шаблона, команды — `checks` в `.peppa/project.json`; шаг пишет статус `peppa/<проверка>` и шлёт отчёт в Пеппу, подписанный `PEPPA_CI_SECRET` (секрет Actions = `projectHookSecret(project.id)`). Логи job через API Gitea 1.22 недоступны — хвост лога присылает сам шаг. В тестах регистрация — `mock-ci-register` (`PEPPA_CI_REGISTER_BIN`) - Обратная связь: `POST /api/hooks/gitea` (веб, без входа, подпись `X-Gitea-Signature` секретом проекта) → `handleGiteaHook` (runner/ci-feedback.ts): `X-Peppa-Event: check` — отчёт шага CI → `check_runs` → красное уходит в живой раннер (шаг + хвост лога) или задача возвращается в работу с новым раннером; счётчик `tasks.ci_attempts` по разным SHA, на 3-м — вопрос PM; остальные события Gitea (pull_request, push) — в обработчики `onGiteaEvent`. Запасной путь — `pollChecks` в вачдоге раз в минуту (статусы `peppa/*` PR задач в работе/ревью) diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts index 0609abb7..80de86f2 100644 --- a/apps/web/app/(app)/actions.ts +++ b/apps/web/app/(app)/actions.ts @@ -11,7 +11,6 @@ import { projectForUser, resolveTask, revokeApp, - setClaudeToken, createPairingCode, getSetting, unpairTelegram, @@ -29,7 +28,7 @@ import { } from "@peppa/core"; import { bugsinkFromEnv } from "@peppa/bugsink"; import { loadEnv } from "@peppa/shared"; -import { deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, cancelClaudeSetup, finishClaudeSetup, grantRepoAccess, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, startClaudeSetup, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider } from "@peppa/runner"; +import { deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider } from "@peppa/runner"; import { revalidatePath } from "next/cache"; import { redirect } from "next/navigation"; import { requireUser } from "@/lib/auth"; @@ -116,7 +115,13 @@ export async function startTaskSession(f: FormData) { await attempt(f, async () => { const ref = await resolveTask(db, str(f, "taskKey")); await projectForUser(db, user.id, ref.project.id); - await startSession(db, ref.key, { provider: (str(f, "provider") || "claude") as Provider, prompt: str(f, "prompt") || undefined }); + // PEP-67: a superadmin may pick a pool or tick subscriptions; otherwise the project's pool. + const choice = (await isSuperadmin(db, user)) ? str(f, "choice") : ""; + const subscriptionIds = choice === "pick" ? f.getAll("subscription").map(Number).filter((n) => n > 0) : undefined; + if (choice === "pick" && !subscriptionIds?.length) throw new PeppaError("Отметьте хотя бы одну подписку"); + const poolId = choice.startsWith("pool:") ? Number(choice.slice(5)) : undefined; + const provider = str(f, "provider") as Provider | ""; + await startSession(db, ref.key, { provider: provider || undefined, subscriptionIds, poolId, prompt: str(f, "prompt") || undefined }); }); } @@ -187,35 +192,6 @@ export async function revokeConnectedApp(f: FormData) { }); } -export async function connectClaude(f: FormData) { - const user = await requireUser(); - await attempt(f, async () => { - await startClaudeSetup(db, user.id); - }); -} - -export async function submitClaudeCode(f: FormData) { - const user = await requireUser(); - await attempt(f, async () => { - await finishClaudeSetup(db, user.id, str(f, "code")); - return "/settings?claude=connected"; - }); -} - -export async function cancelClaude(f: FormData) { - const user = await requireUser(); - await attempt(f, async () => { - await cancelClaudeSetup(db, user.id); - }); -} - -export async function disconnectClaude(f: FormData) { - const user = await requireUser(); - await attempt(f, async () => { - await setClaudeToken(db, user.id, null); - }); -} - export async function unlinkEgov(f: FormData) { const user = await requireUser(); await attempt(f, async () => { diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx index b13be4d2..704753c9 100644 --- a/apps/web/app/(app)/help/page.tsx +++ b/apps/web/app/(app)/help/page.tsx @@ -52,8 +52,8 @@ export default async function Help() {
  • Стори (PEP-12) — одна бизнесовая история с описанием и условиями готовности; агент реализует её одним OpenSpec change. «Задачи» — это пункты tasks.md внутри change, не путать.
  • Эпик — необязательная метка, которая группирует стори («Оплата картой»): тег на карточке, фильтр над доской, выбор в «+ Стори». Его описание агент получает вместе со стори как контекст «зачем». Заводятся в «⋯ Настройки проекта» или через MCP.
  • Доска — Бэклог → В работе → Ревью → Готово. Перенос в «В работе» запускает агента.
  • -
  • Агент — Claude Code (или Codex) в сессии на машине Пеппы: пишет OpenSpec-proposal, реализует, открывает PR и отдаёт стори на ревью.
  • -
  • Участники — владелец проекта добавляет людей по логину Gitea (блок «Участники» на странице проекта). Агенты проекта работают на подписке Claude владельца.
  • +
  • Агент — Claude Code, Codex или OpenCode в сессии на машине Пеппы: пишет OpenSpec-proposal, реализует, открывает PR и отдаёт стори на ревью.
  • +
  • Участники — владелец проекта добавляет людей по логину Gitea (блок «Участники» на странице проекта). Агенты проекта работают на подписках из пула проекта.
  • Локальные пользователи — аккаунты Пеппы без Gitea: входят по логину и паролю на странице входа, создаёт их суперадмин в разделе «Пользователи», пароль меняется в «Настройках». Их добавляют в участники по логину Пеппы; доступа к репозиторию в Gitea у них нет — код только через Пеппу, а их новые проекты создаются в пространстве peppa-bot.
  • Раннер — агент, запущенный по стори в tmux на машине Пеппы. Все раннеры твоих и общих проектов — в разделе Раннеры: статус, стори, команда tmux attach, сообщение, остановка и resume; фильтры-счётчики «ждут тебя / работают / упали / готово» и поиск; строки, где нужен ты, подсвечены, у раннера на лимите — «остановлена · продолжит в HH:MM». Выбери раннер — справа его детали, вопросы и действия (живой терминал появится там же).
  • Главная — вопросы агентов (только архитектурные стопперы) и «готово к ревью», активные раннеры и проекты. Отвечать можно в вебе, Telegram или через MCP. Список проектов и «Новый проект» — в разделе Проекты.
  • @@ -67,7 +67,7 @@ export default async function Help() {
  • ChatGPT: Settings → Apps & Connectors → Advanced → включить Developer mode → Create: URL выше, авторизация OAuth. Откроется Пеппа — войдите (Gitea, eGov или логин и пароль) и нажмите «Разрешить». В чате включите коннектор Peppa.
  • Codex, Claude и другие MCP-клиенты: добавьте удалённый MCP-сервер по этому URL с OAuth — клиент зарегистрируется сам, вход и согласие на экране Пеппы.
  • Если клиент не видит новых инструментов — обновите или переподключите коннектор. Доступ отзывается в Настройках.
  • -
  • Чтобы агенты работали на вашей подписке, подключите Claude в Настройках.
  • +
  • Подписки — аккаунты Claude Code, Codex и OpenCode, на которых работают агенты, и пулы для ротации ведёт суперадмин в разделе «Подписки». У проекта — пул по умолчанию («⋯ Настройки проекта»): раннер стартует на первой свободной активной подписке пула, а в «Раннерах» видно, на какой.
  • diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx index 82187214..41018ed0 100644 --- a/apps/web/app/(app)/p/[key]/page.tsx +++ b/apps/web/app/(app)/p/[key]/page.tsx @@ -1,7 +1,7 @@ import { notFound } from "next/navigation"; import { ExternalLink, Plus, Rocket } from "lucide-react"; import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, repoOverview, type Release } from "@peppa/runner"; -import { getIncidentSettings, listEpics, listErrorSources, listIncidents, listMembers, listSpecs, repoAudience, repoVisibilityLabel } from "@peppa/core"; +import { getIncidentSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, projectPool, repoAudience, repoVisibilityLabel } from "@peppa/core"; import { AutoRefresh } from "@/components/AutoRefresh"; import { PanelSection } from "@/components/ActivityAside"; import { Board, type Card } from "@/components/Board"; @@ -19,6 +19,7 @@ import { db } from "@/lib/db"; import { board, projectForUserByKey, projectSessions } from "@/lib/queries"; import { addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember, setProjectVisibilityAction } from "../../actions"; import { CodeTab, EpicsPanel, PullsTab, SpecsTab } from "./tabs"; +import { setProjectPoolAction } from "../../subscriptions/actions"; const RELEASE_STATUS: Record = { deploying: { label: "выкатывается", tone: "info" }, @@ -85,6 +86,9 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr repo.collaborators !== null && login.toLowerCase() !== p.giteaOwner.toLowerCase() && !collaborators.has(login.toLowerCase()); const missingAccess = team.members.some((m) => noRepoAccess(m.login)); const isOwner = p.ownerId === user.id; + // PEP-67: default subscription pool; only a superadmin changes it. + const superadmin = await isSuperadmin(db, user); + const [pool, pools] = await Promise.all([projectPool(db, p.id), superadmin ? listPools(db) : Promise.resolve([])]); // Epic filter (PEP-66): only an open epic of this project filters; anything else shows all. const epicFilter = epics.find((e) => String(e.id) === epicParam) ?? null; const boardHref = (epicId?: number) => (epicId ? `/p/${p.key}?epic=${epicId}` : `/p/${p.key}`); @@ -162,7 +166,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
    • {team.owner?.login ?? "—"} - владелец · агенты работают на его подписке Claude + владелец
    • {team.members.map((m) => (
    • @@ -208,6 +212,24 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr )} {isOwner &&

      Участник видит доску и входящие, двигает карточки и отвечает агентам; получает доступ на запись к репозиторию.

      } + + + {superadmin ? ( +
      + + + + {pools.map((x) => ( + + ))} + + + + ) : ( +

      {pool ? <>Пул «{pool.name}» : "Пул не назначен — агенты работают на входе машины"}

      + )} +

      Раннеры проекта стартуют на свободной подписке пула по умолчанию. {superadmin ? Пулы и подписки : "Меняет суперадмин."}

      +
      ); diff --git a/apps/web/app/(app)/settings/page.tsx b/apps/web/app/(app)/settings/page.tsx index 1e1ed210..02ced8fd 100644 --- a/apps/web/app/(app)/settings/page.tsx +++ b/apps/web/app/(app)/settings/page.tsx @@ -1,6 +1,4 @@ -import { ExternalLink } from "lucide-react"; import { connectedApps, isLocalUser, isSuperadmin, maskIin, MIN_PASSWORD } from "@peppa/core"; -import { pendingClaudeSetup } from "@peppa/runner"; import { Hidden } from "@/components/cards"; import { ago, Empty, Flash, Notice, PageHeader, Section } from "@/components/common"; import { Button } from "@/components/ui/button"; @@ -10,7 +8,7 @@ import { EgovSign } from "@/components/EgovSign"; import { Workspace } from "@/components/Workspace"; import { publicOrigin, requireUser } from "@/lib/auth"; import { db } from "@/lib/db"; -import { changePasswordAction, cancelClaude, connectClaude, disconnectClaude, pairTelegram, revokeConnectedApp, submitClaudeCode, unlinkEgov, unpairTelegramAction } from "../actions"; +import { changePasswordAction, pairTelegram, revokeConnectedApp, unlinkEgov, unpairTelegramAction } from "../actions"; const back = { back: "/settings" }; @@ -27,12 +25,11 @@ function Row({ title, children, actions }: { title: React.ReactNode; children?: ); } -export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; claude?: string; egov?: string; password?: string }> }) { +export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; egov?: string; password?: string }> }) { const user = await requireUser(); - const { error, claude, egov, password } = await searchParams; + const { error, egov, password } = await searchParams; const local = isLocalUser(user); const superadmin = await isSuperadmin(db, user); - const setup = await pendingClaudeSetup(db, user.id); const apps = await connectedApps(db, user.id); const origin = await publicOrigin(); return ( @@ -75,70 +72,26 @@ export default async function Settings({ searchParams }: { searchParams: Promise {superadmin && ( - Пользователи - - } - > - Локальные пользователи без Gitea: создать, сбросить пароль, отключить. - - )} - -
      - {claude === "connected" && Claude подключён} - {setup ? ( - -

      1. Откройте ссылку на любом устройстве и войдите в аккаунт Claude (нужна подписка):

      - -

      2. Claude покажет код — вставьте его сюда:

      -
      - - - - -
      - - - -
      - ) : user.claudeTokenEnc ? ( - -
      - - - -
      - - - + + } > - с {user.claudeTokenSetAt?.toLocaleDateString("ru-RU")} · сессии ваших проектов работают на вашей подписке -
      - ) : ( - - - - - } - > - Агенты ваших проектов запускаются как Claude Code. Подключите свой аккаунт Claude — Пеппа получит годовой токен через{" "} - claude setup-token, вход делаете вы сами по ссылке. + Локальные пользователи без Gitea: создать, сбросить пароль, отключить. Подписки агентов и пулы для ротации. )}
      +
      +

      + Подписки Claude Code, Codex и OpenCode, на которых работают агенты, ведёт суперадмин в разделе «Подписки»; проект запускает раннеры на своём пуле подписок. +

      +
      {egov === "linked" && eGov привязан — теперь можно входить по QR} {user.egovIin ? ( diff --git a/apps/web/app/(app)/subscriptions/actions.ts b/apps/web/app/(app)/subscriptions/actions.ts new file mode 100644 index 00000000..41b66eff --- /dev/null +++ b/apps/web/app/(app)/subscriptions/actions.ts @@ -0,0 +1,122 @@ +"use server"; +// «Подписки» (PEP-67): every action is superadmin-only (others get "not found"). + +import { createPool, deletePool, getProject, PeppaError, requireSuperadmin, setProjectPool, updatePool, updateSubscription, type SubscriptionProvider } from "@peppa/core"; +import { addSubscription, cancelLogin, checkSubscription, finishClaudeLogin, removeSubscription, startClaudeLogin, startCodexLogin } from "@peppa/runner"; +import { revalidatePath } from "next/cache"; +import { redirect } from "next/navigation"; +import { requireUser } from "@/lib/auth"; +import { db } from "@/lib/db"; + +const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim(); +const ids = (f: FormData, k: string) => f.getAll(k).map(Number).filter((n) => Number.isInteger(n) && n > 0); +const BASE = "/subscriptions"; + +/** Runs a superadmin action; errors come back as ?error=… (redirect stays outside try). */ +async function attempt(f: FormData, fn: () => Promise): Promise { + const user = await requireUser(); + let target = str(f, "back") || BASE; + try { + await requireSuperadmin(db, user); + target = (await fn()) || target; + } catch (e) { + const msg = e instanceof PeppaError ? e.message : `Ошибка: ${(e as Error).message}`; + const [path, query] = target.split("?"); + const params = new URLSearchParams(query); + params.set("error", msg.slice(0, 300)); + target = `${path}?${params}`; + } + revalidatePath("/", "layout"); + redirect(target); +} + +export async function addSubscriptionAction(f: FormData) { + const user = await requireUser(); + await attempt(f, async () => { + const provider = str(f, "provider") as SubscriptionProvider; + if (!["claude", "codex", "opencode"].includes(provider)) throw new PeppaError("Неизвестный провайдер"); + const s = await addSubscription(db, { + provider, + name: str(f, "name"), + method: str(f, "method"), + secret: str(f, "secret") || undefined, + keyProvider: str(f, "keyProvider") || undefined, + createdBy: user.id, + }); + return s.status === "pending" ? `${BASE}?login=${s.id}#s-${s.id}` : `${BASE}?added=${s.id}#s-${s.id}`; + }); +} + +export async function reconnectSubscription(f: FormData) { + await attempt(f, async () => { + const id = Number(str(f, "id")); + if (str(f, "provider") === "codex") await startCodexLogin(db, id); + else await startClaudeLogin(db, id); + return `${BASE}?login=${id}#s-${id}`; + }); +} + +export async function submitLoginCode(f: FormData) { + await attempt(f, async () => { + const id = Number(str(f, "id")); + await finishClaudeLogin(db, id, str(f, "code")); + return `${BASE}?added=${id}#s-${id}`; + }); +} + +export async function cancelLoginAction(f: FormData) { + await attempt(f, async () => { + await cancelLogin(db, Number(str(f, "id"))); + }); +} + +export async function checkSubscriptionAction(f: FormData) { + await attempt(f, async () => { + const id = Number(str(f, "id")); + await checkSubscription(db, id); + return `${BASE}#s-${id}`; + }); +} + +export async function renameSubscription(f: FormData) { + await attempt(f, async () => { + if (!str(f, "name")) throw new PeppaError("Нужно название подписки"); + await updateSubscription(db, Number(str(f, "id")), { name: str(f, "name") }); + }); +} + +export async function deleteSubscriptionAction(f: FormData) { + await attempt(f, async () => { + await removeSubscription(db, Number(str(f, "id"))); + }); +} + +export async function createPoolAction(f: FormData) { + const user = await requireUser(); + await attempt(f, async () => { + await createPool(db, { name: str(f, "name"), subscriptionIds: ids(f, "subscription"), createdBy: user.id }); + return `${BASE}#pools`; + }); +} + +export async function updatePoolAction(f: FormData) { + await attempt(f, async () => { + await updatePool(db, Number(str(f, "id")), { name: str(f, "name") || undefined, subscriptionIds: ids(f, "subscription") }); + return `${BASE}#pools`; + }); +} + +export async function deletePoolAction(f: FormData) { + await attempt(f, async () => { + await deletePool(db, Number(str(f, "id"))); + return `${BASE}#pools`; + }); +} + +/** «⋯ Настройки проекта» → пул по умолчанию (only a superadmin changes it). */ +export async function setProjectPoolAction(f: FormData) { + await attempt(f, async () => { + const p = await getProject(db, str(f, "projectKey")); + await setProjectPool(db, p.id, str(f, "poolId") ? Number(str(f, "poolId")) : null); + }); +} diff --git a/apps/web/app/(app)/subscriptions/page.tsx b/apps/web/app/(app)/subscriptions/page.tsx new file mode 100644 index 00000000..d87bd4be --- /dev/null +++ b/apps/web/app/(app)/subscriptions/page.tsx @@ -0,0 +1,257 @@ +import { notFound } from "next/navigation"; +import { ExternalLink, KeyRound, Plus, RefreshCw, Trash2 } from "lucide-react"; +import { isSuperadmin, isUsable, listPools, listSubscriptions, OPENCODE_KEY_ENV, PROVIDER_NAMES, type SubscriptionView } from "@peppa/core"; +import { pendingLogin, pollCodexLogin, type PendingLogin } from "@peppa/runner"; +import { AutoRefresh } from "@/components/AutoRefresh"; +import { Hidden } from "@/components/cards"; +import { ago, Disclosure, Empty, Flash, Notice, PageHeader, Section } from "@/components/common"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Card } from "@/components/ui/card"; +import { Input, Label, NativeSelect } from "@/components/ui/input"; +import { Workspace } from "@/components/Workspace"; +import { requireUser } from "@/lib/auth"; +import { db } from "@/lib/db"; +import { + addSubscriptionAction, + cancelLoginAction, + checkSubscriptionAction, + createPoolAction, + deletePoolAction, + deleteSubscriptionAction, + reconnectSubscription, + submitLoginCode, + updatePoolAction, +} from "./actions"; + +export const metadata = { title: "Подписки — Пеппа" }; + +const hhmm = (d: Date) => d.toLocaleString("ru-RU", { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" }); + +function StatusOf({ s }: { s: SubscriptionView }) { + if (s.status === "pending") return ожидает входа; + if (s.status === "auth_error") return ошибка входа; + if (s.status === "limited" && !isUsable(s)) return лимит до {s.limitedUntil ? hhmm(s.limitedUntil) : "?"}; + return активна; +} + +function LoginSteps({ s, login }: { s: SubscriptionView; login: PendingLogin }) { + return ( +
      + {login.kind === "claude" ? ( + <> +

      1. Откройте ссылку на любом устройстве и войдите в аккаунт Claude с подпиской:

      + +

      2. Claude покажет код — вставьте его сюда:

      +
      + + + + + + ) : ( + <> +

      1. Откройте ссылку на любом устройстве и войдите в ChatGPT:

      + +

      + 2. Введите одноразовый код: {login.code} +

      +

      Страница обновится сама, когда Codex подтвердит вход.

      + + )} +
      + + + +
      + ); +} + +function SubscriptionCard({ s, login, pools }: { s: SubscriptionView; login: PendingLogin | null; pools: Map }) { + return ( + +
      + {PROVIDER_NAMES[s.provider]} + {s.name} + + сессий сейчас: {s.activeSessions} +
      +
      + {s.authKind === "api_key" ? `API-ключ${s.keyProvider ? ` ${s.keyProvider}` : ""}` : s.authKind === "device" ? "вход ChatGPT" : "токен Claude"} + {" · "}добавил {s.createdByLogin ?? "—"} {ago(s.createdAt)} + {s.checkedAt && <> · проверена {ago(s.checkedAt)}} + {s.poolIds.length > 0 && <> · пулы: {s.poolIds.map((id) => pools.get(id)).filter(Boolean).join(", ")}} +
      + {s.lastError && s.status !== "active" &&

      {s.lastError}

      } + {login && } + {!login && ( +
      + {s.status !== "pending" && ( +
      + + + + )} + {(s.provider === "claude" || (s.provider === "codex" && s.authKind === "device")) && ( +
      + + + + )} +
      + + + +
      + )} +
      + ); +} + +function SubscriptionChecks({ subs, checked }: { subs: SubscriptionView[]; checked: number[] }) { + return subs.length === 0 ? ( +

      Сначала добавьте подписки.

      + ) : ( +
      + {subs.map((s) => ( + + ))} +
      + ); +} + +function AddForm({ provider, children }: { provider: string; children: React.ReactNode }) { + return ( +
      + + + {children} + + ); +} + +type Params = { error?: string; login?: string; added?: string }; + +export default async function Subscriptions({ searchParams }: { searchParams: Promise }) { + const user = await requireUser(); + if (!(await isSuperadmin(db, user))) notFound(); + const { error, added } = await searchParams; + let subs = await listSubscriptions(db); + // Codex device sign-ins finish on the user's device: look whether they are done. + let polled = false; + for (const s of subs) if (s.provider === "codex" && s.status === "pending") polled = (await pollCodexLogin(db, s.id)) !== "pending" || polled; + if (polled) subs = await listSubscriptions(db); + const logins = new Map(); + for (const s of subs) { + const l = await pendingLogin(db, s.id); + if (l) logins.set(s.id, l); + } + const pools = await listPools(db); + const poolNames = new Map(pools.map((p) => [p.id, p.name])); + const addedSub = added ? subs.find((s) => s.id === Number(added)) : undefined; + + return ( + + {[...logins.values()].some((l) => l.kind === "codex") && } +
      + + Подписки}> + Аккаунты, на которых работают агенты, и пулы для ротации. Раннер берёт первую свободную активную подписку из пула проекта или из выбранных при запуске. Раздел видят только суперадмины. + + {addedSub && Подписка «{addedSub.name}» добавлена{addedSub.status === "active" ? " и активна" : ""}} + +
      + {subs.length === 0 ? Подписок пока нет — добавьте первую ниже. : subs.map((s) => )} +
      + Claude Code}> + + + + + + + + + + Codex}> + + + + + + + + + + OpenCode}> + + + + {Object.keys(OPENCODE_KEY_ENV).map((k) => ( + + ))} + + + + + +
      +
      + +
      + {pools.length === 0 && Пулов нет. Пул — набор подписок, который назначается проекту по умолчанию.} + {pools.map((p) => ( + +
      + +
      + + + {p.projectKeys.length ? `по умолчанию у ${p.projectKeys.join(", ")}` : "не назначен проектам"} + +
      + + + +
      + + + +
      + ))} + Новый пул}> +
      + + + + +
      +

      Пул проекта по умолчанию выбирается в «⋯ Настройки проекта».

      +
      +
      +
      + ); +} diff --git a/apps/web/app/(app)/t/[key]/page.tsx b/apps/web/app/(app)/t/[key]/page.tsx index 8508aa15..e2248df6 100644 --- a/apps/web/app/(app)/t/[key]/page.tsx +++ b/apps/web/app/(app)/t/[key]/page.tsx @@ -1,7 +1,7 @@ import Link from "next/link"; import { notFound } from "next/navigation"; import { CircleCheck, CircleX, GitPullRequest, Hourglass, Play } from "lucide-react"; -import { getEpic, taskCiSummary } from "@peppa/core"; +import { getEpic, isSuperadmin, listPools, listSubscriptions, projectPool, PROVIDER_NAMES, taskCiSummary } from "@peppa/core"; import { AutoRefresh } from "@/components/AutoRefresh"; import { PanelSection } from "@/components/ActivityAside"; import { Hidden, QuestionCard, SessionCard } from "@/components/cards"; @@ -28,6 +28,10 @@ export default async function StoryPage({ params, searchParams }: { params: Prom const ci = await taskCiSummary(db, ref); const epic = task.goalId ? await getEpic(db, project.id, task.goalId).catch(() => null) : null; const back = `/t/${ref.key}`; + // PEP-67: superadmins choose the subscriptions a runner may take; others run on the project's pool. + const superadmin = await isSuperadmin(db, user); + const pool = await projectPool(db, project.id); + const [pools, subs] = superadmin ? await Promise.all([listPools(db), listSubscriptions(db)]) : [[], []]; const aside = (
      @@ -109,16 +113,42 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
      - + + + + {superadmin && ( + + + {pools.filter((p) => p.id !== pool?.id).map((p) => ( + + ))} + {subs.length > 0 && } + + )} + {superadmin && subs.length > 0 && ( +
      + Отметить подписки (для «Отмеченные подписки») +
      + {subs.map((s) => ( + + ))} +
      +
      + )} + {!superadmin && pool &&

      Агент запустится на свободной подписке пула «{pool.name}».

      } {sessions.map((s) => )}
      diff --git a/apps/web/components/AutoRefresh.tsx b/apps/web/components/AutoRefresh.tsx index ad877ec6..0e6475a1 100644 --- a/apps/web/components/AutoRefresh.tsx +++ b/apps/web/components/AutoRefresh.tsx @@ -3,14 +3,14 @@ import { useRouter } from "next/navigation"; import { useEffect } from "react"; -/** Re-renders server data every few seconds, unless the user is typing. */ +/** Re-renders server data every few seconds, unless the user is typing (or left an unsent draft). */ export function AutoRefresh({ everyMs = 5000 }: { everyMs?: number }) { const router = useRouter(); useEffect(() => { const id = setInterval(() => { const el = document.activeElement; const typing = el instanceof HTMLTextAreaElement || (el instanceof HTMLInputElement && el.type === "text"); - const draft = [...document.querySelectorAll("textarea, input[type=text]")].some((i) => i.value); + const draft = [...document.querySelectorAll("textarea, input[type=text]")].some((i) => i.value !== i.defaultValue); if (!typing && !draft && document.visibilityState === "visible") router.refresh(); }, everyMs); return () => clearInterval(id); diff --git a/apps/web/components/RunnerConsole.tsx b/apps/web/components/RunnerConsole.tsx index a060b38b..c31f8c48 100644 --- a/apps/web/components/RunnerConsole.tsx +++ b/apps/web/components/RunnerConsole.tsx @@ -1,7 +1,7 @@ // Runners console (PEP-38): list rows with status and limit info, and the details panel of the chosen runner. import Link from "next/link"; import { SquareTerminal, X } from "lucide-react"; -import type { SessionView } from "@peppa/core"; +import { PROVIDER_NAMES, type SessionView } from "@peppa/core"; import { MAX_LIMIT_RESUMES_PER_DAY } from "@peppa/runner"; import { PanelSection } from "@/components/ActivityAside"; import { AttachCommand, QuestionCard, SessionActions } from "@/components/cards"; @@ -57,7 +57,7 @@ export function RunnerRow({ s, href, selected, needsPm }: { s: SessionView; href )} - {s.projectKey} · {s.provider} · #{s.id} · {s.tmuxName} + {s.projectKey} · {s.provider}{s.subscriptionName ? ` · ${s.subscriptionName}` : ""} · #{s.id} · {s.tmuxName} {ago(s.lastActivityAt)} {limited && ( @@ -103,7 +103,9 @@ export function RunnerDetails({ s, questions, events, back, closeHref, chosen }: {s.projectKey}
      Агент
      -
      {s.provider === "codex" ? "Codex" : "Claude Code"} · поколение {s.generation}
      +
      {PROVIDER_NAMES[s.provider]} · поколение {s.generation}
      +
      Подписка
      +
      {s.subscriptionName ?? (s.subscriptionId ? `#${s.subscriptionId}` : "вход машины")}
      Запущен
      {ago(s.startedAt)}
      Активность
      diff --git a/apps/web/components/Sidebar.tsx b/apps/web/components/Sidebar.tsx index 2ac0416d..66349ecd 100644 --- a/apps/web/components/Sidebar.tsx +++ b/apps/web/components/Sidebar.tsx @@ -2,7 +2,7 @@ import Link from "next/link"; import { usePathname } from "next/navigation"; -import { Bot, FolderKanban, House, LifeBuoy, LogOut, Settings, Users, type LucideIcon } from "lucide-react"; +import { Bot, FolderKanban, House, KeyRound, LifeBuoy, LogOut, Settings, Users, type LucideIcon } from "lucide-react"; import { Brand } from "@/components/Brand"; import { ThemeToggle } from "@/components/ThemeToggle"; import { Button } from "@/components/ui/button"; @@ -14,7 +14,7 @@ interface Item { icon: LucideIcon; match: (p: string) => boolean; count?: "questions" | "waitingRunners"; - /** Superadmin only (PEP-68); desktop panel only — on phones it is linked from Settings. */ + /** Superadmin only (PEP-68, PEP-67; others get 404 on the URL too); desktop panel only — on phones it is linked from Settings. */ admin?: boolean; } @@ -23,6 +23,7 @@ const ITEMS: Item[] = [ { href: "/projects", label: "Проекты", icon: FolderKanban, match: (p) => p.startsWith("/projects") || p.startsWith("/p/") || p.startsWith("/t/") }, { href: "/runners", label: "Раннеры", icon: Bot, match: (p) => p.startsWith("/runners"), count: "waitingRunners" }, { href: "/help", label: "Помощь", icon: LifeBuoy, match: (p) => p.startsWith("/help") }, + { href: "/subscriptions", label: "Подписки", icon: KeyRound, match: (p) => p.startsWith("/subscriptions"), admin: true }, { href: "/users", label: "Пользователи", icon: Users, match: (p) => p.startsWith("/users"), admin: true }, { href: "/settings", label: "Настройки", icon: Settings, match: (p) => p.startsWith("/settings") }, ]; diff --git a/openspec/changes/pep-67-subscriptions/tasks.md b/openspec/changes/pep-67-subscriptions/tasks.md index ead0113c..5d7e669a 100644 --- a/openspec/changes/pep-67-subscriptions/tasks.md +++ b/openspec/changes/pep-67-subscriptions/tasks.md @@ -1,26 +1,26 @@ # Tasks: PEP-67 ## 1. Данные -- [ ] 1.1 Схема: subscriptions, subscription_pools, subscription_pool_members, projects.subscription_pool_id, sessions.subscription_id, provider opencode -- [ ] 1.2 Миграция (drizzle-kit generate) + перенос users.claude_token_enc в подписки и пулы -- [ ] 1.3 core: isSuperadmin, CRUD подписок и пулов, пул проекта, выбор подписки, claudeTokenForProject из пула +- [x] 1.1 Схема: subscriptions, subscription_pools, subscription_pool_members, projects.subscription_pool_id, sessions.subscription_id, provider opencode +- [x] 1.2 Миграция (drizzle-kit generate) + перенос users.claude_token_enc в подписки и пулы +- [x] 1.3 core: isSuperadmin, CRUD подписок и пулов, пул проекта, выбор подписки, claudeTokenForProject из пула ## 2. Раннер -- [ ] 2.1 Вход: Claude setup-token на подписку, ручной токен; Codex device auth и API-ключ (CODEX_HOME); OpenCode ключ -- [ ] 2.2 «Проверить» (пробный запуск) и статусы -- [ ] 2.3 Провайдер OpenCode (providers.ts, opencode.json, env) -- [ ] 2.4 startSession/resumeSession: выбор подписки, env подписки, sessions.subscription_id +- [x] 2.1 Вход: Claude setup-token на подписку, ручной токен; Codex device auth и API-ключ (CODEX_HOME); OpenCode ключ +- [x] 2.2 «Проверить» (пробный запуск) и статусы +- [x] 2.3 Провайдер OpenCode (providers.ts, opencode.json, env) +- [x] 2.4 startSession/resumeSession: выбор подписки, env подписки, sessions.subscription_id ## 3. Моки -- [ ] 3.1 mock-claude -p, mock-codex login/exec, mock-opencode +- [x] 3.1 mock-claude -p, mock-codex login/exec, mock-opencode ## 4. Веб -- [ ] 4.1 Меню «Подписки» только суперадмину, /subscriptions (404 остальным) -- [ ] 4.2 Страница подписок: список, добавление трёх провайдеров, проверка, удаление, пулы -- [ ] 4.3 Настройки проекта: пул по умолчанию; форма запуска: пул/подписки; «Раннеры»: подписка -- [ ] 4.4 Убрать «Настройки → Claude», обновить Помощь +- [x] 4.1 Меню «Подписки» только суперадмину, /subscriptions (404 остальным) +- [x] 4.2 Страница подписок: список, добавление трёх провайдеров, проверка, удаление, пулы +- [x] 4.3 Настройки проекта: пул по умолчанию; форма запуска: пул/подписки; «Раннеры»: подписка +- [x] 4.4 Убрать «Настройки → Claude», обновить Помощь ## 5. Тесты и документация -- [ ] 5.1 testkit: subscriptions.test.ts (сценарии спеки), перенос claude-auth.test.ts, миграция токенов -- [ ] 5.2 AGENTS.md -- [ ] 5.3 pnpm run ci зелёный +- [x] 5.1 testkit: subscriptions.test.ts (сценарии спеки), перенос claude-auth.test.ts, миграция токенов +- [x] 5.2 AGENTS.md +- [x] 5.3 pnpm run ci зелёный From e2beb70dc40d212b9a592ac9a7f29f5205cb95ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sat, 14 Nov 2026 03:31:11 +0500 Subject: [PATCH 4/5] PEP-67: archive OpenSpec change pep-67-subscriptions Co-Authored-By: Claude Opus 5.5 --- .../design.md | 0 .../proposal.md | 0 .../specs/agent-credentials/spec.md | 0 .../specs/web-workspace/spec.md | 0 .../2026-11-14-pep-67-subscriptions}/tasks.md | 0 openspec/specs/agent-credentials/spec.md | 109 ++++++++++++++---- openspec/specs/web-workspace/spec.md | 15 +++ 7 files changed, 102 insertions(+), 22 deletions(-) rename openspec/changes/{pep-67-subscriptions => archive/2026-11-14-pep-67-subscriptions}/design.md (100%) rename openspec/changes/{pep-67-subscriptions => archive/2026-11-14-pep-67-subscriptions}/proposal.md (100%) rename openspec/changes/{pep-67-subscriptions => archive/2026-11-14-pep-67-subscriptions}/specs/agent-credentials/spec.md (100%) rename openspec/changes/{pep-67-subscriptions => archive/2026-11-14-pep-67-subscriptions}/specs/web-workspace/spec.md (100%) rename openspec/changes/{pep-67-subscriptions => archive/2026-11-14-pep-67-subscriptions}/tasks.md (100%) diff --git a/openspec/changes/pep-67-subscriptions/design.md b/openspec/changes/archive/2026-11-14-pep-67-subscriptions/design.md similarity index 100% rename from openspec/changes/pep-67-subscriptions/design.md rename to openspec/changes/archive/2026-11-14-pep-67-subscriptions/design.md diff --git a/openspec/changes/pep-67-subscriptions/proposal.md b/openspec/changes/archive/2026-11-14-pep-67-subscriptions/proposal.md similarity index 100% rename from openspec/changes/pep-67-subscriptions/proposal.md rename to openspec/changes/archive/2026-11-14-pep-67-subscriptions/proposal.md diff --git a/openspec/changes/pep-67-subscriptions/specs/agent-credentials/spec.md b/openspec/changes/archive/2026-11-14-pep-67-subscriptions/specs/agent-credentials/spec.md similarity index 100% rename from openspec/changes/pep-67-subscriptions/specs/agent-credentials/spec.md rename to openspec/changes/archive/2026-11-14-pep-67-subscriptions/specs/agent-credentials/spec.md diff --git a/openspec/changes/pep-67-subscriptions/specs/web-workspace/spec.md b/openspec/changes/archive/2026-11-14-pep-67-subscriptions/specs/web-workspace/spec.md similarity index 100% rename from openspec/changes/pep-67-subscriptions/specs/web-workspace/spec.md rename to openspec/changes/archive/2026-11-14-pep-67-subscriptions/specs/web-workspace/spec.md diff --git a/openspec/changes/pep-67-subscriptions/tasks.md b/openspec/changes/archive/2026-11-14-pep-67-subscriptions/tasks.md similarity index 100% rename from openspec/changes/pep-67-subscriptions/tasks.md rename to openspec/changes/archive/2026-11-14-pep-67-subscriptions/tasks.md diff --git a/openspec/specs/agent-credentials/spec.md b/openspec/specs/agent-credentials/spec.md index 29441d1a..a2b59659 100644 --- a/openspec/specs/agent-credentials/spec.md +++ b/openspec/specs/agent-credentials/spec.md @@ -1,34 +1,99 @@ # agent-credentials Specification ## Purpose -Позволяет пользователю, работающему удалённо, подключить свой аккаунт Claude к Пеппе из веба, чтобы сессии его проектов работали на его подписке. +Подписки агентов (Claude Code, Codex, OpenCode) и пулы для ротации, которые ведёт суперадмин из веба; раннеры проектов запускаются на подписках пула (PEP-13 → PEP-67). ## Requirements -### Requirement: Подключение Claude из веба -Пользователь SHALL мочь подключить Claude, не имея доступа к машине Пеппы: Пеппа -показывает ссылку входа Claude, пользователь вводит полученный код в веб-форму, Пеппа -сохраняет долгоживущий токен. +### Requirement: Раздел «Подписки» только для суперадмина +Раздел «Подписки» SHALL быть виден и доступен только суперадмину (логин из +`platform.admins`): у остальных пункта меню нет, `/subscriptions` отвечает 404, действия +раздела отклоняются. -#### Scenario: Успешное подключение -- **WHEN** пользователь нажимает «Подключить Claude», открывает показанную ссылку, получает код и вставляет его в форму -- **THEN** в настройках отображается «Claude подключён» с датой, токен не показывается +#### Scenario: Пользователь без прав суперадмина +- **GIVEN** пользователь «dana» не входит в `platform.admins` +- **WHEN** он открывает Пеппу и затем `/subscriptions` +- **THEN** пункта «Подписки» в меню нет, а `/subscriptions` отвечает 404 -#### Scenario: Неверный или просроченный код -- **WHEN** введённый код не принят Claude -- **THEN** пользователь видит ошибку и может начать заново; старый токен (если был) не меняется +#### Scenario: Суперадмин +- **GIVEN** `platform.admins` = asel, admin +- **WHEN** «asel» открывает Пеппу +- **THEN** в меню есть «Подписки», страница показывает подписки и пулы -### Requirement: Хранение и отключение -Токен SHALL храниться только в зашифрованном виде и удаляться по «Отключить». +### Requirement: Подписка агента +Суперадмин SHALL добавлять подписки Claude Code, Codex и OpenCode. Подписка хранит +провайдера, название, кто добавил, статус (ожидает входа / активна / лимит до … / ошибка +входа) и показывает число сессий на ней сейчас. Секреты SHALL храниться только +зашифрованно (или в закрытом каталоге входа CLI) и не показываться. -#### Scenario: Отключение -- **WHEN** пользователь нажимает «Отключить» -- **THEN** токен удалён, новые сессии его проектов запускаются без него +#### Scenario: Суперадмин добавляет подписку Claude +- **GIVEN** суперадмин открыл «Подписки» +- **WHEN** он выбирает «+ Claude Code» с названием «Claude Max — asel», входит по ссылке и вставляет код +- **THEN** подписка «Claude Max — asel» появляется в списке со статусом «активна», токен хранится зашифрованным -### Requirement: Токен в сессиях -Сессии Claude по проектам владельца с подключённым Claude SHALL запускаться с его -токеном; проекты без владельца или владельцы без токена используют вход машины. +#### Scenario: Неверный код Claude +- **GIVEN** суперадмин начал вход новой подписки Claude +- **WHEN** Claude не принимает вставленный код +- **THEN** суперадмин видит ошибку, подписка не становится активной -#### Scenario: Запуск сессии -- **WHEN** запускается сессия Claude по задаче проекта, владелец которого подключил Claude -- **THEN** процесс агента получает токен владельца +#### Scenario: Codex через ChatGPT +- **GIVEN** суперадмин выбрал «+ Codex» и вход через ChatGPT +- **WHEN** он открывает показанную ссылку и вводит показанный одноразовый код на своём устройстве +- **THEN** подписка Codex становится активной, вход хранится в её собственном `CODEX_HOME` + +#### Scenario: OpenCode по ключу +- **WHEN** суперадмин добавляет подписку OpenCode с ключом провайдера «anthropic» +- **THEN** подписка активна, ключ хранится зашифрованным + +### Requirement: Проверка подписки +Кнопка «Проверить» SHALL делать короткий пробный запуск CLI с этой подпиской и обновлять +её статус. + +#### Scenario: Подписка упёрлась в лимит +- **GIVEN** у подписки Claude исчерпан лимит +- **WHEN** суперадмин нажимает «Проверить» +- **THEN** статус подписки — «лимит до …» + +#### Scenario: Отозванный вход +- **WHEN** пробный запуск завершился ошибкой авторизации +- **THEN** статус подписки — «ошибка входа» с текстом ошибки без секретов + +### Requirement: Пулы подписок +Суперадмин SHALL создавать пулы — именованные наборы подписок (подписка может быть в +нескольких пулах) — и назначать проекту пул по умолчанию. Пул проекта меняет только +суперадмин. + +#### Scenario: Пул для ротации +- **GIVEN** есть две активные подписки Claude и одна Codex +- **WHEN** суперадмин создаёт пул «Основной» из этих трёх подписок и назначает его проекту по умолчанию +- **THEN** новые раннеры проекта стартуют на свободной подписке из этого пула + +#### Scenario: Не суперадмин меняет пул проекта +- **GIVEN** «dana» — участник проекта, но не суперадмин +- **WHEN** она пытается сменить пул проекта +- **THEN** изменение отклонено + +### Requirement: Подписка сессии +Раннер SHALL при старте брать первую свободную активную подписку из выбранного набора +(отмеченные подписки или пул из формы запуска, иначе пул проекта) и запоминать её у сессии; +провайдер сессии — провайдер подписки, процесс агента получает вход этой подписки. Resume +SHALL идти на той же подписке. Без пула и выбора сессия запускается на входе машины. + +#### Scenario: Свободная подписка +- **GIVEN** в пуле проекта подписки «A» и «B», на «A» уже работает сессия +- **WHEN** запускается новый раннер проекта +- **THEN** он стартует на подписке «B» + +#### Scenario: Нет активных подписок +- **GIVEN** у всех подписок пула проекта статус «ошибка входа» +- **WHEN** запускается новый раннер +- **THEN** запуск отклонён с сообщением «Нет активных подписок» + +### Requirement: Перенос токена Claude из настроек +Миграция SHALL переносить подключённые токены Claude пользователей (PEP-13) в подписки +Claude и делать пул с этой подпиской пулом по умолчанию проектов владельца. + +#### Scenario: Был подключён Claude +- **GIVEN** у «asel» в настройках был подключён Claude и он владелец проекта PEP +- **WHEN** применяется миграция +- **THEN** есть активная подписка «Claude — asel» с тем же токеном, у PEP пул «Claude — asel», а у пользователя токена больше нет diff --git a/openspec/specs/web-workspace/spec.md b/openspec/specs/web-workspace/spec.md index b7014a85..0c22f752 100644 --- a/openspec/specs/web-workspace/spec.md +++ b/openspec/specs/web-workspace/spec.md @@ -285,3 +285,18 @@ change остаются «задачами». Имена MCP-инструмен #### Scenario: Имя инструмента - **WHEN** клиент MCP запрашивает список инструментов - **THEN** `create_task` есть, а его описание говорит о стори + +### Requirement: Выбор подписок при запуске агента +Форма «Запустить агента» SHALL давать суперадмину выбрать пул или отметить несколько +подписок (по умолчанию — пул проекта); остальные запускают на пуле проекта. «Раннеры» +SHALL показывать, на какой подписке работает сессия. + +#### Scenario: Выбор при запуске +- **GIVEN** суперадмин на странице стори, есть подписки «Claude A», «Claude B», «Codex C» +- **WHEN** он отмечает «Claude B» и «Codex C» и запускает агента +- **THEN** раннер стартует на одной из них, и в «Раннерах» видно, на какой + +#### Scenario: Отмеченная подписка неактивна +- **GIVEN** у отмеченной подписки статус «ошибка входа», других не отмечено +- **WHEN** суперадмин запускает агента +- **THEN** запуск отклонён с сообщением «Нет активных подписок» From 16a6fcf8ac8c1c6b153ea6947ca3cd5e06d8b066 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sat, 14 Nov 2026 03:35:53 +0500 Subject: [PATCH 5/5] PEP-67: migrate-to-sqlite skips tables that don't exist in the legacy Postgres schema Co-Authored-By: Claude Opus 5.5 --- packages/cli/src/migrate-to-sqlite.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/cli/src/migrate-to-sqlite.ts b/packages/cli/src/migrate-to-sqlite.ts index d02ee5cc..cf4feab2 100644 --- a/packages/cli/src/migrate-to-sqlite.ts +++ b/packages/cli/src/migrate-to-sqlite.ts @@ -38,6 +38,12 @@ export async function migrateToSqlite(sourceUrl: string, file: string): Promise< // One read-only snapshot of Postgres for all tables. await pg.begin("isolation level repeatable read read only", async (tx) => { for (const t of tablesInFkOrder()) { + // Tables born after the move to SQLite (PEP-67 subscriptions…) don't exist in Postgres. + const [{ found }] = await tx.unsafe(`select to_regclass($1) is not null as found`, [`public."${t.name}"`]); + if (!found) { + report.push({ name: t.name, source: 0, copied: 0 }); + continue; + } const rows = await tx.unsafe(`select * from "${t.name}"`); const cols = t.columns.filter((c) => rows.length === 0 || c.name in rows[0]!); if (rows.length) {