UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

700 lines (699 loc) • 45.3 kB
import { ownerStoreOf, ruleSourceOf } from "../permission-rule-provider.js"; import { holdsRuleWriter, sameRuleIdentity } from "../permission-rule-store.js"; import { identityUnread, reachesEveryCall, unreadableRowFaultsOf, unreadableRowsInScope } from "./unreadable-person-rows.js"; import { readPrincipal } from "../principal-name.js"; import { ORG_ADJUDICATION_TIMEOUT_MS, orgResolutionHeld, orgRowsStandOverFace } from "../permission-rule-org.js"; import { canonicalize } from "../canonical-json.js"; import { PATH_RULE_FACES, READ_RULE_TOOL, eligiblePersisted, noticeRuleText, ruleToolGrammarOf } from "../permission-rule-model.js"; import { indexOfUnescaped } from "@sema-agent/primitives"; import { ROSTERLESS_RETIRED_VIEW, ruleListUnderView } from "../tool-name-aliases.js"; import { bindPathRules, persistedRowAnchors, projectScopeIdentity } from "../path-rule-binding.js"; import { DEFAULT_GATE_AWAIT_TIMEOUT_MS, gateWaitFailureOf, withGateTimeout } from "../gate-bounded-await.js"; import { thrownText } from "../thrown-value.js"; import { ruleStoreFaultReasonOf, ruleStoreSourcesWord } from "../rule-store-fault.js"; import { inlineUntrusted } from "../untrusted-text.js"; import { deliverEngineNotice } from "../engine-notice.js"; import { entriesNotAppliedDetail } from "../entries-not-applied.js"; import { compileReadDeny, compileWriteDeny, readDenySeat, rowsWhereTheyLead } from "../../tools/fs/read-deny.js"; import { carryHomeViews, placeReadDenyAtHome, readDenyOver } from "../../tools/fs/read-deny-home.js"; import { composeReadChecks, readStationsHold } from "../../tools/fs/file-read-check.js"; import { readStationMemberOf } from "../../tools/fs/shell-read-check.js"; import { compileSessionRuleBucket, readSessionRulesShape, unreadableDenyEntries } from "../session-policy-store.js"; import { readRuleEntry, wholeToolEntryOf } from "../allow-entry.js"; import { rootAdmittingArtifactStore } from "../../tools/fs/safety.js"; import { emitTrace } from "../trace.js"; const PARTITIONS = ["session", "durable"]; const partitionOf = (source) => (source === "session" ? "session" : "durable"); const tightening = (rule) => rule.behavior === "deny" || rule.behavior === "ask"; export const PERSON_READ_BOUND_MS = ORG_ADJUDICATION_TIMEOUT_MS - 1_000; export const PATH_TABLES_READY_BOUND_MS = DEFAULT_GATE_AWAIT_TIMEOUT_MS; const COMPILED_TABLES_KEPT = 8; export const READ_FACE_SEATS_BEYOND = Object.freeze(["org", "session_rules", "ancestor_session_rules", "skill_grants"]); const READ_TOOL_CALL = { toolName: READ_RULE_TOOL }; const entryRowOverReads = (compiled, behavior) => compiled.kind === "path" ? PATH_RULE_FACES[compiled.rule.tool]?.[behavior]?.includes("read") === true : wholeToolEntryOf([{ behavior, entry: "", compiled }], READ_TOOL_CALL, behavior) !== undefined; export function seatStandsOverReads(s) { switch (s.seat) { case "org": return s.org.status === "unavailable" || orgRowsStandOverFace(s.org.rules, "read"); case "session_rules": case "ancestor_session_rules": { const shaped = readSessionRulesShape(s.rules); if (s.unread === true || "fault" in shaped) return true; const rules = { ...shaped.rules, toolDeny: ruleListUnderView(shaped.rules.toolDeny, ROSTERLESS_RETIRED_VIEW) }; if (unreadableDenyEntries(rules).length > 0) return true; if (compileSessionRuleBucket(rules, "toolDeny").rows.some((r) => entryRowOverReads(r.compiled, "deny"))) return true; return shaped.rules.toolAllow !== undefined && wholeToolEntryOf(compileSessionRuleBucket(shaped.rules, "toolAllow").rows.map((r) => ({ ...r, behavior: "allow" })), READ_TOOL_CALL, "allow") === undefined; } case "skill_grants": return s.records.some((r) => { const read = r.behavior === "deny" ? readRuleEntry(r.entry, "deny", undefined, ROSTERLESS_RETIRED_VIEW) : undefined; return read !== undefined && (read.kind === "inert" || entryRowOverReads(read.compiled, "deny")); }); } } export const EMPTY_READ_ROOTS = Object.assign(() => [], { forCall: () => () => [], ready: () => Promise.resolve() }); export function createPersonPathRows(cfg) { const provider = cfg.provider; const anonymous = readPrincipal(cfg.principal).kind === "absent"; const holdsPersonRows = provider !== undefined && provider.partitions.durable && (!anonymous || cfg.localOwnerDeclared); const partitions = PARTITIONS.filter((p) => (p === "durable" ? provider?.partitions.durable === true : provider?.partitions.session === true)); const fixedOwner = (() => { if (!holdsPersonRows || !partitions.includes("session") || typeof cfg.sessionId !== "string" || cfg.sessionId === "") return undefined; const named = readPrincipal(cfg.principal); return named.kind === "name" ? { kind: "principal", principal: named.name } : { kind: "local-owner" }; })(); const sessionRowOwner = () => { if (fixedOwner === undefined) return undefined; try { return holdsRuleWriter(ownerStoreOf(provider, cfg.principal, cfg.localOwnerDeclared)) ? fixedOwner : undefined; } catch { return undefined; } }; const unit = { durable: { failedSeq: 0 }, session: { failedSeq: 0 } }; let seqs = 0; const pins = new Map(); let prepared; let silent; let answeredSeq = 0; let requestSeq = 0; let compile; const compiled = new Map(); let unitTables; const unanchoredSaid = new Set(); let orgGuard = { seq: 0, stands: false }; const orgStands = (org) => org !== undefined && seatStandsOverReads({ seat: "org", org }); const land = (o) => { if (o.cut === true) return; let changed = false; if (o.view !== undefined && o.seq > orgGuard.seq) orgGuard = { seq: o.seq, stands: orgStands(o.view.org) }; for (const p of partitions) { const cell = unit[p]; const okSeq = cell.ok?.seq ?? 0; if (o.failed.has(p) || o.view === undefined) { if (o.seq > okSeq && o.seq > cell.failedSeq) { cell.failedSeq = o.seq; changed = true; } } else if (o.seq >= cell.failedSeq && o.seq > okSeq) { cell.ok = { seq: o.seq, rows: readRows(p, o.view, cell.ok), unreadable: unreadableOf(p, o.view) }; changed = true; } } if (changed && compile !== undefined) refreshUnitTables(); }; const hasDroppedIn = (p, view) => p === "durable" && (view.droppedRows ?? []).some((d) => d.reason === "scope_root_not_absolute"); const readRows = (p, view, before) => { const rows = view.rules.filter((r) => partitionOf(r.source) === p); if (!unreadableOf(p, view).some(identityUnread) && !hasDroppedIn(p, view)) return rows; const removed = view.removed ?? []; return [...rows, ...(before?.rows ?? []).filter((w) => tightening(w) && !rows.some((r) => sameRuleIdentity(r, w)) && !removed.some((t) => sameRuleIdentity(t, w)))]; }; const lawed = (p, read) => read !== undefined ? read : (unit[p].ok?.rows ?? []).filter(tightening); const lawedUnreadable = (p, view) => (view !== undefined ? unreadableOf(p, view) : (unit[p].ok?.unreadable ?? [])); const outOfScope = new WeakSet(); const scopesPending = new Set(); const scopesOf = new WeakMap(); const judgeScopes = (view) => { if (scopesOf.has(view)) return scopesOf.get(view); const project = holdsPersonRows ? (view.unreadableRows ?? []).filter((u) => identityUnread(u) && u.scope?.kind === "project") : []; let judged; if (project.length > 0) { const inScope = projectScopeIdentity(project.map((u) => ({ scope: u.scope })), cfg.rootCanonical, cfg.leads).then((scopeIdentity) => new Set(unreadableRowsInScope(project, READ_RULE_TOOL, { cwd: cfg.root, sessionId: cfg.sessionId, ...(scopeIdentity !== undefined ? { scopeIdentity } : {}) }))); const settled = withGateTimeout(inScope, PATH_TABLES_READY_BOUND_MS, cfg.signal, "personRowScopes").then((rows) => { for (const u of project) if (!rows.has(u)) outOfScope.add(u); }, () => undefined); judged = settled; scopesPending.add(settled); void settled.then(() => scopesPending.delete(settled)); } scopesOf.set(view, judged); return judged; }; const readScopes = new WeakMap(); const reachesEveryJudgment = (u) => reachesEveryCall(u) && !outOfScope.has(u); const latestUnread = () => holdsPersonRows && partitions.some((p) => unit[p].failedSeq > (unit[p].ok?.seq ?? 0) || (unit[p].ok?.unreadable ?? []).some(reachesEveryJudgment)); const unitLatestRules = () => partitions.flatMap((p) => { const cell = unit[p]; return lawed(p, cell.ok !== undefined && cell.failedSeq <= cell.ok.seq ? cell.ok.rows : undefined); }); const readOnce = (at) => { const seq = ++seqs; if (provider === undefined) return Promise.resolve({ rules: [] }); let raw; try { raw = ownerStoreOf(provider, cfg.principal, cfg.localOwnerDeclared).effective({ sessionId: cfg.sessionId }); } catch (err) { raw = Promise.reject(err); } raw = raw.then((view) => (view.org !== undefined ? { ...view, org: orgResolutionHeld(view.org) } : view)); const outcomeOf = (view) => ({ seq, view: holdsPersonRows ? view : { ...view, rules: [], unreadableRows: [] }, failed: holdsPersonRows ? failedOf(view) : new Set() }); const answer = () => void (answeredSeq = Math.max(answeredSeq, seq)); void raw.then((view) => { answer(); for (const line of view.disclosures) cfg.onDisclosure(line); cfg.onRowsDropped(view.droppedRows, view.unreadableRows); if (holdsPersonRows && view.unreadable !== undefined) announce(at, view.unreadable, faultsOfView(view)); const tellUnread = () => { const unreadRows = holdsPersonRows ? (view.unreadableRows ?? []).filter((u) => identityUnread(u) && !outOfScope.has(u)) : []; if (unreadRows.length > 0) cfg.onUnread(at, unreadableRowFaultsOf(unreadRows), unreadRows.length); }; const scoped = judgeScopes(view); if (scoped === undefined) tellUnread(); else void scoped.then(tellUnread); land(outcomeOf(view)); }, answer); const read = withGateTimeout(raw, PERSON_READ_BOUND_MS, cfg.signal, "personRules").then((view) => { const out = readOf(outcomeOf(view)); const scoped = judgeScopes(view); if (scoped !== undefined) readScopes.set(out, scoped); return out; }, (err) => { const failure = gateWaitFailureOf(err); const cut = failure === "aborted"; const faults = [{ sources: sourcesOf(partitions), reason: failure === "timeout" ? "no_answer" : ruleStoreFaultReasonOf(err) }]; const outcome = { seq, failed: new Set(partitions), why: thrownText(err), ...(cut ? { cut: true } : { faults }) }; land(outcome); if (holdsPersonRows && !cut) announce(at, outcome.why, faults); if (failure === "timeout" && seq > (silent?.seq ?? 0)) silent = { seq, read }; return readOf(outcome); }); if (at === "prepare") prepared = { seq, read }; return read; }; const forRequest = () => { const first = prepared; prepared = undefined; const s = silent; const read = first !== undefined && first.seq === seqs ? first.read : s !== undefined && s.seq > requestSeq && s.seq > answeredSeq ? s.read : readOnce("call"); requestSeq = seqs; return read; }; const unreadableOf = (p, view) => (view.unreadableRows ?? []).filter((u) => partitionOf(u.scope !== undefined ? ruleSourceOf(u.scope) : "user") === p); const failedOf = (view) => view.unreadable !== undefined && (view.unreadableSources ?? []).length === 0 ? new Set(partitions) : new Set((view.unreadableSources ?? []).map(partitionOf).filter((p) => partitions.includes(p))); const defect = (message) => { cfg.onDisclosure(message); cfg.onDefect?.(new Error(message)); }; const sourcesOf = (ps) => { const set = new Set(ps); return [...(set.has("durable") ? ["user", "project"] : []), ...(set.has("session") ? ["session"] : [])]; }; const faultsOfView = (view) => { if (view.unreadable === undefined) return undefined; const named = view.unreadableSources ?? []; return view.unreadableFaults ?? [{ sources: named.length > 0 ? named : sourcesOf(failedOf(view)), reason: "unclassified" }]; }; const readOf = (o) => { const readOfPartition = (p, view) => { const ok = unit[p].ok; return ok !== undefined && ok.seq === o.seq ? ok.rows : readRows(p, view, ok); }; const rules = partitions.flatMap((p) => lawed(p, o.view !== undefined && !o.failed.has(p) ? readOfPartition(p, o.view) : undefined)); const unreadableRows = partitions.flatMap((p) => lawedUnreadable(p, o.view !== undefined && !o.failed.has(p) ? o.view : undefined)); const unreadable = o.view !== undefined ? o.view.unreadable : (o.why ?? "the store did not answer"); const faults = o.view !== undefined ? faultsOfView(o.view) : o.faults; return { rules, ...(o.view !== undefined ? { org: o.view.org } : {}), ...(unreadable !== undefined ? { unreadable } : {}), ...(faults !== undefined ? { unreadableFaults: faults } : {}), ...(unreadableRows.length > 0 ? { unreadableRows } : {}) }; }; const announce = (at, why, faults) => { const sources = (faults ?? []).flatMap((f) => f.sources); cfg.onDisclosure(`the person's persisted rules could not be read (${at === "prepare" ? "when the run started" : "for a call"}${sources.length > 0 ? `; ${ruleStoreSourcesWord(sources)} rows` : ""}): their allow rows take no part until a read succeeds, the deny and ask rows of the run's last successful read still apply — ${why}`); cfg.onUnread(at, faults ?? []); }; const tableRowsOf = async (rules) => { if (rules.length === 0) return { denyRows: [], readDirectories: [] }; const scopeIdentity = await projectScopeIdentity(rules, cfg.rootCanonical, cfg.leads); const call = { tool: READ_RULE_TOOL, cwd: cfg.root, sessionId: cfg.sessionId, ...(scopeIdentity !== undefined ? { scopeIdentity } : {}) }; const readDirectories = []; const denySpecs = []; const readFaceSpecs = { allow: [], ask: [] }; const writeAskSpecs = []; for (const rule of rules) { if (rule.status !== "live") continue; if (rule.behavior === "allow" && rule.tool === READ_RULE_TOOL && rule.match === "subpath" && eligiblePersisted(rule, call, "allow")) { if (!readDirectories.includes(rule.command)) readDirectories.push(rule.command); continue; } const pathRow = (rule.behavior === "allow" || rule.behavior === "ask") && (rule.match === "path" || rule.match === "subpath"); const columns = pathRow ? PATH_RULE_FACES[rule.tool]?.[rule.behavior] : undefined; const readFace = columns?.includes("read") === true; const writeAsk = rule.behavior === "ask" && columns?.includes("write") === true; if ((readFace || writeAsk) && eligiblePersisted(rule, { ...call, tool: rule.tool }, rule.behavior)) { if (readFace) readFaceSpecs[rule.behavior].push({ parsed: rule, ruleText: rule.rule, rule }); if (writeAsk) writeAskSpecs.push({ parsed: rule, ruleText: rule.rule, rule }); continue; } const faces = PATH_RULE_FACES[rule.tool]?.deny; if (rule.behavior !== "deny" || faces === undefined || (rule.match !== "path" && rule.match !== "subpath") || !eligiblePersisted(rule, { ...call, tool: rule.tool }, "deny")) continue; denySpecs.push({ parsed: rule, ruleText: rule.rule, faces, rule }); } const denyRows = []; for (const row of bindPathRules(denySpecs, (spec) => persistedRowAnchors(spec.rule.scope, cfg.chainTop))) { if (row.unanchored !== undefined) { if (!unanchoredSaid.has(row.rule)) { unanchoredSaid.add(row.rule); cfg.onDisclosure(`the persisted deny rule ${inlineUntrusted(row.rule, 200)} needs a ${row.unanchored.join(" / ")} base this task does not declare — the shell's file commands and the search tools do not judge it on this leg (the gate asks)`); } continue; } denyRows.push(row); } const bound = (behavior) => bindPathRules(readFaceSpecs[behavior], (spec) => persistedRowAnchors(spec.rule.scope, cfg.chainTop)).filter((row) => { if (row.unanchored === undefined) return true; if (behavior === "ask" && !unanchoredSaid.has(row.rule)) (unanchoredSaid.add(row.rule), cfg.onDisclosure(`the persisted ask rule ${inlineUntrusted(row.rule, 200)} needs a ${row.unanchored.join(" / ")} base this task does not declare — the shell's file commands do not ask it on this leg (the Read tool's own check still does)`)); return false; }); const allow = bound("allow"); const ask = bound("ask"); const writeAskBound = bindPathRules(writeAskSpecs, (spec) => persistedRowAnchors(spec.rule.scope, cfg.chainTop)); const writeAskRows = writeAskBound.filter((row) => row.unanchored === undefined); const writeAskUnanchored = writeAskBound.flatMap((row) => (row.unanchored === undefined ? [] : [{ rule: row.rule, needs: row.unanchored }])); return { denyRows, readDirectories, ...(allow.length > 0 || ask.length > 0 ? { readFaceRows: { allow, ask } } : {}), ...(writeAskRows.length > 0 ? { writeAskRows } : {}), ...(writeAskUnanchored.length > 0 ? { writeAskUnanchored } : {}) }; }; const tablesOf = (rules) => { const make = compile; if (make === undefined) return Promise.resolve(undefined); const compiling = (async () => { const person = await tableRowsOf(rules); const rowKey = (rows) => (rows ?? []).map((r) => [r.rule, r.tool, r.spec.parsed.match, r.spec.parsed.command, scopeKey(r.spec.rule)]); const key = JSON.stringify([rowKey(person.denyRows), person.readDirectories, rowKey(person.readFaceRows?.allow), rowKey(person.readFaceRows?.ask), rowKey(person.writeAskRows), (person.writeAskUnanchored ?? []).map((u) => [u.rule, u.needs])]); let tables = compiled.get(key); if (tables === undefined) { tables = withGateTimeout(make(person), PATH_TABLES_READY_BOUND_MS, undefined, "pathTablesCompile"); compiled.set(key, tables); if (compiled.size > COMPILED_TABLES_KEPT) compiled.delete(compiled.keys().next().value); tables.catch(() => compiled.delete(key)); } return await tables; })(); return withGateTimeout(compiling, PATH_TABLES_READY_BOUND_MS, undefined, "pathTablesCompile"); }; const contentOf = (rules) => JSON.stringify(rules.map(({ adds, ...row }) => { const n = adds?.length; return [row, typeof n === "number" && n > 0]; })); const refreshUnitTables = () => { const rules = unitLatestRules(); const key = contentOf(rules); if (unitTables !== undefined && unitTables.key === key && unitTables.state !== "failed") return; const cell = { key, state: "compiling", settled: Promise.resolve() }; cell.settled = tablesOf(rules).then((tables) => { cell.tables = tables; cell.state = "ready"; }, (err) => { cell.failed = thrownText(err); cell.state = "failed"; defect(`the path tables over the person's newest rows could not be compiled; the checks that are no call's refuse until a later read compiles: ${cell.failed}`); }); unitTables = cell; }; const unitReady = async (signal) => { const deadline = Date.now() + PATH_TABLES_READY_BOUND_MS; for (let cell = unitTables; cell?.state === "compiling" && signal?.aborted !== true; cell = unitTables) { const left = deadline - Date.now(); if (left <= 0) return; await withGateTimeout(cell.settled, left, signal, "pathTablesReady").catch(() => undefined); } const left = deadline - Date.now(); if (scopesPending.size > 0 && left > 0) await withGateTimeout(Promise.all([...scopesPending]), left, signal, "personRowScopes").catch(() => undefined); }; const pinOf = (toolCallId) => { const p = toolCallId === undefined ? undefined : pins.get(toolCallId); if (p === undefined || cfg.occurrences?.get(toolCallId) === p.attempt) return p; pins.delete(toolCallId); return undefined; }; const enter = (toolCallId, attempt, judged) => { const rows = readOnce("call").then((read) => (entry.read = read)); const entry = { attempt, rows, tables: holdsPersonRows ? rows.then((read) => Promise.all([settleTables(entry, read), readScopes.get(read)]).then(() => undefined)) : Promise.resolve(), ...(holdsPersonRows ? {} : { settled: {} }), ...(judged !== undefined ? { judged: { value: judged } } : {}) }; pins.set(toolCallId, entry); return entry; }; const serves = (p, judged) => { if (judged === undefined || p.judged === undefined || p.judged.value === judged) return true; p.judged.canonical ??= canonicalize(p.judged.value); return p.judged.canonical === canonicalize(judged); }; const pin = (toolCallId, judged) => { for (const id of [...pins.keys()]) pinOf(id); const known = pinOf(toolCallId); if (known !== undefined && serves(known, judged)) { if (judged !== undefined) known.judged ??= { value: judged }; return known.rows; } const attempt = cfg.occurrences?.get(toolCallId); return attempt === undefined ? readOnce("call") : enter(toolCallId, attempt, judged).rows; }; const settleTables = async (entry, read) => { try { const tables = await tablesOf(read.rules); entry.settled = tables !== undefined ? { tables } : {}; } catch (err) { entry.settled = { failed: thrownText(err) }; defect(`the path tables of a call's read of the person's rows could not be compiled — the call's file and shell checks refuse it rather than judge it with other tables: ${entry.settled.failed}`); } }; const tablesFor = (toolCallId) => { const p = pinOf(toolCallId); if (p?.settled?.failed !== undefined) throw new Error(`this call's path tables could not be compiled, so the call is refused: ${p.settled.failed}`); if (p !== undefined && p.settled === undefined) throw new Error("a call's path tables were read before they were compiled (an engine defect: a check ran ahead of its call's read)"); if (p?.settled?.tables !== undefined) return p.settled.tables; const u = unitTables; if (u === undefined) throw new Error("the run's path tables were read before they were compiled (an engine defect)"); if (u.state === "ready" && u.tables !== undefined) return u.tables; throw new Error(u.state === "failed" ? `the path tables over the person's newest rows could not be compiled, so this check refuses rather than judge with the tables of the rows they replace: ${u.failed}` : "the path tables over the person's newest rows are still being compiled, so this check refuses rather than judge with the tables of the rows they replace"); }; return { holdsPersonRows, sessionRowOwner, prime: () => holdsPersonRows ? readOnce("prepare").then(() => undefined) : undefined, pin, forRequest, tablesReady: (toolCallId, signal) => { const p = pinOf(toolCallId); const cut = signal === undefined || cfg.signal === undefined ? (signal ?? cfg.signal) : AbortSignal.any([signal, cfg.signal]); return p !== undefined ? withGateTimeout(p.tables, undefined, cut, "callTables").catch(() => undefined) : unitReady(cut); }, holds: (toolCallId) => cfg.occurrences?.get(toolCallId) !== undefined, unreadFor: (toolCallId) => { const read = pinOf(toolCallId)?.read; return read !== undefined ? holdsPersonRows && (read.unreadable !== undefined || (read.unreadableRows ?? []).some(reachesEveryJudgment)) : latestUnread(); }, attachTables: async (make) => { compile = make; const rules = unitLatestRules(); const tables = await tablesOf(rules); unitTables ??= { key: contentOf(rules), state: "ready", tables: tables, settled: Promise.resolve() }; const judging = () => { if (latestUnread()) throw new Error("a partition of the person's persisted rules could not be read when the run last read it, so this check refuses rather than judge past rows it cannot see"); return tablesFor(undefined); }; const denyFacade = (pick) => Object.assign(readDenyOver(() => pick(tablesFor(undefined)), tables.readDeny.homeViews), { matchPath: (path, opts) => pick(judging()).matchPath(path, opts), matchTarget: (canonicalKey, lexicalView, opts) => pick(judging()).matchTarget(canonicalKey, lexicalView, opts), unexcludableUnder: (scope) => pick(judging()).unexcludableUnder?.(scope) ?? false, rowUnderRoot: (scope) => pick(judging()).rowUnderRoot?.(scope) ?? null, rowAtOrBelow: (path) => pick(judging()).rowAtOrBelow?.(path) ?? null, forCall: (id) => pick(id === undefined ? judging() : tablesFor(id)), }); const readDeny = denyFacade((t) => t.readDeny); const structuredReadDeny = denyFacade((t) => t.structuredReadDeny ?? t.readDeny); const writeDeny = { face: "write", get hasRows() { return tablesFor(undefined).writeDeny.hasRows; }, get ruleRows() { return tablesFor(undefined).writeDeny.ruleRows; }, matchPath: (path) => judging().writeDeny.matchPath(path), matchTarget: (canonicalKey, lexicalView, opts) => judging().writeDeny.matchTarget(canonicalKey, lexicalView, opts), guardsReads: (pattern) => judging().writeDeny.guardsReads?.(pattern) === true, rowUnderRoot: (scope) => judging().writeDeny.rowUnderRoot?.(scope) ?? null, rowAtOrBelow: (path) => judging().writeDeny.rowAtOrBelow?.(path) ?? null, get unanchoredRows() { return tablesFor(undefined).writeDeny.unanchoredRows ?? []; }, rowLedByName: (name) => judging().writeDeny.rowLedByName?.(name) ?? null, homeViews: readDeny.homeViews, forCall: (id) => tablesFor(id).writeDeny, }; return { forCall: tablesFor, readDeny, structuredReadDeny, writeDeny, readDirectories: (id) => tablesFor(id).readDirectories, ruleRows: () => tablesFor(undefined).ruleRows }; }, boundaryRows: (tables, toolCallId) => { const rows = tables.readFaceRows; if (rows === undefined || rows.allow.length === 0) return rows; const read = pinOf(toolCallId)?.read; const beyond = cfg.seatsBeyond; const own = beyond?.session_rules(); const heldOut = (read?.org !== undefined ? orgStands(read.org) : orgGuard.stands) || (own !== undefined && seatStandsOverReads({ seat: "session_rules", ...own })) || (beyond?.ancestor_session_rules() ?? []).some((a) => seatStandsOverReads({ seat: "ancestor_session_rules", ...a })) || seatStandsOverReads({ seat: "skill_grants", records: beyond?.skill_grants() ?? [] }); return !heldOut ? rows : askRowsAlone(rows); }, }; } function askRowsAlone(rows) { return rows === undefined || rows.ask.length === 0 ? undefined : { allow: [], ask: rows.ask }; } export function pathTablesCompile(seats) { return async (person) => { const rows = [...seats.legRows, ...person.denyRows]; const led = rowsWhereTheyLead(rows, await seats.leads.resolve(rows)); const compileAt = (builtin) => (homes, linked) => compileReadDeny(seats.additions, "readDenyPatterns", builtin, led, homes, linked); const placed = await placeReadDenyAtHome(seats.env, compileAt(seats.builtin), undefined, undefined, { configRoots: seats.configRoots, callerHomes: seats.callerHomes, ...(seats.workspaceRoot !== undefined ? { workspaceRoot: seats.workspaceRoot } : {}) }); const allow = person.readFaceRows?.allow ?? []; const asks = [...seats.legReadAskRows.map((r) => ({ ...r, policy: true })), ...(person.readFaceRows?.ask ?? [])]; const readFaceRows = allow.length > 0 || asks.length > 0 ? { allow, ask: rowsWhereTheyLead(asks, await seats.leads.resolve(asks)) } : undefined; const legWriteAsks = seats.legWriteAskRows ?? []; const writeAsks = [...legWriteAsks.filter((r) => r.unanchored === undefined).map(({ unanchored: _u, ...r }) => ({ ...r, policy: true })), ...(person.writeAskRows ?? [])]; const writeAskUnanchored = [...legWriteAsks.flatMap((r) => (r.unanchored === undefined ? [] : [{ rule: r.rule, needs: r.unanchored }])), ...(person.writeAskUnanchored ?? [])]; let writeAsksLed; const writeAskRowsLed = () => (writeAsksLed ??= withGateTimeout(seats.writeAskLeads.resolve(writeAsks).then((leads) => rowsWhereTheyLead(writeAsks, leads)), PATH_TABLES_READY_BOUND_MS, undefined, "writeAskRowsLed").catch((err) => { writeAsksLed = undefined; throw err; })); const forRead = seats.builtinStructuredRead === undefined ? undefined : compileAt(seats.builtinStructuredRead); const structuredReadDeny = forRead === undefined ? undefined : carryHomeViews(placed.linked.size === 0 ? forRead(placed.homes) : forRead(placed.homes, placed.linked), placed.matcher.homeViews); return { readDeny: placed.matcher, ...(structuredReadDeny !== undefined ? { structuredReadDeny } : {}), writeDeny: carryHomeViews(compileWriteDeny(placed.matcher), placed.matcher.homeViews), readDirectories: [...new Set(await seats.canonicalize(person.readDirectories))], ...(readFaceRows !== undefined ? { readFaceRows } : {}), ...(writeAsks.length > 0 ? { writeAskRows: writeAsks, writeAskRowsLed } : {}), ...(writeAskUnanchored.length > 0 ? { writeAskUnanchored } : {}), ruleRows: rows }; }; } export function boundaryRowsOver(rows, personDirectories) { return personDirectories === "set_aside" ? (tables) => askRowsAlone(tables.readFaceRows) : (tables, toolCallId) => rows.boundaryRows(tables, toolCallId); } export function readRootsOver(seats) { const said = new Set(); const rootsOf = (rowDirs) => { const personDirs = seats.personDirectories === "set_aside" ? [] : rowDirs; const own = seats.own(); const store = seats.store(); const held = store === undefined ? [] : personDirs.filter((k) => !own.includes(k) && rootAdmittingArtifactStore(store, [k]) !== undefined); for (const dir of held) if (!said.has(dir)) (said.add(dir), seats.onHeld(dir, store)); return [...new Set([...own, ...personDirs.filter((k) => !held.includes(k))])]; }; return Object.assign(() => rootsOf(seats.tables.readDirectories()), { forCall: (toolCallId) => () => rootsOf(seats.tables.readDirectories(toolCallId)), ready: (signal) => seats.ready(undefined, signal) }); } const SEATS = new WeakMap(); export function denySeatsOf(t) { let seats = SEATS.get(t); if (seats === undefined) { const unanchored = t.writeDeny.unanchoredRows ?? []; seats = { read: readDenySeat(t.readDeny), write: t.writeDeny.hasRows ? { writeDenyMatch: (p) => t.writeDeny.matchPath(p)?.pattern ?? null, writeDenyGuardsReads: (pattern) => t.writeDeny.guardsReads?.(pattern) === true, writeDenyUnder: (p) => { const hit = t.writeDeny.rowUnderRoot?.(p) ?? null; return hit === null ? null : hit.unplaced === true ? { unplaced: hit.pattern } : hit.pattern; }, writeDenyAtOrBelow: (p) => t.writeDeny.rowAtOrBelow !== undefined ? (t.writeDeny.rowAtOrBelow(p)?.pattern ?? null) : (t.writeDeny.ruleRows[0]?.rule ?? null), ...(unanchored.length > 0 ? { writeDenyNamed: { rows: unanchored, ledBy: (name) => t.writeDeny.rowLedByName?.(name) ?? null } } : {}), } : {}, }; SEATS.set(t, seats); } return seats; } const EVERY_ROW = Object.freeze({ any: true, guardsWrites: true }); export function confinedDenyRowsOf(tables, unreadFor, toolCallId) { try { if (tables === undefined || unreadFor(toolCallId) || unreadFor(undefined)) return EVERY_ROW; const both = [tables.forCall(toolCallId), tables.forCall(undefined)]; const seats = both.map(denySeatsOf); const guardsWrites = seats.some((s) => s.write.writeDenyMatch !== undefined); return { any: guardsWrites || seats.some((s) => s.read.denyMatch !== undefined), guardsWrites, ...(both.some((t) => t.writeAskRows !== undefined) ? { writeAsk: true } : {}) }; } catch { return EVERY_ROW; } } const VOUCHED = { disposition: "vouch", finding: "none" }; export function onPinnedRead(rows, stations) { const check = composeReadChecks(stations); if (check === undefined || !rows.holdsPersonRows) return check; return { judge(call, args, cwd, signal, callOpts) { const id = callOpts.toolCallId; if (!readStationsHold(stations, call)) return check.judge(call, args, cwd, signal, callOpts); const ready = id !== undefined && rows.holds(id) ? rows.pin(id, args).then(() => rows.tablesReady(id)) : rows.tablesReady(undefined, signal); return ready.then(() => check.judge(call, args, cwd, signal, callOpts) ?? VOUCHED); }, unanswered: (call, cause, args) => check.unanswered(call, cause, args), ...(check.writeAskRowsUncounted !== undefined ? { writeAskRowsUncounted: check.writeAskRowsUncounted } : {}), }; } export function onNewestRead(rows, station) { const { check } = station; if (!rows.holdsPersonRows) return check; return { judge(call, args, cwd, signal, callOpts) { if (readStationMemberOf(call, station.tools) === undefined) return check.judge(call, args, cwd, signal, callOpts); return rows.tablesReady(undefined, signal).then(() => check.judge(call, args, cwd, signal, callOpts) ?? VOUCHED); }, unanswered: (call, cause, args) => check.unanswered(call, cause, args), ...(check.writeAskRowsUncounted !== undefined ? { writeAskRowsUncounted: check.writeAskRowsUncounted } : {}), }; } export function afterCallTables(rows, tool) { return { ...tool, execute: async (toolCallId, params, signal, onUpdate) => { await rows.tablesReady(toolCallId, signal); return await tool.execute(toolCallId, params, signal, onUpdate); }, }; } export function personPathRowsOfTask(t) { const { sessionId, taskId } = t.ids; return createPersonPathRows({ seatsBeyond: t.seatsBeyond, provider: t.deps.permissionRuleStore, localOwnerDeclared: t.deps.localOwnerRules === true, principal: t.principal, sessionId: t.ruleSessionId, root: t.root, rootCanonical: t.rootCanonical, leads: t.leads, chainTop: t.chainTop, occurrences: t.occurrences, onDisclosure: (message) => emitTrace(t.deps.tracer, () => ({ kind: "permission.rule_store_unreadable", version: 1, taskId, message, ts: Date.now() })), onUnread: t.notices.onUnread, onRowsDropped: t.notices.onRowsDropped, onDefect: (err) => t.deps.onError?.(err, { phase: "config", sessionId }), signal: AbortSignal.any([...t.signals]), }); } function scopeKey(rule) { const scope = rule?.scope; return scope === undefined ? "" : scope.kind === "project" ? `project:${scope.root}` : scope.kind; } function droppedRowKind(row) { if (row.reason === "scope_root_not_absolute") return "scope"; if (row.element !== undefined) return "element"; if (row.member !== undefined) return "unread"; const open = indexOfUnescaped(row.rule, "("); return open > 0 && ruleToolGrammarOf(row.rule.slice(0, open).trim()) === "path" && /\\[\\()]/.test(row.rule.slice(open + 1)) ? "path" : "spelling"; } const READER_WORDS = /^(?:(?:null|nothing|an? [a-z]+) where a row belongs|behavior: (?:a read that threw|(?:null|undefined|nothing|an? [a-z]+) where a text belongs))$/; const elementAt = (row) => row.reason !== "scope_root_not_absolute" && row.element !== undefined ? `the ${row.element.partition === "session" ? "session" : "stored"} list's entry #${row.element.index}${READER_WORDS.test(row.element.read) ? `: ${row.element.read}` : ""}` : ""; const DROPPED_ROW_SENTENCE = { element: (n, rows) => `${n} ${n === 1 ? "entry" : "entries"} of your stored rules could not be read as a rule at all — no behavior word could be read (${rows.slice(0, 3).map(elementAt).join("; ")}${n > 3 ? "; …" : ""}) — so ${n === 1 ? "it is" : "they are"} not read as a rule in this run: nothing says ${n === 1 ? "it was" : "they were"} a deny or an ask. Have the store send whole rows, or remove ${n === 1 ? "it" : "them"}.`, scope: (n) => `${n} of your persisted permission rule rows ${n === 1 ? "is" : "are"} scoped to a project directory that is not written as a complete absolute path, so ${n === 1 ? "it takes" : "they take"} no part in this run's checks — a deny or ask row among them protects nothing. Rewrite ${n === 1 ? "it" : "them"} with the project's full path, or remove ${n === 1 ? "it" : "them"}.`, unread: (n) => `${n} of your allow rule rows came from the store with a part missing or not in plain form (the rule's text, the record of when it was added, or another stored part), so ${n === 1 ? "it allows" : "they allow"} nothing in this run. Have the store send the whole row, or remove ${n === 1 ? "it" : "them"} and approve the call again.`, spelling: (n) => `${n} of your persisted allow rule rows ${n === 1 ? "is" : "are"} not stored the way an approval stores a rule (${n === 1 ? "its" : "their"} text is another spelling of a rule, or not what ${n === 1 ? "the row is" : "the rows are"} stored to allow), so ${n === 1 ? "it allows" : "they allow"} nothing in this run. Remove ${n === 1 ? "it" : "them"}, and approve the call again to store the rule in its own form.`, path: (n) => `${n} of your persisted allow rule rows for a path ${n === 1 ? "does" : "do"} not read back as the path ${n === 1 ? "it is" : "they are"} stored to allow (${n === 1 ? "its" : "their"} text escapes a backslash or a parenthesis), so ${n === 1 ? "it allows" : "they allow"} nothing in this run. Correct the path in the settings file ${n === 1 ? "it was" : "they were"} imported from and import ${n === 1 ? "it" : "them"} again, or remove ${n === 1 ? "it" : "them"}.`, }; const UNREADABLE_ROW_SENTENCE = { as_read: (n) => `${n} of your deny or ask rule rows came from the store with a part missing or not in plain form (the rule's text, its tool, match or path, the record of when it was added, or its scope), so ${n === 1 ? "it applies" : "they apply"} as written in every permission mode — a missing text read from the tool, match and path stored with ${n === 1 ? "it" : "them"}; where the tool, match or path is the part, all three read from ${n === 1 ? "its" : "their"} text, so ${n === 1 ? "it reaches" : "they reach"} what the rule's text says; where the scope is the part, everywhere (a row of this session's rules: in this session). Have the store send the whole row, or remove ${n === 1 ? "it" : "them"} from the store and add the rule again.`, strictest: (n) => `${n} of your deny or ask rule rows could not be read (the store sent neither a rule text this version reads nor the tool, match or path it names as plain data), so ${n === 1 ? "it is" : "they are"} not ignored: no allow rule of yours clears a call ${n === 1 ? "it" : "they"} may reach — ${n === 1 ? "its tool's" : "their tools'"} calls, or every call for a Read or Edit deny rule (the file, shell and search checks read those too) or when the tool cannot be read — while your other deny and ask rules still refuse and ask. Under the permission modes that ask, such a call is put to you; auto mode's classifier and bypass mode answer it without asking. Have the store send plain values, or repair or remove ${n === 1 ? "it" : "them"} in the store.`, behavior: (n) => `${n} of your stored rule rows could not be read because ${n === 1 ? "its" : "their"} behavior word could not be read (missing, not a text, or outside deny, ask and allow), so ${n === 1 ? "it is" : "they are"} not ignored: no allow rule of yours clears a call ${n === 1 ? "it" : "they"} may reach — ${n === 1 ? "its tool's" : "their tools'"} calls, or every call for Read or Edit or when the tool cannot be read — while your other deny and ask rules still refuse and ask; under the permission modes that ask, such a call is put to you (auto mode's classifier and bypass mode answer it without asking) — repair or remove ${n === 1 ? "it" : "them"} in the store.`, }; export function ruleRowsDroppedNotice(onNotice, ids) { let sent = false; return (dropped, unreadable) => { const rows = [...(dropped ?? []), ...(unreadable ?? [])]; if (sent || rows.length === 0) return; sent = true; const said = [ ...Object.entries(DROPPED_ROW_SENTENCE).flatMap(([kind, say]) => { const of = (dropped ?? []).filter((r) => droppedRowKind(r) === kind); return of.length > 0 ? [say(of.length, of)] : []; }), ...[ [(unreadable ?? []).filter((r) => !identityUnread(r)).length, UNREADABLE_ROW_SENTENCE.as_read], [(unreadable ?? []).filter((r) => identityUnread(r) && r.member !== "behavior").length, UNREADABLE_ROW_SENTENCE.strictest], [(unreadable ?? []).filter((r) => identityUnread(r) && r.member === "behavior").length, UNREADABLE_ROW_SENTENCE.behavior], ].flatMap(([n, say]) => (n > 0 ? [say(n)] : [])), ]; deliverEngineNotice(onNotice, { code: "config.entries_not_applied", message: said.join(" "), detail: { ...entriesNotAppliedDetail("stored_rule_row", rows.map((r) => ({ entry: noticeRuleText(r.rule), reason: r.reason, ...(r.reason === "scope_root_not_absolute" ? { scopeRoot: inlineUntrusted(r.scopeRoot, 200) } : {}), ...("behavior" in r && r.member !== "behavior" ? { behavior: r.behavior } : {}), ...("member" in r && r.member !== undefined ? { member: r.member } : {}), ...("element" in r && r.element !== undefined ? { element: { partition: r.element.partition, index: r.element.index, read: inlineUntrusted(r.element.read, 200) } } : {}), }))), sessionId: ids.sessionId, runId: ids.runId, }, }); }; }