UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

48 lines (47 loc) • 1.96 kB
const DECLARED_NAMES = Symbol.for("sema.core.delegationDeclaredNames"); export class DelegationRegistryOccupied extends Error { code = "config.tool_face_control"; detail = { reason: "registry_occupied" }; constructor(why) { super(`The table of declared delegation-tool names (globalThis[Symbol.for("sema.core.delegationDeclaredNames")]) ${why} — a delegation tool mounted under another name than it declares could not be told from a clean mount, so the run does not start. Leave that slot to the engine.`); } } const tableIfAny = () => { const slot = Reflect.get(globalThis, DECLARED_NAMES); if (slot instanceof WeakMap) return slot; if (slot !== undefined) throw new DelegationRegistryOccupied("holds a value that is not the engine's table"); return undefined; }; const tableToBind = () => { const held = tableIfAny(); if (held !== undefined) return held; const fresh = new WeakMap(); if (!Reflect.set(globalThis, DECLARED_NAMES, fresh)) throw new DelegationRegistryOccupied("cannot be written"); return fresh; }; export function bindDelegationName(name, tool) { if (typeof tool.execute === "function") tableToBind().set(tool.execute, name); return tool; } export function carryDelegationName(source, product) { const slot = Reflect.get(globalThis, DECLARED_NAMES); const names = slot instanceof WeakMap ? slot : undefined; const name = names !== undefined && typeof source === "function" ? names.get(source) : undefined; if (name !== undefined && typeof product === "function") names.set(product, name); } export function declaredDelegationNameOf(tool) { const names = tableIfAny(); try { const execute = typeof tool === "object" && tool !== null ? tool.execute : undefined; return typeof execute === "function" ? names?.get(execute) : undefined; } catch { return undefined; } }