@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
187 lines • 7.5 kB
JavaScript
import { randomUUID } from "node:crypto";
import { link, mkdir, open, readdir, readFile, unlink } from "node:fs/promises";
import { hostname } from "node:os";
import { dirname, join } from "node:path";
import { resolveMovedPath } from "./extensions/builtin/moved-path-guard/resolve.js";
import { errorCode } from "./extensions/builtin/terminal/lease-file.js";
import { BOOT_INSTANT_TOLERANCE_MS, ownBootAtMs, ownProcessStartedAtMs, sameBoot, } from "./extensions/builtin/terminal/process-identity.js";
import { readProcessStartMs } from "./extensions/builtin/terminal/process-start-probe.js";
import { encodedSessionId } from "./session-sidecar-store.js";
const WRITERS_DIR = "session-writers";
const CLAIM = /^(\d+)\.json$/;
export class SessionWriterBusyError extends Error {
constructor(holder) {
super(`Session is already open for writing by process ${holder.pid}; close it there or open it read-only.`);
this.code = "session_writer_busy";
this.name = "SessionWriterBusyError";
this.holder = holder;
}
}
export class SessionWriterClaimError extends Error {
constructor(message) {
super(message);
this.code = "session_writer_claim_invalid";
this.name = "SessionWriterClaimError";
}
}
export const realWriterProbes = {
pidAlive: (pid) => {
try {
process.kill(pid, 0);
return true;
}
catch (error) {
return errorCode(error) === "EPERM";
}
},
readProcessStartMs,
bootAtMs: ownBootAtMs,
host: () => hostname(),
self: () => ({ pid: process.pid, processStartedAtMs: ownProcessStartedAtMs() }),
};
export function writerClaimsDir(sessionFile, sessionId) {
return join(dirname(resolveMovedPath(sessionFile)), WRITERS_DIR, encodedSessionId(sessionId));
}
/** Takes the next writer generation, only after proving the current owner can no longer write (senpi#3549). */
export async function acquireWriterClaim(dir, canonicalPath, probes = realWriterProbes) {
await mkdir(dir, { recursive: true });
const current = await latestClaim(dir);
// Resolved before the claim check, so nothing yields between proving the owner gone and publishing the next claim.
// A claim from another boot is checked against a fresh read first: a cached record that a wall-clock step made
// stale must not call a live writer's claim gone.
let bootAtMs = await probes.bootAtMs();
if (current !== undefined && current.host === probes.host() && !sameBoot(bootAtMs, current.bootAtMs))
bootAtMs = await probes.bootAtMs({ fresh: true });
if (current !== undefined && !(await ownerGone(dir, current, probes, bootAtMs)))
throw new SessionWriterBusyError(current);
const self = probes.self();
const claim = {
generation: (current?.generation ?? 0) + 1,
nonce: randomUUID(),
host: probes.host(),
pid: self.pid,
bootAtMs,
processStartedAtMs: self.processStartedAtMs,
canonicalPath,
};
try {
await publishLinked(join(dir, `${claim.generation}.json`), JSON.stringify(claim));
}
catch (error) {
if (errorCode(error) !== "EEXIST")
throw error;
const winner = await latestClaim(dir);
throw winner === undefined ? error : new SessionWriterBusyError(winner);
}
return claim;
}
/** True only while `claim` is still the newest generation and has not been released. */
export async function writerClaimIsCurrent(dir, claim) {
const current = await latestClaim(dir);
if (current?.generation !== claim.generation || current.nonce !== claim.nonce)
return false;
return !(await releasedWith(dir, claim));
}
/** Publishes the nonce-matched release marker; call only once nothing can append, consume or dispatch. */
export async function releaseWriterClaim(dir, claim) {
try {
await publishLinked(join(dir, `${claim.generation}.released`), claim.nonce);
}
catch (error) {
if (errorCode(error) !== "EEXIST")
throw error;
}
}
async function latestClaim(dir) {
const generations = (await readdir(dir).catch(emptyWhenMissing))
.map((name) => CLAIM.exec(name)?.[1])
.filter((value) => value !== undefined)
.map(Number)
.sort((a, b) => a - b);
generations.forEach((generation, index) => {
if (generation !== index + 1)
throw new SessionWriterClaimError(`Writer claims in ${dir} have a gap before ${generation}.`);
});
const last = generations.at(-1);
if (last === undefined)
return undefined;
return parseClaim(await readFile(join(dir, `${last}.json`), "utf8"), dir);
}
async function ownerGone(dir, claim, probes, bootAtMs) {
if (await releasedWith(dir, claim))
return true;
// A writer on another host (a shared or network directory) cannot be probed from here: never displace it.
if (claim.host !== probes.host())
return false;
if (!sameBoot(bootAtMs, claim.bootAtMs))
return true;
if (!probes.pidAlive(claim.pid))
return true;
const startedAtMs = await probes.readProcessStartMs(claim.pid);
if (startedAtMs === undefined)
return false;
return Math.abs(startedAtMs - claim.processStartedAtMs) > BOOT_INSTANT_TOLERANCE_MS;
}
async function releasedWith(dir, claim) {
try {
return (await readFile(join(dir, `${claim.generation}.released`), "utf8")) === claim.nonce;
}
catch (error) {
if (errorCode(error) === "ENOENT")
return false;
throw error;
}
}
async function publishLinked(path, content) {
const temp = `${path}.${randomUUID()}.tmp`;
const file = await open(temp, "wx", 0o600);
try {
await file.writeFile(content, "utf8");
await file.sync();
}
finally {
await file.close();
}
try {
await link(temp, path);
}
catch (error) {
const code = errorCode(error);
if (code === "ENOTSUP" || code === "EOPNOTSUPP" || code === "EPERM") {
throw new SessionWriterClaimError(`Writer claims need hard links, which ${dirname(path)} does not support.`);
}
throw error;
}
finally {
await unlink(temp).catch(() => undefined);
}
}
function parseClaim(raw, dir) {
const parsed = JSON.parse(raw);
if (typeof parsed !== "object" ||
parsed === null ||
!("generation" in parsed && typeof parsed.generation === "number") ||
!("nonce" in parsed && typeof parsed.nonce === "string") ||
!("host" in parsed && typeof parsed.host === "string") ||
!("pid" in parsed && typeof parsed.pid === "number") ||
!("bootAtMs" in parsed && typeof parsed.bootAtMs === "number") ||
!("processStartedAtMs" in parsed && typeof parsed.processStartedAtMs === "number") ||
!("canonicalPath" in parsed && typeof parsed.canonicalPath === "string")) {
throw new SessionWriterClaimError(`A writer claim in ${dir} is malformed.`);
}
return {
generation: parsed.generation,
nonce: parsed.nonce,
host: parsed.host,
pid: parsed.pid,
bootAtMs: parsed.bootAtMs,
processStartedAtMs: parsed.processStartedAtMs,
canonicalPath: parsed.canonicalPath,
};
}
function emptyWhenMissing(error) {
if (errorCode(error) === "ENOENT")
return [];
throw error;
}
//# sourceMappingURL=session-writer-claims.js.map