UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

295 lines (294 loc) • 11.7 kB
import { rootSessionAddressKeyOf } from "../agents/root-session-lane.js"; import { canonicalize } from "./canonical-json.js"; import { ConnectionListing } from "./mcp-server-link.js"; import { carrierOf, peerSeatIdentityOf } from "./peer-seat.js"; import { principalNameFault, readPrincipal } from "./principal-name.js"; const ENGINE_DIALS = new WeakMap(); export function recordEngineDial(client, key) { ENGINE_DIALS.set(client, { key, entered: false }); } const UNPOOLED = Object.freeze({ recalled: undefined, settle: () => false }); function supersede(memo) { memo.floor = memo.opened; delete memo.failed; } export class McpConnectionPool { entries = new Map(); dialing = new Map(); memo = new Map(); generation = new Map(); leased = 0; shut = false; sessionId; constructor(opts) { this.sessionId = opts?.sessionId; } static keyOf(spec, principal, kind, startupMs, isolationScope, seat) { const rest = Object.fromEntries(Object.keys(spec.transport).filter((k) => k !== "kind").map((k) => [k, Reflect.get(spec.transport, k)])); const fingerprint = spec.fingerprint; const identity = [spec.name, kind ?? null, rest, principal ?? null]; if (fingerprint !== undefined) identity.push(fingerprint); if (startupMs !== undefined) identity.push({ startupTimeoutMs: startupMs }); if (isolationScope !== undefined && isolationScope !== principal) identity.push({ isolationScope }); const source = peerSeatIdentityOf(seat); if (source !== null) identity.push({ peerSeat: source }); return canonicalize(identity); } async acquire(key, dial, opts) { if (this.shut) return undefined; opts?.signal?.throwIfAborted(); const held = this.entries.get(key); if (opts?.fresh === true || (held !== undefined && carrierOf(held.client)?.expired() === true)) this.detach(key); let entry = this.entries.get(key); if (entry === undefined || entry.closed) { let pending = this.dialing.get(key); if (pending === undefined) { const stop = new AbortController(); const started = this.dialNew(key, this.generation.get(key) ?? 0, () => dial(stop.signal)); const own = { promise: started, waiters: 0, stop }; pending = own; this.dialing.set(key, own); const settled = () => { if (this.dialing.get(key) === own) this.dialing.delete(key); }; void started.then(settled, settled); } entry = await this.waitOn(key, pending, opts?.signal); } return this.lease(entry); } async waitOn(key, dial, signal) { dial.waiters++; let waiting = true; const stopWaiting = () => { if (waiting) dial.waiters--; waiting = false; }; try { if (signal === undefined) return await dial.promise; return await new Promise((resolve, reject) => { const walkAway = () => { stopWaiting(); if (dial.waiters === 0) this.abandon(key, dial, signal.reason); reject(signal.reason); }; signal.addEventListener("abort", walkAway, { once: true }); dial.promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", walkAway)); }); } finally { stopWaiting(); } } abandon(key, dial, reason) { if (this.dialing.get(key) === dial) this.dialing.delete(key); dial.stop.abort(reason); dial.promise.then((entry) => { if (entry.refs > 0 || entry.closed) return; entry.current = false; if (this.entries.get(key) === entry) this.entries.delete(key); void entry.client.close().catch(() => undefined); }, () => undefined); } detach(key) { this.dropDial(key); const e = this.entries.get(key); if (e !== undefined) { e.current = false; this.entries.delete(key); } } dropDial(key) { this.generation.set(key, (this.generation.get(key) ?? 0) + 1); this.dialing.delete(key); } attempt(key, server, opts) { if (this.shut) return UNPOOLED; const memo = this.memo.get(key) ?? { server, opened: 0, floor: 0 }; this.memo.set(key, memo); if (opts?.fresh === true) supersede(memo); const recalled = memo.failed !== undefined && !this.liveUnder(key) ? memo.failed : undefined; if (recalled !== undefined) return { recalled, settle: () => false }; const place = memo.opened++; let open = true; return { recalled, settle: (outcome) => { if (!open) return false; open = false; const failed = outcome !== "connected" && outcome !== "unkept"; if (outcome === "unkept" || place < memo.floor || (failed && this.liveUnder(key))) return failed && memo.failed !== undefined; memo.floor = place + 1; if (failed) memo.failed = { reason: outcome.failed }; else delete memo.failed; return failed; }, }; } forget(server) { let forgotten = false; for (const [key, memo] of this.memo) { if (memo.server !== server) continue; if (memo.failed !== undefined) forgotten = true; supersede(memo); if (this.dialing.has(key)) this.dropDial(key); } return forgotten; } get idle() { return this.leased === 0 && this.dialing.size === 0; } liveUnder(key) { const e = this.entries.get(key); return e !== undefined && !e.closed; } close() { this.shut = true; for (const e of [...this.entries.values()]) if (e.refs === 0 && !e.closed) void e.client.close().catch(() => undefined); } get live() { let n = 0; for (const e of this.entries.values()) if (!e.closed) n++; return n; } async dialNew(key, generation, dial) { const client = await dial(); const dialled = ENGINE_DIALS.get(client); if (dialled === undefined || dialled.key !== key || dialled.entered) { throw Object.assign(new Error("McpConnectionPool: the dial answered a connection the engine did not dial for this declaration (a client built elsewhere, dialled for another declaration or principal, or already held by a pool entry) — refused, the pool keeps nothing of it; the pool holds only connections the engine dials itself"), { code: "config.mcp_pool_foreign_connection" }); } dialled.entered = true; const entry = { client, listing: new ConnectionListing(), refs: 0, listeners: new Set(), current: true, closed: false }; client.onclose = () => { entry.closed = true; if (this.entries.get(key) === entry) this.entries.delete(key); for (const fn of [...entry.listeners]) { try { fn(); } catch { } } }; if ((this.generation.get(key) ?? 0) === generation) this.entries.set(key, entry); else entry.current = false; return entry; } lease(entry) { entry.refs++; this.leased++; const mine = new Set(); let released = false; const lease = { client: entry.client, listing: entry.listing, onClose: (fn) => { mine.add(fn); entry.listeners.add(fn); }, release: async () => { if (released) return; released = true; for (const fn of mine) entry.listeners.delete(fn); entry.refs--; this.leased--; if (entry.refs > 0) return; entry.current = false; for (const [k, v] of this.entries) if (v === entry) this.entries.delete(k); await entry.client.close().catch(() => undefined); }, }; return lease; } } export class SessionMcpPools { pools = new Map(); static CAP = 1024; of(root, principal, seat) { const address = rootSessionAddressKeyOf(root); if (address === undefined) return undefined; const person = principalOf(principal); const source = peerSeatIdentityOf(seat); const key = canonicalize([address, person, source]); const held = this.pools.get(key) ?? { pool: new McpConnectionPool({ sessionId: root.sessionId }), principal: person, seat: source }; this.pools.delete(key); this.pools.set(key, held); for (const [k, p] of this.pools) { if (this.pools.size <= SessionMcpPools.CAP) break; if (k !== key && p.pool.idle) this.pools.delete(k); } return held.pool; } forget(sessionId, principal, seat, server) { const person = principalOf(principal); const source = peerSeatIdentityOf(seat); let forgotten = false; for (const held of this.pools.values()) if (held.pool.sessionId === sessionId && held.principal === person && held.seat === source && held.pool.forget(server)) forgotten = true; return forgotten; } } function principalOf(principal) { const reading = readPrincipal(principal); return reading.kind === "name" ? reading.name : null; } const PROCESS_POOLS = new SessionMcpPools(); export function processSessionMcpPools() { return PROCESS_POOLS; } export function forgetSessionMcpFailure(pools, request, seat) { const read = (field) => { const value = request?.[field]; if (typeof value !== "string" || value.length === 0) { throw Object.assign(new Error(`forgetMcpFailure: request.${field} must be a non-empty string (got ${value === null ? "null" : typeof value === "string" ? "an empty string" : typeof value}) — nothing was forgotten`), { code: "config.invalid_argument", detail: { field: `ForgetMcpFailureRequest.${field}` } }); } return value; }; const sessionId = read("sessionId"); const server = read("server"); const principal = request.principal; const person = readPrincipal(principal); if (person.kind === "invalid") { throw Object.assign(new Error(`forgetMcpFailure: request.principal must be a principal name when present (got ${principalNameFault(principal)}) — omit it for tasks that run under no principal; nothing was forgotten`), { code: "config.invalid_argument", detail: { field: "ForgetMcpFailureRequest.principal" } }); } return { server, outcome: pools.forget(sessionId, person.kind === "name" ? person.name : undefined, seat, server) ? "forgotten" : "none_remembered" }; }