Files
rea/src/application/reverse/ReverseEngineeringService.ts
T
ezan 69a2faa120 feat: add FreeBuff agent support for REA setup (#2736)
* feat: add FreeBuff agent support for REA setup

Register FreeBuff as a supported setup client using the shared user
agents directory (~/.agents/mcp.json with mcpServers, skills in
~/.agents/skills), which matches what FreeBuff Desktop loads. Adds the
client definition, boundary tests, supported-agent docs, and the skill
reference client list.

* fix(freebuff): detect FreeBuff from its profile directory, not shared .agents

The ~/.agents marker made FreeBuff appear installed for any home where
REA had installed shared skills (the default skill destination, also
Gemini CLI's), producing false doctor failures. Detect FreeBuff from
its own fixed profile directory ~/.config/freebuff-desktop instead,
and add a regression test covering a home with only the shared agents
skill directory.

* fix(setup): require product evidence for FreeBuff discovery

Address review findings at their producing boundaries and preserve directly affected consumers. Source inspection and git diff --check completed. Tests and automated checks were not run at the user’s explicit request.

* fix(uninstall): retain unverified shared client configuration

* fix(clients): preserve scoped removal evidence

* fix(doctor): omit undefined selectedClientIds under exactOptionalPropertyTypes

Passing selectedClientIds explicitly as undefined fails typecheck on this
branch (TS2379), which blocks the focused test workflow before any test
can run. Spread the option only when defined.

* fix(update): separate ownership evidence from product applicability

rea update's maintenance scope inspected only product applicability
evidence, so when a FreeBuff profile was absent but REA already owned a
version-pinned row in the shared ~/.agents/mcp.json, the plan omitted
freebuff and left the integration stale. FreeBuff now declares its
registration storage as shared, which proves ownership of an owned row
but never product applicability, and maintenance requests ownership
evidence through that declaration instead of reinterpreting the shared
paths. Doctor and setup keep readiness evidence, foreign rows stay out
of maintenance, and the Doctor exactOptionalPropertyTypes fix makes the
focused test workflow runnable.

* test(dotnet): split oversized operand extent diagnostics describe

The describe callback reached 162 lines (max 150), failing
max-lines-per-function and blocking the pre-push check for this branch.
Move the single-case extent scenarios into their own describe; no test
content or order changes.

* fix(update): preserve ZCode's disabled shared registration during maintenance

The shared user agents file doubles as ZCode's fallback, where
`enable: false` disables the registration. Ownership-based maintenance
read that row as a FreeBuff registration, whose format does not
recognize the flag, so the row was selected and the emitted setup
command rewrote it, dropping the flag and silently re-enabling a
registration the user had disabled.

registrationActivation now honors `enable: false` for any client whose
registration storage is shared, because the activation fact binds every
reader of that storage. Maintenance leaves such rows out; doctor
reports them as stale, matching ZCode's own treatment.

* fix(doctor): let explicit client selection authorize the config read

When an ACL or an inaccessible shared parent made every access probe
fail, a client selected by name was omitted before the configuration
read could return its unreadable-config detail, so doctor reported it
as not detected with installation remediation: an unresolved selected
path collapsed to absence.

An explicit selection now authorizes the read outright and the probes
serve automatic discovery only. A selected client with an unreadable
config reports invalid with the read failure; one with no config
reports missing; automatic discovery still probes before inspecting.

* fix(uninstall): share shared-storage checks between ZCode and FreeBuff

clients() queued ~/.agents/mcp.json twice: once as zcode_fallback and once
as freebuff. ZCode has no discoveryPaths, so its strict read still blocked
uninstall on malformed shared text, despite FreeBuff's new retain-and-continue
behavior. For a valid owned entry, ZCode removed it first, so FreeBuff reported
skipped rather than removed.

Make the shared file's checks and removal one shared decision:
- Add zcodeDiscoveryPaths to ZCode so it has its own applicability evidence.
- Gate zcode_fallback push on applicable, not just zcodeFallbackPath presence.
- Report shared storage ownership as one decision for both clients:
  FreeBuff and ZCode now use clientOwnershipEvidencePaths together, so a
  recognizable REA-owned row proves ownership once for the shared storage, and
  both clients report the same result consistently.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(uninstall): merge duplicated host and prove shared ownership from owned rows

Uninstall.ts declared systemUninstallHost twice, preventing module load,
with the exported copy returning only clients and the second copy missing
clientWriteBlocker. Merge into one exported host carrying both blockers.

hasOwnershipEvidence used access() existence, so an unrelated malformed
~/.agents/mcp.json established ownership and blocked every removal.
Ownership now requires a readable, recognizable REA-owned row via the
injected filesystem, so unrelated shared data stays retained.

Also cover ZCode discoveryPaths in its path test.

* fix(uninstall): keep denied product-local configurations fail-closed

Unproven product applicability marked every configuration path of that client unverified, so a denied ZCode profile turned an unreadable product-local config into a retained item: uninstall continued and could report complete with REA still registered. The retain-and-continue exception now applies only to storage REA does not own, classified once by clientSharedRegistrationPaths (shared configuration plus another product's same-scope fallback).

Covers the Greptile P1 on Uninstall.ts. Validation: the new test fails on the pre-fix Uninstall and passes after it; freebuff/zcode/updateMaintenance/bom/dsh suites green; clientLifecycle, clientRegistrationStatus and claudeDesktop keep the same 8 host failures as the pre-merge baseline (symlink EPERM, stale-vs-aligned on Windows).

* fix(update): retain FreeBuff when ZCode reads the shared fallback

Maintenance deduplicated clients on the path each inspection read, so ZCode's fallback view of ~/.agents/mcp.json marked that file "covered" and dropped FreeBuff from the scope. ZCode setup writes ~/.zcode/cli/config.json and deliberately leaves the fallback untouched (docs/client-configuration.md), so the emitted command refreshed only ZCode while the shared row both products load stayed pinned to the old package version. Each setup action rewrites only its own configuration path and no other action rewrites the shared row, so every selected client keeps its own maintenance action; the read-path covered/deduped filter is removed.

Covers the Codex P2 on UpdateMaintenance.ts:104. Validation: the new regression fails on e2fdec384 with {clients:["zcode"]} and passes with {clients:["freebuff","zcode"]}; updateMaintenance 31/31, setupClientConfigCleanupOwnership, cliUpdateAlias, updateOutput, cliStartupImports green; tsc --noEmit, oxlint (0 errors) and oxfmt --check clean; clientRegistrationStatus keeps the same 4 symlink/stale-vs-aligned failures this Windows host has on base e2fdec384 (verified by stashing the change).

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>

* fix(uninstall): preserve completed reads as shared ownership evidence

hasOwnershipEvidence caught every read failure and kept scanning, so a handle-close failure after a successful read — a RegularFileCleanupFailure whose completed outcome still contains the exact shared-file text — was discarded as "no proof". FreeBuff's applicability-unverified storage therefore never got its ownership fact, and once the retained handle blocked later reads, readClientConfiguration downgraded them to retained: inspection passed, removals soft-failed, and runUninstall(true) could purge REA data while the active shared registration remained. The catch now parses the completed outcome for the ownership text while missing or unreadable storage and malformed data keep their proves-nothing semantics, so ownership holds and every later read failure stays blocking.

Covers the Codex P2 on Uninstall.ts:252. Validation: the new regression fails on 4dbfdf1a9 (freebuff reports no blocking failure while the poisoned-scope error lands on claude_code) and passes after; setupClientConfigCleanupOwnership 25/25; the other 21 Uninstall-consumer suites are byte-identical to base 4dbfdf1a9 (61 pre-existing Windows-host failures: symlink EPERM, stale-vs-aligned); tsc --noEmit, oxlint (0 errors, same 6 warnings) and oxfmt --check clean.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>

* fix(uninstall): keep owned-row proof through removal refusals

hasOwnershipEvidence treated any clientRegistrationRemoval refusal as no ownership: an effective REA-owned rea member shadowed by an earlier foreign duplicate (shadowed_unowned_member), or an owned native row beside a foreign V1 fallback (foreign_legacy_fallback), discarded the already-parsed positive row fact. With FreeBuff unverified and close failures recurring on the preflight/removal rereads, those failures were then downgraded to retained, so runUninstall(true) removed the skill and purged REA data while the active owned row remained. The refusal now carries the owned rows that motivated it — the refusal only refuses the edit — and hasOwnershipEvidence evaluates that fact on both paths; preflight and removal keep refusing the unsafe edit exactly as before.

Covers the Codex P2 on Uninstall.ts:269. Validation: the new regression fails on 225cb214a (freebuff reports no blocking failure while the poisoned-scope error lands on claude_code) and passes after; setupClientConfigCleanupOwnership 26/26; the 21 Uninstall-consumer suites are byte-identical to the recorded 225cb214a baseline (61 pre-existing Windows-host failures: symlink EPERM, stale-vs-aligned); tsc --noEmit, oxlint (0 errors, same 6 warnings) and oxfmt --check clean.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>

* fix(uninstall): keep unresolved discovery probes from softening shared failures

The discovery probe swallowed every stat failure, so a FreeBuff profile denied with EACCES/EIO was indistinguishable from an absent profile: shared storage was marked applicability-unverified and, when ~/.agents/mcp.json also remained unreadable, the ownership and removal reads softened to retained. runUninstall(true) then removed the skill and purged REA data while an installed FreeBuff could still hold an active registration — the regression even reports complete. Absence (ENOENT) is now the only state that leaves shared paths unverified; any other probe failure leaves applicability unresolved, and shared-config failures stay blocking.

Covers the Codex P2 on Uninstall.ts:318. Validation: the new regression fails on 7572a7082 with status complete and purged data and passes after; freebuffClientConfiguration 13/13; the Uninstall-consumer batches are byte-identical to the recorded baselines (61 pre-existing Windows-host failures: symlink EPERM, stale-vs-aligned); tsc --noEmit, oxlint (0 errors, same warning rules) and oxfmt --check clean.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>

* fix(uninstall): retain completed configuration reads as removal evidence

A close failure after a completed read discarded the text that read
produced, so an owned registration row the text proves softened to
retained. The completed text now drives removal, keeping shared-config
failures blocking when ownership evidence exists.

Co-Authored-By: Anthropic <noreply@anthropic.com>

* fix(uninstall): stop removal when a cleanup retry leaves a handle unreleased

A completed reread whose handle the cleanup retry cannot release now fails
blockingly instead of serving the text: with no owned row, the soft path
let removeAll purge managed data before close() reported the incomplete
cleanup. The completed text is served only after the retry releases the
handle; an unreleased handle is REA's own failure, never applicability
uncertainty, so it bypasses the retained softening.

Co-Authored-By: Anthropic <noreply@anthropic.com>

* fix(uninstall): keep the ZCode fallback when its profile probe is unresolved

A denied or failed profile probe leaves ZCode's applicability unresolved,
never absent, but the fallback branch dropped the shared row on
applicability alone: with the native config and FreeBuff's profile both
absent, an installed ZCode kept its uninspected registration while
uninstall purged skill and data. Unresolved probes now keep the fallback
in scope with the same fail-closed treatment as other unresolved shared
paths; definitive absence still keeps ZCode out of another product's
primary storage.

Co-Authored-By: Anthropic <noreply@anthropic.com>

* fix(setup): preserve a shared row's enable:false during FreeBuff repair

The shared agents file doubles as ZCode's fallback, so its `enable: false`
binds every reader: doctor now reports the disabled row as stale for
FreeBuff, but following that remediation rebuilt the generic JSON entry
without the flag and silently re-enabled a registration ZCode disabled.
Repairs of shared storage now carry the activation fact forward, while a
client's own native storage keeps its established single-reader repair
contract; the denied-profile uninstall regression also pins the
fallback's new fail-closed inspection beside the denied read.

Co-Authored-By: Anthropic <noreply@anthropic.com>

* test(uninstall): retarget the completed-reread regression to a released retry

The concurrent-writer regression held the reread handle open forever,
which the fail-closed path now serves: it duplicated the unreleased-handle
regression while documenting the opposite contract. The fixture's close
spy gains a failure limit so the cleanup retry releases the handle, and
the test again proves the completed text drives removal of the
concurrently added owned row, with purge verified against the cache
layout purge actually removes.

Co-Authored-By: Anthropic <noreply@anthropic.com>

* fix(doctor): report a preserved shared disable as a manual conflict

Preserving a shared row's enable:false left doctor recommending a setup
run that registrationCurrent correctly treats as already current, so the
scoped doctor returned needs_human forever. The shared-enable
interpretation now has one owner, sharedEnableFlagBinds, used by both
the activation rule and the remediation: a row disabled through the
shared flag reports the manual conflict and states that rea setup will
not change it, instead of an endlessly ineffective repair.

Co-Authored-By: Anthropic <noreply@anthropic.com>

* fix(doctor): keep a native ZCode disable on the setup repair path

The manual-conflict remediation matched a native zcode row through
sharedEnableFlagBinds, but setup drops enable:false on single-reader
storage, so a native disabled registration was told setup would not
change it. The remediation now reads setup's own writer rule,
exported as setupPreservesDisabledActivation: shared storage and the
zcode fallback view keep the manual-conflict message, while a native
row keeps the working rea setup instruction. Regressions pin both
remediations.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>

* revert: drop the unrelated managed-CIL describe split

The split does not belong to FreeBuff client support and only widens this
PR's diff.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>

* fix(uninstall): remove the shared agent registration once for both clients

ZCode's ~/.agents/mcp.json fallback and FreeBuff's own configuration queued the
same physical file twice, so ZCode removed the row and FreeBuff then reported
it absent, losing the outcome for the client that owns the file.

Resolve every configuration path to one owner -- the client whose
configuration it is -- and project that single inspection and removal to each
client that loads it. A fallback reader still contributes its discovery probe,
so an installed or unresolved reader keeps the shared file fail-closed.

Discovery also accepted a dangling ~/.config/freebuff-desktop link, which setup
and doctor reject because they follow the target, so an unrelated malformed
shared file blocked every other removal. Resolve the link before treating the
profile as installation evidence, keeping lstat for removal safety.

Also date the FreeBuff release wording against the published 6.7.0 package.

* fix(uninstall): keep a row per client when two clients own one file

OPENCODE_CONFIG can point OpenCode at FreeBuff's configuration file, where
OpenCode writes `mcp.rea` and FreeBuff writes `mcpServers.rea`. Grouping by
filename gave that path a single owner, so uninstall removed only OpenCode's
row, reported that removal for FreeBuff, and could purge managed data with
FreeBuff's registration still active.

Share the decision only through a fallback view of another client's row: every
client that declares the path as its own configuration keeps its own
inspection and removal, and the fallback reader reports each of them.

* fix(clients): preserve discovery and fallback registration identity

Follow product discovery link targets without losing configuration entry
presence or explicitly selected inspections. Associate fallback readers with
the format owner's registration table and project outcomes by owner and path,
so OpenCode removal cannot be reported as a ZCode fallback removal.

All three new boundary regressions fail against the previous source and pass
with the fixes. Validation: check:fast; 217 focused tests passed; the two
changed test files were rerun with 50 passing tests. No installed FreeBuff
client was launched.

---------

Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>
Co-authored-by: Codebuff <noreply@codebuff.com>
2026-10-25 11:29:17 +08:00

1199 lines
42 KiB
TypeScript

import { createHash, randomUUID } from "node:crypto";
import { createReadStream } from "node:fs";
import { stat as statPath } from "node:fs/promises";
import type { Stats } from "node:fs";
import {
requireAnalysisViewRetention,
summarizeRetainedAnalysis,
type AnalysisViewRetention,
} from "../analysisView/AnalysisViewService.js";
import {
AnalysisAccessDeniedError,
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
AnalysisInputError,
AnalysisResourceConstraintError,
AnalysisTimeoutError,
AnalysisOutputError,
} from "../../domain/analysisErrorCore.js";
import {
AnalysisError,
type AnalysisCleanupObservation,
} from "../../domain/analysisErrorBase.js";
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
import { createEvidence, type Evidence } from "../../domain/evidence.js";
import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js";
import type { JsonValue } from "../../domain/jsonValue.js";
import { err, ok, type Result } from "../../domain/result.js";
import {
DEFAULT_REVERSE_COMMAND_TIMEOUT_MS,
MAX_REVERSE_COMMAND_TIMEOUT_MS,
objdumpInputSchema,
rizinInputSchema,
type RizinInput,
} from "../../domain/reverseEngineering.js";
import type {
ReverseEngineeringCommandPort,
ReverseEngineeringProviderCommand,
} from "./ReverseEngineeringCommandPort.js";
import {
execFileOutput,
execFileOutputFailure,
} from "../../process/ExecFileOutput.js";
import {
OwnedCommandFailure,
runOwnedCommand,
} from "../../process/OwnedCommand.js";
import type { ProviderProcessSupervisor } from "../../process/ProviderProcess.js";
import { absoluteCallerPath } from "../../filesystem/callerPath.js";
export type ReverseEngineeringOperation =
| "inspect_with_objdump"
| "execute_rizin_command";
const MAX_COMBINED_OUTPUT_BYTES = 16 * 1024 * 1024;
// Eight concurrent captures bound retained provider output to 128 MiB.
const MAX_CONCURRENT_REVERSE_ENGINEERING_OPERATIONS = 8;
export interface ReverseEngineeringServiceOptions {
readonly environment?: Readonly<NodeJS.ProcessEnv>;
readonly commands: ReverseEngineeringCommandPort;
readonly run?: ReverseEngineeringCommandRunner;
readonly runOwned?: typeof runOwnedCommand;
readonly digest?: typeof digestFile;
readonly stat?: (path: string) => Promise<Stats>;
}
interface ReverseEngineeringCommandRunner {
(
command: string,
arguments_: readonly string[],
options?: Parameters<typeof execFileOutput>[2],
): Promise<{
readonly stdout: string;
readonly stderr: string;
readonly stdoutInvalidUtf8?: boolean;
readonly stderrInvalidUtf8?: boolean;
readonly stdoutBytes?: number;
readonly stderrBytes?: number;
readonly outputTruncated?: boolean;
}>;
}
export type ReverseEngineeringServiceRuntimeOptions = Omit<
ReverseEngineeringServiceOptions,
"commands" | "environment"
>;
/** Resolve one command for shared execution and adapter admission decisions. */
export const resolveRizinCommandRequest = (
input: unknown,
): Result<RizinInput, AnalysisInputError> => {
const parsed = rizinInputSchema.safeParse(input);
return parsed.success
? ok(parsed.data)
: err(
analysisInputErrorFromIssues(
"execute_rizin_command",
parsed.error.issues,
input,
{ cause: parsed.error },
),
);
};
/** Shared application workflow for caller-selected local analysis commands. */
export class ReverseEngineeringService {
readonly #environment: Readonly<NodeJS.ProcessEnv>;
readonly #commands: ReverseEngineeringCommandPort;
readonly #run: ReverseEngineeringCommandRunner;
readonly #digest: typeof digestFile;
readonly #stat: (path: string) => Promise<Stats>;
readonly #pendingCleanup = new Map<
ProviderProcessSupervisor,
{
readonly observation: AnalysisCleanupObservation;
readonly failures: Set<AnalysisError>;
readonly retryFailure?: AnalysisError;
}
>();
readonly #activeOperations = new Map<
AbortController,
Promise<Result<Evidence, AnalysisError>>
>();
#closing = false;
#closePromise: Promise<void> | undefined;
constructor(options: ReverseEngineeringServiceOptions) {
this.#environment = { ...(options.environment ?? process.env) };
this.#commands = options.commands;
this.#run =
options.run ??
runOwnedCommandOutput(
options.runOwned ?? runOwnedCommand,
(owner, cleanup) =>
this.#pendingCleanup.set(owner, {
observation: cleanup,
failures: this.#pendingCleanup.get(owner)?.failures ?? new Set(),
}),
);
this.#digest = options.digest ?? digestFile;
this.#stat = options.stat ?? statPath;
}
/** Ask retained process owners to settle cleanup before admitting more work. */
async retryCleanup(
operation = "reverse_engineering_cleanup",
): Promise<Result<null, AnalysisError>> {
let failure: AnalysisError | undefined;
for (const [owner, retained] of this.#pendingCleanup) {
let stopped: Awaited<ReturnType<ProviderProcessSupervisor["stop"]>>;
try {
stopped = await owner.stop();
} catch (cause) {
stopped = {
status: "incomplete",
reason: cause instanceof Error ? cause.message : String(cause),
};
}
if (stopped.status === "incomplete") {
const observation = {
reason: stopped.reason,
resources: retained.observation.resources,
};
let retryFailure = retained.retryFailure;
if (retryFailure === undefined) {
retryFailure = new AnalysisOutputError(
operation,
"A previous provider process still requires cleanup.",
{ cleanup: observation },
);
retained.failures.add(retryFailure);
}
this.#pendingCleanup.set(owner, {
observation,
failures: retained.failures,
retryFailure,
});
if (failure === undefined) failure = retryFailure;
} else {
for (const previous of retained.failures) previous.resolveCleanup();
this.#pendingCleanup.delete(owner);
}
}
return failure === undefined ? ok(null) : err(failure);
}
/** Retry cleanup for provider process groups retained after an incomplete stop. */
close(): Promise<void> {
this.#closing = true;
this.#closePromise ??= this.#closeActiveOperationsAndCleanup().catch(
(cause: unknown) => {
this.#closePromise = undefined;
throw cause;
},
);
return this.#closePromise;
}
async #closeActiveOperationsAndCleanup(): Promise<void> {
const active = [...this.#activeOperations.entries()];
for (const [controller] of active) controller.abort();
await Promise.allSettled(active.map(([, operation]) => operation));
const cleanup = await this.retryCleanup();
if (!cleanup.ok) throw cleanup.error;
}
async inspectWithObjdump(
rawInput: unknown,
options: { readonly signal?: AbortSignal } = {},
retention: AnalysisViewRetention = {
evidenceById: undefined,
recordEvidence: undefined,
},
): Promise<Result<Evidence, AnalysisError>> {
const parsed = objdumpInputSchema.safeParse(rawInput);
if (!parsed.success)
return err(
analysisInputErrorFromIssues(
"inspect_with_objdump",
parsed.error.issues,
rawInput,
{ cause: parsed.error },
),
);
const {
detail,
command_timeout_ms: commandTimeoutMs,
...input
} = parsed.data;
if (detail === "summary") {
const ready = requireAnalysisViewRetention(
"inspect_with_objdump",
retention,
);
if (!ready.ok) return ready;
}
const command = this.#commands.objdump(input);
let parameters: Readonly<Record<string, JsonValue>>;
if (input.operation === "disassemble") {
const { symbol, ...base } = input;
parameters = symbol === undefined ? base : { ...base, symbol };
} else parameters = input;
if (commandTimeoutMs !== undefined)
parameters = { ...parameters, command_timeout_ms: commandTimeoutMs };
const observed = await this.#observe(
"inspect_with_objdump",
command,
input.operation === "architectures" ? undefined : input.path,
parameters,
options.signal,
commandTimeoutMs ?? DEFAULT_REVERSE_COMMAND_TIMEOUT_MS,
);
return observed.ok && detail === "summary"
? summarizeRetainedAnalysis(observed.value, retention)
: observed;
}
executeRizinCommand(
rawInput: unknown,
options: { readonly signal?: AbortSignal } = {},
): Promise<Result<Evidence, AnalysisError>> {
const parsed = resolveRizinCommandRequest(rawInput);
return parsed.ok
? this.executeRizinCommandValidated(parsed.value, options)
: Promise.resolve(parsed);
}
/** Execute owner-validated input after the adapter has admitted its target. */
executeRizinCommandValidated(
request: RizinInput,
options: { readonly signal?: AbortSignal } = {},
): Promise<Result<Evidence, AnalysisError>> {
const { command_timeout_ms: commandTimeoutMs, ...input } = request;
const command = this.#commands.rizin(input);
return this.#observe(
"execute_rizin_command",
command,
input.path,
commandTimeoutMs === undefined ? input : request,
options.signal,
commandTimeoutMs ?? DEFAULT_REVERSE_COMMAND_TIMEOUT_MS,
);
}
#observe(
operation: ReverseEngineeringOperation,
profile: ReverseEngineeringProviderCommand,
path: string | undefined,
parameters: Readonly<Record<string, JsonValue>>,
signal: AbortSignal | undefined,
timeoutMs: number,
): Promise<Result<Evidence, AnalysisError>> {
if (signal?.aborted)
return Promise.resolve(
err(new AnalysisCancelledError(operation, { cause: signal.reason })),
);
if (this.#closing)
return Promise.resolve(
err(
new AnalysisOutputError(
operation,
"Reverse-engineering service is closed.",
),
),
);
if (
this.#activeOperations.size >=
MAX_CONCURRENT_REVERSE_ENGINEERING_OPERATIONS
)
return Promise.resolve(
err(
new AnalysisResourceConstraintError(
operation,
"transport",
`Concurrent reverse-engineering operation capacity reached (${String(MAX_CONCURRENT_REVERSE_ENGINEERING_OPERATIONS)} operations). This release has no runtime override.`,
{
max_concurrent_operations:
MAX_CONCURRENT_REVERSE_ENGINEERING_OPERATIONS,
active_operations: this.#activeOperations.size,
},
{
remediationAction: `Wait for an active objdump or rizin command to finish, then retry. This capacity of ${String(MAX_CONCURRENT_REVERSE_ENGINEERING_OPERATIONS)} operations has no runtime override, and command_timeout_ms does not raise it.`,
},
),
),
);
const controller = new AbortController();
const relayAbort = (): void => controller.abort(signal?.reason);
if (signal instanceof AbortSignal) {
if (signal.aborted) relayAbort();
else signal.addEventListener("abort", relayAbort, { once: true });
}
const operationSignal =
signal === undefined || signal instanceof AbortSignal
? controller.signal
: signal;
const running = this.#observeProvider(
operation,
profile,
path,
parameters,
operationSignal,
timeoutMs,
);
const tracked = running.finally(() => {
signal?.removeEventListener("abort", relayAbort);
this.#activeOperations.delete(controller);
});
this.#activeOperations.set(controller, tracked);
return tracked;
}
async #observeProvider(
operation: ReverseEngineeringOperation,
profile: ReverseEngineeringProviderCommand,
path: string | undefined,
parameters: Readonly<Record<string, JsonValue>>,
signal: AbortSignal | undefined,
timeoutMs: number,
): Promise<Result<Evidence, AnalysisError>> {
const { executable: command, arguments: args } = profile;
if (signal?.aborted)
return err(
new AnalysisCancelledError(operation, { cause: signal.reason }),
);
const cleanup = await this.retryCleanup(operation);
if (!cleanup.ok) return cleanup;
const absolutePath =
path === undefined ? undefined : absoluteCallerPath(path);
let digest: string | undefined;
try {
if (absolutePath !== undefined)
digest = await this.#digest(
absolutePath,
signal,
this.#stat,
timeoutMs,
);
} catch (cause) {
const code = commandFailureCode(cause);
if (preflightCancelled(signal, cause, code))
return err(
new AnalysisCancelledError(operation, {
cause: callerCancellationCause(signal, cause),
}),
);
if (code === "EACCES" || code === "EPERM") {
const deniedPath = absolutePath === undefined ? command : absolutePath;
return err(
new AnalysisAccessDeniedError(operation, deniedPath, code, {
cause,
}),
);
}
if (code === "ETIMEDOUT")
return err(
new AnalysisTimeoutError(operation, timeoutMs, {
cause,
...reverseCommandTimeoutGuidance(timeoutMs),
}),
);
if (
code !== "ENOENT" &&
code !== "ENOTDIR" &&
code !== "EINVAL" &&
code !== "ELOOP" &&
code !== "ENAMETOOLONG"
) {
if (cause instanceof AnalysisError) return err(cause);
return err(
new ProviderAdapterError(profile.identity.id, operation, {
cause,
diagnostics: {
phase: "target_preflight",
...(code === undefined ? {} : { system_code: code }),
},
}),
);
}
const targetReason =
code === "EINVAL"
? "The selected target is not a regular file."
: code === "ELOOP"
? "The selected target path contains a symbolic-link loop."
: code === "ENAMETOOLONG"
? "The selected target path is too long."
: "The selected target was not found.";
return err(
new AnalysisInputError(
operation,
{
cause,
userMessage: `${targetReason} Selected path: ${absolutePath}. Check the path and choose a readable regular file before retrying.`,
},
[
{
path: ["path"],
reason: "invalid_value",
message: `${targetReason}${code === undefined ? "" : ` (host error ${code})`}`,
},
],
),
);
}
let stdout = "";
let stderr = "";
let stdoutBytes = 0;
let stderrBytes = 0;
let exitCode: number | string | null = 0;
let signalName: string | null = null;
let outputTruncated = false;
let stdoutInvalidUtf8 = false;
let stderrInvalidUtf8 = false;
let cleanupIncomplete = false;
let cleanupOnlyFailure = false;
let completionStatus: "complete" | "unknown" = "complete";
let failure: AnalysisError | undefined;
let cleanupOwner: ProviderProcessSupervisor | undefined;
let earlyFailure: AnalysisError | undefined;
try {
const output = await this.#run(command, args, {
env: {
...this.#environment,
...profile.environmentOverrides,
},
signal,
timeout: timeoutMs,
stopSignal: "SIGTERM",
maxBuffer: MAX_COMBINED_OUTPUT_BYTES,
});
stdout = output.stdout;
stderr = output.stderr;
stdoutBytes = output.stdoutBytes ?? Buffer.byteLength(stdout);
stderrBytes = output.stderrBytes ?? Buffer.byteLength(stderr);
stdoutInvalidUtf8 = output.stdoutInvalidUtf8 === true;
stderrInvalidUtf8 = output.stderrInvalidUtf8 === true;
outputTruncated = output.outputTruncated === true;
} catch (cause) {
cleanupOwner =
cause instanceof OwnedOutputFailure ? cause.cleanupOwner : undefined;
if (
cause instanceof OwnedOutputFailure &&
cause.capabilityError !== undefined
)
earlyFailure = new AnalysisCapabilityUnavailableError(
cause.capabilityError.providerId,
cause.capabilityError.operation,
cause.capabilityError.reason,
{
cause: cause.capabilityError,
...(cause.capabilityError.diagnostics === undefined
? {}
: { diagnostics: cause.capabilityError.diagnostics }),
...(cause.capabilityError.capturedOutput === undefined
? {}
: { capturedOutput: cause.capabilityError.capturedOutput }),
...(cause.capabilityError.partialObservation === undefined
? {}
: {
partialObservation: cause.capabilityError.partialObservation,
}),
...(cause.capabilityError.userMessage === undefined
? {}
: { userMessage: cause.capabilityError.userMessage }),
retryable: cause.capabilityError.retryable,
...ownedCleanupOptions(cause),
},
);
const capture = execFileOutputFailure(cause);
const code = capture?.code ?? commandFailureCode(cause);
if (earlyFailure === undefined && code === "E2BIG")
earlyFailure = new AnalysisResourceConstraintError(
operation,
"transport",
"The host rejected the provider command because its argument list exceeds the process launch limit.",
{
argument_bytes: args.reduce(
(bytes, argument, index) =>
bytes + Buffer.byteLength(argument) + (index === 0 ? 0 : 1),
0,
),
},
{ cause, ...ownedCleanupOptions(cause) },
);
if (
earlyFailure === undefined &&
(capture === undefined ||
(cause instanceof OwnedOutputFailure && cause.launchFailure) ||
code === "ENOENT" ||
code === "EACCES" ||
code === "EPERM" ||
code === "ERR_PROVIDER_LAUNCH")
) {
if (commandCancelled(signal, cause, code))
earlyFailure = new AnalysisCancelledError(operation, {
cause: callerCancellationCause(signal, cause),
...ownedCleanupOptions(cause),
});
else if (code === "ETIMEDOUT")
earlyFailure = new AnalysisTimeoutError(operation, timeoutMs, {
cause,
...ownedCleanupOptions(cause),
...reverseCommandTimeoutGuidance(timeoutMs),
});
else {
const provider =
operation === "inspect_with_objdump" ? "objdump" : "rizin";
const setting =
provider === "objdump"
? "REA_OBJDUMP_COMMAND"
: "REA_RIZIN_COMMAND";
earlyFailure = new AnalysisCapabilityUnavailableError(
provider,
operation,
`Unable to run configured command (${String(code ?? "unknown error")})`,
{
cause,
userMessage: `Could not launch the selected ${provider} executable ${JSON.stringify(command)} (${String(code ?? "unknown error")}).`,
remediationAction: `Set ${setting} to an installed executable ${provider === "objdump" ? "GNU objdump" : "Rizin"} command, or make that command available on PATH. Check execute permission on the command and search permission on its parent directories before retrying.`,
diagnostics: {
boundary: "provider-launch",
command,
system_code: code ?? null,
},
...ownedCleanupOptions(cause),
},
);
}
}
if (earlyFailure === undefined && capture !== undefined) {
stdout = capture.stdout;
stderr = capture.stderr;
stdoutBytes = capture.stdoutBytes ?? Buffer.byteLength(stdout);
stderrBytes = capture.stderrBytes ?? Buffer.byteLength(stderr);
exitCode = capture.code;
signalName = capture.signal;
outputTruncated = capture.outputTruncated;
if (capture.collectionFailure) {
exitCode = null;
completionStatus = "unknown";
}
const capturedOutput = {
stdout,
stderr,
truncated: outputTruncated,
stdout_bytes: stdoutBytes,
stderr_bytes: stderrBytes,
exit_code:
!capture.collectionFailure && typeof capture.code === "number"
? capture.code
: null,
signal: capture.signal,
};
if (commandCancelled(signal, cause, code))
failure = new AnalysisCancelledError(operation, {
cause: callerCancellationCause(signal, cause),
capturedOutput,
...ownedCleanupOptions(cause),
});
else if (code === "ETIMEDOUT")
failure = new AnalysisTimeoutError(operation, timeoutMs, {
cause,
capturedOutput,
...ownedCleanupOptions(cause),
...reverseCommandTimeoutGuidance(timeoutMs),
});
if (
cause instanceof OwnedOutputFailure &&
cause.cleanup !== undefined
) {
cleanupIncomplete = true;
if (failure === undefined) {
cleanupOnlyFailure =
!capture.collectionFailure &&
!capture.outputTruncated &&
!capture.killed &&
capture.signal === null &&
typeof capture.code === "number" &&
!signal?.aborted;
failure = new AnalysisOutputError(
operation,
"Provider process cleanup remains incomplete.",
{
cause,
capturedOutput,
cleanup: cause.cleanup,
cleanupOnly: cleanupOnlyFailure,
},
);
}
}
if (
failure === undefined &&
cause instanceof OwnedOutputFailure &&
cause.collectionFailure
)
failure = new AnalysisOutputError(
operation,
"Provider output collection failed.",
{ cause, capturedOutput },
);
if (
capture.killed ||
capture.signal !== null ||
typeof capture.code !== "number"
) {
exitCode = null;
completionStatus = "unknown";
}
if (cause instanceof OwnedOutputFailure) {
stdoutInvalidUtf8 = cause.stdoutInvalidUtf8;
stderrInvalidUtf8 = cause.stderrInvalidUtf8;
}
}
}
if (earlyFailure !== undefined)
return err(this.#registerCleanupFailure(earlyFailure, cleanupOwner));
if (failure !== undefined && cleanupOwner !== undefined)
failure = this.#registerCleanupFailure(failure, cleanupOwner);
let digestAfter: string | null = null;
if (absolutePath === undefined) {
digestAfter = null;
} else if (cleanupIncomplete) {
if (!cleanupOnlyFailure) completionStatus = "unknown";
} else {
try {
digestAfter = await this.#digest(
absolutePath,
signal,
this.#stat,
timeoutMs,
);
} catch {
// Preserve the provider's collected observations if the artifact vanished or became unreadable.
}
}
if (signal?.aborted && failure === undefined) {
failure = new AnalysisCancelledError(operation, {
cause: signal.reason,
capturedOutput: {
stdout,
stderr,
truncated: outputTruncated,
stdout_bytes: stdoutBytes,
stderr_bytes: stderrBytes,
exit_code: typeof exitCode === "number" ? exitCode : null,
signal: signalName,
},
});
exitCode = null;
completionStatus = "unknown";
}
const artifactChanged =
absolutePath === undefined
? null
: digestAfter === null || digest === undefined
? null
: digestAfter !== digest;
const result = {
stdout,
stderr,
exit_code: exitCode,
signal: signalName,
output_truncated: outputTruncated,
completion_status: completionStatus,
artifact_sha256_after: absolutePath === undefined ? null : digestAfter,
artifact_changed: absolutePath === undefined ? null : artifactChanged,
};
const limitations = [
...(absolutePath === undefined
? [
"The objdump version is not reported; the output lists BFD targets advertised by the installed tool and does not establish support for the selected artifact.",
]
: [
"The executable version and supported formats are reported as unknown because no reliable version probe was performed.",
]),
"A non-zero process exit is preserved as an observed command result.",
...(operation === "inspect_with_objdump" &&
typeof parameters.symbol === "string"
? [
"Disassembly is scoped to the caller-selected symbol using the provider's matching and symbol-boundary semantics; an empty match does not establish artifact-wide absence.",
]
: []),
...(operation === "inspect_with_objdump" &&
parameters.operation === "dwarf" &&
parameters.follow_debug_links === true
? [
"DWARF output may include local debug-link files whose identities are not bound to Evidence.",
]
: []),
...(operation === "execute_rizin_command"
? [
"Rizin commands and retained plugins may read files or access network resources outside the selected artifact; those external inputs are not bound to Evidence.",
]
: []),
...(stdoutInvalidUtf8 || stderrInvalidUtf8
? [
`Captured ${[
...(stdoutInvalidUtf8 ? ["stdout"] : []),
...(stderrInvalidUtf8 ? ["stderr"] : []),
].join(
" and ",
)} bytes contain invalid or incomplete UTF-8; replacement characters in the text capture do not preserve the original bytes.`,
]
: []),
...(outputTruncated
? [
"Captured provider output is partial because bytes were omitted; process completion is reported separately.",
]
: []),
...(signalName === null
? []
: [
`The provider process terminated by signal ${signalName}; captured output may be partial and command completion is unknown.`,
]),
...(failure === undefined ||
(failure instanceof AnalysisOutputError && failure.cleanupOnly)
? []
: [
`Command completion is unknown because the operation failed with ${failure._tag}: ${failure.message}`,
]),
...(absolutePath === undefined
? [
"This output lists BFD targets advertised by the installed objdump and is independent of the selected artifact.",
]
: [
"When both are available, pre-run and post-run digests detect artifact changes across the provider call but cannot prove the exact bytes consumed during the call.",
]),
...(artifactChanged === true
? [
"The provider command may have changed the artifact while analysis was running; pre-run and post-run digests are both reported.",
]
: []),
...(absolutePath !== undefined && digestAfter === null
? [
cleanupIncomplete
? "The post-run artifact digest was not captured because owned provider cleanup was incomplete at observation time; artifact changes during the command remain unquantified."
: signal?.aborted
? "The post-run artifact digest is unknown because cancellation interrupted the digest."
: "The post-run artifact digest is unknown because the artifact could not be read after the provider call.",
]
: []),
];
const evidence = createEvidence(
absolutePath === undefined || digest === undefined
? undefined
: { path: absolutePath, sha256: digest, format: "unknown" },
profile.identity,
{
predicateType: "rea.reverse-engineering.command-observation",
operation,
parameters: {
...(absolutePath === undefined
? {
operation: "architectures",
...(typeof parameters.command_timeout_ms === "number"
? { command_timeout_ms: parameters.command_timeout_ms }
: {}),
}
: parameters),
provider_executable: command,
command_arguments: [...args],
},
rawResult: result,
result,
limitations,
...(absolutePath === undefined
? {}
: {
locations: [
{ kind: "artifact-path" as const, path: absolutePath },
],
}),
},
);
return failure === undefined
? ok(evidence)
: err(failure.retainPartialObservation(evidence));
}
#registerCleanupFailure(
failure: AnalysisError,
cleanupOwner: ProviderProcessSupervisor | undefined,
): AnalysisError {
if (cleanupOwner !== undefined && failure.cleanupIncomplete)
this.#pendingCleanup.get(cleanupOwner)?.failures.add(failure);
return failure;
}
}
interface OwnedOutputFailureOptions {
readonly stdout: string;
readonly stderr: string;
readonly code: number | string | null;
readonly signal: string | null;
readonly outputTruncated: boolean;
readonly stdoutInvalidUtf8: boolean;
readonly stderrInvalidUtf8: boolean;
readonly stdoutBytes: number;
readonly stderrBytes: number;
readonly capabilityError?: AnalysisCapabilityUnavailableError;
readonly collectionFailure?: boolean;
readonly cleanup?: AnalysisCleanupObservation;
readonly cleanupOwner?: ProviderProcessSupervisor;
readonly cause?: unknown;
readonly launchFailure?: boolean;
}
class OwnedOutputFailure extends Error {
readonly stdout: string;
readonly stderr: string;
readonly code: number | string | null;
readonly signal: string | null;
readonly outputTruncated: boolean;
readonly stdoutInvalidUtf8: boolean;
readonly stderrInvalidUtf8: boolean;
readonly stdoutBytes: number;
readonly stderrBytes: number;
readonly capabilityError: AnalysisCapabilityUnavailableError | undefined;
readonly collectionFailure: boolean;
readonly cleanup: AnalysisCleanupObservation | undefined;
readonly cleanupOwner: ProviderProcessSupervisor | undefined;
readonly launchFailure: boolean;
constructor(options: OwnedOutputFailureOptions) {
super("Owned provider command did not produce a complete result.", {
cause: options.cause,
});
this.stdout = options.stdout;
this.stderr = options.stderr;
this.code = options.code;
this.signal = options.signal;
this.outputTruncated = options.outputTruncated;
this.stdoutInvalidUtf8 = options.stdoutInvalidUtf8;
this.stderrInvalidUtf8 = options.stderrInvalidUtf8;
this.stdoutBytes = options.stdoutBytes;
this.stderrBytes = options.stderrBytes;
this.capabilityError = options.capabilityError;
this.collectionFailure = options.collectionFailure ?? false;
this.cleanup = options.cleanup;
this.cleanupOwner = options.cleanupOwner;
this.launchFailure = options.launchFailure ?? false;
}
}
const runOwnedCommandOutput =
(
runOwned: typeof runOwnedCommand,
onCleanupOwner: (
owner: ProviderProcessSupervisor,
cleanup: AnalysisCleanupObservation,
) => void,
): ReverseEngineeringCommandRunner =>
async (command, args, options = {}) => {
const spawnEnv = { ...options.env };
try {
const snapshot = await runOwned(
{
command,
arguments: [...args],
runId: randomUUID(),
expectedCommand: null,
env: spawnEnv,
hostEnvironment: {},
sweepTokenOwnedProcesses: true,
},
{
timeoutMs: options.timeout ?? DEFAULT_REVERSE_COMMAND_TIMEOUT_MS,
diagnosticBytes: MAX_COMBINED_OUTPUT_BYTES,
acceptNonZeroExit: true,
},
{ signal: options.signal },
);
if (snapshot.signal !== null && snapshot.signal !== undefined)
throw new OwnedOutputFailure({
stdout: snapshot.stdout.text,
stderr: snapshot.stderr.text,
code: snapshot.exitCode ?? null,
signal: snapshot.signal,
outputTruncated: snapshot.diagnosticTruncated === true,
stdoutInvalidUtf8: snapshot.stdout.invalidUtf8 === true,
stderrInvalidUtf8: snapshot.stderr.invalidUtf8 === true,
stdoutBytes: snapshot.stdout.bytes,
stderrBytes: snapshot.stderr.bytes,
});
if (snapshot.exitCode !== 0)
throw new OwnedOutputFailure({
stdout: snapshot.stdout.text,
stderr: snapshot.stderr.text,
code: snapshot.exitCode ?? null,
signal: null,
outputTruncated: snapshot.diagnosticTruncated === true,
stdoutInvalidUtf8: snapshot.stdout.invalidUtf8 === true,
stderrInvalidUtf8: snapshot.stderr.invalidUtf8 === true,
stdoutBytes: snapshot.stdout.bytes,
stderrBytes: snapshot.stderr.bytes,
});
return {
stdout: snapshot.stdout.text,
stderr: snapshot.stderr.text,
outputTruncated: snapshot.diagnosticTruncated === true,
stdoutInvalidUtf8: snapshot.stdout.invalidUtf8 === true,
stderrInvalidUtf8: snapshot.stderr.invalidUtf8 === true,
stdoutBytes: snapshot.stdout.bytes,
stderrBytes: snapshot.stderr.bytes,
};
} catch (cause) {
if (!(cause instanceof OwnedCommandFailure)) throw cause;
if (cause.cleanupOwner !== undefined && cause.cleanupFailure !== null)
onCleanupOwner(cause.cleanupOwner, {
reason: cause.cleanupFailure,
resources: cause.resources,
});
const snapshot = cause.snapshot;
const launchErrorCode =
cause.cause instanceof Error
? Reflect.get(cause.cause, "code")
: undefined;
const code =
cause.reason === "cancelled"
? "ABORT_ERR"
: cause.reason === "timeout"
? "ETIMEDOUT"
: cause.reason === "output-limit"
? "ERR_CHILD_PROCESS_STDIO_MAXBUFFER"
: launchErrorCode === "E2BIG"
? "E2BIG"
: snapshot === null
? typeof launchErrorCode === "string"
? launchErrorCode
: "ERR_PROVIDER_LAUNCH"
: (snapshot.exitCode ?? null);
throw new OwnedOutputFailure({
stdout: snapshot?.stdout.text ?? "",
stderr: snapshot?.stderr.text ?? "",
code,
launchFailure: cause.reason === "process" && snapshot === null,
signal: snapshot?.signal ?? null,
outputTruncated: snapshot?.diagnosticTruncated === true,
stdoutInvalidUtf8: snapshot?.stdout.invalidUtf8 === true,
stderrInvalidUtf8: snapshot?.stderr.invalidUtf8 === true,
stdoutBytes: snapshot?.stdout.bytes ?? 0,
stderrBytes: snapshot?.stderr.bytes ?? 0,
...(cause.cause instanceof AnalysisCapabilityUnavailableError
? { capabilityError: cause.cause }
: {}),
...(cause.collectionFailure ? { collectionFailure: true } : {}),
...(cause.cleanupFailure === null
? {}
: {
cleanup: {
reason: cause.cleanupFailure,
resources: cause.resources,
},
}),
...(cause.cleanupOwner === undefined
? {}
: { cleanupOwner: cause.cleanupOwner }),
cause,
});
}
};
const ownedCleanupOptions = (
cause: unknown,
): { readonly cleanup?: AnalysisCleanupObservation } =>
cause instanceof OwnedOutputFailure && cause.cleanup !== undefined
? { cleanup: cause.cleanup }
: {};
const reverseCommandTimeoutGuidance = (
timeoutMs: number,
): { readonly userMessage: string; readonly remediationAction: string } => ({
userMessage: `This objdump or rizin command reached its ${String(timeoutMs)} ms server/provider deadline (command_timeout_ms) during target preflight or the one-shot command (deadlineExpired). This is not a Ghidra or Hopper startup deadline and not a debugger session deadline.`,
remediationAction: `${
timeoutMs < MAX_REVERSE_COMMAND_TIMEOUT_MS
? `Increase command_timeout_ms above ${String(timeoutMs)} (integer milliseconds from 1 to ${String(MAX_REVERSE_COMMAND_TIMEOUT_MS)}; omitted means ${String(DEFAULT_REVERSE_COMMAND_TIMEOUT_MS)}), or use --command-timeout-ms on the CLI.`
: `command_timeout_ms is already at the maximum ${String(MAX_REVERSE_COMMAND_TIMEOUT_MS)} ms; no higher deadline is supported.`
} The new value applies on the next call; no restart is required. The ${String(MAX_COMBINED_OUTPUT_BYTES)} byte (16 MiB) combined output cap has no runtime override. Allow execution, cleanup and delivery headroom in the outer MCP client deadline. Confirm outstanding work and cleanup before retrying.`,
});
export const digestFile = async (
path: string,
signal?: AbortSignal,
stat: (path: string) => Promise<Stats> = statPath,
timeoutMs: number = DEFAULT_REVERSE_COMMAND_TIMEOUT_MS,
open: (
path: string,
) => ReturnType<typeof createReadStream> = createReadStream,
): Promise<string> => {
const startedAt = performance.now();
const info = await statWithDeadline(path, signal, stat, timeoutMs);
if (!info.isFile())
throw Object.assign(new Error("Artifact digest requires a regular file"), {
code: "EINVAL",
});
const remainingMs = Math.max(
0,
Math.ceil(timeoutMs - (performance.now() - startedAt)),
);
if (remainingMs === 0)
throw Object.assign(new Error("Artifact digest timed out"), {
code: "ETIMEDOUT",
});
return new Promise<string>((resolveDigest, rejectDigest) => {
const hash = createHash("sha256");
const stream = open(path);
const timer = setTimeout(
() =>
stream.destroy(
Object.assign(new Error("Artifact digest timed out"), {
code: "ETIMEDOUT",
}),
),
remainingMs,
);
const abort = (): void => {
stream.destroy(
new AnalysisCancelledError("artifact_digest", {
cause: signal?.reason,
}),
);
};
const cleanup = (): void => {
clearTimeout(timer);
signal?.removeEventListener("abort", abort);
};
if (signal?.aborted) {
cleanup();
stream.destroy();
rejectDigest(
new AnalysisCancelledError("artifact_digest", {
cause: signal.reason,
}),
);
return;
}
signal?.addEventListener("abort", abort, { once: true });
stream.on("data", (chunk: Buffer | string) => hash.update(chunk));
stream.once("error", (cause: Error) => {
cleanup();
rejectDigest(cause);
});
stream.once("end", () => {
cleanup();
resolveDigest(hash.digest("hex"));
});
});
};
const PHYSICAL_FAILURE_CODES = new Set([
"EACCES",
"EPERM",
"ETIMEDOUT",
"ENOENT",
"ENOTDIR",
"EINVAL",
"ELOOP",
"ENAMETOOLONG",
"E2BIG",
"EBUSY",
"ERR_PROVIDER_LAUNCH",
]);
/**
* A late abort does not replace a recognized physical failure. Other rejections
* observed while the caller signal is aborted remain cancellation. A bare
* `ABORT_ERR` is not cancellation until the command boundary, which already
* used that code for an aborted provider process.
*/
const preflightCancelled = (
signal: AbortSignal | undefined,
cause: unknown,
code: string | number | undefined,
): boolean => {
if (cause instanceof AnalysisCancelledError) return true;
if (signal?.aborted !== true) return false;
if (cause === signal.reason) return true;
return typeof code !== "string" || !PHYSICAL_FAILURE_CODES.has(code);
};
const commandCancelled = (
signal: AbortSignal | undefined,
cause: unknown,
code: string | number | undefined,
): boolean => code === "ABORT_ERR" || preflightCancelled(signal, cause, code);
const callerCancellationCause = (
signal: AbortSignal | undefined,
cause: unknown,
): unknown => (signal?.aborted === true ? signal.reason : cause);
const commandFailureCode = (cause: unknown): string | number | undefined => {
if (typeof cause !== "object" || cause === null) return undefined;
const code: unknown = Reflect.get(cause, "code");
return typeof code === "string" || typeof code === "number"
? code
: undefined;
};
const statWithDeadline = (
path: string,
signal: AbortSignal | undefined,
stat: (path: string) => Promise<Stats>,
timeoutMs: number,
): Promise<Stats> => {
if (signal?.aborted)
return Promise.reject(
new AnalysisCancelledError("artifact_digest", { cause: signal.reason }),
);
return new Promise<Stats>((resolveStat, rejectStat) => {
let settled = false;
const finish = (outcome: Result<Stats, unknown>): void => {
if (settled) return;
settled = true;
clearTimeout(timer);
signal?.removeEventListener("abort", abort);
if (outcome.ok) resolveStat(outcome.value);
else rejectStat(outcome.error);
};
const abort = (): void =>
finish(
err(
new AnalysisCancelledError("artifact_digest", {
cause: signal?.reason,
}),
),
);
const timer = setTimeout(
() =>
finish(
err(
Object.assign(new Error("Artifact stat timed out"), {
code: "ETIMEDOUT",
}),
),
),
timeoutMs,
);
signal?.addEventListener("abort", abort, { once: true });
if (signal?.aborted) {
abort();
return;
}
// Promise handlers stay attached after timeout/cancellation so a delayed
// stat rejection is observed and cannot become an unhandled rejection.
try {
void stat(path).then(
(info) => finish(ok(info)),
(cause: unknown) => finish(err(cause)),
);
} catch (cause) {
finish(err(cause));
}
});
};