mirror of
https://github.com/morluto/rea.git
synced 2026-11-29 09:56:23 +00:00
* feat(delivery)!: bound default results by an agent result budget Omitted detail now returns complete Evidence only when it fits the new delivery.agent_result_budget_bytes runtime setting (default 49152 compact JSON bytes, about 12k tokens at an estimated 4 bytes per token). Larger results are retained and delivered as the producer's summary with a limitation naming the budget and the recovery call; nothing is refused or truncated. inspect_analysis_view gains an evidence-json view that pages the exact JSON text of retained Evidence. The CLI applies the same budget and publishes the complete bundle with --evidence_output. inspect_managed_members type_names now also narrows member_refs and exported_types, and inspect-byte-entropy gains CLI evidence delivery. BREAKING CHANGE: An omitted detail no longer always returns complete Evidence inline on MCP or the CLI for tools with a detail selector (including inspect_managed_members, inspect_managed_artifact, inspect_byte_entropy, inspect_artifact, analyze_javascript_application, list_procedures, list_strings and the other operations listed in src/domain/agentBudgetOperations.ts). Over the budget they return the retained summary; pass detail complete (--detail complete) for complete inline delivery. inspect_managed_members type_names narrows member_refs and exported_types. Fixes #14172 Fixes #14180 Part of #14187 Part of #14156 * test(schemas): record advertised summaries for budgeted detail * fix(delivery): keep budgeted summaries canonical and carry delivery facts beside them Review fixes for the agent result budget: - Deliver the producer's own summary record, identical to detail summary, so its identity holds in summary consumers such as compare_artifacts. The budget, sizes, retention and the exact paging call travel as delivery facts: a second MCP text block and _meta, or a delivery field in CLI output. - Capture the caller's detail for application-validated tools too, so inspect_binary_layout and similar tools are budgeted. - Keep recovery facts when a budgeted summary itself exceeds the frame. - Size an omitted evidence-json limit by escaped UTF-8 bytes and never split a surrogate pair, even in a one-unit page. - Add the REA_AGENT_RESULT_BUDGET_BYTES launch seed; the shared test environment raises it for semantic tests, and budget tests clear it. - Align tool descriptions and verifiers that read complete Evidence. * fix(delivery): retain the budgeted summary like an explicit summary * fix(delivery): read the budget seed from the captured environment and count delivery facts in the frame - The agent result budget seed is read from the environment the server or CLI invocation captured: ToolResultDelivery takes it at construction, and a CLI invocation binds it in its publication context. The ambient process environment is no longer read. - The frame check reserves the bytes of the delivery block and _meta that are added after encoding, so a budgeted response cannot exceed the frame. - Conformance workflows that resend complete Evidence raise the budget through the shared inline-Evidence environment, as do the artifact and binary layout verifiers. * fix(delivery)!: request complete Evidence explicitly and never spill CLI overflow - Shared test and verifier environments no longer raise the agent result budget. Every test and verifier workflow that reads complete Evidence from a budgeted tool now requests it with detail complete or --detail complete, including the real-provider verifiers outside PR CI (Ghidra, Hopper, IDA, Kuna and client verifiers). Default delivery is exercised as shipped. - Budgeting applies only to tools with a detail selector, so every budgeted call has a complete opt-out. - CLI overflow without --evidence_output writes nothing; its delivery facts carry exact rerun argv for --detail complete and --evidence_output, omitted when the command declares sensitive values. * test(delivery): prove captured budget seeds with valid in-range values * test: state complete-detail requests once and fix codemod regressions - Add tests/support/completeDetail.ts with COMPLETE_DETAIL and completeArguments so tests that read complete Evidence request it in one place, keeping functions within max-lines-per-function without raising the limit. - Restore provider-client tests (GhidraClient, Hopper health): their callTool("name", ...) calls are bridge requests, not MCP tools, and take no detail. - Update the game-scale type inventory test for member_refs narrowing. * test: request complete Evidence in shared JavaScript analysis helpers and remaining CLI workflows * test: request complete Evidence by default in the shared test transports The shared MCP client helpers (createTestMcp, connectLocalToolsMcp and the CLI fixture's shared MCP session) and the CLI runners (the cli fixture and the shared CLI session) now apply one named default, completeEvidenceByDefault. A budgeted tool called with neither detail nor view gets detail complete; the CLI does the same with --detail complete, chosen by the command's tool contract. A budgeted operation that resolves to no contract fails loudly at load. Tests whose subject is delivery opt out with delivery "budgeted". This is a test-harness choice; production delivery is unchanged and the budget tests prove the default path. Per-call complete-detail edits are reverted in the 204 test files whose transports all apply the default. Explicit requests remain where a test drives its own SDK client, server, CLI instance or process, and where the detail choice is the test's subject. * test: resolve CLI complete-detail defaults from the CLI registry The Real Apple and browser verifiers read complete Evidence through artifactCliEvidence, which ran the compiled CLI without a detail choice and got the budgeted {summary, delivery} output. The helper now requests complete Evidence for commands that take --detail, read from the compiled CLI's own registry (scripts/lib/complete-evidence-cli.mjs). The test harness default had a sibling bug: it treated every cli-flagged budgeted contract as taking --detail, but only Evidence-delivery commands do (inspect-binary-layout does not). It now reads the source CLI registry too, and covers every command the CLI budgets. * test(verifiers): request complete Evidence at each verifier's SDK client and CLI argv The real-browser failure was the same missing normalized_result as the Apple one: browser-capture-metadata-budget-e2e reads analyze-web-bundle through artifactCliEvidence, fixed in the previous commit. The shared verifier module, scripts/lib/complete-evidence.mjs, now owns both transports: - completeEvidenceClient wraps each verifier's SDK Client once, so every callTool to a budgeted tool with neither detail nor view requests complete Evidence, whatever local call helper a verifier uses (86 clients, including the Ghidra, Hopper, IDA and Kuna verifiers' argument-less list_procedures and inspect_native_load_image calls). - completeEvidenceCliArguments covers the remaining verifier CLI argv that chose no detail, such as function, decompile, analyze and the Android and Apple commands. Commands and tools that are not budgeted are sent as written. * test(delivery): await async completeEvidenceCliArguments helper in boundary test * test(delivery): request complete detail in Electron CLI artifact format test * docs(delivery): document delivery.rerun as add-only argument arrays * test(schemas): record advertised summaries for the unified delivery budget Tool descriptions now name the agent result budget, and the evidence-json default page is derived from the 32 KiB default, which changes the advertised input digests of the 28 affected tools. Recorded from the Build package job's output. * test(delivery): pin the budget boundary and keep failures unbudgeted Main's retainedSummaryDelivery tests pinned the size decision at exactly 32,768 and 32,769 UTF-8 JSON bytes. Unifying that decision into budgetedSummaryBytes deleted them, and their port never landed, so the byte measurement went unchecked. Restore them against budgetedSummaryBytes at the configured budget and one byte over, for the default and a runtime budget, with ASCII, escaped and multibyte text, plus each condition of the decision. Off-by-one mutants (< for <=, a cap one byte short) fail six cases; measuring UTF-16 code units instead of UTF-8 bytes fails the multibyte cases. An MCP case pins that a target failure from a budgeted tool under the minimum budget is identical with detail omitted and complete, with no delivery facts. * test(verifiers): route literal CLI argv for budgeted commands through complete Evidence real-browser failed with "Scenario CLI did not report external disconnect ownership": runScenarioCli ran capture-browser-scenario without --detail, so an over-budget capture came back as its summary, which has no browser.cleanup. The earlier sweep counted these files as covered because their MCP clients were wrapped, but their CLI argv was not. Route the shared runScenarioCli helper (five callers), the local cli helpers in the module, source-map and script-export verifiers, and every other literal argv for a budgeted CLI command without --detail or --view (EVM interface, binary layout, packet capture, devicetree, DOM destinations, Ghidra relocation symbols, WABT cleanup, Termux browser) through completeEvidenceCliArguments. A sweep of scripts/ for budgeted command literals with --json and no detail selection now finds none. * fix(verifiers): leave clients without callTool unwrapped The native verifier cleanup test drives native-value-e2e with a connection double whose Client has only connect and close. completeEvidenceClient bound client.callTool unconditionally, so wrapping threw a TypeError before connect ran. That TypeError replaced the primary connection failure the test asserts is preserved, and all four fault cases failed in Test shard 5 and Portable tests. A client without callTool has no tool call to complete, so the helper now returns it unchanged. Locally all five fault modes of the fixture now exit 0. * fix(delivery): keep the catalog recorder on shipped helpers and expect view-implied summary The verifier sweep wrapped record-mcp-catalog.mjs in completeEvidenceClient, which lives in an unshipped helper. deferredRuntime copies only the package's shipped files plus the recorder, so the recorder failed to load (ERR_MODULE_NOT_FOUND) and its cleanup recorder never wrote. The recorder only lists tools and prompts, so the wrapper had no effect; it is removed. This branch makes a view with no --detail select summary delivery, as MCP does for a view. Three CLI cases still expected the old view refusal; with a view alone the missing input is now the summary bundle, so they expect evidence_output, and a view with --detail complete still refuses the view. * fix(delivery): request complete Evidence where callers need the whole result Budgeted delivery made four callers receive a summary they cannot use: - The GitHub Actions example uploads the analysis as a CI artifact, so it now asks for --detail complete; over budget it had saved a summary. - javascriptIntegrityPolicyCli spawns the CLI itself, outside the test harness default, and reads normalized_result; it now applies the same completeEvidenceCliArguments default. - nativeObservationViewsMcp builds its own client to prove complete observations overflow into a paging continuation; it now applies the harness default so each call asks for complete Evidence. - The CLI parity goldens are re-recorded for the --detail and --evidence_output options the budgeted commands now advertise. * fix(tests): give processes tests spawn the largest agent result budget About 90 tests spawn scripts/rea.mjs or a server directly, outside the harness default that asks for complete Evidence, and read analysis facts from the result. Over the default budget they received a summary instead; javascriptChildHandleOwnership failed this way. The Vitest environment now seeds REA_AGENT_RESULT_BUDGET_BYTES with the largest accepted value, so a spawned CLI or server delivers complete Evidence, as the in-process default does. Delivery tests keep their own budget: agentResultBudgetMcp builds its server without the seed, so its default-budget cases still exercise the shipped default. * fix(tests): give budgeted harness tests the shipped agent result budget The test environment seeds the largest agent result budget so spawned processes deliver complete Evidence. In-memory servers built by createApplicationMcpHarness (and connectGhidraMcp, which uses it) inherit process.env too, so a test that chose testDelivery "budgeted" kept the seed: the 600-row list_procedures case and the omitted-detail web page views returned complete Evidence instead of a summary. testDeliveryEnvironment now owns that choice: a budgeted test's server environment drops the seed and uses the shipped default. The application harness applies it to every server it builds. * fix(tests): expect view-implied summary delivery in the Playwright trace refusal A view with no --detail now selects summary delivery, so its refusal names the missing evidence_output bundle; --detail complete still refuses the view. The trace test still expected a view refusal in both cases.
558 lines
17 KiB
TypeScript
558 lines
17 KiB
TypeScript
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
|
import { fileURLToPath } from "node:url";
|
|
|
|
import { z } from "zod";
|
|
|
|
import { waitForExit } from "../process/processFixture.js";
|
|
import {
|
|
completeEvidenceCliArguments,
|
|
type TestDelivery,
|
|
} from "../completeEvidenceByDefault.js";
|
|
import {
|
|
createCliSessionFrameReader,
|
|
encodeCliSessionFrame,
|
|
} from "./cliCommandSessionFrames.mjs";
|
|
|
|
const workerPath = fileURLToPath(
|
|
new URL("./cliCommandSessionWorker.mjs", import.meta.url),
|
|
);
|
|
const SHUTDOWN_GRACE_MS = 1_000;
|
|
/** Restart after this many commands so one file cannot retain every heap. */
|
|
const COMMAND_REUSE_LIMIT = 32;
|
|
/** Restart when the worker reports a resident set at least this large. */
|
|
const RESIDENT_REUSE_LIMIT_BYTES = 1024 * 1024 * 1024;
|
|
|
|
const responseSchema = z.object({
|
|
ready: z.boolean().optional(),
|
|
id: z.number().optional(),
|
|
exitCode: z.number().nullable().optional(),
|
|
stdout: z.string().optional(),
|
|
stderr: z.string().optional(),
|
|
pid: z.number().optional(),
|
|
rss: z.number().finite().nonnegative().optional(),
|
|
fatal: z.boolean().optional(),
|
|
});
|
|
|
|
/** One compiled CLI command sent to the shared process. */
|
|
export interface CliCommandRequest {
|
|
readonly arguments: readonly string[];
|
|
readonly cwd: string;
|
|
readonly environment: Readonly<Record<string, string>>;
|
|
/** The harness requests complete Evidence unless this is `"budgeted"`. */
|
|
readonly delivery?: TestDelivery;
|
|
}
|
|
|
|
/** Captured result from one shared CLI command. */
|
|
export interface CliCommandResult {
|
|
readonly exitCode: number | null;
|
|
readonly signal: NodeJS.Signals | null;
|
|
readonly stdout: string;
|
|
readonly stderr: string;
|
|
readonly json: unknown | undefined;
|
|
}
|
|
|
|
/** File-scoped compiled CLI process. */
|
|
export interface CliCommandSession {
|
|
run(request: CliCommandRequest): Promise<CliCommandResult>;
|
|
/** PID of the live process, when one is running. */
|
|
processId(): number | undefined;
|
|
close(): Promise<void>;
|
|
}
|
|
|
|
interface CliCommandSessionDependencies {
|
|
readonly spawnWorker?: (
|
|
environment: Readonly<Record<string, string>>,
|
|
) => ChildProcessWithoutNullStreams;
|
|
/** Commands served by one process before the next command starts a new one. */
|
|
readonly commandLimit?: number;
|
|
/** Resident-set bytes, reported by the worker, that start a new process. */
|
|
readonly residentLimitBytes?: number;
|
|
/** Optional caller-selected startup and command deadlines; unset by default. */
|
|
readonly startTimeoutMs?: number;
|
|
readonly requestTimeoutMs?: number;
|
|
/** Grace for EOF cleanup and each signal before escalation. */
|
|
readonly shutdownGraceMs?: number;
|
|
}
|
|
|
|
interface PendingCommand {
|
|
readonly id: number;
|
|
readonly resolve: (result: CliCommandResult) => void;
|
|
readonly reject: (error: unknown) => void;
|
|
readonly timer: ReturnType<typeof setTimeout> | undefined;
|
|
}
|
|
|
|
interface RetiredWorker {
|
|
readonly child: ChildProcessWithoutNullStreams;
|
|
attempt: Promise<void> | undefined;
|
|
}
|
|
|
|
type SessionResponse = z.infer<typeof responseSchema>;
|
|
|
|
const closedError = (): Error => new Error("Shared CLI session is closed");
|
|
|
|
const positiveLimit = (value: number | undefined, fallback: number): number =>
|
|
value !== undefined && Number.isSafeInteger(value) && value > 0
|
|
? value
|
|
: fallback;
|
|
|
|
const selectedTimeout = (value: number | undefined): number | undefined =>
|
|
value !== undefined && Number.isSafeInteger(value) && value > 0
|
|
? value
|
|
: undefined;
|
|
|
|
const envKey = (environment: Readonly<Record<string, string>>): string =>
|
|
JSON.stringify(
|
|
Object.keys(environment)
|
|
.sort()
|
|
.map((key) => [key, environment[key]]),
|
|
);
|
|
|
|
const parseCliStdout = (stdout: string): unknown | undefined => {
|
|
const document = stdout.trim();
|
|
if (document.length === 0) return undefined;
|
|
try {
|
|
return JSON.parse(document) as unknown;
|
|
} catch {
|
|
return undefined;
|
|
}
|
|
};
|
|
|
|
const signalChild = (
|
|
child: ChildProcessWithoutNullStreams,
|
|
signal: NodeJS.Signals,
|
|
): void => {
|
|
try {
|
|
child.kill(signal);
|
|
} catch (error) {
|
|
const code =
|
|
error instanceof Error && "code" in error ? error.code : undefined;
|
|
if (code !== "ESRCH") throw error;
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Stop an owned test child process via EOF, SIGTERM, and SIGKILL, throwing
|
|
* when the process still has not exited so the caller retains ownership.
|
|
*/
|
|
export const stopOwnedChildProcess = async (
|
|
child: ChildProcessWithoutNullStreams,
|
|
graceMs: number,
|
|
label = "shared CLI process",
|
|
): Promise<void> => {
|
|
if (child.exitCode !== null || child.signalCode !== null) return;
|
|
if (!child.stdin.writableEnded) child.stdin.end();
|
|
if (await waitForExit(child, graceMs)) return;
|
|
signalChild(child, "SIGTERM");
|
|
if (await waitForExit(child, graceMs)) return;
|
|
if (child.exitCode !== null || child.signalCode !== null) return;
|
|
signalChild(child, "SIGKILL");
|
|
if (await waitForExit(child, graceMs)) return;
|
|
throw new Error(`${label} ${String(child.pid)} did not exit after SIGKILL`);
|
|
};
|
|
|
|
const stopChild = (
|
|
child: ChildProcessWithoutNullStreams,
|
|
graceMs: number,
|
|
): Promise<void> => stopOwnedChildProcess(child, graceMs, "shared CLI process");
|
|
|
|
const commandResult = (message: SessionResponse): CliCommandResult => ({
|
|
exitCode: message.exitCode ?? null,
|
|
signal: null,
|
|
stdout: message.stdout ?? "",
|
|
stderr: message.stderr ?? "",
|
|
json: parseCliStdout(message.stdout ?? ""),
|
|
});
|
|
|
|
const writeChild = (
|
|
child: ChildProcessWithoutNullStreams,
|
|
frame: Buffer,
|
|
): Promise<void> =>
|
|
new Promise((resolve, reject) => {
|
|
child.stdin.write(frame, (error) => {
|
|
if (error) reject(error);
|
|
else resolve();
|
|
});
|
|
});
|
|
|
|
const defaultSpawnWorker = (
|
|
environment: Readonly<Record<string, string>>,
|
|
): ChildProcessWithoutNullStreams =>
|
|
spawn(process.execPath, [workerPath], {
|
|
cwd: process.cwd(),
|
|
env: environment,
|
|
stdio: ["pipe", "pipe", "pipe"],
|
|
});
|
|
|
|
class SharedCliProcess implements CliCommandSession {
|
|
readonly #spawnWorker: (
|
|
environment: Readonly<Record<string, string>>,
|
|
) => ChildProcessWithoutNullStreams;
|
|
|
|
readonly #commandLimit: number;
|
|
readonly #residentLimitBytes: number;
|
|
readonly #startTimeoutMs: number | undefined;
|
|
readonly #requestTimeoutMs: number | undefined;
|
|
readonly #shutdownGraceMs: number;
|
|
#child: ChildProcessWithoutNullStreams | undefined;
|
|
#childEnvKey: string | undefined;
|
|
#commands = 0;
|
|
#residentBytes: number | undefined;
|
|
#retiring: RetiredWorker | undefined;
|
|
#closed = false;
|
|
#closing: Promise<void> | undefined;
|
|
#starting: Promise<void> | undefined;
|
|
#nextId = 1;
|
|
#pending: PendingCommand | undefined;
|
|
#resolveReady: (() => void) | undefined;
|
|
#rejectReady: ((error: unknown) => void) | undefined;
|
|
#queue: Promise<unknown> = Promise.resolve();
|
|
|
|
constructor(dependencies: CliCommandSessionDependencies) {
|
|
this.#spawnWorker = dependencies.spawnWorker ?? defaultSpawnWorker;
|
|
this.#commandLimit = positiveLimit(
|
|
dependencies.commandLimit,
|
|
COMMAND_REUSE_LIMIT,
|
|
);
|
|
this.#residentLimitBytes = positiveLimit(
|
|
dependencies.residentLimitBytes,
|
|
RESIDENT_REUSE_LIMIT_BYTES,
|
|
);
|
|
this.#startTimeoutMs = selectedTimeout(dependencies.startTimeoutMs);
|
|
this.#requestTimeoutMs = selectedTimeout(dependencies.requestTimeoutMs);
|
|
this.#shutdownGraceMs = positiveLimit(
|
|
dependencies.shutdownGraceMs,
|
|
SHUTDOWN_GRACE_MS,
|
|
);
|
|
}
|
|
|
|
run(request: CliCommandRequest): Promise<CliCommandResult> {
|
|
const result = this.#queue.then(async () => {
|
|
const selected =
|
|
request.delivery === "budgeted"
|
|
? request
|
|
: {
|
|
...request,
|
|
arguments: await completeEvidenceCliArguments(
|
|
request.arguments,
|
|
request.cwd,
|
|
),
|
|
};
|
|
return this.#invoke(selected);
|
|
});
|
|
this.#queue = result.then(
|
|
() => undefined,
|
|
() => undefined,
|
|
);
|
|
return result;
|
|
}
|
|
|
|
processId(): number | undefined {
|
|
const child = this.#child;
|
|
if (
|
|
child === undefined ||
|
|
child.exitCode !== null ||
|
|
child.signalCode !== null
|
|
) {
|
|
return undefined;
|
|
}
|
|
return child.pid;
|
|
}
|
|
|
|
close(): Promise<void> {
|
|
this.#closed = true;
|
|
if (this.#closing !== undefined) return this.#closing;
|
|
let attempt: Promise<void>;
|
|
attempt = this.#shutdown().catch((error: unknown) => {
|
|
if (this.#closing === attempt) this.#closing = undefined;
|
|
throw error;
|
|
});
|
|
this.#closing = attempt;
|
|
return attempt;
|
|
}
|
|
|
|
async #shutdown(): Promise<void> {
|
|
const pendingStart = this.#starting;
|
|
this.#failReady(closedError());
|
|
this.#failPending(closedError());
|
|
const owner = this.#child;
|
|
if (owner !== undefined) this.#retire(owner);
|
|
await this.#finishRetirement();
|
|
if (pendingStart !== undefined) await pendingStart.catch(() => undefined);
|
|
}
|
|
|
|
async #invoke(request: CliCommandRequest): Promise<CliCommandResult> {
|
|
if (this.#closed) throw closedError();
|
|
await this.#finishRetirement();
|
|
const current = this.#child;
|
|
if (
|
|
!this.#reusable(current, envKey(request.environment)) &&
|
|
current !== undefined
|
|
) {
|
|
this.#retire(current);
|
|
await this.#finishRetirement();
|
|
}
|
|
if (this.#closed) throw closedError();
|
|
let result: CliCommandResult;
|
|
try {
|
|
if (this.#child === undefined) await this.#start(request.environment);
|
|
result = await this.#run(request);
|
|
} catch (primary) {
|
|
try {
|
|
await this.#finishRetirement();
|
|
} catch (cleanup) {
|
|
const primaryReason =
|
|
primary instanceof Error ? primary.message : String(primary);
|
|
const cleanupReason =
|
|
cleanup instanceof Error ? cleanup.message : String(cleanup);
|
|
throw new AggregateError(
|
|
[primary, cleanup],
|
|
`${primaryReason}; shared CLI cleanup failed: ${cleanupReason}`,
|
|
{ cause: primary },
|
|
);
|
|
}
|
|
throw primary;
|
|
}
|
|
await this.#finishRetirement();
|
|
return result;
|
|
}
|
|
|
|
async #run(request: CliCommandRequest): Promise<CliCommandResult> {
|
|
const owner = this.#child;
|
|
if (this.#closed || owner === undefined) throw closedError();
|
|
const id = this.#nextId;
|
|
this.#nextId += 1;
|
|
const result = new Promise<CliCommandResult>((resolve, reject) => {
|
|
const timer =
|
|
this.#requestTimeoutMs === undefined
|
|
? undefined
|
|
: setTimeout(() => {
|
|
this.#failTransport(
|
|
owner,
|
|
new Error(
|
|
`Shared CLI command did not respond within ${String(this.#requestTimeoutMs)} ms`,
|
|
),
|
|
);
|
|
}, this.#requestTimeoutMs);
|
|
timer?.unref();
|
|
this.#pending = { id, resolve, reject, timer };
|
|
});
|
|
try {
|
|
void writeChild(
|
|
owner,
|
|
encodeCliSessionFrame({
|
|
id,
|
|
arguments: request.arguments,
|
|
cwd: request.cwd,
|
|
env: request.environment,
|
|
}),
|
|
).catch((error: unknown) => {
|
|
this.#failTransport(owner, error);
|
|
});
|
|
} catch (error) {
|
|
this.#failTransport(owner, error);
|
|
}
|
|
return await result;
|
|
}
|
|
|
|
async #finishRetirement(): Promise<void> {
|
|
const retiring = this.#retiring;
|
|
if (retiring === undefined) return;
|
|
retiring.attempt ??= stopChild(
|
|
retiring.child,
|
|
this.#shutdownGraceMs,
|
|
).finally(() => {
|
|
retiring.attempt = undefined;
|
|
});
|
|
await retiring.attempt;
|
|
if (this.#retiring === retiring) this.#retiring = undefined;
|
|
}
|
|
|
|
#reusable(
|
|
current: ChildProcessWithoutNullStreams | undefined,
|
|
key: string,
|
|
): current is ChildProcessWithoutNullStreams {
|
|
if (
|
|
current === undefined ||
|
|
current.exitCode !== null ||
|
|
current.signalCode !== null ||
|
|
this.#childEnvKey !== key
|
|
) {
|
|
return false;
|
|
}
|
|
if (this.#commands >= this.#commandLimit) return false;
|
|
return !(
|
|
this.#residentBytes !== undefined &&
|
|
this.#residentBytes >= this.#residentLimitBytes
|
|
);
|
|
}
|
|
|
|
#start(environment: Readonly<Record<string, string>>): Promise<void> {
|
|
if (this.#closed) return Promise.reject(closedError());
|
|
const started = this.#spawnWorker(environment);
|
|
this.#child = started;
|
|
this.#childEnvKey = envKey(environment);
|
|
this.#commands = 0;
|
|
this.#residentBytes = undefined;
|
|
const ready = new Promise<void>((resolve, reject) => {
|
|
this.#resolveReady = resolve;
|
|
this.#rejectReady = reject;
|
|
});
|
|
this.#starting = ready;
|
|
const timer =
|
|
this.#startTimeoutMs === undefined
|
|
? undefined
|
|
: setTimeout(() => {
|
|
this.#failTransport(
|
|
started,
|
|
new Error(
|
|
`Shared CLI worker did not become ready within ${String(this.#startTimeoutMs)} ms`,
|
|
),
|
|
);
|
|
}, this.#startTimeoutMs);
|
|
timer?.unref();
|
|
this.#watch(started);
|
|
if (this.#closed) {
|
|
this.#failReady(closedError());
|
|
this.#retire(started);
|
|
}
|
|
return ready.finally(() => {
|
|
clearTimeout(timer);
|
|
if (this.#starting === ready) this.#starting = undefined;
|
|
});
|
|
}
|
|
|
|
#watch(started: ChildProcessWithoutNullStreams): void {
|
|
const reader = createCliSessionFrameReader((frame) => {
|
|
this.#onFrame(started, frame);
|
|
});
|
|
started.stdout.on("data", (chunk: Buffer) => {
|
|
try {
|
|
reader(chunk);
|
|
} catch (error) {
|
|
this.#failTransport(started, error);
|
|
}
|
|
});
|
|
started.stdout.once("end", () => {
|
|
try {
|
|
reader.finish();
|
|
} catch (error) {
|
|
this.#failTransport(started, error);
|
|
}
|
|
});
|
|
started.stderr.resume();
|
|
started.stdin.on("error", (error) => {
|
|
this.#failTransport(started, error);
|
|
});
|
|
started.once("error", (error) => {
|
|
this.#failTransport(started, error);
|
|
});
|
|
started.once("close", (code, signal) => {
|
|
this.#onClose(started, code, signal);
|
|
});
|
|
}
|
|
|
|
#onFrame(owner: ChildProcessWithoutNullStreams, value: unknown): void {
|
|
if (this.#child !== owner || this.#closed) return;
|
|
const parsed = responseSchema.safeParse(value);
|
|
if (!parsed.success) {
|
|
this.#failTransport(
|
|
owner,
|
|
new Error("CLI session response was not a command result"),
|
|
);
|
|
return;
|
|
}
|
|
const message = parsed.data;
|
|
if (message.ready === true && message.id === undefined) {
|
|
const resolve = this.#resolveReady;
|
|
this.#resolveReady = undefined;
|
|
this.#rejectReady = undefined;
|
|
resolve?.();
|
|
return;
|
|
}
|
|
const current = this.#pending;
|
|
if (current === undefined || message.id !== current.id) {
|
|
this.#failTransport(
|
|
owner,
|
|
new Error("CLI session response did not match the command"),
|
|
);
|
|
return;
|
|
}
|
|
if (message.exitCode === undefined) {
|
|
this.#failTransport(
|
|
owner,
|
|
new Error("CLI session response omitted its exit code"),
|
|
);
|
|
return;
|
|
}
|
|
this.#pending = undefined;
|
|
clearTimeout(current.timer);
|
|
if (message.fatal === true) {
|
|
this.#retire(owner);
|
|
} else {
|
|
this.#commands += 1;
|
|
if (message.rss !== undefined) this.#residentBytes = message.rss;
|
|
}
|
|
current.resolve(commandResult(message));
|
|
}
|
|
|
|
#retire(owner: ChildProcessWithoutNullStreams): void {
|
|
if (this.#child === owner) {
|
|
this.#child = undefined;
|
|
this.#childEnvKey = undefined;
|
|
}
|
|
this.#commands = 0;
|
|
this.#residentBytes = undefined;
|
|
this.#retiring ??= { child: owner, attempt: undefined };
|
|
}
|
|
|
|
#onClose(
|
|
owner: ChildProcessWithoutNullStreams,
|
|
code: number | null,
|
|
signal: NodeJS.Signals | null,
|
|
): void {
|
|
if (this.#child !== owner) return;
|
|
this.#child = undefined;
|
|
this.#childEnvKey = undefined;
|
|
const error = this.#closed
|
|
? closedError()
|
|
: new Error(
|
|
`Shared CLI process exited (${String(code ?? signal ?? "unknown")})`,
|
|
);
|
|
this.#failReady(error);
|
|
this.#failPending(error);
|
|
}
|
|
|
|
#failTransport(owner: ChildProcessWithoutNullStreams, error: unknown): void {
|
|
if (this.#child !== owner) return;
|
|
this.#failReady(error);
|
|
this.#failPending(error);
|
|
// Clear the worker before the queued command runs. SIGTERM does not set
|
|
// signalCode until the process actually exits, so #reusable would still
|
|
// accept this process and write into it.
|
|
this.#retire(owner);
|
|
}
|
|
|
|
#failPending(error: unknown): void {
|
|
const current = this.#pending;
|
|
this.#pending = undefined;
|
|
clearTimeout(current?.timer);
|
|
current?.reject(error);
|
|
}
|
|
|
|
#failReady(error: unknown): void {
|
|
const reject = this.#rejectReady;
|
|
this.#resolveReady = undefined;
|
|
this.#rejectReady = undefined;
|
|
reject?.(error);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Keep one compiled CLI process for commands that share an environment.
|
|
* The process restarts after its command limit, after a reported resident-set
|
|
* limit, when the environment changes, or when a command fails fatally.
|
|
*/
|
|
export const createCliCommandSession = (
|
|
dependencies: CliCommandSessionDependencies = {},
|
|
): CliCommandSession => new SharedCliProcess(dependencies);
|