@sema-agent/core
Version:
Stateless, task-oriented AI agent core
181 lines (180 loc) • 10.9 kB
JavaScript
import { hasBackgroundShell, sweepBackgroundShells, sweepRunBoundaryBackgroundShells } from "../background-shell.js";
import { debitLedger, mintCheckpointId, mintCheckpointToken, } from "../checkpoint-store.js";
import { defaultTaskRegistry } from "../task-registry.js";
import { DEFAULT_RESOURCE_TTL_MS, humanReviewSnapshot, publishCommittedSuspend, sanitizedTtlMs, USAGE_WINDOW_REAP_MARGIN_MS } from "./park-commit.js";
import { remoteEnvFailureNote } from "./remote-env-retry.js";
import { isolationScopeRecordOf } from "../isolation-scope.js";
import { CLAMP_SET } from "../child-clamp-seats.js";
import { textContentHashOf } from "../canonical-json.js";
import { reviewWithdrawalClause } from "../present-plan-tool.js";
export function prepareBoundaryParks(input) {
const { saga, spec, checkpointStore, checkpointScope, approvalParkNotResumable, abortController, harness, session, sessions, sessionId, askSource, deps, priorLedger, maxSlices, maxSuspends, resourceTotal, priorSuspendCount, suspendChainBase, humanReviewRef, liveSpendRef, now, pausedRef, remoteEnvFailures, resourceSuspendEligible, durableSuspendInfraReady, suspendTargetGap } = input;
if (saga === undefined)
return { suspendForResource: undefined, suspendForPlatformLimit: undefined, suspendForReview: undefined };
const { inFlightSpendMicroUsd, serializeCheckpointState, commitSuspendSaga, suspendLoopCapHit, suspendableEnv, parkOnlyRemoteEnv, parkOnlyHandle, syncBeforePark } = saga;
const mintResourceSuspend = async (reason, sliceSpend, hint) => {
const rs = spec.resourceSuspend;
if (!checkpointStore)
return { tag: "not_written", reason: "no CheckpointStore is wired" };
const scope = rs?.scope ?? checkpointScope;
if (abortController.signal.aborted)
return { tag: "not_written", reason: "the run is being cancelled" };
if (suspendLoopCapHit(priorLedger?.sliceCount ?? 0, maxSlices, " (resource slice limit)"))
return { tag: "fatal", reason: "the resource slice limit (resourceSuspend.maxSlices) is reached" };
const leafId = await session.getLeafId();
if (!leafId)
return { tag: "not_written", reason: "the session has no committed leaf to resume from" };
if (abortController.signal.aborted)
return { tag: "not_written", reason: "the run is being cancelled" };
await syncBeforePark(abortController.signal);
if (abortController.signal.aborted)
return { tag: "not_written", reason: "the run is being cancelled" };
let remoteHandle;
if (suspendableEnv !== undefined) {
if (hasBackgroundShell(suspendableEnv))
await sweepBackgroundShells(suspendableEnv, defaultTaskRegistry);
const snap = await suspendableEnv.suspendVM({ abortSignal: abortController.signal });
if (!snap.ok) {
remoteEnvFailures.push(remoteEnvFailureNote("suspendVM", snap.error, 1));
deps.onError?.(new Error(`resource suspendVM failed (${snap.error.code}): ${snap.error.message}`, { cause: snap.error }), { phase: "config", sessionId });
return { tag: "not_written", reason: `the execution environment refused to suspend (${snap.error.code})` };
}
remoteHandle = { ...suspendableEnv.workspaceHandle(), snapshotId: snap.value };
}
else if (parkOnlyRemoteEnv !== undefined) {
if (hasBackgroundShell(parkOnlyRemoteEnv))
await sweepRunBoundaryBackgroundShells(parkOnlyRemoteEnv, defaultTaskRegistry, { task: spec.retainBackgroundProcesses === true });
remoteHandle = parkOnlyHandle(parkOnlyRemoteEnv);
}
const token = mintCheckpointToken();
const gate = { kind: "resource_limit", reason, ...(hint !== undefined ? { resumeAfterMs: hint.resumeAfterMs } : {}) };
const resourceLedgerOut = debitLedger(priorLedger, sliceSpend, resourceTotal);
const mintedAt = Date.now();
const cp = {
token,
checkpointId: mintCheckpointId(),
scope,
sessionId,
leafId,
gate,
pendingAction: { kind: "resource_limit", reason },
state: serializeCheckpointState(remoteHandle),
status: "pending",
createdAt: mintedAt,
deadline: mintedAt + Math.max(sanitizedTtlMs(rs?.ttlMs) ?? DEFAULT_RESOURCE_TTL_MS, hint !== undefined ? hint.resumeAfterMs + USAGE_WINDOW_REAP_MARGIN_MS : 0),
suspendCount: priorSuspendCount,
humanReview: humanReviewSnapshot(humanReviewRef),
resourceLedger: resourceLedgerOut,
...(spec.durableApproval !== undefined ? { durableApproval: { ...spec.durableApproval } } : approvalParkNotResumable === "host" ? { durableApproval: CLAMP_SET.durableApproval.value } : {}),
...(spec.principal ? { principal: spec.principal } : {}),
...isolationScopeRecordOf(spec),
};
const saga = await commitSuspendSaga(token, cp, suspendableEnv, remoteHandle);
if (saga.tag === "unknown" || saga.tag === "compensation_failed" || saga.tag === "superseded")
return { tag: "fatal", reason: saga.reason };
if (saga.tag !== "committed")
return { tag: "not_written", reason: saga.tag === "absent" && saga.reason !== undefined ? saga.reason : "the checkpoint was not written" };
publishCommittedSuspend({ pausedRef }, token, gate, scope, remoteHandle, cp, saga.writes);
try {
await sessions.pin?.(sessionId);
}
catch (pinErr) {
deps.onError?.(pinErr, { phase: "config", sessionId });
}
harness.requestStopAfterTurn();
return { tag: "committed" };
};
const suspendForResource = resourceSuspendEligible ? mintResourceSuspend : undefined;
const suspendForPlatformLimit = durableSuspendInfraReady ? mintResourceSuspend : undefined;
const parkSkipped = (why) => {
try {
deps.onError?.(new Error(`plan_review park skipped: ${why} (the plan-review request was dropped; the run continues without pausing)`), { phase: "config", sessionId });
}
catch {
}
return false;
};
const suspendForReview = checkpointStore && approvalParkNotResumable === undefined
? async ({ reason, requestedByCallId, presented, withdrawn }) => {
if (!checkpointStore)
return false;
if (abortController.signal.aborted)
return false;
if (suspendTargetGap !== undefined)
return parkSkipped(`the per-task execution env ${suspendTargetGap}, so its workspace could not be restored on resume`);
if (withdrawn !== undefined)
return parkSkipped(reviewWithdrawalClause(withdrawn));
if (suspendLoopCapHit(suspendChainBase(), maxSuspends, " for a plan_review (likely a resume/restart loop)."))
return false;
const leafId = await session.getLeafId();
if (!leafId)
return parkSkipped("no committed session leaf");
if (abortController.signal.aborted)
return false;
await syncBeforePark(abortController.signal);
if (abortController.signal.aborted)
return false;
let remoteHandle;
if (suspendableEnv !== undefined) {
if (hasBackgroundShell(suspendableEnv))
await sweepBackgroundShells(suspendableEnv, defaultTaskRegistry);
const snap = await suspendableEnv.suspendVM({ abortSignal: abortController.signal });
if (!snap.ok) {
remoteEnvFailures.push(remoteEnvFailureNote("suspendVM", snap.error, 1));
deps.onError?.(new Error(`plan_review suspendVM failed (${snap.error.code}): ${snap.error.message}`, { cause: snap.error }), { phase: "config", sessionId });
return false;
}
remoteHandle = { ...suspendableEnv.workspaceHandle(), snapshotId: snap.value };
}
else if (parkOnlyRemoteEnv !== undefined) {
if (hasBackgroundShell(parkOnlyRemoteEnv))
await sweepRunBoundaryBackgroundShells(parkOnlyRemoteEnv, defaultTaskRegistry, { task: spec.retainBackgroundProcesses === true });
remoteHandle = parkOnlyHandle(parkOnlyRemoteEnv);
}
const token = mintCheckpointToken();
const scope = checkpointScope;
const gate = { kind: "plan_review", reason: reason ?? `plan review requested` };
const reviewLedger = debitLedger(priorLedger, liveSpendRef.get?.() ?? { costMicroUsd: 0, tokens: 0, turns: 0, walltimeMs: 0 }, resourceTotal, { countSlice: false });
const mintedAt = Date.now();
const cp = {
token,
checkpointId: mintCheckpointId(),
scope,
sessionId,
leafId,
gate,
pendingAction: {
kind: "plan_review",
...(requestedByCallId !== undefined && requestedByCallId !== "" ? { requestedByCallId } : {}),
...(presented !== undefined ? { planContentHash: textContentHashOf(presented) } : {}),
},
state: serializeCheckpointState(remoteHandle, inFlightSpendMicroUsd()),
status: "pending",
createdAt: mintedAt,
suspendedAt: now(),
deadline: mintedAt + (sanitizedTtlMs(spec.durableApproval?.ttlMs) ?? DEFAULT_RESOURCE_TTL_MS),
suspendCount: suspendChainBase() + 1,
humanReview: humanReviewSnapshot(humanReviewRef),
resourceLedger: reviewLedger,
sourceSessionId: askSource.sourceSessionId,
...(spec.principal ? { principal: spec.principal } : {}),
...isolationScopeRecordOf(spec),
...(spec.durableApproval !== undefined ? { durableApproval: { ...spec.durableApproval } } : {}),
};
const committed = await commitSuspendSaga(token, cp, suspendableEnv, remoteHandle);
if (committed.tag !== "committed")
return false;
publishCommittedSuspend({ pausedRef }, token, gate, scope, remoteHandle, cp, committed.writes);
try {
await sessions.pin?.(sessionId);
}
catch (pinErr) {
deps.onError?.(pinErr, { phase: "config", sessionId });
}
abortController.abort();
void harness.abort();
return true;
}
: undefined;
return { suspendForResource, suspendForPlatformLimit, suspendForReview };
}