@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
236 lines • 9.74 kB
JavaScript
import { closeSync, fstatSync } from "node:fs";
import { isMainThread } from "node:worker_threads";
import { releaseInheritedStartupFillers } from "./private-fd-startup-fillers.js";
import { decodePrivateFdTable, PRIVATE_FDS_TABLE_ENV } from "./private-fd-table.js";
import { inheritedDuplex, isFifoMode } from "./utils/inherited-duplex.js";
import { clearPrivateFdInherit } from "./utils/private-fd-inherit.js";
/** Set only on the supervisor-to-engine hop: the engine claims its channels and never forwards them. */
export const PRIVATE_FDS_FINAL_ENV = "SENPI_PRIVATE_FDS_FINAL";
const STATE = Symbol.for("senpi.private-fds.v3");
/**
* Recorded after the Windows compiled-runtime proof and old-parser control passed on Bun 1.4.4 (senpi main run
* 41147881849, #4898). Every Bun bump invalidates this proof automatically; re-run both before recording the new version.
*/
const WINDOWS_PRIVATE_FD_PAIR_PROVEN = { bun: "1.4.4" };
function isState(value) {
return (typeof value === "object" &&
value !== null &&
"declared" in value &&
value.declared instanceof Set &&
"channels" in value &&
value.channels instanceof Map &&
"forward" in value &&
value.forward instanceof Map);
}
/**
* Measured on Node 24/26 and Bun 1.4 (macOS and Linux): each runtime marks inherited descriptors up to
* at least 21 close-on-exec at startup, while Node on Linux leaks 24 and above into every child it
* spawns. POSIX adopts only 5..15; Windows pairs instead clear inheritance explicitly at receipt.
*/
export const ADOPTABLE_MAX = 15;
/**
* The runtime's own IPC channel is an AF_UNIX socketpair too. Node names its descriptor; Bun exposes the
* channel without one, so a Bun process with IPC adopts nothing (`undefined` = every descriptor refused).
*/
function ipcDescriptor() {
const channel = Reflect.get(process, "channel");
if (typeof channel !== "object" || channel === null)
return null;
const fd = Reflect.get(channel, "fd");
return typeof fd === "number" ? fd : undefined;
}
function isSocket(fd) {
try {
return fstatSync(fd).isSocket();
}
catch {
return false;
}
}
function isPipe(fd) {
try {
return isFifoMode(fstatSync(fd).mode);
}
catch {
return false;
}
}
function inRange(fd) {
return typeof fd === "number" && Number.isSafeInteger(fd) && fd >= 5 && fd <= 64;
}
/**
* POSIX is socket-only: runtime-internal pipes (signal, async wakeup) are FIFOs and never adopted. A named socket
* that cannot become a channel (above the protected range, or named twice) is closed so no child inherits it.
*/
function inspectEntry(fd, shared, runtime, cleared) {
const { ipc } = runtime;
if (Array.isArray(fd)) {
if (runtime.platform !== "win32" ||
runtime.proven === false ||
runtime.bun !== runtime.proven.bun ||
fd.length !== 2 ||
!inRange(fd[0]) ||
!inRange(fd[1]) ||
fd[0] === fd[1] ||
shared ||
ipc === undefined ||
fd[0] === ipc ||
fd[1] === ipc ||
!runtime.isPipe(fd[0]) ||
!runtime.isPipe(fd[1]))
return { channel: null, discard: null };
// Receipt clearing already ran for every named integer, even when another entry was refused.
return { channel: cleared.get(fd[0]) && cleared.get(fd[1]) ? [fd[0], fd[1]] : null, discard: null };
}
if (!inRange(fd))
return { channel: null, discard: null };
if (runtime.platform === "win32" || ipc === undefined || fd === ipc || !runtime.isSocket(fd)) {
return { channel: null, discard: null };
}
if (shared || fd > ADOPTABLE_MAX)
return { channel: null, discard: fd };
return { channel: fd, discard: null };
}
/**
* A valid name is always declared. Only an unshared POSIX socket or a version-proven Windows pipe pair
* becomes a channel. A table that does not parse declares the names it still quotes, without a channel.
*/
export function parseTable(encoded, inspection = {}) {
const table = decodePrivateFdTable(encoded);
const entries = new Map();
if (!table.parsed) {
for (const name of table.names)
entries.set(name, null);
return { entries, parsed: false, discard: new Set() };
}
const raw = table.entries;
const runtime = {
platform: process.platform,
bun: process.versions.bun,
proven: WINDOWS_PRIVATE_FD_PAIR_PROVEN,
ipc: ipcDescriptor(),
isSocket,
isPipe,
clearInherit: clearPrivateFdInherit,
...inspection,
};
const cleared = new Map();
if (runtime.platform === "win32") {
// Protect refused handles too, before any shape, alias, IPC, proof or type decision.
for (const fd of table.values) {
for (const number of Array.isArray(fd) ? fd : [fd]) {
if (inRange(number) && !cleared.has(number))
cleared.set(number, runtime.clearInherit(number));
}
}
}
const counts = new Map();
// Only valid names participate, but a malformed entry's third element still aliases a handle.
for (const [, fd] of raw) {
for (const number of Array.isArray(fd) ? fd : [fd]) {
if (typeof number === "number")
counts.set(number, (counts.get(number) ?? 0) + 1);
}
}
const discard = new Set();
for (const [name, fd] of raw) {
// A descriptor named twice belongs to neither name.
const numbers = Array.isArray(fd) ? fd : [fd];
const shared = numbers.some((number) => typeof number === "number" && (counts.get(number) ?? 0) > 1);
const entry = inspectEntry(fd, shared, runtime, cleared);
entries.set(name, entry.channel);
if (entry.discard !== null)
discard.add(entry.discard);
}
// A handle that stays inheritable would reach every child this process spawns, so close it like POSIX does.
for (const [fd, ok] of cleared)
if (!ok && fd !== runtime.ipc)
discard.add(fd);
return { entries, parsed: true, discard };
}
/** A discarded Windows name may not be open at all (its clear failed for that reason): nothing to close then. */
export function closeDiscarded(fd, close = closeSync) {
try {
close(fd);
}
catch (error) {
if (!(error instanceof Error && "code" in error && error.code === "EBADF"))
throw error;
}
}
/** Read once, in the capturing main thread; session Workers never read a table. */
function capturedState() {
const previous = Reflect.get(globalThis, STATE);
if (isState(previous))
return previous;
// The filler release must see the table it exempts, so it runs here, before the table leaves the environment, not
// only from an entry's earlier import: a bundled entry evaluates its own body after every imported chunk, which put
// the release after this capture and closed the private slots as fillers (senpi#6769). It is idempotent.
if (isMainThread)
releaseInheritedStartupFillers(process.env);
const encoded = isMainThread ? process.env[PRIVATE_FDS_TABLE_ENV] : undefined;
const final = isMainThread && process.env[PRIVATE_FDS_FINAL_ENV] === "1";
if (isMainThread) {
delete process.env[PRIVATE_FDS_TABLE_ENV];
delete process.env[PRIVATE_FDS_FINAL_ENV];
}
const { entries, parsed, discard } = encoded
? parseTable(encoded)
: { entries: new Map(), parsed: true, discard: new Set() };
for (const fd of discard)
closeDiscarded(fd);
const unparseable = !parsed && entries.size === 0;
const state = {
present: Boolean(encoded),
declared: new Set(entries.keys()),
unparseable,
channels: new Map(),
forward: new Map(),
forwardUnparseable: unparseable && !final,
};
for (const [name, fd] of entries) {
if (fd !== null)
state.channels.set(name, fd);
if (!final)
state.forward.set(name, fd);
}
Reflect.set(globalThis, STATE, state);
return state;
}
const state = capturedState();
/** True when the launcher declared this channel for the launch, with or without a usable descriptor. */
export function privateChannelDeclared(name) {
return state.declared.has(name);
}
/** True when this launch carried a table at all, even one that does not parse. */
export function privateTablePresent() {
return state.present;
}
/** True when a table was present but no channel name could be read from it: declared, unavailable. */
export function privateFdTableUnparseable() {
return state.unparseable;
}
/** Claim once. The caller owns disposal of the socket or both halves of the pipe pair. */
export function takeInheritedPrivateChannel(name) {
const fd = state.channels.get(name);
if (fd === undefined)
return undefined;
state.channels.delete(name);
if (state.forward.has(name))
state.forward.set(name, null);
return inheritedDuplex(fd);
}
/** Only the intentional next engine hop may take the table and descriptor ownership from this process. */
export function takePrivateDescriptors() {
if (state.forwardUnparseable)
return { kind: "unparseable" };
const entries = new Map(state.forward);
// A later hop (an ensure retry) still declares every name; only the descriptors move, once.
for (const [name, fd] of entries) {
state.forward.set(name, null);
if (fd !== null)
state.channels.delete(name);
}
return { kind: "entries", entries };
}
//# sourceMappingURL=private-fds.js.map