UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

501 lines (500 loc) • 25.2 kB
import { TOOL_CATALOG_ENTRIES } from "./tool-catalog-entries.js"; import { writesProtectedPath } from "./tool-registry.js"; export const TOOL_MOUNT_FACTS = Object.freeze([ "runner.self", "leg.parentNotify", "leg.peerLane", "leg.taskNotification", "leg.session", "leg.backgroundAgents", "leg.startersWithheld", "env.hands", "env.performsIo", "env.modelShell", "env.backgroundShell", "env.scheduler", "spec.enableBlockedReport", "spec.planMode", "spec.interactiveTools.on", "spec.interactiveTools.off", "spec.planFile", "spec.selfOrchestration", "spec.outputSchema", "spec.handsReadOnly", "spec.runLedger", "spec.mcp", "spec.advisorModel", "spec.selector", "seat.checkpoint", "seat.workflows", "seat.offload", "seat.offloadBytes", "seat.lsp", "seat.artifact", "seat.question", "seat.sharedMemory", "seat.memoryEngine", "seat.peerTasks", "caps.allowWorkflows", "model.gate", "listing.skills", "listing.mcp", "listing.mcp.resources", "listing.a2a", "artifact.verdict", "advisor.route", "lsp.readFace", "names.declared", "names.occupied.sharedMemory", "names.occupied.memoryEngine", "names.deferred", "names.retracted", ]); const FACT_SET = new Set(TOOL_MOUNT_FACTS); const isMountFact = (k) => FACT_SET.has(k); export const TOOL_MOUNT_SEGMENTS = Object.freeze(["caller", "synthetic", "workflow", "output", "protocol", "hands", "delegation", "question", "scheduler", "lsp", "artifact", "context", "advisor", "engine"]); export const TOOL_MOUNT_FAMILIES = Object.freeze(["caller", "mcp", "mcp-resources", "a2a"]); const F = (fact) => ({ fact }); const NOT = (not) => ({ not }); const ALL = (...all) => ({ all }); const ANY = (...any) => ({ any }); const ROW = (row) => ({ row }); const VALVE = (valve, aliases) => (aliases === undefined ? { valve } : { valve, aliases }); const DECLARED = (declared, viaAlias) => (viaAlias === undefined ? { declared } : { declared, viaAlias }); const HANDS = F("env.hands"); const WRITES = ALL(HANDS, NOT(F("spec.handsReadOnly"))); const SHELL = ALL(HANDS, F("env.performsIo")); const FULL_SHELL = ALL(SHELL, NOT(F("spec.handsReadOnly"))); const BACKGROUND = ALL(FULL_SHELL, F("env.modelShell"), F("env.backgroundShell")); const DELEGATION = ANY(BACKGROUND, ROW("workflow"), F("leg.backgroundAgents")); const PLAN_PAIR = ALL(F("spec.planMode"), NOT(F("spec.interactiveTools.off")), ANY(F("spec.interactiveTools.on"), F("seat.checkpoint"))); const ENTRY_BY_ID = new Map(TOOL_CATALOG_ENTRIES.map((e) => [e.id, e])); const entryOf = (id) => { const e = ENTRY_BY_ID.get(id); if (e === undefined) throw mismatch(`mount row "${id}" names no catalog definition`); return e; }; const namesOf = (e) => [e.name, ...(e.face.aliases ?? [])]; const SHARED_MEMORY_IDS = ["memory-list", "memory-read"]; const ENGINE_MEMORY_IDS = ["memory-search", "memory-get", "memory-index"]; const LIST_AGENTS = entryOf("list-agents"); const SEND_USER_MESSAGE = entryOf("send-user-message"); export const TOOL_MOUNT_RULES = Object.freeze([ { id: "report-blocked", segment: "synthetic", tag: "always", when: F("spec.enableBlockedReport") }, { id: "report-findings", segment: "synthetic", tag: "always", when: NOT(DECLARED("ReportFindings", true)) }, { id: "exit-plan-mode", segment: "synthetic", tag: "optional", when: ALL(PLAN_PAIR, NOT(F("spec.planFile"))) }, { id: "exit-plan-mode-file", segment: "synthetic", tag: "optional", when: ALL(PLAN_PAIR, F("spec.planFile")) }, { id: "enter-plan-mode", segment: "synthetic", tag: "optional", when: ALL(PLAN_PAIR, F("seat.checkpoint")) }, { id: "workflow", segment: "workflow", tag: "workflow", when: ALL(F("runner.self"), F("spec.selfOrchestration"), F("seat.workflows"), F("caps.allowWorkflows")) }, { id: "structured-output", segment: "output", tag: "optional", when: F("spec.outputSchema") }, { id: "refresh-mcp-tools", segment: "protocol", tag: "optional", when: F("spec.mcp") }, { id: "read", segment: "hands", tag: "hands", when: HANDS, envHand: true }, { id: "edit", segment: "hands", tag: "hands", when: WRITES, envHand: true }, { id: "write", segment: "hands", tag: "hands", when: WRITES, envHand: true }, { id: "notebook-edit", segment: "hands", tag: "hands", when: WRITES, envHand: true }, { id: "save-tool-result", segment: "hands", tag: "hands", when: ALL(WRITES, F("seat.offloadBytes")), envHand: true }, { id: "grep", segment: "hands", tag: "hands", when: HANDS, envHand: true }, { id: "glob", segment: "hands", tag: "hands", when: HANDS, envHand: true }, { id: "repo-map", segment: "hands", tag: "hands", when: HANDS, envHand: true }, { id: "bash", segment: "hands", tag: "hands", when: ALL(FULL_SHELL, F("env.modelShell")), envHand: true }, { id: "bash-readonly", segment: "hands", tag: "hands", when: ALL(SHELL, F("spec.handsReadOnly"), F("env.modelShell")), envHand: true }, { id: "task-stop", segment: "delegation", tag: "delegation", when: ANY(DELEGATION, F("seat.peerTasks")) }, { id: "send-message", segment: "delegation", tag: "delegation", when: ALL(ANY(DELEGATION, F("leg.parentNotify"), F("leg.peerLane"), F("leg.startersWithheld")), F("runner.self"), NOT(DECLARED("SendMessage"))) }, { id: "agent-transcript", segment: "delegation", tag: "delegation", when: ALL(DELEGATION, F("runner.self"), NOT(DECLARED("SendMessage")), NOT(DECLARED("AgentTranscript"))) }, { id: "read-inbox", segment: "delegation", tag: "peerLane", when: ALL(F("leg.taskNotification"), VALVE("ReadInbox"), NOT(DECLARED("ReadInbox"))) }, { id: "list-agents", segment: "delegation", tag: "peerLane", when: ALL(ANY(F("leg.peerLane"), DELEGATION), F("runner.self"), NOT(DECLARED("SendMessage")), VALVE("SendMessage"), VALVE(LIST_AGENTS.name, LIST_AGENTS.face.aliases), ...namesOf(LIST_AGENTS).map((n) => NOT(DECLARED(n, true)))), }, { id: "send-user-message", segment: "delegation", tag: "optional", when: ALL(F("spec.runLedger"), NOT(DECLARED(SEND_USER_MESSAGE.name))) }, { id: "monitor", segment: "delegation", tag: "backgroundTasks", when: BACKGROUND, envHand: true }, { id: "enter-worktree", segment: "delegation", tag: "hands", when: FULL_SHELL, envHand: true }, { id: "exit-worktree", segment: "delegation", tag: "hands", when: FULL_SHELL, envHand: true }, { id: "read-tool-result", segment: "delegation", tag: "optional", when: F("seat.offload") }, { id: "ask-user-question", segment: "question", tag: "optional", when: ALL(ANY(F("spec.interactiveTools.on"), ALL(NOT(F("spec.interactiveTools.off")), F("seat.question"))), VALVE("AskUserQuestion")) }, { id: "cron-create", segment: "scheduler", tag: "scheduler", when: ALL(NOT(F("spec.handsReadOnly")), F("env.scheduler"), F("leg.session")), envHand: true }, { id: "cron-delete", segment: "scheduler", tag: "scheduler", when: ALL(NOT(F("spec.handsReadOnly")), F("env.scheduler")), envHand: true }, { id: "cron-list", segment: "scheduler", tag: "scheduler", when: ALL(NOT(F("spec.handsReadOnly")), F("env.scheduler")), envHand: true }, { id: "schedule-wakeup", segment: "scheduler", tag: "scheduler", when: ALL(NOT(F("spec.handsReadOnly")), F("env.scheduler"), F("leg.session")), envHand: true }, { id: "lsp", segment: "lsp", tag: "hands", when: ALL(HANDS, F("seat.lsp"), F("lsp.readFace")), envHand: true }, { id: "artifact", segment: "artifact", tag: "optional", when: ALL(F("seat.artifact"), F("artifact.verdict")), envHand: true }, { id: "skill", segment: "context", tag: "optional", when: F("listing.skills") }, ...SHARED_MEMORY_IDS.map((id) => ({ id, segment: "context", tag: "memory", when: ALL(F("seat.sharedMemory"), ...SHARED_MEMORY_IDS.map((m) => VALVE(entryOf(m).name)), NOT(F("names.occupied.sharedMemory"))), retractable: "sharedMemory", })), ...ENGINE_MEMORY_IDS.map((id) => ({ id, segment: "context", tag: "memory", when: ALL(F("seat.memoryEngine"), ...ENGINE_MEMORY_IDS.map((m) => VALVE(entryOf(m).name)), NOT(F("names.occupied.memoryEngine"))), retractable: "memoryEngine", })), { id: "advisor", segment: "advisor", tag: "optional", when: ALL(F("spec.advisorModel"), VALVE("advisor"), F("advisor.route")) }, { id: "tool-search", segment: "engine", tag: "optional", when: F("names.deferred"), engineLane: true }, ]); const RULE_BY_ID = new Map(TOOL_MOUNT_RULES.map((r) => [r.id, r])); const INTERACTIVE_SWITCH_FACTS = new Set(["spec.interactiveTools.on", "spec.interactiveTools.off"]); function readsInteractiveSwitch(cond, seen) { if ("fact" in cond) return INTERACTIVE_SWITCH_FACTS.has(cond.fact); if ("not" in cond) return readsInteractiveSwitch(cond.not, seen); if ("all" in cond) return cond.all.some((c) => readsInteractiveSwitch(c, seen)); if ("any" in cond) return cond.any.some((c) => readsInteractiveSwitch(c, seen)); if ("row" in cond) { if (seen.has(cond.row)) return false; seen.add(cond.row); const rule = RULE_BY_ID.get(cond.row); if (rule === undefined) throw mismatch(`mount condition names no row "${cond.row}"`); return readsInteractiveSwitch(rule.when, seen); } return false; } export const INTERACTIVE_TOOL_NAMES = Object.freeze([ ...new Set(TOOL_MOUNT_RULES.filter((rule) => readsInteractiveSwitch(rule.when, new Set([rule.id]))).map((rule) => mountRuleEntry(rule).name)), ]); function needsFact(cond, fact) { if ("fact" in cond) return cond.fact === fact; return "all" in cond && cond.all.some((c) => needsFact(c, fact)); } export function namesNeedingFact(fact) { return new Set(TOOL_MOUNT_RULES.filter((rule) => needsFact(rule.when, fact)).flatMap((rule) => namesOf(mountRuleEntry(rule)))); } export function mountRuleEntry(rule) { return entryOf(rule.id); } export function mountGroupNames(group) { return TOOL_MOUNT_RULES.filter((r) => r.retractable === group).flatMap((r) => namesOf(mountRuleEntry(r))); } export function mountRuleOf(id) { return RULE_BY_ID.get(id); } const leaf = (v, f) => ({ value: v === undefined ? "unknown" : v, why: [f] }); const union = (vs) => [...new Set(vs.flatMap((v) => v.why))]; export function evaluateMountCond(cond, src, row) { if ("fact" in cond) return leaf(src.fact(cond.fact), cond.fact); if ("valve" in cond) return leaf(src.valve(cond.aliases === undefined ? { name: cond.valve } : { name: cond.valve, aliases: cond.aliases }), "spec.selector"); if ("declared" in cond) return leaf(src.declared(cond.declared, cond.viaAlias === true), "names.declared"); if ("kept" in cond) return leaf(src.kept(cond.kept), "model.gate"); if ("retracted" in cond) return leaf(src.retracted(cond.retracted), "names.retracted"); if ("row" in cond) return row(cond.row); if ("not" in cond) { const v = evaluateMountCond(cond.not, src, row); return { value: v.value === "unknown" ? "unknown" : !v.value, why: v.why }; } const parts = ("all" in cond ? cond.all : cond.any).map((c) => evaluateMountCond(c, src, row)); const decisive = "all" in cond ? false : true; const decided = parts.filter((p) => p.value === decisive); if (decided.length > 0) return { value: decisive, why: union(decided) }; const open = parts.filter((p) => p.value === "unknown"); if (open.length > 0) return { value: "unknown", why: union(open) }; return { value: !decisive, why: union(parts) }; } function finalCond(rule) { const e = mountRuleEntry(rule); const parts = [rule.when]; if (rule.engineLane !== true) parts.push(VALVE(e.name, e.face.aliases)); if (rule.retractable !== undefined) parts.push(NOT({ retracted: rule.retractable })); return ALL(...parts); } function rowVerdicts(src) { const memo = new Map(); const of = (id) => { const hit = memo.get(id); if (hit !== undefined) return hit; const rule = RULE_BY_ID.get(id); if (rule === undefined) throw mismatch(`mount condition names no row "${id}"`); const v = evaluateMountCond(rule.when, src, of); memo.set(id, v); return v; }; return of; } export function mountRowVerdict(id, facts, leaves) { const rule = RULE_BY_ID.get(id); if (rule === undefined) throw mismatch(`no mount row "${id}"`); const src = { fact: (f) => facts[f], valve: leaves, declared: () => undefined, kept: () => true, retracted: () => undefined }; const v = evaluateMountCond(finalCond(rule), src, rowVerdicts(src)); if (v.value === "unknown") throw mismatch(`the row "${id}" asked ${v.why.join(", ")}, which was never stated`); return v.value; } export function planToolMounts(reading, executionEnv) { const { src, members } = reading; const families = reading.families.map((f) => f.family); const row = rowVerdicts(src); const out = []; const absent = []; const place = (name, id, source, mountedBy, v) => { if (v.value === false) { absent.push({ ...(id !== undefined ? { id } : {}), name, because: v.why }); return; } out.push({ name, ...(id !== undefined ? { id } : {}), source, mountedBy, state: v.value === true ? "mounted" : "conditional", ...(v.value === "unknown" ? { when: v.why } : {}) }); }; for (const m of members) { const v = evaluateMountCond(ALL(m.when, VALVE(m.identity.name, m.identity.aliases)), src, row); place(m.identity.name, m.id, m.source, m.mountedBy, v); } for (const rule of TOOL_MOUNT_RULES) { const e = mountRuleEntry(rule); place(e.name, e.id, e.source, rule.tag, evaluateMountCond(finalCond(rule), src, row)); } const kept = dedupeLaterWins(out); const named = new Set(kept.map((m) => m.name)); return { half: "static", members: kept, families: [...families], absent: absent.filter((a) => !named.has(a.name)), executionEnv }; } export const EXECUTION_ENV_NEEDS = Object.freeze(["needed", "conditional", "unneeded"]); export const EXECUTION_ENV_ASKS = Object.freeze(["workspace", "attachment_paths", "plan_file", "restore_files", "checkout", "restore", "compaction_restore", "caller_placement", "delegation", "mods", "memory", "park_lane"]); const ENV_FACTS = new Set(TOOL_MOUNT_FACTS.filter((f) => f.startsWith("env."))); const placementOf = (v) => (v.value === true ? "mounted" : v.value === false ? "absent" : "conditional"); export function readExecutionEnv(r) { const over = (env) => ({ ...r.src, fact: (f) => (ENV_FACTS.has(f) ? env : r.src.fact(f)) }); const withEnv = over(true), without = over(false); const rowWith = rowVerdicts(withEnv), rowWithout = rowVerdicts(without); const consumers = new Map(); const consume = (name, p) => { if (p !== "absent") consumers.set(name, consumers.get(name) === "mounted" ? "mounted" : p); }; const callable = r.families.map(() => "conditional"); const memberCond = (m) => ALL(m.when, VALVE(m.identity.name, m.identity.aliases)); for (const m of r.members) { const p = placementOf(evaluateMountCond(memberCond(m), withEnv, rowWith)); const q = placementOf(evaluateMountCond(memberCond(m), without, rowWithout)); callable.push(p); if (p !== q || m.pathTarget?.access === "read" || (r.writeProtected && writesProtectedPath([m.identity.name, ...(m.identity.aliases ?? [])], m.pathTarget))) consume(m.identity.name, p); } for (const rule of TOOL_MOUNT_RULES) { const e = mountRuleEntry(rule); const p = placementOf(evaluateMountCond(finalCond(rule), withEnv, rowWith)); const q = placementOf(evaluateMountCond(finalCond(rule), without, rowWithout)); if (rule.engineLane !== true) callable.push(p); if (p !== q || rule.envHand === true || (r.writeProtected && writesProtectedPath(namesOf(e), e.face.pathTarget))) consume(e.name, p); } for (const { family, writesPath, readsPath } of r.families) if ((r.writeProtected && writesPath) || readsPath === true) consume(`${family.source}:${family.peer}`, "conditional"); const delegators = [finalCond(RULE_BY_ID.get("workflow")), ...r.members.filter((m) => m.delegates === true).map(memberCond)].map((c) => placementOf(evaluateMountCond(c, withEnv, rowWith))); const canCall = !callable.some((p) => p !== "absent") ? false : callable.includes("mounted") ? true : undefined; const both = (a, b) => (a === false || b === false ? false : a === true && b === true ? true : undefined); const onCall = both(r.mods.onCall, canCall); const mods = r.mods.always === true || onCall === true ? true : r.mods.always === false && onCall === false ? false : undefined; const asked = { ...r.asks, mods, park_lane: both(r.src.fact("seat.checkpoint"), canCall), delegation: delegators.includes("mounted") ? true : delegators.includes("conditional") ? undefined : false }; const asks = EXECUTION_ENV_ASKS.filter((a) => asked[a] !== false); const placements = [...consumers.values()]; const state = placements.includes("mounted") || asks.some((a) => asked[a] === true) ? "needed" : placements.length > 0 || asks.length > 0 ? "conditional" : "unneeded"; return Object.freeze({ state, tools: Object.freeze([...consumers.keys()]), asks: Object.freeze(asks) }); } function dedupeLaterWins(members) { const byName = new Map(); for (const m of members) { byName.delete(m.name); byName.set(m.name, m); } return [...byName.values()]; } export const TOOL_MOUNT_PLAN_MISMATCH = "internal.tool_mount_plan_mismatch"; function mismatch(message) { return Object.assign(new Error(`tool mount plan: ${message}`), { code: TOOL_MOUNT_PLAN_MISMATCH }); } export class ToolMountLedger { #contractOf; #facts = new Map(); #retracted = new Map(); #judged = new Map(); #envHands = new Set(); #expected = []; #leg; #plan; constructor(contractOf) { this.#contractOf = contractOf; } bindLeg(leg) { if (this.#leg !== undefined) throw mismatch("the leg's name domain was bound twice"); this.#leg = leg; } know(facts) { for (const [k, v] of Object.entries(facts)) { if (!isMountFact(k)) throw mismatch(`"${k}" is not a mount fact`); if (typeof v !== "boolean") continue; const had = this.#facts.get(k); if (had !== undefined && had !== v) throw mismatch(`the fact ${k} was stated ${had} and then ${v}`); this.#facts.set(k, v); } } knows(f) { return this.#facts.has(f); } factOf(f) { return this.#facts.get(f); } #source() { const leg = () => { if (this.#leg === undefined) throw mismatch("a mount judgment read the name domain before it was bound"); return this.#leg; }; return { fact: (f) => this.#facts.get(f), valve: (identity) => leg().leaves(identity), declared: (name, viaAlias) => leg().declared.some((t) => t.name === name || (viaAlias && t.aliases?.includes(name) === true)), kept: () => true, retracted: (g) => this.#retracted.get(g), }; } #verdict(id) { const v = rowVerdicts(this.#source())(id); if (v.value === "unknown") throw mismatch(`the row "${id}" asked ${v.why.join(", ")}, which this leg never stated`); return v; } holds(id) { if (!RULE_BY_ID.has(id)) throw mismatch(`no mount row "${id}"`); return this.#verdict(id).value === true; } holdsIf(id, assumed) { if (!RULE_BY_ID.has(id)) throw mismatch(`no mount row "${id}"`); const base = this.#source(); const v = rowVerdicts({ ...base, fact: (f) => assumed[f] ?? base.fact(f) })(id); if (v.value === "unknown") throw mismatch(`the row "${id}" asked ${v.why.join(", ")}, which this leg never stated`); return v.value === true; } holding(select) { const out = new Set(); for (const rule of TOOL_MOUNT_RULES) { const e = mountRuleEntry(rule); if (select(e) && this.holds(rule.id)) out.add(e.name); } return [...out]; } judge(id) { const had = this.#judged.get(id); if (had !== undefined) return had; const rule = RULE_BY_ID.get(id); if (rule === undefined) throw mismatch(`no mount row "${id}"`); const holds = this.#verdict(id).value === true; this.#judged.set(id, holds); if (holds) { const e = mountRuleEntry(rule); if (rule.envHand === true) this.#envHands.add(e.name); this.#expected.push({ name: e.name, ...(e.face.aliases !== undefined ? { aliases: e.face.aliases } : {}), rowId: id, ...(e.face.contract !== undefined ? { contract: e.face.contract.contractId } : {}), ...(rule.engineLane === true ? { engineLane: true } : {}), ...(rule.retractable !== undefined ? { retractable: rule.retractable } : {}), }); } return holds; } get envHands() { return this.#envHands; } judgeTool(tool) { const contract = this.#contractOf(tool); const rule = TOOL_MOUNT_RULES.find((r) => { const e = mountRuleEntry(r); return e.name === tool.name && (e.face.contract === undefined || e.face.contract.contractId === contract); }); if (rule === undefined) throw mismatch(`"${tool.name}" (${contract}) is no catalog definition a mount row names`); return this.judge(rule.id); } judgeMember(family, tool) { this.#expected.push({ name: tool.name, ...(tool.aliases !== undefined ? { aliases: tool.aliases } : {}), family, contract: this.#contractOf(tool) }); return true; } retract(group, taken) { const had = this.#retracted.get(group); if (had !== undefined && had !== taken) throw mismatch(`the ${group} retraction was stated ${had} and then ${taken}`); this.#retracted.set(group, taken); } settle(onRoster, members, executionEnv) { const leg = this.#leg; if (leg === undefined) throw mismatch("the roster settled before its name domain was bound"); const survives = (e) => (e.engineLane === true || leg.leaves(e)) && (e.retractable === undefined || this.#retracted.get(e.retractable) !== true); const expected = laterWins(this.#expected.filter(survives)); const actual = laterWins(onRoster); for (const name of new Set([...expected.keys(), ...actual.keys()])) { const e = expected.get(name), a = actual.get(name); if (e === undefined) throw mismatch(`"${name}" is on the roster but no mount row or member judgment put it there`); if (a === undefined) throw mismatch(`"${name}" was judged mounted (${e.rowId ?? e.family}) but is not on the roster`); if (e.contract !== undefined && this.#contractOf(a) !== e.contract) throw mismatch(`"${name}" answers as ${this.#contractOf(a)}, but its row mounts ${e.contract}`); if (e.engineLane !== true && !leg.leaves(a)) throw mismatch(`"${name}" dispatches to an instance the valve takes out`); } const src = this.#source(); const row = rowVerdicts(src); const absent = []; for (const rule of TOOL_MOUNT_RULES) { const e = mountRuleEntry(rule); const v = evaluateMountCond(finalCond(rule), src, row); if (v.value === "unknown") throw mismatch(`the row "${rule.id}" was left open: ${v.why.join(", ")} never stated`); if (!this.#judged.has(rule.id) && evaluateMountCond(rule.when, src, row).value === true) throw mismatch(`the row "${rule.id}" holds but its mount site never asked`); if (v.value === false && !actual.has(e.name)) absent.push({ id: e.id, name: e.name, because: v.why }); } for (const t of leg.declared) if (!leg.leaves(t) && !actual.has(t.name)) absent.push({ name: t.name, because: ["spec.selector"] }); this.#plan = { half: "effective", members, families: [], absent, executionEnv }; return this.#plan; } get plan() { return this.#plan; } } function laterWins(items) { const out = new Map(); for (const t of items) out.set(t.name, t); return out; }