@sema-agent/core
Version:
Stateless, task-oriented AI agent core
150 lines (149 loc) • 10 kB
JavaScript
import { planFileHistoryRestore } from "../file-history-store.js";
import { ENV_PURPOSE_UNSUPPORTED, hasDestroy } from "../remote-env.js";
import { ABSOLUTE_HOST_PATH_MAX, isAbsoluteHostPath } from "@sema-agent/primitives";
import { readMember } from "../thrown-value.js";
import { readRestoreOptions, resolveDeploymentFileHistory, storeUnconfiguredRefusal } from "./file-history-request.js";
import { prepareExecutionEnv } from "./prepare-execution-env.js";
import { noBoundaryRefusal, refuseFailedPlan, refuseUnheldPlan, settleFileHistoryRestore } from "./file-history-restore.js";
import { adoptForkedFileHistory, unaddressedRewindRefusal } from "./prepare-file-history.js";
import { openSessionFiles } from "./session-files-open.js";
import { createRollbackStack } from "./rollback-stack.js";
import { assertStoreJudgesHolder } from "../checkpoint-generation.js";
import { acquireExistingSession, claimIdleSession, readOccupantExpectation, readPlainRequest, shownValue } from "./session-verb-doors.js";
import { settleTeardownLeg } from "./teardown-bounded.js";
import { settleBound } from "./continues-from.js";
import { syncAtRewindEnd } from "./workspace-sync.js";
import { recordedRootOf } from "../session-checkout.js";
import { canonicalOrSelf } from "./child-tree.js";
const REQUEST_KEYS = new Set(["sessionId", "to", "dryRun", "signal", "expect", "unplacedHistoryRecordedUnder", "cwd", "holder"]);
export async function rewindSessionFiles(seats, request) {
const req = screenRewindFilesRequest(request);
assertStoreJudgesHolder("session", "RunnerDeps.sessionStore", seats.sessions, req.holder, "host");
const { deps } = seats;
const { wiredSeat, fileHistoryStore, captureStore } = resolveDeploymentFileHistory(deps);
if (fileHistoryStore === undefined)
throw storeUnconfiguredRefusal(wiredSeat, req.to);
const release = await claimIdleSession(seats, req.sessionId, () => sessionBusyRefusal(req.sessionId, req.to));
try {
const session = await acquireExistingSession(seats.sessions, req.sessionId, "Runner.rewindFiles", "nothing was rewound", req.expect);
const report = (err) => {
try {
deps.onError?.(err, { phase: "config", sessionId: req.sessionId });
}
catch {
}
};
const rollback = createRollbackStack(report);
let envPhase;
try {
envPhase = await prepareExecutionEnv({ deps, spec: {}, internals: req.cwd !== undefined ? { requestedCwd: req.cwd } : undefined, resume: undefined, placementRootResolved: req.sessionId, sessionId: req.sessionId, forgetOnThrow: async () => { }, rollback, startsEnv: true, purpose: "rewind_files" });
}
catch (err) {
await rollback.unwindAll();
if (readMember(err, "code") === ENV_PURPOSE_UNSUPPORTED)
throw filesEnvUnsupportedRefusal(req.sessionId, req.to, err);
throw err;
}
rollback.commit();
const outcome = { moved: "none" };
try {
return await rewindOnEnv(req, envPhase.executionEnv, envPhase.handsEnabled, envPhase.taskRootInitial, { store: fileHistoryStore, captureStore, session: session.session, seats, readStates: seats.readStates, outcome });
}
catch (err) {
throw withVerbSettlement(err, outcome);
}
finally {
const moved = outcome.moved !== "none";
const owned = envPhase.ownedEnvSeat.current;
const destroying = owned !== undefined && hasDestroy(owned);
const bound = settleBound();
if (moved)
await syncAtRewindEnd(envPhase.executionEnv, destroying, { sessionId: req.sessionId, onNotice: deps.onNotice, boundMs: bound(destroying ? 2 : 1) });
if (owned !== undefined && hasDestroy(owned))
await settleTeardownLeg(() => owned.destroy(), "ownedEnv.destroy (rewindFiles)", report, bound(1));
}
}
finally {
release();
}
}
async function rewindOnEnv(req, env, handsEnabled, baseRoot, ctx) {
const opened = await openSessionFiles({
session: ctx.session,
sessionId: req.sessionId,
target: req.to,
tree: {
hands: handsEnabled ? { env, baseRoot } : undefined,
refusedAs: `Runner.rewindFiles: where session "${req.sessionId}"'s files stand cannot be resolved from its checkout (TaskSpec.workspace), so nothing was rewound to entry "${req.to}" — a rewind is never applied to the base checkout in place of the session's own tree; a session that works in its own tree is rewound while that checkout stands (before releaseSessionCheckout, its tree on disk).`,
sessions: ctx.seats.sessions,
},
history: { unaddressed: () => unaddressedRewindRefusal(req.sessionId, req.to) },
});
if (opened.kind === "no_hands")
throw filesEnvUnsupportedRefusal(req.sessionId, req.to);
if (opened.kind !== "opened")
throw noBoundaryRefusal(req.to, req.sessionId, req.dryRun);
const { row, ownScope, historyScope, historyRoot } = opened.history;
const at = { env, session: ctx.session, sessionId: req.sessionId, baseRoot };
const roots = { own: () => Promise.resolve(historyRoot), source: async (origin) => { const r = await recordedRootOf(at, origin); return r === undefined ? undefined : canonicalOrSelf(env, r); } };
if (ctx.captureStore !== undefined)
await adoptForkedFileHistory(ctx.captureStore, { origin: row.forkedFrom, originIncarnation: row.forkedFromIncarnation }, req.sessionId, ownScope, ctx.seats.deps.onError, roots);
const forkedSession = row.forkedFrom !== undefined && row.forkedFrom !== req.sessionId;
if (req.dryRun) {
const plan = await planFileHistoryRestore(ctx.store, { scope: historyScope, entryId: req.to, env, root: historyRoot, ...(req.signal !== undefined ? { signal: req.signal } : {}), ...(req.restoreOptions !== undefined ? { options: req.restoreOptions } : {}), ...(forkedSession ? { forkedSession: true } : {}) });
refuseUnheldPlan(plan, req.to, req.sessionId, "preview");
refuseFailedPlan(plan.restore, req.to, req.sessionId, "preview");
return { dryRun: true, preview: plan.diffStats };
}
const restore = await settleFileHistoryRestore({ store: ctx.store, sessionId: req.sessionId, scope: historyScope, target: req.to, before: false, env, root: historyRoot, signal: req.signal, readStates: ctx.readStates, options: req.restoreOptions, wholeOrNothing: false, ...(forkedSession ? { forkedSession: true } : {}), outcome: ctx.outcome });
return { dryRun: false, restore };
}
function withVerbSettlement(err, outcome) {
if (readMember(err, "code") !== "rewind.restore_failed")
return err;
const detail = readMember(err, "detail");
if (detail === null || typeof detail !== "object")
return err;
try {
if (Object.isExtensible(detail))
detail.rewind = { moved: outcome.moved, branch: "untouched" };
}
catch {
}
return err;
}
function screenRewindFilesRequest(request) {
const bad = (what) => {
const e = new Error(`Runner.rewindFiles: ${what} — nothing was rewound. The request is { sessionId, to, dryRun?, signal?, expect?, unplacedHistoryRecordedUnder?, cwd?, holder? }.`);
e.code = "rewind.invalid_spec";
throw e;
};
const { sessionId, to, dryRun, signal, expect, unplacedHistoryRecordedUnder, cwd, holder } = readPlainRequest(request, REQUEST_KEYS, bad);
if (typeof sessionId !== "string" || sessionId === "")
return bad(`sessionId must be a non-empty string, got ${shownValue(sessionId)}`);
if (typeof to !== "string" || to === "")
return bad(`to must be a non-empty entry id, got ${shownValue(to)}`);
if (dryRun !== undefined && typeof dryRun !== "boolean")
return bad(`dryRun must be a boolean when given, got ${shownValue(dryRun)}`);
if (signal !== undefined && !(signal instanceof AbortSignal))
return bad(`signal must be an AbortSignal when given, got ${shownValue(signal)}`);
if (cwd !== undefined && !isAbsoluteHostPath(cwd))
return bad(`cwd must be an absolute host path when given (posix "/…", a Windows drive "C:\\…" or UNC "\\\\server\\share\\…"; no ".." segment, no NUL, at most ${ABSOLUTE_HOST_PATH_MAX} characters), got ${shownValue(cwd)}`);
if (holder !== undefined && (typeof holder !== "string" || holder === ""))
return bad(`holder must be a non-empty string when given (the grant the verb acts under), got ${holder === "" ? "an empty string" : `a ${holder === null ? "null" : typeof holder}`}`);
return { sessionId, to, dryRun: dryRun === true, signal, expect: readOccupantExpectation(expect, bad), restoreOptions: readRestoreOptions(unplacedHistoryRecordedUnder, true, "Runner.rewindFiles"), cwd, holder };
}
function sessionBusyRefusal(sessionId, target) {
const e = new Error(`Runner.rewindFiles: a task is running or queued on session "${sessionId}" in this Runner, or a write one of its tasks issued has not settled — rewinding its files to entry "${target}" now would move them under that work, so nothing was rewound; retry once it has ended and its writes have settled`);
e.code = "rewind.session_busy";
return e;
}
function filesEnvUnsupportedRefusal(sessionId, target, purposeRefusal) {
const why = purposeRefusal === undefined
? "this deployment mounts no filesystem-capable ExecutionEnv"
: `this deployment's executionEnvFactory does not serve a rewind (it refused purpose "rewind_files" with ${ENV_PURPOSE_UNSUPPORTED})`;
const message = `Runner.rewindFiles: ${why}, so session "${sessionId}" has no working tree to rewind to entry "${target}" — nothing was rewound`;
const e = (purposeRefusal === undefined ? new Error(message) : new Error(message, { cause: purposeRefusal }));
e.code = "rewind.files_env_unsupported";
return e;
}