@sema-agent/core
Version:
Stateless, task-oriented AI agent core
108 lines (107 loc) • 6.76 kB
JavaScript
import { resolveCheckpointStore } from "../checkpoint-store.js";
import { isSessionConflict } from "../session.js";
import { userRowSourceOf } from "../user-row-origin.js";
import { indexOnBranch, refuseBranchOutsideWindow } from "./branch-window.js";
import { refuseOpenToolCallAt } from "./continues-from.js";
import { judgeRewindTarget } from "./rewind-target.js";
import { assertStoreJudgesHolder } from "../checkpoint-generation.js";
import { stampHolder } from "./session-write-ledger.js";
import { acquireExistingSession, claimIdleSession, readOccupantExpectation, readPlainRequest, refuseParkedSession, shownValue } from "./session-verb-doors.js";
const VERB = "Runner.rewindConversation";
const REQUEST_KEYS = new Set(["sessionId", "to", "dryRun", "lastSeenInput", "expect", "checkpointStore", "holder"]);
const PARKED = {
verb: VERB,
code: "rewind.session_parked",
undone: "a parked session's resume puts its leaf back at the checkpoint's leaf, and the turns a rewind takes back with it, so nothing was rewound; decide the checkpoint (resume it) or expire it, then rewind",
};
export async function rewindSessionConversation(seats, request) {
const req = screenRequest(request);
const store = resolveCheckpointStore(req.checkpointStore !== undefined ? { checkpointStore: req.checkpointStore } : {}, seats.deps);
assertStoreJudgesHolder("session", "RunnerDeps.sessionStore", seats.sessions, req.holder, "host");
const release = await claimIdleSession(seats, req.sessionId, () => sessionBusyRefusal(req.to, `a task is running or queued on session "${req.sessionId}" in this Runner, or a write one of its tasks issued has not settled`));
try {
const acquired = await acquireExistingSession(seats.sessions, req.sessionId, VERB, "nothing was rewound", req.expect);
await refuseParkedSession(store, req.sessionId, req.checkpointStore !== undefined ? "the request's" : "the deployment's", PARKED);
const raw = acquired.session.getStorage();
const storage = req.holder !== undefined ? stampHolder(raw, req.holder) : raw;
const { landing } = await judgeRewindTarget(storage, req.to, "before", req.sessionId, VERB);
const leaf = await storage.getLeafId();
const answer = { dryRun: req.dryRun, leafId: landing, previousLeafId: leaf };
if (leaf === landing)
return answer;
await refuseBranchOutsideWindow(storage, landing, req.to, req.sessionId, VERB);
const branch = await storage.getPathToRoot(leaf);
if (indexOnBranch(branch, req.to, `${VERB}: entry "${req.to}" (to)`, req.sessionId) < 0)
throw targetOffBranch(leaf, req);
if (req.lastSeenInput !== undefined)
refuseUnseenLaterTurn(branch, req.lastSeenInput, req);
await storage.getPathToRoot(landing);
await refuseOpenToolCallAt(acquired.session, landing, req.to, VERB);
if (req.dryRun)
return answer;
try {
await storage.setLeafId(landing, { expectedLeafId: leaf });
}
catch (err) {
if (isSessionConflict(err))
throw sessionBusyRefusal(req.to, `another writer moved session "${req.sessionId}"'s leaf after this rewind read it`, err);
throw err;
}
return answer;
}
finally {
release();
}
}
function targetOffBranch(leaf, req) {
const e = new Error(`${VERB}: entry "${req.to}" (to) is not on session "${req.sessionId}"'s current conversation branch — ${leaf === null ? "the session's leaf is empty" : `the branch ending at its leaf, entry "${leaf}", does not pass through it`}, so nothing was rewound; a view that showed it there is out of date: read the session again (to continue from another branch, start a run with resumeAt)`);
e.code = "rewind.target_off_branch";
return e;
}
function refuseUnseenLaterTurn(branch, seen, req) {
const at = indexOnBranch(branch, seen, `${VERB}: entry "${seen}" (lastSeenInput)`, req.sessionId);
let later;
for (let i = branch.length - 1; at >= 0 && i > at && later === undefined; i--) {
const e = branch[i];
if (e.type === "message" && userRowSourceOf(e.message)?.origin === "human_input")
later = e.id;
}
if (at >= 0 && later === undefined)
return;
const what = at < 0 ? `entry "${seen}" (lastSeenInput) is not on session "${req.sessionId}"'s current branch, so the request's view is not that branch` : `the newest person's input on session "${req.sessionId}"'s branch is entry "${later}", after entry "${seen}" (lastSeenInput)`;
const e = new Error(`${VERB}: ${what} — a turn the request has not seen would leave the branch with entry "${req.to}", so nothing was rewound; read the session again and rewind from what it shows`);
e.code = "rewind.unseen_later_turn";
throw e;
}
function screenRequest(request) {
const bad = (what) => {
const e = new Error(`${VERB}: ${what} — nothing was rewound. The request is { sessionId, to, dryRun?, lastSeenInput?, expect?, checkpointStore?, holder? }.`);
e.code = "rewind.invalid_spec";
throw e;
};
const { sessionId, to, dryRun, lastSeenInput, expect, checkpointStore, 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 (lastSeenInput !== undefined && (typeof lastSeenInput !== "string" || lastSeenInput === ""))
return bad(`lastSeenInput must be a non-empty entry id when given, got ${shownValue(lastSeenInput)}`);
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 {
holder,
sessionId,
to,
dryRun: dryRun === true,
lastSeenInput,
expect: readOccupantExpectation(expect, bad),
checkpointStore: checkpointStore,
};
}
function sessionBusyRefusal(target, why, cause) {
const e = new Error(`${VERB}: ${why} — rewinding it before entry "${target}" now would move its leaf under that work, so nothing was rewound; read the session again once that work has settled`, cause !== undefined ? { cause } : undefined);
e.code = "rewind.session_busy";
return e;
}