@sema-agent/core
Version:
Stateless, task-oriented AI agent core
155 lines (154 loc) • 10.6 kB
JavaScript
import { declaredSuspend, frozenHandleCopy, isRemoteExecutionEnv, missingRestoreSurface, pathsAreHostLocal, placementHonored, placementTargetOf, RemoteExecutionError } from "../remote-env.js";
import { thrownText } from "../thrown-value.js";
import { connectAtRestoreSeat, establishAtRestoreSeat } from "./restore-seat.js";
import { deviceMoveRefusal, devicesDisprove, settleOwnTarget } from "./placement-fence.js";
import { remoteEnvFailureNote, restoreWorkspaceWithRetry } from "./remote-env-retry.js";
import { rebaseWorkspacePathAcross } from "./workspace-path.js";
import { foldRedundantPathSegments } from "../unc-spelling.js";
import { envErrorDetail } from "../../tools/fs/env-error-detail.js";
export { remoteEnvFailureNote, restoreWorkspaceWithRetry } from "./remote-env-retry.js";
async function canonicalInEnv(env, p, signal) {
try {
const r = await env.canonicalPath(p, signal);
return r.ok ? r.value : undefined;
}
catch {
return undefined;
}
}
function sameRootByLetters(a, b) {
return a === b || (a.startsWith("/") && b.startsWith("/") && foldRedundantPathSegments(a) === foldRedundantPathSegments(b));
}
export async function prepareWorkspaceRestore(input) {
const { ownedEnv, deps, spec, resume, abortController, sessionId } = input;
let taskRootPath = input.taskRootInitial;
let restoredRootRebase;
const rebaseRestoredPath = (p) => restoredRootRebase === undefined ? p : rebaseWorkspacePathAcross(p, restoredRootRebase.from, restoredRootRebase.to);
const restoreSignal = spec.signal ? AbortSignal.any([abortController.signal, spec.signal]) : abortController.signal;
const rowHandle = resume?.workspaceHandle !== undefined ? frozenHandleCopy(resume.workspaceHandle) : undefined;
if (rowHandle === undefined && ownedEnv !== undefined && isRemoteExecutionEnv(ownedEnv)) {
await connectAtRestoreSeat(ownedEnv, restoreSignal);
}
if (rowHandle !== undefined && resume !== undefined) {
const failResume = (message, cause, note, disowns) => {
const e = new Error(message, cause ? { cause } : undefined);
e.code = "resume.env_failed";
if (note !== undefined)
e.remoteEnvFailure = note;
if (disowns === true)
e.envDisowned = true;
throw e;
};
const handle = rowHandle;
const refuseIdentityMismatch = (resumedHandle) => {
if (resumedHandle.provider !== handle.provider) {
failResume(`resume workspace identity mismatch: the checkpoint records provider "${handle.provider}" but the resumed env reports "${resumedHandle.provider}" — refusing to continue a workspace on a different backend (wire the factory to rebuild the checkpointed lane and re-resume)`, undefined, undefined, true);
}
const reported = placementTargetOf(resumedHandle);
if (!placementHonored(input.placementFence, reported)) {
throw Object.assign(deviceMoveRefusal("resume.env_failed", input.placementFence?.deviceId, reported?.deviceId), devicesDisprove(handle.deviceId, reported?.deviceId) ? { envDisowned: true } : {});
}
};
if (ownedEnv === undefined || !isRemoteExecutionEnv(ownedEnv)) {
failResume("resume needs a RemoteExecutionEnv from executionEnvFactory to restore the workspace snapshot");
}
else if (handle.snapshotId === undefined) {
if (handle.restoreMode !== "park_only" && declaredSuspend(ownedEnv) !== false) {
failResume("checkpoint workspaceHandle has no snapshotId and is not a park_only handle, but the resumed env is suspendable — refusing to resume on a possibly-unrestored workspace (corrupt checkpoint?)");
}
refuseIdentityMismatch(ownedEnv.workspaceHandle());
await connectAtRestoreSeat(ownedEnv, restoreSignal);
const parkedRoot = handle.mountPath;
if (parkedRoot) {
const standsAt = (() => {
try {
return ownedEnv.workspaceHandle().mountPath;
}
catch {
return undefined;
}
})();
if (typeof standsAt !== "string" || !sameRootByLetters(standsAt, parkedRoot)) {
const [want, got] = typeof standsAt === "string" ? [await canonicalInEnv(ownedEnv, parkedRoot, restoreSignal), await canonicalInEnv(ownedEnv, standsAt, restoreSignal)] : [undefined, undefined];
if (want === undefined || got === undefined || want !== got) {
const resolvedBoth = want !== undefined && got !== undefined;
failResume(`resume workspace root mismatch: the checkpoint records the parked workspace at "${parkedRoot}" but the resumed env stands at ${typeof standsAt === "string" ? `"${standsAt}"` : "no root it can report"}${resolvedBoth ? "" : " (the env could not resolve both to one directory)"} — refusing to run the resumed work in another directory (the factory must go back to ExecutionEnvFactoryContext.priorHandle, or throw)`, undefined, undefined, resolvedBoth);
}
}
if (parkedRoot !== taskRootPath)
taskRootPath = parkedRoot;
}
}
else {
const missingHere = missingRestoreSurface(ownedEnv);
if (missingHere.length > 0) {
failResume(`the resumed execution env cannot restore a workspace snapshot: its adapter does not implement ${missingHere.join(" or ")}. The checkpoint holds snapshot "${handle.snapshotId}" — wire an adapter that implements the full RemoteExecutionEnv restore surface and re-resume.`);
}
refuseIdentityMismatch(ownedEnv.workspaceHandle());
const snapshotId = handle.snapshotId;
let restoreAttempts = 0;
const restored = await establishAtRestoreSeat("resumeVM", restoreSignal, async () => {
const settled = await restoreWorkspaceWithRetry(ownedEnv, snapshotId, {
abortSignal: restoreSignal,
priorHandle: handle,
});
restoreAttempts = settled.attempts;
return settled.outcome;
});
if (!restored.ok) {
failResume(`resumeVM failed after ${restoreAttempts} attempt(s) (${restored.error.code}): ${envErrorDetail(restored.error.message)}`, restored.error, remoteEnvFailureNote("resumeVM", restored.error, restoreAttempts));
}
else {
refuseIdentityMismatch(restored.value);
let checkpointedCanonical;
let sameRootUnderAlias = false;
if (restored.value.mountPath !== handle.mountPath) {
checkpointedCanonical = await canonicalInEnv(ownedEnv, handle.mountPath, restoreSignal);
const restoredCanonical = await canonicalInEnv(ownedEnv, restored.value.mountPath, restoreSignal);
sameRootUnderAlias =
checkpointedCanonical !== undefined && restoredCanonical !== undefined && checkpointedCanonical === restoredCanonical;
}
if (restored.value.mountPath !== handle.mountPath && !sameRootUnderAlias) {
if (resume.executesApprovedAction === true) {
failResume(`resumeVM workspace-root divergence with a pending approved action: checkpointed mountPath "${handle.mountPath}" but the restored handle reports "${restored.value.mountPath}" — the approved args are bound to the checkpointed root; refusing to execute them against a moved workspace (adapter should honor priorHandle)`);
}
try {
deps.onError?.(new Error(`resumeVM workspace-root divergence: checkpointed mountPath "${handle.mountPath}" but the restored handle reports "${restored.value.mountPath}" — the resumed task follows the restored root`), { phase: "config", sessionId });
}
catch {
}
}
if (restored.value.mountPath && restored.value.mountPath !== taskRootPath) {
taskRootPath = restored.value.mountPath;
}
if (restored.value.mountPath && restored.value.mountPath !== handle.mountPath && !sameRootUnderAlias) {
const from = checkpointedCanonical !== undefined && checkpointedCanonical !== handle.mountPath
? [handle.mountPath, checkpointedCanonical]
: [handle.mountPath];
restoredRootRebase = { from, to: restored.value.mountPath };
try {
deps.onError?.(new Error(from.length > 1
? `resumeVM workspace-root rebase accepts both spellings of the checkpointed root (${from.map((f) => `"${f}"`).join(" and ")}) when migrating persisted paths to "${restored.value.mountPath}"`
: `resumeVM workspace-root rebase is spelling-exact: it matches the checkpointed root "${handle.mountPath}" only, so persisted paths recorded under an equivalent alias of it are NOT migrated to "${restored.value.mountPath}" and stay as written`), { phase: "config", sessionId });
}
catch {
}
}
}
const init = await Promise.resolve()
.then(() => ownedEnv.postResumeInit())
.catch((thrown) => {
if (restoreSignal.aborted)
throw thrown;
return { ok: false, error: new RemoteExecutionError("unknown", `postResumeInit threw: ${thrownText(thrown)}`) };
});
if (!init.ok) {
failResume(`postResumeInit failed (${init.error.code}): ${envErrorDetail(init.error.message)}`, init.error, remoteEnvFailureNote("postResumeInit", init.error, 1), true);
}
}
}
const workspaceEnv = ownedEnv ?? deps.executionEnv;
const remote = workspaceEnv !== undefined && workspaceEnv !== null && !pathsAreHostLocal(workspaceEnv);
const ownTarget = settleOwnTarget(workspaceEnv ?? undefined, input.placementFence, rowHandle);
return { taskRootFinal: taskRootPath, rebaseRestoredPath, remote, ownTarget };
}