UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

107 lines • 5.14 kB
/** * The restore orchestrator: `restoreTerminalState` replays the manifest after a restart. Every * monitor is classified up front (expired, ephemeral with or without time left, durable) and the * durable and still-live ephemeral ones are handed to their kind's handler, all concurrently. * The result carries per-monitor outcomes and reasons, background sessions told apart as still * running or exited, and an upper bound on how long the session was detached. */ import { confirmOwner } from "./orphan-reaper.js"; import { sessionActivityBeforeMs } from "./session-activity.js"; export { InvalidTerminalManifestError, parseTerminalManifest } from "./terminal-manifest-parse.js"; /** * Re-apply a persisted `deliveryPaused` mute to a freshly restored monitor and report the * outcome it contributes to the digest. The mute MUST be applied by the FRESH runtime id * (bash_N/watch_N) the restore just allocated: `MonitorRegistry.pause` resolves records by * runtime id only, so passing the persisted `mon_` id silently no-ops and the mute is lost. */ export function reapplyPersistedMute(registry, monitor, runtimeId) { if (!monitor.deliveryPaused) return "restored"; registry.pause([runtimeId]); return "muted"; } /** Stub handlers: every monitor is reported lost until a caller plugs the real ones in. */ export const stubRestoreHandlers = { "restartable-command": () => ({ outcome: "lost", reason: "no restore handler" }), "checkpointed-file": () => ({ outcome: "lost", reason: "no restore handler" }), "checkpointed-rpc": () => ({ outcome: "lost", reason: "no restore handler" }), }; function emptyDigest() { return { restored: 0, lost: 0, expired: 0, muted: 0, completed: 0, attachedElsewhere: 0, storeError: false, results: [], backgroundSessions: [], downtimeMs: 0, }; } async function defaultBackgroundAlive(session) { if (session.runtime === undefined) return false; return (await confirmOwner(session.runtime, undefined)) === "confirmed"; } function resultFor(monitor, outcome, handled) { return { monitorId: monitor.monitorId, description: monitor.description, kind: monitor.runtimeKind, outcome, ...(monitor.command !== undefined ? { command: monitor.command } : {}), ...(monitor.path !== undefined ? { path: monitor.path } : {}), ...(handled?.reason !== undefined ? { reason: handled.reason } : {}), ...(handled?.orphan !== undefined ? { orphan: handled.orphan } : {}), }; } export async function restoreTerminalState(options) { let state; try { state = await options.manifest.read(); } catch { // Fail closed: a corrupt or foreign manifest restores nothing and reports the store error. return { ...emptyDigest(), storeError: true }; } if (state === null) return emptyDigest(); const now = (options.now ?? Date.now)(); const lastSeen = Math.max(state.updatedAt, (await sessionActivityBeforeMs(options.sessionFile, options.processStartedAtMs ?? now)) ?? 0); const downtimeMs = Math.max(0, now - lastSeen); const handlers = { ...stubRestoreHandlers, ...options.handlers }; const results = await Promise.all(state.monitors.map(async (monitor) => { // At the deadline the entry is already expired: the handler must not see it at all. if (monitor.expiresAt !== null && monitor.expiresAt <= now) return resultFor(monitor, "expired"); if (monitor.durabilityClass === "ephemeral") { if (monitor.deadlineMs === undefined || monitor.deadlineMs <= now) { return resultFor(monitor, "lost", { outcome: "lost", reason: "deadline passed while detached" }); } const handler = monitor.runtimeKind === "file" ? handlers["checkpointed-file"] : monitor.runtimeKind === "rpc" ? handlers["checkpointed-rpc"] : handlers["restartable-command"]; const handled = await handler(monitor, { downtimeMs, remainingMs: monitor.deadlineMs - now }); return resultFor(monitor, handled.outcome, handled); } const handled = await handlers[monitor.durabilityClass](monitor, { downtimeMs }); return resultFor(monitor, handled.outcome, handled); })); const isAlive = options.isBackgroundAlive ?? defaultBackgroundAlive; const backgroundSessions = await Promise.all(state.backgroundSessions.map(async (session) => { if (session.runtime !== undefined && (await isAlive(session))) { return { id: session.id, command: session.command, outcome: "running", pid: session.runtime.pid }; } return { id: session.id, command: session.command, outcome: "exited" }; })); const digest = { ...emptyDigest(), results, backgroundSessions, downtimeMs }; for (const result of results) digest[result.outcome] += 1; digest.lost += backgroundSessions.length; return digest; } //# sourceMappingURL=restore.js.map