UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

100 lines (99 loc) • 6.48 kB
import { CheckpointError, judgeParkedSteerRepeat, readPendingSteerQueue, validatePendingSteer } from "../checkpoint-store.js"; import { checkpointRowResumeRefusal } from "../checkpoint-row-verdict.js"; import { chainRefusalOfThrown } from "./chain-refusal-throw.js"; import { refuseResumeDoors } from "./prepare-config-doors.js"; import { readResumeConfig, resolveResumeStore, snapshotResumeInternals } from "../resume-config-judge.js"; import { runExpiredDuty } from "./expire-settle.js"; import { describeSuppliedValue } from "./decide-continuation.js"; import { withSeatTaken } from "../swappable-deps.js"; import { PAUSE_REGISTRY } from "../pause-registry.js"; import { admitLegFrameSeat } from "./leg-frame.js"; import { enterConfigDoor } from "../config-refusal-input.js"; import { adoptHostPromise } from "../host-promise.js"; import { revivalParentConstraints } from "./constraint-layers.js"; const DECIDE_ENTRY_BY_RESUME_GATE = { policy_ask: "a `policy_ask` outcome (decision allow/deny bound to the pending tool call)", dry_run_review: "a `dry_run_review` outcome (decision approve/reject)", plan_review: "a `plan_review` outcome (decision approve/edit/reject)", resource_limit: 'a `resource_limit` outcome (decision "continue")', }; export async function resumeAdmission(input) { const { token, outcome, taskConfig, runner, sessions, parentConstraintRegistry, suspendedEnvReaps } = input; let internals = enterConfigDoor("deps", () => admitLegFrameSeat(input.internals, "resumeStream")); if (outcome === null || typeof outcome !== "object") { throw new CheckpointError("checkpoint.invalid_outcome", `resume outcome must be an object naming its gate (got ${outcome === null ? "null" : typeof outcome})`, { field: "outcome" }); } let config = readResumeConfig(taskConfig); config = withSeatTaken(config, () => runner.deps.models); internals = snapshotResumeInternals(internals); const store = resolveResumeStore(config, runner.deps); if (!store) { throw new CheckpointError("checkpoint.not_found", "no CheckpointStore wired — cannot resume (set RunnerDeps.checkpointStore or taskConfig.checkpointStore)"); } let cp = await store.get(token); if (!cp) { throw new CheckpointError("checkpoint.not_found", "no checkpoint found for the supplied token"); } if (cp.status !== "pending") { const live = await store.get(token); if (live?.status === "pending") { throw new CheckpointError("checkpoint.reopened_concurrently", "checkpoint changed concurrently (a resolve/reopen cycle landed between this resume's read of the row and its state check) — nothing was validated or executed; re-resume against the current state"); } if (live?.status === "expired") { await runExpiredDuty({ token, parentConstraintRegistry, suspendedEnvReaps, destroyLabel: "expired-row env destroy (resume refused)", onDestroyError: (err, sessionId) => runner.deps.onError?.(err, { phase: "config", sessionId }), }); } throw new CheckpointError("checkpoint.already_resolved", `checkpoint is ${describeSuppliedValue(live?.status ?? cp.status)} — the token is consumed, so this resume was neither validated nor executed (idempotent); a different outcome cannot redeem it`); } const rowRefusal = checkpointRowResumeRefusal(cp); if (rowRefusal !== undefined && !rowRefusal.chainArm) throw rowRefusal.refusal; let wakeMessage; const outcomeGate = outcome.gate; const resumeSignal = config.signal; let suppliedMessage; config = refuseResumeDoors(config, runner.deps, sessions, internals, cp.resourceLedger); const parkedSteers = readPendingSteerQueue(cp.state); if (outcomeGate === "wake") { suppliedMessage = outcome.message; const gk = cp.gate.kind; if (gk !== "task_done") { throw new CheckpointError("wake.gate_pending", `cannot wake: this checkpoint awaits a pending gate decision (gate "${gk}") — wake is not a decision ` + `channel; resume it with ${DECIDE_ENTRY_BY_RESUME_GATE[PAUSE_REGISTRY[gk].resume]} instead`); } if (suppliedMessage !== undefined) { wakeMessage = validatePendingSteer(suppliedMessage); if (wakeMessage.reply !== undefined) throw new CheckpointError("steering.invalid_content", "a wake message carries no reply — the answer an extension gives an input is the engine's to record when it takes the input"); if (judgeParkedSteerRepeat(parkedSteers, wakeMessage) !== undefined) wakeMessage = undefined; } else if (parkedSteers.length === 0) { throw new CheckpointError("wake.nothing_to_deliver", "cannot wake: no message was supplied and the checkpoint holds no parked pendingSteer — an empty " + "wake would burn the checkpoint on a blank continuation; supply `message` or park a steer first"); } } const handed = internals?.inheritedGate?.parentConstraints; const rootPolicy = internals?.rootPolicy ?? undefined; const record = cp.state.inheritedGate; let parentConstraints; let chainRefusal = rowRefusal?.refusal; let rootLayerUnrestated = false; if (chainRefusal === undefined) { try { const onRootLayerUnrestated = () => void (rootLayerUnrestated = true); const picked = revivalParentConstraints({ token, record, handed, registry: parentConstraintRegistry, deps: runner.deps, leg: config, rootPolicy, onRootLayerUnrestated }); const pickedAsync = adoptHostPromise(picked); parentConstraints = pickedAsync !== undefined ? await pickedAsync : picked; } catch (e) { chainRefusal = chainRefusalOfThrown(e, (what) => new CheckpointError("resume.parent_constraint_unrebuildable", `the inherited constraint chain could not be rebuilt (${what} was thrown); rejected pre-CAS (the checkpoint stays pending)`)); } } if (parentConstraints !== undefined && parentConstraints !== internals?.inheritedGate?.parentConstraints) internals = { ...(internals ?? {}), inheritedGate: { ...(internals?.inheritedGate ?? {}), parentConstraints } }; return await input.next({ config, internals, store, cp, outcomeGate, resumeSignal, wakeMessage, chainRefusal, rootLayerUnrestated }); }