UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

196 lines (195 loc) • 8.91 kB
import { classifyMcpFailure, readMcpFailure } from "./mcp-failure.js"; import { UNPROVEN_GATE } from "./mcp-listing-drift.js"; import { resendUndelivered } from "./peer-seat.js"; import { declarerWord } from "./mcp-server-spec.js"; import { revocationTargetName } from "./protocol-revocation.js"; import { readMember } from "./thrown-value.js"; import { inlineUntrusted } from "./untrusted-text.js"; import { foreignLine } from "./protocol-http-auth.js"; export function observedFailure(err, site, health, answer) { const { failure, exchange } = readMcpFailure(err, site); health?.observe?.(exchange); if (answer && failure.authorization !== undefined) health?.owed?.(failure.authorization); return failure; } export function owedByAnswer(err, health) { const owed = classifyMcpFailure(readMember(err, "cause"), { phase: "request" }).authorization; if (owed !== undefined) health.owed?.(owed); } export const IDLE_WATCHDOG_ABORT_REASON = Symbol("mcp-idle-watchdog-abort"); export function armMcpIdleWatchdog(health, idleMs, outerSignal) { const idleController = new AbortController(); let timer; const rearm = () => { if (timer !== undefined) clearTimeout(timer); const armedAt = Date.now(); timer = setTimeout(() => { if (health.pendingElicitations > 0 || health.lastElicitationClosedAt > armedAt) { rearm(); return; } idleController.abort(IDLE_WATCHDOG_ABORT_REASON); }, idleMs); }; rearm(); return { combinedSignal: outerSignal !== undefined ? AbortSignal.any([outerSignal, idleController.signal]) : idleController.signal, idleSignal: idleController.signal, rearm, dispose: () => { if (timer !== undefined) clearTimeout(timer); }, }; } export class ConnectionListing { opened = 0; recorded = -1; entries = []; unprovenNames = new Set(); open() { return this.opened++; } answer(at, entries, incomplete, carried) { const reached = new Set(entries.map((e) => e.name)); const fresh = this.recorded === -1; const before = incomplete ? (fresh ? (carried ?? []) : this.entries).filter((e) => !reached.has(e.name)) : []; const view = before.length > 0 ? [...entries, ...before] : entries; const kept = new Set(before.map((e) => e.name)); const unproven = fresh ? kept : new Set([...this.unprovenNames].filter((n) => kept.has(n))); if (at < this.recorded) return { recorded: false, view, kept, unproven }; this.recorded = at; this.entries = view; this.unprovenNames = unproven; return { recorded: true, view, kept, unproven }; } latest() { return { at: this.recorded, entries: this.entries, unproven: this.unprovenNames }; } } export function reach(link, name, gate) { const live = link.live(); if (live === undefined || live.health.dead) return "gone"; const listed = live.gates().get(name); if (listed === UNPROVEN_GATE) return "unreached"; if (listed !== gate) return "changed"; return live.definitions().get(name)?.outputSchemaUncompilable === true ? "output_schema" : live; } export class Resendable { on; error; constructor(on, error) { this.on = on; this.error = error; } } export async function callThroughLink(link, name, gate, signal, send, gone) { const first = reach(link, name, gate); if (first === "gone") gone(); if (typeof first === "string") return first; const res = await send(first, false); if (!(res instanceof Resendable)) return res; if (!(await settlesFirst(link.recover(res.on), signal))) throw res.error; const next = reach(link, name, gate); if (typeof next === "string" || next === res.on) throw res.error; const again = await send(next, true).catch((err) => { throw resendUndelivered(err) ? res.error : err; }); if (again instanceof Resendable) throw again.error; return again; } const REFUSAL_JUDGES = { listing: () => ({ rule: "each later call to this tool is checked again against the connection's latest listing", standing: "" }), revocation: (declarer) => ({ rule: `each later call to this ${declarer} is checked again against the operator's current revocation list`, standing: `This ${declarer} stays on this run's tool roster. ` }), declaration: () => ({ rule: "each later call to this tool is judged by the declaration of the listing it was mounted from, until a refresh or reconnect of the server mints the tool anew", standing: "" }), connection: (declarer) => ({ rule: `each later call to this ${declarer} is checked again against its connection at that time`, standing: "" }), }; export function refusalScope(judge, at) { const j = REFUSAL_JUDGES[judge](declarerWord(at)); return `${j.standing}This refusal is for this call only: ${j.rule}.`; } export function revokedCallResult(refusal, what, accepted) { const { target, code } = refusal; const declarer = declarerWord(target.protocol); const name = inlineUntrusted(revocationTargetName(target), 120); const stopped = refusal.why === "unreadable" ? `the revocation ledger could not be read for ${declarer} "${name}", which is registered inside the trust boundary` : `${declarer} "${name}" was revoked by the operator`; const text = accepted !== undefined ? `${what} stopped: ${stopped} after it accepted ${accepted.taskId !== undefined ? `task ${accepted.taskId}` : "the task"}. No further status request is sent, so the task's outcome is UNKNOWN — it may still complete on the peer's side, and only the operator can check it there.` : `${refusal.afterSentHop ? `${what} stopped: ${stopped} while the request was being redirected. Its first hop was sent and the redirect was NOT followed, so whether the ${declarer} acted on it is UNKNOWN — only the operator can check it on the ${declarer}'s side.` : `${what} was refused: ${stopped}. The request was NOT sent, so the ${declarer} did not act on it.`} ${refusal.why === "unreadable" ? "A later call is judged again: it goes out once the ledger can be read." : refusalScope("revocation", target.protocol)}`; return { content: [{ type: "text", text }], details: { error: code, code, delivered: accepted !== undefined ? "yes" : refusal.details.delivered, ...(target.protocol === "mcp" ? { server: target.server } : { peer: target.peer }), ...(accepted?.taskId !== undefined ? { taskId: accepted.taskId } : {}), }, terminate: false, isError: true, }; } const LISTING_REFUSAL_CODES = { changed: "mcp.tool_declaration_changed", unreached: "mcp.tool_listing_unreached", output_schema: "mcp.tool_output_schema_invalid", }; export function listingRefusal(refusal, remoteName, server) { const code = LISTING_REFUSAL_CODES[refusal]; return { content: [ { type: "text", text: `The call to tool ${foreignLine(remoteName)} was refused before it was sent: MCP server "${inlineUntrusted(server)}" ${refusal === "changed" ? "no longer declares this tool the way it was mounted (its safety declaration changed, or a complete listing no longer lists it)" : refusal === "unreached" ? "has not listed this tool since it was reconnected (the re-listing stopped before it reached the tool), so whether the server still declares it the way it was mounted is unknown" : "lists this tool with an output schema this client cannot compile, so its structured result could not be checked"}. The server did not execute it. ${refusalScope("listing", "mcp")}`, }, ], details: { error: code, code, delivered: "no", server }, terminate: false, isError: true, }; } function settlesFirst(work, signal) { const settled = work.then(() => true, () => true); if (signal === undefined) return settled; if (signal.aborted) return Promise.resolve(false); return new Promise((resolve) => { const stop = () => resolve(false); signal.addEventListener("abort", stop, { once: true }); void settled.then((v) => { signal.removeEventListener("abort", stop); resolve(v); }); }); } export class Flights { open = new Map(); running(key) { return this.open.get(key); } start(key, run) { const flight = run().finally(() => this.open.delete(key)); this.open.set(key, flight); return flight; } }