From 84f50b1c5b994020fdebf9141d088bf97255dfdf Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Tue, 24 Nov 2026 11:22:45 +0000 Subject: [PATCH] =?UTF-8?q?PEP-250:=20=D0=B7=D0=B0=D0=BF=D1=80=D0=BE=D1=81?= =?UTF-8?q?=D1=8B=20=D0=B4=D0=BE=D1=81=D1=82=D1=83=D0=BF=D0=B0=20=E2=80=94?= =?UTF-8?q?=20=D1=82=D0=B0=D0=B1=D0=BB=D0=B8=D1=86=D0=B0,=20=D1=8F=D0=B4?= =?UTF-8?q?=D1=80=D0=BE,=20MCP=20=D0=B0=D0=B3=D0=B5=D0=BD=D1=82=D0=B0,=20?= =?UTF-8?q?=D0=BA=D0=BD=D0=BE=D0=BF=D0=BA=D0=B0=20=D0=B1=D0=BE=D1=82=D0=B0?= =?UTF-8?q?,=20=D0=BA=D0=B0=D1=80=D1=82=D0=BE=D1=87=D0=BA=D0=B0=20=D0=B2?= =?UTF-8?q?=D0=BB=D0=B0=D0=B4=D0=B5=D0=BB=D1=8C=D1=86=D0=B0,=20=D0=BF?= =?UTF-8?q?=D0=B5=D1=80=D0=B5=D0=B2=D0=BE=D0=B4=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- apps/bot/src/bot.ts | 11 +- apps/web/app/(app)/actions.ts | 38 +- apps/web/app/(app)/connections/page.tsx | 10 +- .../(app)/connections/requests/[id]/page.tsx | 184 + apps/web/components/AccessRequests.tsx | 44 + packages/core/src/access-requests.ts | 367 ++ packages/core/src/connections.ts | 10 +- packages/core/src/index.ts | 1 + .../db/migrations/0031_access_requests.sql | 32 + .../db/migrations/meta/0031_snapshot.json | 5532 +++++++++++++++++ packages/db/migrations/meta/_journal.json | 7 + packages/db/src/schema.ts | 31 + packages/mcp/src/agent.ts | 93 +- packages/runner/src/access-requests.ts | 64 + packages/runner/src/index.ts | 1 + packages/shared/src/i18n/en/access-hub.ts | 43 + packages/shared/src/i18n/kk/access-hub.ts | 43 + 17 files changed, 6500 insertions(+), 11 deletions(-) create mode 100644 apps/web/app/(app)/connections/requests/[id]/page.tsx create mode 100644 apps/web/components/AccessRequests.tsx create mode 100644 packages/core/src/access-requests.ts create mode 100644 packages/db/migrations/0031_access_requests.sql create mode 100644 packages/db/migrations/meta/0031_snapshot.json create mode 100644 packages/runner/src/access-requests.ts diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts index 8d2e32b4..fa62e1ba 100644 --- a/apps/bot/src/bot.ts +++ b/apps/bot/src/bot.ts @@ -80,7 +80,7 @@ import { } from "@peppa/core"; import { projects, tasks, type Db } from "@peppa/db"; import { formatTaskKey, voiceStoriesEnabled } from "@peppa/shared"; -import { delayAction, resolveTaskById } from "@peppa/runner"; +import { delayAction, denyAccessRequestAndTell, resolveTaskById } from "@peppa/runner"; import { parseDelayCallback } from "@peppa/core"; import { acceptTask, answerAndDeliver, classifyMessage, decideIncident, decideProposals, moveTask, postToChat, REQUEST_SENT_TEXT, requestSubscription, resumeSession, stopSession } from "@peppa/runner"; import { INTENT_TEXT, statusAnswer } from "@peppa/core"; @@ -1019,6 +1019,15 @@ export function createBot(o: BotOptions) { await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`)); return "done"; } + // PEP-250: «Отказать» under an agent's access request: `ar::no` — only the project's owner (core checks). + if (parts[0] === "ar") { + const toast = await denyAccessRequestAndTell(db, user.id, Number(parts[1]), null).then( + () => tr("Отказано. Агент узнает об этом."), + (e) => (e instanceof PeppaError ? e.message : (log(`access request: ${(e as Error).stack ?? e}`), tr("Ошибка"))), + ); + await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`)); + return "done"; + } if (parts[0] === "f") { const toast = await onFeedbackButton(user, c, parts).catch((e) => (log(`feedback: ${(e as Error).stack ?? e}`), tr("Ошибка"))); wakeOutbox?.(); diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts index 7d83c314..6b26998c 100644 --- a/apps/web/app/(app)/actions.ts +++ b/apps/web/app/(app)/actions.ts @@ -66,7 +66,7 @@ import { } from "@peppa/core"; import { checkConnection, createConnection, deleteConnection, grantConnection, replaceConnectionSecret, revokeConnection, revokeGrant, type CatalogAuth, type ConnectionCheckResult, type GrantMode } from "@peppa/core"; import { attachmentLabel, fixFeedback, linkAttachments, linkFeedback, parseAttachmentIds, rejectFeedback, restoreProject } from "@peppa/core"; -import { deleteProject, decideProposals, mergeProposals } from "@peppa/runner"; +import { deleteProject, decideProposals, mergeProposals, connectAndGrantAccessRequest, denyAccessRequestAndTell, grantAccessRequestFromExisting } from "@peppa/runner"; import { bugsinkFromEnv } from "@peppa/bugsink"; import { loadEnv } from "@peppa/shared"; import { pauseProject, resumeProject, acceptAll, acceptStory, autoPublish, fixStory, confirmTaskDecision, changeTaskDecision, undoSplit, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProjectOnce, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, syncSessionAttachments, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, managesProject, saveAgentsMd, cancelOwnLogin, finishOwnClaudeLogin, connectOwnSubscription, removeOwnSubscription, type OwnSubscriptionKind, chooseSharedSubscription, requestSubscription } from "@peppa/runner"; @@ -1038,6 +1038,42 @@ export async function grantConnectionAction(f: FormData) { }); } +// PEP-250: an agent's access request — only its project's owner decides (core checks). +export async function connectAccessRequestAction(f: FormData) { + const user = asWebActor(await requireUser()); + await attempt(f, async () => { + const id = Number(str(f, "requestId")); + const kind = str(f, "authKind") as CatalogAuth; + const { connection } = await connectAndGrantAccessRequest(db, user.id, id, { + name: str(f, "name"), + baseUrl: str(f, "baseUrl") || undefined, + secret: String(f.get("secret") ?? "").trim(), + authKind: AUTH_KINDS.includes(kind) ? kind : "bearer", + authHeader: str(f, "authHeader") || null, + }); + const r = await checkConnection(db, user.id, connection.id).catch(() => null); + return `/connections/requests/${id}?done=granted&check=${checkWord(r)}`; + }); +} + +export async function grantAccessRequestAction(f: FormData) { + const user = asWebActor(await requireUser()); + await attempt(f, async () => { + const id = Number(str(f, "requestId")); + await grantAccessRequestFromExisting(db, user.id, id, Number(str(f, "connectionId"))); + return `/connections/requests/${id}?done=granted`; + }); +} + +export async function denyAccessRequestAction(f: FormData) { + const user = asWebActor(await requireUser()); + await attempt(f, async () => { + const id = Number(str(f, "requestId")); + await denyAccessRequestAndTell(db, user.id, id, str(f, "reason") || null); + return `/connections/requests/${id}?done=denied`; + }); +} + export async function revokeGrantAction(f: FormData) { const user = asWebActor(await requireUser()); await attempt(f, async () => { diff --git a/apps/web/app/(app)/connections/page.tsx b/apps/web/app/(app)/connections/page.tsx index d2cb7ad1..101edc5c 100644 --- a/apps/web/app/(app)/connections/page.tsx +++ b/apps/web/app/(app)/connections/page.tsx @@ -11,6 +11,7 @@ import { grantableAgents, listConnections, listUserProjects, + ownerAccessRequests, searchCatalog, type CatalogKind, type CatalogService, @@ -20,6 +21,7 @@ import { type ConnectionView, type GrantMode, } from "@peppa/core"; +import { AccessRequestList } from "@/components/AccessRequests"; import { Hidden } from "@/components/cards"; import { ago, Empty, Flash, Notice, PageHeader, Section } from "@/components/common"; import { Badge } from "@/components/ui/badge"; @@ -358,7 +360,7 @@ export default async function ConnectionsPage({ searchParams }: { searchParams: const user = await requireUser(); const t = await getT(); const engineer = (await uiMode()) === "engineer"; - const [list, journal, projects, agents] = await Promise.all([listConnections(db, user.id), connectionJournal(db, user.id, { limit: 50 }), listUserProjects(db, user.id), grantableAgents(db)]); + const [list, journal, projects, agents, requests] = await Promise.all([listConnections(db, user.id), connectionJournal(db, user.id, { limit: 50 }), listUserProjects(db, user.id), grantableAgents(db), ownerAccessRequests(db, user.id)]); const chosen = q.service === "custom" ? "custom" : catalogService(q.service); const kind = q.kind && (CATALOG_KINDS as string[]).includes(q.kind) ? q.kind : null; return ( @@ -371,6 +373,12 @@ export default async function ConnectionsPage({ searchParams }: { searchParams:

+ {requests.length > 0 && ( +
+ +
+ )} + {list.length > 0 && (
{list.map((c) => ( diff --git a/apps/web/app/(app)/connections/requests/[id]/page.tsx b/apps/web/app/(app)/connections/requests/[id]/page.tsx new file mode 100644 index 00000000..508b5b1a --- /dev/null +++ b/apps/web/app/(app)/connections/requests/[id]/page.tsx @@ -0,0 +1,184 @@ +import Link from "next/link"; +import { notFound } from "next/navigation"; +import { ExternalLink, KeyRound } from "lucide-react"; +import { accessRequestForUser, catalogService, connectionsForRequest, type AccessRequestView, type CatalogService, type ConnectionView } from "@peppa/core"; +import type { Translator } from "@peppa/shared/i18n"; +import { AccessStatus, accessModeText } from "@/components/AccessRequests"; +import { Hidden } from "@/components/cards"; +import { Flash, Notice, PageHeader, Section } from "@/components/common"; +import { Button } from "@/components/ui/button"; +import { Card } from "@/components/ui/card"; +import { Input, Textarea } from "@/components/ui/input"; +import { Workspace } from "@/components/Workspace"; +import { requireUser } from "@/lib/auth"; +import { db } from "@/lib/db"; +import { getT } from "@/lib/i18n"; +import { connectAccessRequestAction, denyAccessRequestAction, grantAccessRequestAction } from "../../../actions"; + +export async function generateMetadata() { + const t = await getT(); + return { title: t("Запрос доступа — FORGE") }; +} + +const SELECT = "h-9 rounded-md border border-input bg-background px-2 text-sm"; + +function Fact({ label, children }: { label: string; children: React.ReactNode }) { + return ( +
+ {label} + {children} +
+ ); +} + +function DoneNotice({ done, check, t }: { done?: string; check?: string; t: Translator }) { + if (done === "denied") return {t("Отказано. Агент получит вашу причину и продолжит без этого сервиса.")}; + if (done !== "granted") return null; + const tail = check === "bad_key" ? t("Но сервис не принял ключ: замените его в разделе «Подключения».") : check === "down" ? t("Сервис сейчас не отвечает — ключ проверится при первом запросе агента.") : ""; + return ( + + {t("Доступ выдан. Агент получил сообщение и продолжит работу; ключ доступа он не видит.")} {tail} + + ); +} + +function ConnectForm({ r, card, t }: { r: AccessRequestView; card: CatalogService | null; t: Translator }) { + const back = `/connections/requests/${r.id}`; + return ( +
    +
  1. + {t("Возьмите ключ доступа")} + {card ? ( + <> + {t.text(card.keyHint)} + + {t("Открыть страницу, где берут ключ")} + + + ) : ( + {t("Он есть в описании сервиса для разработчиков или у того, кто его сделал.")} + )} +
  2. +
  3. + {t("Вставьте его сюда")} +
    + + {(!card || card.baseEditable) && } + + {!card && ( +
    + + +
    + )} + + +
  4. +
+ ); +} + +function ExistingForm({ r, fit, other, t }: { r: AccessRequestView; fit: ConnectionView[]; other: ConnectionView[]; t: Translator }) { + const all = [...fit, ...other]; + if (!all.length) return null; + return ( +
+ + + + + ); +} + +/** PEP-250: the card of an agent's access request — its project's owner only (others: 404). */ +export default async function AccessRequestPage({ params, searchParams }: { params: Promise<{ id: string }>; searchParams: Promise<{ error?: string; done?: string; check?: string }> }) { + const [{ id }, q] = await Promise.all([params, searchParams]); + const user = await requireUser(); + const t = await getT(); + const r = /^\d+$/.test(id) ? await accessRequestForUser(db, user.id, Number(id)) : null; + if (!r) notFound(); + const card = catalogService(r.catalogId); + const { fit, other } = r.status === "open" ? await connectionsForRequest(db, user.id, r) : { fit: [], other: [] }; + return ( + + + + {t("Агент просит доступ к {service}", { service: r.service })}} + crumbs={{t("Подключения")}} + > +

+ {r.status === "open" + ? t("Агенту нужен этот сервис для работы над задачей. Ключ доступа вы вводите один раз, агент его не увидит: запросы выполняет FORGE и записывает их в журнал. Можно и отказать — агент продолжит без сервиса.") + : t("По этому запросу уже есть решение.")} +

+
+ + +
+ + {r.repeats > 0 && {t("агент просил ещё раз: {n}", { n: r.repeats })}} +
+ {r.agentName ?? "—"} + {r.taskKey ? {r.taskKey}{r.taskTitle ? ` — ${r.taskTitle}` : ""} : "—"} + {r.projectName} + + {r.service} + {card && ( + + {t("Документация сервиса")} + + )} + {!card && r.host && {r.host}} + + {accessModeText(r.mode, t)} + {/* The agent's own words: shown as is, never as instructions. */} + {r.purpose} + {r.status === "denied" && {r.reason ?? t("без причины")}} +
+ + {r.status === "open" && ( + <> +
+ + +

+ {r.mode === "write" + ? t("Агенты проекта смогут читать и менять данные в этом сервисе. Изменить или отозвать доступ можно в разделе «Подключения».") + : t("Агенты проекта смогут только читать данные в этом сервисе. Изменить или отозвать доступ можно в разделе «Подключения».")} +

+
+
+ {fit.length + other.length > 0 && ( +
+ + + +
+ )} +
+ +
+ +