@sema-agent/core
Version:
Stateless, task-oriented AI agent core
869 lines (868 loc) • 46.1 kB
JavaScript
import { randomBytes, randomUUID } from "node:crypto";
import { types } from "node:util";
import { uuidv7 } from "../internal/harness.js";
import { PROBE_REASON_MAX, inlineUntrusted, sanitizeUntrustedText } from "./untrusted-text.js";
import { CheckpointError, checkpointVersionOf, copiedRiskAxes, isPlainRecord, normalizeProbeCause, safeDataValue } from "./checkpoint-features.js";
import { judgeCheckpointRow, retiredSteerSeatRefusal, UNREADABLE_ROW_VERDICT } from "./checkpoint-row-verdict.js";
import { checkpointRowLabel, readGateIdentity } from "./checkpoint-identity.js";
import { boundedThrownName } from "./thrown-value.js";
import { planReviewFactsOf } from "./plan-review-facts.js";
import { carriesBidiControls } from "./tool-policy.js";
import { agentIdOf, legTaskIdOf, readLegIdentityRecord } from "./leg-identity.js";
import { isAutoModeFallbackCause, readDenialLimitFallback } from "./auto-mode.js";
import { isAskOrigin, isPersistedRuleMandate, isRuleOffersAbsence, receiveAskReasons } from "./ask-origin.js";
import { approvalMessageOf } from "./approval-display.js";
import { isRunOrigin, RUN_ORIGINS } from "./run-origin.js";
import { describeRejectedValue } from "./tool-search-setting.js";
import { readBoundBinding } from "./skill-grant-binding.js";
import { checkpointExecutionRecorded, executionRecordDisposition, ExecutionOutcomeConflictError, } from "./checkpoint-execution-record.js";
import { checkpointHolderMatches, checkpointOccMatches, checkpointRevOf, holderJudgedCurrent, readHolderJudge } from "./checkpoint-generation.js";
import { holderSupersededError } from "./grant-holder.js";
import { isGateKind, parkedApprovalCardOf } from "./pause-registry.js";
import { checkpointDeadlineColumn, checkpointDeadlinePassed, checkpointRunSessionOf, storedCheckpointRowRefusal, deleteSessionRowsAtStart, ownerSessionRowsDelete, unreadableSessionRowsDelete, readCheckpointOverdueQuery, readCheckpointSessionQuery, rowMemberProblem, selectOverduePage, selectSessionPage } from "./checkpoint-queries.js";
import { renderUntrustedCommandText, stripFormatCharacters } from "./permission-rule-model.js";
import { egressText } from "./untrusted-egress.js";
import { steerReplayRefusal } from "./steer-replay.js";
import { readRetentionDeclaration } from "./retention.js";
import { memberPresent, optionKeys, receiptRefusal, receiveOptions, strayMembersOf } from "./own-property-receipt.js";
import { describeFault, receive } from "./mods/kernel/receive.js";
import { isBlankInput, MAX_PENDING_STEER_CHARS, STEERING_CONTROL_CHARS_RE, steeringTextDefect } from "./input-author.js";
import { oneStepRekeyAnswerOf, readIdentityRekeyInput } from "./identity-rekey.js";
import { rekeyCheckpointRow } from "./checkpoint-rekey.js";
export { MAX_PENDING_STEER_CHARS };
export { CHECKPOINT_CONFIG_REFUSAL_CODES, CHECKPOINT_ERROR_CODES, CHECKPOINT_FEATURES, CheckpointError, checkpointVersionOf, encodeAtFidelity, isCheckpointConfigRefusalCode, isCheckpointErrorCode, isPlainRecord, MAX_SUPPORTED_CHECKPOINT_VERSION, normalizeProbeCause, safeDataValue, SPAWN_RESUME_REFUSAL_CODES, } from "./checkpoint-features.js";
export function mintCheckpointToken() {
return randomBytes(16).toString("hex");
}
export function mintCheckpointId() {
return `cp_${randomUUID()}`;
}
import { isResourceLimitReason } from "./resource-limit-reasons.js";
export { RESOURCE_LIMIT_REASONS, PLATFORM_LIMIT_REASONS, isResourceLimitReason } from "./resource-limit-reasons.js";
export { PROBE_REASON_MAX } from "./untrusted-text.js";
export function riskSeverity(axes) {
return readRiskAxes(axes).tier;
}
function readRiskAxes(axes) {
const word = (v) => (v === undefined ? "absent" : v === null ? "null" : Array.isArray(v) ? "an array" : typeof v === "object" ? "an object" : `a ${typeof v}`);
if (!isPlainRecord(axes))
return { tier: undefined, problem: `${word(axes)}${typeof axes === "object" && axes !== null && !Array.isArray(axes) ? " that is not a plain record" : ""}` };
const damaged = [];
const mark = (name, v) => (v === undefined || typeof v === "boolean" ? v === true : (damaged.push(`\`${name}\` mark is ${word(v)}`), false));
const egress = mark("egress", axes.egress);
const irreversible = mark("irreversible", axes.irreversible);
const shell = mark("shell", axes.shell);
const proven = irreversible && egress ? 5 : irreversible ? 4 : egress || shell ? 3 : 2;
return damaged.length === 0 ? { tier: proven } : { tier: proven === 2 ? undefined : proven, problem: `a record whose ${damaged.join(" and ")}, not a boolean` };
}
const SUMMARY_CMD_MAX = 200;
const SUMMARY_VALUE_MAX = 120;
const SUMMARY_TOTAL_MAX = 200;
const PATH_MAX = 200;
const MAX_TOUCHED_PATHS = 8;
const MAX_DIGEST_KEYS = 16;
const MAX_DIGEST_SCAN_KEYS = 256;
export const MAX_TOOL_INPUT_PREVIEW_CHARS = 512;
const BIDI_BACKFILL_MAX_CHARS = 32_000;
const BIDI_BACKFILL_MAX_NODES = 512;
export const PENDING_STEER_QUEUE_BYTE_BUDGET_BYTES = 48_000;
export const PENDING_STEER_FROZEN_FIELDS = Object.freeze(["text", "trusted", "actor", "seq", "inputId", "priority", "runOrigin", "reply", "source"]);
const PENDING_STEER_REPLY_FROZEN_FIELDS = Object.freeze(["text", "by", "entered"]);
const PENDING_STEER_REPLY_WORDS = Object.freeze({ subject: "steering reply", unit: "field", moment: "when the entry is persisted" });
function safeKeys(obj) {
try {
return Object.keys(obj);
}
catch {
return [];
}
}
function fsPathArg(args) {
if (!isPlainRecord(args))
return undefined;
const fp = safeDataValue(args, "file_path");
if (typeof fp === "string" && fp.length > 0)
return fp;
const p = safeDataValue(args, "path");
return typeof p === "string" && p.length > 0 ? p : undefined;
}
export function buildRiskDescriptor(input) {
const { toolName } = input;
try {
const { args, safety, shellGated } = input;
const egress = safety?.egress === true;
const shell = shellGated === true;
const irreversible = !shell && safety?.irreversible === true;
const axes = {};
if (egress)
axes.egress = true;
if (irreversible)
axes.irreversible = true;
if (shell)
axes.shell = true;
let summary;
if (shell || toolName === "Bash") {
const cmd = isPlainRecord(args) ? safeDataValue(args, "command") : undefined;
if (typeof cmd === "string" && cmd.length > 0)
summary = renderUntrustedCommandText(stripFormatCharacters(egressText("same-principal", cmd)), SUMMARY_CMD_MAX);
const bg = isPlainRecord(args) ? safeDataValue(args, "run_in_background") : undefined;
if (bg === true)
summary = `[background persistent process — no per-step recheck] ${summary ?? ""}`.trimEnd();
}
else if (isPlainRecord(args)) {
{
const parts = [];
for (const key of safeKeys(args).slice(0, MAX_DIGEST_SCAN_KEYS).sort().slice(0, MAX_DIGEST_KEYS)) {
if (key === "__proto__" || key === "constructor" || key === "prototype")
continue;
const v = safeDataValue(args, key);
if (typeof v === "string" || typeof v === "number" || typeof v === "boolean") {
const encDigest = (s) => s.replace(/%/g, "%25").replace(/=/g, "%3D").replace(/ /g, "%20");
const k = encDigest(renderUntrustedCommandText(key, 40));
const val = encDigest(renderUntrustedCommandText(stripFormatCharacters(egressText("same-principal", String(v))), SUMMARY_VALUE_MAX));
parts.push(`${k}=${val}`);
}
}
if (parts.length > 0)
summary = renderUntrustedCommandText(parts.join(" "), SUMMARY_TOTAL_MAX);
}
}
const touched = [];
if (!shell && toolName !== "Bash") {
const p = fsPathArg(args);
if (p !== undefined)
touched.push(renderUntrustedCommandText(p, PATH_MAX));
}
const touchedPaths = touched.length > 0 ? touched.slice(0, MAX_TOUCHED_PATHS) : undefined;
return {
severity: riskSeverity(axes),
axes, ...copiedRiskAxes(input.riskAxes),
toolName,
...(input.shellGated && input.shellGateDoctrine !== undefined ? { shellGateDoctrine: input.shellGateDoctrine } : {}),
...(input.allowRuleShadowed !== undefined && input.allowRuleShadowed.length > 0 ? { allowRuleShadowed: input.allowRuleShadowed.map((r) => ({ member: r.member, entries: r.entries.map((e) => renderUntrustedCommandText(e, 200)), ...(r.omitted !== undefined ? { omitted: r.omitted } : {}), ...(r.reason !== undefined ? { reason: r.reason } : {}) })) } : {}),
...(input.probeReason !== undefined ? { probeReason: inlineUntrusted(input.probeReason, PROBE_REASON_MAX) } : {}),
...(() => {
if (input.probeCause === undefined)
return {};
const cause = normalizeProbeCause(input.probeCause);
return cause !== undefined ? { probeCause: cause } : {};
})(),
...(summary !== undefined ? { summary } : {}),
...(touchedPaths !== undefined ? { touchedPaths } : {}),
};
}
catch {
return { severity: 2, axes: {}, toolName: typeof toolName === "string" ? toolName : "" };
}
}
export function realApprovalOrgFact(bit) {
if (bit === undefined)
return undefined;
if (bit.org !== undefined)
return bit.org;
return bit.origin === "org_rule" ? "rule" : bit.origin === "org_unavailable" ? "unavailable" : undefined;
}
function finiteBound(v) {
return v !== undefined && Number.isFinite(v) ? v : undefined;
}
function finiteSpend(v) {
return v !== undefined && Number.isFinite(v) ? v : undefined;
}
export function debitLedger(prior, slice, total, opts) {
return {
totalBudgetMicroUsd: finiteBound(prior?.totalBudgetMicroUsd) ?? finiteBound(total?.totalBudgetMicroUsd),
totalTokens: finiteBound(prior?.totalTokens) ?? finiteBound(total?.totalTokens),
spentMicroUsd: (finiteSpend(prior?.spentMicroUsd) ?? 0) + Math.max(0, finiteSpend(slice.costMicroUsd) ?? 0),
spentTokens: (finiteSpend(prior?.spentTokens) ?? 0) + Math.max(0, finiteSpend(slice.tokens) ?? 0),
spentTurns: (finiteSpend(prior?.spentTurns) ?? 0) + Math.max(0, finiteSpend(slice.turns) ?? 0),
spentWalltimeMs: (finiteSpend(prior?.spentWalltimeMs) ?? 0) + Math.max(0, finiteSpend(slice.walltimeMs) ?? 0),
sliceCount: (prior?.sliceCount ?? 0) + (opts?.countSlice === false ? 0 : 1),
};
}
export function remainingBudgetMicroUsd(ledger) {
const total = ledger?.totalBudgetMicroUsd;
if (total === undefined || !Number.isFinite(total))
return undefined;
const spent = ledger?.spentMicroUsd;
if (spent !== undefined && !Number.isFinite(spent))
return 0;
return Math.max(0, total - (spent ?? 0));
}
export function remainingTokens(ledger) {
const total = ledger?.totalTokens;
if (total === undefined || !Number.isFinite(total))
return undefined;
const spent = ledger?.spentTokens;
if (spent !== undefined && !Number.isFinite(spent))
return 0;
return Math.max(0, total - (spent ?? 0));
}
export { REOPEN_REASONS } from "./resume-startup-cause.js";
const INDEX_TREE_DATA = Object.freeze({ accessors: "refuse", depth: 1, others: "as-is", isProxy: (v) => types.isProxy(v) });
function indexTreeRefusal(member, value) {
let why;
if (value === undefined)
why = "absent";
else if (value === null)
why = "null";
else if (typeof value !== "object")
why = `a ${typeof value}`;
else {
const received = receive(value, INDEX_TREE_DATA);
if (!received.ok)
why = describeFault(received.fault);
else if (Array.isArray(value))
why = "a list";
else if (!isPlainRecord(value))
why = "an object of another prototype";
}
if (why === undefined)
return undefined;
return receiptRefusal(`checkpointIndexFacts: the row's ${member} is ${why} — it must be an object of plain data (a record read off its own members: no accessor, no Proxy, no other prototype). The index facts are derived from the gate and the pending action alone, so a row without them is refused before any column is derived.`);
}
export function checkpointIndexFacts(cp) {
const gate = cp.gate;
const pending = cp.pendingAction;
const refused = indexTreeRefusal("gate", gate) ?? indexTreeRefusal("pendingAction", pending);
if (refused !== undefined)
throw refused;
const runSessionId = checkpointRunSessionOf(cp) ?? null;
const card = parkedApprovalCardOf(gate);
const tool = pending.kind === "tool_approval" ? pending : undefined;
return {
token: cp.token,
scope: cp.scope,
sessionId: cp.sessionId,
runSessionId,
version: checkpointVersionOf(cp),
gateKind: gate.kind,
approvalCard: card.kind === "card" ? card.card : card.kind === "unknown_word" && typeof card.word === "string" ? card.word : null,
toolName: tool?.toolName ?? null,
toolCallId: tool?.toolCallId ?? null,
boundInputHash: tool?.boundInputHash ?? null,
deadline: checkpointDeadlineColumn(cp.deadline),
createdAt: cp.createdAt,
riskDescriptor: card.kind !== "not_approval" && "riskDescriptor" in gate ? (gate.riskDescriptor ?? null) : null,
hasBidiControls: tool?.hasBidiControls === true ? true : null,
};
}
export function summarizeCheckpoint(cp, disclose, verdict) {
const rowVerdict = verdict ?? judgeCheckpointRow(cp);
let why;
try {
const problem = rowMemberProblem(cp);
if (problem === undefined)
return projectCheckpoint(cp, rowVerdict, disclose);
why = problem.problem;
}
catch (e) {
why = boundedThrownName(e);
}
return unreadableSummary(cp, rowVerdict, disclose, why);
}
const isFiniteMember = (v) => typeof v === "number" && Number.isFinite(v);
const MAX_DATE_EPOCH_MS = 8.64e15;
function resourceLimitOf(publishedKind, gate, createdAt) {
if (publishedKind !== "resource_limit" || gate === null || typeof gate !== "object")
return undefined;
const { kind, reason, resumeAfterMs } = gate;
if (kind !== "resource_limit" || !isResourceLimitReason(reason))
return undefined;
const resumableAt = reason === "usage_window" && isFiniteMember(resumeAfterMs) && resumeAfterMs >= 0 && isFiniteMember(createdAt) ? createdAt + resumeAfterMs : undefined;
return isFiniteMember(resumableAt) && Math.abs(resumableAt) <= MAX_DATE_EPOCH_MS ? { reason, resumableAt } : { reason };
}
const UNREADABLE_SUMMARY_MEMBERS = Object.freeze(["token", "rowVerdict", "sessionId", "scope", "gateKind", "resourceLimit", "createdAt", "deadline"]);
function unreadableForm(summary) {
return summary;
}
export function isUnreadableCheckpointSummary(summary) {
const members = UNREADABLE_SUMMARY_MEMBERS;
return summary.rowVerdict.kind !== "ok" && Object.keys(summary).every((member) => members.includes(member));
}
function unreadableSummary(cp, judged, disclose, why) {
const read = (member, unreadable) => {
try {
return member();
}
catch {
return unreadable;
}
};
const token = read(() => cp.token);
const sessionId = read(() => cp.sessionId);
const scope = read(() => cp.scope);
const gateKind = read(() => cp.gate.kind);
const createdAt = read(() => cp.createdAt);
const deadline = read(() => cp.deadline);
const resourceLimit = read(() => resourceLimitOf(gateKind, cp.gate, createdAt));
const identity = readGateIdentity(read(() => cp.checkpointId, null), token);
disclose?.(`${checkpointRowLabel(identity)} of session ${typeof sessionId === "string" ? JSON.stringify(sessionId) : "(unreadable)"}: its summary could not be projected (${why}) — it is listed as unreadable, with the members that could be read`);
return unreadableForm({
token: (typeof token === "string" ? token : ""),
rowVerdict: judged.kind === "ok" ? UNREADABLE_ROW_VERDICT : judged,
sessionId: typeof sessionId === "string" ? sessionId : "",
scope: typeof scope === "string" ? scope : "",
...(isGateKind(gateKind) ? { gateKind } : {}),
...(resourceLimit !== undefined ? { resourceLimit } : {}),
...(isFiniteMember(createdAt) ? { createdAt } : {}),
...(isFiniteMember(deadline) ? { deadline } : {}),
});
}
function workflowMemberSummary(member) {
if (member === null || typeof member !== "object")
return {};
const { runId, label, askedAgain } = member;
if (typeof runId !== "string" || runId === "" || typeof label !== "string")
return {};
return { workflowRunId: runId, workflowAgentLabel: label, ...(askedAgain === true ? { workflowStepAskedAgain: true } : {}) };
}
function projectCheckpoint(cp, rowVerdict, disclose) {
const facts = checkpointIndexFacts(cp);
const rowIdentity = readGateIdentity(cp.checkpointId, cp.token);
const rowName = `${checkpointRowLabel(rowIdentity)} of session ${JSON.stringify(cp.sessionId)}`;
const descriptor = facts.riskDescriptor;
const axes = descriptor === null ? undefined : readRiskAxes(descriptor?.axes);
const severity = axes?.tier;
if (axes?.problem !== undefined) {
disclose?.(`${rowName}: the risk descriptor's axes are ${axes.problem} — ${severity === undefined ? "the summary carries no severity" : `the summary's severity ${severity} is read from the valid marks`}`);
}
const cardReading = parkedApprovalCardOf(cp.gate);
const tool = cp.pendingAction.kind === "tool_approval" ? cp.pendingAction : undefined;
let toolInput;
if (tool !== undefined) {
try {
const raw = JSON.stringify(tool.args);
if (typeof raw === "string") {
toolInput = raw.length > MAX_TOOL_INPUT_PREVIEW_CHARS ? `${raw.slice(0, MAX_TOOL_INPUT_PREVIEW_CHARS)}…` : raw;
}
}
catch {
toolInput = undefined;
}
}
const shownPreview = tool?.preview;
const hasBidi = tool !== undefined &&
(facts.hasBidiControls === true ||
carriesBidiControls([toolInput, shownPreview], { maxNodes: BIDI_BACKFILL_MAX_NODES, maxChars: BIDI_BACKFILL_MAX_CHARS }));
const agentId = agentIdOf({ taskId: cp.state.legTaskId ?? legTaskIdOf({}, cp.state, cp.sessionId), isDelegatedChild: cp.state.isDelegatedChild === true });
const preview = (() => {
if (shownPreview === undefined)
return {};
try {
return { copy: structuredClone(shownPreview) };
}
catch {
disclose?.(`${rowName}: its approval preview is not a value a summary can copy — the summary carries no preview`);
return {};
}
})();
return {
token: facts.token,
rowVerdict,
...(cp.checkpointId !== undefined ? { checkpointId: cp.checkpointId } : {}),
...(cp.parentSessionId !== undefined ? { parentSessionId: cp.parentSessionId } : {}),
...(cp.parentTaskId !== undefined ? { parentTaskId: cp.parentTaskId } : {}),
...(cp.rootSessionId !== undefined ? { rootSessionId: cp.rootSessionId } : {}),
...(cp.rootSessionIncarnation !== undefined ? { rootSessionIncarnation: cp.rootSessionIncarnation } : {}),
sessionId: facts.sessionId,
scope: facts.scope,
gateKind: facts.gateKind,
...((resourceLimit) => (resourceLimit !== undefined ? { resourceLimit } : {}))(resourceLimitOf(facts.gateKind, cp.gate, facts.createdAt)),
...(severity !== undefined ? { severity } : {}),
...(cp.resourceLedger !== undefined ? { spentMicroUsd: cp.resourceLedger.spentMicroUsd } : {}),
...(isFiniteMember(facts.deadline) ? { deadline: facts.deadline } : {}),
createdAt: facts.createdAt,
...(cp.sourceSessionId !== undefined ? { sourceSessionId: cp.sourceSessionId } : {}),
...(agentId !== undefined ? { agentId } : {}), ...(cp.state.fromSubagent === true ? { fromSubagent: true } : {}),
...((name) => (typeof name === "string" ? { sourceAgentName: name } : {}))(cp.state.sourceAgentName),
...workflowMemberSummary(cp.state.workflowMember), ...((leg) => (typeof leg === "object" && leg.ruleSessionId !== undefined ? { sessionScope: leg.ruleSessionId } : {}))(readLegIdentityRecord(cp.state.legIdentity)),
...(cp.principal !== undefined ? { principal: cp.principal } : {}),
...(facts.toolCallId !== null ? { toolCallId: facts.toolCallId } : {}),
...planReviewFactsOf(cp),
...(facts.toolName !== null ? { toolName: facts.toolName } : {}),
...(cardReading.kind === "card" ? { approvalCard: cardReading.card } : {}),
...(toolInput !== undefined ? { toolInput } : {}),
...(cp.state.workspaceHandle !== undefined
? { restoreMode: cp.state.workspaceHandle.restoreMode === "park_only" ? "park_only" : "snapshot" }
: {}),
...((runOrigin) => (isRunOrigin(runOrigin) ? { runOrigin } : {}))(cp.state.runOrigin),
...("copy" in preview ? { preview: preview.copy } : {}),
...(tool?.previewWithheld === "oversize" || tool?.previewWithheld === "unavailable" ? { previewWithheld: tool.previewWithheld } : {}),
...(tool?.requiresRealApproval === true ? { requiresRealApproval: true } : {}),
...(tool?.mandated === true ? { mandated: true } : {}),
...(tool?.authoredBy === "deployment" ? { authoredBy: "deployment" } : {}),
...(tool?.fromApprovalList === true ? { fromApprovalList: true } : {}),
...(() => {
const fb = readDenialLimitFallback(tool?.denialLimitFallback);
return fb !== undefined ? { denialLimitFallback: fb } : {};
})(),
...(() => {
const origin = tool?.origin;
const mandate = tool?.mandate;
const why = tool?.classifierNoRuling;
const absence = tool?.ruleOffersAbsence;
return {
...(isAskOrigin(origin) ? { origin } : {}),
...(isPersistedRuleMandate(mandate) ? { mandate } : {}),
...(isAutoModeFallbackCause(why) ? { classifierNoRuling: why } : {}),
...(isRuleOffersAbsence(absence) ? { ruleOffersAbsence: absence } : {}),
};
})(),
...((askReasons) => (askReasons !== undefined ? { askReasons } : {}))(receiveAskReasons(tool?.askReasons)),
...((cardMessage) => (cardMessage !== undefined ? { cardMessage } : {}))(approvalMessageOf(tool?.cardMessage)),
...((headline) => (headline !== undefined ? { headline } : {}))(approvalMessageOf(tool?.headline)),
...(tool !== undefined ? readBoundBinding(tool) : {}),
...(hasBidi ? { hasBidiControls: true } : {}),
};
}
export function summarizeStoredCheckpoint(cp, memo, disclose) {
let verdict = memo.get(cp);
if (verdict === undefined) {
verdict = judgeCheckpointRow(cp);
memo.set(cp, verdict);
}
return summarizeCheckpoint(cp, disclose, verdict);
}
export function resolveDeclaredFidelity(store, storeName) {
const declared = store?.fidelity;
if (declared === undefined)
return "json";
if (declared === "structured-clone" || declared === "json")
return declared;
const e = new Error(`${storeName}.fidelity declares ${JSON.stringify(declared)} — not a recognized StoreFidelity ` +
`("structured-clone" | "json"). Fix the declaration; an unparseable fidelity cannot be folded to either arm.`);
e.code = "config.store_fidelity_invalid";
throw e;
}
export function resolveCheckpointStore(spec, deps) {
if (Object.is(spec.checkpointStore, null))
throw retiredCheckpointStoreNull();
if (spec.checkpointStore === "disabled")
return undefined;
if (spec.checkpointStore !== undefined) {
const refused = checkpointStoreIncomplete("TaskSpec.checkpointStore", spec.checkpointStore);
if (refused !== undefined)
throw refused;
return spec.checkpointStore;
}
if (deps.checkpointStore !== undefined) {
const refused = checkpointStoreIncomplete("RunnerDeps.checkpointStore", deps.checkpointStore);
if (refused !== undefined)
throw refused;
}
return deps.checkpointStore;
}
const REQUIRED_STORE_MEMBERS = [
{ carried: (store) => typeof store?.recordExecutionOutcome === "function", lacks: "does not carry the `recordExecutionOutcome` verb", cost: "the execution-outcome record (recordExecutionOutcome, and reopen refusing a recorded row) — without it no reader can settle how a resumed approval was disposed" },
{ carried: (store) => typeof store?.reopen === "function", lacks: "does not carry the `reopen` verb", cost: "the claim's reversal (reopen) — without it a resume the engine claimed and then refused before its decided action was disposed would consume the approval" },
];
export function checkpointStoreIncomplete(seat, store) {
const read = store;
const missing = REQUIRED_STORE_MEMBERS.filter((m) => !m.carried(read));
if (missing.length === 0)
return undefined;
const ctor = read?.constructor?.name;
const name = typeof ctor === "string" && ctor.length > 0 && ctor !== "Object" ? ` (${ctor})` : "";
const e = new Error(`${seat}: the wired CheckpointStore${name} ${missing.map((m) => m.lacks).join(" and ")} — ${missing.map((m) => m.cost).join("; ")}. ` +
"Each is a required member of the store contract, so the run is refused here. Implement it (the in-tree stores and the " +
"store-contract kit are the reference).");
e.code = "config.invalid_checkpoint_store";
return e;
}
export function retiredCheckpointStoreNull() {
const e = new Error('TaskSpec.checkpointStore: null is not a value any more — write checkpointStore: "disabled" to run without a ' +
"checkpoint store (the per-run durable off switch), or leave the field unset to use the deployment's store.");
e.code = "config.invalid_checkpoint_store";
return e;
}
export function winnerFromOutcome(outcome) {
if (outcome.gate === "plan_review" || outcome.gate === "dry_run_review") {
const editedPlan = outcome.gate === "plan_review" ? outcome.editedPlan : undefined;
return {
boundCallId: `gate:${outcome.gate}`,
decision: outcome.decision,
...(editedPlan !== undefined ? { updatedInput: editedPlan } : {}),
...(outcome.reason !== undefined ? { reason: outcome.reason } : {}),
...(outcome.gate === "plan_review" && outcome.permissionMode !== undefined ? { permissionMode: outcome.permissionMode } : {}),
...(outcome.gate === "plan_review" && outcome.gateOutcome !== undefined ? { gateOutcome: outcome.gateOutcome } : {}),
};
}
if (outcome.gate !== "policy_ask")
return undefined;
return {
boundCallId: outcome.boundCallId,
decision: outcome.decision,
...(outcome.updatedInput === undefined ? {} : { updatedInput: outcome.updatedInput }),
...(outcome.answer === undefined ? {} : { answer: outcome.answer }),
...(outcome.gateOutcome === undefined ? {} : { gateOutcome: outcome.gateOutcome }),
...(outcome.reason === undefined ? {} : { reason: outcome.reason }),
...(outcome.feedback === undefined ? {} : { feedback: outcome.feedback }),
};
}
export function validatePendingSteer(steer) {
if (steer === null || typeof steer !== "object") {
throw new CheckpointError("steering.invalid_content", `steering entry must be an object carrying text/trusted (got ${steer === null ? "null" : typeof steer})`);
}
const allowed = new Set(PENDING_STEER_FROZEN_FIELDS.filter((f) => f !== "seq"));
for (const key of Object.keys(steer)) {
if (!allowed.has(key)) {
throw new CheckpointError("steering.invalid_content", `unknown steering field "${key}" — the persisted entry shape is frozen (${[...allowed].join(", ")}); ` +
`a field this worker does not know would be dropped silently on the parked leg`);
}
}
const text = steer.text;
const trusted = steer.trusted;
const actor = steer.actor;
const inputId = steer.inputId;
const priority = steer.priority;
const runOrigin = steer.runOrigin;
const reply = steer.reply;
const source = steer.source;
if (typeof text !== "string") {
throw new CheckpointError("steering.invalid_content", "steering text must be a string");
}
if (typeof trusted !== "boolean") {
throw new CheckpointError("steering.invalid_content", "steering trusted must be a boolean stated by the caller");
}
if (inputId !== undefined && typeof inputId !== "string") {
throw new CheckpointError("steering.invalid_content", "steering inputId must be a string when supplied");
}
if (priority !== undefined && priority !== "now" && priority !== "next" && priority !== "later") {
throw new CheckpointError("steering.invalid_content", `steering priority "${typeof priority === "string" ? priority : priority === null ? "null" : typeof priority}" is outside the injection-priority domain ("now", "next", "later")`);
}
if (runOrigin !== undefined && !isRunOrigin(runOrigin)) {
throw new CheckpointError("steering.invalid_content", `steering runOrigin ${describeRejectedValue(runOrigin)} is not a run origin (${RUN_ORIGINS.map((w) => JSON.stringify(w)).join(" | ")}) — omit it when the deployment's scheduler did not hand this input`);
}
if (source !== undefined && source !== "steer" && source !== "system") {
throw new CheckpointError("steering.invalid_content", `steering source ${describeRejectedValue(source)} is not "steer" or "system"`);
}
const actorTwin = actor === undefined ? undefined : captureActorAssertion(actor);
const replyTwin = reply === undefined ? undefined : capturePendingSteerReply(reply);
if (replyTwin !== undefined && priority !== "later") {
throw new CheckpointError("steering.invalid_content", 'a steering reply rides only an entry whose priority is "later"');
}
if (inputId !== undefined && (inputId === "" || inputId.length > MAX_STEER_INPUT_ID_CHARS)) {
throw new CheckpointError("steering.invalid_content", `steering inputId must be a non-empty string of at most ${MAX_STEER_INPUT_ID_CHARS} characters`);
}
const defect = steeringTextDefect(text);
if (defect === "break_out_tag") {
throw new CheckpointError("steering.invalid_content", "steering text must not contain a system-reminder break-out tag");
}
if (defect === "control_chars") {
throw new CheckpointError("steering.invalid_content", "steering text must not contain control characters");
}
if (defect === "too_long") {
throw new CheckpointError("steering.invalid_content", `steering text must be at most ${MAX_PENDING_STEER_CHARS} characters (got ${text.length})`);
}
return {
text,
trusted,
...(actorTwin !== undefined ? { actor: actorTwin } : {}),
inputId: inputId ?? uuidv7(),
...(priority !== undefined ? { priority: priority } : {}),
...(runOrigin !== undefined ? { runOrigin } : {}),
...(replyTwin !== undefined ? { reply: replyTwin } : {}),
...(source !== undefined ? { source } : {}),
};
}
function capturePendingSteerReply(reply) {
if (reply === null || typeof reply !== "object") {
throw new CheckpointError("steering.invalid_content", `steering reply must be an object carrying text/by (got ${reply === null ? "null" : typeof reply})`);
}
const stray = strayMembersOf(reply, PENDING_STEER_REPLY_WORDS, PENDING_STEER_REPLY_FROZEN_FIELDS);
if (stray !== undefined)
throw new CheckpointError("steering.invalid_content", stray.sentence);
const supplied = reply;
const text = supplied.text;
const by = supplied.by;
const entered = supplied.entered;
for (const [field, value] of [
["text", text],
["entered", entered],
]) {
if (field === "entered" && value === undefined)
continue;
if (typeof value !== "string" || isBlankInput(value)) {
throw new CheckpointError("steering.invalid_content", `steering reply.${field} must be a non-empty string`);
}
if (steeringTextDefect(value) !== undefined) {
throw new CheckpointError("steering.invalid_content", `steering reply.${field} must not contain control characters or a system-reminder break-out tag, and must be at most ${MAX_PENDING_STEER_CHARS} characters`);
}
}
if (typeof by !== "string" || by === "" || by.length > MAX_ACTOR_FIELD_CHARS || STEERING_CONTROL_CHARS_RE.test(by)) {
throw new CheckpointError("steering.invalid_content", `steering reply.by must name the registration that answered (a non-empty string of at most ${MAX_ACTOR_FIELD_CHARS} characters, no control characters)`);
}
return { text: text, by, ...(entered !== undefined ? { entered: entered } : {}) };
}
export const MAX_ACTOR_FIELD_CHARS = 256;
export const MAX_STEER_INPUT_ID_CHARS = 128;
export const ACTOR_ASSERTION_FROZEN_FIELDS = Object.freeze(["id", "hostAsserted", "issuer"]);
function captureActorAssertion(actor) {
if (actor === null || typeof actor !== "object") {
throw new CheckpointError("steering.invalid_content", `actor must be an object carrying the attribution fields (got ${actor === null ? "null" : typeof actor})`);
}
const supplied = actor;
const allowed = new Set(ACTOR_ASSERTION_FROZEN_FIELDS);
for (const key of Object.keys(actor)) {
if (!allowed.has(key)) {
throw new CheckpointError("steering.invalid_content", `unknown actor field "${key}" — the persisted actor shape is frozen (${[...allowed].join(", ")})`);
}
}
const id = supplied.id;
const hostAsserted = supplied.hostAsserted;
const issuer = supplied.issuer;
if (typeof id !== "string" || id === "" || id.length > MAX_ACTOR_FIELD_CHARS) {
throw new CheckpointError("steering.invalid_content", `actor.id must be a non-empty namespaced string of at most ${MAX_ACTOR_FIELD_CHARS} characters (e.g. "slack:U123")`);
}
if (typeof hostAsserted !== "boolean") {
throw new CheckpointError("steering.invalid_content", "actor.hostAsserted must be a boolean stated by the host");
}
if (issuer !== undefined && (typeof issuer !== "string" || issuer === "" || issuer.length > MAX_ACTOR_FIELD_CHARS)) {
throw new CheckpointError("steering.invalid_content", `actor.issuer must be a non-empty string of at most ${MAX_ACTOR_FIELD_CHARS} characters`);
}
for (const [field, value] of [
["id", id],
["issuer", issuer],
]) {
if (value === undefined)
continue;
if (sanitizeUntrustedText(value) !== value || STEERING_CONTROL_CHARS_RE.test(value)) {
throw new CheckpointError("steering.invalid_content", `actor.${field} must not contain control characters or a system-reminder break-out tag`);
}
}
return { id, hostAsserted, ...(issuer !== undefined ? { issuer } : {}) };
}
export function readPendingSteerQueue(state) {
const retired = retiredSteerSeatRefusal(state);
if (retired !== undefined)
throw retired;
return [...(state.pendingSteerQueue ?? [])].sort((a, b) => a.seq - b.seq);
}
export function judgeParkedSteerRepeat(queue, entry) {
const collision = queue.find((e) => e.inputId === entry.inputId);
if (collision === undefined)
return undefined;
const refusal = steerReplayRefusal(collision, entry, { seat: "parked", inputId: entry.inputId });
if (refusal !== undefined)
throw new CheckpointError("steering.duplicate_input_id", refusal.message, refusal.detail);
return collision;
}
export function appendPendingSteer(state, entry) {
const current = readPendingSteerQueue(state);
if (judgeParkedSteerRepeat(current, entry) !== undefined)
return current;
const nextSeq = current.reduce((max, e) => Math.max(max, e.seq), 0) + 1;
const next = [...current, { ...entry, seq: nextSeq }];
const bytes = Buffer.byteLength(JSON.stringify({ pendingSteerQueue: next }), "utf8");
if (bytes > PENDING_STEER_QUEUE_BYTE_BUDGET_BYTES) {
throw new CheckpointError("steering.queue_full", `the parked steering queue would serialize to ${bytes} bytes (max ${PENDING_STEER_QUEUE_BYTE_BUDGET_BYTES}) — ` +
`deliver or remove a parked steer before adding another`);
}
return next;
}
export function checkpointRowMatches(cp, scope, status) {
return cp !== undefined && cp.scope === scope && cp.status === status;
}
const IN_MEMORY_CHECKPOINT_STORE_OPTION_KEYS = optionKeys()({ disclose: 0, sessionHeadOf: 0, holderIsCurrent: 0, retention: 0 });
export class InMemoryCheckpointStore {
retention;
durability = "process-local";
fidelity = "structured-clone";
cps = new Map();
rowVerdicts = new WeakMap();
fault = null;
disclose;
holderIsCurrent;
constructor(options) {
const opts = receiveOptions(options, "InMemoryCheckpointStore", IN_MEMORY_CHECKPOINT_STORE_OPTION_KEYS);
this.retention = readRetentionDeclaration("InMemoryCheckpointStore.retention", opts.retention);
this.disclose = opts.disclose;
this.holderIsCurrent = readHolderJudge("InMemoryCheckpointStore.holderIsCurrent", opts.holderIsCurrent);
if (this.holderIsCurrent !== undefined)
this.fence = Object.freeze({ holder: "writes" });
const headOf = opts.sessionHeadOf;
if (headOf !== undefined) {
const remove = (token, row) => this.cps.get(token) === row && this.cps.delete(token);
this.deleteSessionCheckpoints = async (sessionId, guard) => deleteSessionRowsAtStart(this.cps, ownerSessionRowsDelete(sessionId, guard, headOf), remove);
this.deleteUnreadableSessionCheckpoints = async (sessionId) => deleteSessionRowsAtStart(this.cps, unreadableSessionRowsDelete(sessionId, headOf), remove);
}
}
async put(token, cp, opts) {
if (!holderJudgedCurrent(opts?.holder, this.holderIsCurrent, "checkpoint"))
throw holderSupersededError("put");
if (this.cps.has(token)) {
throw new CheckpointError("checkpoint.already_exists", `checkpoint token already exists`);
}
this.cps.set(token, structuredClone(cp));
}
async get(token) {
if (!this.cps.has(token))
return null;
const cp = this.cps.get(token), refused = storedCheckpointRowRefusal(token, cp);
if (refused !== undefined)
throw refused;
return structuredClone(cp);
}
claimLossFrom(cp, scope) {
if (cp === undefined || cp.scope !== scope)
return { claimed: false, current: { status: "absent" } };
return {
claimed: false,
current: {
status: cp.status,
rev: checkpointRevOf(cp),
...(memberPresent(cp, "resolvedOutcome") ? { resolvedOutcome: structuredClone(cp.resolvedOutcome) } : {}),
},
};
}
claimResolveCore(token, scope, outcome, expect) {
const cp = this.cps.get(token);
if (!checkpointRowMatches(cp, scope, "pending")) {
return this.claimLossFrom(cp, scope);
}
if (!checkpointOccMatches(cp, expect)) {
return this.claimLossFrom(cp, scope);
}
if (!checkpointHolderMatches(expect, this.holderIsCurrent)) {
return this.claimLossFrom(cp, scope);
}
const winner = winnerFromOutcome(outcome);
const winnerClone = winner ? structuredClone(winner) : undefined;
cp.status = "resolved";
cp.rev = checkpointRevOf(cp) + 1;
if (winnerClone)
cp.resolvedOutcome = winnerClone;
delete cp.reopenReason;
return { claimed: true };
}
claimExpireCore(token, scope, holder) {
const cp = this.cps.get(token);
if (!checkpointRowMatches(cp, scope, "pending")) {
return this.claimLossFrom(cp, scope);
}
if (!holderJudgedCurrent(holder, this.holderIsCurrent, "checkpoint")) {
return this.claimLossFrom(cp, scope);
}
cp.status = "expired";
return { claimed: true };
}
async resolve(token, scope, outcome, expect) {
if (this.fault === "resolve-before-commit") {
this.fault = null;
throw new Error("injected fault: resolve before commit");
}
if (!checkpointRowMatches(this.cps.get(token), scope, "pending")) {
return false;
}
const out = this.claimResolveCore(token, scope, outcome, expect);
if (out.claimed && this.fault === "resolve-after-commit") {
this.fault = null;
throw new Error("injected fault: resolve after commit");
}
return out.claimed;
}
async claimTerminal(token, scope, intent) {
if (this.fault === "claim-before-commit" || (intent.kind === "resolve" && this.fault === "resolve-before-commit")) {
const name = this.fault === "claim-before-commit" ? "claim" : "resolve";
this.fault = null;
throw new Error(`injected fault: ${name} before commit`);
}
const out = intent.kind === "resolve" ? this.claimResolveCore(token, scope, intent.outcome, intent.expect) : this.claimExpireCore(token, scope, intent.expect?.holder);
if (out.claimed && (this.fault === "claim-after-commit" || (intent.kind === "resolve" && this.fault === "resolve-after-commit"))) {
const name = this.fault === "claim-after-commit" ? "claim" : "resolve";
this.fault = null;
throw new Error(`injected fault: ${name} after commit`);
}
return out;
}
async recordExecutionOutcome(token, scope, gate) {
const cp = this.cps.get(token);
const disposition = executionRecordDisposition(cp, scope, gate);
if (disposition === "conflict")
throw new ExecutionOutcomeConflictError(cp.executionOutcome, gate);
if (disposition !== "commit")
return disposition;
const record = structuredClone(gate);
cp.executionOutcome = record;
cp.executionAtMs = Date.now();
return "recorded";
}
async reopen(token, scope, reason, expect) {
const cp = this.cps.get(token);
if (!checkpointRowMatches(cp, scope, "resolved") || !checkpointOccMatches(cp, expect) || checkpointExecutionRecorded(cp)) {
return false;
}
cp.status = "pending";
cp.rev = checkpointRevOf(cp) + 1;
cp.reopenReason = reason;
return true;
}
async setPendingSteer(token, scope, steer, opts) {
const clean = validatePendingSteer(steer);
if (!holderJudgedCurrent(opts?.holder, this.holderIsCurrent, "checkpoint"))
throw holderSupersededError("setPendingSteer");
const cp = this.cps.get(token);
if (!checkpointRowMatches(cp, scope, "pending")) {
return false;
}
const held = (cp.state.pendingSteerQueue ?? []).length;
const next = appendPendingSteer(cp.state, clean);
if (next.length > held)
cp.rev = checkpointRevOf(cp) + 1;
cp.state.pendingSteerQueue = next;
return true;
}
async expire(token, scope, opts) {
if (!checkpointRowMatches(this.cps.get(token), scope, "pending")) {
return false;
}
return this.claimExpireCore(token, scope, opts?.holder).claimed;
}
async reap(scope, cutoff) {
let n = 0;
for (const cp of this.cps.values()) {
if (cp.scope === scope && cp.status === "pending" && checkpointDeadlinePassed(cp.deadline, cutoff)) {
cp.status = "expired";
n++;
}
}
return n;
}
async listByScope(scope) {
const out = [];
for (const cp of this.cps.values()) {
if (cp.scope === scope && cp.status === "pending")
out.push(summarizeStoredCheckpoint(cp, this.rowVerdicts, this.disclose));
}
return out;
}
async listScopes() {
const out = new Set();
for (const cp of this.cps.values())
if (cp.status === "pending")
out.add(cp.scope);
return [...out];
}
async listOverdue(query) {
return selectOverduePage(this.cps.entries(), readCheckpointOverdueQuery(query), (cp) => summarizeStoredCheckpoint(cp, this.rowVerdicts, this.disclose), this.disclose);
}
async listBySession(query) {
return selectSessionPage(this.cps.entries(), readCheckpointSessionQuery(query), (cp) => structuredClone(cp), this.disclose);
}
async rekeyIdentity(input) {
const { mode, ...map } = readIdentityRekeyInput("CheckpointStore.rekeyIdentity", input);
const verdicts = [...this.cps].map(([token, cp]) => {
const verdict = rekeyCheckpointRow(cp, map, this.fidelity);
if (mode === "leave" && verdict.kind === "rekeyed")
this.cps.set(token, verdict.row);
return verdict;
});
return oneStepRekeyAnswerOf(mode, verdicts);
}
testInjectFault(mode) {
this.fault = mode;
}
get size() {
return this.cps.size;
}
}