PEP-250: запросы доступа — таблица, ядро, MCP агента, кнопка бота, карточка владельца, переводы

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
peppa-bot 2026-11-24 11:22:45 +00:00
parent b331305f4a
commit 84f50b1c5b
17 changed files with 6500 additions and 11 deletions

View File

@ -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?.();

View File

@ -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 () => {

View File

@ -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:
</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) => (

View 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>
);
}

View 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>
);
}

View 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))!;
}

View File

@ -555,6 +555,8 @@ export interface AgentConnection {
slug: string;
/** Catalog service name, null = own service. */
service: string | null;
/** PEP-250: the catalog card id, null = own service. */
catalogId: string | null;
baseUrl: string;
docsUrl: string | null;
readMode: GrantMode;
@ -582,7 +584,7 @@ export async function agentConnections(db: Db, sessionId: number): Promise<Agent
for (const r of rows) {
if (r.agentId != null && r.agentId !== s.agentId) continue;
const card = catalogService(r.c.catalogId);
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 };
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 };
c.operations = [...new Set([...c.operations, ...r.operations])];
c.readMode = widest(c.readMode, r.readMode);
c.writeMode = widest(c.writeMode, r.writeMode);
@ -645,7 +647,7 @@ export interface ConnectionCall {
export type ConnectionResult =
| { ok: true; status: number; contentType: string | null; body: string; truncated: boolean }
| { ok: false; reason: ConnectionReason; status?: number };
| { ok: false; reason: ConnectionReason; status?: number; service?: { catalogId: string | null; baseUrl: string }; kind?: "read" | "write" };
/** One outbound request, injectable in tests. */
export type ConnectionFetch = (o: { url: URL; method: string; headers: Record<string, string>; body: Buffer | null }) => Promise<{ status: number; contentType: string | null; body: Buffer; truncated: boolean; location?: boolean }>;
@ -739,7 +741,9 @@ export async function callConnection(db: Db, call: ConnectionCall, o: { fetch?:
};
const deny = async (reason: ConnectionReason): Promise<ConnectionResult> => {
await record("denied", reason, null);
return { ok: false, reason };
// PEP-250: which service and what kind of request — a missing grant becomes an access request.
const clean = cleanPath(rawPath);
return { ok: false, reason, ...(conn ? { service: { catalogId: conn.catalogId, baseUrl: conn.baseUrl } } : {}), ...(clean && conn ? { kind: classifyRequest(conn.catalogId, method, clean.path) } : {}) };
};
if (!s) return { ok: false, reason: "no_session" };

View File

@ -110,6 +110,7 @@ export * from "./accept-digest.ts";
export * from "./connections.ts";
export * from "./connection-journal.ts";
export * from "./connection-catalog.ts";
export * from "./access-requests.ts";
export * from "./edge-dns.ts";
export * from "./retention.ts";
export * from "./history.ts";

View 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`);

File diff suppressed because it is too large Load Diff

View File

@ -218,6 +218,13 @@
"when": 1795512094088,
"tag": "0030_access_hub_journal",
"breakpoints": true
},
{
"idx": 31,
"version": "6",
"when": 1795518856978,
"tag": "0031_access_requests",
"breakpoints": true
}
]
}

View File

@ -747,6 +747,37 @@ export const connectionLog = sqliteTable(
(t) => [index("connection_log_owner").on(t.ownerId, t.id), index("connection_log_session_created").on(t.sessionId, t.createdAt)],
);
/** PEP-250: an agent asks the project's owner for access to an external service. */
export const accessRequests = sqliteTable(
"access_requests",
{
id: integer("id").primaryKey({ autoIncrement: true }),
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
// The project's owner when asked: only they see and decide it.
ownerId: integer("owner_id").notNull().references(() => users.id, { onDelete: "cascade" }),
taskId: integer("task_id").references(() => tasks.id, { onDelete: "set null" }),
sessionId: integer("session_id").references(() => sessions.id, { onDelete: "set null" }),
agentId: integer("agent_id").references(() => agents.id, { onDelete: "set null" }),
agentName: text("agent_name"),
// A catalog card (core/connection-catalog.ts) or an https origin of an own service.
catalogId: text("catalog_id"),
host: text("host"),
// catalog_id ?? host: one open request per project × service.
serviceKey: text("service_key").notNull(),
purpose: text("purpose").notNull(),
mode: text("mode").$type<"read" | "write">().notNull().default("read"),
status: text("status").$type<"open" | "granted" | "denied" | "cancelled">().notNull().default("open"),
reason: text("reason"),
connectionId: integer("connection_id").references(() => connections.id, { onDelete: "set null" }),
repeats: integer("repeats").notNull().default(0),
decidedBy: integer("decided_by").references(() => users.id, { onDelete: "set null" }),
decidedAt: integer("decided_at", { mode: "timestamp_ms" }),
createdAt: createdAt(),
updatedAt: updatedAt(),
},
(t) => [index("access_requests_project_service").on(t.projectId, t.serviceKey, t.status), index("access_requests_owner").on(t.ownerId, t.status)],
);
/** PEP-26: the reviewer agent of a project (no row = off). */
export const reviewSettings = sqliteTable("review_settings", {
projectId: integer("project_id").primaryKey().references(() => projects.id, { onDelete: "cascade" }),

View File

@ -51,6 +51,11 @@ import {
productOnlySecret,
agentConnections,
callConnection,
cancelAccessRequest,
catalogFromSecretName,
requestAccess,
sessionAccessRequests,
type AccessRequestView,
guardUntrusted,
sessionIsolated,
CONNECTION_REASON_TEXT,
@ -406,7 +411,7 @@ export function createAgentServer(db: Db, opts: AgentServerOptions = {}): McpSer
// PEP-234 Access Hub: the owner's external services, reached only through Peppa's gateway.
tool(
"list_connections",
"List the external services (Access Hub connections) you may use in this session: short name to call it by (e.g. `stripe`), the service, its address and API docs, whether you may read and write («at once», or «asks the owner» — such calls are refused until owner confirmations exist), extra fine-grained operations («METHOD /path-prefix») and whether the key works. Their keys are NOT available to you and never will be: call with call_connection (in code mode: peppa.connections.call(\"stripe\", {method, path, body})) and FORGE adds the key itself. Anything not allowed is refused. Missing an access? Tell the owner through ask_pm which service and what for — they grant it in «Подключения».",
"List the external services (Access Hub connections) you may use in this session: short name to call it by (e.g. `stripe`), the service, its address and API docs, whether you may read and write («at once», or «asks the owner» — such calls are refused until owner confirmations exist), extra fine-grained operations («METHOD /path-prefix») and whether the key works. Their keys are NOT available to you and never will be: call with call_connection (in code mode: peppa.connections.call(\"stripe\", {method, path, body})) and FORGE adds the key itself. Anything not allowed is refused. Missing an access? request_access (service + purpose) — the owner gets a link, adds the key once, and you are told when it is granted. Never ask for an external service key as a project secret for your own work.",
{},
async () => {
if (!sessionId) return "Connections work only in sessions started by FORGE.";
@ -440,16 +445,76 @@ export function createAgentServer(db: Db, opts: AgentServerOptions = {}): McpSer
},
async ({ connection, method, path, body, content_type }) => {
const r = await callConnection(db, { sessionId, connection, method, path, body, contentType: content_type });
if (!r.ok) throw new PeppaError(`Refused: ${stripAsIs(CONNECTION_REASON_TEXT[r.reason])} (${r.reason})${r.status ? `, HTTP ${r.status}` : ""}`);
if (!r.ok) {
const refused = `Refused: ${stripAsIs(CONNECTION_REASON_TEXT[r.reason])} (${r.reason})${r.status ? `, HTTP ${r.status}` : ""}`;
// PEP-250: no grant for this service → the refusal becomes an access request by itself.
const asked = await autoRequest(r, String(connection), method, path).catch(() => null);
throw new PeppaError(asked ? `${refused}\n${asked}` : refused);
}
const s = await getSession(db, sessionId!);
const data = await guardUntrusted(db, { projectId: s.projectId, taskId: s.taskId, sessionId, source: `подключение ${String(connection)}`, text: r.body });
return [`HTTP ${r.status}${r.contentType ? ` · ${r.contentType}` : ""}${r.truncated ? " · truncated at 256 KB" : ""}`, data].join("\n");
},
);
// ── PEP-250: the agent asks the owner for access itself ─────────────────────
const requestLine = (r: AccessRequestView) =>
`- #${r.id} ${r.service} (${r.mode}) — ${r.status === "open" ? "open, waiting for the owner" : r.status === "granted" ? "GRANTED — see list_connections" : r.status === "denied" ? `DENIED${r.reason ? `: ${r.reason}` : " (no reason given)"}` : "cancelled"}${r.taskKey ? ` · ${r.taskKey}` : ""}${r.repeats ? ` · asked ${r.repeats + 1} times` : ""}\n purpose: ${r.purpose}`;
const AUTO_REASONS = new Set(["no_grant", "read_denied", "write_denied", "operation_denied"]);
async function autoRequest(r: Extract<Awaited<ReturnType<typeof callConnection>>, { ok: false }>, connection: string, method: string, path: string): Promise<string | null> {
if (!sessionId) return null;
const service = AUTO_REASONS.has(r.reason) && r.service ? r.service : r.reason === "unknown_connection" ? { catalogId: connection.trim().toLowerCase(), baseUrl: "" } : null;
if (!service) return null;
const purpose = `Агент обратился: ${method.toUpperCase()} ${String(path).split("?")[0]!.slice(0, 120)}`;
const mode = (r.kind ?? (method.toUpperCase() === "GET" ? "read" : "write")) as "read" | "write";
const got = service.catalogId
? await requestAccess(db, { sessionId, service: service.catalogId, host: service.baseUrl || null, purpose, mode }, { auto: true }).catch(() => null)
: await requestAccess(db, { sessionId, host: service.baseUrl, purpose, mode }, { auto: true }).catch(() => null);
if (!got) return null;
return `Access requested from the owner (request #${got.request.id}${got.created ? "" : ", added to the open one"}). Wait for the decision or go on without it (a mock, another way); you will get a message when it is granted or denied. Better: call request_access yourself with a clear purpose.`;
}
tool(
"request_access",
"Ask the project's owner for access to an external service you need for your work (Access Hub). Name a catalog service (`service`: stripe, github, sendgrid… — the id or the name) or an own service's address (`host`, https only, open internet), say in plain words what for (`purpose` — the owner decides by it) and whether you need to change anything there (`mode`: read | write). The owner gets one message with a link, adds the key once (you never see it) or refuses with a reason; you get a message either way, and a stopped story comes back to work. One open request per service and project: asking again adds to it. Don't put external service keys in project secrets for your own work — ask here. Then go on with what you can (a mock) instead of waiting.",
{
service: z.string().optional().describe("Catalog service id or name, e.g. stripe"),
host: z.string().optional().describe("Address of a service not in the catalog, e.g. https://api.example.com"),
purpose: z.string().min(3).describe("What for, plainly, ≤ 500 chars: «проверить статус оплаты заказа в тестовом режиме»"),
mode: z.enum(["read", "write"]).optional().describe("read (default) — look at data; write — create, change, delete, send"),
},
async ({ service, host, purpose, mode }) => {
const { request, created } = await requestAccess(db, { sessionId, service, host, purpose, mode });
return created
? `Requested: #${request.id} ${request.service} (${request.mode}). The owner got a message. Go on without it (a mock, another way) — you will be told when it is granted or denied; list_requests shows the state.`
: `An open request for ${request.service} already exists (#${request.id}); your ask was added to it (mode now: ${request.mode}). The owner is not messaged again. Go on without it meanwhile.`;
},
);
tool(
"list_requests",
"Your project's access requests (request_access): open, granted (then call it via list_connections / call_connection), denied with the owner's reason, cancelled.",
{},
async () => {
const list = await sessionAccessRequests(db, sessionId);
if (!list.length) return "No access requests in this project.";
return ["Access requests of this project (newest first):", ...list.map(requestLine)].join("\n");
},
);
tool(
"cancel_request",
"Cancel an open access request you no longer need (e.g. found another way).",
{ id: z.number().int().describe("Request number from list_requests") },
async ({ id }) => {
const r = await cancelAccessRequest(db, sessionId, id);
return `Cancelled: #${r.id} ${r.service}.`;
},
);
tool(
"declare_needs",
"Declare what the product's OWNER must give before the product works for real instead of on mocks/demo data: an API key, an account, credentials. Call it BEFORE moving the story to review whenever the story needs something only the owner has. The owner (a product manager, not a programmer) gets the list in plain words in the project chat and on the «Ваш продукт» card, with a field to paste each key; an item with `secret` closes itself once the owner stores that secret, and FORGE hands all project secrets to the deployed product as env vars of the same name and restarts it. Write title/why/how in the owner's language, no jargon. Items add up across stories (same secret or title = same item). Returns the whole list with states.",
"Declare what the product's OWNER must give before the product works for real instead of on mocks/demo data: an API key, an account, credentials. Call it BEFORE moving the story to review whenever the story needs something only the owner has. The owner (a product manager, not a programmer) gets the list in plain words in the project chat and on the «Ваш продукт» card, with a field to paste each key; an item with `secret` closes itself once the owner stores that secret, and FORGE hands all project secrets to the deployed product as env vars of the same name and restarts it. A service only YOU need for your work (not the product) — mark it use: agent (or call request_access): the owner connects it in Access Hub and you never see the key. Write title/why/how in the owner's language, no jargon. Items add up across stories (same secret or title = same item). Returns the whole list with states.",
{
task: taskArg.optional().describe("The story that needs it (for the record)"),
needs: z
@ -459,15 +524,33 @@ export function createAgentServer(db: Db, opts: AgentServerOptions = {}): McpSer
why: z.string().optional().describe("What does not work without it, plainly: «без него ответы — вымышленные примеры»"),
how: z.string().optional().describe("Where to get it, step by step for a non-programmer"),
secret: z.string().optional().describe("Env name the product reads it from (A–Z, 0–9, _), e.g. ANTHROPIC_API_KEY. Omit for things that are not a key (the owner ticks them off)"),
use: z.enum(["product", "agent"]).optional().describe("product (default) — the deployed product needs it; agent — only YOU need the service for your work: it becomes an Access Hub request (request_access), not a project secret"),
service: z.string().optional().describe("With use: agent — catalog service id (stripe…); default: guessed from `secret`"),
}),
)
.min(1)
.max(10),
},
async ({ task, needs }) => {
async ({ task, needs: asked }) => {
const ref = task ? await resolve(task) : null;
const session = sessionId ? await getSession(db, sessionId) : null;
const p = ref?.project ?? (session ? await getProject(db, session.projectKey) : await projectOrDefault());
// PEP-250: a service only the agent needs goes through Access Hub — the key never reaches the agent's env.
const viaHub: string[] = [];
for (const n of asked.filter((x) => x.use === "agent")) {
const service = n.service ?? catalogFromSecretName(n.secret)?.id;
if (!service) {
viaHub.push(`- «${n.title}»: not a catalog service — call request_access with its address (host) instead.`);
continue;
}
const got = await requestAccess(db, { sessionId, service, purpose: n.why || n.title, mode: "read" }).then(
(r) => `- «${n.title}»: access request #${r.request.id} (${r.request.service})${r.created ? " sent to the owner" : " — already open"}. Ask write access with request_access if you need it.`,
(e) => `- «${n.title}»: ${(e as Error).message}`,
);
viaHub.push(got);
}
const needs = asked.filter((x) => x.use !== "agent").map(({ use: _u, service: _s, ...n }) => n);
if (!needs.length) return ["Nothing added to the product's list. Access Hub:", ...viaHub].join("\n");
const { added, all } = await declareNeeds(db, p.id, needs, { source: "agent", story: ref?.key ?? null });
if (added.length) {
const chat = await ensureProjectChat(db, p.id);
@ -475,7 +558,7 @@ export function createAgentServer(db: Db, opts: AgentServerOptions = {}): McpSer
await sayInDiscussion(db, p, chat.id, text, session?.agentName ?? null, { agent: true });
}
const line = (n: (typeof all)[number]) => `- ${n.open ? "⏳ ждёт владельца" : "✅ дано"}: ${n.title}${n.secret ? ` ($${n.secret})` : ""}`;
return [`Список «чтобы заработало по-настоящему» проекта ${p.key}:`, ...all.map(line), added.length ? `Владельцу отправлено сообщение о новых пунктах (${added.length}).` : "Новых пунктов нет — владельцу ничего не отправлено.", "Пока пункт открыт, продукт работает на моке: в резюме PR и в сообщении о готовности так и скажи. Служебных полей (токены, ключи) на экране пользователя быть не должно."].join("\n");
return [...(viaHub.length ? ["Access Hub:", ...viaHub, ""] : []), `Список «чтобы заработало по-настоящему» проекта ${p.key}:`, ...all.map(line), added.length ? `Владельцу отправлено сообщение о новых пунктах (${added.length}).` : "Новых пунктов нет — владельцу ничего не отправлено.", "Пока пункт открыт, продукт работает на моке: в резюме PR и в сообщении о готовности так и скажи. Служебных полей (токены, ключи) на экране пользователя быть не должно."].join("\n");
},
);

View 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;
}

View File

@ -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";

View File

@ -163,4 +163,47 @@ 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",
};

View File

@ -163,4 +163,47 @@ 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}",
"Откройте запрос, чтобы подключить сервис или отказать.": "Сервисті қосу немесе бас тарту үшін сұрауды ашыңыз.",
"Агент просит доступ": "Агент қолжетімділік сұрайды",
"Запрос не найден": "Сұрау табылмады",
"По этому запросу уже есть решение": "Бұл сұрау бойынша шешім бұрыннан бар",
};