From b331305f4aaa501e8f58b19aa22cdb2a7035a8dd Mon Sep 17 00:00:00 2001
From: peppa-bot
Date: Tue, 24 Nov 2026 11:14:06 +0000
Subject: [PATCH 1/6] =?UTF-8?q?PEP-250:=20=D0=BF=D0=BB=D0=B0=D0=BD=20?=
=?UTF-8?q?=E2=80=94=20=D0=B7=D0=B0=D0=BF=D1=80=D0=BE=D1=81=D1=8B=20=D0=B4?=
=?UTF-8?q?=D0=BE=D1=81=D1=82=D1=83=D0=BF=D0=B0=20=D0=B0=D0=B3=D0=B5=D0=BD?=
=?UTF-8?q?=D1=82=D0=B0=20=D0=BA=20=D1=81=D0=B5=D1=80=D0=B2=D0=B8=D1=81?=
=?UTF-8?q?=D0=B0=D0=BC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Opus 5.5
---
.../changes/pep-250-access-requests/design.md | 43 ++++++++++++++++
.../pep-250-access-requests/proposal.md | 28 ++++++++++
.../specs/access-hub/spec.md | 51 +++++++++++++++++++
.../changes/pep-250-access-requests/tasks.md | 18 +++++++
4 files changed, 140 insertions(+)
create mode 100644 openspec/changes/pep-250-access-requests/design.md
create mode 100644 openspec/changes/pep-250-access-requests/proposal.md
create mode 100644 openspec/changes/pep-250-access-requests/specs/access-hub/spec.md
create mode 100644 openspec/changes/pep-250-access-requests/tasks.md
diff --git a/openspec/changes/pep-250-access-requests/design.md b/openspec/changes/pep-250-access-requests/design.md
new file mode 100644
index 00000000..7c8d872f
--- /dev/null
+++ b/openspec/changes/pep-250-access-requests/design.md
@@ -0,0 +1,43 @@
+# Design: PEP-250 запросы доступа
+
+## Модель
+Таблица `access_requests`: `project_id`, `owner_id` (владелец проекта на момент запроса — только он
+видит и решает), `task_id`, `session_id`, `agent_id`, `agent_name`, `catalog_id` | `host`
+(https-origin), `service_key` (= `catalog_id` или `host`, ключ «без повторов»), `purpose` (≤ 500),
+`mode` read|write, `status`, `reason`, `connection_id`, `repeats`, `decided_by`, `decided_at`.
+Отдельная таблица, а не `settings`: нужны выборки по владельцу и проекту, история решений.
+
+## Решения
+- **Кому**: всегда владелец проекта (`projects.owner_id`). Агент получателя не выбирает — так ключ
+ не уходит «чужому» человеку и нельзя навязать запрос постороннему.
+- **Без повторов**: один открытый запрос на `project × service_key`; повтор агента — `repeats + 1`,
+ режим расширяется до записи, если просили запись; второе сообщение владельцу не отправляется.
+- **Сервис**: `service` — id каталога (`stripe`) или его название; иначе `host` (адрес или имя
+ хоста). Адрес проверяется как в шлюзе: `parseBaseUrl` (только https, без логина, не localhost/
+ внутренние имена/частные IP) и DNS — если имя разрешается в закрытый адрес, отказ. Не разрешилось
+ имя — запрос принимается, шлюз проверит адрес ещё раз при вызове.
+- **Уже есть доступ**: если у агента уже есть подключение к этому сервису с нужным режимом —
+ отказ с подсказкой вызвать `call_connection`.
+- **Цель — данные**: текст цели хранится как есть, владельцу показывается дословно (`asIs`), при
+ записи проходит `guardUntrusted` (признаки инъекции → событие и сообщение людям проекта).
+- **Выдача**: «Разрешить из уже подключённого» — разрешение проекту (любой агент проекта): чтение
+ «сразу», запись «сразу» только если просили запись. Существующее разрешение того же проекта
+ расширяется, а не перезаписывается. «Подключить и разрешить» — `createConnection` по карточке
+ каталога (или свой сервис с адресом из запроса) + то же разрешение + проверка ключа.
+- **Агенту**: `runner/access-requests.ts` — живой агент задачи получает сообщение (`sendToSession`);
+ нет живого и задача не готова/не в архиве — `moveTask(in_progress, { prompt })`; проект на паузе —
+ ничего (решение видно в `list_requests`). Отказ — с причиной владельца.
+- **Автозапрос**: `call_connection` с отказом `no_grant | read_denied | write_denied |
+ operation_denied` (и `unknown_connection`, если имя — id каталога) создаёт запрос с целью
+ «агент обратился: МЕТОД /путь». `needs_approval` — не запрос (это подтверждения PEP-235).
+ Инструмента `http_request` в MCP нет — эта часть описания стори не применима.
+- **Уведомление**: мастер-чат владельца (важное, ссылка на карточку) + `deliverToUser` событием
+ `questions` с `projectId`: ночная тишина (outbox) и пауза проекта (ничего не шлётся) соблюдаются
+ сами. Кнопки Telegram: ссылка на карточку и `ar::no` (отказ без причины; причину — на сайте).
+- **Чужой не видит**: `accessRequestForUser` отдаёт запрос только `owner_id`, который всё ещё
+ владелец проекта; иначе 404. Бот проверяет то же.
+- **declare_needs**: у пункта поле `use: "product" | "agent"`; `agent` — запрос доступа к сервису
+ каталога, найденному по `service` или имени секрета, вместо пункта списка.
+
+## Риски
+- Решение в остановленном проекте не будит агента — увидит при следующем запуске в `list_requests`.
diff --git a/openspec/changes/pep-250-access-requests/proposal.md b/openspec/changes/pep-250-access-requests/proposal.md
new file mode 100644
index 00000000..e736200c
--- /dev/null
+++ b/openspec/changes/pep-250-access-requests/proposal.md
@@ -0,0 +1,28 @@
+# PEP-250: агент сам просит доступ к сервису
+
+## Why
+Агенту нужен внешний сервис, которого нет в его подключениях (Access Hub, PEP-234/249). Сейчас он
+останавливается или просит положить ключ в секреты проекта — и ключ попадает агенту в окружение.
+Нужно, чтобы агент сам отправил владельцу запрос «нужен доступ к X, вот зачем», владелец один раз
+подключил ключ (или разрешил уже подключённое), а агент продолжил без перезапуска стори руками.
+
+## What Changes
+- Новая таблица `access_requests` (миграция 0031): запрос доступа проекта к сервису каталога или
+ адресу, цель словами, чтение/запись, статус `open | granted | denied | cancelled`, причина отказа,
+ счётчик повторов.
+- MCP агента: `request_access`, `list_requests`, `cancel_request`; отказ `call_connection` по
+ отсутствию разрешения сам становится запросом доступа.
+- Владелец проекта получает одно сообщение (мастер-чат, Telegram с кнопками «Посмотреть и решить» /
+ «Отказать», push) и видит блок «Агенты просят доступ» в «Подключениях»; карточка запроса
+ `/connections/requests/` — только ему: «Подключить и разрешить» (ключ один раз),
+ «Разрешить из уже подключённого», «Отказать» с причиной.
+- Решение доходит до агента: живому — сообщение, остановленному — задача возвращается в работу
+ с этим сообщением.
+- `declare_needs` с пометкой `use: "agent"` превращается в запрос доступа вместо секрета проекта.
+- Правило агентам в `template/RULES.md`: ключи внешних сервисов для своей работы — `request_access`.
+
+## Impact
+- `packages/db` (схема, миграция), `packages/core/src/access-requests.ts`,
+ `packages/runner/src/access-requests.ts`, `packages/mcp/src/agent.ts`, бот (кнопка `ar:`),
+ веб «Подключения», переводы ru/kk/en, `template/RULES.md`.
+- Существующие подключения, разрешения и шлюз не меняются.
diff --git a/openspec/changes/pep-250-access-requests/specs/access-hub/spec.md b/openspec/changes/pep-250-access-requests/specs/access-hub/spec.md
new file mode 100644
index 00000000..8f288dee
--- /dev/null
+++ b/openspec/changes/pep-250-access-requests/specs/access-hub/spec.md
@@ -0,0 +1,51 @@
+## ADDED Requirements
+
+### Requirement: Агент запрашивает доступ к сервису
+Агент SHALL запрашивать доступ к сервису каталога или адресу в интернете с целью словами и режимом (чтение или запись). Запрос SHALL получать только владелец проекта: одно сообщение со ссылкой на карточку запроса. Адрес SHALL проверяться как в шлюзе: только https и открытый интернет.
+
+#### Scenario: Запрос доходит до владельца
+- **GIVEN** проект «SHOP» владельца «anna» и агент «Шустрик» в задаче «SHOP-3»
+- **WHEN** агент запрашивает доступ к «stripe» с целью «проверить оплату заказа» на чтение
+- **THEN** у «anna» в «Подключениях» в блоке «Агенты просят доступ» запрос: «Шустрик», «SHOP-3», «Stripe», цель и «чтение»
+- **AND** «anna» получает одно сообщение со ссылкой на карточку запроса
+
+#### Scenario: Адрес внутрь отклоняется
+- **GIVEN** агент проекта «SHOP»
+- **WHEN** он запрашивает доступ к адресу «https://127.0.0.1/admin» или «localhost»
+- **THEN** запрос не создаётся
+- **AND** агент получает отказ: адрес должен быть в интернете
+
+#### Scenario: Повтор не создаёт второй запрос
+- **GIVEN** открытый запрос проекта «SHOP» к «stripe»
+- **WHEN** агент снова запрашивает «stripe», теперь на запись
+- **THEN** запрос остаётся один, повторов: 1, режим — запись
+- **AND** второго сообщения владельцу нет
+
+### Requirement: Владелец выдаёт доступ или отказывает
+Карточку запроса SHALL видеть только владелец проекта. Владелец SHALL подключить сервис и разрешить его проекту одним действием (ключ вводится один раз), разрешить уже подключённое или отказать с причиной. Решение SHALL доходить до агента: живому — сообщением, остановленному — задача возвращается в работу.
+
+#### Scenario: Подключить и разрешить
+- **GIVEN** открытый запрос «SHOP» к «stripe» на чтение и живой агент задачи
+- **WHEN** «anna» вставляет ключ на карточке и нажимает «Подключить и разрешить»
+- **THEN** появляется подключение «Stripe» с разрешением проекту «SHOP»: чтение — сразу, запись — нет
+- **AND** агент получает «доступ к Stripe выдан» и может вызвать его
+
+#### Scenario: Отказ с причиной
+- **GIVEN** открытый запрос «SHOP» к «stripe»
+- **WHEN** «anna» отказывает с причиной «используйте тестовые данные»
+- **THEN** запрос закрыт как отказанный
+- **AND** агент получает причину «используйте тестовые данные»
+
+#### Scenario: Чужой не видит запрос
+- **GIVEN** запрос проекта «SHOP» владельца «anna»
+- **WHEN** пользователь «boris» открывает ссылку на карточку или нажимает кнопку отказа
+- **THEN** запрос ему не показывается и не меняется
+
+### Requirement: Отказ шлюза становится запросом
+Вызов подключения без разрешения проекта или агента SHALL сам создавать запрос доступа к этому сервису, а агент SHALL получать ответ «запросил доступ — жди или продолжай без него».
+
+#### Scenario: Вызов без разрешения
+- **GIVEN** у «anna» подключение «Stripe», разрешённое проекту «SHOP» только на чтение
+- **WHEN** агент «SHOP» делает запись через «stripe»
+- **THEN** вызов отклонён
+- **AND** создан запрос доступа «SHOP» к «stripe» на запись, агенту сказано, что доступ запрошен
diff --git a/openspec/changes/pep-250-access-requests/tasks.md b/openspec/changes/pep-250-access-requests/tasks.md
new file mode 100644
index 00000000..4b602cb8
--- /dev/null
+++ b/openspec/changes/pep-250-access-requests/tasks.md
@@ -0,0 +1,18 @@
+## 1. Данные и ядро
+- [ ] 1.1 Таблица `access_requests` + миграция 0031
+- [ ] 1.2 `core/access-requests.ts`: запрос, повтор, проверка адреса, список, отмена, вид для владельца, выдача и отказ
+- [ ] 1.3 Сообщение владельцу: мастер-чат, Telegram с кнопками, push
+
+## 2. Агент и решения
+- [ ] 2.1 `runner/access-requests.ts`: решение доходит до агента (живой / остановленный)
+- [ ] 2.2 MCP: `request_access`, `list_requests`, `cancel_request`; автозапрос из `call_connection`; `declare_needs use: agent`
+- [ ] 2.3 Бот: кнопка `ar::no`
+
+## 3. Экран
+- [ ] 3.1 «Подключения»: блок «Агенты просят доступ»; карточка запроса с тремя действиями
+- [ ] 3.2 Переводы ru/kk/en, словарь
+
+## 4. Правила, тесты, завершение
+- [ ] 4.1 `template/RULES.md`: `request_access` вместо ключей в секретах
+- [ ] 4.2 Тест `access-requests.test.ts`: запрос, выдача, отказ, повтор, чужой, адрес внутрь
+- [ ] 4.3 Память, архив, PR
--
2.45.2
From 84f50b1c5b994020fdebf9141d088bf97255dfdf Mon Sep 17 00:00:00 2001
From: peppa-bot
Date: Tue, 24 Nov 2026 11:22:45 +0000
Subject: [PATCH 2/6] =?UTF-8?q?PEP-250:=20=D0=B7=D0=B0=D0=BF=D1=80=D0=BE?=
=?UTF-8?q?=D1=81=D1=8B=20=D0=B4=D0=BE=D1=81=D1=82=D1=83=D0=BF=D0=B0=20?=
=?UTF-8?q?=E2=80=94=20=D1=82=D0=B0=D0=B1=D0=BB=D0=B8=D1=86=D0=B0,=20?=
=?UTF-8?q?=D1=8F=D0=B4=D1=80=D0=BE,=20MCP=20=D0=B0=D0=B3=D0=B5=D0=BD?=
=?UTF-8?q?=D1=82=D0=B0,=20=D0=BA=D0=BD=D0=BE=D0=BF=D0=BA=D0=B0=20=D0=B1?=
=?UTF-8?q?=D0=BE=D1=82=D0=B0,=20=D0=BA=D0=B0=D1=80=D1=82=D0=BE=D1=87?=
=?UTF-8?q?=D0=BA=D0=B0=20=D0=B2=D0=BB=D0=B0=D0=B4=D0=B5=D0=BB=D1=8C=D1=86?=
=?UTF-8?q?=D0=B0,=20=D0=BF=D0=B5=D1=80=D0=B5=D0=B2=D0=BE=D0=B4=D1=8B?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Opus 5.5
---
apps/bot/src/bot.ts | 11 +-
apps/web/app/(app)/actions.ts | 38 +-
apps/web/app/(app)/connections/page.tsx | 10 +-
.../(app)/connections/requests/[id]/page.tsx | 184 +
apps/web/components/AccessRequests.tsx | 44 +
packages/core/src/access-requests.ts | 367 ++
packages/core/src/connections.ts | 10 +-
packages/core/src/index.ts | 1 +
.../db/migrations/0031_access_requests.sql | 32 +
.../db/migrations/meta/0031_snapshot.json | 5532 +++++++++++++++++
packages/db/migrations/meta/_journal.json | 7 +
packages/db/src/schema.ts | 31 +
packages/mcp/src/agent.ts | 93 +-
packages/runner/src/access-requests.ts | 64 +
packages/runner/src/index.ts | 1 +
packages/shared/src/i18n/en/access-hub.ts | 43 +
packages/shared/src/i18n/kk/access-hub.ts | 43 +
17 files changed, 6500 insertions(+), 11 deletions(-)
create mode 100644 apps/web/app/(app)/connections/requests/[id]/page.tsx
create mode 100644 apps/web/components/AccessRequests.tsx
create mode 100644 packages/core/src/access-requests.ts
create mode 100644 packages/db/migrations/0031_access_requests.sql
create mode 100644 packages/db/migrations/meta/0031_snapshot.json
create mode 100644 packages/runner/src/access-requests.ts
diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts
index 8d2e32b4..fa62e1ba 100644
--- a/apps/bot/src/bot.ts
+++ b/apps/bot/src/bot.ts
@@ -80,7 +80,7 @@ import {
} from "@peppa/core";
import { projects, tasks, type Db } from "@peppa/db";
import { formatTaskKey, voiceStoriesEnabled } from "@peppa/shared";
-import { delayAction, resolveTaskById } from "@peppa/runner";
+import { delayAction, denyAccessRequestAndTell, resolveTaskById } from "@peppa/runner";
import { parseDelayCallback } from "@peppa/core";
import { acceptTask, answerAndDeliver, classifyMessage, decideIncident, decideProposals, moveTask, postToChat, REQUEST_SENT_TEXT, requestSubscription, resumeSession, stopSession } from "@peppa/runner";
import { INTENT_TEXT, statusAnswer } from "@peppa/core";
@@ -1019,6 +1019,15 @@ export function createBot(o: BotOptions) {
await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`));
return "done";
}
+ // PEP-250: «Отказать» under an agent's access request: `ar::no` — only the project's owner (core checks).
+ if (parts[0] === "ar") {
+ const toast = await denyAccessRequestAndTell(db, user.id, Number(parts[1]), null).then(
+ () => tr("Отказано. Агент узнает об этом."),
+ (e) => (e instanceof PeppaError ? e.message : (log(`access request: ${(e as Error).stack ?? e}`), tr("Ошибка"))),
+ );
+ await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`));
+ return "done";
+ }
if (parts[0] === "f") {
const toast = await onFeedbackButton(user, c, parts).catch((e) => (log(`feedback: ${(e as Error).stack ?? e}`), tr("Ошибка")));
wakeOutbox?.();
diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts
index 7d83c314..6b26998c 100644
--- a/apps/web/app/(app)/actions.ts
+++ b/apps/web/app/(app)/actions.ts
@@ -66,7 +66,7 @@ import {
} from "@peppa/core";
import { checkConnection, createConnection, deleteConnection, grantConnection, replaceConnectionSecret, revokeConnection, revokeGrant, type CatalogAuth, type ConnectionCheckResult, type GrantMode } from "@peppa/core";
import { attachmentLabel, fixFeedback, linkAttachments, linkFeedback, parseAttachmentIds, rejectFeedback, restoreProject } from "@peppa/core";
-import { deleteProject, decideProposals, mergeProposals } from "@peppa/runner";
+import { deleteProject, decideProposals, mergeProposals, connectAndGrantAccessRequest, denyAccessRequestAndTell, grantAccessRequestFromExisting } from "@peppa/runner";
import { bugsinkFromEnv } from "@peppa/bugsink";
import { loadEnv } from "@peppa/shared";
import { pauseProject, resumeProject, acceptAll, acceptStory, autoPublish, fixStory, confirmTaskDecision, changeTaskDecision, undoSplit, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProjectOnce, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, syncSessionAttachments, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, managesProject, saveAgentsMd, cancelOwnLogin, finishOwnClaudeLogin, connectOwnSubscription, removeOwnSubscription, type OwnSubscriptionKind, chooseSharedSubscription, requestSubscription } from "@peppa/runner";
@@ -1038,6 +1038,42 @@ export async function grantConnectionAction(f: FormData) {
});
}
+// PEP-250: an agent's access request — only its project's owner decides (core checks).
+export async function connectAccessRequestAction(f: FormData) {
+ const user = asWebActor(await requireUser());
+ await attempt(f, async () => {
+ const id = Number(str(f, "requestId"));
+ const kind = str(f, "authKind") as CatalogAuth;
+ const { connection } = await connectAndGrantAccessRequest(db, user.id, id, {
+ name: str(f, "name"),
+ baseUrl: str(f, "baseUrl") || undefined,
+ secret: String(f.get("secret") ?? "").trim(),
+ authKind: AUTH_KINDS.includes(kind) ? kind : "bearer",
+ authHeader: str(f, "authHeader") || null,
+ });
+ const r = await checkConnection(db, user.id, connection.id).catch(() => null);
+ return `/connections/requests/${id}?done=granted&check=${checkWord(r)}`;
+ });
+}
+
+export async function grantAccessRequestAction(f: FormData) {
+ const user = asWebActor(await requireUser());
+ await attempt(f, async () => {
+ const id = Number(str(f, "requestId"));
+ await grantAccessRequestFromExisting(db, user.id, id, Number(str(f, "connectionId")));
+ return `/connections/requests/${id}?done=granted`;
+ });
+}
+
+export async function denyAccessRequestAction(f: FormData) {
+ const user = asWebActor(await requireUser());
+ await attempt(f, async () => {
+ const id = Number(str(f, "requestId"));
+ await denyAccessRequestAndTell(db, user.id, id, str(f, "reason") || null);
+ return `/connections/requests/${id}?done=denied`;
+ });
+}
+
export async function revokeGrantAction(f: FormData) {
const user = asWebActor(await requireUser());
await attempt(f, async () => {
diff --git a/apps/web/app/(app)/connections/page.tsx b/apps/web/app/(app)/connections/page.tsx
index d2cb7ad1..101edc5c 100644
--- a/apps/web/app/(app)/connections/page.tsx
+++ b/apps/web/app/(app)/connections/page.tsx
@@ -11,6 +11,7 @@ import {
grantableAgents,
listConnections,
listUserProjects,
+ ownerAccessRequests,
searchCatalog,
type CatalogKind,
type CatalogService,
@@ -20,6 +21,7 @@ import {
type ConnectionView,
type GrantMode,
} from "@peppa/core";
+import { AccessRequestList } from "@/components/AccessRequests";
import { Hidden } from "@/components/cards";
import { ago, Empty, Flash, Notice, PageHeader, Section } from "@/components/common";
import { Badge } from "@/components/ui/badge";
@@ -358,7 +360,7 @@ export default async function ConnectionsPage({ searchParams }: { searchParams:
const user = await requireUser();
const t = await getT();
const engineer = (await uiMode()) === "engineer";
- const [list, journal, projects, agents] = await Promise.all([listConnections(db, user.id), connectionJournal(db, user.id, { limit: 50 }), listUserProjects(db, user.id), grantableAgents(db)]);
+ const [list, journal, projects, agents, requests] = await Promise.all([listConnections(db, user.id), connectionJournal(db, user.id, { limit: 50 }), listUserProjects(db, user.id), grantableAgents(db), ownerAccessRequests(db, user.id)]);
const chosen = q.service === "custom" ? "custom" : catalogService(q.service);
const kind = q.kind && (CATALOG_KINDS as string[]).includes(q.kind) ? q.kind : null;
return (
@@ -371,6 +373,12 @@ export default async function ConnectionsPage({ searchParams }: { searchParams:
+ {requests.length > 0 && (
+
+ )}
+
{list.length > 0 && (
{list.map((c) => (
diff --git a/apps/web/app/(app)/connections/requests/[id]/page.tsx b/apps/web/app/(app)/connections/requests/[id]/page.tsx
new file mode 100644
index 00000000..508b5b1a
--- /dev/null
+++ b/apps/web/app/(app)/connections/requests/[id]/page.tsx
@@ -0,0 +1,184 @@
+import Link from "next/link";
+import { notFound } from "next/navigation";
+import { ExternalLink, KeyRound } from "lucide-react";
+import { accessRequestForUser, catalogService, connectionsForRequest, type AccessRequestView, type CatalogService, type ConnectionView } from "@peppa/core";
+import type { Translator } from "@peppa/shared/i18n";
+import { AccessStatus, accessModeText } from "@/components/AccessRequests";
+import { Hidden } from "@/components/cards";
+import { Flash, Notice, PageHeader, Section } from "@/components/common";
+import { Button } from "@/components/ui/button";
+import { Card } from "@/components/ui/card";
+import { Input, Textarea } from "@/components/ui/input";
+import { Workspace } from "@/components/Workspace";
+import { requireUser } from "@/lib/auth";
+import { db } from "@/lib/db";
+import { getT } from "@/lib/i18n";
+import { connectAccessRequestAction, denyAccessRequestAction, grantAccessRequestAction } from "../../../actions";
+
+export async function generateMetadata() {
+ const t = await getT();
+ return { title: t("Запрос доступа — FORGE") };
+}
+
+const SELECT = "h-9 rounded-md border border-input bg-background px-2 text-sm";
+
+function Fact({ label, children }: { label: string; children: React.ReactNode }) {
+ return (
+
+ {label}
+ {children}
+
+ );
+}
+
+function DoneNotice({ done, check, t }: { done?: string; check?: string; t: Translator }) {
+ if (done === "denied") return {t("Отказано. Агент получит вашу причину и продолжит без этого сервиса.")} ;
+ if (done !== "granted") return null;
+ const tail = check === "bad_key" ? t("Но сервис не принял ключ: замените его в разделе «Подключения».") : check === "down" ? t("Сервис сейчас не отвечает — ключ проверится при первом запросе агента.") : "";
+ return (
+
+ {t("Доступ выдан. Агент получил сообщение и продолжит работу; ключ доступа он не видит.")} {tail}
+
+ );
+}
+
+function ConnectForm({ r, card, t }: { r: AccessRequestView; card: CatalogService | null; t: Translator }) {
+ const back = `/connections/requests/${r.id}`;
+ return (
+
+
+ {t("Возьмите ключ доступа")}
+ {card ? (
+ <>
+ {t.text(card.keyHint)}
+
+ {t("Открыть страницу, где берут ключ")}
+
+ >
+ ) : (
+ {t("Он есть в описании сервиса для разработчиков или у того, кто его сделал.")}
+ )}
+
+
+ {t("Вставьте его сюда")}
+
+
+
+ );
+}
+
+function ExistingForm({ r, fit, other, t }: { r: AccessRequestView; fit: ConnectionView[]; other: ConnectionView[]; t: Translator }) {
+ const all = [...fit, ...other];
+ if (!all.length) return null;
+ return (
+
+ );
+}
+
+/** PEP-250: the card of an agent's access request — its project's owner only (others: 404). */
+export default async function AccessRequestPage({ params, searchParams }: { params: Promise<{ id: string }>; searchParams: Promise<{ error?: string; done?: string; check?: string }> }) {
+ const [{ id }, q] = await Promise.all([params, searchParams]);
+ const user = await requireUser();
+ const t = await getT();
+ const r = /^\d+$/.test(id) ? await accessRequestForUser(db, user.id, Number(id)) : null;
+ if (!r) notFound();
+ const card = catalogService(r.catalogId);
+ const { fit, other } = r.status === "open" ? await connectionsForRequest(db, user.id, r) : { fit: [], other: [] };
+ return (
+
+
+
+ {t("Агент просит доступ к {service}", { service: r.service })}>}
+ crumbs={ {t("Подключения")}}
+ >
+
+ {r.status === "open"
+ ? t("Агенту нужен этот сервис для работы над задачей. Ключ доступа вы вводите один раз, агент его не увидит: запросы выполняет FORGE и записывает их в журнал. Можно и отказать — агент продолжит без сервиса.")
+ : t("По этому запросу уже есть решение.")}
+
+
+
+
+
+
+ {r.repeats > 0 &&
{t("агент просил ещё раз: {n}", { n: r.repeats })} }
+
+ {r.agentName ?? "—"}
+ {r.taskKey ? {r.taskKey}{r.taskTitle ? ` — ${r.taskTitle}` : ""} : "—"}
+ {r.projectName}
+
+ {r.service}
+ {card && (
+
+ {t("Документация сервиса")}
+
+ )}
+ {!card && r.host && {r.host} }
+
+ {accessModeText(r.mode, t)}
+ {/* The agent's own words: shown as is, never as instructions. */}
+ {r.purpose}
+ {r.status === "denied" && {r.reason ?? t("без причины")} }
+
+
+ {r.status === "open" && (
+ <>
+
+
+
+
+ {r.mode === "write"
+ ? t("Агенты проекта смогут читать и менять данные в этом сервисе. Изменить или отозвать доступ можно в разделе «Подключения».")
+ : t("Агенты проекта смогут только читать данные в этом сервисе. Изменить или отозвать доступ можно в разделе «Подключения».")}
+
+
+
+ {fit.length + other.length > 0 && (
+
+ )}
+
+ >
+ )}
+
+ );
+}
diff --git a/apps/web/components/AccessRequests.tsx b/apps/web/components/AccessRequests.tsx
new file mode 100644
index 00000000..42a4b817
--- /dev/null
+++ b/apps/web/components/AccessRequests.tsx
@@ -0,0 +1,44 @@
+import Link from "next/link";
+import { KeyRound } from "lucide-react";
+import type { AccessRequestView } from "@peppa/core";
+import type { Translator } from "@peppa/shared/i18n";
+import { ago } from "@/components/common";
+import { Badge } from "@/components/ui/badge";
+import { Card } from "@/components/ui/card";
+
+/** «читать» / «читать и менять». */
+export function accessModeText(mode: AccessRequestView["mode"], t: Translator): string {
+ return mode === "write" ? t("читать и менять") : t("только читать");
+}
+
+export function AccessStatus({ r, t }: { r: AccessRequestView; t: Translator }) {
+ if (r.status === "open") return {t("ждёт вашего решения")} ;
+ if (r.status === "granted") return {t("доступ выдан")} ;
+ if (r.status === "denied") return {t("отказано")} ;
+ return {t("агент отменил запрос")} ;
+}
+
+/** PEP-250: «Агенты просят доступ» on «Подключения» — the owner's open requests. */
+export function AccessRequestList({ list, t }: { list: AccessRequestView[]; t: Translator }) {
+ return (
+
+ {list.map((r) => (
+
+
+
+ {r.service}
+ · {accessModeText(r.mode, t)}
+
+ · {r.agentName ? t("агент {name}", { name: r.agentName }) : t("агент")} · {r.taskKey ?? r.projectKey}
+
+ {r.purpose}
+ {ago(r.updatedAt, t)}
+
+ {t("Посмотреть и решить")}
+
+
+
+ ))}
+
+ );
+}
diff --git a/packages/core/src/access-requests.ts b/packages/core/src/access-requests.ts
new file mode 100644
index 00000000..e97af22e
--- /dev/null
+++ b/packages/core/src/access-requests.ts
@@ -0,0 +1,367 @@
+// PEP-250 Access Hub: an agent asks the project's owner for access to an external service.
+// The owner gets one message with a link to the request's card (only they can open it), adds the
+// key once or allows an existing connection, or refuses with a reason. One open request per
+// project × service; a repeated ask adds to it. Telling the agent about the decision is the
+// runner's job (runner/access-requests.ts) — this module only stores, checks and notifies.
+import { asIs, m as tr } from "@peppa/shared/i18n";
+import { accessRequests, agents, connectionGrants, projects, sessions, tasks, users, type Db } from "@peppa/db";
+import { and, desc, eq, inArray, type SQL } from "drizzle-orm";
+import { lookup as dnsLookup } from "node:dns/promises";
+import { logEvent } from "./audit.ts";
+import { addMasterMessage } from "./chats.ts";
+import { catalogService, CONNECTION_CATALOG, type CatalogService } from "./connection-catalog.ts";
+import { agentConnections, createConnection, grantConnection, isBlockedAddress, listConnections, parseBaseUrl, type ConnectionInput, type ConnectionView, type GrantMode } from "./connections.ts";
+import { PeppaError } from "./errors.ts";
+import { deliverToUser } from "./notifications.ts";
+import { guardUntrusted } from "./untrusted.ts";
+
+export type AccessMode = "read" | "write";
+export type AccessRequestStatus = "open" | "granted" | "denied" | "cancelled";
+export const ACCESS_PURPOSE_MAX = 500;
+export const ACCESS_REASON_MAX = 500;
+/** How many recent requests an agent sees in list_requests. */
+const AGENT_LIST_MAX = 20;
+
+export interface AccessRequestView {
+ id: number;
+ projectId: number;
+ projectKey: string;
+ projectName: string;
+ ownerId: number;
+ taskId: number | null;
+ taskKey: string | null;
+ taskTitle: string | null;
+ sessionId: number | null;
+ agentName: string | null;
+ catalogId: string | null;
+ host: string | null;
+ /** Brand name of the catalog card, or the host. */
+ service: string;
+ purpose: string;
+ mode: AccessMode;
+ status: AccessRequestStatus;
+ reason: string | null;
+ connectionId: number | null;
+ repeats: number;
+ decidedAt: Date | null;
+ createdAt: Date;
+ updatedAt: Date;
+}
+
+export type HostLookup = (host: string) => Promise;
+const defaultLookup: HostLookup = async (host) => (await dnsLookup(host, { all: true, verbatim: true })).map((a) => a.address);
+
+/**
+ * An address from an agent → an https origin in the open internet, checked like the gateway does
+ * (parseBaseUrl), plus DNS: a name resolving to a closed address is refused. A name that does not
+ * resolve is accepted — the gateway checks the address again on every call.
+ */
+export async function publicOrigin(raw: string, o: { lookup?: HostLookup; env?: NodeJS.ProcessEnv } = {}): Promise {
+ const s = String(raw ?? "").trim();
+ if (!s || s.length > 300) throw new PeppaError(tr("Укажите адрес сервиса в интернете"));
+ const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(s) ? s : `https://${s}`;
+ let origin: string;
+ try {
+ const u = new URL(withScheme);
+ if (u.username || u.password) throw new Error("login");
+ // The path and the query of the agent's address don't matter: access is to the whole service.
+ origin = new URL(parseBaseUrl(`${u.protocol}//${u.host}`, o.env)).origin;
+ } catch (e) {
+ if (e instanceof PeppaError) throw e;
+ throw new PeppaError(tr("Адрес сервиса должен начинаться с https:// и не содержать логин, пароль, «?» и «#»"));
+ }
+ const host = new URL(origin).hostname.replace(/^\[|\]$/g, "");
+ if ((o.env ?? process.env).PEPPA_CONNECTIONS_ALLOW_PRIVATE === "1") return origin;
+ const ips = await (o.lookup ?? defaultLookup)(host).catch(() => [] as string[]);
+ if (ips.some(isBlockedAddress)) throw new PeppaError(tr("Этот адрес сервиса недоступен: укажите адрес в интернете"));
+ return origin;
+}
+
+/** A catalog card by its id or its name (case-insensitive). */
+export function findCatalogService(q: string | null | undefined): CatalogService | null {
+ const s = String(q ?? "").trim().toLowerCase();
+ if (!s) return null;
+ return catalogService(s) ?? CONNECTION_CATALOG.find((c) => c.name.toLowerCase() === s) ?? null;
+}
+
+/** A catalog card from an env name: STRIPE_SECRET_KEY → stripe. */
+export function catalogFromSecretName(name: string | null | undefined): CatalogService | null {
+ const words = String(name ?? "").toLowerCase().split(/_+/).filter(Boolean);
+ for (let n = Math.min(3, words.length); n >= 1; n--) {
+ for (const glue of ["-", ""]) {
+ const hit = catalogService(words.slice(0, n).join(glue));
+ if (hit) return hit;
+ }
+ }
+ return null;
+}
+
+const serviceName = (r: { catalogId: string | null; host: string | null }) => catalogService(r.catalogId)?.name ?? (r.host ? new URL(r.host).host : "?");
+
+async function views(db: Db, where: SQL | undefined, limit = 200): Promise {
+ const rows = await db
+ .select({ r: accessRequests, projectKey: projects.key, projectName: projects.name, taskNumber: tasks.number, taskTitle: tasks.title })
+ .from(accessRequests)
+ .innerJoin(projects, eq(projects.id, accessRequests.projectId))
+ .leftJoin(tasks, eq(tasks.id, accessRequests.taskId))
+ .where(where)
+ .orderBy(desc(accessRequests.updatedAt), desc(accessRequests.id))
+ .limit(limit);
+ return rows.map(({ r, projectKey, projectName, taskNumber, taskTitle }) => ({
+ id: r.id,
+ projectId: r.projectId,
+ projectKey,
+ projectName,
+ ownerId: r.ownerId,
+ taskId: r.taskId,
+ taskKey: taskNumber != null ? `${projectKey}-${taskNumber}` : null,
+ taskTitle: taskTitle ?? null,
+ sessionId: r.sessionId,
+ agentName: r.agentName,
+ catalogId: r.catalogId,
+ host: r.host,
+ service: serviceName(r),
+ purpose: r.purpose,
+ mode: r.mode,
+ status: r.status,
+ reason: r.reason,
+ connectionId: r.connectionId,
+ repeats: r.repeats,
+ decidedAt: r.decidedAt,
+ createdAt: r.createdAt,
+ updatedAt: r.updatedAt,
+ }));
+}
+
+export async function getAccessRequest(db: Db, id: number): Promise {
+ return (await views(db, eq(accessRequests.id, id), 1))[0] ?? null;
+}
+
+export interface AccessRequestInput {
+ sessionId: number | null | undefined;
+ /** A catalog id (`stripe`) or a card's name. */
+ service?: string | null;
+ /** An address or a host name of an own service. */
+ host?: string | null;
+ purpose: string;
+ mode?: AccessMode;
+}
+
+export interface AccessRequestResult {
+ request: AccessRequestView;
+ /** false — an open request for this service existed: the ask was added to it. */
+ created: boolean;
+}
+
+async function sessionOf(db: Db, sessionId: number | null | undefined) {
+ if (sessionId == null) throw new PeppaError("Access requests work only in sessions started by FORGE");
+ const [s] = await db
+ .select({ id: sessions.id, projectId: sessions.projectId, taskId: sessions.taskId, agentId: sessions.agentId, agentName: agents.name })
+ .from(sessions)
+ .leftJoin(agents, eq(agents.id, sessions.agentId))
+ .where(eq(sessions.id, sessionId));
+ if (!s) throw new PeppaError("Session not found");
+ return s;
+}
+
+/** Does this connection serve the requested service? */
+const serves = (c: { catalogId: string | null; baseUrl: string }, r: { catalogId: string | null; host: string | null }) =>
+ r.catalogId ? c.catalogId === r.catalogId : !!r.host && safeOrigin(c.baseUrl) === r.host;
+const safeOrigin = (u: string) => {
+ try {
+ return new URL(u).origin;
+ } catch {
+ return null;
+ }
+};
+
+/**
+ * The agent asks for access. Refused: no service, a closed address, access already given. An
+ * open request for the same project × service gets the ask added (`repeats`, write widens the
+ * mode) and no second message; a new one is announced to the project's owner.
+ */
+export async function requestAccess(db: Db, i: AccessRequestInput, o: { lookup?: HostLookup; now?: Date; auto?: boolean } = {}): Promise {
+ const s = await sessionOf(db, i.sessionId);
+ const purpose = String(i.purpose ?? "").replace(/\s+/g, " ").trim().slice(0, ACCESS_PURPOSE_MAX);
+ if (!purpose) throw new PeppaError("Say what the access is for (purpose): the owner decides by it");
+ const mode: AccessMode = i.mode === "write" ? "write" : "read";
+ let catalogId: string | null = null;
+ let host: string | null = null;
+ if (i.service) {
+ const card = findCatalogService(i.service);
+ if (card) catalogId = card.id;
+ else if (!i.host) throw new PeppaError(`No service «${String(i.service).slice(0, 60)}» in the catalog: pass its address as host (https://…)`);
+ }
+ if (!catalogId) {
+ if (!i.host) throw new PeppaError("Name the service (a catalog id like stripe) or its address (host)");
+ host = await publicOrigin(i.host, { lookup: o.lookup });
+ // An address of a catalog service is the catalog card (shared rules and steps for the owner).
+ const card = CONNECTION_CATALOG.find((c) => !c.baseEditable && safeOrigin(c.baseUrl) === host);
+ if (card) [catalogId, host] = [card.id, null];
+ }
+ const serviceKey = catalogId ?? host!;
+ const [project] = await db.select().from(projects).where(eq(projects.id, s.projectId));
+ if (!project) throw new PeppaError("Project not found");
+ if (project.ownerId == null) throw new PeppaError("This project has no owner to ask");
+
+ // Already allowed: no request, call it.
+ const have = (await agentConnections(db, s.id)).find((c) => serves(c, { catalogId, host }) && (mode === "read" ? c.readMode === "auto" : c.writeMode === "auto"));
+ if (have) throw new PeppaError(`You already have this access: call_connection("${have.slug}", …) (list_connections shows what is allowed)`);
+
+ const now = o.now ?? new Date();
+ const [open] = await db.select().from(accessRequests).where(and(eq(accessRequests.projectId, s.projectId), eq(accessRequests.serviceKey, serviceKey), eq(accessRequests.status, "open")));
+ if (open) {
+ const wider: AccessMode = open.mode === "write" || mode === "write" ? "write" : "read";
+ await db.update(accessRequests).set({ repeats: open.repeats + 1, mode: wider, updatedAt: now }).where(eq(accessRequests.id, open.id));
+ await logEvent(db, { projectId: s.projectId, taskId: s.taskId, sessionId: s.id, type: "access_request_repeated", payload: { requestId: open.id, service: serviceKey, mode: wider } });
+ return { request: (await getAccessRequest(db, open.id))!, created: false };
+ }
+ // The purpose is the agent's text: kept as is, shown verbatim, checked for injection signs.
+ await guardUntrusted(db, { projectId: s.projectId, taskId: s.taskId, sessionId: s.id, source: "запрос доступа агента", text: purpose }).catch(() => null);
+ const [row] = await db
+ .insert(accessRequests)
+ .values({ projectId: s.projectId, ownerId: project.ownerId, taskId: s.taskId, sessionId: s.id, agentId: s.agentId, agentName: s.agentName, catalogId, host, serviceKey, purpose, mode, createdAt: now, updatedAt: now })
+ .returning({ id: accessRequests.id });
+ await logEvent(db, { projectId: s.projectId, taskId: s.taskId, sessionId: s.id, type: "access_requested", payload: { requestId: row!.id, service: serviceKey, mode, auto: !!o.auto } });
+ const request = (await getAccessRequest(db, row!.id))!;
+ await announceAccessRequest(db, request).catch(() => null);
+ return { request, created: true };
+}
+
+export const accessRequestUrl = (id: number) => `/connections/requests/${id}`;
+
+/** The text of the owner's message (master chat, Telegram, push). */
+export function accessRequestText(r: AccessRequestView): string {
+ const who = r.agentName ? tr("Агент {name}", { name: asIs(r.agentName) }) : tr("Агент");
+ const where = r.taskKey ? tr("{project}, задача {task}", { project: asIs(r.projectName), task: r.taskKey }) : asIs(r.projectName);
+ const what = r.mode === "write" ? tr("{service} — читать и менять", { service: asIs(r.service) }) : tr("{service} — только читать", { service: asIs(r.service) });
+ return [tr("{who} просит доступ: {what}.", { who, what }), tr("Зачем: {purpose}", { purpose: asIs(r.purpose) }), tr("Проект: {where}", { where }), tr("Откройте запрос, чтобы подключить сервис или отказать.")].join("\n");
+}
+
+/** One message to the project's owner. Night quiet and the project's pause apply (outbox, deliverToUser). */
+export async function announceAccessRequest(db: Db, r: AccessRequestView): Promise {
+ const text = accessRequestText(r);
+ const url = accessRequestUrl(r.id);
+ await addMasterMessage(db, r.ownerId, { kind: "event", important: true, text, dedupeKey: `master:access-request:${r.id}`, url }).catch(() => null);
+ const [u] = await db.select().from(users).where(eq(users.id, r.ownerId));
+ if (!u) return;
+ const base = (process.env.PEPPA_WEB_URL ?? "").replace(/\/+$/, "");
+ const buttons = [...(base.startsWith("https://") ? [[{ text: tr("Посмотреть и решить"), url: `${base}${url}` }]] : []), [{ text: tr("Отказать"), callback_data: `ar:${r.id}:no` }]];
+ await deliverToUser(db, u, {
+ event: "questions",
+ projectId: r.projectId,
+ dedupeKey: `access-request:${r.id}:${u.telegramChatId}`,
+ pushKey: `access-request:${r.id}:u${u.id}`,
+ telegram: { params: { text, reply_markup: { inline_keyboard: buttons } } },
+ push: { title: tr("Агент просит доступ"), body: text, url, tag: `access-request:${r.id}` },
+ });
+}
+
+// ---------- the agent's side ----------
+
+/** The project's recent requests for list_requests (the session's project only). */
+export async function sessionAccessRequests(db: Db, sessionId: number | null | undefined): Promise {
+ const s = await sessionOf(db, sessionId);
+ return views(db, eq(accessRequests.projectId, s.projectId), AGENT_LIST_MAX);
+}
+
+export async function cancelAccessRequest(db: Db, sessionId: number | null | undefined, id: number): Promise {
+ const s = await sessionOf(db, sessionId);
+ const [r] = await db.select().from(accessRequests).where(eq(accessRequests.id, id));
+ if (!r || r.projectId !== s.projectId) throw new PeppaError(`Request #${id} not found in this project`);
+ if (r.status !== "open") throw new PeppaError(`Request #${id} is already ${r.status}`);
+ await db.update(accessRequests).set({ status: "cancelled", decidedAt: new Date(), updatedAt: new Date() }).where(eq(accessRequests.id, id));
+ await logEvent(db, { projectId: r.projectId, taskId: s.taskId, sessionId: s.id, type: "access_request_cancelled", payload: { requestId: id } });
+ return (await getAccessRequest(db, id))!;
+}
+
+// ---------- the owner's side ----------
+
+/** The request for its owner only — someone else (a member, a superadmin) gets null → 404. */
+export async function accessRequestForUser(db: Db, userId: number, id: number): Promise {
+ const r = await getAccessRequest(db, id);
+ if (!r || r.ownerId !== userId) return null;
+ const [p] = await db.select({ ownerId: projects.ownerId, deletedAt: projects.deletedAt }).from(projects).where(eq(projects.id, r.projectId));
+ // Ownership moved on or the project is deleted: the old owner no longer decides.
+ if (!p || p.ownerId !== userId || p.deletedAt) return null;
+ return r;
+}
+
+async function ownOpen(db: Db, userId: number, id: number): Promise {
+ const r = await accessRequestForUser(db, userId, id);
+ if (!r) throw new PeppaError(tr("Запрос не найден"));
+ if (r.status !== "open") throw new PeppaError(tr("По этому запросу уже есть решение"));
+ return r;
+}
+
+/** «Агенты просят доступ»: the user's open requests. */
+export async function ownerAccessRequests(db: Db, userId: number): Promise {
+ const list = await views(db, and(eq(accessRequests.ownerId, userId), eq(accessRequests.status, "open")));
+ const ids = [...new Set(list.map((r) => r.projectId))];
+ if (!ids.length) return [];
+ const own = new Set((await db.select({ id: projects.id, ownerId: projects.ownerId, deletedAt: projects.deletedAt }).from(projects).where(inArray(projects.id, ids))).filter((p) => p.ownerId === userId && !p.deletedAt).map((p) => p.id));
+ return list.filter((r) => own.has(r.projectId));
+}
+
+/** The owner's connections that can serve this request (same catalog card or address) first, then the rest. */
+export async function connectionsForRequest(db: Db, userId: number, r: AccessRequestView): Promise<{ fit: ConnectionView[]; other: ConnectionView[] }> {
+ const all = (await listConnections(db, userId)).filter((c) => c.status === "active" && c.hasKey);
+ const fit = all.filter((c) => serves(c, r));
+ return { fit, other: all.filter((c) => !fit.includes(c)) };
+}
+
+const RANK: Record = { off: 0, ask: 1, auto: 2 };
+const widest = (a: GrantMode, b: GrantMode): GrantMode => (RANK[b] > RANK[a] ? b : a);
+
+/** Grant to the request's project (any of its agents): read at once, write at once only if asked. An existing grant only widens. */
+async function grantFor(db: Db, userId: number, r: AccessRequestView, connectionId: number): Promise {
+ const [prev] = (await db.select().from(connectionGrants).where(and(eq(connectionGrants.connectionId, connectionId), eq(connectionGrants.projectId, r.projectId)))).filter((g) => g.agentId == null);
+ await grantConnection(db, userId, connectionId, {
+ projectId: r.projectId,
+ agentId: null,
+ operations: prev?.operations ?? [],
+ readMode: widest(prev?.readMode ?? "off", "auto"),
+ writeMode: widest(prev?.writeMode ?? "off", r.mode === "write" ? "auto" : "off"),
+ });
+}
+
+async function closeGranted(db: Db, userId: number, r: AccessRequestView, connectionId: number): Promise {
+ const now = new Date();
+ await db.update(accessRequests).set({ status: "granted", connectionId, decidedBy: userId, decidedAt: now, updatedAt: now }).where(eq(accessRequests.id, r.id));
+ await logEvent(db, { projectId: r.projectId, taskId: r.taskId, type: "access_granted", payload: { requestId: r.id, connectionId } });
+ return (await getAccessRequest(db, r.id))!;
+}
+
+/** «Разрешить из уже подключённого». */
+export async function grantAccessFromExisting(db: Db, userId: number, id: number, connectionId: number): Promise {
+ const r = await ownOpen(db, userId, id);
+ await grantFor(db, userId, r, connectionId); // grantConnection checks that the connection is the user's and active
+ return closeGranted(db, userId, r, connectionId);
+}
+
+/** «Подключить и разрешить»: the key is entered once — a new connection by the catalog card (or the requested address) and the grant. */
+export async function connectAndGrantAccess(db: Db, userId: number, id: number, i: Omit & { secret: string }): Promise<{ request: AccessRequestView; connection: ConnectionView }> {
+ const r = await ownOpen(db, userId, id);
+ const card = catalogService(r.catalogId);
+ const input: ConnectionInput = card
+ ? { name: i.name, secret: i.secret, catalogId: card.id, baseUrl: card.baseEditable ? i.baseUrl : undefined }
+ : { name: i.name || new URL(r.host!).host, secret: i.secret, baseUrl: i.baseUrl?.trim() || r.host!, authKind: i.authKind, authHeader: i.authHeader };
+ // Free name: «Stripe», «Stripe 2»…
+ const taken = new Set((await listConnections(db, userId)).map((c) => c.name));
+ const base = (input.name ?? "").trim() || card?.name || "";
+ let name = base;
+ for (let n = 2; taken.has(name); n++) name = `${base} ${n}`;
+ const connection = await createConnection(db, userId, { ...input, name });
+ await grantFor(db, userId, r, connection.id);
+ return { request: await closeGranted(db, userId, r, connection.id), connection };
+}
+
+/** «Отказать»: the reason (optional) reaches the agent. */
+export async function denyAccessRequest(db: Db, userId: number, id: number, reason?: string | null): Promise {
+ const r = await ownOpen(db, userId, id);
+ const why = String(reason ?? "").replace(/\s+/g, " ").trim().slice(0, ACCESS_REASON_MAX) || null;
+ const now = new Date();
+ await db.update(accessRequests).set({ status: "denied", reason: why, decidedBy: userId, decidedAt: now, updatedAt: now }).where(eq(accessRequests.id, id));
+ await logEvent(db, { projectId: r.projectId, taskId: r.taskId, type: "access_denied", payload: { requestId: id, reason: why } });
+ return (await getAccessRequest(db, id))!;
+}
diff --git a/packages/core/src/connections.ts b/packages/core/src/connections.ts
index d44566ad..3d9fb2c6 100644
--- a/packages/core/src/connections.ts
+++ b/packages/core/src/connections.ts
@@ -555,6 +555,8 @@ export interface AgentConnection {
slug: string;
/** Catalog service name, null = own service. */
service: string | null;
+ /** PEP-250: the catalog card id, null = own service. */
+ catalogId: string | null;
baseUrl: string;
docsUrl: string | null;
readMode: GrantMode;
@@ -582,7 +584,7 @@ export async function agentConnections(db: Db, sessionId: number): Promise; body: Buffer | null }) => Promise<{ status: number; contentType: string | null; body: Buffer; truncated: boolean; location?: boolean }>;
@@ -739,7 +741,9 @@ export async function callConnection(db: Db, call: ConnectionCall, o: { fetch?:
};
const deny = async (reason: ConnectionReason): Promise => {
await record("denied", reason, null);
- return { ok: false, reason };
+ // PEP-250: which service and what kind of request — a missing grant becomes an access request.
+ const clean = cleanPath(rawPath);
+ return { ok: false, reason, ...(conn ? { service: { catalogId: conn.catalogId, baseUrl: conn.baseUrl } } : {}), ...(clean && conn ? { kind: classifyRequest(conn.catalogId, method, clean.path) } : {}) };
};
if (!s) return { ok: false, reason: "no_session" };
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 13b43606..c97e01d4 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -110,6 +110,7 @@ export * from "./accept-digest.ts";
export * from "./connections.ts";
export * from "./connection-journal.ts";
export * from "./connection-catalog.ts";
+export * from "./access-requests.ts";
export * from "./edge-dns.ts";
export * from "./retention.ts";
export * from "./history.ts";
diff --git a/packages/db/migrations/0031_access_requests.sql b/packages/db/migrations/0031_access_requests.sql
new file mode 100644
index 00000000..37d457b6
--- /dev/null
+++ b/packages/db/migrations/0031_access_requests.sql
@@ -0,0 +1,32 @@
+CREATE TABLE `access_requests` (
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
+ `project_id` integer NOT NULL,
+ `owner_id` integer NOT NULL,
+ `task_id` integer,
+ `session_id` integer,
+ `agent_id` integer,
+ `agent_name` text,
+ `catalog_id` text,
+ `host` text,
+ `service_key` text NOT NULL,
+ `purpose` text NOT NULL,
+ `mode` text DEFAULT 'read' NOT NULL,
+ `status` text DEFAULT 'open' NOT NULL,
+ `reason` text,
+ `connection_id` integer,
+ `repeats` integer DEFAULT 0 NOT NULL,
+ `decided_by` integer,
+ `decided_at` integer,
+ `created_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ `updated_at` integer DEFAULT (cast(unixepoch('subsec') * 1000 as integer)) NOT NULL,
+ FOREIGN KEY (`project_id`) REFERENCES `projects`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`owner_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,
+ FOREIGN KEY (`task_id`) REFERENCES `tasks`(`id`) ON UPDATE no action ON DELETE set null,
+ FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE set null,
+ FOREIGN KEY (`agent_id`) REFERENCES `agents`(`id`) ON UPDATE no action ON DELETE set null,
+ FOREIGN KEY (`connection_id`) REFERENCES `connections`(`id`) ON UPDATE no action ON DELETE set null,
+ FOREIGN KEY (`decided_by`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null
+);
+--> statement-breakpoint
+CREATE INDEX `access_requests_project_service` ON `access_requests` (`project_id`,`service_key`,`status`);--> statement-breakpoint
+CREATE INDEX `access_requests_owner` ON `access_requests` (`owner_id`,`status`);
\ No newline at end of file
diff --git a/packages/db/migrations/meta/0031_snapshot.json b/packages/db/migrations/meta/0031_snapshot.json
new file mode 100644
index 00000000..df023cd0
--- /dev/null
+++ b/packages/db/migrations/meta/0031_snapshot.json
@@ -0,0 +1,5532 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "52cd3bda-fbca-4c5c-8dde-7dbe12b1145d",
+ "prevId": "1ad8db33-759f-4508-9ebd-50d0f75742c5",
+ "tables": {
+ "access_requests": {
+ "name": "access_requests",
+ "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
+ },
+ "owner_id": {
+ "name": "owner_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
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_name": {
+ "name": "agent_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "catalog_id": {
+ "name": "catalog_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "host": {
+ "name": "host",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "service_key": {
+ "name": "service_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "purpose": {
+ "name": "purpose",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "mode": {
+ "name": "mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'read'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'open'"
+ },
+ "reason": {
+ "name": "reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "connection_id": {
+ "name": "connection_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "repeats": {
+ "name": "repeats",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "decided_by": {
+ "name": "decided_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "decided_at": {
+ "name": "decided_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))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "access_requests_project_service": {
+ "name": "access_requests_project_service",
+ "columns": [
+ "project_id",
+ "service_key",
+ "status"
+ ],
+ "isUnique": false
+ },
+ "access_requests_owner": {
+ "name": "access_requests_owner",
+ "columns": [
+ "owner_id",
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "access_requests_project_id_projects_id_fk": {
+ "name": "access_requests_project_id_projects_id_fk",
+ "tableFrom": "access_requests",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "access_requests_owner_id_users_id_fk": {
+ "name": "access_requests_owner_id_users_id_fk",
+ "tableFrom": "access_requests",
+ "tableTo": "users",
+ "columnsFrom": [
+ "owner_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "access_requests_task_id_tasks_id_fk": {
+ "name": "access_requests_task_id_tasks_id_fk",
+ "tableFrom": "access_requests",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "access_requests_session_id_sessions_id_fk": {
+ "name": "access_requests_session_id_sessions_id_fk",
+ "tableFrom": "access_requests",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "access_requests_agent_id_agents_id_fk": {
+ "name": "access_requests_agent_id_agents_id_fk",
+ "tableFrom": "access_requests",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "access_requests_connection_id_connections_id_fk": {
+ "name": "access_requests_connection_id_connections_id_fk",
+ "tableFrom": "access_requests",
+ "tableTo": "connections",
+ "columnsFrom": [
+ "connection_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "access_requests_decided_by_users_id_fk": {
+ "name": "access_requests_decided_by_users_id_fk",
+ "tableFrom": "access_requests",
+ "tableTo": "users",
+ "columnsFrom": [
+ "decided_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "agents": {
+ "name": "agents",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "character": {
+ "name": "character",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "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))"
+ }
+ },
+ "indexes": {
+ "agents_name_unique": {
+ "name": "agents_name_unique",
+ "columns": [
+ "name"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "attachments": {
+ "name": "attachments",
+ "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
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "chat_message_id": {
+ "name": "chat_message_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "event_id": {
+ "name": "event_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "file": {
+ "name": "file",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "mime": {
+ "name": "mime",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "size": {
+ "name": "size",
+ "type": "integer",
+ "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": {
+ "attachments_task": {
+ "name": "attachments_task",
+ "columns": [
+ "task_id"
+ ],
+ "isUnique": false
+ },
+ "attachments_message": {
+ "name": "attachments_message",
+ "columns": [
+ "chat_message_id"
+ ],
+ "isUnique": false
+ },
+ "attachments_event": {
+ "name": "attachments_event",
+ "columns": [
+ "event_id"
+ ],
+ "isUnique": false
+ },
+ "attachments_project": {
+ "name": "attachments_project",
+ "columns": [
+ "project_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "attachments_project_id_projects_id_fk": {
+ "name": "attachments_project_id_projects_id_fk",
+ "tableFrom": "attachments",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "attachments_user_id_users_id_fk": {
+ "name": "attachments_user_id_users_id_fk",
+ "tableFrom": "attachments",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "attachments_task_id_tasks_id_fk": {
+ "name": "attachments_task_id_tasks_id_fk",
+ "tableFrom": "attachments",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "attachments_chat_message_id_chat_messages_id_fk": {
+ "name": "attachments_chat_message_id_chat_messages_id_fk",
+ "tableFrom": "attachments",
+ "tableTo": "chat_messages",
+ "columnsFrom": [
+ "chat_message_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "attachments_event_id_events_id_fk": {
+ "name": "attachments_event_id_events_id_fk",
+ "tableFrom": "attachments",
+ "tableTo": "events",
+ "columnsFrom": [
+ "event_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "chat_messages": {
+ "name": "chat_messages",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "thread_key": {
+ "name": "thread_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "thread_title": {
+ "name": "thread_title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "important": {
+ "name": "important",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "author_kind": {
+ "name": "author_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'system'"
+ },
+ "author_user_id": {
+ "name": "author_user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "author_login": {
+ "name": "author_login",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "via": {
+ "name": "via",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "question_id": {
+ "name": "question_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "dedupe_key": {
+ "name": "dedupe_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tg_chat_id": {
+ "name": "tg_chat_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tg_message_id": {
+ "name": "tg_message_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))"
+ }
+ },
+ "indexes": {
+ "chat_messages_dedupe_key_unique": {
+ "name": "chat_messages_dedupe_key_unique",
+ "columns": [
+ "dedupe_key"
+ ],
+ "isUnique": true
+ },
+ "chat_messages_chat": {
+ "name": "chat_messages_chat",
+ "columns": [
+ "chat_id",
+ "id"
+ ],
+ "isUnique": false
+ },
+ "chat_messages_thread": {
+ "name": "chat_messages_thread",
+ "columns": [
+ "chat_id",
+ "thread_key",
+ "id"
+ ],
+ "isUnique": false
+ },
+ "chat_messages_created_at": {
+ "name": "chat_messages_created_at",
+ "columns": [
+ "created_at"
+ ],
+ "isUnique": false
+ },
+ "chat_messages_tg": {
+ "name": "chat_messages_tg",
+ "columns": [
+ "tg_chat_id",
+ "tg_message_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "chat_messages_chat_id_chats_id_fk": {
+ "name": "chat_messages_chat_id_chats_id_fk",
+ "tableFrom": "chat_messages",
+ "tableTo": "chats",
+ "columnsFrom": [
+ "chat_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "chat_messages_author_user_id_users_id_fk": {
+ "name": "chat_messages_author_user_id_users_id_fk",
+ "tableFrom": "chat_messages",
+ "tableTo": "users",
+ "columnsFrom": [
+ "author_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "chat_messages_question_id_questions_id_fk": {
+ "name": "chat_messages_question_id_questions_id_fk",
+ "tableFrom": "chat_messages",
+ "tableTo": "questions",
+ "columnsFrom": [
+ "question_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "chat_messages_task_id_tasks_id_fk": {
+ "name": "chat_messages_task_id_tasks_id_fk",
+ "tableFrom": "chat_messages",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "chats": {
+ "name": "chats",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tg_chat_id": {
+ "name": "tg_chat_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tg_title": {
+ "name": "tg_title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tg_linked_at": {
+ "name": "tg_linked_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tg_linked_by": {
+ "name": "tg_linked_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tg_bot_user_id": {
+ "name": "tg_bot_user_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))"
+ }
+ },
+ "indexes": {
+ "chats_user_id_unique": {
+ "name": "chats_user_id_unique",
+ "columns": [
+ "user_id"
+ ],
+ "isUnique": true
+ },
+ "chats_project_id_unique": {
+ "name": "chats_project_id_unique",
+ "columns": [
+ "project_id"
+ ],
+ "isUnique": true
+ },
+ "chats_tg_chat_id_unique": {
+ "name": "chats_tg_chat_id_unique",
+ "columns": [
+ "tg_chat_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "chats_user_id_users_id_fk": {
+ "name": "chats_user_id_users_id_fk",
+ "tableFrom": "chats",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "chats_project_id_projects_id_fk": {
+ "name": "chats_project_id_projects_id_fk",
+ "tableFrom": "chats",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "chats_tg_linked_by_users_id_fk": {
+ "name": "chats_tg_linked_by_users_id_fk",
+ "tableFrom": "chats",
+ "tableTo": "users",
+ "columnsFrom": [
+ "tg_linked_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "chats_tg_bot_user_id_users_id_fk": {
+ "name": "chats_tg_bot_user_id_users_id_fk",
+ "tableFrom": "chats",
+ "tableTo": "users",
+ "columnsFrom": [
+ "tg_bot_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "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
+ },
+ "check_runs_task_sha": {
+ "name": "check_runs_task_sha",
+ "columns": [
+ "task_id",
+ "sha"
+ ],
+ "isUnique": false
+ },
+ "check_runs_updated": {
+ "name": "check_runs_updated",
+ "columns": [
+ "updated_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "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": {}
+ },
+ "code_reviews": {
+ "name": "code_reviews",
+ "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": true,
+ "autoincrement": false
+ },
+ "pr_number": {
+ "name": "pr_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sha": {
+ "name": "sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'queued'"
+ },
+ "verdict": {
+ "name": "verdict",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "findings": {
+ "name": "findings",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "started_at": {
+ "name": "started_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))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "code_reviews_project_id_projects_id_fk": {
+ "name": "code_reviews_project_id_projects_id_fk",
+ "tableFrom": "code_reviews",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "code_reviews_task_id_tasks_id_fk": {
+ "name": "code_reviews_task_id_tasks_id_fk",
+ "tableFrom": "code_reviews",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "connection_grants": {
+ "name": "connection_grants",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "connection_id": {
+ "name": "connection_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "operations": {
+ "name": "operations",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "read_mode": {
+ "name": "read_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'off'"
+ },
+ "write_mode": {
+ "name": "write_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'off'"
+ },
+ "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": {
+ "connection_grants_project": {
+ "name": "connection_grants_project",
+ "columns": [
+ "project_id"
+ ],
+ "isUnique": false
+ },
+ "connection_grants_connection": {
+ "name": "connection_grants_connection",
+ "columns": [
+ "connection_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "connection_grants_connection_id_connections_id_fk": {
+ "name": "connection_grants_connection_id_connections_id_fk",
+ "tableFrom": "connection_grants",
+ "tableTo": "connections",
+ "columnsFrom": [
+ "connection_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "connection_grants_project_id_projects_id_fk": {
+ "name": "connection_grants_project_id_projects_id_fk",
+ "tableFrom": "connection_grants",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "connection_grants_agent_id_agents_id_fk": {
+ "name": "connection_grants_agent_id_agents_id_fk",
+ "tableFrom": "connection_grants",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "connection_grants_created_by_users_id_fk": {
+ "name": "connection_grants_created_by_users_id_fk",
+ "tableFrom": "connection_grants",
+ "tableTo": "users",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "connection_log": {
+ "name": "connection_log",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "owner_id": {
+ "name": "owner_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "connection_id": {
+ "name": "connection_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "connection_name": {
+ "name": "connection_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_name": {
+ "name": "agent_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "method": {
+ "name": "method",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "path": {
+ "name": "path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "decision": {
+ "name": "decision",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "reason": {
+ "name": "reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status_code": {
+ "name": "status_code",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'call'"
+ },
+ "parent_id": {
+ "name": "parent_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "project_key": {
+ "name": "project_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "duration_ms": {
+ "name": "duration_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "prev_hash": {
+ "name": "prev_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "hash": {
+ "name": "hash",
+ "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": {
+ "connection_log_owner": {
+ "name": "connection_log_owner",
+ "columns": [
+ "owner_id",
+ "id"
+ ],
+ "isUnique": false
+ },
+ "connection_log_session_created": {
+ "name": "connection_log_session_created",
+ "columns": [
+ "session_id",
+ "created_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "connection_log_owner_id_users_id_fk": {
+ "name": "connection_log_owner_id_users_id_fk",
+ "tableFrom": "connection_log",
+ "tableTo": "users",
+ "columnsFrom": [
+ "owner_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "connection_log_connection_id_connections_id_fk": {
+ "name": "connection_log_connection_id_connections_id_fk",
+ "tableFrom": "connection_log",
+ "tableTo": "connections",
+ "columnsFrom": [
+ "connection_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "connection_log_project_id_projects_id_fk": {
+ "name": "connection_log_project_id_projects_id_fk",
+ "tableFrom": "connection_log",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "connection_log_session_id_sessions_id_fk": {
+ "name": "connection_log_session_id_sessions_id_fk",
+ "tableFrom": "connection_log",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "connection_log_agent_id_agents_id_fk": {
+ "name": "connection_log_agent_id_agents_id_fk",
+ "tableFrom": "connection_log",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "connections": {
+ "name": "connections",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "owner_id": {
+ "name": "owner_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "base_url": {
+ "name": "base_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "auth_kind": {
+ "name": "auth_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'bearer'"
+ },
+ "auth_header": {
+ "name": "auth_header",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "catalog_id": {
+ "name": "catalog_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "check_status": {
+ "name": "check_status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "checked_at": {
+ "name": "checked_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "check_alerted_at": {
+ "name": "check_alerted_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "secret_enc": {
+ "name": "secret_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "dek_enc": {
+ "name": "dek_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "revoked_at": {
+ "name": "revoked_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_used_at": {
+ "name": "last_used_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))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "connections_owner_name": {
+ "name": "connections_owner_name",
+ "columns": [
+ "owner_id",
+ "name"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "connections_owner_id_users_id_fk": {
+ "name": "connections_owner_id_users_id_fk",
+ "tableFrom": "connections",
+ "tableTo": "users",
+ "columnsFrom": [
+ "owner_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "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
+ },
+ "actor_kind": {
+ "name": "actor_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "actor_user_id": {
+ "name": "actor_user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "actor_channel": {
+ "name": "actor_channel",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "actor_client_id": {
+ "name": "actor_client_id",
+ "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": {
+ "events_created_at": {
+ "name": "events_created_at",
+ "columns": [
+ "created_at"
+ ],
+ "isUnique": false
+ },
+ "events_session_type": {
+ "name": "events_session_type",
+ "columns": [
+ "session_id",
+ "type"
+ ],
+ "isUnique": false
+ },
+ "events_type_created": {
+ "name": "events_type_created",
+ "columns": [
+ "type",
+ "created_at"
+ ],
+ "isUnique": false
+ },
+ "events_project_created": {
+ "name": "events_project_created",
+ "columns": [
+ "project_id",
+ "created_at"
+ ],
+ "isUnique": false
+ },
+ "events_task_type": {
+ "name": "events_task_type",
+ "columns": [
+ "task_id",
+ "type"
+ ],
+ "isUnique": false
+ }
+ },
+ "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"
+ },
+ "events_actor_user_id_users_id_fk": {
+ "name": "events_actor_user_id_users_id_fk",
+ "tableFrom": "events",
+ "tableTo": "users",
+ "columnsFrom": [
+ "actor_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "feedback": {
+ "name": "feedback",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "via": {
+ "name": "via",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "context": {
+ "name": "context",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "screenshots": {
+ "name": "screenshots",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'received'"
+ },
+ "analysis": {
+ "name": "analysis",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "analysis_error": {
+ "name": "analysis_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "analysis_started_at": {
+ "name": "analysis_started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "option_index": {
+ "name": "option_index",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "reject_reason": {
+ "name": "reject_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "decided_by": {
+ "name": "decided_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "decided_at": {
+ "name": "decided_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))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "feedback_user": {
+ "name": "feedback_user",
+ "columns": [
+ "user_id",
+ "created_at"
+ ],
+ "isUnique": false
+ },
+ "feedback_status": {
+ "name": "feedback_status",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "feedback_user_id_users_id_fk": {
+ "name": "feedback_user_id_users_id_fk",
+ "tableFrom": "feedback",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "feedback_task_id_tasks_id_fk": {
+ "name": "feedback_task_id_tasks_id_fk",
+ "tableFrom": "feedback",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "feedback_decided_by_users_id_fk": {
+ "name": "feedback_decided_by_users_id_fk",
+ "tableFrom": "feedback",
+ "tableTo": "users",
+ "columnsFrom": [
+ "decided_by"
+ ],
+ "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": {}
+ },
+ "project_secrets": {
+ "name": "project_secrets",
+ "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
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value_enc": {
+ "name": "value_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "updated_by": {
+ "name": "updated_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))"
+ },
+ "updated_at": {
+ "name": "updated_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": {
+ "project_secrets_project_name": {
+ "name": "project_secrets_project_name",
+ "columns": [
+ "project_id",
+ "name"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "project_secrets_project_id_projects_id_fk": {
+ "name": "project_secrets_project_id_projects_id_fk",
+ "tableFrom": "project_secrets",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_secrets_created_by_users_id_fk": {
+ "name": "project_secrets_created_by_users_id_fk",
+ "tableFrom": "project_secrets",
+ "tableTo": "users",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "project_secrets_updated_by_users_id_fk": {
+ "name": "project_secrets_updated_by_users_id_fk",
+ "tableFrom": "project_secrets",
+ "tableTo": "users",
+ "columnsFrom": [
+ "updated_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "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
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "deleted_by": {
+ "name": "deleted_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))"
+ },
+ "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"
+ },
+ "projects_deleted_by_users_id_fk": {
+ "name": "projects_deleted_by_users_id_fk",
+ "tableFrom": "projects",
+ "tableTo": "users",
+ "columnsFrom": [
+ "deleted_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "push_outbox": {
+ "name": "push_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
+ },
+ "subscription_id": {
+ "name": "subscription_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "payload": {
+ "name": "payload",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "urgency": {
+ "name": "urgency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'normal'"
+ },
+ "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))"
+ },
+ "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": {
+ "push_outbox_dedupe_key_unique": {
+ "name": "push_outbox_dedupe_key_unique",
+ "columns": [
+ "dedupe_key"
+ ],
+ "isUnique": true
+ },
+ "push_outbox_status_created": {
+ "name": "push_outbox_status_created",
+ "columns": [
+ "status",
+ "created_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "push_outbox_subscription_id_push_subscriptions_id_fk": {
+ "name": "push_outbox_subscription_id_push_subscriptions_id_fk",
+ "tableFrom": "push_outbox",
+ "tableTo": "push_subscriptions",
+ "columnsFrom": [
+ "subscription_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "push_subscriptions": {
+ "name": "push_subscriptions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "endpoint": {
+ "name": "endpoint",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "p256dh": {
+ "name": "p256dh",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "auth": {
+ "name": "auth",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "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))"
+ },
+ "last_ok_at": {
+ "name": "last_ok_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "push_subscriptions_endpoint_unique": {
+ "name": "push_subscriptions_endpoint_unique",
+ "columns": [
+ "endpoint"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "push_subscriptions_user_id_users_id_fk": {
+ "name": "push_subscriptions_user_id_users_id_fk",
+ "tableFrom": "push_subscriptions",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "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
+ },
+ "msg_type": {
+ "name": "msg_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "default_option": {
+ "name": "default_option",
+ "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
+ },
+ "reminders": {
+ "name": "reminders",
+ "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))"
+ },
+ "answered_at": {
+ "name": "answered_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "questions_project_answered": {
+ "name": "questions_project_answered",
+ "columns": [
+ "project_id",
+ "answered_at"
+ ],
+ "isUnique": false
+ },
+ "questions_task": {
+ "name": "questions_task",
+ "columns": [
+ "task_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "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
+ },
+ "screenshots": {
+ "name": "screenshots",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "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": {}
+ },
+ "review_settings": {
+ "name": "review_settings",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "max_iterations": {
+ "name": "max_iterations",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 2
+ },
+ "rules": {
+ "name": "rules",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "review_settings_project_id_projects_id_fk": {
+ "name": "review_settings_project_id_projects_id_fk",
+ "tableFrom": "review_settings",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "runner_commands": {
+ "name": "runner_commands",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "payload": {
+ "name": "payload",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'queued'"
+ },
+ "result": {
+ "name": "result",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "error_kind": {
+ "name": "error_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "actor": {
+ "name": "actor",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "host": {
+ "name": "host",
+ "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))"
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "finished_at": {
+ "name": "finished_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "runner_commands_status_idx": {
+ "name": "runner_commands_status_idx",
+ "columns": [
+ "status",
+ "id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "runner_hosts": {
+ "name": "runner_hosts",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ssh_target": {
+ "name": "ssh_target",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ssh_port": {
+ "name": "ssh_port",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 22
+ },
+ "workdir": {
+ "name": "workdir",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'peppa'"
+ },
+ "peppa_url": {
+ "name": "peppa_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'unknown'"
+ },
+ "info": {
+ "name": "info",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_seen_at": {
+ "name": "last_seen_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "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))"
+ }
+ },
+ "indexes": {
+ "runner_hosts_name_unique": {
+ "name": "runner_hosts_name_unique",
+ "columns": [
+ "name"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "runner_tasks": {
+ "name": "runner_tasks",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "prompt": {
+ "name": "prompt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "front": {
+ "name": "front",
+ "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))"
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "ended_at": {
+ "name": "ended_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "runner_tasks_session_idx": {
+ "name": "runner_tasks_session_idx",
+ "columns": [
+ "session_id",
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "runner_tasks_session_id_sessions_id_fk": {
+ "name": "runner_tasks_session_id_sessions_id_fk",
+ "tableFrom": "runner_tasks",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "runner_tasks_task_id_tasks_id_fk": {
+ "name": "runner_tasks_task_id_tasks_id_fk",
+ "tableFrom": "runner_tasks",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_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
+ },
+ "rotate_reason": {
+ "name": "rotate_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "workspace_path": {
+ "name": "workspace_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "host_id": {
+ "name": "host_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "container": {
+ "name": "container",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "usage": {
+ "name": "usage",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "watch_state": {
+ "name": "watch_state",
+ "type": "text",
+ "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
+ },
+ "sessions_task_status": {
+ "name": "sessions_task_status",
+ "columns": [
+ "task_id",
+ "status"
+ ],
+ "isUnique": false
+ },
+ "sessions_status": {
+ "name": "sessions_status",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "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"
+ },
+ "sessions_host_id_runner_hosts_id_fk": {
+ "name": "sessions_host_id_runner_hosts_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "runner_hosts",
+ "columnsFrom": [
+ "host_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "sessions_agent_id_agents_id_fk": {
+ "name": "sessions_agent_id_agents_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "agent_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": {}
+ },
+ "task_deps": {
+ "name": "task_deps",
+ "columns": {
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "blocked_by_id": {
+ "name": "blocked_by_id",
+ "type": "integer",
+ "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": {
+ "task_deps_blocked_by": {
+ "name": "task_deps_blocked_by",
+ "columns": [
+ "blocked_by_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "task_deps_task_id_tasks_id_fk": {
+ "name": "task_deps_task_id_tasks_id_fk",
+ "tableFrom": "task_deps",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "task_deps_blocked_by_id_tasks_id_fk": {
+ "name": "task_deps_blocked_by_id_tasks_id_fk",
+ "tableFrom": "task_deps",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "blocked_by_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "task_deps_task_id_blocked_by_id_pk": {
+ "columns": [
+ "task_id",
+ "blocked_by_id"
+ ],
+ "name": "task_deps_task_id_blocked_by_id_pk"
+ }
+ },
+ "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
+ },
+ "gitea_issue": {
+ "name": "gitea_issue",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "position": {
+ "name": "position",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "archived_at": {
+ "name": "archived_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "origin": {
+ "name": "origin",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'human'"
+ },
+ "proposed": {
+ "name": "proposed",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "severity": {
+ "name": "severity",
+ "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
+ },
+ "tasks_project_issue": {
+ "name": "tasks_project_issue",
+ "columns": [
+ "project_id",
+ "gitea_issue"
+ ],
+ "isUnique": true
+ },
+ "tasks_project_status_pos": {
+ "name": "tasks_project_status_pos",
+ "columns": [
+ "project_id",
+ "status",
+ "position"
+ ],
+ "isUnique": false
+ }
+ },
+ "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
+ },
+ "chat_message_id": {
+ "name": "chat_message_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
+ },
+ "telegram_outbox_status_created": {
+ "name": "telegram_outbox_status_created",
+ "columns": [
+ "status",
+ "created_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "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"
+ },
+ "telegram_outbox_chat_message_id_chat_messages_id_fk": {
+ "name": "telegram_outbox_chat_message_id_chat_messages_id_fk",
+ "tableFrom": "telegram_outbox",
+ "tableTo": "chat_messages",
+ "columnsFrom": [
+ "chat_message_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": {
+ "telegram_updates_created": {
+ "name": "telegram_updates_created",
+ "columns": [
+ "created_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "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
+ },
+ "telegram_bot_token_enc": {
+ "name": "telegram_bot_token_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telegram_bot_username": {
+ "name": "telegram_bot_username",
+ "type": "text",
+ "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
+ },
+ "google_sub": {
+ "name": "google_sub",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "google_email": {
+ "name": "google_email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "google_linked_at": {
+ "name": "google_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
+ },
+ "users_google_sub_unique": {
+ "name": "users_google_sub_unique",
+ "columns": [
+ "google_sub"
+ ],
+ "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 b7d35a85..e47cb7e8 100644
--- a/packages/db/migrations/meta/_journal.json
+++ b/packages/db/migrations/meta/_journal.json
@@ -218,6 +218,13 @@
"when": 1795512094088,
"tag": "0030_access_hub_journal",
"breakpoints": true
+ },
+ {
+ "idx": 31,
+ "version": "6",
+ "when": 1795518856978,
+ "tag": "0031_access_requests",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts
index 3483bc51..2475cf72 100644
--- a/packages/db/src/schema.ts
+++ b/packages/db/src/schema.ts
@@ -747,6 +747,37 @@ export const connectionLog = sqliteTable(
(t) => [index("connection_log_owner").on(t.ownerId, t.id), index("connection_log_session_created").on(t.sessionId, t.createdAt)],
);
+/** PEP-250: an agent asks the project's owner for access to an external service. */
+export const accessRequests = sqliteTable(
+ "access_requests",
+ {
+ id: integer("id").primaryKey({ autoIncrement: true }),
+ projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
+ // The project's owner when asked: only they see and decide it.
+ ownerId: integer("owner_id").notNull().references(() => users.id, { onDelete: "cascade" }),
+ taskId: integer("task_id").references(() => tasks.id, { onDelete: "set null" }),
+ sessionId: integer("session_id").references(() => sessions.id, { onDelete: "set null" }),
+ agentId: integer("agent_id").references(() => agents.id, { onDelete: "set null" }),
+ agentName: text("agent_name"),
+ // A catalog card (core/connection-catalog.ts) or an https origin of an own service.
+ catalogId: text("catalog_id"),
+ host: text("host"),
+ // catalog_id ?? host: one open request per project × service.
+ serviceKey: text("service_key").notNull(),
+ purpose: text("purpose").notNull(),
+ mode: text("mode").$type<"read" | "write">().notNull().default("read"),
+ status: text("status").$type<"open" | "granted" | "denied" | "cancelled">().notNull().default("open"),
+ reason: text("reason"),
+ connectionId: integer("connection_id").references(() => connections.id, { onDelete: "set null" }),
+ repeats: integer("repeats").notNull().default(0),
+ decidedBy: integer("decided_by").references(() => users.id, { onDelete: "set null" }),
+ decidedAt: integer("decided_at", { mode: "timestamp_ms" }),
+ createdAt: createdAt(),
+ updatedAt: updatedAt(),
+ },
+ (t) => [index("access_requests_project_service").on(t.projectId, t.serviceKey, t.status), index("access_requests_owner").on(t.ownerId, t.status)],
+);
+
/** PEP-26: the reviewer agent of a project (no row = off). */
export const reviewSettings = sqliteTable("review_settings", {
projectId: integer("project_id").primaryKey().references(() => projects.id, { onDelete: "cascade" }),
diff --git a/packages/mcp/src/agent.ts b/packages/mcp/src/agent.ts
index 1df600b7..955aedd8 100644
--- a/packages/mcp/src/agent.ts
+++ b/packages/mcp/src/agent.ts
@@ -51,6 +51,11 @@ import {
productOnlySecret,
agentConnections,
callConnection,
+ cancelAccessRequest,
+ catalogFromSecretName,
+ requestAccess,
+ sessionAccessRequests,
+ type AccessRequestView,
guardUntrusted,
sessionIsolated,
CONNECTION_REASON_TEXT,
@@ -406,7 +411,7 @@ export function createAgentServer(db: Db, opts: AgentServerOptions = {}): McpSer
// PEP-234 Access Hub: the owner's external services, reached only through Peppa's gateway.
tool(
"list_connections",
- "List the external services (Access Hub connections) you may use in this session: short name to call it by (e.g. `stripe`), the service, its address and API docs, whether you may read and write («at once», or «asks the owner» — such calls are refused until owner confirmations exist), extra fine-grained operations («METHOD /path-prefix») and whether the key works. Their keys are NOT available to you and never will be: call with call_connection (in code mode: peppa.connections.call(\"stripe\", {method, path, body})) and FORGE adds the key itself. Anything not allowed is refused. Missing an access? Tell the owner through ask_pm which service and what for — they grant it in «Подключения».",
+ "List the external services (Access Hub connections) you may use in this session: short name to call it by (e.g. `stripe`), the service, its address and API docs, whether you may read and write («at once», or «asks the owner» — such calls are refused until owner confirmations exist), extra fine-grained operations («METHOD /path-prefix») and whether the key works. Their keys are NOT available to you and never will be: call with call_connection (in code mode: peppa.connections.call(\"stripe\", {method, path, body})) and FORGE adds the key itself. Anything not allowed is refused. Missing an access? request_access (service + purpose) — the owner gets a link, adds the key once, and you are told when it is granted. Never ask for an external service key as a project secret for your own work.",
{},
async () => {
if (!sessionId) return "Connections work only in sessions started by FORGE.";
@@ -440,16 +445,76 @@ export function createAgentServer(db: Db, opts: AgentServerOptions = {}): McpSer
},
async ({ connection, method, path, body, content_type }) => {
const r = await callConnection(db, { sessionId, connection, method, path, body, contentType: content_type });
- if (!r.ok) throw new PeppaError(`Refused: ${stripAsIs(CONNECTION_REASON_TEXT[r.reason])} (${r.reason})${r.status ? `, HTTP ${r.status}` : ""}`);
+ if (!r.ok) {
+ const refused = `Refused: ${stripAsIs(CONNECTION_REASON_TEXT[r.reason])} (${r.reason})${r.status ? `, HTTP ${r.status}` : ""}`;
+ // PEP-250: no grant for this service → the refusal becomes an access request by itself.
+ const asked = await autoRequest(r, String(connection), method, path).catch(() => null);
+ throw new PeppaError(asked ? `${refused}\n${asked}` : refused);
+ }
const s = await getSession(db, sessionId!);
const data = await guardUntrusted(db, { projectId: s.projectId, taskId: s.taskId, sessionId, source: `подключение ${String(connection)}`, text: r.body });
return [`HTTP ${r.status}${r.contentType ? ` · ${r.contentType}` : ""}${r.truncated ? " · truncated at 256 KB" : ""}`, data].join("\n");
},
);
+ // ── PEP-250: the agent asks the owner for access itself ─────────────────────
+ const requestLine = (r: AccessRequestView) =>
+ `- #${r.id} ${r.service} (${r.mode}) — ${r.status === "open" ? "open, waiting for the owner" : r.status === "granted" ? "GRANTED — see list_connections" : r.status === "denied" ? `DENIED${r.reason ? `: ${r.reason}` : " (no reason given)"}` : "cancelled"}${r.taskKey ? ` · ${r.taskKey}` : ""}${r.repeats ? ` · asked ${r.repeats + 1} times` : ""}\n purpose: ${r.purpose}`;
+ const AUTO_REASONS = new Set(["no_grant", "read_denied", "write_denied", "operation_denied"]);
+ async function autoRequest(r: Extract>, { ok: false }>, connection: string, method: string, path: string): Promise {
+ if (!sessionId) return null;
+ const service = AUTO_REASONS.has(r.reason) && r.service ? r.service : r.reason === "unknown_connection" ? { catalogId: connection.trim().toLowerCase(), baseUrl: "" } : null;
+ if (!service) return null;
+ const purpose = `Агент обратился: ${method.toUpperCase()} ${String(path).split("?")[0]!.slice(0, 120)}`;
+ const mode = (r.kind ?? (method.toUpperCase() === "GET" ? "read" : "write")) as "read" | "write";
+ const got = service.catalogId
+ ? await requestAccess(db, { sessionId, service: service.catalogId, host: service.baseUrl || null, purpose, mode }, { auto: true }).catch(() => null)
+ : await requestAccess(db, { sessionId, host: service.baseUrl, purpose, mode }, { auto: true }).catch(() => null);
+ if (!got) return null;
+ return `Access requested from the owner (request #${got.request.id}${got.created ? "" : ", added to the open one"}). Wait for the decision or go on without it (a mock, another way); you will get a message when it is granted or denied. Better: call request_access yourself with a clear purpose.`;
+ }
+
+ tool(
+ "request_access",
+ "Ask the project's owner for access to an external service you need for your work (Access Hub). Name a catalog service (`service`: stripe, github, sendgrid… — the id or the name) or an own service's address (`host`, https only, open internet), say in plain words what for (`purpose` — the owner decides by it) and whether you need to change anything there (`mode`: read | write). The owner gets one message with a link, adds the key once (you never see it) or refuses with a reason; you get a message either way, and a stopped story comes back to work. One open request per service and project: asking again adds to it. Don't put external service keys in project secrets for your own work — ask here. Then go on with what you can (a mock) instead of waiting.",
+ {
+ service: z.string().optional().describe("Catalog service id or name, e.g. stripe"),
+ host: z.string().optional().describe("Address of a service not in the catalog, e.g. https://api.example.com"),
+ purpose: z.string().min(3).describe("What for, plainly, ≤ 500 chars: «проверить статус оплаты заказа в тестовом режиме»"),
+ mode: z.enum(["read", "write"]).optional().describe("read (default) — look at data; write — create, change, delete, send"),
+ },
+ async ({ service, host, purpose, mode }) => {
+ const { request, created } = await requestAccess(db, { sessionId, service, host, purpose, mode });
+ return created
+ ? `Requested: #${request.id} ${request.service} (${request.mode}). The owner got a message. Go on without it (a mock, another way) — you will be told when it is granted or denied; list_requests shows the state.`
+ : `An open request for ${request.service} already exists (#${request.id}); your ask was added to it (mode now: ${request.mode}). The owner is not messaged again. Go on without it meanwhile.`;
+ },
+ );
+
+ tool(
+ "list_requests",
+ "Your project's access requests (request_access): open, granted (then call it via list_connections / call_connection), denied with the owner's reason, cancelled.",
+ {},
+ async () => {
+ const list = await sessionAccessRequests(db, sessionId);
+ if (!list.length) return "No access requests in this project.";
+ return ["Access requests of this project (newest first):", ...list.map(requestLine)].join("\n");
+ },
+ );
+
+ tool(
+ "cancel_request",
+ "Cancel an open access request you no longer need (e.g. found another way).",
+ { id: z.number().int().describe("Request number from list_requests") },
+ async ({ id }) => {
+ const r = await cancelAccessRequest(db, sessionId, id);
+ return `Cancelled: #${r.id} ${r.service}.`;
+ },
+ );
+
tool(
"declare_needs",
- "Declare what the product's OWNER must give before the product works for real instead of on mocks/demo data: an API key, an account, credentials. Call it BEFORE moving the story to review whenever the story needs something only the owner has. The owner (a product manager, not a programmer) gets the list in plain words in the project chat and on the «Ваш продукт» card, with a field to paste each key; an item with `secret` closes itself once the owner stores that secret, and FORGE hands all project secrets to the deployed product as env vars of the same name and restarts it. Write title/why/how in the owner's language, no jargon. Items add up across stories (same secret or title = same item). Returns the whole list with states.",
+ "Declare what the product's OWNER must give before the product works for real instead of on mocks/demo data: an API key, an account, credentials. Call it BEFORE moving the story to review whenever the story needs something only the owner has. The owner (a product manager, not a programmer) gets the list in plain words in the project chat and on the «Ваш продукт» card, with a field to paste each key; an item with `secret` closes itself once the owner stores that secret, and FORGE hands all project secrets to the deployed product as env vars of the same name and restarts it. A service only YOU need for your work (not the product) — mark it use: agent (or call request_access): the owner connects it in Access Hub and you never see the key. Write title/why/how in the owner's language, no jargon. Items add up across stories (same secret or title = same item). Returns the whole list with states.",
{
task: taskArg.optional().describe("The story that needs it (for the record)"),
needs: z
@@ -459,15 +524,33 @@ export function createAgentServer(db: Db, opts: AgentServerOptions = {}): McpSer
why: z.string().optional().describe("What does not work without it, plainly: «без него ответы — вымышленные примеры»"),
how: z.string().optional().describe("Where to get it, step by step for a non-programmer"),
secret: z.string().optional().describe("Env name the product reads it from (A–Z, 0–9, _), e.g. ANTHROPIC_API_KEY. Omit for things that are not a key (the owner ticks them off)"),
+ use: z.enum(["product", "agent"]).optional().describe("product (default) — the deployed product needs it; agent — only YOU need the service for your work: it becomes an Access Hub request (request_access), not a project secret"),
+ service: z.string().optional().describe("With use: agent — catalog service id (stripe…); default: guessed from `secret`"),
}),
)
.min(1)
.max(10),
},
- async ({ task, needs }) => {
+ async ({ task, needs: asked }) => {
const ref = task ? await resolve(task) : null;
const session = sessionId ? await getSession(db, sessionId) : null;
const p = ref?.project ?? (session ? await getProject(db, session.projectKey) : await projectOrDefault());
+ // PEP-250: a service only the agent needs goes through Access Hub — the key never reaches the agent's env.
+ const viaHub: string[] = [];
+ for (const n of asked.filter((x) => x.use === "agent")) {
+ const service = n.service ?? catalogFromSecretName(n.secret)?.id;
+ if (!service) {
+ viaHub.push(`- «${n.title}»: not a catalog service — call request_access with its address (host) instead.`);
+ continue;
+ }
+ const got = await requestAccess(db, { sessionId, service, purpose: n.why || n.title, mode: "read" }).then(
+ (r) => `- «${n.title}»: access request #${r.request.id} (${r.request.service})${r.created ? " sent to the owner" : " — already open"}. Ask write access with request_access if you need it.`,
+ (e) => `- «${n.title}»: ${(e as Error).message}`,
+ );
+ viaHub.push(got);
+ }
+ const needs = asked.filter((x) => x.use !== "agent").map(({ use: _u, service: _s, ...n }) => n);
+ if (!needs.length) return ["Nothing added to the product's list. Access Hub:", ...viaHub].join("\n");
const { added, all } = await declareNeeds(db, p.id, needs, { source: "agent", story: ref?.key ?? null });
if (added.length) {
const chat = await ensureProjectChat(db, p.id);
@@ -475,7 +558,7 @@ export function createAgentServer(db: Db, opts: AgentServerOptions = {}): McpSer
await sayInDiscussion(db, p, chat.id, text, session?.agentName ?? null, { agent: true });
}
const line = (n: (typeof all)[number]) => `- ${n.open ? "⏳ ждёт владельца" : "✅ дано"}: ${n.title}${n.secret ? ` ($${n.secret})` : ""}`;
- return [`Список «чтобы заработало по-настоящему» проекта ${p.key}:`, ...all.map(line), added.length ? `Владельцу отправлено сообщение о новых пунктах (${added.length}).` : "Новых пунктов нет — владельцу ничего не отправлено.", "Пока пункт открыт, продукт работает на моке: в резюме PR и в сообщении о готовности так и скажи. Служебных полей (токены, ключи) на экране пользователя быть не должно."].join("\n");
+ return [...(viaHub.length ? ["Access Hub:", ...viaHub, ""] : []), `Список «чтобы заработало по-настоящему» проекта ${p.key}:`, ...all.map(line), added.length ? `Владельцу отправлено сообщение о новых пунктах (${added.length}).` : "Новых пунктов нет — владельцу ничего не отправлено.", "Пока пункт открыт, продукт работает на моке: в резюме PR и в сообщении о готовности так и скажи. Служебных полей (токены, ключи) на экране пользователя быть не должно."].join("\n");
},
);
diff --git a/packages/runner/src/access-requests.ts b/packages/runner/src/access-requests.ts
new file mode 100644
index 00000000..6af4bafd
--- /dev/null
+++ b/packages/runner/src/access-requests.ts
@@ -0,0 +1,64 @@
+// PEP-250: the owner's decision on an agent's access request reaches the agent — like an answer
+// to a question: the live agent of the story gets a message; with nobody alive a story still in
+// work goes back to work with that message. A project on pause wakes nobody (the decision is in
+// list_requests). Owner checks are in core (accessRequestForUser).
+import { connectAndGrantAccess, denyAccessRequest, grantAccessFromExisting, isProjectPaused, listConnections, listSessions, logEvent, type AccessRequestView, type ConnectionInput } from "@peppa/core";
+import type { Db } from "@peppa/db";
+import { moveTask } from "./flow.ts";
+import { resolveTaskById, sendToSession } from "./sessions.ts";
+
+/** A story in these states gets a new agent with the decision; review/done/backlog are left alone. */
+const WAKE = ["proposing", "in_progress", "blocked"];
+
+export type AccessDelivery = "agent" | "restarted" | "none";
+
+/** Text for the agent (agents read English/Russian prompts — not translated). */
+export function accessDecisionText(r: AccessRequestView, slug?: string | null): string {
+ if (r.status === "granted") {
+ const what = r.mode === "write" ? "чтение и запись" : "чтение";
+ return `Доступ выдан (запрос #${r.id}): владелец разрешил ${r.service} — ${what}. Посмотри list_connections и вызывай call_connection${slug ? `("${slug}", …)` : ""}; ключ подставит FORGE. Продолжай задачу.`;
+ }
+ return `Владелец отказал в доступе к ${r.service} (запрос #${r.id}).${r.reason ? ` Причина: ${r.reason}` : " Причину не указал."} Продолжай без этого сервиса (мок, другой путь) и не проси этот доступ снова без новой причины.`;
+}
+
+export async function tellAgentAboutAccess(db: Db, r: AccessRequestView, slug?: string | null): Promise {
+ if (r.taskId == null || (await isProjectPaused(db, r.projectId))) return "none";
+ const text = accessDecisionText(r, slug);
+ let action: AccessDelivery = "none";
+ try {
+ const [live] = await listSessions(db, { active: true, taskId: r.taskId });
+ if (live) {
+ await sendToSession(db, live.id, text);
+ action = "agent";
+ } else {
+ const ref = await resolveTaskById(db, r.taskId);
+ if (!ref.task.archivedAt && WAKE.includes(ref.task.status)) {
+ await moveTask(db, ref, "in_progress", { prompt: text });
+ action = "restarted";
+ }
+ }
+ } catch {
+ action = "none";
+ }
+ await logEvent(db, { projectId: r.projectId, taskId: r.taskId, type: "access_decision_delivered", payload: { requestId: r.id, status: r.status, action } }).catch(() => null);
+ return action;
+}
+
+export async function grantAccessRequestFromExisting(db: Db, userId: number, id: number, connectionId: number): Promise {
+ const r = await grantAccessFromExisting(db, userId, id, connectionId);
+ const slug = (await listConnections(db, userId)).find((c) => c.id === connectionId)?.slug ?? null;
+ await tellAgentAboutAccess(db, r, slug);
+ return r;
+}
+
+export async function connectAndGrantAccessRequest(db: Db, userId: number, id: number, i: Omit & { secret: string }) {
+ const out = await connectAndGrantAccess(db, userId, id, i);
+ await tellAgentAboutAccess(db, out.request, out.connection.slug);
+ return out;
+}
+
+export async function denyAccessRequestAndTell(db: Db, userId: number, id: number, reason?: string | null): Promise {
+ const r = await denyAccessRequest(db, userId, id, reason);
+ await tellAgentAboutAccess(db, r);
+ return r;
+}
diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts
index da27aca1..6b094161 100644
--- a/packages/runner/src/index.ts
+++ b/packages/runner/src/index.ts
@@ -26,6 +26,7 @@ export * from "./triage.ts";
export * from "./ci-feedback.ts";
export * from "./deploy.ts";
export * from "./deploy-feedback.ts";
+export * from "./access-requests.ts";
export * from "./product-link.ts";
export * from "./platform-release.ts";
export * from "./platform-build.ts";
diff --git a/packages/shared/src/i18n/en/access-hub.ts b/packages/shared/src/i18n/en/access-hub.ts
index ed68b521..fedde5b5 100644
--- a/packages/shared/src/i18n/en/access-hub.ts
+++ b/packages/shared/src/i18n/en/access-hub.ts
@@ -163,4 +163,47 @@ export const accessHub: Record = {
"Журнал подключений: контрольные точки": "Connections journal: checkpoints",
"Журнал подключений пользователя {login} изменён в обход FORGE (запись {id}). Проверьте доступ к базе.": "The connections journal of user {login} was changed bypassing FORGE (entry {id}). Check access to the database.",
"Журнал ваших подключений изменён в обход FORGE. Администратор уже знает и разбирается; ключи доступа лучше заменить в разделе «Подключения».": "The journal of your connections was changed bypassing FORGE. The administrator already knows and is looking into it; better replace the access keys in «Connections».",
+ // PEP-250: agents ask for access themselves.
+ "Агенты просят доступ": "Agents ask for access",
+ "Запрос доступа — FORGE": "Access request — FORGE",
+ "Отказано. Агент получит вашу причину и продолжит без этого сервиса.": "Refused. The agent will get your reason and go on without this service.",
+ "Но сервис не принял ключ: замените его в разделе «Подключения».": "But the service didn't accept the key: replace it in «Connections».",
+ "Сервис сейчас не отвечает — ключ проверится при первом запросе агента.": "The service isn't answering now — the key will be checked on the agent's first request.",
+ "Доступ выдан. Агент получил сообщение и продолжит работу; ключ доступа он не видит.": "Access granted. The agent got a message and will go on working; it doesn't see the access key.",
+ "Он есть в описании сервиса для разработчиков или у того, кто его сделал.": "It's in the service's description for developers or with whoever made it.",
+ "Подключить и разрешить": "Connect and allow",
+ "Выберите подключение": "Choose a connection",
+ "Разрешить из уже подключённого": "Allow from what's already connected",
+ "Агент просит доступ к {service}": "An agent asks for access to {service}",
+ "Агенту нужен этот сервис для работы над задачей. Ключ доступа вы вводите один раз, агент его не увидит: запросы выполняет FORGE и записывает их в журнал. Можно и отказать — агент продолжит без сервиса.": "The agent needs this service to work on the task. You enter the access key once, and the agent won't see it: FORGE makes the requests and records them in the journal. You can also refuse — the agent will go on without the service.",
+ "По этому запросу уже есть решение.": "This request has already been decided.",
+ "агент просил ещё раз: {n}": "the agent asked again: {n}",
+ "Сервис": "Service",
+ "Что можно": "What's allowed",
+ "Зачем": "What for",
+ "Причина отказа": "Reason for refusal",
+ "без причины": "no reason",
+ "Агенты проекта смогут читать и менять данные в этом сервисе. Изменить или отозвать доступ можно в разделе «Подключения».": "The project's agents will be able to read and change data in this service. You can change or revoke the access in «Connections».",
+ "Агенты проекта смогут только читать данные в этом сервисе. Изменить или отозвать доступ можно в разделе «Подключения».": "The project's agents will only be able to read data in this service. You can change or revoke the access in «Connections».",
+ "Или разрешить из уже подключённого": "Or allow from what's already connected",
+ "Причина — агент её получит, например «используйте тестовые данные»": "Reason — the agent will get it, e.g. «use test data»",
+ "читать и менять": "read and change",
+ "только читать": "read only",
+ "ждёт вашего решения": "waiting for your decision",
+ "доступ выдан": "access granted",
+ "отказано": "refused",
+ "агент отменил запрос": "the agent cancelled the request",
+ "Посмотреть и решить": "View and decide",
+ "Отказано. Агент узнает об этом.": "Refused. The agent will be told.",
+ "Укажите адрес сервиса в интернете": "Give the service's address on the internet",
+ "{project}, задача {task}": "{project}, task {task}",
+ "{service} — читать и менять": "{service} — read and change",
+ "{service} — только читать": "{service} — read only",
+ "{who} просит доступ: {what}.": "{who} asks for access: {what}.",
+ "Зачем: {purpose}": "What for: {purpose}",
+ "Проект: {where}": "Project: {where}",
+ "Откройте запрос, чтобы подключить сервис или отказать.": "Open the request to connect the service or refuse.",
+ "Агент просит доступ": "An agent asks for access",
+ "Запрос не найден": "Request not found",
+ "По этому запросу уже есть решение": "This request has already been decided",
};
diff --git a/packages/shared/src/i18n/kk/access-hub.ts b/packages/shared/src/i18n/kk/access-hub.ts
index 147b3c06..ebc68fd0 100644
--- a/packages/shared/src/i18n/kk/access-hub.ts
+++ b/packages/shared/src/i18n/kk/access-hub.ts
@@ -163,4 +163,47 @@ export const accessHub: Record = {
"Журнал подключений: контрольные точки": "Қосылымдар журналы: бақылау нүктелері",
"Журнал подключений пользователя {login} изменён в обход FORGE (запись {id}). Проверьте доступ к базе.": "{login} пайдаланушысының қосылымдар журналы FORGE-ды айналып өтіп өзгертілді (жазба {id}). Дерекқорға қолжетімділікті тексеріңіз.",
"Журнал ваших подключений изменён в обход FORGE. Администратор уже знает и разбирается; ключи доступа лучше заменить в разделе «Подключения».": "Қосылымдарыңыздың журналы FORGE-ды айналып өтіп өзгертілді. Әкімші біледі және анықтап жатыр; қолжетімділік кілттерін «Қосылымдар» бөлімінде ауыстырған жөн.",
+ // PEP-250: agents ask for access themselves.
+ "Агенты просят доступ": "Агенттер қолжетімділік сұрайды",
+ "Запрос доступа — FORGE": "Қолжетімділік сұрауы — FORGE",
+ "Отказано. Агент получит вашу причину и продолжит без этого сервиса.": "Бас тартылды. Агент себебіңізді алып, бұл сервиссіз жалғастырады.",
+ "Но сервис не принял ключ: замените его в разделе «Подключения».": "Бірақ сервис кілтті қабылдамады: оны «Қосылымдар» бөлімінде ауыстырыңыз.",
+ "Сервис сейчас не отвечает — ключ проверится при первом запросе агента.": "Сервис қазір жауап бермейді — кілт агенттің алғашқы сұрауында тексеріледі.",
+ "Доступ выдан. Агент получил сообщение и продолжит работу; ключ доступа он не видит.": "Қолжетімділік берілді. Агент хабарлама алып, жұмысын жалғастырады; қолжетімділік кілтін ол көрмейді.",
+ "Он есть в описании сервиса для разработчиков или у того, кто его сделал.": "Ол сервистің әзірлеушілерге арналған сипаттамасында немесе оны жасаған адамда бар.",
+ "Подключить и разрешить": "Қосу және рұқсат беру",
+ "Выберите подключение": "Қосылымды таңдаңыз",
+ "Разрешить из уже подключённого": "Бұрыннан қосылғаннан рұқсат беру",
+ "Агент просит доступ к {service}": "Агент {service} сервисіне қолжетімділік сұрайды",
+ "Агенту нужен этот сервис для работы над задачей. Ключ доступа вы вводите один раз, агент его не увидит: запросы выполняет FORGE и записывает их в журнал. Можно и отказать — агент продолжит без сервиса.": "Агентке тапсырма бойынша жұмыс істеу үшін бұл сервис керек. Қолжетімділік кілтін бір рет енгізесіз, агент оны көрмейді: сұрауларды FORGE орындайды және журналға жазады. Бас тартуға да болады — агент сервиссіз жалғастырады.",
+ "По этому запросу уже есть решение.": "Бұл сұрау бойынша шешім бұрыннан бар.",
+ "агент просил ещё раз: {n}": "агент тағы сұрады: {n}",
+ "Сервис": "Сервис",
+ "Что можно": "Не рұқсат",
+ "Зачем": "Не үшін",
+ "Причина отказа": "Бас тарту себебі",
+ "без причины": "себепсіз",
+ "Агенты проекта смогут читать и менять данные в этом сервисе. Изменить или отозвать доступ можно в разделе «Подключения».": "Жоба агенттері бұл сервистегі деректерді оқып, өзгерте алады. Қолжетімділікті «Қосылымдар» бөлімінде өзгертуге немесе қайтарып алуға болады.",
+ "Агенты проекта смогут только читать данные в этом сервисе. Изменить или отозвать доступ можно в разделе «Подключения».": "Жоба агенттері бұл сервистегі деректерді тек оқи алады. Қолжетімділікті «Қосылымдар» бөлімінде өзгертуге немесе қайтарып алуға болады.",
+ "Или разрешить из уже подключённого": "Немесе бұрыннан қосылғаннан рұқсат беру",
+ "Причина — агент её получит, например «используйте тестовые данные»": "Себеп — агент оны алады, мысалы «сынақ деректерін пайдаланыңыз»",
+ "читать и менять": "оқу және өзгерту",
+ "только читать": "тек оқу",
+ "ждёт вашего решения": "шешіміңізді күтеді",
+ "доступ выдан": "қолжетімділік берілді",
+ "отказано": "бас тартылды",
+ "агент отменил запрос": "агент сұрауды болдырмады",
+ "Посмотреть и решить": "Қарау және шешу",
+ "Отказано. Агент узнает об этом.": "Бас тартылды. Агент бұл туралы біледі.",
+ "Укажите адрес сервиса в интернете": "Сервистің интернеттегі мекенжайын көрсетіңіз",
+ "{project}, задача {task}": "{project}, тапсырма {task}",
+ "{service} — читать и менять": "{service} — оқу және өзгерту",
+ "{service} — только читать": "{service} — тек оқу",
+ "{who} просит доступ: {what}.": "{who} қолжетімділік сұрайды: {what}.",
+ "Зачем: {purpose}": "Не үшін: {purpose}",
+ "Проект: {where}": "Жоба: {where}",
+ "Откройте запрос, чтобы подключить сервис или отказать.": "Сервисті қосу немесе бас тарту үшін сұрауды ашыңыз.",
+ "Агент просит доступ": "Агент қолжетімділік сұрайды",
+ "Запрос не найден": "Сұрау табылмады",
+ "По этому запросу уже есть решение": "Бұл сұрау бойынша шешім бұрыннан бар",
};
--
2.45.2
From d1162e3acf21d1f517c92a955d6efd52bacb5012 Mon Sep 17 00:00:00 2001
From: peppa-bot
Date: Tue, 24 Nov 2026 11:27:52 +0000
Subject: [PATCH 3/6] =?UTF-8?q?PEP-250:=20=D0=B0=D0=B2=D1=82=D0=BE=D0=B7?=
=?UTF-8?q?=D0=B0=D0=BF=D1=80=D0=BE=D1=81=20=D0=B8=D0=B7=20=D0=BE=D1=82?=
=?UTF-8?q?=D0=BA=D0=B0=D0=B7=D0=B0=20=D1=88=D0=BB=D1=8E=D0=B7=D0=B0=20?=
=?UTF-8?q?=D0=B1=D0=B5=D0=B7=20=D1=81=D0=BC=D0=B5=D0=BD=D1=8B=20=D1=84?=
=?UTF-8?q?=D0=BE=D1=80=D0=BC=D1=8B=20=D0=BE=D1=82=D0=B2=D0=B5=D1=82=D0=B0?=
=?UTF-8?q?,=20=D1=82=D0=B5=D1=81=D1=82=D1=8B=20=D1=81=D1=86=D0=B5=D0=BD?=
=?UTF-8?q?=D0=B0=D1=80=D0=B8=D0=B5=D0=B2,=20=D0=BF=D1=80=D0=B0=D0=B2?=
=?UTF-8?q?=D0=B8=D0=BB=D0=BE=20=D0=B0=D0=B3=D0=B5=D0=BD=D1=82=D0=B0=D0=BC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Opus 5.5
---
AGENTS.md | 1 +
packages/core/src/connections.ts | 34 ++-
packages/mcp/src/agent.ts | 6 +-
packages/testkit/test/access-requests.test.ts | 197 ++++++++++++++++++
template/RULES.md | 18 +-
5 files changed, 242 insertions(+), 14 deletions(-)
create mode 100644 packages/testkit/test/access-requests.test.ts
diff --git a/AGENTS.md b/AGENTS.md
index 7773e62e..1a0412fc 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -64,6 +64,7 @@
- **Фабрика не ставит себе задачи по кругу (PEP-197)**: `tasks.origin` (`human` | `acceptance` | `incident` | `analyst`; миграция 0023 проставила старым по признакам), `tasks.proposed` («Предложено»: `status` остаётся `backlog`, `readyBacklog`, диспетчер и «всё сделано» такие задачи не видят; `moveTask` снимает флаг — человек решил) и `tasks.severity` (`breakage` «Поломка» | `important` | `minor`). `core/task-origin.ts`: пределы (`project.agent-limits:` `{inWork: 3, perPass: 5}`, меняет суперадмин — `peppa project agent-limits`; диспетчер не берёт задачу агента, когда `agentTasksInWork` ≥ предела, задачу человека предел не держит), `approveProposal`/`rejectProposal` («Не надо» → архив + `product.rejected:`, агент приёмки больше не предлагает), `mayAutoAccept` (настройка автономности `acceptOwn`: `mine` | `mine_breakage` по умолчанию | `all`; автомерж, автозакрытие и хук «готово к ревью» учитывают — задача агента без разрешения ждёт «Принять» владельца), версия проекта (`product.version:` `{ids, doneAt}`: задачи человека открываются в `createTask` через `touchVersion`; проход приёмки без поломок при всех принятых → «Версия готова» в том же сообщении, `ProjectProduct.versionDone` → «Готово» на карточке; после финиша улучшения копятся в `product.digest:` и раз в неделю `productDigestTick` заводит их в «Предложено»; новая задача человека начинает новую версию), `agentTaskSummary` (люди / агенты / траты за 7 дней; суперадмину на Главной, CLI `peppa agent-tasks report`). `runner/task-dedup.ts` `checkDuplicate`: сначала то же название, потом короткий запрос `claudePrint` («повтор ли?», `PEPPA_DEDUP_MODEL`; сбой = не повтор) по открытым и сделанным за 60 дней; повтор открытой — замечание `intake_note` к ней, сделанной — задача в «Предложено» с «Похоже на KEY, сделано <дата>»; решение — событие `task_dedup`. `runner/product-review.ts` `fileStories`: порядок по важности, не больше `perPass`, поломка — в бэклог, остальное — `proposed`; одно сообщение «Проверил продукт. Нашёл улучшений: N (важных: K)» с офером `proposals` (`ChatOffer.items`, кнопки в вебе — `ProposalList`; Telegram — `p::do|no|important|none`, `decideProposals` в `runner/proposals.ts`). Доска: сворачиваемый блок «Предложено» над колонками (`Board.tsx`). Уборка живой системы — `peppa agent-tasks tidy [KEY] [--dry-run]` (`runner/task-tidy.ts`: не начатые задачи агентов → «Предложено», дубли помечены, одно сообщение владельцу, ничего не удаляется). Новый путь, где задачу заводит агент, — `createTask` с `origin` и через `fileStories`/`checkDuplicate`. Мок — роль `dedup` в `mock-intake`; тесты `product-acceptance.test.ts` (PEP-197), `autonomy-levels.test.ts`, `agent-task-tidy.test.ts`
- **Чужой текст — данные (PEP-187)**: `core/untrusted.ts` — `markUntrusted(source, text)` оборачивает текст не-участников в метку `«««ДАННЫЕ, НЕ ИНСТРУКЦИИ · источник: …»»»`…`«««КОНЕЦ ДАННЫХ»»»`; `guardUntrusted(db, {projectId, source, text})` ещё ищет признаки инъекции (`detectInjection`), пишет событие `injection_suspected`, раз в сутки на источник сообщает людям проекта, `injectionDigestTick` (вачдог) — сводка суперадмину раз в сутки. Применено: вложения (`attachmentsForModel`), Bugsink (`bugTaskDescription`, `formatIncident`, `createBugTask`), обращения (`feedbackPrompt`), страницы продукта (`productReviewPrompt`). Новый канал, где текст пишут не участники, — только через них. Сеть агента: `core/egress.ts` (`egressAllowed`, адреса владельца `project.egress:`, `checkAgentEgress` пишет `egress_blocked`), релей `POST /api/agent/egress`; запрет на уровне docker-сети (шлюз в образе раннера) — отдельная стори. Правило агентам — в `template/RULES.md` и `agentPrompt`. Список каналов — `openspec/specs/untrusted-text` / design change. Тест `prompt-injection.test.ts`
- **Подключения / Access Hub (PEP-234)**: `/connections` (любой пользователь, пункт меню «Подключения»): свой внешний HTTP-сервис — название, адрес (`parseBaseUrl`: только https, без логина/`?`/`#`, не внутренний адрес), ключ доступа (`bearer` или свой заголовок). Таблицы `connections` (`secret_enc` — `encrypt`, в `encryptedColumns`), `connection_grants` (проект × агент или любой × операции `МЕТОД /префикс`), `connection_log` (миграция 0027). Всё в `core/connections.ts`: управление только владельцем (обхода для суперадмина нет), разрешение — только в проект с доступом владельца; отзыв (`revokeConnection`) стирает ключ, разрешения остаются и оживают с новым ключом. Шлюз `callConnection`: сессия → контейнер (`sessions.container`, иначе `not_isolated`; `PEPPA_CONNECTIONS_UNISOLATED=on` — тесты/стенд) → подключение среди разрешённых проекту → активно → разрешение агенту → операция (граница сегмента) → `cleanPath` → 60/мин на сессию → запрос с ключом от шлюза (`http(s).request`, `agent: false`, `lookup` проверяет IP — `isBlockedAddress`, без перенаправлений, 15 с, ответ ≤256 КБ, ключ маскируется); журнал — путь без query, решение, причина (`CONNECTION_REASON_TEXT`). Внутренние адреса и http — только `PEPPA_CONNECTIONS_ALLOW_PRIVATE=1`. MCP агента `list_connections` / `call_connection` (ответ через `guardUntrusted`). Тест `access-hub.test.ts`
+- **Агент просит доступ (PEP-250)**: таблица `access_requests` (миграция 0031), всё в `core/access-requests.ts`: `requestAccess` (сессия → проект; `service` — карточка каталога по id/названию, иначе `host` → `publicOrigin`: `parseBaseUrl` + DNS, закрытый адрес — отказ, нерезолвящееся имя пропускается; адрес карточки каталога = карточка; доступ уже есть — отказ с подсказкой `call_connection`; один `open` на `project × service_key`, повтор — `repeats`, запись расширяет режим, второго сообщения нет; цель — `guardUntrusted`), `announceAccessRequest` (мастер-чат + `deliverToUser` `questions` с `projectId`: пауза и ночная тишина сами; кнопки — ссылка `/connections/requests/` и `ar::no`), решения только владельца проекта (`accessRequestForUser`, иначе null/404): `connectAndGrantAccess` (ключ один раз по карточке или адресу), `grantAccessFromExisting`, `denyAccessRequest`; разрешение — проекту, любой агент, чтение «сразу», запись — если просили, прежнее разрешение только расширяется. Агенту — `runner/access-requests.ts` (`tellAgentAboutAccess`: живой — `sendToSession`, нет и задача proposing/in_progress/blocked — `moveTask(in_progress, { prompt })`, пауза — никому). MCP агента `request_access`/`list_requests`/`cancel_request`, отказ `call_connection` (`no_grant|read_denied|write_denied|operation_denied`, `unknown_connection` с id каталога) сам заводит запрос (`refusedCallService`); `declare_needs` пункт `use: agent` → запрос. Веб: блок «Агенты просят доступ» в `/connections`, карточка `/connections/requests/[id]` (`components/AccessRequests.tsx`). Тест `access-requests.test.ts`
- **Пауза проекта (PEP-174)**: `core/project-pause.ts` — `settings` `project.paused:` `{since, by, sessions}` (без миграции), `isProjectPaused`/`assertProjectActive`/`pausedProjectIds`, окно последней паузы `project.pause.last:` и `duringPause` (что появилось во время паузы, не рассылается потом). `runner/pause.ts`: `pauseProject` (сначала отметка, потом `stopSession` живых агентов, событие `project_paused`), `resumeProject` (событие `project_resumed` «Пауза: с … по …», `activateRunnerTask` + `resumeSession` остановленных паузой). Узкие места: запуск агента — `startSession`/`startRunner`/`resumeSession`/`relaunchFresh`/`moveTask → in_progress` (отказ `PROJECT_PAUSED_TEXT`), ИИ-роли — `claudePrint`, уведомления — `deliverToUser`, `notifyPm`, `mirrorTargets`, бот `reconcile`; тики пропускают проект без потери состояния (автономность, перезапуски, напоминания, intake, уточнение, чат с аналитиком, приёмка продукта, ссылка на продукт, перезапуск из-за секретов, ревьюер, «готово к ревью», отложенное «Принять», ошибки из прода — `open` без сообщения), вебхуки (красные проверки, комментарии Gitea) записываются без запуска агента; живой агент проекта на паузе вачдог останавливает сам и дописывает в `sessions`. Веб: `components/ProjectPause.tsx` (кнопка с подтверждением, плашка, метка «На паузе»), «⋯ Настройки проекта → Пауза», «Ждут вашего ответа»/счётчики/дайджест без проектов на паузе. CLI `peppa project pause|resume `. Новое место, которое запускает агента, зовёт модель или пишет человеку по проекту, — через эти узкие места или с `isProjectPaused`. Тест `project-pause.test.ts`
- **Прогресс на Главной (PEP-77)**: `progressOverview` (core/progress.ts: стори по колонкам доски без архивных, стори в работе с агентом и прогрессом tasks.md, ждущие «Принять»; итог — только свои проекты, суперадмину отдельно `others`), раздел «Прогресс» — `components/ProgressOverview.tsx`
- **«Принять» при конфликте (PEP-127)**: PR стори конфликтует с основной веткой → `acceptTask`/`acceptStory` (runner/flow.ts `deferAccept`) не падают, а запоминают решение — `settings` `accept.pending:` (`core/accept-pending.ts`: `{at, via, rebases}`), вопрос «готово к ревью» закрывается ответом `PENDING_ACCEPT_ANSWER`, агент получает `requestRebase` (flow.ts; общий с автомержем), результат `pending: true` (бот/MCP/веб отвечают «принято, закроется само»). `pendingAcceptTick` (runner/accept-pending.ts, тик вачдога перед `autonomyTick`): стори в `review` и гейт зелёный → мерж, `done`, событие `accept_completed`, сообщение PM; снова конфликт → ещё rebase (до `ACCEPT_MAX_REBASES` = 3); провал (3 конфликта, PR закрыт, `PEPPA_ACCEPT_WAIT_HOURS` = 24) → состояние стирается, одно `attention` PM; стори ушла в бэклог/архив — стирается молча. Пока ждёт: Stop-хук не шлёт «готово к ревью» (`awaiting_accept_merge`), ревьюер и автомерж стори не трогают. Веб: плашка `PENDING_ACCEPT_LABEL` на странице стори и карточке доски, кнопка «Принять» на вкладке результата активна при конфликте. Красные/идущие проверки по-прежнему отказ с причиной. Тест `accept-pending.test.ts`
diff --git a/packages/core/src/connections.ts b/packages/core/src/connections.ts
index 3d9fb2c6..51d13f20 100644
--- a/packages/core/src/connections.ts
+++ b/packages/core/src/connections.ts
@@ -647,7 +647,7 @@ export interface ConnectionCall {
export type ConnectionResult =
| { ok: true; status: number; contentType: string | null; body: string; truncated: boolean }
- | { ok: false; reason: ConnectionReason; status?: number; service?: { catalogId: string | null; baseUrl: string }; kind?: "read" | "write" };
+ | { ok: false; reason: ConnectionReason; status?: number };
/** One outbound request, injectable in tests. */
export type ConnectionFetch = (o: { url: URL; method: string; headers: Record; body: Buffer | null }) => Promise<{ status: number; contentType: string | null; body: Buffer; truncated: boolean; location?: boolean }>;
@@ -705,6 +705,29 @@ export const defaultConnectionFetch: ConnectionFetch = ({ url, method, headers,
const CONTENT_TYPE_RE = /^[a-z]+\/[a-z0-9.+-]+(;\s*charset=[a-z0-9-]+)?$/i;
+/** A connection named by the agent among those granted to its project: id, then name, then short name. */
+function matchGranted(granted: T[], connection: string | number): T[] {
+ const want = String(connection).trim();
+ const byId = /^\d+$/.test(want) ? granted.filter((g) => g.c.id === Number(want)) : [];
+ const byName = granted.filter((g) => g.c.name === want);
+ return byId.length ? byId : byName.length ? byName : granted.filter((g) => connectionSlug(g.c) === want.toLowerCase());
+}
+
+/**
+ * PEP-250: the service behind a refused call — a connection granted to the session's project —
+ * and whether the request reads or writes. Null when the name matches nothing (or several).
+ */
+export async function refusedCallService(db: Db, sessionId: number, connection: string | number, method: string, path: string): Promise<{ catalogId: string | null; baseUrl: string; kind: "read" | "write" } | null> {
+ const s = await sessionCtx(db, sessionId);
+ if (!s) return null;
+ const granted = await db.select({ c: connections }).from(connectionGrants).innerJoin(connections, eq(connections.id, connectionGrants.connectionId)).where(eq(connectionGrants.projectId, s.projectId));
+ const ids = new Set(matchGranted(granted, connection).map((g) => g.c.id));
+ if (ids.size !== 1) return null;
+ const c = granted.find((g) => ids.has(g.c.id))!.c;
+ const clean = cleanPath(String(path ?? ""));
+ return { catalogId: c.catalogId, baseUrl: c.baseUrl, kind: clean ? classifyRequest(c.catalogId, String(method).toUpperCase(), clean.path) : String(method).toUpperCase() === "GET" ? "read" : "write" };
+}
+
/**
* The gateway: decides, injects the key, calls the service, masks the key in the answer and
* writes one journal row (method, path without query, decision, reason — never a key or a body).
@@ -741,9 +764,7 @@ export async function callConnection(db: Db, call: ConnectionCall, o: { fetch?:
};
const deny = async (reason: ConnectionReason): Promise => {
await record("denied", reason, null);
- // PEP-250: which service and what kind of request — a missing grant becomes an access request.
- const clean = cleanPath(rawPath);
- return { ok: false, reason, ...(conn ? { service: { catalogId: conn.catalogId, baseUrl: conn.baseUrl } } : {}), ...(clean && conn ? { kind: classifyRequest(conn.catalogId, method, clean.path) } : {}) };
+ return { ok: false, reason };
};
if (!s) return { ok: false, reason: "no_session" };
@@ -754,10 +775,7 @@ export async function callConnection(db: Db, call: ConnectionCall, o: { fetch?:
.from(connectionGrants)
.innerJoin(connections, eq(connections.id, connectionGrants.connectionId))
.where(eq(connectionGrants.projectId, s.projectId));
- const want = String(call.connection).trim();
- const byId = /^\d+$/.test(want) ? granted.filter((g) => g.c.id === Number(want)) : [];
- const byName = granted.filter((g) => g.c.name === want);
- const matches = byId.length ? byId : byName.length ? byName : granted.filter((g) => connectionSlug(g.c) === want.toLowerCase());
+ const matches = matchGranted(granted, call.connection);
const ids = new Set(matches.map((g) => g.c.id));
if (ids.size > 1) return { ok: false, reason: "ambiguous_connection" };
if (!ids.size) return { ok: false, reason: "unknown_connection" };
diff --git a/packages/mcp/src/agent.ts b/packages/mcp/src/agent.ts
index 955aedd8..c84d3504 100644
--- a/packages/mcp/src/agent.ts
+++ b/packages/mcp/src/agent.ts
@@ -53,6 +53,7 @@ import {
callConnection,
cancelAccessRequest,
catalogFromSecretName,
+ refusedCallService,
requestAccess,
sessionAccessRequests,
type AccessRequestView,
@@ -463,10 +464,11 @@ export function createAgentServer(db: Db, opts: AgentServerOptions = {}): McpSer
const AUTO_REASONS = new Set(["no_grant", "read_denied", "write_denied", "operation_denied"]);
async function autoRequest(r: Extract>, { ok: false }>, connection: string, method: string, path: string): Promise {
if (!sessionId) return null;
- const service = AUTO_REASONS.has(r.reason) && r.service ? r.service : r.reason === "unknown_connection" ? { catalogId: connection.trim().toLowerCase(), baseUrl: "" } : null;
+ const found = AUTO_REASONS.has(r.reason) ? await refusedCallService(db, sessionId, connection, method, path) : null;
+ const service = found ?? (r.reason === "unknown_connection" ? { catalogId: connection.trim().toLowerCase(), baseUrl: "", kind: method.toUpperCase() === "GET" ? ("read" as const) : ("write" as const) } : null);
if (!service) return null;
const purpose = `Агент обратился: ${method.toUpperCase()} ${String(path).split("?")[0]!.slice(0, 120)}`;
- const mode = (r.kind ?? (method.toUpperCase() === "GET" ? "read" : "write")) as "read" | "write";
+ const mode = service.kind;
const got = service.catalogId
? await requestAccess(db, { sessionId, service: service.catalogId, host: service.baseUrl || null, purpose, mode }, { auto: true }).catch(() => null)
: await requestAccess(db, { sessionId, host: service.baseUrl, purpose, mode }, { auto: true }).catch(() => null);
diff --git a/packages/testkit/test/access-requests.test.ts b/packages/testkit/test/access-requests.test.ts
new file mode 100644
index 00000000..4df49e73
--- /dev/null
+++ b/packages/testkit/test/access-requests.test.ts
@@ -0,0 +1,197 @@
+// PEP-250 Access Hub: an agent asks the owner for access itself; the owner connects the key once
+// or refuses; the decision reaches the agent. Scenario names follow
+// openspec/changes/pep-250-access-requests/specs/access-hub/spec.md.
+import assert from "node:assert/strict";
+import { after, before, describe, test } from "node:test";
+import { Client } from "@modelcontextprotocol/sdk/client/index.js";
+import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
+import { and, eq, like } from "drizzle-orm";
+import { stripAsIs } from "@peppa/shared/i18n";
+import { core, db, project, runner, teardown, type TestProject } from "./helpers.ts";
+
+process.env.PEPPA_SECRET ??= "mock-access-requests-secret";
+process.env.PEPPA_CONNECTIONS_UNISOLATED = "on"; // mock agents run without a container
+process.env.PEPPA_WEB_URL = "https://forge.mock.test";
+const { createAgentServer } = await import("@peppa/mcp/agent");
+const { accessRequests, chatMessages, sessions, tasks, telegramOutbox, users } = await import("@peppa/db");
+
+let anna: Awaited>;
+let boris: Awaited>;
+const ANNA_CHAT = 2_500_001;
+
+before(async () => {
+ anna = await core.upsertUserFromGitea(db, { id: 2501, login: "mock-anna-250" }, { access_token: "a" });
+ boris = await core.upsertUserFromGitea(db, { id: 2502, login: "mock-boris-250" }, { access_token: "b" });
+ await db.update(users).set({ telegramChatId: ANNA_CHAT, telegramUserId: ANNA_CHAT }).where(eq(users.id, anna.id));
+});
+after(teardown);
+
+/** A project of anna with a live mock agent on its story. */
+async function story(turns: number): Promise<{ tp: TestProject; proj: Awaited>; sessionId: number; taskId: number }> {
+ const tp = await project({ turns: Array.from({ length: turns }, () => [{ say: "Работаю." }]) });
+ const proj = await core.getProject(db, tp.key);
+ await core.setProjectOwner(db, proj.id, anna.id);
+ const sessionId = await tp.start();
+ await tp.waitLog("turn 0", (e) => e.ev === "prompt");
+ const taskId = (await tp.task()).id;
+ await db.update(tasks).set({ status: "in_progress" }).where(eq(tasks.id, taskId));
+ return { tp, proj, sessionId, taskId };
+}
+
+async function mcpAgent(sessionId: number, key: string) {
+ const [a, b] = InMemoryTransport.createLinkedPair();
+ await createAgentServer(db, { defaultKey: key, sessionId, lockProject: true }).connect(a);
+ const client = new Client({ name: "mock-agent", version: "0" });
+ await client.connect(b);
+ return async (name: string, args: Record = {}) => {
+ const r = await client.callTool({ name, arguments: args });
+ return { text: (r.content as Array<{ text: string }>)[0]!.text, isError: !!r.isError };
+ };
+}
+
+/** anna's Telegram messages about access requests. */
+const annaHeard = async (id: number) => db.select().from(telegramOutbox).where(and(like(telegramOutbox.dedupeKey, `access-request:${id}:%`)));
+const stopAll = async (projectId: number) => {
+ for (const s of await core.listSessions(db, { active: true, projectId })) await runner.stopSession(db, s.id);
+};
+const said = (tp: TestProject, text: string) => tp.log().some((e) => JSON.stringify(e).includes(text));
+
+describe("Агент запрашивает доступ к сервису", () => {
+ let s: Awaited>;
+ let call: Awaited>;
+ let requestId: number;
+ before(async () => {
+ s = await story(4);
+ call = await mcpAgent(s.sessionId, s.proj.key);
+ });
+ after(async () => stopAll(s.proj.id));
+
+ test("Запрос доходит до владельца", async () => {
+ const r = await call("request_access", { service: "stripe", purpose: "проверить оплату заказа", mode: "read" });
+ assert.equal(r.isError, false, r.text);
+ assert.match(r.text, /Requested: #\d+ Stripe \(read\)/);
+ requestId = Number(r.text.match(/#(\d+)/)![1]);
+
+ const open = await core.ownerAccessRequests(db, anna.id);
+ const mine = open.find((x) => x.id === requestId)!;
+ assert.ok(mine, "anna sees it in «Агенты просят доступ»");
+ assert.equal(mine.service, "Stripe");
+ assert.equal(mine.taskKey, s.tp.taskKey);
+ assert.equal(mine.purpose, "проверить оплату заказа");
+ assert.equal(mine.mode, "read");
+
+ const tg = await annaHeard(requestId);
+ assert.equal(tg.length, 1, "one Telegram message");
+ const text = stripAsIs(String(tg[0]!.params.text));
+ assert.match(text, /просит доступ: Stripe — только читать/);
+ assert.match(text, /Зачем: проверить оплату заказа/);
+ const markup = JSON.stringify(tg[0]!.params.reply_markup);
+ assert.ok(markup.includes(`ar:${requestId}:no`), "a «Отказать» button");
+ assert.ok(markup.includes(`https://forge.mock.test/connections/requests/${requestId}`), "a link to the card");
+ const [master] = await db.select().from(chatMessages).where(eq(chatMessages.dedupeKey, `master:access-request:${requestId}`));
+ assert.equal(master?.url, `/connections/requests/${requestId}`, "the master chat has it with the link");
+ });
+
+ test("Повтор не создаёт второй запрос", async () => {
+ const r = await call("request_access", { service: "Stripe", purpose: "создать возврат", mode: "write" });
+ assert.match(r.text, /already exists \(#\d+\)/);
+ const rows = await db.select().from(accessRequests).where(and(eq(accessRequests.projectId, s.proj.id), eq(accessRequests.serviceKey, "stripe")));
+ assert.equal(rows.length, 1);
+ assert.equal(rows[0]!.repeats, 1);
+ assert.equal(rows[0]!.mode, "write", "write widens the request");
+ assert.equal((await annaHeard(requestId)).length, 1, "no second message");
+ const list = await call("list_requests");
+ assert.match(list.text, /Stripe \(write\) — open/);
+ });
+
+ test("Чужой не видит запрос", async () => {
+ assert.equal(await core.accessRequestForUser(db, boris.id, requestId), null);
+ await assert.rejects(runner.denyAccessRequestAndTell(db, boris.id, requestId, "нет"), /Запрос не найден/);
+ await assert.rejects(core.connectAndGrantAccess(db, boris.id, requestId, { secret: "sk_test_mock_boris_123456" }), /Запрос не найден/);
+ assert.equal((await core.ownerAccessRequests(db, boris.id)).length, 0);
+ assert.equal((await core.getAccessRequest(db, requestId))!.status, "open");
+ });
+
+ test("Подключить и разрешить", async () => {
+ const out = await runner.connectAndGrantAccessRequest(db, anna.id, requestId, { secret: "sk_test_mock_STRIPE_250_123456" });
+ assert.equal(out.request.status, "granted");
+ assert.equal(out.connection.catalogId, "stripe");
+ const grant = out.connection.grants.length ? out.connection.grants : (await core.listConnections(db, anna.id)).find((c) => c.id === out.connection.id)!.grants;
+ assert.equal(grant[0]!.projectId, s.proj.id);
+ assert.equal(grant[0]!.readMode, "auto");
+ assert.equal(grant[0]!.writeMode, "auto", "the request asked to write");
+ await s.tp.waitLog("the live agent is told", (e) => JSON.stringify(e).includes("Доступ выдан"));
+ const conns = await core.agentConnections(db, s.sessionId);
+ assert.ok(conns.some((c) => c.catalogId === "stripe" && c.readMode === "auto"), "the agent now has it");
+ // Asking again for what it has: refused with a hint to call it.
+ const again = await call("request_access", { service: "stripe", purpose: "ещё раз" });
+ assert.equal(again.isError, true);
+ assert.match(again.text, /already have this access: call_connection\("stripe"/);
+ });
+
+ test("Вызов без разрешения", async () => {
+ const crm = await core.createConnection(db, anna.id, { name: "CRM 250", baseUrl: "https://crm250.example.com/api", secret: "sk_test_mock_CRM_250_123456" });
+ await core.grantConnection(db, anna.id, crm.id, { projectId: s.proj.id, readMode: "auto", writeMode: "off" });
+ const r = await call("call_connection", { connection: crm.slug, method: "POST", path: "/orders", body: "{}" });
+ assert.equal(r.isError, true);
+ assert.match(r.text, /write_denied/);
+ assert.match(r.text, /Access requested from the owner \(request #\d+\)/);
+ const [req] = await db.select().from(accessRequests).where(and(eq(accessRequests.projectId, s.proj.id), eq(accessRequests.serviceKey, "https://crm250.example.com"), eq(accessRequests.status, "open")));
+ assert.ok(req, "the refusal became a request");
+ assert.equal(req.mode, "write");
+ assert.match(req.purpose, /POST \/orders/);
+ // The owner allows it from the existing connection: write widens the grant, read stays.
+ await runner.grantAccessRequestFromExisting(db, anna.id, req.id, crm.id);
+ const g = (await core.listConnections(db, anna.id)).find((c) => c.id === crm.id)!.grants.find((x) => x.projectId === s.proj.id)!;
+ assert.equal(g.readMode, "auto");
+ assert.equal(g.writeMode, "auto");
+ });
+
+ test("Ключ внешнего сервиса для агента — запрос доступа, а не секрет проекта", async () => {
+ const r = await call("declare_needs", { needs: [{ title: "Ключ SendGrid", why: "отправить тестовое письмо", secret: "SENDGRID_API_KEY", use: "agent" }] });
+ assert.equal(r.isError, false, r.text);
+ assert.match(r.text, /access request #\d+ \(SendGrid\) sent to the owner/);
+ assert.equal((await core.productNeeds(db, s.proj.id)).length, 0, "nothing in the product's list");
+ });
+});
+
+describe("Отказ и адреса", () => {
+ test("Отказ с причиной: остановленный агент получает её с новым запуском", async () => {
+ const s = await story(3);
+ const { request } = await core.requestAccess(db, { sessionId: s.sessionId, service: "github", purpose: "прочитать задачи репозитория" });
+ await stopAll(s.proj.id);
+ await db.update(sessions).set({ status: "done" }).where(eq(sessions.id, s.sessionId));
+ const r = await runner.denyAccessRequestAndTell(db, anna.id, request.id, "используйте тестовые данные");
+ assert.equal(r.status, "denied");
+ assert.equal(r.reason, "используйте тестовые данные");
+ await s.tp.waitLog("a new agent got the reason", (e) => JSON.stringify(e).includes("используйте тестовые данные"));
+ assert.ok(said(s.tp, "отказал в доступе к GitHub"));
+ assert.equal((await s.tp.task()).status, "in_progress");
+ await assert.rejects(runner.denyAccessRequestAndTell(db, anna.id, request.id, "ещё раз"), /уже есть решение/);
+ await stopAll(s.proj.id);
+ });
+
+ test("Адрес внутрь отклоняется", async () => {
+ const was = process.env.PEPPA_CONNECTIONS_ALLOW_PRIVATE;
+ delete process.env.PEPPA_CONNECTIONS_ALLOW_PRIVATE;
+ try {
+ const tp = await project({ turns: [] });
+ const proj = await core.getProject(db, tp.key);
+ await core.setProjectOwner(db, proj.id, anna.id);
+ const sess = await core.createSession(db, { projectId: proj.id, taskId: (await tp.task()).id });
+ for (const host of ["https://127.0.0.1/admin", "localhost", "http://10.0.0.5", "https://[::1]/", "https://intranet.local", "https://user:pw@api.example.com"]) {
+ await assert.rejects(core.requestAccess(db, { sessionId: sess.id, host, purpose: "x y z" }), (e: Error) => /адрес|Адрес/.test(e.message), host);
+ }
+ // A name that resolves inside is refused like the gateway refuses it.
+ await assert.rejects(core.requestAccess(db, { sessionId: sess.id, host: "https://sneaky.example.com", purpose: "x y z" }, { lookup: async () => ["192.168.1.10"] }), /недоступен/);
+ const ok = await core.requestAccess(db, { sessionId: sess.id, host: "api.example.com/v1/items?x=1", purpose: "x y z" }, { lookup: async () => ["93.184.216.34"] });
+ assert.equal(ok.request.host, "https://api.example.com", "only the origin is kept");
+ assert.equal((await db.select().from(accessRequests).where(eq(accessRequests.projectId, proj.id))).length, 1, "nothing stored for the refused ones");
+ // An address of a catalog service becomes its card.
+ const card = await core.requestAccess(db, { sessionId: sess.id, host: "https://api.stripe.com", purpose: "x y z" }, { lookup: async () => ["93.184.216.35"] });
+ assert.equal(card.request.catalogId, "stripe");
+ } finally {
+ if (was !== undefined) process.env.PEPPA_CONNECTIONS_ALLOW_PRIVATE = was;
+ }
+ });
+});
diff --git a/template/RULES.md b/template/RULES.md
index 9c8fd7da..65e3709e 100644
--- a/template/RULES.md
+++ b/template/RULES.md
@@ -160,9 +160,18 @@ git, тесты, раннеры — решаешь ты сам и пишешь,
- Ключи API и доступы для твоей работы (тестовые ключи, токены внешних сервисов) лежат в
секретах проекта FORGE: `peppa.list_secrets` — их имена, значения уже в твоём окружении
(`$NAME`). Не печатай, не логируй и не коммить значения; в код и конфиги — только чтение
- из env. Нужного секрета нет — `declare_needs` (ключ для продукта) или `ask_pm` (доступ
- только для твоей работы), PM заведёт его в «⋯ Настройки проекта → Секреты» (появится при
- следующем запуске сессии).
+ из env. Нужного секрета нет и ключ нужен выкаченному продукту — `declare_needs`, PM заведёт
+ его в «⋯ Настройки проекта → Секреты» (появится при следующем запуске сессии).
+- **Внешний сервис для твоей работы — через Access Hub, не через секреты.** Ключи внешних
+ сервисов (Stripe, GitHub, почта…) в секреты проекта не проси. `peppa.list_connections` —
+ что уже разрешено, вызов — `call_connection` (ключ подставит FORGE, ты его не видишь).
+ Нет доступа — `peppa.request_access(service: "stripe" | host: "https://…", purpose: "зачем,
+ простыми словами", mode: read|write)`: владелец получит ссылку, подключит ключ один раз или
+ откажет с причиной; решение придёт тебе сообщением, остановленная задача вернётся в работу.
+ Не жди: продолжай на моке. Один открытый запрос на сервис — повтор прибавится к нему;
+ `list_requests` — состояние, `cancel_request` — если доступ больше не нужен. Отказ шлюза
+ из-за отсутствия разрешения сам становится запросом. В `declare_needs` такой пункт помечай
+ `use: "agent"`.
## Песочница раннера
@@ -252,7 +261,8 @@ FORGE живёт на той же машине. Контейнер, которы
ход**: продолжай по `default` и запиши его в `design.md`. Ответ придёт позже
сообщением — если он другой, переделаешь.
- Нужен ключ или аккаунт, которого нет, — делай на моке (раздел ниже) и объяви его через
- `peppa.declare_needs`: владелец получит список «что дать и куда вставить».
+ `peppa.declare_needs` (нужен продукту) или `peppa.request_access` (нужен тебе для работы):
+ владелец получит список «что дать и куда вставить» или ссылку на запрос доступа.
## Сообщения PM: четыре типа
--
2.45.2
From 89b7fa4f177ce72dab7d7ac09ecafb13c2ce0643 Mon Sep 17 00:00:00 2001
From: peppa-bot
Date: Tue, 24 Nov 2026 11:28:11 +0000
Subject: [PATCH 4/6] =?UTF-8?q?PEP-250:=20=D0=B0=D1=80=D1=85=D0=B8=D0=B2?=
=?UTF-8?q?=20=D0=B8=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5=D0=BD=D0=B8=D1=8F,=20?=
=?UTF-8?q?=D1=82=D1=80=D0=B5=D0=B1=D0=BE=D0=B2=D0=B0=D0=BD=D0=B8=D1=8F=20?=
=?UTF-8?q?=D0=B2=20openspec/specs/access-hub;=20=D0=BF=D0=B0=D0=BC=D1=8F?=
=?UTF-8?q?=D1=82=D1=8C=20=D0=BF=D1=80=D0=BE=D0=B5=D0=BA=D1=82=D0=B0?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Opus 5.5
---
.peppa/memory.md | 2 +-
.../design.md | 0
.../proposal.md | 0
.../specs/access-hub/spec.md | 0
.../tasks.md | 18 +++++++
.../changes/pep-250-access-requests/tasks.md | 18 -------
openspec/specs/access-hub/spec.md | 50 +++++++++++++++++++
7 files changed, 69 insertions(+), 19 deletions(-)
rename openspec/changes/{pep-250-access-requests => archive/2026-11-24-pep-250-access-requests}/design.md (100%)
rename openspec/changes/{pep-250-access-requests => archive/2026-11-24-pep-250-access-requests}/proposal.md (100%)
rename openspec/changes/{pep-250-access-requests => archive/2026-11-24-pep-250-access-requests}/specs/access-hub/spec.md (100%)
create mode 100644 openspec/changes/archive/2026-11-24-pep-250-access-requests/tasks.md
delete mode 100644 openspec/changes/pep-250-access-requests/tasks.md
diff --git a/.peppa/memory.md b/.peppa/memory.md
index c88da5fe..f6139ffb 100644
--- a/.peppa/memory.md
+++ b/.peppa/memory.md
@@ -49,12 +49,12 @@
- Вопрос ≠ задача (PEP-153): текст человека, который может стать задачей, — через `classifyMessage` (runner/message-intent.ts; в тестах mock-intake роль `intent`); молча задачу не заводить — кнопки (`chat.offer:`, `INTENT_TEXT`).
- Задачу агента заводи через createTask с origin (acceptance|incident|analyst) и fileStories/checkDuplicate (PEP-197); «Предложено» = backlog + tasks.proposed, readyBacklog их не отдаёт; автомерж задач агента — по autonomy.acceptOwn (mayAutoAcceptTask).
- Неудачная версия (PEP-158): `rolled_back`/`failed` → агенту задачи, `returnFailedRelease` (runner/deploy-feedback.ts); счётчик — `attempts` задержки `deploy` (3 — суперадмину, 6 — стоп).
-- Bugsink API (PEP-218): схема — `GET /api/canonical/0/schema/`; экран — `core/bugsink-errors.ts`, действия — `runner/bugsink-errors.ts`.
- Bugsink API (PEP-218): схема — `GET /api/canonical/0/schema/` (2.6.3); `q` = текст + теги `key:value`; числа пользователей нет. Экран — `core/bugsink-errors.ts` (кэш 45 с), действия — `runner/bugsink-errors.ts`.
- Access Hub (PEP-249): новый сервис — карточка в `core/connection-catalog.ts` (тест access-hub-catalog сверяет каждую); сервис, который меняет данные через GET (Slack, Telegram), — чтение перечислять по методам.
- act_runner (PEP-233): идут контейнеры `GITEA-ACTIONS-TASK-*` — не рестартовать; голова без ci.yml или >2 суток — `orphan`, не очередь.
## Решения
+- Access Hub (PEP-250): агенту внешний сервис — только `request_access` (core/access-requests.ts), не секрет проекта; форму отказа `callConnection` не расширять (тесты сверяют deepEqual) — нужное для автозапроса ищи отдельно (`refusedCallService`).
- Access Hub (PEP-254): журнал — только `appendJournal` (core/connection-journal.ts, цепочка хэшей; правка строки задним числом = нарушение), ключ подключения — `sealConnectionSecret`/`openConnectionSecret`, не `encrypt`/`decrypt`.
- История (PEP-221): журнал/статусы — `history.db` (core/history.ts), логи — `archive/<вид>/<день>.jsonl.gz`; из основной базы события удаляет только `runRetention` после переноса.
- Docker (PEP-222): раннеры по умолчанию `container` (тесты — `PEPPA_DEFAULT_ISOLATION=none`).
diff --git a/openspec/changes/pep-250-access-requests/design.md b/openspec/changes/archive/2026-11-24-pep-250-access-requests/design.md
similarity index 100%
rename from openspec/changes/pep-250-access-requests/design.md
rename to openspec/changes/archive/2026-11-24-pep-250-access-requests/design.md
diff --git a/openspec/changes/pep-250-access-requests/proposal.md b/openspec/changes/archive/2026-11-24-pep-250-access-requests/proposal.md
similarity index 100%
rename from openspec/changes/pep-250-access-requests/proposal.md
rename to openspec/changes/archive/2026-11-24-pep-250-access-requests/proposal.md
diff --git a/openspec/changes/pep-250-access-requests/specs/access-hub/spec.md b/openspec/changes/archive/2026-11-24-pep-250-access-requests/specs/access-hub/spec.md
similarity index 100%
rename from openspec/changes/pep-250-access-requests/specs/access-hub/spec.md
rename to openspec/changes/archive/2026-11-24-pep-250-access-requests/specs/access-hub/spec.md
diff --git a/openspec/changes/archive/2026-11-24-pep-250-access-requests/tasks.md b/openspec/changes/archive/2026-11-24-pep-250-access-requests/tasks.md
new file mode 100644
index 00000000..465b13d1
--- /dev/null
+++ b/openspec/changes/archive/2026-11-24-pep-250-access-requests/tasks.md
@@ -0,0 +1,18 @@
+## 1. Данные и ядро
+- [x] 1.1 Таблица `access_requests` + миграция 0031
+- [x] 1.2 `core/access-requests.ts`: запрос, повтор, проверка адреса, список, отмена, вид для владельца, выдача и отказ
+- [x] 1.3 Сообщение владельцу: мастер-чат, Telegram с кнопками, push
+
+## 2. Агент и решения
+- [x] 2.1 `runner/access-requests.ts`: решение доходит до агента (живой / остановленный)
+- [x] 2.2 MCP: `request_access`, `list_requests`, `cancel_request`; автозапрос из `call_connection`; `declare_needs use: agent`
+- [x] 2.3 Бот: кнопка `ar::no`
+
+## 3. Экран
+- [x] 3.1 «Подключения»: блок «Агенты просят доступ»; карточка запроса с тремя действиями
+- [x] 3.2 Переводы ru/kk/en, словарь
+
+## 4. Правила, тесты, завершение
+- [x] 4.1 `template/RULES.md`: `request_access` вместо ключей в секретах
+- [x] 4.2 Тест `access-requests.test.ts`: запрос, выдача, отказ, повтор, чужой, адрес внутрь
+- [x] 4.3 Память, архив, PR
diff --git a/openspec/changes/pep-250-access-requests/tasks.md b/openspec/changes/pep-250-access-requests/tasks.md
deleted file mode 100644
index 4b602cb8..00000000
--- a/openspec/changes/pep-250-access-requests/tasks.md
+++ /dev/null
@@ -1,18 +0,0 @@
-## 1. Данные и ядро
-- [ ] 1.1 Таблица `access_requests` + миграция 0031
-- [ ] 1.2 `core/access-requests.ts`: запрос, повтор, проверка адреса, список, отмена, вид для владельца, выдача и отказ
-- [ ] 1.3 Сообщение владельцу: мастер-чат, Telegram с кнопками, push
-
-## 2. Агент и решения
-- [ ] 2.1 `runner/access-requests.ts`: решение доходит до агента (живой / остановленный)
-- [ ] 2.2 MCP: `request_access`, `list_requests`, `cancel_request`; автозапрос из `call_connection`; `declare_needs use: agent`
-- [ ] 2.3 Бот: кнопка `ar::no`
-
-## 3. Экран
-- [ ] 3.1 «Подключения»: блок «Агенты просят доступ»; карточка запроса с тремя действиями
-- [ ] 3.2 Переводы ru/kk/en, словарь
-
-## 4. Правила, тесты, завершение
-- [ ] 4.1 `template/RULES.md`: `request_access` вместо ключей в секретах
-- [ ] 4.2 Тест `access-requests.test.ts`: запрос, выдача, отказ, повтор, чужой, адрес внутрь
-- [ ] 4.3 Память, архив, PR
diff --git a/openspec/specs/access-hub/spec.md b/openspec/specs/access-hub/spec.md
index 7fd6e07b..2e144a36 100644
--- a/openspec/specs/access-hub/spec.md
+++ b/openspec/specs/access-hub/spec.md
@@ -229,3 +229,53 @@ SHALL отправить владельцу одно сообщение.
- **WHEN** выполняется перевод ключей
- **THEN** у «CRM» появляется свой ключ данных
- **AND** вызов через «CRM» работает с прежним ключом доступа
+
+### Requirement: Агент запрашивает доступ к сервису
+Агент SHALL запрашивать доступ к сервису каталога или адресу в интернете с целью словами и режимом (чтение или запись). Запрос SHALL получать только владелец проекта: одно сообщение со ссылкой на карточку запроса. Адрес SHALL проверяться как в шлюзе: только https и открытый интернет.
+
+#### Scenario: Запрос доходит до владельца
+- **GIVEN** проект «SHOP» владельца «anna» и агент «Шустрик» в задаче «SHOP-3»
+- **WHEN** агент запрашивает доступ к «stripe» с целью «проверить оплату заказа» на чтение
+- **THEN** у «anna» в «Подключениях» в блоке «Агенты просят доступ» запрос: «Шустрик», «SHOP-3», «Stripe», цель и «чтение»
+- **AND** «anna» получает одно сообщение со ссылкой на карточку запроса
+
+#### Scenario: Адрес внутрь отклоняется
+- **GIVEN** агент проекта «SHOP»
+- **WHEN** он запрашивает доступ к адресу «https://127.0.0.1/admin» или «localhost»
+- **THEN** запрос не создаётся
+- **AND** агент получает отказ: адрес должен быть в интернете
+
+#### Scenario: Повтор не создаёт второй запрос
+- **GIVEN** открытый запрос проекта «SHOP» к «stripe»
+- **WHEN** агент снова запрашивает «stripe», теперь на запись
+- **THEN** запрос остаётся один, повторов: 1, режим — запись
+- **AND** второго сообщения владельцу нет
+
+### Requirement: Владелец выдаёт доступ или отказывает
+Карточку запроса SHALL видеть только владелец проекта. Владелец SHALL подключить сервис и разрешить его проекту одним действием (ключ вводится один раз), разрешить уже подключённое или отказать с причиной. Решение SHALL доходить до агента: живому — сообщением, остановленному — задача возвращается в работу.
+
+#### Scenario: Подключить и разрешить
+- **GIVEN** открытый запрос «SHOP» к «stripe» на чтение и живой агент задачи
+- **WHEN** «anna» вставляет ключ на карточке и нажимает «Подключить и разрешить»
+- **THEN** появляется подключение «Stripe» с разрешением проекту «SHOP»: чтение — сразу, запись — нет
+- **AND** агент получает «доступ к Stripe выдан» и может вызвать его
+
+#### Scenario: Отказ с причиной
+- **GIVEN** открытый запрос «SHOP» к «stripe»
+- **WHEN** «anna» отказывает с причиной «используйте тестовые данные»
+- **THEN** запрос закрыт как отказанный
+- **AND** агент получает причину «используйте тестовые данные»
+
+#### Scenario: Чужой не видит запрос
+- **GIVEN** запрос проекта «SHOP» владельца «anna»
+- **WHEN** пользователь «boris» открывает ссылку на карточку или нажимает кнопку отказа
+- **THEN** запрос ему не показывается и не меняется
+
+### Requirement: Отказ шлюза становится запросом
+Вызов подключения без разрешения проекта или агента SHALL сам создавать запрос доступа к этому сервису, а агент SHALL получать ответ «запросил доступ — жди или продолжай без него».
+
+#### Scenario: Вызов без разрешения
+- **GIVEN** у «anna» подключение «Stripe», разрешённое проекту «SHOP» только на чтение
+- **WHEN** агент «SHOP» делает запись через «stripe»
+- **THEN** вызов отклонён
+- **AND** создан запрос доступа «SHOP» к «stripe» на запись, агенту сказано, что доступ запрошен
--
2.45.2
From 9d09ba1914efb1b3f0ef2b8e23849eb4b708bf36 Mon Sep 17 00:00:00 2001
From: peppa-bot
Date: Tue, 24 Nov 2026 14:04:50 +0000
Subject: [PATCH 5/6] =?UTF-8?q?PEP-250:=20=D0=BF=D0=B0=D0=BC=D1=8F=D1=82?=
=?UTF-8?q?=D1=8C=20=D0=BF=D1=80=D0=BE=D0=B5=D0=BA=D1=82=D0=B0=20=D0=B2=20?=
=?UTF-8?q?=D0=BF=D1=80=D0=B5=D0=B4=D0=B5=D0=BB=D0=B5=20=D0=BF=D0=BE=D1=81?=
=?UTF-8?q?=D0=BB=D0=B5=20=D0=BC=D0=B5=D1=80=D0=B6=D0=B0=20main?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Opus 5.5
---
.peppa/memory.md | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/.peppa/memory.md b/.peppa/memory.md
index 19d17e95..0b23ac87 100644
--- a/.peppa/memory.md
+++ b/.peppa/memory.md
@@ -48,14 +48,14 @@
- Тесты: места подписки занимай `core.createSession` с `subscriptionId`; очередь ёмкости чисти `moveTask(backlog)`. Конец хода вопроса не создаёт — жди `idle`. Суперадмин — `superadmin()`. Текст чатов — через `stripAsIs`.
- Узкие места: подписка — `pickSubscription`/`rotationCandidate`; агент — `startRunner`/`resumeSession`, модель — `claudePrint`, сообщение — `deliverToUser`; проекты — `listProjects`/`userProjectIds` (`from(projects)` — с `isNull(deletedAt)`); веб → runnerCall; функция от внешнего сервиса — `featureGateView` + `` (PEP-224).
- Вопрос ≠ задача (PEP-153): текст человека, который может стать задачей, — через `classifyMessage` (runner/message-intent.ts; в тестах mock-intake роль `intent`); молча задачу не заводить — кнопки (`chat.offer:`, `INTENT_TEXT`).
-- Задачу агента заводи через createTask с origin (acceptance|incident|analyst) и fileStories/checkDuplicate (PEP-197); «Предложено» = backlog + tasks.proposed, readyBacklog их не отдаёт; автомерж задач агента — по autonomy.acceptOwn (mayAutoAcceptTask).
+- Задачу агента — createTask с origin (acceptance|incident|analyst) и fileStories/checkDuplicate (PEP-197); «Предложено» = backlog + tasks.proposed, readyBacklog их не отдаёт; автомерж задач агента — по autonomy.acceptOwn (mayAutoAcceptTask).
- Неудачная версия (PEP-158): `rolled_back`/`failed` → агенту задачи, `returnFailedRelease` (runner/deploy-feedback.ts); счётчик — `attempts` задержки `deploy` (3 — суперадмину, 6 — стоп).
-- Bugsink API (PEP-218): схема — `GET /api/canonical/0/schema/` (2.6.3); `q` = текст + теги `key:value`; числа пользователей нет. Экран — `core/bugsink-errors.ts` (кэш 45 с), действия — `runner/bugsink-errors.ts`.
+- Bugsink API (PEP-218): схема — `GET /api/canonical/0/schema/` (2.6.3); `q` = текст + теги `key:value`; числа пользователей нет. Экран — `core/bugsink-errors.ts`, действия — `runner/bugsink-errors.ts`.
- Access Hub (PEP-249): новый сервис — карточка в `core/connection-catalog.ts` (тест access-hub-catalog сверяет каждую); сервис, который меняет данные через GET (Slack, Telegram), — чтение перечислять по методам.
- act_runner (PEP-233): идут контейнеры `GITEA-ACTIONS-TASK-*` — не рестартовать; голова без ci.yml или >2 суток — `orphan`, не очередь.
## Решения
-- Access Hub (PEP-250): агенту внешний сервис — только `request_access` (core/access-requests.ts), не секрет проекта; форму отказа `callConnection` не расширять (тесты сверяют deepEqual) — нужное для автозапроса ищи отдельно (`refusedCallService`).
+- Access Hub (PEP-250): сервис агенту — `request_access`, не секрет проекта; форму отказа `callConnection` не расширять (deepEqual в тестах) — для автозапроса `refusedCallService`.
- Access Hub (PEP-254): журнал — только `appendJournal` (core/connection-journal.ts, цепочка хэшей; правка строки задним числом = нарушение), ключ подключения — `sealConnectionSecret`/`openConnectionSecret`, не `encrypt`/`decrypt`.
- История (PEP-221): журнал/статусы — `history.db` (core/history.ts), логи — `archive/<вид>/<день>.jsonl.gz`; из основной базы события удаляет только `runRetention` после переноса.
- Docker (PEP-222): раннеры по умолчанию `container` (тесты — `PEPPA_DEFAULT_ISOLATION=none`).
--
2.45.2
From 00cb57cdd601475d4a6022aed883066686b0857f Mon Sep 17 00:00:00 2001
From: peppa-bot
Date: Tue, 24 Nov 2026 16:11:44 +0000
Subject: [PATCH 6/6] =?UTF-8?q?PEP-250:=20=D1=82=D0=B5=D1=81=D1=82=20?=
=?UTF-8?q?=D0=BF=D0=B5=D1=80=D0=B5=D1=85=D0=BE=D0=B4=D0=B0=20Claude=20?=
=?UTF-8?q?=E2=86=92=20Codex=20=D0=B1=D0=B5=D0=B7=20=D0=B3=D0=BE=D0=BD?=
=?UTF-8?q?=D0=BA=D0=B8=20=D1=81=20=D0=BD=D0=BE=D0=BC=D0=B5=D1=80=D0=BE?=
=?UTF-8?q?=D0=BC=20=D0=BD=D0=BE=D0=B2=D0=BE=D0=B3=D0=BE=20=D1=80=D0=B0?=
=?UTF-8?q?=D0=B7=D0=B3=D0=BE=D0=B2=D0=BE=D1=80=D0=B0?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Codex может успеть сообщить свой thread-id до чтения сессии; проверяем, что разговор
Claude не перенесён, а не что номер пуст.
Co-Authored-By: Claude Opus 5.5
---
packages/testkit/test/subscription-failover.test.ts | 7 +++++--
1 file changed, 5 insertions(+), 2 deletions(-)
diff --git a/packages/testkit/test/subscription-failover.test.ts b/packages/testkit/test/subscription-failover.test.ts
index 15f17e07..46f8c65c 100644
--- a/packages/testkit/test/subscription-failover.test.ts
+++ b/packages/testkit/test/subscription-failover.test.ts
@@ -84,7 +84,8 @@ describe("Переезд на подписку другого провайдер
const sid = await p.start();
assert.equal((await sess(sid)).provider, "claude");
await p.waitStatus(sid, "rate_limited");
- assert.equal((await sess(sid)).rotateReason, "limit");
+ const before = await sess(sid);
+ assert.equal(before.rotateReason, "limit");
await tick();
const start = await p.waitLog("relaunched on Codex", (e) => e.ev === "start" && e.gen === "2");
assert.equal(start.resume, null, "a conversation doesn't move between CLIs");
@@ -93,7 +94,9 @@ describe("Переезд на подписку другого провайдер
const s = await sess(sid);
assert.equal(s.provider, "codex");
assert.equal(s.subscriptionId, c.id);
- assert.equal(s.conversationId, null);
+ // Claude's conversation is dropped; Codex may already have reported its own new thread (codex-notify).
+ assert.ok(before.conversationId, "Claude had a conversation before the switch");
+ assert.notEqual(s.conversationId, before.conversationId, "Claude's conversation is not carried over to Codex");
const ev = (await typeEvents(runner.SWITCH_EVENT)).find((e) => e.sessionId === sid)!.payload as Record;
assert.deepEqual({ from: ev.fromProvider, to: ev.toProvider, carried: ev.carried }, { from: "claude", to: "codex", carried: "fresh" });
const [msg] = await outboxTexts(`rot:${sid}:g2:`);
--
2.45.2