PEP-250: Access Hub — агент сам просит доступ к сервису, владелец подключает ключ один раз #240
@ -25,16 +25,15 @@
|
||||
- SSRF-проверка в `lookup` — только с `agent: false` (keep-alive Node пропускает lookup, PEP-234).
|
||||
- QuickJS (PEP-212): строки из хост-функции читай синхронно до await (хэндлы аргументов слабые); все хэндлы и deferred dispose-ить, иначе rt.dispose падает.
|
||||
- Настройки по префиксу — `keyPrefix(settings.key, "x:")` из @peppa/db, не `like(…"x:%")` (LIKE без индекса). Индексы — тест db-indexes.
|
||||
- Смержено ≠ на сайте: сверь `/api/health` commit с main.
|
||||
- Смержено ≠ на сайте: сверь commit `/api/health` с main.
|
||||
- 530 при живом сервере — обрыв Mac → сервер (PEP-245); лечит только перенос адресов (ключ Cloudflare).
|
||||
- Продукт на другой docker — только `scripts/server-move/products-move.sh` (PEP-231, с данными); `peppa deploy redeploy` поднимает с пустыми томами.
|
||||
- Продукт на другой docker — только `scripts/server-move/products-move.sh` (PEP-231); `peppa deploy redeploy` — с пустыми томами.
|
||||
- Агент в контейнере не видит хост сервера, Mac и Cloudflare (PEP-231): инфраструктуру — скриптом в `scripts/server-move/` + шаги в docs/SERVER.md, выполнить просить суперадмина через `report_blocker`.
|
||||
- Пути сессий с Mac (PEP-246): `runnerCwd` пересоздаёт копию сам; чистка — `peppa session paths --fix`.
|
||||
- Сервер (PEP-230): docs/SERVER.md. Нет глобального git в контейнере: автор — `gitRelayEnv`; иначе `git -c user.name=peppa-bot -c user.email=peppa-bot@telecom.quest commit`.
|
||||
- Песочница раннера: нет tmux, openspec, Node 26 (есть 22). tmux — .deb с deb.debian.org (tmux_3.3a-3, libevent-core-2.1-7_2.1.12-stable-8, libutempter0) → `dpkg-deb -x` + LD_LIBRARY_PATH; openspec — `npm i -g --prefix /tmp/os @fission-ai/openspec`; тесты на 22 — MIN_MAJOR в scripts/lib/require-node.mjs (не коммитить). Падают и на main (среда): glossary-check.test, тесты хостов в sandbox-hosts.test.ts (нет ssh).
|
||||
- Codex (PEP-241): доверие папке — по корню основного репо worktree; `-c` режет ключ по точкам — пишем в config.toml CODEX_HOME (`codex-trust.ts`).
|
||||
- Песочница раннера: нет tmux, openspec, Node 26 (есть 22). tmux — .deb (tmux, libevent-core, libutempter) → `dpkg-deb -x` + LD_LIBRARY_PATH; openspec — `npm i -g --prefix /tmp/os @fission-ai/openspec`; тесты на 22 — MIN_MAJOR в require-node.mjs (не коммитить). Падают и на main: glossary-check, sandbox-hosts.
|
||||
- Codex (PEP-241): доверие папке — по корню основного репо worktree; `-c` режет ключ по точкам — пишем в config.toml CODEX_HOME (codex-trust.ts).
|
||||
- tmux на сервере (PEP-256) — контейнер `peppa-tmux`, сервисы — клиенты (`PEPPA_TMUX_EXTERNAL`); его образ меняет только `platform-deploy.sh --tmux`. Нет docker — compose проверяй парсером `yaml` (`{merge:true}`).
|
||||
|
||||
- Зависимость с build-скриптом (ssh2, cpu-features) роняет `pnpm install --frozen-lockfile` (ERR_PNPM_IGNORED_BUILDS): реши в `allowBuilds` pnpm-workspace.yaml.
|
||||
|
||||
## Соглашения
|
||||
@ -50,13 +49,14 @@
|
||||
- Тесты: места подписки занимай `core.createSession` с `subscriptionId`; очередь ёмкости чисти `moveTask(backlog)`. Конец хода вопроса не создаёт — жди `idle`. Суперадмин — `superadmin()`. Текст чатов — через `stripAsIs`.
|
||||
- Узкие места: подписка — `pickSubscription`/`rotationCandidate`; агент — `startRunner`/`resumeSession`, модель — `claudePrint`, сообщение — `deliverToUser`; проекты — `listProjects`/`userProjectIds` (`from(projects)` — с `isNull(deletedAt)`); веб → runnerCall; функция от внешнего сервиса — `featureGateView` + `<FeatureGate>` (PEP-224).
|
||||
- Вопрос ≠ задача (PEP-153): текст человека, который может стать задачей, — через `classifyMessage` (runner/message-intent.ts; в тестах mock-intake роль `intent`); молча задачу не заводить — кнопки (`chat.offer:<messageId>`, `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): новый HTTP-сервис — карточка в `core/connection-catalog.ts` (тест сверяет каждую); меняет данные через GET (Slack) — чтение по методам. Новый не-HTTP вид (PEP-251) — операция в `PROTOCOL_OPERATIONS`, драйвер `GatewayDrivers` (получает проверенный `address`, сам DNS не разрешает) и мок в testkit/mock-access.ts.
|
||||
- act_runner (PEP-233): идут контейнеры `GITEA-ACTIONS-TASK-*` — не рестартовать; голова без ci.yml или >2 суток — `orphan`, не очередь.
|
||||
|
||||
## Решения
|
||||
- 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`).
|
||||
@ -66,7 +66,7 @@
|
||||
- `template/` уходит в Gitea сам с выкаткой (PEP-242); старым проектам — `peppa ci connect <KEY> [--secrets-only]`.
|
||||
- Живой сайт (с PEP-230 — сервер, контейнеры) — только `scripts/platform-deploy.sh` из `~/peppa/src` на main (docs/SERVER.md); launchd/live-deploy.sh — только откат на Mac.
|
||||
- Эталон (PEP-184, PM): подписка прогона — наименее загруженная свободная из общего пула; про подписку PM не спрашивать.
|
||||
- Речь — свой faster-whisper (`<Dictate>`). Google: по почте учётки не склеиваем.
|
||||
- Речь — faster-whisper (`<Dictate>`). Google: по почте учётки не склеиваем.
|
||||
- Секреты (PEP-253): агенту — `agent_env` при `project.agent-secrets` (нет строки = вкл.); в тестах — `{ agent: true }`.
|
||||
- Привязка Google к чужой Google-only учётке — `mergeUserInto`; с eGov/Gitea — отказ (PEP-195).
|
||||
- Язык голоса (PEP-131): `transcribeLanguage(cfg, locale)` — язык интерфейса говорящего; новый вызов `transcribe` передаёт его пятым аргументом.
|
||||
|
||||
@ -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:<id>` `{inWork: 3, perPass: 5}`, меняет суперадмин — `peppa project agent-limits`; диспетчер не берёт задачу агента, когда `agentTasksInWork` ≥ предела, задачу человека предел не держит), `approveProposal`/`rejectProposal` («Не надо» → архив + `product.rejected:<id>`, агент приёмки больше не предлагает), `mayAutoAccept` (настройка автономности `acceptOwn`: `mine` | `mine_breakage` по умолчанию | `all`; автомерж, автозакрытие и хук «готово к ревью» учитывают — задача агента без разрешения ждёт «Принять» владельца), версия проекта (`product.version:<id>` `{ids, doneAt}`: задачи человека открываются в `createTask` через `touchVersion`; проход приёмки без поломок при всех принятых → «Версия готова» в том же сообщении, `ProjectProduct.versionDone` → «Готово» на карточке; после финиша улучшения копятся в `product.digest:<id>` и раз в неделю `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:<ids>: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:<id>`, `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` (миграция 0033), всё в `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/<id>` и `ar:<id>: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`
|
||||
- **Access Hub: базы, серверы, хранилища, почта (PEP-251)**: `connections.protocol` (`http` | `postgres` | `mysql` | `ssh` | `s3` | `mail`) + `connections.config` (JSON без секрета; миграция 0031). `core/connection-protocols.ts` — чистое: `normalizeProtocolConfig`, `PROTOCOL_OPERATIONS` (операция = read | write → режимы PEP-249), `checkHost`/`isBlockedAddress`, `singleStatement`/`isReadQuery`, `sftpPath`, `s3Key`, `signS3` (SigV4 path-style, сверена с `@smithy/signature-v4`), `formatRows` (≤ 1000 строк, страница 100 / 64 КБ). `core/connection-drivers.ts` — `pg`/`mysql2`/`ssh2`/`imapflow`/`nodemailer` через `import()`, соединение на проверенный IP (имя — только для сертификата). `core/connection-gateway.ts` — `useConnection` (порядок как у `callConnection`: сессия в контейнере → разрешение → режим операции → аргументы → 60/мин → адрес → журнал до и после, без текста SQL/команды/файла/письма), `protocolCheck`, ключ SSH закрепляется при первом подключении (`config.hostKey`), смена — `host_key_changed` + `tellHostKeyChanged` (одно сообщение на отпечаток), `resetHostKey` («Принять новый ключ сервера»); `setGatewayDefaults` — моки для тестов/стенда. Внутренние адреса — только хосты из `settings` `connections.internal_hosts` (`setInternalHosts` — суперадмин, CLI `peppa connections internal-hosts`). MCP агента `use_connection` (`peppa.connections.use`), операции видны в `list_connections`; `call_connection` для них — `wrong_protocol`. Веб: плитки видов в каталоге «Подключений» (`?service=proto:<вид>`), запись в базу и почта по умолчанию «спрашивать меня». Драйверы — в `serverExternalPackages` и зависимостях apps/web. Моки — `packages/testkit/src/mock-access.ts`; тест `access-hub-protocols.test.ts`
|
||||
- **Пауза проекта (PEP-174)**: `core/project-pause.ts` — `settings` `project.paused:<id>` `{since, by, sessions}` (без миграции), `isProjectPaused`/`assertProjectActive`/`pausedProjectIds`, окно последней паузы `project.pause.last:<id>` и `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 <KEY>`. Новое место, которое запускает агента, зовёт модель или пишет человеку по проекту, — через эти узкие места или с `isProjectPaused`. Тест `project-pause.test.ts`
|
||||
- **Прогресс на Главной (PEP-77)**: `progressOverview` (core/progress.ts: стори по колонкам доски без архивных, стори в работе с агентом и прогрессом tasks.md, ждущие «Принять»; итог — только свои проекты, суперадмину отдельно `others`), раздел «Прогресс» — `components/ProgressOverview.tsx`
|
||||
|
||||
@ -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:<id>: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?.();
|
||||
|
||||
@ -69,7 +69,7 @@ import {
|
||||
} from "@peppa/core";
|
||||
import { checkConnection, createConnection, deleteConnection, grantConnection, isGatewayProtocol, replaceConnectionSecret, resetHostKey, 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";
|
||||
@ -1090,6 +1090,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 () => {
|
||||
|
||||
@ -11,6 +11,7 @@ import {
|
||||
grantableAgents,
|
||||
listConnections,
|
||||
listUserProjects,
|
||||
ownerAccessRequests,
|
||||
searchCatalog,
|
||||
type CatalogKind,
|
||||
type CatalogService,
|
||||
@ -22,6 +23,7 @@ import {
|
||||
type GatewayProtocol,
|
||||
GATEWAY_PROTOCOLS,
|
||||
} 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";
|
||||
@ -489,7 +491,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 proto = q.service?.startsWith("proto:") ? (GATEWAY_PROTOCOLS as string[]).find((p) => `proto:${p}` === q.service) as GatewayProtocol | undefined : undefined;
|
||||
const chosen = q.service === "custom" ? "custom" : catalogService(q.service);
|
||||
const kind = q.kind && (CATALOG_KINDS as string[]).includes(q.kind) ? q.kind : null;
|
||||
@ -503,6 +505,12 @@ export default async function ConnectionsPage({ searchParams }: { searchParams:
|
||||
</p>
|
||||
</PageHeader>
|
||||
|
||||
{requests.length > 0 && (
|
||||
<Section id="requests" title={t("Агенты просят доступ")} count={requests.length}>
|
||||
<AccessRequestList list={requests} t={t} />
|
||||
</Section>
|
||||
)}
|
||||
|
||||
{list.length > 0 && (
|
||||
<Section title={t("Ваши подключения")} count={list.length}>
|
||||
{list.map((c) => (
|
||||
|
||||
184
apps/web/app/(app)/connections/requests/[id]/page.tsx
Normal file
184
apps/web/app/(app)/connections/requests/[id]/page.tsx
Normal file
@ -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 (
|
||||
<div className="flex flex-col gap-0.5 sm:flex-row sm:gap-3">
|
||||
<span className="w-32 shrink-0 text-muted-foreground">{label}</span>
|
||||
<span className="min-w-0 break-words">{children}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DoneNotice({ done, check, t }: { done?: string; check?: string; t: Translator }) {
|
||||
if (done === "denied") return <Notice>{t("Отказано. Агент получит вашу причину и продолжит без этого сервиса.")}</Notice>;
|
||||
if (done !== "granted") return null;
|
||||
const tail = check === "bad_key" ? t("Но сервис не принял ключ: замените его в разделе «Подключения».") : check === "down" ? t("Сервис сейчас не отвечает — ключ проверится при первом запросе агента.") : "";
|
||||
return (
|
||||
<Notice>
|
||||
{t("Доступ выдан. Агент получил сообщение и продолжит работу; ключ доступа он не видит.")} {tail}
|
||||
</Notice>
|
||||
);
|
||||
}
|
||||
|
||||
function ConnectForm({ r, card, t }: { r: AccessRequestView; card: CatalogService | null; t: Translator }) {
|
||||
const back = `/connections/requests/${r.id}`;
|
||||
return (
|
||||
<ol className="m-0 flex list-decimal flex-col gap-4 pl-5 text-sm">
|
||||
<li className="flex flex-col gap-1">
|
||||
<span className="font-medium">{t("Возьмите ключ доступа")}</span>
|
||||
{card ? (
|
||||
<>
|
||||
<span className="text-muted-foreground">{t.text(card.keyHint)}</span>
|
||||
<a href={card.keyUrl} target="_blank" rel="noreferrer noopener" className="inline-flex items-center gap-1 self-start text-primary underline-offset-2 hover:underline">
|
||||
{t("Открыть страницу, где берут ключ")} <ExternalLink className="size-3" />
|
||||
</a>
|
||||
</>
|
||||
) : (
|
||||
<span className="text-muted-foreground">{t("Он есть в описании сервиса для разработчиков или у того, кто его сделал.")}</span>
|
||||
)}
|
||||
</li>
|
||||
<li className="flex flex-col gap-2">
|
||||
<span className="font-medium">{t("Вставьте его сюда")}</span>
|
||||
<form action={connectAccessRequestAction} className="flex max-w-xl flex-col gap-2" autoComplete="off">
|
||||
<Hidden fields={{ back, requestId: r.id }} />
|
||||
{(!card || card.baseEditable) && <Input name="baseUrl" required type="url" defaultValue={r.host ?? ""} placeholder={card?.baseUrl ?? "https://api.example.com/v1"} aria-label={t("Адрес сервиса")} className="font-mono" spellCheck={false} />}
|
||||
<Input name="secret" required type="password" placeholder={card?.auth === "basic" ? t("логин:пароль — после сохранения их не увидит никто") : t("Ключ доступа — после сохранения его не увидит никто")} aria-label={t("Ключ доступа")} autoComplete="new-password" />
|
||||
{!card && (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<select name="authKind" aria-label={t("Как передавать ключ")} className={SELECT} defaultValue="bearer">
|
||||
<option value="bearer">{t("Как «Authorization: Bearer …»")}</option>
|
||||
<option value="header">{t("В своём заголовке")}</option>
|
||||
<option value="query">{t("В адресе запроса (параметр)")}</option>
|
||||
<option value="basic">{t("Логин и пароль")}</option>
|
||||
</select>
|
||||
<Input name="authHeader" placeholder="X-Api-Key" aria-label={t("Имя заголовка или параметра")} className="max-w-48 font-mono" spellCheck={false} />
|
||||
</div>
|
||||
)}
|
||||
<Button size="sm" className="self-start">{t("Подключить и разрешить")}</Button>
|
||||
</form>
|
||||
</li>
|
||||
</ol>
|
||||
);
|
||||
}
|
||||
|
||||
function ExistingForm({ r, fit, other, t }: { r: AccessRequestView; fit: ConnectionView[]; other: ConnectionView[]; t: Translator }) {
|
||||
const all = [...fit, ...other];
|
||||
if (!all.length) return null;
|
||||
return (
|
||||
<form action={grantAccessRequestAction} className="flex flex-wrap items-center gap-2 text-sm">
|
||||
<Hidden fields={{ back: `/connections/requests/${r.id}`, requestId: r.id }} />
|
||||
<select name="connectionId" required aria-label={t("Подключение")} className={SELECT} defaultValue={fit[0]?.id ?? ""}>
|
||||
{!fit.length && <option value="">{t("Выберите подключение")}</option>}
|
||||
{all.map((c) => (
|
||||
<option key={c.id} value={c.id}>
|
||||
{c.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<Button size="sm" variant="secondary">{t("Разрешить из уже подключённого")}</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
/** 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 (
|
||||
<Workspace>
|
||||
<Flash error={q.error} />
|
||||
<DoneNotice done={q.done} check={q.check} t={t} />
|
||||
<PageHeader
|
||||
title={<><KeyRound className="mr-1 inline size-5 text-primary" />{t("Агент просит доступ к {service}", { service: r.service })}</>}
|
||||
crumbs={<Link href="/connections" className="hover:underline">{t("Подключения")}</Link>}
|
||||
>
|
||||
<p className="m-0 text-sm text-muted-foreground">
|
||||
{r.status === "open"
|
||||
? t("Агенту нужен этот сервис для работы над задачей. Ключ доступа вы вводите один раз, агент его не увидит: запросы выполняет FORGE и записывает их в журнал. Можно и отказать — агент продолжит без сервиса.")
|
||||
: t("По этому запросу уже есть решение.")}
|
||||
</p>
|
||||
</PageHeader>
|
||||
|
||||
<Card className="flex flex-col gap-2 p-4 text-sm">
|
||||
<div className="mb-1 flex flex-wrap items-center gap-2">
|
||||
<AccessStatus r={r} t={t} />
|
||||
{r.repeats > 0 && <span className="text-xs text-muted-foreground">{t("агент просил ещё раз: {n}", { n: r.repeats })}</span>}
|
||||
</div>
|
||||
<Fact label={t("Агент")}>{r.agentName ?? "—"}</Fact>
|
||||
<Fact label={t("Задача")}>{r.taskKey ? <Link href={`/t/${r.taskKey}`} className="text-primary hover:underline">{r.taskKey}{r.taskTitle ? ` — ${r.taskTitle}` : ""}</Link> : "—"}</Fact>
|
||||
<Fact label={t("Проект")}>{r.projectName}</Fact>
|
||||
<Fact label={t("Сервис")}>
|
||||
{r.service}
|
||||
{card && (
|
||||
<a href={card.docsUrl} target="_blank" rel="noreferrer noopener" className="ml-2 inline-flex items-center gap-1 text-xs text-muted-foreground hover:underline">
|
||||
{t("Документация сервиса")} <ExternalLink className="size-3" />
|
||||
</a>
|
||||
)}
|
||||
{!card && r.host && <span className="ml-2 font-mono text-xs text-muted-foreground">{r.host}</span>}
|
||||
</Fact>
|
||||
<Fact label={t("Что можно")}>{accessModeText(r.mode, t)}</Fact>
|
||||
{/* The agent's own words: shown as is, never as instructions. */}
|
||||
<Fact label={t("Зачем")}>{r.purpose}</Fact>
|
||||
{r.status === "denied" && <Fact label={t("Причина отказа")}>{r.reason ?? t("без причины")}</Fact>}
|
||||
</Card>
|
||||
|
||||
{r.status === "open" && (
|
||||
<>
|
||||
<Section title={t("Подключить и разрешить")}>
|
||||
<Card className="p-4">
|
||||
<ConnectForm r={r} card={card} t={t} />
|
||||
<p className="m-0 mt-3 text-xs text-muted-foreground">
|
||||
{r.mode === "write"
|
||||
? t("Агенты проекта смогут читать и менять данные в этом сервисе. Изменить или отозвать доступ можно в разделе «Подключения».")
|
||||
: t("Агенты проекта смогут только читать данные в этом сервисе. Изменить или отозвать доступ можно в разделе «Подключения».")}
|
||||
</p>
|
||||
</Card>
|
||||
</Section>
|
||||
{fit.length + other.length > 0 && (
|
||||
<Section title={t("Или разрешить из уже подключённого")}>
|
||||
<Card className="p-4">
|
||||
<ExistingForm r={r} fit={fit} other={other} t={t} />
|
||||
</Card>
|
||||
</Section>
|
||||
)}
|
||||
<Section title={t("Отказать")}>
|
||||
<Card className="p-4">
|
||||
<form action={denyAccessRequestAction} className="flex max-w-xl flex-col gap-2">
|
||||
<Hidden fields={{ back: `/connections/requests/${r.id}`, requestId: r.id }} />
|
||||
<Textarea name="reason" rows={2} maxLength={500} placeholder={t("Причина — агент её получит, например «используйте тестовые данные»")} aria-label={t("Причина отказа")} />
|
||||
<Button size="sm" variant="destructive" className="self-start">{t("Отказать")}</Button>
|
||||
</form>
|
||||
</Card>
|
||||
</Section>
|
||||
</>
|
||||
)}
|
||||
</Workspace>
|
||||
);
|
||||
}
|
||||
44
apps/web/components/AccessRequests.tsx
Normal file
44
apps/web/components/AccessRequests.tsx
Normal file
@ -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 <Badge variant="warn">{t("ждёт вашего решения")}</Badge>;
|
||||
if (r.status === "granted") return <Badge variant="ok">{t("доступ выдан")}</Badge>;
|
||||
if (r.status === "denied") return <Badge variant="danger">{t("отказано")}</Badge>;
|
||||
return <Badge variant="outline">{t("агент отменил запрос")}</Badge>;
|
||||
}
|
||||
|
||||
/** PEP-250: «Агенты просят доступ» on «Подключения» — the owner's open requests. */
|
||||
export function AccessRequestList({ list, t }: { list: AccessRequestView[]; t: Translator }) {
|
||||
return (
|
||||
<ul className="m-0 flex list-none flex-col gap-2 p-0">
|
||||
{list.map((r) => (
|
||||
<li key={r.id}>
|
||||
<Card className="flex flex-wrap items-center gap-x-3 gap-y-1 p-3 text-sm">
|
||||
<KeyRound className="size-4 text-primary" />
|
||||
<span className="font-medium">{r.service}</span>
|
||||
<span className="text-muted-foreground">· {accessModeText(r.mode, t)}</span>
|
||||
<span className="text-muted-foreground">
|
||||
· {r.agentName ? t("агент {name}", { name: r.agentName }) : t("агент")} · {r.taskKey ?? r.projectKey}
|
||||
</span>
|
||||
<span className="basis-full truncate text-muted-foreground">{r.purpose}</span>
|
||||
<span className="text-xs text-muted-foreground">{ago(r.updatedAt, t)}</span>
|
||||
<Link href={`/connections/requests/${r.id}`} className="ml-auto text-primary underline-offset-2 hover:underline">
|
||||
{t("Посмотреть и решить")}
|
||||
</Link>
|
||||
</Card>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
@ -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:<id>:no` (отказ без причины; причину — на сайте).
|
||||
- **Чужой не видит**: `accessRequestForUser` отдаёт запрос только `owner_id`, который всё ещё
|
||||
владелец проекта; иначе 404. Бот проверяет то же.
|
||||
- **declare_needs**: у пункта поле `use: "product" | "agent"`; `agent` — запрос доступа к сервису
|
||||
каталога, найденному по `service` или имени секрета, вместо пункта списка.
|
||||
|
||||
## Риски
|
||||
- Решение в остановленном проекте не будит агента — увидит при следующем запуске в `list_requests`.
|
||||
@ -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/<id>` — только ему: «Подключить и разрешить» (ключ один раз),
|
||||
«Разрешить из уже подключённого», «Отказать» с причиной.
|
||||
- Решение доходит до агента: живому — сообщение, остановленному — задача возвращается в работу
|
||||
с этим сообщением.
|
||||
- `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`.
|
||||
- Существующие подключения, разрешения и шлюз не меняются.
|
||||
@ -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» на запись, агенту сказано, что доступ запрошен
|
||||
@ -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:<id>: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
|
||||
@ -230,6 +230,55 @@ SHALL отправить владельцу одно сообщение.
|
||||
- **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» на запись, агенту сказано, что доступ запрошен
|
||||
### Requirement: Базы данных, серверы, хранилища и почта через FORGE
|
||||
Пользователь SHALL подключать базу данных PostgreSQL или MySQL, сервер по SSH, хранилище S3 и почтовый ящик: адрес, пользователь и пароль (или ключ). Агент SHALL работать с ними только операциями FORGE и никогда не получать пароль или ключ. Каждая операция SHALL быть чтением или записью и разрешаться режимами владельца («сразу», «спрашивать меня», «нет»).
|
||||
|
||||
|
||||
367
packages/core/src/access-requests.ts
Normal file
367
packages/core/src/access-requests.ts
Normal file
@ -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<string[]>;
|
||||
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<string> {
|
||||
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<AccessRequestView[]> {
|
||||
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<AccessRequestView | null> {
|
||||
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<AccessRequestResult> {
|
||||
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<void> {
|
||||
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<AccessRequestView[]> {
|
||||
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<AccessRequestView> {
|
||||
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<AccessRequestView | null> {
|
||||
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<AccessRequestView> {
|
||||
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<AccessRequestView[]> {
|
||||
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<GrantMode, number> = { 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<void> {
|
||||
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<AccessRequestView> {
|
||||
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<AccessRequestView> {
|
||||
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<ConnectionInput, "catalogId"> & { 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<AccessRequestView> {
|
||||
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))!;
|
||||
}
|
||||
@ -625,6 +625,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;
|
||||
@ -657,7 +659,7 @@ export async function agentConnections(db: Db, sessionId: number): Promise<Agent
|
||||
const card = catalogService(r.c.catalogId);
|
||||
const proto = r.c.protocol;
|
||||
const protocolOperations = isGatewayProtocol(proto) ? Object.entries(PROTOCOL_OPERATIONS[proto]).map(([name, op]) => ({ name, ...op })) : [];
|
||||
const c = by.get(r.c.id) ?? { id: r.c.id, name: r.c.name, slug: connectionSlug(r.c), service: card?.name ?? null, baseUrl: r.c.baseUrl, docsUrl: card?.docsUrl ?? null, readMode: "off", writeMode: "off", operations: [], checkStatus: r.c.checkStatus, protocol: proto, protocolOperations };
|
||||
const c = by.get(r.c.id) ?? { id: r.c.id, name: r.c.name, slug: connectionSlug(r.c), service: card?.name ?? null, catalogId: card?.id ?? null, baseUrl: r.c.baseUrl, docsUrl: card?.docsUrl ?? null, readMode: "off", writeMode: "off", operations: [], checkStatus: r.c.checkStatus, protocol: proto, protocolOperations };
|
||||
c.operations = [...new Set([...c.operations, ...r.operations])];
|
||||
c.readMode = widest(c.readMode, r.readMode);
|
||||
c.writeMode = widest(c.writeMode, r.writeMode);
|
||||
@ -803,6 +805,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<T extends { c: typeof connections.$inferSelect }>(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).
|
||||
|
||||
@ -112,6 +112,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 "./connection-protocols.ts";
|
||||
export * from "./connection-gateway.ts";
|
||||
export { DriverError, type GatewayDrivers, type SqlTarget, type SqlRequest, type SshTarget, type SshRequest, type SshAnswer, type MailTarget, type MailRequest, type MailAnswer, type TlsMode } from "./connection-drivers.ts";
|
||||
|
||||
32
packages/db/migrations/0033_access_requests.sql
Normal file
32
packages/db/migrations/0033_access_requests.sql
Normal file
@ -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`);
|
||||
5575
packages/db/migrations/meta/0033_snapshot.json
Normal file
5575
packages/db/migrations/meta/0033_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
@ -232,6 +232,13 @@
|
||||
"when": 1795530560091,
|
||||
"tag": "0032_secrets_agent_env",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 33,
|
||||
"version": "6",
|
||||
"when": 1795534160168,
|
||||
"tag": "0033_access_requests",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@ -756,6 +756,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" }),
|
||||
|
||||
@ -52,6 +52,12 @@ import {
|
||||
agentSecretsEnabled,
|
||||
agentConnections,
|
||||
callConnection,
|
||||
cancelAccessRequest,
|
||||
catalogFromSecretName,
|
||||
refusedCallService,
|
||||
requestAccess,
|
||||
sessionAccessRequests,
|
||||
type AccessRequestView,
|
||||
useConnection,
|
||||
guardUntrusted,
|
||||
sessionIsolated,
|
||||
@ -412,7 +418,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 — HTTP services, and (PEP-251) databases, SSH servers, S3 storages and mailboxes with their operations: 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 — HTTP services, and (PEP-251) databases, SSH servers, S3 storages and mailboxes with their operations: 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.";
|
||||
@ -448,13 +454,74 @@ 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<Awaited<ReturnType<typeof callConnection>>, { ok: false }>, connection: string, method: string, path: string): Promise<string | null> {
|
||||
if (!sessionId) return 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 = 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);
|
||||
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}.`;
|
||||
},
|
||||
);
|
||||
|
||||
// PEP-251: databases, SSH/SFTP, S3 and mail through the same gateway.
|
||||
tool(
|
||||
"use_connection",
|
||||
@ -479,7 +546,7 @@ export function createAgentServer(db: Db, opts: AgentServerOptions = {}): McpSer
|
||||
|
||||
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
|
||||
@ -489,15 +556,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);
|
||||
@ -505,7 +590,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");
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
64
packages/runner/src/access-requests.ts
Normal file
64
packages/runner/src/access-requests.ts
Normal file
@ -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<AccessDelivery> {
|
||||
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<AccessRequestView> {
|
||||
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<ConnectionInput, "catalogId"> & { 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<AccessRequestView> {
|
||||
const r = await denyAccessRequest(db, userId, id, reason);
|
||||
await tellAgentAboutAccess(db, r);
|
||||
return r;
|
||||
}
|
||||
@ -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";
|
||||
|
||||
@ -163,6 +163,49 @@ export const accessHub: Record<string, string> = {
|
||||
"Журнал подключений: контрольные точки": "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",
|
||||
// PEP-251: databases, servers, storages and mailboxes
|
||||
"«Спрашивать меня» пока означает отказ: подтверждение запросов появится позже.": "«Ask me» means a refusal for now: request confirmations will come later.",
|
||||
"Адрес отправителя (пусто — логин)": "Sender address (empty — the login)",
|
||||
|
||||
@ -163,6 +163,49 @@ export const accessHub: Record<string, string> = {
|
||||
"Журнал подключений: контрольные точки": "Қосылымдар журналы: бақылау нүктелері",
|
||||
"Журнал подключений пользователя {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}",
|
||||
"Откройте запрос, чтобы подключить сервис или отказать.": "Сервисті қосу немесе бас тарту үшін сұрауды ашыңыз.",
|
||||
"Агент просит доступ": "Агент қолжетімділік сұрайды",
|
||||
"Запрос не найден": "Сұрау табылмады",
|
||||
"По этому запросу уже есть решение": "Бұл сұрау бойынша шешім бұрыннан бар",
|
||||
// PEP-251: databases, servers, storages and mailboxes
|
||||
"«Спрашивать меня» пока означает отказ: подтверждение запросов появится позже.": "«Менен сұрау» әзірге бас тартуды білдіреді: сұрауларды растау кейінірек пайда болады.",
|
||||
"Адрес отправителя (пусто — логин)": "Жіберуші мекенжайы (бос болса — логин)",
|
||||
|
||||
197
packages/testkit/test/access-requests.test.ts
Normal file
197
packages/testkit/test/access-requests.test.ts
Normal file
@ -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<ReturnType<typeof core.upsertUserFromGitea>>;
|
||||
let boris: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||||
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<ReturnType<typeof core.getProject>>; 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<string, unknown> = {}) => {
|
||||
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<ReturnType<typeof story>>;
|
||||
let call: Awaited<ReturnType<typeof mcpAgent>>;
|
||||
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;
|
||||
}
|
||||
});
|
||||
});
|
||||
@ -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<string, unknown>;
|
||||
assert.deepEqual({ from: ev.fromProvider, to: ev.toProvider, carried: ev.carried }, { from: "claude", to: "codex", carried: "fresh" });
|
||||
const [msg] = await outboxTexts(`rot:${sid}:g2:`);
|
||||
|
||||
@ -159,8 +159,13 @@ git, тесты, раннеры — решаешь ты сам и пишешь,
|
||||
`ANTHROPIC_*`, `CLAUDE_*`, `OPENCODE_*` доходят только до продукта, в твоё окружение — нет.
|
||||
- **Внешний сервис для твоей работы (Stripe, OpenAI, GitHub, Telegram…) — только через подключение**
|
||||
(Access Hub): `list_connections`, затем `call_connection` — ключ FORGE подставит сам, ты его не
|
||||
видишь. Нужного подключения нет — `request_access` (если есть) или `ask_pm`: какой сервис и зачем;
|
||||
владелец даст его в «Подключениях». Не проси положить ключ сервиса в секреты проекта.
|
||||
видишь. Не проси положить ключ сервиса в секреты проекта. Нет доступа —
|
||||
`peppa.request_access(service: "stripe" | host: "https://…", purpose: "зачем, простыми словами",
|
||||
mode: read|write)`: владелец получит ссылку, подключит ключ один раз или откажет с причиной;
|
||||
решение придёт тебе сообщением, остановленная задача вернётся в работу. Не жди: продолжай на
|
||||
моке. Один открытый запрос на сервис — повтор прибавится к нему; `list_requests` — состояние,
|
||||
`cancel_request` — если доступ больше не нужен. Отказ шлюза из-за отсутствия разрешения сам
|
||||
становится запросом. В `declare_needs` такой пункт помечай `use: "agent"`.
|
||||
- Секреты проекта по умолчанию идут только выкаченному продукту; в твоё окружение — лишь те, что
|
||||
владелец пометил «агенту и продукту», и только если в проекте включено «Агенты получают секреты
|
||||
в окружение» (новые проекты — выкл.). `peppa.list_secrets` показывает имена и что из них есть
|
||||
@ -255,7 +260,8 @@ FORGE живёт на той же машине. Контейнер, которы
|
||||
ход**: продолжай по `default` и запиши его в `design.md`. Ответ придёт позже
|
||||
сообщением — если он другой, переделаешь.
|
||||
- Нужен ключ или аккаунт, которого нет, — делай на моке (раздел ниже) и объяви его через
|
||||
`peppa.declare_needs`: владелец получит список «что дать и куда вставить».
|
||||
`peppa.declare_needs` (нужен продукту) или `peppa.request_access` (нужен тебе для работы):
|
||||
владелец получит список «что дать и куда вставить» или ссылку на запрос доступа.
|
||||
|
||||
## Сообщения PM: четыре типа
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user