UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

52 lines (51 loc) • 2.53 kB
import { AsyncLocalStorage } from "node:async_hooks"; import { ENGINE_ORIGIN } from "./kernel/index.js"; const store = new AsyncLocalStorage(); export function extensionCallOf(bus, toolCallId) { const c = store.getStore(); return c !== undefined && c.live && c.bus === bus && (toolCallId === undefined || c.toolCallId === toolCallId) ? c : undefined; } export function callParkRoute(legParks, bus, toolCallId) { return legParks && extensionCallOf(bus, toolCallId) === undefined; } export function requesterOf(bus, toolCallId) { const c = extensionCallOf(bus, toolCallId); return c !== undefined ? { requestedBy: Object.freeze({ kind: "extension", name: c.caller.origin.plugin }) } : {}; } export function noteExtensionCallDenied(bus, toolCallId) { const c = store.getStore(); if (c !== undefined && c.live && c.bus === bus && c.toolCallId === toolCallId) c.denied = true; } export function noteExtensionCallLaunched(bus, toolCallId, launched) { const c = store.getStore(); if (c !== undefined && c.live && c.bus === bus && c.toolCallId === toolCallId && c.launched === undefined) c.launched = Object.freeze({ agentId: launched.agentId, model: launched.model }); } export async function runExtensionCall(bus, toolCallId, door, caller, pipeline) { const call = { bus, toolCallId, door, caller, live: true, denied: false }; try { return await store.run(call, () => pipeline(call)); } finally { call.live = false; } } export function legBusOf(bus, report) { const leg = { records: bus.records, mounted: () => bus.mounted(), hasHandlers: (event, participant) => bus.hasHandlers(event, participant), dispatch: (event, e, options) => { const c = store.getStore(); if (c === undefined || c.bus !== leg || options.frames !== undefined) return bus.dispatch(event, e, options); if (c.live) return bus.dispatch(event, e, { ...options, frames: c.caller.frames, origin: c.caller.origin }); const reason = `${event}: raised under extension "${c.caller.origin.plugin}"'s call ${c.toolCallId}, which has ended — an event is not raised under a call that is over`; report(new Error(`engine: ${reason} — the dispatch was not run`)); return Promise.resolve(Object.freeze({ kind: "failed", registration: ENGINE_ORIGIN.plugin, cause: "violation", reason, skipped: Object.freeze([]) })); }, }; return leg; }