Files
reverse-engineering-anything/src/domain/analysisErrorCore.ts
T
morluto bd353e7e5c fix(errors)!: producers declare retry class, refusal recovery and real error codes (#15372)
* fix(errors)!: derive retryable from the producer's declared retry class

`retryable` means the unchanged request may succeed, but it was computed
downstream as an OR of a code table and five class rules. Every error
classification now declares a retry class (same_call, change_first, never,
unknown_outcome); `retryable` is `same_call` after one incomplete-cleanup
check, and the RETRYABLE_CODES table is deleted.

Producer corrections:
- update_unknown revision conflicts are change_first and report
  details.current_revision; duplicate record_unknown reports
  details.existing_unknown_id.
- close_gdb_session's explicit-disposition refusal is change_first.
- Per-call artifact reader limits are change_first (never when the limit
  cannot rise).
- An exited or unreachable Hopper bridge, and a Hopper start that another
  REA session owns, are change_first.
- File-descriptor exhaustion (EMFILE/ENFILE) outside process launch is
  occupied host capacity (same_call) for private workspaces, model and GPU
  readers and JavaScript application reads.
- apktool JVM native-thread exhaustion follows the shared capacity default.

BREAKING CHANGE: these refusals now report `retryable: false` (descriptor
pressure now reports `retryable: true` as `resource_constraint`). Callers
that repeated them unchanged should follow the remediation first: re-read
the unknown and retry with details.current_revision, dispose GDB inferiors,
raise the reported reader limit, or restart the Hopper provider.

* fix(errors): require producers to name recovery for conforming refusals

A refusal whose arguments match the input schema was presented as a schema
error whenever its producer left out remediation, and many producers did.
AnalysisInputError's options are now a union: a conforming refusal must
supply both its outcome (userMessage) and next step (remediationAction),
so the compiler lists every producer; only contract violations may fall
back to the schema guidance.

Producers fixed: unknown Frida session and script, decompile_all
output-directory state, the duplicate unknown build computer factory
(collapsed), stale Cutter sessions, Mach-O architecture selection, output
roots that already exist, selected files the host refuses, Ghidra lookups
the bridge could not resolve, YARA path refusals, unresolved native symbol
names, apt key files and withheld sign-in state. A missing selected APK is
now target_unavailable like every other selected-file reader.

The capability fallback "Choose another analysis or target" is deleted; a
capability refusal without its own recovery names details.reason and
binary_session.

Refs #15312

* fix(errors): classify caller selections and target bytes by their real failure

Several refusals reported a code that reads as corruption or a crash:
- a missing unknown_id and a missing Evidence reference now report
  invalid_request instead of execution_failure and
  evidence_integrity_mismatch;
- close_binary with snapshot_path in a resource-only session reports
  invalid_request instead of evidence_integrity_mismatch;
- ADB push onto an existing device path and pulls into an occupied output
  directory are conforming invalid_request refusals naming overwrite or
  output_directory, not unreadable_output;
- damaged APK ZIP, signing-block, signer and central-directory structures
  are malformed targets, not invalid input;
- NuGet and VSIX bytes without a ZIP signature are unrecognized, not
  malformed;
- a historical source graph file whose entries contradict its root
  commitment is an integrity failure, not invalid input;
- a CDP protocol failure states what happened instead of the unclassified
  fallback message.

Refs #15319

* feat(errors): expose the producer's retry class as retry_class

Every error projection now carries retry_class (same_call, change_first, never or unknown_outcome) beside retryable, which stays true exactly for same_call. The field is additive: the error schema accepts errors retained by earlier releases without it.

Refs #15323

* fix(errors): address review of the folded error-contract PRs

Keep a provider's own capability message as its remediation; the binary_session fallback applies only to a bare declared reason. Delete the unused conformingInputRefusal helper. Compose both retry fields for a refused publication whose cleanup is incomplete. Report descriptor exhaustion from a JavaScript directory opendir as occupied capacity. Let an exited Hopper startup attempt without a setup failure code retry unchanged. Declare retry for the Ghidra superseded checkpoint and unknown IDA readiness. Redact ambiguous selector candidates. Give a Ghidra document miss its own recovery. Drop an unchanged-files claim the journal repair cannot make. Name each withheld sign-in refusal's step. Hash the source graph commitment before the cancellation yield. Keep the browser protocol_error message neutral. Add tests for mutation-audit survivors C3, C5, P2, P4, P8, H1, H4 and H5.

* fix(errors): keep a missing Evidence reference an integrity failure and state only the observed commitment mismatch

* test(desktop): assert the unknown build computer refusal's remediation, not its message

The refusal now carries its next step in remediation.action instead of the message, so the closed-computer checks assert the exact code, message and remediation facts.

* fix(errors): keep producer retry choices apart from cleanup and fixed ceilings

A capture's retryable flag no longer folds in pending cleanup, so the projection applies the cleanup rule once and a transient capture with pending cleanup reports change_first instead of never. A release-fixed artifact allowance reports never, and a stale admitted session identity reports change_first (reopen, then retry); both have catalogue rows. The bare capability-unavailable remediation names binary_session only for a binary-analysis session, so standalone bridges such as Cutter are pointed at their own reason.

* test(vsix): expect a non-ZIP selection to be refused as unrecognized

This PR reports bytes without a ZIP signature as another format (unrecognized), not a damaged package; the exact-reason assertion added on main still expected malformed.

* test(delivery): expect the capacity refusal's retry class in delivered failure facts

The exact failure facts asserted on main predate the projection's retry_class; occupied capacity reports same_call.

* fix(errors): mark a sent Hopper cancellation unknown and missing Evidence recoverable

A cancellation Hopper already received may still apply, so its retry class is unknown_outcome instead of same_call; an unsent cancellation keeps same_call. A missing EvidenceReferenceError is change_first, since importing the referenced records lets the same request succeed; other reference failures stay never. Both have catalogue rows.

* fix(hopper): ask for changed launch arguments before retrying an unencodable launch

A launcher path or argument that cannot be encoded as an AppleScript literal meets the same pre-launch guard on every attempt, so the start refusal is change_first and its retry_action is unknown; a start failure without a declared reason stays same_call.

* fix(errors): keep a one-shot cleanup failure's retry class with its cleanup state

A one-shot reply that reports cleanup_incomplete spread the primary or cleanup projection and overrode only retryable, so a timed-out read whose close also failed carried retry_class same_call. The reply now reads its retry class from the typed composed failure, and never offers the same call before cleanup settles.

* test(evtx): expect an unreadable selected log to be refused with its own recovery

This PR treats a well-formed path the host refused as a regular file as conforming input with its own remediation; the evtx boundary test still expected a schema-recovery refusal.

* test(javascript): expect a broken source-graph commitment as an integrity failure

This PR reports a well-formed historical source graph whose entries disagree with its root_sha256 as evidence_integrity_mismatch, not an input issue; the exact refusal assertion added on main still expected invalid_request.
2026-12-01 05:32:33 +00:00

787 lines
27 KiB
TypeScript

import type { JsonValue } from "./jsonValue.js";
import type { AnalysisParameterLimit } from "./analysisSettings.js";
import type { FixedAllowance } from "./fixedAllowanceRemediation.js";
import type { AmbiguousSelector } from "./analysisRefusal.js";
import type { ArtifactIntegrityCheck } from "./artifactOperationError.js";
import {
TARGET_FAILURE_PROJECTIONS,
type TargetFailure,
type TargetFailureFacts,
type TargetFailureKind,
type TargetFailureOf,
} from "./targetFailure.js";
import {
AnalysisError,
type AnalysisErrorOptions,
} from "./analysisErrorBase.js";
/**
* The selected target at `path` could not be read, for the reason its owner
* established. The failure's `kind` alone selects the public code, category,
* retryability and recovery; see {@link TARGET_FAILURE_PROJECTIONS}.
*/
export class AnalysisTargetFailureError extends AnalysisError {
readonly _tag = "AnalysisTargetFailureError";
readonly failure: TargetFailure;
constructor(
readonly operation: string,
readonly path: string,
failure: TargetFailure,
options?: AnalysisErrorOptions,
) {
super(
`${TARGET_FAILURE_PROJECTIONS[failure.kind].title} ${failure.format} target for ${operation} at ${path}: ${failure.detail}`,
options,
);
this.failure = Object.freeze({ ...failure });
}
}
/** Where an unsupported or unrecognized target's owner located the failure. */
type TargetFormSite = Pick<TargetFailureFacts, "offset" | "field">;
/**
* The target at `path` holds `format` in a form outside what `operation`
* reads. `undecodedContent` says the target holds the content in that form.
* Name the operations or providers that read it in `options.related`.
*/
export const unsupportedTarget = (
operation: string,
path: string,
format: string,
detail: string,
{
undecodedContent = false,
offset,
field,
...options
}: AnalysisErrorOptions &
TargetFormSite & { readonly undecodedContent?: boolean } = {},
): AnalysisTargetFailureError =>
new AnalysisTargetFailureError(
operation,
path,
{
kind: "unsupported",
format,
detail,
undecodedContent,
...(offset === undefined ? {} : { offset }),
...(field === undefined ? {} : { field }),
},
options,
);
/** No reader of `format` claims the target at `path` for `operation`. */
export const unrecognizedTarget = (
operation: string,
path: string,
format: string,
detail: string,
options: AnalysisErrorOptions = {},
): AnalysisTargetFailureError =>
new AnalysisTargetFailureError(
operation,
path,
{ kind: "unrecognized", format, detail },
options,
);
/** The failure of `error` when it is a target failure of one of `kinds`. */
export const targetFailureOfKind = <Kind extends TargetFailureKind>(
error: unknown,
...kinds: readonly Kind[]
): TargetFailureOf<Kind> | undefined =>
error instanceof AnalysisTargetFailureError &&
(kinds as readonly TargetFailureKind[]).includes(error.failure.kind)
? (error.failure as TargetFailureOf<Kind>)
: undefined;
/** An analysis or transport resource failure, distinct from malformed input or unsupported coverage. */
export const ANALYSIS_RESOURCE_KINDS = [
"memory",
"cpu",
"file-size",
"transport",
"capacity",
] as const;
/** A measured resource constraint or bounded admission refusal. */
export class AnalysisResourceConstraintError extends AnalysisError {
readonly _tag = "AnalysisResourceConstraintError";
/**
* The one recovery this refusal carries. A fixed allowance and a separate
* remediation sentence do not co-occur; retryability belongs to that same
* object.
*/
readonly recovery: ResourceConstraintRecovery;
/**
* Whether the refused request reached its peer: false when it was refused
* before anything was sent, true when the peer received it and may have
* acted on it. Undefined when the producer does not know.
*/
readonly requestSent: boolean | undefined;
constructor(
readonly operation: string,
readonly resource: (typeof ANALYSIS_RESOURCE_KINDS)[number],
readonly reason: string,
readonly reportedLimits: Readonly<Record<string, JsonValue>> | null,
options?: AnalysisErrorOptions &
ResourceConstraintRecovery & { readonly requestSent?: boolean },
) {
super(`Resource constraint during ${operation}: ${reason}`, options);
this.recovery = resourceConstraintRecoveryFrom(options);
this.requestSent = options?.requestSent;
}
/** Projection of `recovery`. Absent when recovery names a fixed allowance. */
get remediationAction(): string | undefined {
return this.recovery.remediationAction;
}
/**
* Projection of `recovery`. The fixed format, decoder, or capture allowance
* that refused the request. Worker limits and host resources do not raise
* it, so recovery derives from this allowance rather than from `resource`.
*/
get fixedAllowance(): FixedAllowance | undefined {
return this.recovery.fixedAllowance;
}
/**
* Projection of `recovery`. Whether retrying the same request can succeed.
* A caller-selected bound is deterministic for the same input, so it is not
* retryable even when its resource kind would otherwise be treated as
* admission capacity.
*/
get retryable(): boolean | undefined {
return this.recovery.retryable;
}
}
const resourceConstraintRecoveryFrom = (
options: ResourceConstraintRecovery | undefined,
): ResourceConstraintRecovery => {
if (options?.fixedAllowance !== undefined)
return {
fixedAllowance: options.fixedAllowance,
...(options.retryable === undefined
? {}
: { retryable: options.retryable }),
};
return {
...(options?.remediationAction === undefined
? {}
: { remediationAction: options.remediationAction }),
...(options?.measuredExhaustion === undefined
? {}
: { measuredExhaustion: options.measuredExhaustion }),
...(options?.retryable === undefined
? {}
: { retryable: options.retryable }),
};
};
/**
* Re-attribute a resource refusal to another operation. Recovery and the
* structured setting limit travel with it; a new error that keeps only the
* sentence drops the setting, source, and effective value.
*/
export const reattributedResourceConstraint = (
operation: string,
error: AnalysisResourceConstraintError,
options?: AnalysisErrorOptions,
): AnalysisResourceConstraintError =>
new AnalysisResourceConstraintError(
operation,
error.resource,
error.reason,
error.reportedLimits,
{
...options,
...resourceConstraintRecovery(error),
...(error.limit === undefined ? {} : { limit: error.limit }),
...(error.related === undefined ? {} : { related: error.related }),
...(error.requestSent === undefined
? {}
: { requestSent: error.requestSent }),
},
);
/**
* Refuse at a fixed ceiling that its producer named. The ceiling carries its
* own value and recovery, so no other limit is reported beside it, and the
* unchanged request is not retryable.
*/
export const fixedCeilingConstraint = (
operation: string,
resource: (typeof ANALYSIS_RESOURCE_KINDS)[number],
reason: string,
ceiling: FixedAllowance,
options?: AnalysisErrorOptions,
): AnalysisResourceConstraintError =>
new AnalysisResourceConstraintError(operation, resource, reason, null, {
...options,
retryable: false,
fixedAllowance: ceiling,
});
/**
* Project an observed file size against the per-call parameter that refused
* it. The typed `limit` carries the measured need, so the shared adjustable
* budget formatter derives recovery in the delivering adapter's spelling (the
* CLI names `--max-file-bytes` and the command). A hand-written sentence here
* would bypass that and drop the adapter's spelling.
*/
export const parameterFileSizeConstraint = (
operation: string,
reason: string,
limit: AnalysisParameterLimit,
observedBytes: bigint | undefined,
options?: AnalysisErrorOptions,
): AnalysisResourceConstraintError => {
if (observedBytes !== undefined && observedBytes > BigInt(limit.maximum))
return fixedCeilingConstraint(
operation,
"file-size",
reason,
{
name: `${limit.parameter} maximum`,
kind: "input",
limit: limit.maximum,
unit: limit.unit,
},
options,
);
const { parameter, effective_value: effective } = limit;
const required =
observedBytes === undefined ||
observedBytes > BigInt(Number.MAX_SAFE_INTEGER)
? undefined
: Number(observedBytes);
return new AnalysisResourceConstraintError(
operation,
"file-size",
reason,
{
[parameter]: effective,
...(required === undefined ? {} : { observed_file_bytes: required }),
},
{
...options,
retryable: false,
limit: {
...limit,
...(required === undefined ? {} : { required_value: required }),
},
},
);
};
/**
* Refuse while shared host capacity, such as open file descriptors, is
* occupied. It clears when other work releases it, so the unchanged request
* is retryable; the producer names how to free it.
*/
export const occupiedHostCapacityConstraint = (
operation: string,
reason: string,
reportedLimits: Readonly<Record<string, JsonValue>>,
options: AnalysisErrorOptions & { readonly remediationAction: string },
): AnalysisResourceConstraintError =>
new AnalysisResourceConstraintError(
operation,
"capacity",
reason,
reportedLimits,
{ ...options, retryable: true, measuredExhaustion: true },
);
/**
* Refuse at a session setting the caller can change. The structured limit is
* that setting. A parser limit still goes through `parseLimitConstraint`.
*/
export const sessionSettingConstraint = (
operation: string,
resource: (typeof ANALYSIS_RESOURCE_KINDS)[number],
reason: string,
reportedLimits: Readonly<Record<string, JsonValue>> | null,
options: Omit<AnalysisErrorOptions, "limit"> &
ResourceConstraintRecovery & {
readonly limit: NonNullable<AnalysisErrorOptions["limit"]>;
readonly requestSent?: boolean;
},
): AnalysisResourceConstraintError =>
new AnalysisResourceConstraintError(
operation,
resource,
reason,
reportedLimits,
{ ...options, retryable: false },
);
/** Carry one refusal's recovery to an error re-attributed or redacted elsewhere. */
export const resourceConstraintRecovery = (
error: AnalysisResourceConstraintError,
text: (value: string) => string = (value) => value,
): ResourceConstraintRecovery => {
const recovery = error.recovery;
return recovery.fixedAllowance !== undefined
? {
fixedAllowance: {
...recovery.fixedAllowance,
name: text(recovery.fixedAllowance.name),
...(recovery.fixedAllowance.narrowing === undefined
? {}
: { narrowing: text(recovery.fixedAllowance.narrowing) }),
},
...(recovery.retryable === undefined
? {}
: { retryable: recovery.retryable }),
}
: {
...(recovery.remediationAction === undefined
? {}
: { remediationAction: text(recovery.remediationAction) }),
...(recovery.measuredExhaustion === undefined
? {}
: { measuredExhaustion: recovery.measuredExhaustion }),
...(recovery.retryable === undefined
? {}
: { retryable: recovery.retryable }),
};
};
/**
* Producer-specific recovery, or a fixed allowance whose recovery is derived.
* `measuredExhaustion` declares an observed runtime exhaustion or occupied
* admission rather than a refusal, so recovery follows the resource kind.
*/
export type ResourceConstraintRecovery =
| {
readonly remediationAction?: string;
readonly fixedAllowance?: never;
readonly measuredExhaustion?: true;
readonly retryable?: boolean;
}
| {
readonly fixedAllowance: FixedAllowance;
readonly remediationAction?: never;
readonly retryable?: boolean;
};
/** Provider-neutral invalid analysis input or output at an application boundary. */
export class AnalysisProtocolError extends AnalysisError {
readonly _tag = "AnalysisProtocolError";
}
/**
* How an input refusal relates to the advertised input contract.
*
* A contract violation (missing, unknown, mistyped or malformed arguments)
* may leave recovery to the shared schema guidance. A refusal whose arguments
* conform cannot be corrected by re-reading the schema, so its producer must
* name the outcome and the next step; an ambiguous selection's refusal names
* its own recovery.
*/
export type AnalysisInputErrorOptions = AnalysisErrorOptions &
(
| {
readonly conformsToInputContract?: false;
readonly userMessage?: string;
/** Refusal-specific correction beside the input-contract advice. */
readonly remediationAction?: string;
readonly ambiguousSelector?: never;
}
| {
readonly conformsToInputContract: true;
readonly userMessage: string;
readonly remediationAction: string;
readonly ambiguousSelector?: never;
}
| {
readonly conformsToInputContract?: true;
readonly userMessage?: string;
readonly remediationAction?: string;
readonly ambiguousSelector: AmbiguousSelector;
}
);
/** Caller input failed provider-neutral application parsing. */
export class AnalysisInputError extends AnalysisError {
readonly _tag = "AnalysisInputError";
override readonly userMessage: string | undefined;
/** Refusal-specific correction, when the generic input-contract advice cannot fix it. */
readonly remediationAction: string | undefined;
/**
* The refused values satisfy the advertised input contract; the selected
* target lacks the requested fact for them. Re-reading the schema cannot
* correct such a refusal, so it carries no input-contract recovery.
*/
readonly conformsToInputContract: boolean;
/** A schema-valid selector that matched several candidates. */
readonly ambiguousSelector: AmbiguousSelector | undefined;
constructor(
readonly operation: string,
options?: AnalysisInputErrorOptions,
readonly issues: readonly AnalysisInputIssue[] = [],
) {
super(`Invalid analysis input for ${operation}`, options);
this.userMessage = options?.userMessage;
this.remediationAction = options?.remediationAction;
this.ambiguousSelector = options?.ambiguousSelector;
// An ambiguous selection conforms to the schema; the contract is not at fault.
this.conformsToInputContract =
options?.conformsToInputContract ??
options?.ambiguousSelector !== undefined;
}
}
/** Secret-safe correction metadata for one rejected caller argument. */
export interface AnalysisInputIssue {
readonly path: readonly (string | number)[];
readonly reason:
| "unknown_argument"
| "missing_argument"
| "invalid_type"
| "out_of_range"
| "invalid_value"
| "invalid_format";
/** Schema-authored correction guidance for cross-field or custom checks. */
readonly message?: string;
readonly expected?: JsonValue;
/** Producer-examined facts about the refused value, such as its location and shape. */
readonly observed?: JsonValue;
readonly minimum?: number;
readonly maximum?: number;
}
/** Refusal-specific context a producer projects with an output failure. */
export interface AnalysisOutputErrorOptions extends AnalysisErrorOptions {
/** Caller-facing explanation for a deterministic, diagnosable refusal. */
readonly userMessage?: string;
readonly remediationAction?: string;
readonly cleanupOnly?: boolean;
}
/** Provider output failed provider-neutral application parsing. */
export class AnalysisOutputError extends AnalysisError {
readonly _tag = "AnalysisOutputError";
override readonly userMessage: string | undefined;
readonly remediationAction: string | undefined;
readonly cleanupOnly: boolean;
constructor(
readonly operation: string,
readonly reason: string,
options?: AnalysisOutputErrorOptions,
) {
super(`Invalid analysis output for ${operation}: ${reason}`, options);
this.userMessage = options?.userMessage;
this.remediationAction = options?.remediationAction;
this.cleanupOnly = options?.cleanupOnly ?? false;
}
}
/** Selected provider cannot execute a declared analysis operation. */
export class AnalysisCapabilityUnavailableError extends AnalysisError {
readonly _tag = "AnalysisCapabilityUnavailableError";
override readonly userMessage: string | undefined;
readonly remediationAction: string | undefined;
/** General recovery used only when a consumer has no more specific action. */
readonly fallbackRemediationAction: string | undefined;
readonly siblingOperations: readonly string[] | undefined;
readonly siblingReasons: Readonly<Record<string, string>> | undefined;
/**
* Whether the capability can become available: `same_call` when the
* condition may clear by itself, `change_first` when the caller must act
* first (such as settling a debugger inferior), `never` when the provider
* does not support the operation. Incomplete cleanup is applied once, by
* the projection.
*/
readonly retry: "same_call" | "change_first" | "never";
/** The unchanged request may succeed once the condition clears. */
get retryable(): boolean {
return this.retry === "same_call" && !this.cleanupIncomplete;
}
/**
* Operations the caller can run now that observe part of what this one
* would answer; the remediation states what they do not establish.
*/
readonly alternatives: readonly string[];
constructor(
readonly providerId: string,
readonly operation: string,
readonly reason: string,
options?: AnalysisErrorOptions & {
readonly userMessage?: string;
readonly remediationAction?: string;
readonly fallbackRemediationAction?: string;
readonly siblingOperations?: readonly string[];
readonly siblingReasons?: Readonly<Record<string, string>>;
readonly retry?: "same_call" | "change_first" | "never";
readonly alternatives?: readonly string[];
},
) {
super(
`Provider ${providerId} cannot execute ${operation}: ${reason}`,
options,
);
this.userMessage = options?.userMessage;
this.remediationAction = options?.remediationAction;
this.fallbackRemediationAction = options?.fallbackRemediationAction;
this.siblingOperations = options?.siblingOperations;
this.siblingReasons = options?.siblingReasons;
this.retry = options?.retry ?? "never";
this.alternatives = Object.freeze([...(options?.alternatives ?? [])]);
}
}
/**
* Cancellation, by the caller or by REA closing the work's owner, won before
* provider-neutral work completed. Build it with `cancelledBy`, which requires
* the reason; `cause` holds that reason.
*/
export class AnalysisCancelledError extends AnalysisError {
readonly _tag = "AnalysisCancelledError";
override readonly userMessage: string | undefined;
constructor(
readonly operation: string,
options?: AnalysisErrorOptions & {
readonly userMessage?: string;
},
) {
super(`Analysis operation was cancelled: ${operation}`, options);
this.userMessage = options?.userMessage;
}
}
/** Why REA ended work on its own authority when no caller abort exists. */
export type OwnerCancellationKind =
/** The provider, session, or service owning the work was closed or disposed. */
| "owner-closed"
/**
* The owner of a shared provider startup closed it. Startup consumers compare
* a startup signal's reason with this one to tell owner closure from a
* caller's cancellation, so only that startup's owner may abort with it.
*/
| "startup-owner-closed"
/**
* A bound REA set on its own work elapsed. The owner that set it reports the
* timeout; this reason only ends the bounded wait or request.
*/
| "deadline-elapsed"
/**
* REA stopped work whose result nobody will consume: its wait settled, its
* consumer closed, the last waiter left, or a sibling already failed.
*/
| "no-longer-needed";
const OWNER_CANCELLATION_MESSAGES: Readonly<
Record<OwnerCancellationKind, string>
> = {
"owner-closed": "REA closed the owner of this operation before it completed",
"startup-owner-closed":
"REA closed the owner of this operation before it completed",
"deadline-elapsed": "An internal REA bound on this operation elapsed",
"no-longer-needed": "REA stopped work whose result is no longer needed",
};
/**
* A cancellation REA initiated itself, such as a provider closing. It stands
* in for a caller abort reason, so it is never mistaken for one.
*/
export class OwnerCancellation extends Error {
override readonly name = "OwnerCancellation";
private constructor(readonly kind: OwnerCancellationKind) {
super(OWNER_CANCELLATION_MESSAGES[kind]);
}
/**
* One shared reason per kind, so repeated owner cancellations compare equal
* the way repeated observations of one caller abort do.
*/
static readonly ownerClosed = new OwnerCancellation("owner-closed");
/** Reserved for the owner of a `SharedStartupAttempt`; see its kind. */
static readonly startupOwnerClosed = new OwnerCancellation(
"startup-owner-closed",
);
/** An internal bound elapsed; see its kind. */
static readonly deadlineElapsed = new OwnerCancellation("deadline-elapsed");
/** Work nobody will consume was stopped; see its kind. */
static readonly noLongerNeeded = new OwnerCancellation("no-longer-needed");
}
/** How the caller ended work, as the CLI, MCP or HTTP adapter observed it. */
export type CallerAbortKind =
/** The CLI or direct-analysis process received SIGINT. */
| "interrupt"
/** The CLI or direct-analysis process received SIGTERM. */
| "terminate"
/** The MCP client sent `notifications/cancelled` for the request. */
| "request-cancelled"
/** The MCP or HTTP client left before its request settled. */
| "client-disconnected";
const CALLER_ABORT_MESSAGES: Readonly<Record<CallerAbortKind, string>> = {
interrupt: "The caller interrupted this operation (SIGINT)",
terminate: "The caller terminated this operation (SIGTERM)",
"request-cancelled": "The MCP client cancelled this request",
"client-disconnected": "The client disconnected before this request settled",
};
/**
* The abort reason an adapter gives when its caller ends work. It is the
* platform's `AbortError` shape, so consumers that recognize a platform abort
* keep recognizing it, and it records which adapter observed the abort and any
* reason the client supplied. Like any caller reason it is opaque: its kind
* never establishes failure origin or cleanup authority.
*/
export class CallerAbort extends DOMException {
constructor(
readonly kind: CallerAbortKind,
/** The client's own stated reason, such as an MCP cancellation's `reason`. */
readonly clientReason?: unknown,
) {
super(CALLER_ABORT_MESSAGES[kind], "AbortError");
}
/** The reason for a process signal delivered to a one-shot command. */
static forProcessSignal(signal: "SIGINT" | "SIGTERM"): CallerAbort {
return new CallerAbort(signal === "SIGINT" ? "interrupt" : "terminate");
}
}
/** A caller abort reason recovered from an earlier observation of that abort. */
export interface CarriedCancellationReason {
readonly carried: unknown;
}
/** Mark a reason already observed from the caller's abort, such as an inner failure's recorded reason. */
export const carriedReason = (reason: unknown): CarriedCancellationReason => ({
carried: reason,
});
/**
* Where a cancellation's reason comes from:
* - an aborted signal, whose `reason` is the caller's (or parent operation's) reason;
* - an earlier `AnalysisCancelledError`, whose reason is carried unchanged;
* - a reason carried from another earlier observation;
* - an owner cancellation that REA initiated itself.
*/
export type CancellationReason =
| AbortSignal
| AnalysisCancelledError
| CarriedCancellationReason
| OwnerCancellation;
/** A signal observed aborted, so its `reason` is the cancellation's reason. */
export type AbortedSignal = AbortSignal & { readonly aborted: true };
/** Whether an optional signal has aborted; narrows it to pass to `cancelledBy`. */
export const isAborted = (
signal: AbortSignal | undefined,
): signal is AbortedSignal => signal?.aborted === true;
/** Options for a cancellation; its cause is always the required reason. */
export type CancelledOptions = Omit<AnalysisErrorOptions, "cause"> & {
readonly cause?: never;
readonly userMessage?: string;
};
// Signals are matched structurally last: callers and tests may pass an
// AbortSignal implementation from another realm or a signal-shaped fake.
const cancellationCause = (reason: CancellationReason): unknown => {
if (reason instanceof AnalysisCancelledError) return reason.cause;
if (reason instanceof OwnerCancellation) return reason;
if ("carried" in reason) return reason.carried;
return reason.reason;
};
/** The one constructor for a cancellation: its reason is required. */
export const cancelledBy = (
operation: string,
reason: CancellationReason,
options?: CancelledOptions,
): AnalysisCancelledError =>
new AnalysisCancelledError(operation, {
...options,
cause: cancellationCause(reason),
});
/**
* A provider's recovery for its elapsed deadline: which deadline elapsed, the
* setting or action that changes it, the accepted setting, and the facts that
* explain it.
*/
export interface AnalysisTimeoutRecovery {
/** Provider-specific explanation of which deadline elapsed. */
readonly userMessage?: string;
/** Provider-specific setting or action that changes that deadline. */
readonly remediationAction?: string;
readonly limit?: AnalysisErrorOptions["limit"];
readonly diagnostics?: AnalysisErrorOptions["diagnostics"];
}
/** Provider-neutral operation exceeded its declared execution deadline. */
export class AnalysisTimeoutError extends AnalysisError {
readonly _tag = "AnalysisTimeoutError";
override readonly userMessage: string | undefined;
readonly remediationAction: string | undefined;
constructor(
readonly operation: string,
readonly timeoutMs: number,
options?: AnalysisErrorOptions & AnalysisTimeoutRecovery,
) {
super(
`Analysis operation timed out after ${String(timeoutMs)}ms: ${operation}`,
options,
);
this.userMessage = options?.userMessage;
this.remediationAction = options?.remediationAction;
}
}
/** Host filesystem permissions denied the selected read; this is not malformed caller input. */
export class AnalysisAccessDeniedError extends AnalysisError {
readonly _tag = "AnalysisAccessDeniedError";
constructor(
readonly operation: string,
readonly path: string,
readonly systemCode: "EACCES" | "EPERM",
options?: AnalysisErrorOptions,
) {
super(
`Host filesystem read access denied (${systemCode}) for ${path} during ${operation}`,
options,
);
}
}
/** Selected artifact acquisition observed a change, so no stable identity can be reported. */
export class AnalysisArtifactChangedError extends AnalysisError {
readonly _tag = "AnalysisArtifactChangedError";
/** The consistency check the producing reader named, when it named one. */
readonly integrityCheck: ArtifactIntegrityCheck | undefined;
constructor(
readonly operation: string,
readonly path: string,
readonly reason: string,
options?: AnalysisErrorOptions & {
readonly integrityCheck?: ArtifactIntegrityCheck | undefined;
},
) {
super(`Selected artifact changed during acquisition: ${reason}`, options);
this.integrityCheck = options?.integrityCheck;
}
}