@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
223 lines • 10.7 kB
JavaScript
/**
* A session's persistence lifecycle across process restarts: take the per-session lease, restore
* the persisted monitors on a detached promise (session_start never waits on a grace window), and
* deliver ONE decided digest through a slot that holds it until a model is bound. A live foreign
* holder defers everything: the footer says who holds the monitors, and a lease keeper takes the
* session over the moment that process exits, running the same restore exactly once. Monitors
* created while waiting are queued and reach the manifest after the takeover.
*/
import { existsSync } from "node:fs";
import { encodedSessionId } from "../../../session-sidecar-store.js";
import { isStaleExtensionContextError } from "../goal/stale-context.js";
import { withTerminalContext } from "./context-lifetime.js";
import { createLeaseKeeper } from "./lease-keeper.js";
import { acquireTerminalLease, releaseTerminalLease, retireLeaseToken, } from "./manifest-lease.js";
import { sweepMonitorOverflowFiles } from "./monitor-overflow-file.js";
import { removeMonitorStateDir, terminalStateDir } from "./monitor-state-dir.js";
import { ownProcessStartedAtMs, processBootAtMs } from "./process-identity.js";
import { restoreTerminalState } from "./restore.js";
import { buildRestoreDigest, createDigestSlot, deliverRestoreDigest } from "./restore-digest.js";
import { restoreHandlers } from "./restore-handlers.js";
import { createTerminalManifestStore, TerminalManifestWriter } from "./terminal-manifest.js";
import { sweepTerminalStateDir } from "./terminal-state-gc.js";
import { bindTerminalManifestWriter, unbindTerminalManifestWriter } from "./tools/monitor.js";
export const RESTORE_STATUS_KEY = "terminal-restore";
const errorText = (error) => (error instanceof Error ? error.message : String(error));
/** Test-only timing overrides; production uses the modules' own defaults. */
export const restoreSessionTestHooks = {};
const decisions = new Map();
function armDecision(sessionKey) {
let resolve = () => { };
const promise = new Promise((settle) => {
resolve = settle;
});
decisions.set(sessionKey, { promise, resolve });
return resolve;
}
/** Settles once this session's current generation has decided its restore (or had nothing to decide). */
export function whenRestoreDecided(sessionKey) {
return decisions.get(sessionKey)?.promise ?? Promise.resolve();
}
export function flushRestoreDigest(pi, state) {
withTerminalContext(() => state.digestSlot.flush((message) => {
// terminal.notify "off" keeps the model channel silent; the user still sees the digest.
if (state.settings.notify !== "off")
return deliverRestoreDigest(pi, state.ctx, message);
state.ctx?.ui?.notify?.(message.content, "info");
return true;
}), () => {
state.keeper?.stop();
state.digestSlot = createDigestSlot();
});
}
function emptyDigest() {
return {
restored: 0,
lost: 0,
expired: 0,
muted: 0,
completed: 0,
attachedElsewhere: 0,
storeError: false,
results: [],
backgroundSessions: [],
downtimeMs: 0,
};
}
/** Non-reload session_start (and a reload that does not hold the lease): take ownership or wait for it. */
export async function startPersistence({ pi, state, toolCtx, sessionKey }) {
state.generation += 1;
state.digestSlot = createDigestSlot();
const decided = armDecision(sessionKey);
const ctx = state.ctx;
const dir = terminalStateDir(ctx);
const sessionManager = ctx?.sessionManager;
if (dir === undefined || sessionManager === undefined)
return decided();
const encoded = encodedSessionId(sessionKey);
const generation = state.generation;
const retire = () => {
state.keeper?.stop();
state.digestSlot = createDigestSlot();
decided();
};
const retired = (error) => {
if (!isStaleExtensionContextError(error))
throw error;
retire();
};
const own = async (lease) => {
state.lease = { path: lease.path, pid: lease.pid, token: lease.token };
ctx?.ui?.setStatus?.(RESTORE_STATUS_KEY, undefined);
const writer = new TerminalManifestWriter({ session: sessionManager });
state.manifestWriter = writer;
state.recordedBackgroundIds.clear();
const bundle = state.bundle;
let restoredFromReadableManifest = false;
if (bundle !== null && existsSync(writer.store.filePath)) {
let digest;
try {
digest = await restoreTerminalState({
manifest: writer.store,
handlers: restoreHandlers(writer, toolCtx, bundle, restoreSessionTestHooks.graceMs),
sessionFile: sessionManager.getSessionFile?.(),
processStartedAtMs: ownProcessStartedAtMs(),
});
}
catch (error) {
if (isStaleExtensionContextError(error))
throw error;
// A restore that throws (an unreadable transcript, a kill error on a confirmed orphan)
// still decides: the session hears it failed, and the lease stays bound for shutdown.
ctx?.ui?.notify?.(`Terminal restore failed: ${errorText(error)}`, "warning");
digest = { ...emptyDigest(), storeError: true };
}
// A watch that did not come back never runs again: its baseline dir goes with it.
await Promise.all(digest.results
.filter((result) => result.outcome === "lost" || result.outcome === "expired" || result.outcome === "completed")
.map((result) => removeMonitorStateDir(dir, result.monitorId)));
if (generation !== state.generation)
return;
restoredFromReadableManifest = !digest.storeError;
if (digest.storeError || digest.results.length > 0 || digest.backgroundSessions.length > 0) {
state.digestSlot.set(buildRestoreDigest(digest, { generation, outcome: "decided" }));
}
}
// Bound AFTER the restore read the file: draining queued specs writes the manifest.
bindTerminalManifestWriter(sessionKey, writer);
// A corrupt manifest is left as it was (fail closed); a readable one is rewritten to the truth.
if (restoredFromReadableManifest)
await writer.persistRestored();
state.ensurePersistence = null;
const self = { pid: process.pid, bootAtMs: await processBootAtMs(), processStartedAtMs: ownProcessStartedAtMs() };
// Housekeeping only: a failed sweep leaves the files for the next start to reclaim.
void sweepTerminalStateDir(dir, { self, keep: new Set([`${encoded}.lease`, `${encoded}.json`]) }).catch(() => undefined);
void sweepMonitorOverflowFiles(dir).catch(() => undefined);
flushRestoreDigest(pi, state);
decided();
};
const wait = (holder) => {
ctx?.ui?.setStatus?.(RESTORE_STATUS_KEY, holder === null ? "monitors waiting for the session lease" : `monitors held by pid ${holder.pid}`);
state.digestSlot.set(buildRestoreDigest(emptyDigest(), {
generation,
outcome: "deferred",
...(holder === null ? {} : { holderPid: holder.pid }),
}));
state.keeper?.stop();
state.keeper = createLeaseKeeper({
dir,
encodedSessionId: encoded,
...(restoreSessionTestHooks.keeperIntervalMs !== undefined
? { intervalMs: restoreSessionTestHooks.keeperIntervalMs }
: {}),
onTakeover: (lease) => {
state.restoreInFlight = own(lease).catch(retired);
return state.restoreInFlight;
},
onError: (error) => {
const waiting = state.keeper?.state === "waiting";
withTerminalContext(() => ctx?.ui?.notify?.(`Terminal lease ${waiting ? "check failed, still waiting" : "takeover failed"}: ${errorText(error)}`, "warning"), retire);
},
});
state.keeper.start(holder);
};
const acquire = async () => {
// The lease kept changing (or the dir failed): never leave the session undecided; the keeper retries.
const lease = await acquireTerminalLease({ dir, encodedSessionId: encoded }).catch((error) => {
ctx?.ui?.notify?.(`Terminal lease not acquired yet, retrying: ${errorText(error)}`, "warning");
return null;
});
if (lease === null)
return wait(null);
if (lease.acquired) {
state.restoreInFlight = own(lease).catch(retired);
return;
}
wait(lease.holder);
};
if (existsSync(createTerminalManifestStore(sessionManager).filePath))
return acquire().catch(retired);
// Nothing to restore: the lease and the recorder wait for the first real registration.
decided();
let binding = null;
state.ensurePersistence = () => {
binding ??= acquire()
.then(() => state.restoreInFlight)
.catch(retired);
return binding;
};
}
/**
* session_shutdown (not reload): stop waiting, finish any restore, suspend and flush, release. A graceful close
* (`closed`, oh-my-openagent#14313) records nothing to restore instead of suspending.
*/
export async function stopPersistence(state, sessionKey, closed = false) {
const keeper = state.keeper;
keeper?.stop();
state.keeper = null;
// A tick in flight may still be acquiring (then releases) or taking over (then restores).
await keeper?.settled();
const lease = state.lease;
state.lease = null;
if (lease !== null)
retireLeaseToken(lease.token);
await state.restoreInFlight;
const writer = state.manifestWriter;
if (writer && state.bundle)
await writer.observeMonitorState(state.bundle.monitors.snapshot());
detachPersistence(state, sessionKey);
if (writer)
await (closed ? writer.recordClosed() : writer.recordShutdown());
if (lease !== null)
await releaseTerminalLease(lease);
decisions.get(sessionKey)?.resolve();
}
/** Detach the manifest recorder without writing (a reload keeps live state instead). */
export function detachPersistence(state, sessionKey) {
state.manifestWriter = null;
state.ensurePersistence = null;
state.recordedBackgroundIds.clear();
if (sessionKey !== undefined)
unbindTerminalManifestWriter(sessionKey);
}
//# sourceMappingURL=restore-session.js.map