UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

78 lines (77 loc) • 3.17 kB
const DECLARED_NAMES = Symbol.for("sema.core.delegationDeclaredNames"); const BACKGROUND_LANES = Symbol.for("sema.core.delegationBackgroundLanes"); export class DelegationRegistryOccupied extends Error { code = "config.tool_face_control"; detail = { reason: "registry_occupied" }; constructor(why, lanes = false) { const slot = lanes ? "sema.core.delegationBackgroundLanes" : "sema.core.delegationDeclaredNames"; super(`The table of declared delegation-tool ${lanes ? "background lanes" : "names"} (globalThis[Symbol.for("${slot}")]) ${why} — ` + `${lanes ? "a delegation tool's background lane could not be told from a synchronous mount" : "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 slotIfAny = (key, isTable) => { const slot = Reflect.get(globalThis, key); if (isTable(slot)) return slot; if (slot !== undefined) throw new DelegationRegistryOccupied("holds a value that is not the engine's table", key === BACKGROUND_LANES); return undefined; }; const namesIfAny = () => slotIfAny(DECLARED_NAMES, (v) => v instanceof WeakMap); const lanesIfAny = () => slotIfAny(BACKGROUND_LANES, (v) => v instanceof WeakSet); const install = (key, table) => { if (!Reflect.set(globalThis, key, table)) throw new DelegationRegistryOccupied("cannot be written", key === BACKGROUND_LANES); return table; }; export function bindDelegationName(name, tool, lane) { if (typeof tool.execute !== "function") return tool; let names = namesIfAny(); if (names === undefined) { const fresh = new WeakMap(); names = install(DECLARED_NAMES, fresh); } names.set(tool.execute, name); if (lane?.background === true) { let lanes = lanesIfAny(); if (lanes === undefined) { const freshLanes = new WeakSet(); lanes = install(BACKGROUND_LANES, freshLanes); } lanes.add(tool.execute); } return tool; } export function carryDelegationName(source, product) { if (typeof source !== "function" || typeof product !== "function") return; const names = Reflect.get(globalThis, DECLARED_NAMES); const name = names instanceof WeakMap ? names.get(source) : undefined; if (name === undefined) return; names.set(product, name); const lanes = Reflect.get(globalThis, BACKGROUND_LANES); if (lanes instanceof WeakSet && lanes.has(source)) lanes.add(product); } export function delegationHasBackgroundLane(tool) { const lanes = lanesIfAny(); try { const execute = tool.execute; return typeof execute === "function" && lanes?.has(execute) === true; } catch { return false; } } export function declaredDelegationNameOf(tool) { const names = namesIfAny(); try { const execute = typeof tool === "object" && tool !== null ? tool.execute : undefined; return typeof execute === "function" ? names?.get(execute) : undefined; } catch { return undefined; } }