@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
110 lines • 3.5 kB
JavaScript
import { stat } from "node:fs/promises";
import { join } from "node:path";
import { acquireTerminalLease, releaseTerminalLease, } from "./manifest-lease.js";
export const LEASE_KEEPER_INTERVAL_MS = 10_000;
function isAlive(pid, probe) {
try {
if (probe)
return probe(pid);
process.kill(pid, 0);
return true;
}
catch (error) {
return typeof error === "object" && error !== null && "code" in error && error.code === "EPERM";
}
}
async function leaseFileExists(path) {
try {
await stat(path);
return true;
}
catch {
return false;
}
}
/**
* The WAITER side of the lease: polls the file system only (stat + kill 0, never a subprocess)
* and hands the session over exactly once when the holder is gone. Losing the race to another
* waiter is not an error: this keeper simply keeps waiting on the new holder.
*/
export function createLeaseKeeper(options) {
const intervalMs = options.intervalMs ?? LEASE_KEEPER_INTERVAL_MS;
const path = join(options.dir, `${options.encodedSessionId}.lease`);
let state = "idle";
let holder = null;
let timer;
let inFlight = Promise.resolve();
const arm = () => {
timer = setTimeout(() => {
timer = undefined;
inFlight = tick().catch((error) => {
if (state === "waiting")
arm();
options.onError?.(error);
});
}, intervalMs);
timer.unref();
};
const tryAcquire = async () => {
const result = await acquireTerminalLease({
dir: options.dir,
encodedSessionId: options.encodedSessionId,
now: options.now,
self: options.self,
isProcessAlive: options.isProcessAlive,
readProcessStartMs: options.readProcessStartMs,
});
if (state !== "waiting") {
// stop() landed while the acquire was in flight: hand the lease straight back, or this
// process would hold a lease no generation of it can ever release or re-enter.
if (result.acquired)
await releaseTerminalLease(result);
return;
}
if (result.acquired) {
state = "owner";
timer = undefined;
await options.onTakeover(result);
return;
}
holder = result.holder;
arm();
};
const tick = async () => {
if (state !== "waiting")
return;
keeper.onTick?.();
const current = holder;
const gone = current === null || !(await leaseFileExists(path)) || !isAlive(current.pid, options.isProcessAlive);
if (state !== "waiting")
return;
if (gone) {
await tryAcquire();
return;
}
arm();
};
const keeper = {
get state() {
return state;
},
start(initialHolder) {
if (state === "stopped" || state === "owner")
return;
holder = initialHolder;
state = "waiting";
if (timer === undefined)
arm();
},
stop() {
if (timer !== undefined)
clearTimeout(timer);
timer = undefined;
if (state !== "owner")
state = "stopped";
},
settled: () => inFlight,
};
return keeper;
}
//# sourceMappingURL=lease-keeper.js.map