UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

206 lines (205 loc) • 11.5 kB
import { hasConversationContent } from "./session.js"; import { egressText } from "./untrusted-egress.js"; import { CROSS_BOUNDARY_POSTURES } from "@sema-agent/primitives"; export const CROSS_BOUNDARY_TAINT_BITS = Object.freeze(["targetExecutionArmed", "offTargetReadObserved"]); export { CROSS_BOUNDARY_POSTURES }; const postureSeatIsTheSet = true; void postureSeatIsTheSet; export const BOUNDARY_LEGS = Object.freeze(["env", "outside_read", "outside_write"]); const LEG_SET = new Set(BOUNDARY_LEGS); const OBLIGATION_TABLE = { env_to_target: { host_lane: "none", armed: "none", armed_observed: "mandate_if_governed" }, outside_read: { host_lane: "none", armed: "record", armed_observed: "none" }, outside_write: { host_lane: "none", armed: "mandate_if_governed", armed_observed: "mandate_if_governed" }, }; const ENV_LEG_ROWS = { target: ["env_to_target"], off_target: ["outside_read", "outside_write"] }; const TREE_MEMBERS = [...CROSS_BOUNDARY_TAINT_BITS, "governed"]; function assertTree(tree, at) { if (typeof tree !== "object" || tree === null || Array.isArray(tree)) throw new TypeError(`${at}: a cross-boundary tree is a record of presence bits (got ${tree === null ? "null" : Array.isArray(tree) ? "an array" : typeof tree})`); for (const member of TREE_MEMBERS) { const v = tree[member]; if (v !== undefined && v !== true) throw new TypeError(`${at}: tree member "${member}" is presence-coded (true or absent), got ${typeof v}`); } } export function crossBoundaryObligation(legs, reachedEnvIsTarget, tree) { if (!Array.isArray(legs)) throw new TypeError(`crossBoundaryObligation: legs is a list of ${BOUNDARY_LEGS.join(" | ")}`); if (typeof reachedEnvIsTarget !== "boolean") throw new TypeError("crossBoundaryObligation: reachedEnvIsTarget is a boolean"); assertTree(tree, "crossBoundaryObligation"); const column = tree.targetExecutionArmed !== true ? "host_lane" : tree.offTargetReadObserved === true ? "armed_observed" : "armed"; let mandate = false; let record = false; for (const leg of legs) { if (!LEG_SET.has(leg)) throw new TypeError(`crossBoundaryObligation: ${JSON.stringify(leg)} is not a boundary leg (${BOUNDARY_LEGS.join(", ")})`); const rows = leg === "env" ? ENV_LEG_ROWS[reachedEnvIsTarget ? "target" : "off_target"] : [leg]; for (const row of rows) { const cell = OBLIGATION_TABLE[row][column]; if (cell === "record") record = true; else if (cell === "mandate_if_governed" && crossBoundaryTreeGoverned(tree)) mandate = true; } } return Object.freeze({ mandate, record }); } export function crossBoundaryQuestion(toolName, afterOffTargetRead) { if (afterOffTargetRead === undefined) return `tool "${toolName}" crosses the device boundary of a run that executes on a target device — it needs approval before it runs`; const after = afterOffTargetRead.by !== undefined ? `${afterOffTargetRead.by} let content from beyond the device into this run` : "this session was read as holding content from beyond the device"; return `tool "${toolName}" reaches into the target device after ${after} — it needs approval before it runs`; } export function crossBoundaryTreeGoverned(tree) { return tree.governed === true; } export function joinCrossBoundaryTree(a, b) { assertTree(a, "joinCrossBoundaryTree"); assertTree(b, "joinCrossBoundaryTree"); const out = {}; if (a.targetExecutionArmed === true || b.targetExecutionArmed === true) out.targetExecutionArmed = true; if (a.offTargetReadObserved === true || b.offTargetReadObserved === true) out.offTargetReadObserved = true; if (a.governed === true || b.governed === true) out.governed = true; return Object.freeze(out); } export function crossBoundaryTreeCovers(covering, tree) { assertTree(covering, "crossBoundaryTreeCovers"); assertTree(tree, "crossBoundaryTreeCovers"); return TREE_MEMBERS.every((m) => tree[m] !== true || covering[m] === true); } export const STRICTEST_CROSS_BOUNDARY_TREE = Object.freeze({ targetExecutionArmed: true, offTargetReadObserved: true, governed: true }); export const CROSS_BOUNDARY_RECORD_TYPE = "engine:cross_boundary"; export function crossBoundaryRecordData(tree) { assertTree(tree, "crossBoundaryRecordData"); if (tree.targetExecutionArmed !== true) throw new TypeError("crossBoundaryRecordData: only an armed tree is recorded"); return Object.freeze({ targetExecutionArmed: true, ...(tree.offTargetReadObserved === true ? { offTargetReadObserved: true } : {}), ...(tree.governed === true ? { governed: true } : {}) }); } const RECORD_MEMBERS = TREE_MEMBERS; function ownedRecordTree(data) { if (typeof data !== "object" || data === null || Array.isArray(data) || Object.getPrototypeOf(data) !== Object.prototype) return { why: `its data is ${data === null ? "null" : Array.isArray(data) ? "an array" : typeof data === "object" ? "not a plain record" : typeof data}` }; const owned = new Map(); for (const key of Reflect.ownKeys(data)) { if (typeof key !== "string" || !RECORD_MEMBERS.includes(key)) return { why: `its data carries ${typeof key === "string" ? JSON.stringify(key.slice(0, 40)) : "a symbol key"}, which is not a member` }; const d = Object.getOwnPropertyDescriptor(data, key); if (d === undefined || !("value" in d)) return { why: `"${key}" is not a data member` }; owned.set(key, d.value); } if (owned.get("targetExecutionArmed") !== true) return { why: `"targetExecutionArmed" is not true` }; for (const m of ["offTargetReadObserved", "governed"]) if (owned.get(m) !== undefined && owned.get(m) !== true) return { why: `"${m}" is neither true nor absent` }; return { tree: Object.freeze({ targetExecutionArmed: true, ...(owned.get("offTargetReadObserved") === true ? { offTargetReadObserved: true } : {}), ...(owned.get("governed") === true ? { governed: true } : {}) }) }; } function readBranchEntry(branch, i) { let id; try { const e = branch[i]; if (typeof e !== "object" || e === null) return { kind: "other", content: false }; const { type, customType } = e; if (type !== "custom" || customType !== CROSS_BOUNDARY_RECORD_TYPE) return { kind: "other", content: typeof type === "string" && hasConversationContent([{ type }]) }; const rawId = e.id; id = typeof rawId === "string" ? rawId : undefined; const read = ownedRecordTree(e.data); return "why" in read ? { kind: "unreadable", ...(id !== undefined ? { id } : {}), why: read.why } : { kind: "record", ...(id !== undefined ? { id } : {}), tree: read.tree }; } catch { return { kind: "unreadable", ...(id !== undefined ? { id } : {}), why: "an entry on the branch could not be read" }; } } export function readCrossBoundaryRecord(branch) { const strictest = (id, why) => Object.freeze({ kind: "malformed", ...(id !== undefined ? { entryId: id } : {}), tree: STRICTEST_CROSS_BOUNDARY_TREE, why: `the cross-boundary record on this branch cannot be read: ${why}` }); let isList; let length; try { isList = Array.isArray(branch); length = isList ? branch.length : undefined; } catch { return strictest(undefined, "the branch could not be read"); } if (!isList) throw new TypeError("readCrossBoundaryRecord: the branch is a list of session entries"); if (typeof length !== "number" || !Number.isSafeInteger(length) || length < 0) return strictest(undefined, "the branch could not be read"); let joined; let newest; let uncoveredContent = false; for (let i = 0; i < length; i++) { const entry = readBranchEntry(branch, i); if (entry.kind === "other") { uncoveredContent ||= entry.content; continue; } if (entry.kind === "unreadable") return strictest(entry.id, entry.why); joined = joinCrossBoundaryTree(joined ?? {}, entry.tree); newest = entry.id; uncoveredContent = false; } return joined === undefined ? Object.freeze({ kind: "absent", uncoveredContent }) : Object.freeze({ kind: "recorded", ...(newest !== undefined ? { entryId: newest } : {}), tree: joined, uncoveredContent }); } export function crossBoundaryPostureUndeclaredNotice(at) { assertTree(at.tree, "crossBoundaryPostureUndeclaredNotice"); return { code: "config.cross_boundary_posture_undeclared", message: 'This run executes on an external-content target (the device lane) and no RunnerDeps.crossBoundaryPosture is configured — the engine reads the permissive "single_user" posture. ' + 'On a multi-tenant deployment declare "multi_tenant", so an org-side write from a tainted run is put to a person; on a single-user deployment declare "single_user" to silence this line.', detail: { sessionId: at.sessionId, runId: at.runId, taint: CROSS_BOUNDARY_TAINT_BITS.filter((b) => at.tree[b] === true) }, }; } export function crossBoundaryRecordUnwrittenNotice(at) { const cause = egressText("same-principal", at.cause).slice(0, 300); return { code: "config.cross_boundary_record_unwritten", message: `The session's cross-boundary record could not be written at ${at.phase} (${cause}) — ` + (!at.governed ? "the tree is not governed: no judgment reads the record, so its failure refused nothing; the tree's growth, or the leg's end, writes next, and a failure of this same state is not reported again." : `the tree is governed: ${at.phase === "prepare" ? "the leg's next write (an exit before its call runs, a suspend before its row, its end) owes the record again; if none lands, " : ""}the next leg on this session reads the content after its newest record as off-target, so its device calls are put to a person.`), detail: { sessionId: at.sessionId, runId: at.runId, phase: at.phase, governed: at.governed, cause }, }; } const NO_LEGS = Object.freeze([]); export function boundaryFlowFace(entry) { return entry?.boundaryFlow === "engine" ? { boundaryLegs: NO_LEGS } : {}; } function ownedLegList(v) { try { if (!Array.isArray(v)) return undefined; const length = v.length; if (typeof length !== "number" || !Number.isSafeInteger(length) || length < 0) return undefined; const held = new Set(); for (let i = 0; i < length; i++) { const leg = v[i]; if (!LEG_SET.has(leg)) return undefined; held.add(leg); } return BOUNDARY_LEGS.filter((l) => held.has(l)); } catch { return undefined; } } export function rosterBoundaryLegs(source, declared, effect) { const list = declared === undefined || declared === "per_call" ? undefined : ownedLegList(declared); if (declared !== undefined && declared !== "per_call" && list === undefined) return undefined; const reads = source === "builtin" || source === "synthetic" || source === "mcp" || source === "a2a"; if (!reads || declared === undefined) return effect === "read" ? ["outside_read"] : ["outside_write"]; return declared === "per_call" ? "per_call" : list; }