UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

154 lines (153 loc) • 12.1 kB
import type { ExecutionEnv } from "../../internal/harness-types.js"; import type { ToolEffect } from "../types.js"; import { type NamedToolPolicy } from "../tool-policy.js"; import { type RetiredNameView } from "../tool-name-aliases.js"; import { type SessionPermissionRules, type SessionPolicyStore, type SessionRuleEntryField, type StoredSessionRules } from "../session-policy-store.js"; import type { PathRuleBases } from "../permission-rule-model.js"; /** The FULL path-confinable write-tool set: every catalog tool declaring a write path target — `Write` / `Edit` * (target `file_path`) and `NotebookEdit`, whose write target is `notebook_path` and is extracted by the shared * tool-aware {@link writeTargetPath} (notebook_path outranks a decoy `file_path` for that tool). * * REF-B3 — the ONE spelling of "tools this codebase can confine by path". Consumers: * {@link createSessionRulePolicy} (below, `allowDirs`) and `createFsWriteGatePolicy` * (core/fs-write-gate-policy.ts), which used to rebuild `["Write", "Edit", "NotebookEdit"]` inline. * The transcript-directory gate (core/tool-policy.ts) spells no list: it reads the call's declared path * target (`protectivePathTargetOf`), the one source this set derives from; a source-scan pin (SW-10) keeps a * literal spelling from coming back. * * SW-10 relax (ruled 2026-08-04): `NotebookEdit` was previously absent from the session-rule face's * covered set, so an `allowDirs` confinement denied it OUTRIGHT via the "mutating but not path-confinable" * arm — a capability GAP relative to the fs-write gate, which has always proven the tool confinable. * Both faces now share this set and the same target extractor, so the session face confines notebooks by * path instead of refusing them. The fail-closed deny for every OTHER non-confinable mutating tool * (bash, deployment-authored write tools, unknown effects) is unchanged. */ export declare const PATH_CONFINABLE_WRITE_TOOLS: ReadonlySet<string>; /** Path-segment-aware containment, FAMILY-AWARE ([K-PLATFORM-SWEEP] MAJOR#2: canonical keys are * backslash-form on a win32 env — the "/"-hardcoded suffix rejected every legitimate write there). * Compare in "/" form with drive-letter case folded; never keyed on process.platform (the env may be * remote and of the OTHER family than the host). * * REF-B3 — exported as the single source for the policy modules that fence WRITES by an allowlist of * directories: fs-write-gate-policy.ts (`acceptDirs` * /`exemptDirs`), plus the K-PLATFORM sweep tests. The line here used to read "exported ONLY for the * K-PLATFORM sweep tests", which was already false when written (fs-write-gate-policy.ts imports it in * production), and a since-retired skill fence carried a byte-identical private twin — comment included — so * a platform-family fix had to be remembered at two coordinates. * * The sibling implementation is `within()` in tools/fs/safety.ts (the fs-tool root fence). Those stay * separate functions on purpose — that one is private to the fence and keyed on canonical roots — but * they must never disagree on a verdict; the empty-root arm below is that alignment. */ export declare function isWithin(root: string, p: string): boolean; /** * Where a session-rule layer takes the rules it enforces. * * @contract session_rules.every_gate_re_reads — a session-rule layer re-reads its rule source at EVERY * tool gate, not once at prepare: an operator's mid-run write (a new deny, a narrowed allowlist) binds the * very next call of the SAME run, on the same beat as the permission-rule store's per-call read. `seed` is * the prepare-time snapshot and stays the FLOOR — a read that fails, a row that was deleted, or a lagging * replica whose `rev` is below the snapshot's enforces the seed rather than loosening toward it — and it is * also what the prepare-time policy-name audit sees, so a rule written after prepare is enforced but not * audited. A source with no `read` is a constant one: the seed at every gate, which is what a caller that * hands a plain rules object gets. */ export interface SessionRuleSource { /** * The prepare-time snapshot: the audit's view, and the floor no live read may loosen. * * @contract session_rules.snapshot_grammar — the grammar a snapshot's entries are read in is one rule for every reader of rules * (this layer, `readSessionRulesShape`, `normalizeRules`, `loosenReasons`): the value's own `grammar` stamp when it carries one; * with none, a value beside a store's `rev` of 1 or more is a row stored before the stamp existed (grammar 0), and any other value * (no `rev`, or the `rev: 0` record of a key nobody wrote) is read in the grammar of the engine that enforces it. A plain rules * object handed straight to `createSessionRulePolicy`, or a constant source's seed, is therefore neither a write nor a stored row: * only a WRITER must declare a grammar, because a row outlives the engine that wrote it, while a snapshot is enforced by the engine * that reads it and cannot outlive that process — a host that wants a literal to keep its reading across an engine upgrade stamps it. */ seed: SessionPermissionRules; /** The live read, asked at every judgment and bounded by the gate's own signal; `toolCallId` names the call being * judged. Absent ⇒ the seed is the whole source. */ read?: (toolCallId: string, signal?: AbortSignal) => Promise<SessionPermissionRules>; } /** May `row` follow `floor` by rev at all (the one reading of the live reader below and of the checkpoint/live merge): a floor * at rev 0 has enforced no row and has no lineage to defend; above it only the floor's own lineage ({@link continuesLineage}). */ export declare function rowFollowsFloor(row: { gen?: number; }, floor: { rev: number; gen?: number; }): boolean; /** * The LIVE half of {@link SessionRuleSource}: re-read `(sessionId, principal)` from the store on each * adjudicated call, floored by `seed`. An ABSENT store is a source that cannot answer — a delegated leg on a * runner wired without the store its ancestors' rules live in — and takes the arm a throwing store takes. * * ONE law, two consumers (this task's own session rules and each inherited ancestor's), where the policy * chain used to carry a hand-written live-preferring read for ancestors only and a frozen snapshot for the * task's own rules. Direction, unchanged from that read and stated once here: a whole-row replacement includes RELAXATION * — any post-prepare write the store's judge accepted propagates in BOTH directions (the replace is the delete port); * what the floor forbids is an UNAUTHORIZED loosening (a lagging replica, a deleted row, an unreachable * store), and nothing task-side can edit the rules row itself. * * The floor RATCHETS to the highest-rev row this layer has actually served, and a live row replaces it only * on a STRICTLY GREATER `rev`. Two reasons, and the second is why "greater or equal" is not good enough: * · pinning the floor to the prepare snapshot would make "a failed read never loosens" false in the one * sequence that matters — a row tightened mid-run, enforced at one gate, then unreadable at the next * would fall back PAST the tightening to the snapshot the run started with; * · `rev` is per-ROW, and both bundled backends compute it as `(prior?.rev ?? 0) + 1`, so a row that is * DELETED and written again starts over at 1. At `>=`, a recreated row whose rev merely TIES the * enforced one would replace it — an unauthorized loosening dressed as an update. At `>`, a tie enforces * the floor, which is a no-op for the honest case (equal rev is the same row) and fail-closed for the * recycled one. Closed since 7.25.0 by the STORE's lineage identity (`StoredSessionRules.gen`): a * recreated row is another generation and is never compared to the enforced one, whatever its rev, and * a backend without lineages (gen 0 throughout) keeps the `>` protection above. * * Every ask is a store read, and nothing is kept between asks. Not by call id: a provider's id is unique within one * assistant response only (`brain/tool-call-id.ts`) and the visibility probes share one synthetic id, so a read kept * under it served a later call an earlier call's snapshot. Nor between the two passes of one judgment: the fold's * trailing narrowing pass runs after a caller policy that may have waited on a person, and judges the rules as they * stand then. */ export declare function createLiveSessionRules(store: SessionPolicyStore | undefined, floor: { sessionId: string; principal?: string; seed: StoredSessionRules; }, hooks?: { /** A rule source this layer could not read, once per distinct reason. */ onUnreadable?: (reason: string) => void; /** The store row this layer now enforces, each time the floor ADVANCES — never for the seed (its holder has it). */ onEnforced?: (row: StoredSessionRules) => void; /** Each read's outcome: `true` when the store could not be read (no store, a throw, no answer in time — the floor is enforced * unseen), `false` when it answered. */ onRead?: (unread: boolean) => void; }): NonNullable<SessionRuleSource["read"]>; /** * Build the per-session deny-narrowing policy. For each tool call: * - `toolDeny` → deny the calls its entries reach — the one list matcher's deny reading (`judgeAllowEntries`): a tool name * under any name the call answers to, a protocol namespace, a shell command rule over every program the command line runs * (a line it cannot read against the rule is refused too), a path rule over every view of the call's target. * - `toolAllow` (if set) → deny any call no entry admits (the matcher's allow reading in the `narrowing` posture: every * segment of a command line named by an entry; never the allow layer's auto-mode strip), naming the uncovered segment. * - an entry that reads as nothing → in no row (it guards and grants nothing; the prepare-time audit names it, or * `onEarlierGrammar(entries, bucket, grammar)`, once per distinct set, when its snapshot's own earlier grammar reads it so; a layer * given no such function says it through the engine's one notice throat with no seat of its own — the default notice seat, else a process line). * - a snapshot that cannot be read (its shape; a `toolDeny` entry no grammar reads) → deny every call, never quoting it. * - `allowDirs` (if set) → a WRITE tool must land inside one of the dirs (resolved via `canonicalizeTarget`, * so a symlink can't carry across a write out); a write-capable tool that cannot be path-confined (e.g. `bash`) * is DENIED while `allowDirs` is set (fail-closed). * The policy structurally emits no ask. Returns `allow` when nothing constrains the call. `env`/`rootPath` are the task's real * exec env + root, so matching sees the actual filesystem (a remote/E2B task resolves in its container). A relative TARGET * prefers the call's live tracked cwd ({@link ToolCallRequest.cwd}) when the engine stamps one; `allowDirs` entries always * resolve against `rootPath`, and a path rule's pattern against `anchors` (the leg's root and home — absent, `rootPath` * alone, so a home-relative pattern is unreadable and refuses in the deny direction). * * The rules are taken from a {@link SessionRuleSource} at EVERY call * ({@link SessionRuleSource} carries the law); a plain rules object is the constant source, which is what * every caller outside the policy chain hands, and what a layer whose rules cannot change under it needs. */ export declare function createSessionRulePolicy(rules: SessionPermissionRules | SessionRuleSource, opts: { env: ExecutionEnv; rootPath?: string; toolEffects?: ReadonlyMap<string, ToolEffect>; anchors?: PathRuleBases; retiredNames?: RetiredNameView; onEarlierGrammar?: (entries: readonly string[], field: SessionRuleEntryField, grammar: number) => void; }): NamedToolPolicy;