76 lines
4.5 KiB
TypeScript
76 lines
4.5 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, grantAccessByButton, grantAccessFromExisting, isProjectPaused, listConnections, listSessions, logEvent, type AccessGrantChoice, type AccessRequestView, type ConnectionInput, type GrantTerm } 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"];
|
|
|
|
// i18n-ignore: text for the agent
|
|
const TERM_FOR_AGENT: Record<GrantTerm, string> = { "1h": "на 1 час", "1d": "на 1 день", "7d": "на 7 дней", forever: "до отзыва" };
|
|
|
|
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.rights ?? (r.mode === "write" ? "full" : "read")) === "full" ? "чтение и запись" : "чтение";
|
|
const term = r.term ? ` ${TERM_FOR_AGENT[r.term]}` : "";
|
|
return `Доступ выдан (запрос #${r.id}): владелец разрешил ${r.service} — ${what}${term}. Посмотри 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, choice: AccessGrantChoice = {}): Promise<AccessRequestView> {
|
|
const r = await grantAccessFromExisting(db, userId, id, connectionId, choice);
|
|
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 }, choice: AccessGrantChoice = {}) {
|
|
const out = await connectAndGrantAccess(db, userId, id, i, choice);
|
|
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;
|
|
}
|
|
|
|
/** PEP-261: «Дать: чтение / полные права» + term by a button (Telegram, «Агенты просят доступ»). */
|
|
export async function grantAccessRequestByButton(db: Db, userId: number, id: number, choice: AccessGrantChoice): Promise<AccessRequestView> {
|
|
const { request, connection } = await grantAccessByButton(db, userId, id, choice);
|
|
await tellAgentAboutAccess(db, request, connection.slug);
|
|
return request;
|
|
}
|