UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

660 lines (659 loc) • 37.3 kB
import { heldBy, wireOf } from "./tool-name-readings.js"; import { ruleIssue } from "./permission-rules.js"; import { isCoveringRuleName, ruleNameCovers } from "./namespaced-rule-name.js"; import { nearMissSpellingOf, toolNameFaultOf } from "./tool-name-aliases.js"; import { catalogToolNames, isShellFaceToolName } from "./tool-registry.js"; import { startedShellOfCall } from "./call-shell.js"; import { ALLOW_LIST_GRANTS, ALLOW_RULE_MEMBERS, ALLOW_RULE_SHADOW_REASONS, isAllowListGrant } from "./allow-rule-shadow.js"; import { A2A_FINGERPRINT_MAX_CHARS, ruleSpellingOf, splitNamespacedName } from "@sema-agent/primitives"; import { callHostTargetOf } from "./host-target.js"; import { adjudicatePersistedDomainRules, wholeToolRuleReaches, adjudicatePersistedNameRules, commandCoverageOf, ruleWordsOf, ruleContentOf, noticeRuleText, parseRuleText, programRunReachIn, ruleToolGrammarOf, unusableDeclaredBase, PATH_RULE_BASES, PATH_RULE_BASE_LABEL } from "./permission-rule-model.js"; import { autoStripReasonOf as stripReasonOf, entryOfRow, readFaceAutoStrip } from "./auto-strip.js"; import { pathRuleLaneAnswer } from "./runner/permission-rule-lanes.js"; import { policyAnchors } from "./path-rule-binding.js"; import { receiptRefusal, receiveOwnProperties } from "./own-property-receipt.js"; import { callTargetReadingOf } from "./effective-path-target.js"; import { ASK_RULE_DISCLOSURE, MANDATE_DISCLOSURE, mandateDisclosureOf } from "./ask-origin.js"; import { inlineUntrusted, isMintableProbeReason } from "./untrusted-text.js"; import { callerKey } from "./caller-text.js"; import { valueTypeLabel } from "./tool-name-list.js"; import { deliverEngineNotice } from "./engine-notice.js"; import { entriesNotAppliedDetail, orderEntriesBySeverity } from "./entries-not-applied.js"; export const ALLOW_ENTRY_INERT_REASONS = Object.freeze(["wildcard_all", "namespace_wildcard", "content_unsupported", "grammar", "tool_name", "near_miss", "earlier_grammar"]); const INERT_REASON_WORDS = { wildcard_all: "a bare wildcard", namespace_wildcard: "a wildcard that names no scope", content_unsupported: "a rule form this tool does not have", grammar: "grammar", tool_name: "a tool name the engine does not read as current", near_miss: "differs by case", earlier_grammar: "read as no rule by this rule grammar", }; const NEAR_MISS_CARRIER = { run: "the mounted spelling is", pool: "a delegation pool carries", catalog: "the engine's tool catalog names" }; export function nonStringMemberLabel(value) { return `<not a string: ${valueTypeLabel(value)}>`; } export function nonListValueLabel(read) { return read.kind === "not_a_list" ? `<not a list: ${read.type}>` : "<a list whose entries cannot be read>"; } export function isRetiredLeftOut(e, roster) { if (e.reason !== "tool_name" || e.verdict !== "retired" || e.currentName !== undefined) return false; const name = ruleSpellingOf(e.entry)?.toolName; return name === undefined || roster === undefined || nearMissSpellingOf(name, roster) === undefined; } function ruleRowOf(parsed) { return { ...parsed, scope: { kind: "global" }, adds: [{ dot: { actor: "list", counter: 1 }, origin: "user", createdAt: "" }] }; } export function rootFacingToolNames(carried) { return new Set([...catalogToolNames(), ...carried]); } function toolNameReading(name, roster, behavior) { const fault = toolNameFaultOf(name, roster, behavior); return fault === undefined ? undefined : { kind: "inert", ...fault }; } export function readRuleEntry(raw, behavior, roster, retiredNames) { const inert = (reason) => ({ kind: "inert", reason }); const row = (compiled) => ({ kind: "row", compiled }); if (typeof raw !== "string") return { kind: "inert", reason: "grammar", valueType: valueTypeLabel(raw) }; const parsed = ruleSpellingOf(raw); if (parsed === undefined) return inert("grammar"); const name = parsed.toolName; if (name === "*" && behavior === "allow") return inert("wildcard_all"); const successor = retiredNames?.successorOf(name); if (successor !== undefined) return readRuleEntry(`${successor}${raw.slice(name.length)}`, behavior, roster, retiredNames); if (roster !== undefined) { const stale = toolNameReading(name, roster, behavior); if (stale !== undefined) return stale; } if (ruleContentOf(parsed) === undefined) { if (isCoveringRuleName(name, behavior)) return row({ kind: "covering", pattern: name }); if (name.includes("*")) return inert(splitNamespacedName(name) !== undefined ? "namespace_wildcard" : "grammar"); return row(isShellFaceToolName(name) ? { kind: "shell", name } : { kind: "tool", name }); } const grammar = ruleToolGrammarOf(name); if (grammar === undefined) return inert("content_unsupported"); const read = parseRuleText(raw, behavior); if ("rule" in read) return row({ kind: grammar, rule: ruleRowOf(read.rule) }); if (grammar === "command" && behavior === "allow" && read.reject.code === "invalid.bare_interpreter_prefix") { const wide = parseRuleText(raw, "deny"); if ("rule" in wide) return row({ kind: "command", rule: ruleRowOf({ ...wide.rule, behavior: "allow" }) }); } return inert(inertReasonOf(read.reject.code)); } export function compiledEntryName(compiled) { switch (compiled.kind) { case "tool": case "shell": return compiled.name; case "covering": return compiled.pattern; default: return compiled.rule.tool; } } function inertReasonOf(code) { return code === "unsupported.tool" ? "content_unsupported" : "grammar"; } export function compileAllowList(entries, behavior, roster, retiredNames) { const rows = []; const inert = []; for (const entry of entries) { const read = readRuleEntry(entry, behavior, roster, retiredNames); if (read.kind === "row") rows.push({ entry, compiled: read.compiled }); else { const { kind: _kind, ...why } = read; void _kind; inert.push({ entry: typeof entry === "string" ? entry : nonStringMemberLabel(entry), ...why }); } } return { rows, inert }; } function answersTo(req, has) { return heldBy("allowEntry.names", { has }, req); } export function autoStripReasonOf(compiled, call, allShell) { return stripReasonOf(compiled, () => call !== undefined && answersTo(call, isShellFaceToolName), allShell); } export function autoStripped(compiled, call, allShell) { return autoStripReasonOf(compiled, call, allShell) !== undefined; } export function strippedInAuto(compiled, call, mode, allShell) { return mode === "auto" && autoStripped(compiled, call, allShell); } function allowEntrySpeaksFor(compiled, call, names) { if (compiled.kind === "tool" || compiled.kind === "shell" || compiled.kind === "covering") return nameRowReaches(compiled, call, names); return ruleWordsOf(call, "allow").includes(compiled.rule.tool); } function strippedFor(row, call, mode, allShell, names, told) { if (mode !== "auto") return false; const reason = autoStripReasonOf(row.compiled, call, allShell); if (reason === undefined) return false; if (told !== undefined && row.behavior === "allow" && allowEntrySpeaksFor(row.compiled, call, names)) told(row, reason); return true; } export function autoStripReasonOfRow(rule, call, mode, allShell) { if (mode !== "auto" || rule.behavior !== "allow") return undefined; const entry = entryOfRow(rule); return entry === undefined ? undefined : autoStripReasonOf(entry, call, allShell); } export function autoStrippedRule(rule, call, mode, allShell) { return autoStripReasonOfRow(rule, call, mode, allShell) !== undefined; } export function allowEntryAutoStrip(entry) { const read = readRuleEntry(entry, "allow"); return read.kind === "row" ? readFaceAutoStrip(read.compiled) : undefined; } export function classifiesAllShell(spec) { return spec.classifyAllShell === true; } const NO_LEADS = new Map(); function nameRowReaches(compiled, req, reach) { if (reach === "wire_name") { const wire = wireOf("allowEntry.launchListNames", req); if (compiled.kind === "tool" || compiled.kind === "shell") return compiled.name === wire; return compiled.kind === "covering" && ruleNameCovers(compiled.pattern, wire); } if (compiled.kind === "tool" || compiled.kind === "shell") return wholeToolRuleReaches(compiled.name, req); return compiled.kind === "covering" && answersTo(req, (n) => ruleNameCovers(compiled.pattern, n)); } function commandOf(req, behavior) { const tool = ruleWordsOf(req, behavior).find((n) => ruleToolGrammarOf(n) === "command"); const command = req.args?.command; return tool !== undefined && typeof command === "string" ? { tool, command, shell: startedShellOfCall(req) } : undefined; } function admissionCallOf(call, ctx, liveCwd, posture) { return { tool: call.tool, command: call.command, shell: call.shell, cwd: ctx.root, ...(ctx.sessionId !== undefined ? { sessionId: ctx.sessionId } : {}), ...(liveCwd !== undefined ? { execCwd: liveCwd } : {}), posture }; } export function uncoveredCommandSegment(rows, req, ctx, posture) { const call = commandOf(req, "allow"); if (call === undefined) return undefined; const rules = rows.flatMap((r) => (r.behavior === "allow" && r.compiled.kind === "command" ? [r.compiled.rule] : [])); const coverage = commandCoverageOf(rules, admissionCallOf(call, ctx, ctx.liveCwd(), posture)); return "uncovered" in coverage ? coverage.uncovered : undefined; } export function wholeToolEntryOf(rows, tool, behavior, names = "every_name") { return rows.find((r) => r.behavior === behavior && nameRowReaches(r.compiled, tool, names)); } export function judgeAllowEntries(rows, req, behavior, ctx, posture = "grant", names = "every_name") { const live = rows.filter((r) => r.behavior === behavior); if (live.length === 0) return undefined; const nameRow = wholeToolEntryOf(live, req, behavior, names); if (nameRow !== undefined) return [nameRow]; const words = ruleWordsOf(req, behavior); const call = commandOf(req, behavior); const liveCwd = ctx.liveCwd(); if (call !== undefined) { const byRule = new Map(); for (const r of live) if (r.compiled.kind === "command") byRule.set(r.compiled.rule, r); if (behavior === "allow") { const coverage = commandCoverageOf([...byRule.keys()], admissionCallOf(call, ctx, liveCwd, posture)); const hits = ("covering" in coverage ? coverage.covering : []).flatMap((rule) => byRule.get(rule) ?? []); if (hits.length > 0) return hits; } else { for (const [rule, row] of byRule) { if (programRunReachIn(call.shell, rule, call.command).reach !== "not_reached") return [row]; } } } const pathRows = live.filter((r) => r.compiled.kind === "path"); if (pathRows.length > 0) { const sets = new Map(); for (const r of pathRows) { const key = anchorsKey(r.pathBases); const set = sets.get(key) ?? { anchors: key === UNDECLARED_SET ? ctx.anchors : policyAnchors(r.pathBases ?? {}, ctx.anchors), rows: [] }; sets.set(key, set); set.rows.push(r); } for (const name of words.filter((n) => ruleToolGrammarOf(n) === "path")) { let unreadable; for (const set of sets.values()) { const table = set.rows.map((r) => r.compiled.rule); const answer = pathRuleLaneAnswer(table, { ...req, toolName: name }, { root: ctx.root, sessionId: ctx.sessionId, anchorsOf: () => set.anchors, leads: callTargetReadingOf(req)?.leads ?? NO_LEADS }); if (answer === undefined) continue; if ("unreadable" in answer) { if (behavior === "deny") unreadable ??= set.rows[0]; continue; } if ("behavior" in answer && answer.behavior === behavior) { const rule = answer.rules[0]?.rule; return [set.rows.find((r) => r.compiled.rule.rule === rule) ?? set.rows[0]]; } } if (unreadable !== undefined) return [unreadable]; } } for (const grammar of ["name", "domain"]) { const familyRows = live.filter((r) => r.compiled.kind === grammar); if (familyRows.length === 0) continue; const table = familyRows.map((r) => r.compiled.rule); for (const name of words.filter((n) => ruleToolGrammarOf(n) === grammar)) { const at = { tool: name, cwd: ctx.root, ...(ctx.sessionId !== undefined ? { sessionId: ctx.sessionId } : {}) }; const named = { ...req, toolName: name }; const verdict = grammar === "name" ? adjudicatePersistedNameRules(table, { ...at, request: req }) : adjudicatePersistedDomainRules(table, { ...at, hosts: { tighten: callHostTargetOf(named, "tighten"), grant: callHostTargetOf(named, "grant") } }); if (verdict !== undefined && verdict.behavior === behavior) return [familyRows.find((r) => r.compiled.rule === verdict.rules[0]) ?? familyRows[0]]; } } return undefined; } export function allowingRows(rows, req, mode, allShell, told, names = "every_name") { return rows.filter((r) => !strippedFor(r, req, mode, allShell, names, told)); } function allowListMemberOf(entry) { return typeof entry === "string" ? { rule: entry } : entry; } function anchorsKey(pathBases) { return JSON.stringify(PATH_RULE_BASES.map((word) => pathBases?.[word] ?? null)); } function objectMembersOf(m) { return { ...(m.pathBases !== undefined ? { pathBases: m.pathBases } : {}), ...(m.peerFingerprint !== undefined ? { peerFingerprint: m.peerFingerprint } : {}), ...(m.grant !== undefined ? { grant: m.grant } : {}) }; } const UNDECLARED_SET = anchorsKey(undefined); function allowListMemberKey(member) { return JSON.stringify([member.rule, anchorsKey(member.pathBases), member.peerFingerprint ?? null, member.grant ?? null]); } export class AllowEntryTable { held = []; heldKeys = new Set(); receivedAt = new Map(); seed(entries, reading = {}) { const members = entries.map(allowListMemberOf); if (reading.received === true) { this.receivedAt = new Map(); members.forEach((m, i) => { const key = allowListMemberKey(m); const at = this.receivedAt.get(key); if (at === undefined) this.receivedAt.set(key, [i]); else at.push(i); }); } const inert = []; for (const member of members) { const read = readRuleEntry(member.rule, "allow", reading.roster, reading.retiredNames); if (read.kind !== "row") { const { kind: _kind, ...why } = read; void _kind; inert.push({ entry: member.rule, ...why }); continue; } const key = allowListMemberKey(member); if (this.heldKeys.has(key)) continue; this.heldKeys.add(key); this.held.push({ behavior: "allow", entry: member.rule, compiled: read.compiled, ...objectMembersOf(member) }); } return inert; } entries() { return this.held.map((r) => { const members = objectMembersOf(r); return Object.keys(members).length === 0 ? r.entry : Object.freeze({ rule: r.entry, ...members }); }); } holdsPathRows() { return this.held.some((r) => r.compiled.kind === "path"); } lane(ctx) { return { allowing: (req, mode) => { const told = ctx.onAutoStripped; const kept = allowingRows(this.held, req, mode, ctx.classifyAllShell === true, told === undefined ? undefined : (r, reason) => told({ entry: r.entry, reason }, req), "wire_name"); const hit = judgeAllowEntries(kept, req, "allow", ctx, "grant", "wire_name"); if (hit === undefined) return undefined; const entries = hit.map((r) => r.entry); const at = (r) => this.receivedAt.get(allowListMemberKey({ rule: r.entry, ...objectMembersOf(r) })) ?? []; const positions = hit.flatMap(at).sort((a, b) => a - b); const reaches = (r) => hit.includes(r) || judgeAllowEntries([r], req, "allow", ctx, "grant", "wire_name") !== undefined; const bound = kept.flatMap((r) => ((r.peerFingerprint === undefined && r.grant === undefined) || !reaches(r) ? [] : [{ entry: r.entry, ...(r.peerFingerprint !== undefined ? { peerFingerprint: r.peerFingerprint } : {}), ...(r.grant !== undefined ? { grant: r.grant } : {}), ...(at(r).length > 0 ? { positions: at(r) } : {}) }])); return { entries, ...(positions.length > 0 ? { positions } : {}), ...(bound.length > 0 ? { bound } : {}) }; }, }; } } export function seedAllowEntryTables(tables, lists, roster, retiredNames) { tables.request.seed(lists.inherited ?? [], { retiredNames }); const requestInert = tables.request.seed(lists.request ?? [], { roster, received: true, retiredNames }); const deploymentInert = tables.deployment.seed(lists.deployment ?? [], { roster, received: true, retiredNames }).filter((e) => e.reason === "tool_name" || e.reason === "near_miss"); return [ ...lists.skillInert.map((e) => ({ source: "skill", ...e })), ...requestInert.map((e) => ({ source: "request", ...e })), ...deploymentInert.map((e) => ({ source: "deployment", ...e })), ]; } export function withDeploymentAllowedTools(deps) { if (deps.allowedTools === undefined) return deps; const allowedTools = screenAllowedToolsValue(deps.allowedTools, "RunnerDeps.allowedTools"); const inert = new AllowEntryTable().seed(allowedTools ?? []); for (const notice of allowedToolsNotGrantedNotices(inert.map((e) => ({ source: "deployment", ...e })), undefined)) deliverEngineNotice(deps.onNotice, notice); return { ...deps, allowedTools }; } export const INVALID_PERMISSION_RULES_CODE = "config.invalid_permission_rules"; const ALLOW_LIST_SEATS = { "TaskSpec.allowedTools": "the request's allow list", "RunnerDeps.allowedTools": "the deployment's allow list", }; const GRANT_SEATS = Object.freeze({ preapproval: Object.freeze(["RunnerDeps.allowedTools"]), recipe: Object.freeze(["RunnerDeps.allowedTools", "TaskSpec.allowedTools"]), }); const ANCHORED_MEMBER_KEYS = new Set(["rule", "pathBases", "peerFingerprint", "grant"]); const PATH_BASE_WORDS = new Set(PATH_RULE_BASES); function receiveAnchoredMember(entry, seat, at) { const member = receiveOwnProperties(entry, { subject: at, unit: "member", moment: "when the list is read" }); for (const key of Object.keys(member)) { if (!ANCHORED_MEMBER_KEYS.has(key)) throw receiptRefusal(`${at} carries ${callerKey(key)}, which is not a member of a list entry (its members are rule, pathBases, peerFingerprint and grant) — refused rather than read without it`); } const own = (key) => (Object.hasOwn(member, key) ? member[key] : undefined); const rule = own("rule"); if (typeof rule !== "string") throw receiptRefusal(`${at}.rule must be a permission-rule string (got ${valueTypeLabel(rule)})`); const peerFingerprint = own("peerFingerprint"); if (peerFingerprint !== undefined && (typeof peerFingerprint !== "string" || peerFingerprint.length === 0 || peerFingerprint.length > A2A_FINGERPRINT_MAX_CHARS)) throw receiptRefusal(`${at}.peerFingerprint must be an identity stamp: a non-empty string of at most ${A2A_FINGERPRINT_MAX_CHARS} characters (got ${valueTypeLabel(peerFingerprint)})`); const grant = own("grant"); if (grant !== undefined && !isAllowListGrant(grant)) throw receiptRefusal(`${at}.grant must be one of ${ALLOW_LIST_GRANTS.join(", ")} (got ${typeof grant === "string" ? "another word" : valueTypeLabel(grant)})`); if (grant !== undefined && !GRANT_SEATS[grant].includes(seat)) { throw receiptRefusal(`${at}.grant is "${grant}", which only ${GRANT_SEATS[grant].map((s) => `${ALLOW_LIST_SEATS[s]} (${s})`).join(" or ")} carries — ${ALLOW_LIST_SEATS[seat]} cannot mark its own entry so; refused rather than recorded as one`); } const bound = { ...(peerFingerprint !== undefined ? { peerFingerprint: peerFingerprint } : {}), ...(grant !== undefined ? { grant } : {}) }; const pathBases = own("pathBases"); if (pathBases === undefined) { if (Object.keys(bound).length === 0) throw receiptRefusal(`${at} carries none of pathBases, peerFingerprint and grant — a member that carries none is written as the rule string`); return Object.freeze({ rule, ...bound }); } if (typeof pathBases !== "object" || pathBases === null || Array.isArray(pathBases)) throw receiptRefusal(`${at}.pathBases must be an object of base words (got ${valueTypeLabel(pathBases)})`); const bases = receiveOwnProperties(pathBases, { subject: `${at}.pathBases`, unit: "base word", moment: "when the list is read" }); const held = Object.create(null); for (const [word, value] of Object.entries(bases)) { if (!PATH_BASE_WORDS.has(word)) throw receiptRefusal(`${at}.pathBases carries ${callerKey(word)}, which is not a base word (${PATH_RULE_BASES.join(", ")}) — refused rather than read without it`); if (typeof value !== "string") throw receiptRefusal(`${at}.pathBases.${word} must be a path string (got ${valueTypeLabel(value)})`); held[word] = value; } if (Object.keys(held).length === 0) throw receiptRefusal(`${at}.pathBases declares no base word (${PATH_RULE_BASES.join(", ")}) — a member that declares no anchors leaves pathBases out`); return Object.freeze({ rule, pathBases: Object.freeze(held), ...bound }); } export function screenAllowedToolsValue(value, seat) { if (value === undefined) return undefined; const label = ALLOW_LIST_SEATS[seat]; const issues = []; const out = []; if (!Array.isArray(value)) { issues.push(ruleIssue("", "invalid.entry_type", `${label} must be a list of permission-rule strings or anchored rule members (got ${value === null ? "null" : typeof value})`, { name: seat })); } else { const list = value; for (let i = 0; i < list.length; i++) { const entry = list[i]; if (typeof entry === "string") { out.push(entry); continue; } if (typeof entry !== "object" || entry === null || Array.isArray(entry)) { issues.push(ruleIssue("", "invalid.entry_type", `entry ${i} of ${label} must be a permission-rule string or an anchored rule member (got ${entry === null ? "null" : Array.isArray(entry) ? "an array" : typeof entry})`, { name: seat })); continue; } const member = receiveAnchoredMember(entry, seat, `${seat}[${i}]`); const read = readRuleEntry(member.rule, "allow"); const bad = read.kind === "row" && read.compiled.kind === "path" && member.pathBases !== undefined ? unusableDeclaredBase(read.compiled.rule, member.pathBases) : undefined; if (bad !== undefined) { issues.push(ruleIssue(noticeRuleText(member.rule), "unsupported.path_base", `entry ${i} of ${label} is relative to ${PATH_RULE_BASE_LABEL[bad.base]}, and the one its set declares (pathBases.${bad.key}) is not an absolute path of its tree's family — the rule could not be judged on any call`, { name: seat })); continue; } out.push(member); } } if (issues.length > 0) { const e = new Error(`${label}: ${issues.length} invalid entr${issues.length === 1 ? "y" : "ies"} — refusing rather than running without them:\n${issues.map((i) => ` [${i.code}] ${i.message}`).join("\n")}`); e.code = INVALID_PERMISSION_RULES_CODE; e.issues = issues; throw e; } return Object.freeze(out); } const SHADOW_ENTRIES_MAX = 5; const SHADOW_ENTRY_MAX_CHARS = 200; export function allowRuleShadowOf(member, entries, reason) { const shown = entries.slice(0, SHADOW_ENTRIES_MAX).map((e) => inlineUntrusted(e, SHADOW_ENTRY_MAX_CHARS)); return { member, entries: shown, ...(entries.length > shown.length ? { omitted: entries.length - shown.length } : {}), ...(reason !== undefined ? { reason } : {}) }; } export function withAllowRuleShadow(list, shadow) { const at = list.findIndex((s) => s.member === shadow.member); if (at < 0) return [...list, shadow]; const held = list[at]; const entries = [...held.entries, ...shadow.entries]; const shown = entries.slice(0, SHADOW_ENTRIES_MAX); const omitted = (held.omitted ?? 0) + (shadow.omitted ?? 0) + (entries.length - shown.length); const reason = held.reason === "identity_changed" || shadow.reason === "identity_changed" ? "identity_changed" : (held.reason ?? shadow.reason); return list.map((s, i) => (i === at ? { member: held.member, entries: shown, ...(omitted > 0 ? { omitted } : {}), ...(reason !== undefined ? { reason } : {}) } : s)); } const MEMBER_SET = new Set(ALLOW_RULE_MEMBERS); const SHADOW_REASON_SET = new Set(ALLOW_RULE_SHADOW_REASONS); export function readAllowRuleShadows(value) { try { if (!Array.isArray(value) || value.length === 0) return undefined; const list = value; const out = []; for (const r of list) { if (typeof r !== "object" || r === null) return undefined; const { member, entries, omitted, reason } = r; if (!MEMBER_SET.has(member) || !Array.isArray(entries) || !entries.every((e) => typeof e === "string")) return undefined; const shadow = allowRuleShadowOf(member, entries, SHADOW_REASON_SET.has(reason) ? reason : undefined); const carried = typeof omitted === "number" && Number.isInteger(omitted) && omitted > 0 ? omitted : 0; out.push(carried > 0 ? { ...shadow, omitted: (shadow.omitted ?? 0) + carried } : shadow); } return out; } catch { return undefined; } } const ARRIVED_MARKED = "this call arrived already marked as requiring confirmation (an earlier layer of this run, or the task that delegated it, judged it so), and that mark outranks an allow entry"; export const SHADOW_REASON = Object.freeze({ content_question: "the call is the engine's own question to a person", hook: "an extension's screening asks about this call (a PreToolUse hook or a tool.check station) — the deployment's own screening is answered by a person", ancestor: "the task that delegated this one owns this question", dangerous_delete: "this removal targets a protected location (the filesystem root, a top-level directory, a home directory, or a workspace directory or one of its ancestors)", transcript_write: "this write targets the session transcript", org_rule: "an organization policy rule requires approval for this call", org_unreadable: "this deployment's organization policy cannot currently be read, so whether one of its rules forbids this call is unknown", rule_unreadable: "the person's standing permission rules cannot currently be read, so whether one of them forbids this call is unknown", call_unreadable: "this call cannot be read against a standing deny or ask rule that may govern it, so whether that rule forbids it is unknown", ask_rule: ASK_RULE_DISCLOSURE, denial_limit_fallback: "the auto-mode classifier refused too many calls in a row, so a person decides", classifier_no_ruling: "the auto-mode classifier could not judge this call, so a person decides", requires_user_interaction: "this tool's server declares that a call must be put to a person", cross_boundary: MANDATE_DISCLOSURE.cross_boundary_taint, operator_forced: ARRIVED_MARKED, shell_floor: MANDATE_DISCLOSURE.operator_always, target_unresolved: MANDATE_DISCLOSURE.target_unresolved, write_protection_on_disk: MANDATE_DISCLOSURE.write_protection, write_protection: MANDATE_DISCLOSURE.write_protection, tool_marks_mcp: MANDATE_DISCLOSURE.tool_marks, tool_marks_a2a: MANDATE_DISCLOSURE.tool_marks, unfinished_check: "the check of what this command reads did not finish, so its safety checks did not run", policy_rra: "the deployment's policy requires a real approval for this call", sandbox_override: "this call asks to run outside the run's OS sandbox (dangerouslyDisableSandbox)", sandbox_network: "a command in the run's OS sandbox connects to a host its sandbox does not list", artifact_shared_read: "this read targets another task's shared artifact", mode: "the permission mode puts this question to a person", a2a_inside: "this peer is registered inside the trust boundary and accepts only a grant bound to its current identity stamp (the stamp its registration carries now)", unverifiable_delete: ARRIVED_MARKED, unverifiable_shell_text: ARRIVED_MARKED, unstated: ARRIVED_MARKED, ordinary: ARRIVED_MARKED, }); const SHADOW_REASON_PHRASE = Object.freeze({ identity_changed: "bound to an identity this peer no longer has: its registration changed since the grant was given", unbound: "not bound to this peer's identity", }); function memberPhrase(s) { return s.reason !== undefined ? `${memberNamed(s)} (${SHADOW_REASON_PHRASE[s.reason]})` : memberNamed(s); } function memberNamed(s) { const listed = `${s.entries.join(", ")}${s.omitted !== undefined ? ` and ${s.omitted} more` : ""}`; switch (s.member) { case "hook": return "a hook's allow"; case "deployment": return `the deployment's allowedTools (${listed})`; case "persisted": return s.entries.length + (s.omitted ?? 0) === 1 ? `a persisted allow rule (${listed})` : `persisted allow rules (${listed})`; case "skill": return `an active skill's allowed-tools (${listed})`; case "request": return `this run's allowedTools (${listed})`; default: { const exhaustive = s.member; return exhaustive; } } } export function allowRuleShadowSentence(shadows, ask) { const one = shadows.length === 1 && (shadows[0].member === "hook" || shadows[0].entries.length + (shadows[0].omitted ?? 0) === 1); const { askClass, mandate, authoredBy, probeReason } = ask; const account = typeof probeReason === "string" && probeReason.trim().length > 0 && isMintableProbeReason(probeReason) ? probeReason : undefined; const why = mandate !== undefined ? mandateDisclosureOf(mandate, account) : authoredBy === "deployment" ? "this deployment requires a person's confirmation for this call" : askClass === "probe" ? account : SHADOW_REASON[askClass ?? "ordinary"]; return `${shadows.map(memberPhrase).join("; ")} ${one ? "matches this call but does not clear the ask" : "match this call but do not clear the ask"}${why !== undefined ? ` — ${why}` : ""}`; } export const askFallbackMessage = (toolName) => `approval required for "${toolName}"`; export const inheritedAskFallbackMessage = (toolName) => `approval required for "${toolName}" (inherited parent policy)`; export function cardDisclosureOf(decision, fallbackMessage) { const base = decision.message ?? fallbackMessage; const rule = decision.matchedAskRule; const outlet = { ...(decision.editRewritten !== undefined ? { editRewritten: decision.editRewritten } : {}), ...(typeof rule === "string" && rule.length > 0 ? { matchedAskRule: rule } : {}), ...(decision.fromApprovalList === true ? { fromApprovalList: true } : {}), }; const shadows = readAllowRuleShadows(decision.allowRuleShadowed); if (shadows === undefined) return { message: base, ...outlet }; return { message: `${base} (${allowRuleShadowSentence(shadows, decision)})`, allowRuleShadowed: shadows, ...outlet }; } const NOTICE_ENTRIES_SHOWN = 5; const UNSEEN_IN_ENTRY = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Zs}]/gu; const ENTRY_RENDER_MAX = 122; function escapedCodePoint(ch) { const cp = ch.codePointAt(0) ?? 0; const hex = cp.toString(16).padStart(4, "0"); return cp > 0xffff ? `\\u{${hex}}` : `\\u${hex}`; } export function spelledListEntry(entry) { return JSON.stringify(entry) .replace(/ {2,}/g, (run) => "\\u0020".repeat(run.length)) .replace(UNSEEN_IN_ENTRY, (ch) => (ch === " " ? ch : escapedCodePoint(ch))); } export function renderListEntry(entry) { return inlineUntrusted(spelledListEntry(entry), ENTRY_RENDER_MAX); } export function inertEntryPhrase(e) { if (e.valueType !== undefined) return `a value that is ${e.valueType} (grammar: not a string)`; const spelling = e.currentName !== undefined ? inlineUntrusted(e.currentName, 120) : undefined; const why = (() => { if (e.reason === "near_miss") return `${INERT_REASON_WORDS.near_miss}: ${NEAR_MISS_CARRIER[e.carriedBy ?? "run"]} "${spelling}"`; if (e.reason !== "tool_name" || e.verdict === undefined) return INERT_REASON_WORDS[e.reason]; switch (e.verdict) { case "retired": return `a retired tool name${spelling !== undefined ? `, now "${spelling}"` : ""}`; case "unprefixed_namespace": return 'a "__" name with no protocol prefix'; case "unmintable_segment": if (e.ambiguous === true && e.guidance !== undefined) return `${e.guidance}${spelling !== undefined ? ` Write "${spelling}"` : ""}`; return `a namespaced name with a segment the engine never mints${spelling !== undefined ? `, write "${spelling}"` : ""}`; default: { const exhaustive = e.verdict; return exhaustive; } } })(); return `${renderListEntry(e.entry)} (${why})`; } function inertEntriesListed(of) { const shown = of .slice(0, NOTICE_ENTRIES_SHOWN) .map((e) => `${e.source === "skill" ? `skill ${inlineUntrusted(e.skill, 80)} ${e.list}` : e.source === "request" ? "this run's allowed-tools list" : "the deployment's allowed-tools list"} ${inertEntryPhrase(e)}`); return `${shown.join("; ")}${of.length > shown.length ? `; and ${of.length - shown.length} more` : ""}`; } export function allowedToolsNotGrantedNotices(inert, sessionId) { const entryOf = (e) => ({ ...e, entry: noticeRuleText(e.entry) }); const route = sessionId !== undefined ? { sessionId } : {}; const refusing = orderEntriesBySeverity(inert.filter((e) => "list" in e && e.list === "disallowed-tools")); const granting = orderEntriesBySeverity(inert.filter((e) => !("list" in e && e.list === "disallowed-tools"))); const notices = []; if (granting.length > 0) { notices.push({ code: "config.entries_not_applied", message: `${granting.length} allowed-tools entr${granting.length === 1 ? "y grants" : "ies grant"} or refuse${granting.length === 1 ? "s" : ""} nothing — ${inertEntriesListed(granting)}. ` + "On an allow list a `*` outside a protocol name's tool segment (`*`, `Re*d`, `mcp__*`) names no scope and grants nothing — the entries beside it still grant — and a rule the grammar refuses (`grammar`) or one on a tool with no such rule form (an allow by path is an `Edit(…)` or `Read(…)` rule) grants nothing; a tool name must be spelled as the tool is mounted; name the tools (or `mcp__<server>`) instead.", detail: { ...entriesNotAppliedDetail("allow_entry_inert", granting.map(entryOf)), ...route }, }); } if (refusing.length > 0) { const { kind: _kind, ...members } = entriesNotAppliedDetail("allow_entry_inert", refusing.map(entryOf)); notices.push({ code: "config.skill_deny_unreadable", message: `${refusing.length} disallowed-tools entr${refusing.length === 1 ? "y refuses" : "ies refuse"} nothing — ${inertEntriesListed(refusing)}. ` + "Such an entry keeps its Skill from activating: a refusal that reads as nothing is not dropped. Name the tools it is meant to refuse as they are mounted.", detail: { ...members, ...route }, }); } return notices; }