peppa/packages/runner/src/access-requests.ts

65 lines
3.6 KiB
TypeScript

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