UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

314 lines (313 loc) • 26.8 kB
import { CheckpointError, checkpointVersionOf, MAX_SUPPORTED_CHECKPOINT_VERSION } from "./checkpoint-features.js"; import { judgeCheckpointRequirements } from "./checkpoint-requirements.js"; import { isAskOrigin, isPermissionMode } from "./ask-origin.js"; import { validatePath } from "./effective-path-target.js"; import { persistedReadDenyEntryProblem } from "../tools/fs/read-deny.js"; import { readFrozenSkillGrants } from "./skill-grant.js"; import { readFrozenSkillScopes } from "./mods/spec-seats.js"; import { readRunLedgerParked } from "./run-ledger.js"; import { constraintChainDigestReading } from "./tool-policy.js"; import { asResumeConfigRefusal } from "./mode-policy.js"; import { screenRecordedRunOrigin } from "./run-origin.js"; import { refusePersistedToolNames } from "./runner/sub-agent-deny-lists.js"; import { boundedThrownName } from "./thrown-value.js"; import { memberPresent } from "./own-property-receipt.js"; import { CHECKPOINT_ROW_DAMAGED_SENTENCE, checkpointRowUnreadable, rowMemberProblem } from "./checkpoint-queries.js"; import { readLegIdentityRecord, SYNC_CHILD_BLOCK_MEMBERS } from "./leg-identity.js"; import { checkpointExecutionRecorded } from "./checkpoint-execution-record.js"; import { readStoredPrincipal, recordedPrincipalNameOf } from "./principal-name.js"; import { GLOBAL_USAGE_KEY } from "./usage-window-store.js"; const READING_CHANGED_CODE = "checkpoint.unsupported_version"; const READING_CHANGED_KEY = `${READING_CHANGED_CODE}|reading_changed`; function readingChanged(diagnostic) { return new CheckpointError(READING_CHANGED_CODE, diagnostic, { reason: "reading_changed" }); } const EARLIER_CHAIN_MEANING = "the row's frozen inherited constraint chain was recorded under an earlier engine release's projection meaning (its command-name component judged the leading command of one simple command), and this release judges that component on every program run of a command, so its frozen layers would not refuse exactly what they refused under that release"; export function earlierChainMeaningRefusal() { return readingChangedRefusal(EARLIER_CHAIN_MEANING); } export function readingChangedRefusal(diagnostic) { const refusal = readingChanged(diagnostic); refusal.message = `${ROW_REFUSAL_SENTENCES[READING_CHANGED_KEY]} Diagnostic: ${refusal.message}`; return refusal; } export const ROW_REFUSAL_SENTENCES = Object.freeze({ "checkpoint.unsupported_version|version_newer": "This engine cannot resume this checkpoint: it was parked by a newer engine release, whose row this release cannot read. The checkpoint stays pending; resume it on a worker at or above the release that parked it.", "checkpoint.unsupported_version|seat_retired": "This engine cannot resume this checkpoint: it carries a seat an earlier engine release wrote and this release retired. The checkpoint stays pending and nothing was consumed. Expire it and run the work again.", "checkpoint.unsupported_version|leg_not_resumable": "This engine cannot resume this checkpoint: it was parked by a synchronous child leg, and nobody resumes such a leg's parks — its result has no road back to the run that spawned it. Nothing was consumed; expire it, and run the work again: have a person who is present approve it live, or delegate it as a background agent whose approvals can wait.", [READING_CHANGED_KEY]: "This engine cannot resume this checkpoint: it was parked by an earlier engine release, and this release reads part of the row differently — a member the decision binds, or the constraints the work inherited — so the row would not mean here what it meant to that release. The row is intact and stays pending; nothing was consumed. Expire it, then start the task again.", "checkpoint.invalid_outcome|requirements_damaged": CHECKPOINT_ROW_DAMAGED_SENTENCE, "checkpoint.invalid_outcome|execution_recorded": "This engine cannot resume this checkpoint: it reads pending, yet it records what became of the action it was decided for — the decision was lost in storage after the action was taken up, so the action may already have run, or been refused. The checkpoint stays pending. Check what the row records (`executionOutcome`) and whether the action already took effect — running it again may repeat it. Expire it, then start the task again.", "checkpoint.invalid_outcome|real_approval_damaged": "This engine cannot resume this checkpoint: its real-approval mark is missing or malformed (a corruption or downgrade guard). The checkpoint stays pending. Expire it, then start the task again.", "checkpoint.invalid_outcome|read_face_damaged": "This engine cannot resume this checkpoint: its read-face section is missing or malformed (a corruption or downgrade guard). The checkpoint stays pending. Expire it, then start the task again.", "checkpoint.invalid_outcome|write_face_damaged": "This engine cannot resume this checkpoint: its write-face section is malformed (a corruption guard). The checkpoint stays pending. Expire it, then start the task again.", "checkpoint.invalid_outcome|skill_grants_damaged": "This engine cannot resume this checkpoint: its skill-grant section does not read as grant rows under this engine — damaged, or written by an earlier release whose entries this release reads differently. The checkpoint stays pending. Expire it and run the work again.", "checkpoint.invalid_outcome|skill_scopes_damaged": "This engine cannot resume this checkpoint: its skill-scope section does not read as a list of named skills (a damaged section). The checkpoint stays pending. Expire it, then start the task again.", "checkpoint.invalid_outcome|hands_coordinates_damaged": "This engine cannot resume this checkpoint: one of its recorded workspace coordinates is not an absolute path (a corruption guard). The checkpoint stays pending. Expire it, then start the task again.", "checkpoint.invalid_outcome|constraint_chain_missing": "This engine cannot resume this checkpoint: it requires parent constraints but does not carry both their frozen chain and its digest (a corruption or downgrade guard). The checkpoint stays pending. Expire it, then start the task again.", "checkpoint.walltime_axis_retired|": "This engine cannot resume this checkpoint: its budget carries a wall-clock allocation, an axis this engine retired, so resuming here would run the work with that ceiling unenforced. The checkpoint stays pending. Expire it and start a fresh task bounded by tokens or budget.", "resume.parent_constraint_mismatch|constraint_chain_damaged": "This engine cannot resume this checkpoint: its own recorded constraint chain does not match the digest it records (a corrupt or inconsistently minted row). The checkpoint stays pending. Expire it, then start the task again.", "config.permission_mode_invalid": "This engine cannot resume this checkpoint: a permission mode it records is not one this engine reads (or not one a plan can return to). The checkpoint stays pending. Expire it and run the work again.", "config.run_origin_invalid": "This engine cannot resume this checkpoint: the run origin it records is not a word this engine knows. The checkpoint stays pending. Expire it and run the work again.", "config.tool_face_control": "This engine cannot resume this checkpoint: its frozen inherited constraint chain records a tool name in a spelling this engine does not replay. The checkpoint stays pending. Expire it and run the work again under a policy that names each tool by its bare name.", }); export const ROW_REFUSAL_TERMINAL = Object.freeze({ "checkpoint.unsupported_version|version_newer": false, "checkpoint.unsupported_version|seat_retired": false, "checkpoint.unsupported_version|leg_not_resumable": true, [READING_CHANGED_KEY]: false, "checkpoint.invalid_outcome|requirements_damaged": true, "checkpoint.invalid_outcome|execution_recorded": true, "checkpoint.invalid_outcome|real_approval_damaged": true, "checkpoint.invalid_outcome|read_face_damaged": true, "checkpoint.invalid_outcome|write_face_damaged": true, "checkpoint.invalid_outcome|skill_grants_damaged": false, "checkpoint.invalid_outcome|skill_scopes_damaged": true, "checkpoint.invalid_outcome|hands_coordinates_damaged": true, "checkpoint.invalid_outcome|constraint_chain_missing": true, "checkpoint.walltime_axis_retired|": false, "resume.parent_constraint_mismatch|constraint_chain_damaged": true, "config.permission_mode_invalid": false, "config.run_origin_invalid": false, "config.tool_face_control": false, }); const LISTED_REQUIREMENT_WORD = /^[a-z][a-z_]{0,39}$/; const MAX_LISTED_REQUIREMENT_WORDS = 8; const OK = Object.freeze({ kind: "ok" }); export const UNREADABLE_ROW_VERDICT = Object.freeze({ kind: "damaged", code: "checkpoint.invalid_outcome", reason: "requirements_damaged", sentence: ROW_REFUSAL_SENTENCES["checkpoint.invalid_outcome|requirements_damaged"], terminal: ROW_REFUSAL_TERMINAL["checkpoint.invalid_outcome|requirements_damaged"], }); class RowChainArm { refusal; constructor(refusal) { this.refusal = refusal; } } export function retiredSteerSeatRefusal(state) { if (state.pendingSteer === undefined) return undefined; return new CheckpointError("checkpoint.unsupported_version", "this checkpoint carries a parked steer in the retired pre-queue single seat (`state.pendingSteer`), which this engine does not read — decide the parked instruction on the host's surface and, if it still applies, park it again with setPendingSteer", { reason: "seat_retired" }); } const RETIRED_MODE_SEED_MEMBERS = Object.freeze([ ["autoModeRequested", () => true], ["approverPosture", () => true], ["shellGate", (v) => v !== "always"], ]); export function retiredModeSeedRefusal(state) { const gate = state.inheritedGate; if (gate === undefined) return undefined; for (const [key, retired] of RETIRED_MODE_SEED_MEMBERS) { const value = gate[key]; if (value === undefined || !retired(value)) continue; const shown = typeof value === "string" ? JSON.stringify(value.slice(0, 40)) : typeof value === "boolean" ? String(value) : typeof value; return new CheckpointError("checkpoint.unsupported_version", `this checkpoint's inheritedGate carries the retired mode-seed member \`${key}\` (${shown}), written before 7.34.0 and read by no engine since 7.39.0 — expire the row (\`CheckpointStore.expire\`), or, if an engine at 7.38.x or earlier still runs, resume it once there (it reads the key into \`permissionMode\`); nothing was consumed`, { reason: "seat_retired" }); } return undefined; } export function recordedModeSeed(gate) { if (gate === undefined) return {}; const refusal = (message) => { const e = new Error(message); e.code = "config.permission_mode_invalid"; return e; }; const { permissionMode, prePlanMode, shellGate } = gate; if (permissionMode !== undefined && !isPermissionMode(permissionMode)) throw refusal(`the checkpoint row's inheritedGate.permissionMode is ${JSON.stringify(permissionMode)}, not a permission mode — the row cannot be resumed under a mode this engine does not know`); if (prePlanMode !== undefined && (!isPermissionMode(prePlanMode) || prePlanMode === "plan")) throw refusal(`the checkpoint row's inheritedGate.prePlanMode is ${JSON.stringify(prePlanMode)}, not a permission mode a plan can return to`); return { ...(permissionMode !== undefined ? { permissionMode } : {}), ...(prePlanMode !== undefined ? { prePlanMode } : {}), ...(shellGate !== undefined ? { shellGate } : {}) }; } function recordedWordRefusal(screen) { try { asResumeConfigRefusal("inheritedGate", screen); return undefined; } catch (e) { if (e instanceof CheckpointError) return e; throw e; } } function belowFormatRefusal(recorded) { const format = recorded === undefined || recorded === null ? "unrecorded (read as v0)" : typeof recorded === "number" ? `v${recorded}` : `${/^[aeiou]/.test(typeof recorded) ? "an" : "a"} ${typeof recorded} that reads below v${MAX_SUPPORTED_CHECKPOINT_VERSION}`; return new CheckpointError("checkpoint.unsupported_version", `this checkpoint's row format is ${format}, below the one this engine reads (v${MAX_SUPPORTED_CHECKPOINT_VERSION}): an engine release of 7.48.x or earlier parked it, and this release reads no row of an earlier format — expire it and run the work again; nothing was consumed`, { reason: "seat_retired" }); } function recordedIdentityRefusal(cp) { const members = [["principal", cp.principal], ["isolationScope", cp.isolationScope]]; for (const [i, key] of (cp.state.inheritedGate?.ancestorRules ?? []).entries()) members.push([`state.inheritedGate.ancestorRules[${i}].principal`, key.principal]); for (const [path, value] of members) { const reading = readStoredPrincipal(value); if (path === "principal" && reading.kind === "name" && reading.name === GLOBAL_USAGE_KEY) return readingChanged(`this checkpoint's \`principal\` is ${JSON.stringify(GLOBAL_USAGE_KEY)}, the usage ledger's key for work with no principal — a name an earlier engine release admitted and this release refuses at the task door, so no resume can run as it: expire the card and start the work again`); if (reading.kind !== "invalid") continue; if (recordedPrincipalNameOf(value) !== undefined) return readingChanged(`this checkpoint's \`${path}\` is a name an earlier engine release admitted and this release does not (${reading.fault}), so the resumed work would not act as the identity it parked under`); return new CheckpointError("checkpoint.invalid_outcome", `this checkpoint's \`${path}\` is no principal name (${reading.fault}) and no engine release records such an identity — a damaged row`, { reason: "requirements_damaged" }); } return undefined; } function rowRefusalOf(cp) { const recorded = cp.version; const version = checkpointVersionOf({ version: recorded }); if (version > MAX_SUPPORTED_CHECKPOINT_VERSION) { return new CheckpointError("checkpoint.unsupported_version", `checkpoint requires reader capabilities this worker lacks (row format v${version}; this worker reads up to v${MAX_SUPPORTED_CHECKPOINT_VERSION}) — resume it on a worker at or above the version that parked it`, { reason: "version_newer" }); } const requirements = version < MAX_SUPPORTED_CHECKPOINT_VERSION ? undefined : judgeCheckpointRequirements(cp); if (requirements?.kind === "lacking") return new CheckpointError("checkpoint.unsupported_version", `checkpoint requires reader capabilities this worker lacks (${requirements.words.join(", ")}) — resume it on a worker at or above the version that parked it`, { reason: "version_newer", requires: requirements.words }); if (cp.status === "pending" && checkpointExecutionRecorded(cp)) return new CheckpointError("checkpoint.invalid_outcome", "this checkpoint reads pending yet already records what became of its decided action (`executionOutcome`) — the decision before it was lost in storage, and its action is not run a second time", { reason: "execution_recorded" }); if (requirements === undefined) return belowFormatRefusal(recorded); const shape = rowMemberProblem(cp); if (shape !== undefined) return new CheckpointError("checkpoint.invalid_outcome", `this checkpoint's \`${shape.member}\` does not read as every reader of a row reads it (${shape.problem}) — a damaged row`, { reason: "requirements_damaged" }); if (SYNC_CHILD_BLOCK_MEMBERS.some((m) => memberPresent(cp, m))) return new CheckpointError("checkpoint.unsupported_version", "this checkpoint was parked by a synchronous child leg (it carries the synchronous-child block), and this engine resumes no such leg: nobody can resume it and its result has no road back to the run that spawned it", { reason: "leg_not_resumable" }); const retiredSeed = retiredModeSeedRefusal(cp.state); if (retiredSeed !== undefined) return retiredSeed; const retiredSteer = retiredSteerSeatRefusal(cp.state); if (retiredSteer !== undefined) return retiredSteer; const retiredWalltimeTotal = cp.resourceLedger?.totalWalltimeSec; if (retiredWalltimeTotal !== undefined) { return new CheckpointError("checkpoint.walltime_axis_retired", "this checkpoint's ledger carries a cross-slice WALL-CLOCK allocation (resourceLedger.totalWalltimeSec), an axis this engine version retired — " + "resuming here would run the leg with that ceiling unenforced. Rejected pre-CAS (the checkpoint stays pending): expire it and start a fresh task " + "bounded by resourceSuspend.totalTokens / totalBudgetUsd."); } if (requirements.kind === "damaged") return new CheckpointError("checkpoint.invalid_outcome", `this checkpoint's reader-requirement list does not match the row (${requirements.why})`, { reason: "requirements_damaged" }); if (requirements.kind === "earlier") return readingChanged(`this checkpoint reads as an earlier engine release wrote it, and this release reads a member the decision binds differently (${requirements.why})`); const identity = recordedIdentityRefusal(cp); if (identity !== undefined) return identity; const modeWords = recordedWordRefusal(() => void recordedModeSeed(cp.state.inheritedGate)); if (modeWords !== undefined) return modeWords; const gateBit = cp.gate.kind === "irreversible_ask" ? cp.gate.realApproval : undefined; const bitWellFormed = gateBit !== undefined && typeof gateBit === "object" && isAskOrigin(gateBit.origin); const faceSaysGoverned = (cp.state.readFace?.realApproval) === true; if (faceSaysGoverned ? !bitWellFormed : gateBit !== undefined && !bitWellFormed) { return new CheckpointError("checkpoint.invalid_outcome", `a v${version} checkpoint's realApproval gate bit must be well-formed (origin a member of the closed ask-origin set) — this row's is not; refusing to resume a damaged real-approval row (corruption / downgrade guard), the checkpoint stays pending`, { reason: "real_approval_damaged" }); } const faceSectionRaw = cp.state.readFace; const faceCandidate = faceSectionRaw !== undefined && typeof faceSectionRaw === "object" && faceSectionRaw !== null ? faceSectionRaw : undefined; const faceWellFormed = faceCandidate !== undefined && (faceCandidate.face === "open" || faceCandidate.face === "roots") && (faceCandidate.realApproval === undefined || faceCandidate.realApproval === true) && (faceCandidate.denyEntries === undefined || (Array.isArray(faceCandidate.denyEntries) && faceCandidate.denyEntries.every((e) => persistedReadDenyEntryProblem(e) === null))); if (faceSectionRaw !== undefined && !faceWellFormed) { return new CheckpointError("checkpoint.invalid_outcome", `a v${version} checkpoint must carry a well-formed read-face section (state.readFace) — this row's is missing or malformed; refusing to resume a damaged read-face row (corruption / downgrade guard), the checkpoint stays pending`, { reason: "read_face_damaged" }); } const writeFaceSectionRaw = cp.state.writeFace; if (writeFaceSectionRaw !== undefined) { const c = typeof writeFaceSectionRaw === "object" && writeFaceSectionRaw !== null ? writeFaceSectionRaw : undefined; if (c === undefined || !(c.face === "open" || c.face === "roots")) { return new CheckpointError("checkpoint.invalid_outcome", `this checkpoint carries a write-face section (state.writeFace) that is not well-formed — refusing to resume a damaged write-face row (corruption guard), the checkpoint stays pending`, { reason: "write_face_damaged" }); } } const readBlockRaw = cp.state.readBlock; if (readBlockRaw !== undefined && readBlockRaw !== true) return new CheckpointError("checkpoint.invalid_outcome", "this checkpoint's `state.readBlock` does not read as every reader of a row reads it (present, it is not `true`) — a damaged row", { reason: "requirements_damaged" }); if (readFrozenSkillGrants(cp.state.skillGrants) === undefined) return new CheckpointError("checkpoint.invalid_outcome", "this checkpoint carries a skill-grant section (state.skillGrants) that does not read as grant rows under this engine — a damaged section, or a row an earlier release wrote whose entry this release reads as nothing (an entry with a surrounding space, say) — refusing to resume without the grant rows and refusals it carries; the checkpoint stays pending: expire it and run the work again", { reason: "skill_grants_damaged" }); if (readFrozenSkillScopes(cp.state.skillScopes) === undefined) return new CheckpointError("checkpoint.invalid_outcome", "this checkpoint carries a skill-scope section (state.skillScopes) that does not read as a list of SkillSpec names — a damaged section — refusing to resume without the active skills' hooks it records; the checkpoint stays pending: expire it and run the work again", { reason: "skill_scopes_damaged" }); const runLedgerRaw = cp.state.runLedger; if (runLedgerRaw !== undefined && readRunLedgerParked(runLedgerRaw) === undefined) return new CheckpointError("checkpoint.invalid_outcome", "this checkpoint's member ledger section (state.runLedger) does not read as the book an engine froze — a damaged row; the checkpoint stays pending", { reason: "requirements_damaged" }); if (readLegIdentityRecord(cp.state.legIdentity) === "damaged") return new CheckpointError("checkpoint.invalid_outcome", "this checkpoint's leg identity section (state.legIdentity) does not read as the record an engine mints — a damaged row; the checkpoint stays pending", { reason: "requirements_damaged" }); for (const field of ["handsRoot", "handsHome", "handsCwd"]) { const coordinate = cp.state[field]; if (coordinate !== undefined && validatePath(coordinate, { intent: "validate-coordinate" }) === undefined) return new CheckpointError("checkpoint.invalid_outcome", `this checkpoint's state.${field} is not an absolute path — refusing to resume a row whose hands' coordinates are damaged (corruption guard), the checkpoint stays pending`, { reason: "hands_coordinates_damaged" }); } const chainNames = recordedWordRefusal(() => refusePersistedToolNames(undefined, cp.state.inheritedGate?.constraintChain, undefined)); if (chainNames !== undefined) return chainNames; const runOrigin = recordedWordRefusal(() => void screenRecordedRunOrigin(cp.state.runOrigin)); if (runOrigin !== undefined) return runOrigin; const gate = cp.state.inheritedGate; if (gate?.requiresParentConstraint === true) { if (gate.constraintChain === undefined || gate.constraintDigest === undefined) { return new CheckpointError("checkpoint.invalid_outcome", `a v${version} checkpoint that requires parent constraints must carry BOTH the frozen constraintChain and its constraintDigest (they are minted in one write with the version stamp) — this row carries neither or only one; refusing to fall back to the count-only contract on a damaged row (corruption / downgrade guard), the checkpoint stays pending`, { reason: "constraint_chain_missing" }); } const expectedDigest = gate.constraintDigest; const reading = expectedDigest === undefined || gate.constraintChain === undefined ? undefined : constraintChainDigestReading(gate.constraintChain, expectedDigest); if (reading === "earlier") return new RowChainArm(readingChanged(EARLIER_CHAIN_MEANING)); if (expectedDigest !== undefined && reading !== "same") { return new CheckpointError("resume.parent_constraint_mismatch", "the checkpoint's OWN recorded constraint chain does not match its recorded digest " + "(corrupt / inconsistently-minted row) — the frozen deny data the resume would execute is not the data the " + "digest authenticates; rejected pre-CAS (the checkpoint stays pending)", { reason: "constraint_chain_damaged" }); } } return undefined; } function refusalKeyOf(refusal) { return refusal.code === "checkpoint.config_refused" ? String(refusal.detail?.code) : `${refusal.code}|${refusal.detail?.reason ?? ""}`; } function isRowRefusalKey(key) { return Object.prototype.hasOwnProperty.call(ROW_REFUSAL_SENTENCES, key); } function readRow(cp) { const found = rowRefusalOf(cp); if (found === undefined) return { verdict: OK }; const refusal = found instanceof RowChainArm ? found.refusal : found; const key = refusalKeyOf(refusal); if (!isRowRefusalKey(key)) throw new Error(`row refusal ${key} has no sentence`); const sentence = ROW_REFUSAL_SENTENCES[key]; const lacking = refusal.code === "checkpoint.unsupported_version" && refusal.detail?.reason === "version_newer"; const token = cp.token; const requires = (refusal.detail?.requires ?? []).filter((w) => LISTED_REQUIREMENT_WORD.test(w) && w !== token).slice(0, MAX_LISTED_REQUIREMENT_WORDS); const verdict = Object.freeze({ kind: lacking ? "lacking" : "damaged", code: refusal.code, ...(refusal.detail?.reason !== undefined ? { reason: refusal.detail.reason } : {}), ...(refusal.detail?.field !== undefined ? { field: refusal.detail.field } : {}), ...(refusal.detail?.code !== undefined ? { blockedBy: refusal.detail.code } : {}), ...(requires.length > 0 ? { requires: Object.freeze(requires) } : {}), sentence, terminal: ROW_REFUSAL_TERMINAL[key], }); refusal.message = `${sentence} Diagnostic: ${refusal.message}`; return { verdict, refusal, ...(found instanceof RowChainArm ? { chainArm: true } : {}) }; } function readRowTotal(cp) { try { return readRow(cp); } catch (e) { const name = boundedThrownName(e); return { verdict: UNREADABLE_ROW_VERDICT, refusal: checkpointRowUnreadable(`the row could not be read (${name} thrown while judging it)`, "pending", name) }; } } export function judgeCheckpointRow(cp) { return readRowTotal(cp).verdict; } export function checkpointRowRefusal(cp) { return readRowTotal(cp).refusal; } export function checkpointRowResumeRefusal(cp) { const reading = readRowTotal(cp); return reading.refusal === undefined ? undefined : { refusal: reading.refusal, chainArm: reading.chainArm === true }; }