UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

475 lines (474 loc) • 31.9 kB
import { compileToolSelector, ownSelectorLayer, valveLeaves, deniedProtocolTools, delegationListWhere, isCanonicalToolName, isToolSelectorLayer, listReaches, notAListSentence, toolListsDigest, notAStringSentence, readAllowedToolList, readDeniedEntry, readDeniedToolList } from "../../agents/tool-filter.js"; import { readToolNameList, valueTypeLabel } from "../tool-name-list.js"; import { compileAllowList, inertEntryPhrase, isRetiredLeftOut, renderListEntry, rootFacingToolNames } from "../allow-entry.js"; import { inlineUntrusted } from "../untrusted-text.js"; import { deliverEngineNotice } from "../engine-notice.js"; import { ENGINE_TOOLS } from "../tool-catalog-entries.js"; import { callerToolNameProblem } from "../caller-tool-name.js"; import { PROTOCOL_TABLE, grantWildcardRefusalOf, mintNamespacePrefix, protocolOf, splitNamespacedName } from "@sema-agent/primitives"; import { legRetiredNameView, mountedToolNames, NO_RETIRED_READING, ruleListUnderView } from "../tool-name-aliases.js"; import { POLICY_NAME_REFUSAL_CODE, retiredToolNameNotice } from "../retired-tool-name-account.js"; import { unmatchedNameIdentity, unmatchedNameWarning, unmatchedNamesNotice } from "../unmatched-tool-names.js"; import { DEFINITION_ENTRY_CODE, DEFINITION_ENTRY_REASON, definitionEntryIdentity, definitionEntryNotice, definitionEntryWarning } from "../definition-entry-grammar.js"; import { closestName } from "../closest-name.js"; import { projectionToolNames } from "../tool-policy.js"; import { declaredDelegationNameOf } from "../delegation-name.js"; import { enterConfigDoor } from "../config-refusal-input.js"; import { announceDigest } from "./announce-once-ledger.js"; export function renamedDelegationMountSentence(...rosters) { for (const tools of rosters) { if (!Array.isArray(tools)) continue; for (const t of tools) { const declared = declaredDelegationNameOf(t); if (declared === undefined) continue; try { const mounted = t.name; if (declared === mounted) continue; return `The delegation tool declared as "${inlineUntrusted(declared, 80)}" is mounted under the name "${inlineUntrusted(String(mounted), 80)}": one tool would answer to two names (the agent definitions' tool lists, the copy a child is handed and the tool's prompt text speak the declared one; the roster and the model's call speak the mounted one). Mount it under its declared name, or declare the name you mount it under (\`createSubagentTool({ name })\`).`; } catch { } } } return undefined; } export function refuseRenamedDelegationMounts(...rosters) { const sentence = renamedDelegationMountSentence(...rosters); if (sentence !== undefined) throw refused(sentence, "config.tool_face_control", "renamed_mount"); } function poolOf(tools) { return { tools, names: mountedToolNames([...tools.map((t) => ({ name: t.name })), ...tools.flatMap((t) => t.agentToolPool ?? [])]), complete: tools.every((t) => t.agentToolPool !== undefined) }; } export function delegationPoolReading(callerTools, leaves) { return poolOf(callerTools.filter((t) => t.agentToolFaces !== undefined && leaves(t))); } function peersOf(known, declaredPeers) { const peers = new Set(PROTOCOL_TABLE.flatMap((ns) => (declaredPeers[ns.id] ?? []).map((p) => mintNamespacePrefix(ns, p.name)))); for (const name of known) { const ns = protocolOf(name); const split = ns !== undefined ? splitNamespacedName(name) : undefined; if (split !== undefined && split.peer !== "") peers.add(mintNamespacePrefix(split.ns, split.peer)); } return peers; } function rootFacingUniverse(mounted, pool, declaredPeers, retiredNames) { const known = rootFacingToolNames([...mounted, ...pool.names]); return { known, peers: peersOf(known, declaredPeers), complete: true, carrierOf: (name) => (mounted.has(name) ? "run" : pool.names.has(name) ? "pool" : "catalog"), retiredNames }; } function childFacingUniverse(pool, declaredPeers) { const known = new Set([...mountedToolNames(ENGINE_TOOLS), ...pool.names]); return { known, peers: peersOf(known, declaredPeers), complete: pool.complete, carrierOf: (name) => (pool.names.has(name) ? "pool" : "catalog"), retiredNames: legRetiredNameView(pool.tools) }; } const NO_LISTS = Object.freeze({ deny: Object.freeze([]) }); const DENY_LIST_NAMES_ONLY = "To block by path or command, write a deny rule in the caller's permission policy: a tool-name list only takes tool names (it narrows which tools are mounted)."; function universeCarries(reach, entry, universe) { for (const name of universe.known) if (listReaches(reach, { name })) return true; const split = splitNamespacedName(entry); if (split === undefined || split.peer === "") return false; return universe.peers.has(mintNamespacePrefix(split.ns, split.peer)); } function refused(message, code, reason) { const e = new Error(message); e.code = code; e.detail = { reason }; return e; } const POLICY_NAME_PROBLEMS_SHOWN = 32; const POLICY_NAME_ENTRY_CHARS = 128; export function policyNameRefusal(first, more) { const e = new Error(first.message); e.code = POLICY_NAME_REFUSAL_CODE; const listed = [first, ...more].map((f) => f.problem).filter((p) => p.entry.length <= POLICY_NAME_ENTRY_CHARS); e.detail = { problems: listed.slice(0, POLICY_NAME_PROBLEMS_SHOWN), total: 1 + more.length }; return e; } const LIST_WORD = { allowed: "allowed tools", denied: "denied tools" }; const NEAR_MISS_EFFECT = { allowed: "it admits nothing, so the tool it was written for is not granted", denied: "it hides nothing, so the tool it was written for stays available to the agent", }; function nearMissRefusal(where, side, flaw, code, poolUnlisted = false) { const tail = poolUnlisted ? "Write the name as the tool is mounted — or, if the name is one a delegation tool's extraTools factory injects, declare it in that tool's extraToolNames so this run can list it." : "Write the name as the tool is mounted."; return refused(`${where} declares tool ${inertEntryPhrase(flaw)} in its ${LIST_WORD[side]}, a spelling that reaches no tool a run mounts — ${NEAR_MISS_EFFECT[side]}. ${tail}`, code, "near_miss"); } function grammarSentence(where, side, entry, consequence) { return `${where} declares tool ${inertEntryPhrase({ entry, reason: "grammar" })} in its ${LIST_WORD[side]}, a spelling no tool name can have — ${consequence} ${DENY_LIST_NAMES_ONLY}`; } const GRAMMAR_REFUSES_THE_RUN = "fix the entry."; const GRAMMAR_REFUSES_THE_DEFINITION = "this agent cannot be delegated to until the entry is fixed."; const isGrammarFlaw = (flaw) => flaw.reason === DEFINITION_ENTRY_REASON; const isStructuralFlaw = (flaw) => flaw.reason !== DEFINITION_ENTRY_REASON; function readToolNameListForm(where, side, value) { if (value === undefined || value === null) return { entries: [], flaws: [] }; const list = readToolNameList(value); if (list.kind !== "entries") return { entries: [], flaws: [{ reason: "not_a_list", message: notAListSentence(where, side, list) }] }; const entries = []; const flaws = []; list.entries.forEach((entry, index) => { const read = readDeniedEntry(entry); if (read.kind === "not_a_string") flaws.push({ reason: "not_a_string", message: notAStringSentence(where, side, index, read.type) }); else if (read.kind === "unreadable") flaws.push({ reason: DEFINITION_ENTRY_REASON, entry: read.entry }); else entries.push({ entry: entry, name: read.name, content: read.content }); }); return { entries, flaws }; } function formRefusal(where, side, flaw, code) { if (isStructuralFlaw(flaw)) return refused(flaw.message, code, flaw.reason); return refused(grammarSentence(where, side, flaw.entry, GRAMMAR_REFUSES_THE_RUN), code, "unknown_name"); } function readableToolNameList(where, side, value, code) { const form = readToolNameListForm(where, side, value); const first = form.flaws[0]; if (first !== undefined) throw formRefusal(where, side, first, code); return form.entries; } export function toolNameListFlaw(where, side, value, withGrammar) { return definitionFlawOf(where, side, readToolNameListForm(where, side, value).flaws, withGrammar); } function definitionFlawOf(where, side, flaws, withGrammar) { const structural = flaws.find(isStructuralFlaw); if (structural !== undefined) return { message: structural.message, reason: structural.reason }; const grammar = withGrammar ? flaws.find(isGrammarFlaw) : undefined; return grammar !== undefined ? { message: grammarSentence(where, side, grammar.entry, GRAMMAR_REFUSES_THE_DEFINITION), reason: grammar.reason } : undefined; } const KEPT_ENTRY = { allowed: "it grants nothing today and stays in force for a tool of that name mounted later", denied: "it denies nothing today and stays in force for a tool of that name mounted later", }; const KEPT_ENTRY_UNLISTED_POOL = "so it is kept here: the pool this delegation tool hands its child cannot be listed, and the spawned child judges the entry against its own roster (another spelling of a tool it carries refuses the child before it starts; an exact name takes effect; a name nothing answers to there stays in force for a tool of that name mounted later)"; const PEER_WORD = { mcp: "MCP server", a2a: "A2A peer" }; function judgeToolNameList(where, side, value, universe, advise, code, retired, definition, hintUnlistedPool = false) { const form = readToolNameListForm(where, side, ruleListUnderView(value, universe.retiredNames)); const refusing = definition === true ? form.flaws.find(isStructuralFlaw) : form.flaws[0]; if (refusing !== undefined) throw formRefusal(where, side, refusing, code); const first = form.flaws.find(isGrammarFlaw); if (first !== undefined) { advise(definitionEntryWarning(grammarSentence(where, side, first.entry, GRAMMAR_REFUSES_THE_DEFINITION), { where: inlineUntrusted(where, 160), side, entry: inlineUntrusted(first.entry, 120), identity: JSON.stringify([where, side, first.entry]) })); } for (const { entry, name: toolName, content: written } of form.entries) { if (toolName === "*" && !written) continue; const name = side === "denied" || !written ? toolName : entry; const content = side === "denied" && written; const reach = side === "denied" ? readDeniedToolList([entry]) : (readAllowedToolList([entry]) ?? readDeniedToolList([])); const split = splitNamespacedName(name); const toolSplit = splitNamespacedName(toolName); if (toolName.includes("*") && (toolSplit === undefined || toolSplit.peer.includes("*"))) { if (side === "denied") continue; throw refused(`${where} declares ${renderListEntry(entry)} in its ${LIST_WORD[side]}: ${grantWildcardRefusalOf(name)}.`, code, "unsupported_pattern"); } const { inert } = compileAllowList([toolName], "deny", universe.known); const flaw = inert[0] === undefined ? undefined : { ...inert[0], entry, ...(inert[0].reason === "near_miss" && inert[0].currentName !== undefined ? { carriedBy: universe.carrierOf(inert[0].currentName) } : {}) }; if (universe.complete && flaw?.currentName !== undefined) throw nearMissRefusal(where, side, flaw, code, hintUnlistedPool); if (toolName !== name) { advise(new Error(`${where} declares ${renderListEntry(entry)} in its allowed tools: an allowed list names tools, not content, so this entry grants nothing — name the tool "${inlineUntrusted(toolName, 80)}" to grant it, or move the content rule to a denied list or a permission rule.`)); continue; } if (flaw === undefined && universeCarries(reach, name, universe)) { if (content) advise(new Error(`${where} declares ${renderListEntry(entry)} in its denied tools: this list reads tool names, not content, so the whole tool "${inlineUntrusted(name, 80)}" is denied. ${DENY_LIST_NAMES_ONLY}`)); continue; } if (retired !== undefined && side === "denied" && universe.complete && flaw !== undefined && isRetiredLeftOut(flaw, universe.known) && flaw.guidance !== undefined) { retired({ field: "deny", entry: inlineUntrusted(entry, 120), layer: "task_selector", guidance: flaw.guidance, source: inlineUntrusted(where, 160) }); continue; } const phrase = flaw !== undefined ? inertEntryPhrase(flaw) : renderListEntry(entry); const undeclared = split !== undefined && split.peer !== "" && !split.peer.includes("*") && !universe.peers.has(mintNamespacePrefix(split.ns, split.peer)); const why = undeclared ? `no ${PEER_WORD[split.ns.id]} named "${inlineUntrusted(split.peer, 80)}" is declared for this task` : universe.complete ? "no tool of this task answers to that name" : "no tool this run can list answers to that name"; const near = flaw?.currentName === undefined ? closestName(toolName, universe.known) : undefined; const nearest = near !== undefined && near !== toolName ? near : undefined; const hint = nearest !== undefined ? ` The nearest name ${universe.complete ? "a tool of this task answers to" : "a tool this run can list answers to"} is "${inlineUntrusted(nearest, 80)}".` : ""; advise(unmatchedNameWarning(`${where} declares tool ${phrase} in its ${LIST_WORD[side]}: ${why}, ${universe.complete ? `so ${KEPT_ENTRY[side]}` : KEPT_ENTRY_UNLISTED_POOL}. If the name is misspelt, fix the entry.${hint}`, { where: inlineUntrusted(where, 160), side, entry: inlineUntrusted(entry, 120), identity: JSON.stringify([where, side, entry]), ...(nearest !== undefined ? { nearest: inlineUntrusted(nearest, 80) } : {}), })); } } export function workflowAgentTypeWhere(agentType) { return `workflow agentType "${inlineUntrusted(agentType, 80)}"`; } export function refuseUnusableDefinition(agentType, lists) { const where = workflowAgentTypeWhere(agentType); const flaw = toolNameListFlaw(where, "allowed", lists.allowTools, true) ?? toolNameListFlaw(where, "denied", lists.denyTools, true); if (flaw !== undefined) throw refused(flaw.message, DEFINITION_ENTRY_CODE, flaw.reason); } function inheritedListsWhere(ceilings, i) { const up = ceilings - 1 - i; return up === 0 ? "the lists of the run this leg was spawned under" : `the lists of the run ${up} spawn${up === 1 ? "" : "s"} above the run this leg was spawned under`; } function readSelectorLayer(layer, layerWhere, listWhere, recorded) { if (!isToolSelectorLayer(layer)) { throw refused(`${layerWhere} are a value that is ${valueTypeLabel(layer)}, not a pair of tool-name lists (an allowed and a denied list) — the leg does not start. Fix the layer.`, "config.tool_face_control", "not_a_list"); } const lists = {}; for (const side of ["allowed", "denied"]) { const where = listWhere(side); const value = side === "allowed" ? layer.allow : layer.deny; const entries = readableToolNameList(where, side, value, "config.tool_face_control"); const written = recorded ? entries.find((read) => !isCanonicalToolName(read.entry)) : undefined; if (written !== undefined) { throw refused(`${where} declares ${renderListEntry(written.entry)} in its ${LIST_WORD[side]}: a row records each tool name in its bare spelling (\`Read\`, never \`Read()\`, \`Read(*)\` or \`Read(…)\`), and this entry was recorded by an engine that read the list otherwise — it is read here neither as that engine read it nor as this one would`, "config.tool_face_control", "unsupported_pattern"); } if (value !== undefined && value !== null) lists[side] = Object.freeze(entries.map((read) => read.entry)); } return Object.freeze({ ...(lists.allowed !== undefined ? { allow: lists.allowed } : {}), deny: lists.denied ?? Object.freeze([]) }); } export function ownListsWhereOf(ownBy) { return ownBy !== undefined ? delegationListWhere(ownBy.toolName, ownBy.definition) : undefined; } export function readToolSelector(input) { const layers = [...input.layers]; const ceilings = layers.length - 1; const read = layers.map((layer, i) => { const inherited = i === ceilings ? undefined : inheritedListsWhere(ceilings, i); const readLayer = () => readSelectorLayer(layer, inherited ?? "this run's own tool lists", (side) => inherited ?? input.where ?? (side === "allowed" ? "TaskSpec.allowTools" : "TaskSpec.excludeTools"), false); const word = input.inputs?.[i]; return word === undefined ? readLayer() : enterConfigDoor(word, readLayer); }); const own = read[ceilings]; const view = input.retiredNames ?? NO_RETIRED_READING; if (own !== undefined) read[ceilings] = Object.freeze(ownSelectorLayer({ allow: ruleListUnderView(own.allow, view), exclude: ruleListUnderView(own.deny, view) }, input.spec ?? {})); return compileToolSelector(read, input.legs); } function readOwnToolListsRecord(value) { try { if (typeof value !== "object" || value === null || Array.isArray(value)) return { flaw: `a value that is ${valueTypeLabel(value)}, not a tool name with an agent definition name and the digest of the lists it wrote` }; const { toolName, definition, lists } = value; if (typeof toolName !== "string" || toolName.length === 0) return { flaw: `a tool whose name is ${typeof toolName === "string" ? "empty" : `a value that is ${valueTypeLabel(toolName)}`}, not a tool name` }; const problem = callerToolNameProblem(toolName); if (problem !== undefined) return { flaw: `a tool whose name is not one a caller tool can carry (${problem})` }; if (definition !== undefined && typeof definition !== "string") return { flaw: `an agent definition whose name is a value that is ${valueTypeLabel(definition)}, not a name` }; if (definition === "") return { flaw: "an agent definition whose name is empty, not a name" }; if (lists === undefined) return { flaw: "a record with no digest of the lists it wrote" }; if (typeof lists !== "string") return { flaw: `a digest of the lists it wrote that is a value that is ${valueTypeLabel(lists)}, not a digest` }; if (lists.length === 0) return { flaw: "a digest of the lists it wrote that is empty, not a digest" }; return { lists }; } catch { return { flaw: "a value that cannot be read" }; } } function ownToolListsFlaw(value) { const read = readOwnToolListsRecord(value); return "flaw" in read ? read.flaw : undefined; } export function ownToolListsDigestOf(value) { if (value === undefined) return undefined; const read = readOwnToolListsRecord(value); return "lists" in read ? read.lists : undefined; } export function persistedToolNamesRefusal(ceiling, chain, ownLists) { const pending = "refused before the claim (the checkpoint stays pending): expire it and run the work again"; const ownFlaw = ownLists === undefined ? undefined : ownToolListsFlaw(ownLists); if (ownFlaw !== undefined) return { message: `this leg's checkpoint row records the delegation tool that wrote its own lists as ${ownFlaw} — ${pending}`, reason: "invalid_record" }; if (ceiling !== undefined) { const layers = readToolNameList(ceiling); if (layers.kind !== "entries") return { message: `the ceiling this leg's checkpoint row recorded is a value that is ${layers.kind === "not_a_list" ? layers.type : "a list that cannot be read"}, not a list of layers — ${pending}`, reason: "not_a_list" }; try { layers.entries.forEach((layer, i) => readSelectorLayer(layer, inheritedListsWhere(layers.entries.length, i), () => inheritedListsWhere(layers.entries.length, i), true)); } catch (e) { return { message: `${e.message} — as this leg's checkpoint row recorded it; ${pending}`, reason: e.detail.reason }; } } if (!Array.isArray(chain)) return undefined; const flaw = (() => { for (const [layer, entry] of chain.entries()) { if (typeof entry !== "object" || entry === null || "opaque" in entry || !Array.isArray(entry.components)) continue; for (const c of entry.components) { if (typeof c !== "object" || c === null) continue; const { member, list } = projectionToolNames(c); const where = `layer ${layer + 1}'s ${c.kind === "tool_deny" || c.kind === "tool_allowlist" || c.kind === "shell_command" ? `\`${c.kind}\`` : "component"} ${member}`; const read = readToolNameList(list); if (read.kind !== "entries") return { what: `${where} as a value that is ${read.kind === "not_a_list" ? read.type : "a list that cannot be read"}, not a list of tool names`, reason: "not_a_list" }; const at = read.entries.findIndex((name) => !isCanonicalToolName(name)); if (at < 0) continue; const name = read.entries[at]; return typeof name === "string" ? { what: `${renderListEntry(name)} in ${where}`, reason: "unsupported_pattern" } : { what: `in ${where}, as entry ${at + 1}, a value that is ${valueTypeLabel(name)}`, reason: "not_a_string" }; } } return undefined; })(); return flaw === undefined ? undefined : { reason: flaw.reason, message: `the checkpoint's frozen inherited constraint chain holds ${flaw.what}: a row records each tool name in its bare spelling (\`Read\`, never \`Read()\`, \`Read(*)\` or \`Read(…)\`), and this entry was recorded by a reading that is not the rule syntax's (an earlier engine's name set, or a policy that reads its lists as written) — it is replayed neither as that reading nor as this engine's; ${pending} (with the policy naming the tool itself)` }; } export function refusePersistedToolNames(ceiling, chain, ownLists) { const refusal = persistedToolNamesRefusal(ceiling, chain, ownLists); if (refusal !== undefined) throw refused(refusal.message, "config.tool_face_control", refusal.reason); } export function boundToolListsJudgment(evidence, own) { return evidence !== undefined && evidence === toolListsDigest(own.allow, own.exclude) ? evidence : undefined; } export function boundOwnToolLists(record, own) { if (record === undefined) return undefined; const flaw = ownToolListsFlaw(record); if (flaw !== undefined) { throw refused(`this leg's internals (RunInternals.ownToolLists) record the delegation tool that wrote its own lists as ${flaw} — the leg does not start. Only the delegation lane writes that record: leave it out.`, "config.tool_face_control", "invalid_record"); } const held = record; return held.lists === toolListsDigest(own.allow, own.exclude) ? held : undefined; } export function judgeRunToolLists(input) { const { spec, tools, onceLedger, sessionId } = input; const retiredLeftOut = []; const retire = (entry) => void retiredLeftOut.push(entry); const advise = (err) => { try { onceLedger.onError(err, { phase: "config", sessionId }); } catch { } }; const authorWarnings = []; const adviseAuthor = (err) => { advise(err); authorWarnings.push(err); }; const tellOnce = (code, identity, deliver) => { try { onceLedger.oncePerSession(announceDigest(`${code}:user`, identity), deliver); } catch { } }; const tellAuthors = () => { for (const warning of authorWarnings) { const unmatched = unmatchedNamesNotice(warning, sessionId); const unmatchedKey = unmatchedNameIdentity(warning); if (unmatched !== undefined && unmatchedKey !== undefined) tellOnce(unmatched.code, unmatchedKey, () => deliverEngineNotice(input.onNotice, unmatched)); const grammar = definitionEntryNotice(warning, sessionId); const grammarKey = definitionEntryIdentity(warning); if (grammar !== undefined && grammarKey !== undefined) tellOnce(grammar.code, grammarKey, () => deliverEngineNotice(input.onNotice, grammar)); } }; const ownWhere = ownListsWhereOf(input.ownBy); const selector = input.selector; const definitionAt = input.definition !== undefined ? selector.layers.length - 2 : -1; const definitionLayer = selector.layers[definitionAt]; const definitionWhere = input.definition !== undefined ? workflowAgentTypeWhere(input.definition.agentType) : undefined; const denied = deniedProtocolTools(selector.layers.filter((_, i) => i !== definitionAt), input.legs); const deniedByDefinition = definitionLayer !== undefined ? deniedProtocolTools([definitionLayer, NO_LISTS], input.legs) : []; if (denied.length > 0 || deniedByDefinition.length > 0) { const names = [...new Set([...denied, ...deniedByDefinition].map((h) => `"${h.name}"`))]; const one = names.length === 1; const deniedBy = (from, own, whose) => { const hits = from.filter((h) => h.own === own).map((h) => `"${h.name}"`); return hits.length > 0 && whose !== undefined ? [`${whose} denies ${one ? "it" : hits.join(", ")}`] : []; }; const by = [...deniedBy(denied, true, ownWhere ?? "this run's own excludeTools"), ...deniedBy(deniedByDefinition, false, definitionWhere), ...deniedBy(denied, false, "an inherited list (the spawning run's excludeTools, or one it inherits)")]; throw refused(`This kind of leg (${input.legs.join(", ")}) relies on ${names.join(", ")}, but ${by.join(" and ")} — the leg cannot work without ${one ? "it" : "them"}. Remove the entry from the list that names it.`, "config.tool_face_control", "protocol_denied"); } const pool = delegationPoolReading(spec.tools ?? [], valveLeaves(selector)); const mounted = mountedToolNames([...tools, ...(spec.tools ?? [])]); const withOwnServers = (servers) => servers === undefined || servers.length === 0 ? input.declaredPeers : { ...input.declaredPeers, mcp: [...(input.declaredPeers.mcp ?? []), ...servers] }; const definitionServers = [...(spec.agents ?? []).flatMap((d) => d.mcp ?? []), ...pool.tools.flatMap((t) => (t.agentToolFaces ?? []).flatMap((f) => f.servers ?? []))]; const root = rootFacingUniverse(input.ownBy !== undefined ? new Set([...mounted, input.ownBy.toolName]) : mounted, pool, withOwnServers(definitionServers), input.retiredNames); if (!input.judgedUpstream) { const own = [["allowed", input.own.allow], ["denied", input.own.exclude]]; const silent = () => undefined; const told = input.toldUpstream === true; const ownAdvise = told ? silent : ownWhere === undefined ? adviseAuthor : advise; const rootTaskLists = ownWhere === undefined && !input.legs.includes("delegated"); for (const [side, value] of own) judgeToolNameList(ownWhere ?? (side === "allowed" ? "TaskSpec.allowTools" : "TaskSpec.excludeTools"), side, value, root, ownAdvise, "config.tool_face_control", told ? silent : retire, undefined, rootTaskLists && !pool.complete); } if (definitionLayer !== undefined && definitionWhere !== undefined) { judgeToolNameList(definitionWhere, "allowed", definitionLayer.allow, root, advise, "config.agent.unknown_tool", undefined, true); judgeToolNameList(definitionWhere, "denied", definitionLayer.deny, root, advise, "config.agent.unknown_tool", retire, true); } const childUniverses = (servers) => pool.tools.length > 0 ? pool.tools.map((t) => childFacingUniverse(poolOf([t]), withOwnServers(servers))) : [childFacingUniverse(poolOf([]), withOwnServers(servers))]; for (const def of spec.agents ?? []) { for (const universe of childUniverses(def.mcp)) { judgeToolNameList(`TaskSpec.agents: agent "${def.name}"`, "allowed", def.allowTools, universe, adviseAuthor, "config.agent.unknown_tool", undefined, true); judgeToolNameList(`TaskSpec.agents: agent "${def.name}"`, "denied", def.denyTools, universe, adviseAuthor, "config.agent.unknown_tool", retire, true); } } const replaced = new Set((spec.agents ?? []).map((d) => d.name)); for (const t of pool.tools) { const universe = childFacingUniverse(poolOf([t]), input.declaredPeers); for (const face of t.agentToolFaces ?? []) { if (face.authored === true && !replaced.has(face.name)) { const faceWhere = delegationListWhere(t.name, face.name); const faceUniverse = childFacingUniverse(poolOf([t]), withOwnServers(face.servers)); judgeToolNameList(faceWhere, "allowed", face.allowTools, faceUniverse, advise, "config.agent.unknown_tool", undefined, true); judgeToolNameList(faceWhere, "denied", face.denyTools, faceUniverse, advise, "config.agent.unknown_tool", retire, true); } } judgeToolNameList(delegationListWhere(t.name, undefined), "allowed", t.agentToolLevelAllowTools, universe, advise, "config.agent.unknown_tool"); judgeToolNameList(delegationListWhere(t.name, undefined), "denied", t.agentToolLevelDenyTools, universe, advise, "config.agent.unknown_tool", retire); } tellAuthors(); if (retiredLeftOut.length > 0) { const notice = retiredToolNameNotice("task_selector", retiredLeftOut, sessionId); const whole = [...new Set(retiredLeftOut.map((e) => `${e.field}\u0000${e.entry}\u0000${e.source ?? ""}`))].sort(); onceLedger.oncePerSession(announceDigest(`${POLICY_NAME_REFUSAL_CODE}:task_selector`, JSON.stringify(whole)), () => deliverEngineNotice(input.onNotice, notice)); } } export function refuseNonListToolCeiling(ceiling, seat) { if (!Array.isArray(ceiling)) throw refused(`${seat} is a value that is ${valueTypeLabel(ceiling)}, not a list of layers — the leg does not start. Fix the ceiling.`, "config.tool_face_control", "not_a_list"); } export function judgeHostToolCeiling(layers, agent, above = [], at = { seat: "RunWorkflowOptions.toolCeiling", legs: ["delegated"] }) { const where = (i) => `${at.seat}, layer ${i + 1}`; refuseNonListToolCeiling(layers, at.seat); layers.forEach((layer, i) => readSelectorLayer(layer, where(i), () => where(i), false)); const callerTools = agent.tools ?? []; const own = ownSelectorLayer({ allow: agent.allowTools ?? undefined, exclude: agent.excludeTools ?? undefined }, agent); const selector = compileToolSelector([...above, ...layers, own], at.legs); const pool = delegationPoolReading(callerTools, valveLeaves(selector)); const universe = rootFacingUniverse(mountedToolNames(callerTools), pool, { mcp: undefined, a2a: undefined }, legRetiredNameView(callerTools)); const unannounced = () => undefined; layers.forEach((layer, i) => { judgeToolNameList(where(i), "allowed", layer.allow, universe, unannounced, "config.tool_face_control"); judgeToolNameList(where(i), "denied", layer.deny, universe, unannounced, "config.tool_face_control"); }); }