UNPKG

@code-yeongyu/senpi

Version:

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

126 lines • 7.07 kB
/** * The handoff-parked residency record: the set of sessions a predecessor host held resident and * parked with `handoff_parked` (or its idle sweep), persisted so the SUCCESSOR can reopen them by * path with the same durable session id (senpi#3282). * * A `retain_on_disconnect` session must survive EVERY generation. Each parked session is ONE file * (`<daemonDir>/handover-parked/<sha>.json`) written atomically, so a successor removes exactly the * entry it reopened and nothing else - a predecessor that parks another session concurrently cannot * be clobbered by that removal, across processes. This per-entry shape is the cross-process guard: * there is no shared list file to read-merge-write, so there is no lost update to lock against. * The predecessor appends an entry (awaited, in-process mutex so two parks in one host keep both); * the successor reopens each entry with the same durable id and `retain_on_disconnect` and deletes * ONLY that entry's file after success (crash-safe, at most once, never lost). An entry whose * session file is gone is dropped, never retried. */ import { createHash } from "node:crypto"; import { existsSync, renameSync } from "node:fs"; import { mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { parsePermissionPresetName } from "../../core/extensions/builtin/permission-system/cli.js"; import { sessionAutoTitleError, sessionBrowserEngineError, sessionContextError, sessionKindError, sessionPromptSurfaceError, sessionRetryFallbackError, } from "./rpc-input-validation.js"; import { sessionEnvShapeError } from "./session-caller-env.js"; import { applyContextPatch } from "./session-context-patch.js"; import { isResidentWriter } from "./host-handover-resident-writer.js"; const recordDir = (daemonDir) => join(daemonDir, "handover-parked"); const entryFile = (daemonDir, sessionPath) => join(recordDir(daemonDir), `${createHash("sha256").update(sessionPath, "utf8").digest("hex").slice(0, 16)}.json`); let mutationChain = Promise.resolve(); function enqueueMutation(mutation) { const next = mutationChain.then(mutation, mutation); mutationChain = next.catch(() => { }); return next; } export function isHandoverParkedEntry(value) { if (typeof value !== "object" || value === null || Array.isArray(value)) return false; const record = value; return (typeof record.sessionPath === "string" && typeof record.retainOnDisconnect === "boolean" && (record.durableSessionId === undefined || typeof record.durableSessionId === "string") && (record.cwd === undefined || typeof record.cwd === "string") && (record.parkedBy === undefined || typeof record.parkedBy === "string") && (record.residentWriter === undefined || isResidentWriter(record.residentWriter)) && (record.live === undefined || record.live === true) && (record.thinkingLevel === undefined || typeof record.thinkingLevel === "string") && (record.permissionPreset === undefined || (typeof record.permissionPreset === "string" && parsePermissionPresetName(record.permissionPreset) !== undefined)) && sessionPromptSurfaceError(record.promptSurface) === undefined && sessionBrowserEngineError(record.browserEngine) === undefined && sessionKindError(record.sessionKind) === undefined && sessionContextError(record.sessionContext) === undefined && (record.contextOverlay === undefined || !("refusal" in applyContextPatch(undefined, record.contextOverlay))) && sessionAutoTitleError(record.autoTitle) === undefined && sessionRetryFallbackError(record.retryFallback) === undefined && sessionEnvShapeError(record.sessionEnv) === undefined && (record.model === undefined || (typeof record.model === "object" && record.model !== null && typeof record.model.provider === "string" && typeof record.model.modelId === "string"))); } async function writeEntryFile(daemonDir, entry) { await mkdir(recordDir(daemonDir), { recursive: true, mode: 0o700 }); const file = entryFile(daemonDir, entry.sessionPath); const tmp = `${file}.${process.pid}.${Math.random().toString(16).slice(2, 10)}.tmp`; await writeFile(tmp, `${JSON.stringify(entry, null, 2)}\n`, { mode: 0o600 }); renameSync(tmp, file); } export function recordHandoverParkedSession(daemonDir, entry) { return enqueueMutation(() => writeEntryFile(daemonDir, entry)); } export async function readHandoverParkedSessions(daemonDir) { let names; try { names = (await readdir(recordDir(daemonDir))).filter((name) => name.endsWith(".json")); } catch { return []; } const entries = []; for (const name of names) { const file = join(recordDir(daemonDir), name); try { const parsed = JSON.parse(await readFile(file, "utf8")); if (isHandoverParkedEntry(parsed)) entries.push(parsed); // A well-formed JSON value that fails the shape check is not corrupt: it may be an entry a // different-version generation wrote (a rollback handover). Leave it alone. } catch (cause) { // Writes are atomic (renameSync), so a torn write cannot happen; only a genuinely corrupt // payload (SyntaxError) is dropped. ENOENT is a normal race with a concurrent clear, and // EMFILE/EACCES are transient - dropping an entry for any of those loses a retained session // for good. On any of those, skip the entry and leave the file for the next read. if (cause instanceof SyntaxError) { process.stderr.write(`senpi rpc handover-parked entry ${name} is corrupt; dropping it\n`); await rm(file, { force: true }); } } } return entries; } export function clearHandoverParkedSession(daemonDir, sessionPath) { return enqueueMutation(() => rm(entryFile(daemonDir, sessionPath), { force: true })); } /** * Clears an inherited entry after its reopen, unless the reopen re-recorded it as resident on * `holder` (a retained session is recorded by the host it is open on, so the next start reopens it). */ export function clearInheritedParkedSession(daemonDir, sessionPath, holder) { return enqueueMutation(async () => { const file = entryFile(daemonDir, sessionPath); if (holder !== undefined) { const recorded = await readFile(file, "utf8").then((text) => JSON.parse(text), () => undefined); if (isHandoverParkedEntry(recorded) && recorded.parkedBy === holder) return; } await rm(file, { force: true }); }); } export function dropHandoverParkedSessionIfFileGone(daemonDir, sessionPath) { if (existsSync(sessionPath)) return Promise.resolve(); return clearHandoverParkedSession(daemonDir, sessionPath); } //# sourceMappingURL=host-handover-parked.js.map