// PEP-235: the owner's «Разрешить» / «Отклонить» on a gateway call that waits for confirmation. // The decision is core's (decideApproval: the connection's owner only, once, within the term). // Allowed and no agent call waiting → the call runs right here, once (claim in core). The agent // learns the outcome from its waiting call, from get_call, or — a live agent of the story — from // a message (approvalDeliveryTick). Paused projects wake nobody: the outcome waits in get_call. import { approvalAgentNote, approvalTick, decideApproval, isProjectPaused, listSessions, markApprovalDelivered, runApproval, undeliveredApprovals, type ApprovalGateway, type ApprovalView } from "@peppa/core"; import type { Db } from "@peppa/db"; import { sendToSession } from "./sessions.ts"; export async function decideConnectionApproval(db: Db, userId: number, id: number, allow: boolean, o: { via?: string; gateway?: ApprovalGateway } = {}): Promise { const { approval, waiting } = await decideApproval(db, userId, id, allow, { via: o.via }); if (allow && !waiting) await runApproval(db, id, { gateway: o.gateway }); await approvalDeliveryTick(db).catch(() => null); return approval; } /** The outcome of decided calls to their live agents (once; no live agent — get_call keeps it). */ export async function approvalDeliveryTick(db: Db, o: { now?: Date } = {}): Promise { const now = o.now ?? new Date(); let told = 0; for (const row of await undeliveredApprovals(db, now)) { if (await isProjectPaused(db, row.projectId)) continue; const live = (await listSessions(db, { active: true, ...(row.taskId != null ? { taskId: row.taskId } : {}) })).find((s) => (row.taskId != null ? true : s.id === row.sessionId)); if (!live) continue; try { await sendToSession(db, live.id, approvalAgentNote(row)); await markApprovalDelivered(db, row.id, now); told++; } catch {} } return told; } /** Watchdog: expire, cut interrupted runs, run approved calls nobody waits for, tell the agents. */ export async function connectionApprovalTick(db: Db, o: { now?: Date; gateway?: ApprovalGateway } = {}): Promise { await approvalTick(db, o); await approvalDeliveryTick(db, o); }