refactor(process): extract reusable provider lifecycle primitives

Introduce provider-neutral ownership, private runtime roots, absolute startup deadlines, pending-operation correlation, bounded output capture, and verified TERM-to-KILL process supervision.\n\nMigrate Hopper onto the shared lifecycle pieces while keeping its Unix-socket protocol and health/shutdown parsing adapter-specific. Preserve exact ownership checks and fail-closed cleanup, including descendant cleanup after the launcher leader exits.\n\nAdd reusable process fixtures and deterministic coverage for startup timeout, cancellation, output bounds, exit diagnostics, cleanup escalation, repeated close, spawn failure, and resource disposal. Update architecture, provider evaluation, contributor guidance, and generated API documentation.
This commit is contained in:
N0zoM1z0
2026-07-15 23:20:48 +09:00
committed by N0zoM1z0
parent a7621c2633
commit 70e1a0f532
82 changed files with 3400 additions and 436 deletions
+83
View File
@@ -0,0 +1,83 @@
/** Timeout and cancellation projections for one correlated operation. */
export interface PendingOperationOptions<Value> {
readonly timeoutMs: number;
readonly signal?: AbortSignal;
readonly timeoutValue: () => Value;
readonly cancelledValue: () => Value;
}
interface PendingOperation<Value> {
readonly resolve: (value: Value) => void;
readonly timer: NodeJS.Timeout;
readonly signal: AbortSignal | undefined;
readonly onAbort: (() => void) | undefined;
}
/**
* Correlates event-driven provider replies with bounded waits.
*
* The registry owns every request timer and abort listener. Settling, timing
* out, cancelling, or failing an operation removes both before resolution, so
* late protocol replies can be ignored without retaining request resources.
*/
export class PendingOperations<Key, Value> {
readonly #pending = new Map<Key, PendingOperation<Value>>();
/** Number of currently correlated operations. */
get size(): number {
return this.#pending.size;
}
/** Return whether an operation key is awaiting a protocol reply. */
has(key: Key): boolean {
return this.#pending.has(key);
}
/** Register one unique operation key and start its bounded wait. */
wait(key: Key, options: PendingOperationOptions<Value>): Promise<Value> {
if (this.#pending.has(key))
throw new Error("Pending operation key is already registered");
if (options.signal?.aborted === true)
return Promise.resolve(options.cancelledValue());
return new Promise((resolve) => {
const onAbort =
options.signal === undefined
? undefined
: () => this.#finish(key, options.cancelledValue());
const timer = setTimeout(
() => this.#finish(key, options.timeoutValue()),
options.timeoutMs,
);
this.#pending.set(key, {
resolve,
timer,
signal: options.signal,
onAbort,
});
if (onAbort !== undefined)
options.signal?.addEventListener("abort", onAbort, { once: true });
});
}
/** Settle one correlated reply; returns false for late or unknown keys. */
settle(key: Key, value: Value): boolean {
return this.#finish(key, value);
}
/** Fail every active operation while releasing all timers and listeners. */
failAll(valueFor: (key: Key) => Value): void {
for (const key of this.#pending.keys()) this.#finish(key, valueFor(key));
}
#finish(key: Key, value: Value): boolean {
const pending = this.#pending.get(key);
if (pending === undefined) return false;
this.#pending.delete(key);
clearTimeout(pending.timer);
if (pending.signal !== undefined && pending.onAbort !== undefined)
pending.signal.removeEventListener("abort", pending.onAbort);
pending.resolve(value);
return true;
}
}
+43
View File
@@ -0,0 +1,43 @@
import { chmod, mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
/** Filesystem coordinates for one provider-owned private runtime directory. */
export interface PrivateRuntimeRootOptions {
readonly parent?: string;
readonly prefix?: string;
}
/**
* Owns one mode-0700 temporary runtime root and removes it idempotently.
*
* Protocol adapters decide what belongs inside the directory; this primitive
* only establishes a private filesystem boundary and deterministic cleanup.
*/
export class PrivateRuntimeRoot {
#closePromise: Promise<void> | undefined;
private constructor(readonly path: string) {}
/** Allocate a new private runtime root without performing protocol work. */
static async create(
options: PrivateRuntimeRootOptions = {},
): Promise<PrivateRuntimeRoot> {
const path = await mkdtemp(
join(options.parent ?? tmpdir(), options.prefix ?? "rea-provider-"),
);
try {
await chmod(path, 0o700);
return new PrivateRuntimeRoot(path);
} catch (cause: unknown) {
await rm(path, { recursive: true, force: true });
throw cause;
}
}
/** Remove the runtime root; concurrent and repeated callers share cleanup. */
close(): Promise<void> {
this.#closePromise ??= rm(this.path, { recursive: true, force: true });
return this.#closePromise;
}
}
+262
View File
@@ -0,0 +1,262 @@
import { execFile } from "node:child_process";
import { readFile } from "node:fs/promises";
import { promisify } from "node:util";
const execFileAsync = promisify(execFile);
/** Identity proof required before REA may signal an owned process group. */
export interface OwnedProcessGroup {
readonly runId: string;
readonly leaderPid: number;
readonly processGroupId: number;
/** Expected launcher identity, checked only while the leader exists. */
readonly expectedCommand?: string;
/** Expected launcher parent, checked only while the leader exists. */
readonly expectedParentPid?: number;
}
/** One operating-system observation of a process-group member. */
interface ProcessGroupMember {
readonly pid: number;
readonly parentPid: number;
readonly processGroupId: number;
readonly state: string;
readonly command: string;
}
/** Narrow operating-system seam used to inspect and signal process groups. */
export interface ProcessOwnershipHost {
listMembers(processGroupId: number): Promise<
readonly {
readonly pid: number;
readonly parentPid: number;
readonly processGroupId: number;
readonly state: string;
readonly command: string;
}[]
>;
environment(pid: number): Promise<Readonly<Record<string, string>>>;
signalGroup(processGroupId: number, signal: NodeJS.Signals): void;
}
/** Per-member reason that token-verified cleanup failed closed. */
interface ProcessOwnershipValidationFailure {
readonly pid: number;
readonly reason: "environment-unreadable" | "run-token-mismatch";
}
/** Cleanup outcome with per-member diagnostics when ownership is uncertain. */
export type ProcessCleanupResult =
| { readonly cleaned: true; readonly signaled: boolean }
| {
readonly cleaned: false;
readonly reason: string;
readonly failures?: readonly {
readonly pid: number;
readonly reason: "environment-unreadable" | "run-token-mismatch";
}[];
};
/** Token-verified liveness result used by post-root-exit settlement. */
export type ProcessGroupObservation =
| { readonly state: "empty" }
| { readonly state: "alive" }
| { readonly state: "unverifiable"; readonly reason: string };
/** Select the PTY root group and groups led by an observed captured process. */
export const selectCapturedProcessGroupIds = (
rootPid: number,
samples: readonly {
readonly pid: number;
readonly process_group_id: number | null;
}[],
): readonly number[] => {
const processGroupIds = new Set<number>([rootPid]);
for (const sample of samples) {
// A sampled member may transiently inherit an unrelated group. POSIX group
// leaders have pid === pgid, so only that observation establishes that the
// group leader itself belonged to the captured tree. Token checks below
// remain the final authority immediately before observation or signaling.
if (sample.pid === sample.process_group_id) processGroupIds.add(sample.pid);
}
return [...processGroupIds];
};
/** Parse the NUL-delimited Linux process environment without nameless keys. */
export const parseProcessEnvironment = (
value: string,
): Readonly<Record<string, string>> =>
Object.fromEntries(
value
.split("\0")
.filter((entry) => entry.indexOf("=") > 0)
.map((entry) => {
const separator = entry.indexOf("=");
return [entry.slice(0, separator), entry.slice(separator + 1)];
}),
);
const systemHost: ProcessOwnershipHost = {
async listMembers(processGroupId) {
if (process.platform === "win32") return [];
const { stdout } = await execFileAsync("ps", [
"-axo",
"pid=,ppid=,pgid=,stat=,command=",
]);
return stdout
.split("\n")
.map((line) => /\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.*)/u.exec(line))
.filter((match): match is RegExpExecArray => match !== null)
.map((match) => ({
pid: Number(match[1]),
parentPid: Number(match[2]),
processGroupId: Number(match[3]),
state: match[4] ?? "",
command: match[5] ?? "",
}))
.filter((member) => member.processGroupId === processGroupId);
},
async environment(pid) {
if (process.platform === "linux") {
return parseProcessEnvironment(
await readFile(`/proc/${pid}/environ`, "utf8"),
);
}
const { stdout } = await execFileAsync("ps", ["eww", "-p", String(pid)]);
const environment: Record<string, string> = {};
for (const match of stdout.matchAll(
/(?:^|\s)([A-Za-z_][A-Za-z0-9_]*)=([^\s]*)/gu,
))
environment[match[1]!] = match[2] ?? "";
return environment;
},
signalGroup(processGroupId, signal) {
process.kill(-processGroupId, signal);
},
};
/** Read the capture run token currently exposed by one live process. */
export const readProcessRunId = async (
pid: number,
host: ProcessOwnershipHost = systemHost,
): Promise<string | undefined> =>
(await host.environment(pid)).REA_PROCESS_RUN_ID;
/**
* Verify run-token ownership before signaling a POSIX process group.
*
* Process IDs and group IDs can be reused. REA therefore re-reads every live
* member's environment immediately before signaling and fails closed if any
* member cannot be inspected or lacks the per-capture run token.
*/
export const cleanupOwnedProcessGroup = async (
ownership: OwnedProcessGroup,
host: ProcessOwnershipHost = systemHost,
): Promise<ProcessCleanupResult> => {
let members: readonly ProcessGroupMember[];
try {
members = await host.listMembers(ownership.processGroupId);
} catch {
return { cleaned: false, reason: "process group could not be inspected" };
}
const liveMembers = liveProcessGroupMembers(members);
if (liveMembers.length === 0) return { cleaned: true, signaled: false };
const leader = liveMembers.find(
(member) => member.pid === ownership.leaderPid,
);
if (leader !== undefined) {
if (
ownership.expectedParentPid !== undefined &&
leader.parentPid !== ownership.expectedParentPid
)
return {
cleaned: false,
reason: "owned launcher parent identity did not match",
};
if (
ownership.expectedCommand !== undefined &&
!commandMatches(leader.command, ownership.expectedCommand)
)
return {
cleaned: false,
reason: "owned launcher command identity did not match",
};
}
const failures: ProcessOwnershipValidationFailure[] = [];
for (const member of liveMembers) {
try {
const environment = await host.environment(member.pid);
if (environment.REA_PROCESS_RUN_ID !== ownership.runId)
failures.push({ pid: member.pid, reason: "run-token-mismatch" });
} catch {
failures.push({ pid: member.pid, reason: "environment-unreadable" });
}
}
if (failures.length > 0)
return {
cleaned: false,
reason: failures.some(({ reason }) => reason === "run-token-mismatch")
? "process group contains an unowned or PID-reused process"
: "process ownership could not be revalidated",
failures,
};
try {
host.signalGroup(ownership.processGroupId, "SIGKILL");
} catch (cause: unknown) {
const code =
cause instanceof Error && "code" in cause ? cause.code : undefined;
if (code !== "ESRCH")
return { cleaned: false, reason: "owned process group signal failed" };
}
return { cleaned: true, signaled: true };
};
/** Observe one group without signaling it, failing closed on identity doubt. */
export const observeOwnedProcessGroup = async (
ownership: OwnedProcessGroup,
host: ProcessOwnershipHost = systemHost,
): Promise<ProcessGroupObservation> => {
let members: readonly ProcessGroupMember[];
try {
members = await host.listMembers(ownership.processGroupId);
} catch {
return {
state: "unverifiable",
reason: "process group could not be inspected",
};
}
const liveMembers = liveProcessGroupMembers(members);
if (liveMembers.length === 0) return { state: "empty" };
for (const member of liveMembers) {
try {
if (
(await host.environment(member.pid)).REA_PROCESS_RUN_ID !==
ownership.runId
)
return {
state: "unverifiable",
reason: "process ownership did not match",
};
} catch {
return {
state: "unverifiable",
reason: "process ownership could not be revalidated",
};
}
}
return { state: "alive" };
};
const liveProcessGroupMembers = (
members: readonly ProcessGroupMember[],
): readonly ProcessGroupMember[] =>
members.filter(({ state }) => !state.startsWith("Z"));
const commandMatches = (actual: string, expected: string): boolean => {
const normalizedActual = actual.trim();
const normalizedExpected = expected.trim();
return (
normalizedActual === normalizedExpected ||
normalizedActual.startsWith(`${normalizedExpected} `)
);
};
+120
View File
@@ -0,0 +1,120 @@
/** Result of an abort-aware interval wait. */
export type AbortableWaitResult = "elapsed" | "aborted";
/** Wait for an interval while removing the supplied abort listener on settle. */
export const waitForAbortableDelay = (
milliseconds: number,
signal?: AbortSignal,
): Promise<AbortableWaitResult> => {
if (signal?.aborted === true) return Promise.resolve("aborted");
return new Promise((resolve) => {
const settle = (result: AbortableWaitResult): void => {
clearTimeout(timer);
signal?.removeEventListener("abort", onAbort);
resolve(result);
};
const onAbort = (): void => settle("aborted");
const timer = setTimeout(
() => settle("elapsed"),
Math.max(0, milliseconds),
);
signal?.addEventListener("abort", onAbort, { once: true });
});
};
/**
* One absolute deadline shared by every phase of a provider startup handshake.
*
* The deadline owns its timer and the listener attached to an optional caller
* signal. Adapters must dispose it after startup succeeds or fails.
*/
export class ProviderStartupDeadline {
readonly #controller = new AbortController();
readonly #deadlineAt: number;
readonly #externalSignal: AbortSignal | undefined;
readonly #onExternalAbort: () => void;
#timer: NodeJS.Timeout | undefined;
#timedOut = false;
#cancelled = false;
constructor(
readonly timeoutMs: number,
signal?: AbortSignal,
) {
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0)
throw new RangeError("Provider startup timeout must be positive");
this.#deadlineAt = Date.now() + timeoutMs;
this.#externalSignal = signal;
this.#onExternalAbort = () => {
if (this.#controller.signal.aborted) return;
if (Date.now() >= this.#deadlineAt) {
this.#timedOut = true;
this.#abort(
new DOMException("Provider startup deadline elapsed", "TimeoutError"),
);
return;
}
this.#cancelled = true;
this.#abort(signal?.reason);
};
if (signal?.aborted === true) {
this.#onExternalAbort();
return;
}
signal?.addEventListener("abort", this.#onExternalAbort, { once: true });
this.#timer = setTimeout(() => {
if (this.#controller.signal.aborted) return;
this.#timedOut = true;
this.#abort(
new DOMException("Provider startup deadline elapsed", "TimeoutError"),
);
}, timeoutMs);
}
/** Composite signal aborted by either the caller or the absolute deadline. */
get signal(): AbortSignal {
return this.#controller.signal;
}
/** True only when the external caller signal initiated cancellation. */
get cancelled(): boolean {
return this.#cancelled;
}
/** True when the absolute startup deadline has elapsed. */
get timedOut(): boolean {
return (
this.#timedOut || (!this.#cancelled && Date.now() >= this.#deadlineAt)
);
}
/** Milliseconds still available to the next startup phase. */
remainingMs(): number {
return Math.max(0, this.#deadlineAt - Date.now());
}
/** Wait for at most one polling interval under the shared deadline signal. */
wait(milliseconds: number): Promise<AbortableWaitResult> {
return waitForAbortableDelay(
Math.min(milliseconds, this.remainingMs()),
this.signal,
);
}
/** Release the deadline timer and external abort listener. */
dispose(): void {
this.#clearTimer();
this.#externalSignal?.removeEventListener("abort", this.#onExternalAbort);
}
#abort(reason: unknown): void {
this.#clearTimer();
this.#externalSignal?.removeEventListener("abort", this.#onExternalAbort);
this.#controller.abort(reason);
}
#clearTimer(): void {
if (this.#timer !== undefined) clearTimeout(this.#timer);
this.#timer = undefined;
}
}
+404
View File
@@ -0,0 +1,404 @@
import { spawn, type ChildProcess } from "node:child_process";
import type { Readable } from "node:stream";
import type {
OwnedProcessGroup,
ProcessCleanupResult,
} from "./ProcessOwnership.js";
const DEFAULT_OUTPUT_BYTES = 64 * 1024;
const DEFAULT_TERMINATION_GRACE_MS = 250;
const DEFAULT_KILL_GRACE_MS = 1_000;
/** Spawn coordinates shared by owned, long-lived provider processes. */
export interface OwnedProviderProcessSpawnOptions {
readonly command: string;
readonly arguments: readonly string[];
readonly runId: string;
readonly expectedCommand?: string;
readonly cwd?: string;
readonly env?: NodeJS.ProcessEnv;
}
/** Spawned process paired with the identity proof required for group cleanup. */
export interface SpawnedOwnedProviderProcess {
readonly process: ChildProcess;
readonly ownership: OwnedProcessGroup;
}
/** Process handle returned by a provider-specific launcher. */
export interface ProviderProcessLaunch {
readonly process: ChildProcess;
readonly ownsProcessLifetime: boolean;
readonly cleanup?: () => Promise<ProcessCleanupResult>;
}
/** Detached diagnostics captured for one supervised provider process. */
export interface ProviderProcessSnapshot {
readonly stdout: {
readonly text: string;
readonly bytes: number;
readonly retainedBytes: number;
readonly truncated: boolean;
};
readonly stderr: {
readonly text: string;
readonly bytes: number;
readonly retainedBytes: number;
readonly truncated: boolean;
};
readonly exitCode: number | null | undefined;
readonly signal: NodeJS.Signals | null | undefined;
}
/** Resource-safe events emitted without imposing provider protocol semantics. */
export type ProviderProcessDiagnostic =
| {
readonly type: "output";
readonly stream: "stdout" | "stderr";
readonly bytes: number;
readonly totalBytes: number;
readonly truncated: boolean;
}
| {
readonly type: "exit";
readonly code: number | null;
readonly signal: NodeJS.Signals | null;
readonly snapshot: ProviderProcessSnapshot;
}
| { readonly type: "error"; readonly message: string };
/** Options for bounded capture and lifecycle diagnostics. */
export interface ProviderProcessSupervisorOptions {
readonly maxOutputBytesPerStream?: number;
readonly onDiagnostic?: (event: ProviderProcessDiagnostic) => void;
}
/** Optional result of provider-specific cleanup performed before stop. */
export interface ProviderProcessStopOptions {
readonly cleanupResult?: ProcessCleanupResult;
readonly terminationGraceMs?: number;
readonly killGraceMs?: number;
}
/** Exact disposition of one owned process stop attempt. */
export type ProviderProcessStopResult =
| {
readonly status:
| "not-owned"
| "already-exited"
| "verified-cleanup"
| "terminated"
| "killed";
}
| { readonly status: "incomplete"; readonly reason: string };
/**
* Spawn a provider in a dedicated POSIX process group with an ownership token.
*
* The caller remains responsible for persisting any ownership manifest and for
* selecting provider-specific command arguments or environment values.
*/
export const spawnOwnedProviderProcess = async (
options: OwnedProviderProcessSpawnOptions,
): Promise<SpawnedOwnedProviderProcess> => {
const child = spawn(options.command, [...options.arguments], {
shell: false,
stdio: ["ignore", "pipe", "pipe"],
detached: process.platform !== "win32",
env: {
...process.env,
...options.env,
REA_PROCESS_RUN_ID: options.runId,
},
...(options.cwd === undefined ? {} : { cwd: options.cwd }),
});
await waitForSpawn(child);
const pid = child.pid;
if (pid === undefined) throw new Error("Provider launcher has no process ID");
const ownership: OwnedProcessGroup = {
runId: options.runId,
leaderPid: pid,
processGroupId: pid,
expectedCommand: options.expectedCommand ?? options.command,
expectedParentPid: process.pid,
};
return { process: child, ownership };
};
/**
* Supervises only generic process resources; wire protocol remains adapter-owned.
*
* Output retention is bounded per stream while byte totals remain exact. Stop
* first honors token-verified group cleanup when supplied, otherwise it uses a
* bounded TERM-to-KILL escalation for a directly owned child.
*/
export class ProviderProcessSupervisor {
readonly #options: ProviderProcessSupervisorOptions;
readonly #stdout: BoundedByteCapture;
readonly #stderr: BoundedByteCapture;
readonly #exit = deferred<{
readonly code: number | null;
readonly signal: NodeJS.Signals | null;
}>();
readonly #onStdout = (chunk: Buffer | string): void => {
this.#capture("stdout", this.#stdout, chunk);
};
readonly #onStderr = (chunk: Buffer | string): void => {
this.#capture("stderr", this.#stderr, chunk);
};
readonly #onExit = (
code: number | null,
signal: NodeJS.Signals | null,
): void => {
this.#recordExit(code, signal);
};
readonly #onClose = (
code: number | null,
signal: NodeJS.Signals | null,
): void => {
this.#recordExit(code, signal);
};
readonly #onError = (cause: Error): void => {
this.#options.onDiagnostic?.({ type: "error", message: cause.message });
};
#exitObservation:
| { readonly code: number | null; readonly signal: NodeJS.Signals | null }
| undefined;
#stopPromise: Promise<ProviderProcessStopResult> | undefined;
#disposed = false;
constructor(
readonly launch: ProviderProcessLaunch,
options: ProviderProcessSupervisorOptions = {},
) {
this.#options = options;
const limit = options.maxOutputBytesPerStream ?? DEFAULT_OUTPUT_BYTES;
if (!Number.isSafeInteger(limit) || limit <= 0)
throw new RangeError("Provider output limit must be a positive integer");
this.#stdout = new BoundedByteCapture(limit);
this.#stderr = new BoundedByteCapture(limit);
this.#attach(launch.process.stdout, "stdout");
this.#attach(launch.process.stderr, "stderr");
launch.process.once("exit", this.#onExit);
launch.process.once("close", this.#onClose);
launch.process.on("error", this.#onError);
if (launch.process.exitCode !== null || launch.process.signalCode !== null)
this.#recordExit(launch.process.exitCode, launch.process.signalCode);
}
/** Latest bounded output and exit observation. */
snapshot(): ProviderProcessSnapshot {
return {
stdout: this.#stdout.snapshot(),
stderr: this.#stderr.snapshot(),
exitCode: this.#exitObservation?.code,
signal: this.#exitObservation?.signal,
};
}
/** Wait for process exit up to a caller-owned bounded interval. */
async waitForExit(timeoutMs: number): Promise<boolean> {
if (this.#exitObservation !== undefined) return true;
let timer: NodeJS.Timeout | undefined;
try {
return await Promise.race([
this.#exit.promise.then(() => true),
new Promise<boolean>((resolve) => {
timer = setTimeout(() => resolve(false), Math.max(0, timeoutMs));
}),
]);
} finally {
if (timer !== undefined) clearTimeout(timer);
}
}
/** Stop an owned process once; concurrent callers share the same escalation. */
stop(
options: ProviderProcessStopOptions = {},
): Promise<ProviderProcessStopResult> {
this.#stopPromise ??= this.#stop(options);
return this.#stopPromise;
}
/** Detach capture and process listeners after an adapter releases ownership. */
dispose(): void {
if (this.#disposed) return;
this.#disposed = true;
this.launch.process.stdout?.off("data", this.#onStdout);
this.launch.process.stderr?.off("data", this.#onStderr);
this.launch.process.off("exit", this.#onExit);
this.launch.process.off("close", this.#onClose);
this.launch.process.off("error", this.#onError);
}
async #stop(
options: ProviderProcessStopOptions,
): Promise<ProviderProcessStopResult> {
try {
if (!this.launch.ownsProcessLifetime) return { status: "not-owned" };
if (this.launch.cleanup !== undefined) {
const cleanup = await this.#ownedCleanup(options.cleanupResult);
if (!cleanup.cleaned)
return { status: "incomplete", reason: cleanup.reason };
const graceMs = options.killGraceMs ?? DEFAULT_KILL_GRACE_MS;
if (await this.waitForExit(graceMs))
return { status: "verified-cleanup" };
const retried = await this.launch.cleanup();
if (!retried.cleaned)
return { status: "incomplete", reason: retried.reason };
if (await this.waitForExit(graceMs))
return { status: "verified-cleanup" };
return {
status: "incomplete",
reason: "verified process-group cleanup did not stop the launcher",
};
}
if (this.#exitObservation !== undefined)
return { status: "already-exited" };
this.#signal("SIGTERM");
if (
await this.waitForExit(
options.terminationGraceMs ?? DEFAULT_TERMINATION_GRACE_MS,
)
)
return { status: "terminated" };
this.#signal("SIGKILL");
if (await this.waitForExit(options.killGraceMs ?? DEFAULT_KILL_GRACE_MS))
return { status: "killed" };
return {
status: "incomplete",
reason: "owned provider process did not exit after SIGKILL",
};
} catch (cause: unknown) {
return {
status: "incomplete",
reason:
cause instanceof Error
? cause.message
: "owned provider process cleanup failed",
};
} finally {
this.dispose();
}
}
#ownedCleanup(
supplied: ProcessCleanupResult | undefined,
): Promise<ProcessCleanupResult> {
if (supplied !== undefined) return Promise.resolve(supplied);
const cleanup = this.launch.cleanup;
return cleanup === undefined
? Promise.resolve({
cleaned: false,
reason: "owned provider process has no cleanup capability",
})
: cleanup();
}
#signal(signal: NodeJS.Signals): void {
if (this.#exitObservation !== undefined) return;
this.launch.process.kill(signal);
}
#attach(stream: Readable | null, name: "stdout" | "stderr"): void {
if (name === "stdout") stream?.on("data", this.#onStdout);
else stream?.on("data", this.#onStderr);
}
#capture(
stream: "stdout" | "stderr",
capture: BoundedByteCapture,
chunk: Buffer | string,
): void {
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
capture.append(bytes);
this.#options.onDiagnostic?.({
type: "output",
stream,
bytes: bytes.byteLength,
totalBytes: capture.bytes,
truncated: capture.truncated,
});
}
#recordExit(code: number | null, signal: NodeJS.Signals | null): void {
if (this.#exitObservation !== undefined) return;
this.#exitObservation = { code, signal };
this.#exit.resolve(this.#exitObservation);
this.#options.onDiagnostic?.({
type: "exit",
code,
signal,
snapshot: this.snapshot(),
});
}
}
class BoundedByteCapture {
readonly #chunks: Buffer[] = [];
#bytes = 0;
#retainedBytes = 0;
constructor(readonly limit: number) {}
get bytes(): number {
return this.#bytes;
}
get truncated(): boolean {
return this.#bytes > this.#retainedBytes;
}
append(chunk: Buffer): void {
this.#bytes += chunk.byteLength;
const remaining = this.limit - this.#retainedBytes;
if (remaining <= 0) return;
const retained = Buffer.from(chunk.subarray(0, remaining));
this.#chunks.push(retained);
this.#retainedBytes += retained.byteLength;
}
snapshot(): ProviderProcessSnapshot["stdout"] {
return {
text: Buffer.concat(this.#chunks, this.#retainedBytes).toString("utf8"),
bytes: this.#bytes,
retainedBytes: this.#retainedBytes,
truncated: this.truncated,
};
}
}
interface Deferred<Value> {
readonly promise: Promise<Value>;
readonly resolve: (value: Value) => void;
}
const deferred = <Value>(): Deferred<Value> => {
let resolver: ((value: Value) => void) | undefined;
const promise = new Promise<Value>((resolve) => {
resolver = resolve;
});
return {
promise,
resolve: (value) => {
resolver?.(value);
},
};
};
const waitForSpawn = (child: ChildProcess): Promise<void> =>
new Promise((resolve, reject) => {
const onSpawn = (): void => {
child.off("error", onError);
resolve();
};
const onError = (cause: Error): void => {
child.off("spawn", onSpawn);
reject(cause);
};
child.once("spawn", onSpawn);
child.once("error", onError);
});