UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

162 lines (161 loc) • 12.2 kB
import { canonicalize, isSha16 } from "./canonical-json.js"; import { licenseCovers } from "./tool-policy.js"; import { pathTargetResolutionOf } from "./effective-path-target.js"; import { parkedSkillApprovalRefusal } from "./skill-grant.js"; import { engineMountedRow, toolDeclarationDigestOf, toolIdentityOf } from "./tool-roster.js"; import { inlineUntrusted } from "./untrusted-text.js"; import { isPlainRecord } from "./mods/kernel/receive.js"; export const APPROVAL_TARGET_ROLES = Object.freeze(["protective", "declared"]); const ALWAYS_MINTED = Object.freeze(["capabilityId", "contractId", "shapeDigest", "implementationRevision", "family", "declarationDigest"]); const isString = (v) => typeof v === "string"; const absentOr = (shape) => (v) => v === undefined || shape(v); const isSlot = (v) => isPlainRecord(v) && typeof v["param"] === "string"; const TOOL_MEMBER_SHAPES = Object.freeze({ capabilityId: isSha16, contractId: isString, shapeDigest: isString, implementationRevision: isString, family: isString, declarationDigest: isString, engineMounted: absentOr((v) => v === true), pathTarget: absentOr(isSlot), hostTarget: absentOr(isSlot), startedShell: absentOr((v) => v === "zsh"), }); const unreadToolMembers = (row) => Object.keys(TOOL_MEMBER_SHAPES).filter((k) => !TOOL_MEMBER_SHAPES[k](row[k])); const wholeTool = (row) => unreadToolMembers(row).length === 0; export function approvalObjectOf(row) { const { targets, targetReads, boundGrantDigest } = row; const tool = wholeTool(row) ? { capabilityId: row.capabilityId, contractId: row.contractId, shapeDigest: row.shapeDigest, implementationRevision: row.implementationRevision, ...(row.engineMounted === true ? { engineMounted: true } : {}), family: row.family, ...(row.pathTarget !== undefined ? { pathTarget: row.pathTarget } : {}), ...(row.hostTarget !== undefined ? { hostTarget: row.hostTarget } : {}), ...(row.startedShell === "zsh" ? { startedShell: row.startedShell } : {}), declarationDigest: row.declarationDigest } : { missing: unreadToolMembers(row) }; return { tool, ...(targets !== undefined ? { targets } : {}), ...(targetReads !== undefined ? { targetReads } : {}), ...(boundGrantDigest !== undefined ? { grants: boundGrantDigest } : {}), }; } export function approvalTargetsOf(reading, reads) { const targets = {}; const landing = (view) => (view?.kind === "path" && (view.canonical !== undefined || view.unread === true) ? (view.canonical ?? null) : undefined); for (const role of APPROVAL_TARGET_ROLES) { const several = reading?.each?.[role]; if (several === undefined) { const one = landing(reading?.[role]); if (one !== undefined) targets[role] = one; continue; } const all = several.map(landing); if (all.length > 0 && all.every((l) => l !== undefined)) targets[role] = Object.freeze(all); } return { ...(Object.keys(targets).length > 0 ? { targets } : {}), ...(reads !== undefined ? { targetReads: Object.fromEntries(reads.map((r) => [r.key, r.landing])) } : {}) }; } export const APPROVAL_STATION_MEMBERS = Object.freeze({ claim: Object.freeze(["tool", "grants"]), session: Object.freeze(["tool"]), execution: Object.freeze(["tool", "grants", "targets"]), }); const IDENTITY_MEMBERS = Object.freeze(["capabilityId", "contractId", "shapeDigest", "implementationRevision", "engineMounted"]); const FACE_MEMBERS = Object.freeze(["family", "pathTarget", "hostTarget", "startedShell"]); const shown = (s) => `"${inlineUntrusted(s, 240)}"`; const vetoed = (name, why) => `The approved tool call "${name}" was not executed: ${why}, so the approval does not cover it (resume.target_moved). This approval is spent — the call has to be re-issued: its new card shows what it would act on now.`; function faceKey(face) { const resolved = (k) => { const pt = face.pathTarget; if (k !== "pathTarget") return face[k] ?? null; return pt === undefined ? null : { param: pt.param, access: pt.access, aliases: [...(pt.aliases ?? [])], ...pathTargetResolutionOf(pt), patternParam: pt.patternParam ?? null, skillScopeEligible: pt.skillScopeEligible === true, ...(pt.each === true ? { each: true } : {}) }; }; return canonicalize(Object.fromEntries(FACE_MEMBERS.map((k) => [k, resolved(k)]))); } function judgeTool(row, live, station) { const bound = approvalObjectOf(row).tool; if ("missing" in bound) { const why = `carries no whole record of the tool it was asked for (${bound.missing.join(", ")} missing or not in its shape — a row parked by an engine before it recorded them, a call parked while its tool was off the leg's roster, or a damaged row), so which tool the approval covers cannot be read`; if (station !== "claim") return { member: "tool", disposition: "veto", code: "resume.target_moved", message: vetoed(row.toolName, `its checkpoint row ${why}`) }; return { member: "tool", disposition: "refuse_pending", code: "checkpoint.unsupported_version", message: `this checkpoint's pending approval ${why}, and it is not redeemed; the checkpoint stays pending: deny it so the model can re-issue the call (a row that also predates the ask's origin is refused a deny too), or expire it` }; } if (station === "claim") return undefined; const entry = live.tool; if (entry === undefined) return { member: "tool", disposition: "reopen", code: "resume.tool_unavailable", message: `the approved tool "${row.toolName}" is no longer available on resume — refusing to continue as if it ran; the checkpoint is reopened for a retry with the tool present` }; const id = { ...toolIdentityOf(entry), engineMounted: engineMountedRow(entry) ? true : undefined }; const differ = IDENTITY_MEMBERS.filter((k) => bound[k] !== id[k]); if (differ.length > 0) { return { member: "tool", disposition: "reopen", code: "resume.tool_contract_mismatch", message: `the approved tool "${row.toolName}" on this leg is not the tool the approval was minted against (${differ.map((k) => (k === "engineMounted" ? "mount site" : k)).join(", ")} differ) — refusing to execute a replacement wearing the name` }; } if (faceKey(bound) !== faceKey(entry)) { return { member: "tool", disposition: "veto", code: "resume.target_moved", message: vetoed(row.toolName, "the tool's face (its display family, the path target or URL slot it declares, or the shell it runs its text on) changed after the approval") }; } if (bound.declarationDigest === toolDeclarationDigestOf(entry)) return undefined; return { member: "tool", disposition: "veto", code: "resume.target_moved", message: vetoed(row.toolName, "the tool's declaration (what it does, reaches and trusts: its effect, egress, irreversibility, content origin, its peer's registration, boundary legs, rule face or model gate) changed after the approval") }; } function judgeTargets(row, live) { if ((row.targets === undefined && row.targetReads === undefined) || ("decided" in live && !licenseCovers(row.boundInputHash, row.toolName, live.decided))) return undefined; const why = landedElsewhere(row.targets, row.targetReads, live); return why === undefined ? undefined : { member: "targets", disposition: "veto", code: "resume.target_moved", message: vetoed(row.toolName, why) }; } const DIGEST = /^[0-9a-f]{64}$/; function landedElsewhere(bound, boundReads, live) { if (bound !== undefined) { const roles = typeof bound === "object" && bound !== null && !Array.isArray(bound) ? Object.entries(bound) : []; const located = (v) => v === null || (typeof v === "string" && v.length > 0); const whole = roles.length > 0 && roles.every(([k, v]) => APPROVAL_TARGET_ROLES.includes(k) && (located(v) || (Array.isArray(v) && v.length > 0 && v.every(located)))); if (!whole) return "the target member of the approval on its checkpoint row is damaged (not a reading → resolved location record)"; const now = live.landings !== undefined ? Object.fromEntries(roles.map(([role, was]) => [role, Array.isArray(was) || live.landings.length !== 1 ? live.landings : live.landings[0]])) : (approvalTargetsOf(live.targetReading).targets ?? {}); const where = (p) => (p === null ? "did not resolve" : `resolved to ${shown(p)}`); for (const [role, was] of roles) { const is = now[role]; if (canonicalize(is) === canonicalize(was)) continue; if (is === undefined) return `where its target resolves (it ${typeof was === "object" && was !== null ? "named several" : where(was)} when the card was asked) could not be established on this leg`; if (Array.isArray(was) || Array.isArray(is)) { const a = (Array.isArray(was) ? was : [was]); const b = (Array.isArray(is) ? is : [is]); const i = a.findIndex((w, j) => b[j] !== w); if (i < 0 || b[i] === undefined) return `the call names ${b.length} target(s) now and named ${a.length} when the card was asked`; return `its target ${i + 1} ${b[i] === null ? "does not resolve" : `resolves to ${shown(b[i])}`} now and ${where(a[i] ?? null)} when the card was asked`; } return `its target ${is === null ? "does not resolve" : `resolves to ${shown(is)}`} now and ${where(was)} when the card was asked`; } } if (boundReads === undefined) return undefined; const record = typeof boundReads === "object" && boundReads !== null && !Array.isArray(boundReads); const reads = record ? Object.entries(boundReads) : []; if (!record || !reads.every(([k, v]) => DIGEST.test(k) && typeof v === "string" && DIGEST.test(v))) return "the read member of the approval on its checkpoint row is damaged (not a read → landing record)"; if (live.reads === undefined) return `where its reads land (the read station judged ${reads.length} when the card was asked) could not be established on this leg`; const was = new Map(reads); const now = new Map(Object.entries(approvalTargetsOf(undefined, live.reads).targetReads ?? {})); const named = (key) => live.reads?.find((r) => r.key === key); const added = [...now.keys()].find((k) => !was.has(k)); if (added !== undefined || [...was.keys()].some((k) => !now.has(k))) return `this leg reads the command differently than when the card was asked (${added !== undefined ? `${shown(named(added)?.raw ?? "?")} is read now at a place or in a form the card did not cover` : "a read the card covered is not read now"})`; const movedKey = [...now.keys()].find((k) => now.get(k) !== was.get(k)); const moved = movedKey === undefined ? undefined : named(movedKey); if (movedKey === undefined) return undefined; const targets = moved?.targets ?? []; const at = targets.length === 0 ? "cannot be placed" : `lands on ${shown(targets[0])}${targets.length > 1 ? ` (and ${targets.length - 1} more)` : ""}`; return `its read ${shown(moved?.raw ?? "?")} ${at} now, not where it landed when the card was asked`; } function judgeGrants(row, live, station) { const refusal = parkedSkillApprovalRefusal(row, live.args, live.skills ?? [], live.skillToolName ?? "", station); if (refusal === undefined) return undefined; return station === "claim" ? { member: "grants", disposition: "refuse_pending", code: "checkpoint.invalid_outcome", message: refusal } : { member: "grants", disposition: "veto", message: refusal }; } export function judgeApprovalObject(row, live, station) { for (const member of APPROVAL_STATION_MEMBERS[station]) { const miss = member === "tool" ? judgeTool(row, live, station) : member === "targets" ? judgeTargets(row, live) : judgeGrants(row, live, station === "claim" ? "claim" : "execution"); if (miss !== undefined) return miss; } return "match"; }