/** * Tool-policy normalization for ONE delegation. * * A role declares a tool policy (`tools` shorthand or `toolFilter`). Before the * child is published the entries are expanded against the delegating agent's * CURRENTLY VISIBLE tool names, because the child's `tools.restrict()` rejects * an unknown name by throwing inside the child's creation window — an MCP * server that has not finished registering yet would otherwise turn every * delegation into a hard failure. * * Glob entries (`*`, `?`) expand to the concrete matches; literal entries that * are not visible are reported so the caller can warn (`onMissingTool: 'drop'`) * or refuse (`'error'`). An `allow` list that expands to nothing is passed * through as an explicit empty allow list — fail closed, never silently widen. */ /** Whether a policy entry is a glob rather than a literal tool name. */ export function isGlobPattern(entry) { return entry.includes('*') || entry.includes('?') } /** * Names the registry can expose but `tools.restrict()` refuses to accept. * `run_code` is the PTC presentation transport: `schemas()` lists it, while * `restrict()` throws on it by name. */ const UNRESTRICTABLE_TOOL_NAMES = new Set(['run_code']) /** * Whether a visible tool name must be kept out of every role policy. * @param name - tool name from the registry view. * @returns whether `tools.restrict()` would reject it outright. */ export function isUnrestrictableToolName(name) { return UNRESTRICTABLE_TOOL_NAMES.has(name) } /** * Extract the tool names the core complained about, so one delegation can drop * them and retry instead of failing with an error the model cannot act on. * @param error - the thrown value from `subagents.start` / `restrict()`. * @returns the offending names, deduplicated (empty when unrelated). */ export function parseUnrestrictableToolNames(error) { const text = String(error?.message ?? error ?? '') const names = [] const unknown = /names unknown global tools? ((?:"[^"]+"(?:,\s*)?)+)/.exec(text) if (unknown !== null) for (const match of unknown[1].matchAll(/"([^"]+)"/g)) names.push(match[1]) const reserved = /cannot name reserved PTC mode presentation transport "([^"]+)"/.exec(text) if (reserved !== null) names.push(reserved[1]) return [...new Set(names)] } /** * Read the set of names `tools.restrict()` will actually accept in one scope. * * The core only restricts INHERITED GLOBAL tools: a tool registered on the * agent's own scope layer (the `ops_*` family, for instance) is visible to that * agent but unknown to `restrict()`, which throws on it. That distinction is * invisible from `schemas()` alone, so a role whitelist that lists such a name * always loses its first `restrict()` call to an exception and silently * degrades through the reactive "drop what the error named" path. * * @param tools - the tools service (or a scoped view of it). * @param scope - the viewing scope (the agent). * @returns the restrictable names, or undefined when the registry cannot say. */ export function restrictableNameSet(tools, scope) { try { const view = typeof tools?.view === 'function' ? tools.view(scope) : undefined const names = view?.restrictableNames return names instanceof Set ? names : undefined } catch { return undefined } } /** * Split a filter into the part `restrict()` accepts and the parts it cannot. * * Three buckets, because the three causes need three different responses: * `scopeLocal` names are visible but owned by the agent's own layer, so they * stay visible whether or not the policy names them — omitting them is lossless * and it is what keeps `restrict()` from throwing; `unresolved` names are * neither restrictable nor visible AT THIS INSTANT and are a role-file error * only when the name is genuinely absent (see the caveat below); * `unenforceable` names were asked to be DENIED but cannot be, which is a real * capability gap the caller must report rather than swallow. * * CAVEAT on `unresolved`: a scope-local tool registered LAZILY — after this * scope is composed, or behind a `when` admission — is indistinguishable here * from a typo, because both are absent from the registry view at this instant. * Callers must therefore word the finding as "not visible now", never as "this * deployment does not register it": the latter is a claim this function cannot * support, and asserting it turns a timing artifact into a false role-file bug. * * @param filter - normalized `{ allow?, deny? }`. * @param options - `restrictableNames` and `visibleNames` sets. * @returns `{ filter?, scopeLocal, unresolved, unenforceable }`; `filter` is the * original filter untouched when `restrictableNames` is unavailable (never * fail open by guessing which names the core would reject). */ export function partitionToolFilter(filter, options = {}) { const restrictable = options.restrictableNames instanceof Set ? options.restrictableNames : undefined const visible = options.visibleNames instanceof Set ? options.visibleNames : undefined const scopeLocal = [] const unresolved = [] const unenforceable = [] if (restrictable === undefined) return { filter, scopeLocal, unresolved, unenforceable } const classify = (name, bucket) => { if (restrictable.has(name)) return true if (visible !== undefined && !visible.has(name)) unresolved.push(name) else bucket.push(name) return false } const kept = {} // An `allow` that survives as an EMPTY list must be kept, not dropped: an // empty allow means "no tools" (fail closed), while omitting the key means // "no restriction at all" (fail open). A role whose whitelist happens to be // entirely scope-local names must not silently escalate to the full surface. if (filter?.allow !== undefined) kept.allow = filter.allow.filter((name) => classify(name, scopeLocal)) if (filter?.deny !== undefined) { const deny = filter.deny.filter((name) => classify(name, unenforceable)) if (deny.length > 0) kept.deny = deny } if (kept.allow === undefined && kept.deny === undefined) { return { filter: undefined, scopeLocal, unresolved, unenforceable } } return { filter: kept, scopeLocal, unresolved, unenforceable } } /** * Copy a normalized filter without the named entries. An explicit `allow` list * is preserved even when it becomes empty (that still means "no tools"). * @param filter - normalized filter. * @param names - names to remove. * @returns the reduced filter, or undefined when nothing effective remains. */ export function dropToolFilterNames(filter, names) { const drop = new Set(names) const next = {} if (filter?.allow !== undefined) next.allow = filter.allow.filter((name) => !drop.has(name)) if (filter?.deny !== undefined) { const deny = filter.deny.filter((name) => !drop.has(name)) if (deny.length > 0) next.deny = deny } if (next.allow === undefined && next.deny === undefined) return undefined return next } function escapeRegExp(character) { return character.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') } /** * Compile one glob entry into a whole-name regular expression. * @param pattern - glob text. * @returns the compiled matcher. */ export function globToRegExp(pattern) { let source = '^' for (const character of pattern) { if (character === '*') source += '.*' else if (character === '?') source += '.' else source += escapeRegExp(character) } return new RegExp(`${source}$`) } /** * Expand one role tool policy against the visible tool names. * @param filter - `{ allow?, deny? }` as declared by the role. * @param visibleNames - tool names visible to the delegating agent. * @param options - `onMissing`: `drop` (default) or `error`. * @returns `{ filter?, missing, unmatched, dropped }`; `filter` is undefined * when nothing effective remains. * @throws when `onMissing` is `error` and any entry could not be resolved. */ export function expandToolFilter(filter, visibleNames, options = {}) { const visible = visibleNames instanceof Set ? visibleNames : new Set(visibleNames ?? []) const missing = [] const unmatched = [] const dropped = [] const expand = (entries) => { const names = [] for (const entry of entries ?? []) { if (!isGlobPattern(entry)) { if (visible.has(entry)) { if (!names.includes(entry)) names.push(entry) } else { missing.push(entry) dropped.push(entry) } continue } const matcher = globToRegExp(entry) const matches = [...visible].filter((name) => matcher.test(name)).sort() if (matches.length === 0) { unmatched.push(entry) dropped.push(entry) continue } for (const name of matches) if (!names.includes(name)) names.push(name) } return names } const hasAllow = filter?.allow !== undefined const hasDeny = filter?.deny !== undefined const expanded = {} if (hasAllow) expanded.allow = expand(filter.allow) if (hasDeny) { const deny = expand(filter.deny) if (deny.length > 0) expanded.deny = deny } if (options.onMissing === 'error' && (missing.length > 0 || unmatched.length > 0)) { const known = [...visible].sort().join(', ') || '(none)' const problems = [...missing.map((name) => `"${name}"`), ...unmatched.map((name) => `"${name}" (glob matched nothing)`)] throw new Error(`subagent-roles: tool policy names unavailable tool${problems.length > 1 ? 's' : ''} ${problems.join(', ')}; visible tools: ${known}`) } if (expanded.allow === undefined && expanded.deny === undefined) return { missing, unmatched, dropped } return { filter: expanded, missing, unmatched, dropped } } /** * Sum the schema characters of the named tools, for budget diagnostics. * @param schemaCharsByName - tool name to serialized-schema length. * @param names - the names to sum. * @returns the total character count. */ export function sumSchemaChars(schemaCharsByName, names) { let total = 0 for (const name of names) total += schemaCharsByName[name] ?? 0 return total }