diff --git a/src/adb/AdbFileStaging.ts b/src/adb/AdbFileStaging.ts index ad2a5c3edeb..741cb47e036 100644 --- a/src/adb/AdbFileStaging.ts +++ b/src/adb/AdbFileStaging.ts @@ -1,3 +1,4 @@ +import { systemCodeFromError } from "../kernel/reportedSystemCode.js"; import { constants as fsConstants } from "node:fs"; import { access, @@ -11,7 +12,6 @@ import { import { basename, extname } from "node:path"; import { ADB_PROVIDER_IDENTITY } from "./AdbProviderIdentity.js"; -import { adbFilesystemErrorCode } from "./AdbFilesystemAdmission.js"; import { displayDevicePath } from "./AdbDeviceOutput.js"; import { absoluteCallerPath, @@ -277,7 +277,7 @@ export const prepareOutputDirectory = async ( await mkdir(root, { recursive: true }); await access(root, fsConstants.W_OK); } catch (cause) { - const code = adbFilesystemErrorCode(cause); + const code = systemCodeFromError(cause); if (code === "EEXIST" || code === "ENOTDIR") return err( new AnalysisInputError(operation, { cause }, [ @@ -598,12 +598,7 @@ export const reservePackageDestinations = async ( }, }); } catch (cause: unknown) { - const errorCode = - cause instanceof Error && - "code" in cause && - typeof cause.code === "string" - ? cause.code - : null; + const errorCode = systemCodeFromError(cause) ?? null; return new AnalysisOutputError( operation, "local_destination_unavailable", @@ -638,12 +633,7 @@ export const reservePackageDestinations = async ( ); await rmdir(reservation.path); } catch (cause: unknown) { - const errorCode = - cause instanceof Error && - "code" in cause && - typeof cause.code === "string" - ? cause.code - : null; + const errorCode = systemCodeFromError(cause) ?? null; return new AnalysisOutputError( operation, "local_destination_unavailable", diff --git a/src/adb/AdbFilesystemAdmission.ts b/src/adb/AdbFilesystemAdmission.ts index 20b3016cf2b..81a4c37e874 100644 --- a/src/adb/AdbFilesystemAdmission.ts +++ b/src/adb/AdbFilesystemAdmission.ts @@ -1,11 +1,7 @@ +import { systemCodeFromError } from "../kernel/reportedSystemCode.js"; import { stat } from "node:fs/promises"; import { AnalysisInputError } from "../domain/analysisErrorCore.js"; -export const adbFilesystemErrorCode = (cause: unknown): string | undefined => - cause instanceof Error && "code" in cause && typeof cause.code === "string" - ? cause.code - : undefined; - /** Admit the caller's file once, retaining the selection and the host's reason. */ export const adbInputFileError = async ( operation: string, @@ -17,7 +13,7 @@ export const adbInputFileError = async ( try { info = await stat(absolutePath); } catch (cause) { - const code = adbFilesystemErrorCode(cause); + const code = systemCodeFromError(cause); const message = code === "ENOENT" || code === "ENOTDIR" ? "The selected file does not exist or a parent is not a directory." diff --git a/src/application/environment/environmentExport.ts b/src/application/environment/environmentExport.ts index 69a057e0b7e..bcf7b3b1dbe 100644 --- a/src/application/environment/environmentExport.ts +++ b/src/application/environment/environmentExport.ts @@ -1,3 +1,4 @@ +import { systemCodeFromError } from "../../kernel/reportedSystemCode.js"; import { isAbsolute } from "node:path"; import { getHeapStatistics } from "node:v8"; @@ -100,11 +101,6 @@ const inputError = ( ): AnalysisInputError => new AnalysisInputError(operation, { userMessage }, [issue]); -const systemCode = (cause: unknown): string | undefined => - cause instanceof Error && "code" in cause && typeof cause.code === "string" - ? cause.code - : undefined; - /** Recovery for a host write failure that may leave partial output behind. */ const hostWriteFailure = (directory: string) => ({ userMessage: `Writing the environment bundle to ${directory} failed on the host; the details name the cause and, when it failed on one bundle file, that file.`, @@ -124,7 +120,7 @@ const hostSystemError = (cause: Error): Error | undefined => { const seen = new Set([cause]); let current = cause.cause; while (current instanceof Error && !seen.has(current)) { - if (systemCode(current) !== undefined) return current; + if (systemCodeFromError(current) !== undefined) return current; seen.add(current); current = current.cause; } @@ -144,7 +140,7 @@ const accessDeniedError = ( seen.add(current); if (current instanceof BundleFileHostFailure) access = current.operation === "reading" ? "read" : "write"; - const code = systemCode(current); + const code = systemCodeFromError(current); if (code === "EACCES" || code === "EPERM") { const options = { cause, @@ -193,7 +189,7 @@ const hostFailurePath = (cause: unknown): string | undefined => { seen.add(current); if (current instanceof BundleFileHostFailure) return current.path; const path = Reflect.get(current, "path"); - if (systemCode(current) !== undefined && typeof path === "string") + if (systemCodeFromError(current) !== undefined && typeof path === "string") return isAbsolute(path) ? path : undefined; current = current.cause; } @@ -348,7 +344,7 @@ export const readEnvironmentExportFile = async ( `${path} changed while being read; retry with stable input files.`, ), ); - if (NOT_A_FILE_CODES.has(systemCode(cause) ?? "")) + if (NOT_A_FILE_CODES.has(systemCodeFromError(cause) ?? "")) return err( inputError( operation, @@ -442,7 +438,7 @@ export const packageTarballBytes = async ( return err(readerFailureError(cause, undefined)); if (cause instanceof BundleFileHostFailure) return err(packageTarballRefusal(path, cause)); - if (systemCode(cause) !== undefined) + if (systemCodeFromError(cause) !== undefined) return err(packageTarballRefusal(path, cause)); throw cause; } @@ -486,7 +482,7 @@ export const exportEnvironmentBundle = async ( return err(readerFailureError(cause, input.directory)); if ( cause instanceof BundleFileHostFailure || - (cause instanceof Error && systemCode(cause) !== undefined) + (cause instanceof Error && systemCodeFromError(cause) !== undefined) ) return err( new AnalysisOutputError(ENVIRONMENT_EXPORT_OPERATION, cause.message, { diff --git a/src/domain/compression/zstandardExactFrame.ts b/src/domain/compression/zstandardExactFrame.ts index 6a37899dfe0..43070ed97c4 100644 --- a/src/domain/compression/zstandardExactFrame.ts +++ b/src/domain/compression/zstandardExactFrame.ts @@ -1,3 +1,4 @@ +import { reportedSystemCode } from "../../kernel/reportedSystemCode.js"; import { constants as bufferConstants } from "node:buffer"; import { promisify } from "node:util"; import { @@ -193,20 +194,13 @@ function* walkFrames( return { ok: true, frames, consumed: offset }; } -const decoderCode = (cause: unknown): string | undefined => { - if (typeof cause !== "object" || cause === null || !("code" in cause)) - return undefined; - const code = cause.code; - return typeof code === "string" ? code : undefined; -}; - const decoderFailure = ( cause: unknown, offset: number, ): ZstandardFrameFailure => { if (hostRangeErrorKind(cause) === "host-capacity") return failure("output_limit", offset); - const code = decoderCode(cause); + const code = reportedSystemCode(cause); const detail = cause instanceof Error ? cause.message : undefined; if (code === "ZSTD_error_dstSize_tooSmall" || code === "ERR_BUFFER_TOO_LARGE") return failure("output_limit", offset, code, detail); diff --git a/src/evm/EvmoleInterfaceProvider.ts b/src/evm/EvmoleInterfaceProvider.ts index ce5d81044a0..33f4a43572b 100644 --- a/src/evm/EvmoleInterfaceProvider.ts +++ b/src/evm/EvmoleInterfaceProvider.ts @@ -1,3 +1,4 @@ +import { systemCodeFromError } from "../kernel/reportedSystemCode.js"; import { finalizedResult, runOwned } from "../providers/runOwned.js"; import { capturedProviderOutput, @@ -193,12 +194,7 @@ const selectEvmLimiter = async ( reason: `Set REA_EVM_PRLIMIT_COMMAND to an absolute executable regular file for caller-supplied util-linux prlimit. The selected path ${path} ${cause.code === "prlimit_not_absolute" ? "is not absolute" : "is not a regular file"}.`, cause, }); - const systemCode = - cause instanceof Error && - "code" in cause && - typeof cause.code === "string" - ? cause.code - : undefined; + const systemCode = systemCodeFromError(cause); const permissionDenied = systemCode === "EACCES" || systemCode === "EPERM"; const missing = systemCode === "ENOENT" || systemCode === "ENOTDIR"; const recovery = permissionDenied diff --git a/src/ghidra/GhidraFileArtifacts.ts b/src/ghidra/GhidraFileArtifacts.ts index 8c8dc5a8819..b934a544eda 100644 --- a/src/ghidra/GhidraFileArtifacts.ts +++ b/src/ghidra/GhidraFileArtifacts.ts @@ -1,3 +1,4 @@ +import { systemCodeFromError } from "../kernel/reportedSystemCode.js"; import { GhidraAdmissionError } from "./GhidraAdmissionError.js"; import type { Hash } from "node:crypto"; import { constants } from "node:fs"; @@ -222,12 +223,7 @@ export const ghidraFileDialect = ( primary instanceof GhidraAdmissionError ? primary : undefined; const reason = admission?.code ?? errorMessage(primary); const systemCode = - admission === undefined && - primary instanceof Error && - "code" in primary && - typeof primary.code === "string" - ? primary.code - : undefined; + admission === undefined ? systemCodeFromError(primary) : undefined; return new ProviderAdapterError("ghidra", operation, { ...details, cause, diff --git a/src/ghidra/GhidraJavaProbe.ts b/src/ghidra/GhidraJavaProbe.ts index 440f1b428c1..f39616ab6b1 100644 --- a/src/ghidra/GhidraJavaProbe.ts +++ b/src/ghidra/GhidraJavaProbe.ts @@ -1,3 +1,4 @@ +import { systemCodeFromError } from "../kernel/reportedSystemCode.js"; import type { ProcessInspectionFailure } from "../process/ProcessInspectionCleanup.js"; import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { launcherFailureOf } from "../process/launchFailure.js"; @@ -307,7 +308,7 @@ const observeGhidraJava = async ( ? "ETIMEDOUT" : commandFailure?.reason === "output-limit" ? "ENOBUFS" - : systemCode(commandFailure?.processError ?? cause); + : systemCodeFromError(commandFailure?.processError ?? cause); const failed: GhidraJavaProbeFailure = { _tag: "GhidraJavaProbeFailure", code: @@ -341,10 +342,6 @@ const observeGhidraJava = async ( } }; -const systemCode = (cause: unknown): string | undefined => - cause instanceof Error && "code" in cause && typeof cause.code === "string" - ? cause.code - : undefined; const probeFailureError = ( failure: GhidraJavaProbeFailure, cause: unknown, diff --git a/src/ghidra/GhidraTemporaryDirectory.ts b/src/ghidra/GhidraTemporaryDirectory.ts index 4e18d3ccc0c..733557e7509 100644 --- a/src/ghidra/GhidraTemporaryDirectory.ts +++ b/src/ghidra/GhidraTemporaryDirectory.ts @@ -1,3 +1,4 @@ +import { systemCodeFromError } from "../kernel/reportedSystemCode.js"; import { randomUUID } from "node:crypto"; import { join } from "node:path"; import { open, unlink } from "node:fs/promises"; @@ -57,11 +58,6 @@ const writeProbe = async ( } }; -const errorCode = (cause: unknown): string | undefined => - cause instanceof Error && "code" in cause && typeof cause.code === "string" - ? cause.code - : undefined; - /** * Create and delete one file under the Ghidra session root from the REA * process. This proves only that REA itself can use the root; a host that @@ -76,7 +72,7 @@ export const probeGhidraTemporaryDirectory = async ( const path = join(directory, `rea-doctor-probe-${randomUUID()}`); const remove = () => unlink(path).catch((cause: unknown) => { - if (errorCode(cause) !== "ENOENT") throw cause; + if (systemCodeFromError(cause) !== "ENOENT") throw cause; }); const retain = () => resourceOwner.retain({ close: remove, cleanupResources: [path] }, path); @@ -100,7 +96,7 @@ export const probeGhidraTemporaryDirectory = async ( ok: false, directory, stage, - code: errorCode(primary), + code: systemCodeFromError(primary), message: errorMessage(primary), ...(removed ? {} : { retainedPath: path }), }; @@ -113,7 +109,7 @@ export const probeGhidraTemporaryDirectory = async ( ok: false, directory, stage: "cleanup", - code: errorCode(cause), + code: systemCodeFromError(cause), message: errorMessage(cause), retainedPath: path, }; diff --git a/src/kernel/reportedSystemCode.test.ts b/src/kernel/reportedSystemCode.test.ts index 380462e4c58..6fb35cc010d 100644 --- a/src/kernel/reportedSystemCode.test.ts +++ b/src/kernel/reportedSystemCode.test.ts @@ -1,5 +1,8 @@ import { expect, it } from "vitest"; -import { reportedSystemCode } from "./reportedSystemCode.js"; +import { + reportedSystemCode, + systemCodeFromError, +} from "./reportedSystemCode.js"; it("reads a reported code once and preserves an empty string", () => { let reads = 0; @@ -11,3 +14,10 @@ it("reads a reported code once and preserves an empty string", () => { expect(reportedSystemCode(cause)).toBe(""); expect(reads).toBe(1); }); + +it("requires an Error only at Error-specific boundaries", () => { + const record = { code: "EPIPE" }; + expect(reportedSystemCode(record)).toBe("EPIPE"); + expect(systemCodeFromError(record)).toBeUndefined(); + expect(systemCodeFromError(Object.assign(new Error(), record))).toBe("EPIPE"); +}); diff --git a/src/kernel/reportedSystemCode.ts b/src/kernel/reportedSystemCode.ts index fee9a460e85..6722ec26c0c 100644 --- a/src/kernel/reportedSystemCode.ts +++ b/src/kernel/reportedSystemCode.ts @@ -1,7 +1,15 @@ -/** Read the string code reported by a caught object, including a plain object. */ -export const reportedSystemCode = (cause: unknown): string | undefined => { - if (typeof cause !== "object" || cause === null || !("code" in cause)) - return undefined; - const code: unknown = cause.code; +const readStringCode = (value: object): string | undefined => { + if (!("code" in value)) return undefined; + const code: unknown = value.code; return typeof code === "string" ? code : undefined; }; + +/** Read the string code reported by a caught object, including a plain object. */ +export const reportedSystemCode = (cause: unknown): string | undefined => + typeof cause === "object" && cause !== null + ? readStringCode(cause) + : undefined; + +/** Read a system code only when the caller caught an Error. */ +export const systemCodeFromError = (cause: unknown): string | undefined => + cause instanceof Error ? readStringCode(cause) : undefined; diff --git a/src/main/reportMcpTransportError.ts b/src/main/reportMcpTransportError.ts index ddc7870a7b7..209cf55537a 100644 --- a/src/main/reportMcpTransportError.ts +++ b/src/main/reportMcpTransportError.ts @@ -1,3 +1,4 @@ +import { systemCodeFromError } from "../kernel/reportedSystemCode.js"; import type { Logger } from "pino"; import { z } from "zod"; import { StreamableHttpListenError } from "../server/http/streamableHttpListenError.js"; @@ -15,8 +16,7 @@ const transportSystemCode = (error: unknown): string | undefined => { : error.classification.error; return "systemCode" in failure ? failure.systemCode : undefined; } - if (!(error instanceof Error) || !("code" in error)) return undefined; - return typeof error.code === "string" ? error.code : undefined; + return systemCodeFromError(error); }; /** diff --git a/src/native/elf/KernelBuildConfig.ts b/src/native/elf/KernelBuildConfig.ts index c52ef40daad..4a992edc952 100644 --- a/src/native/elf/KernelBuildConfig.ts +++ b/src/native/elf/KernelBuildConfig.ts @@ -1,3 +1,4 @@ +import { systemCodeFromError } from "../../kernel/reportedSystemCode.js"; import { createHash } from "node:crypto"; import { setImmediate as nextTurn } from "node:timers/promises"; import { crc32, inflateRaw } from "node:zlib"; @@ -66,11 +67,6 @@ const CONFIG_SEARCH_BUDGET_FACTOR = 4; const TURN_STRIDE = 0x100000; const UNTRUSTED = "target-derived-untrusted" as const; -const codeOf = (error: unknown): string | null => - error instanceof Error && "code" in error && typeof error.code === "string" - ? error.code - : null; - /** * Let pending signals and requests run, then honor an abort they raised. The * scans are otherwise synchronous, so without a turn no abort could land. @@ -256,7 +252,7 @@ const inflateGzipMember = async ( consumed = inflated.engine.bytesWritten; } catch (error) { assertArtifactReadActive(signal); - const code = codeOf(error); + const code = systemCodeFromError(error); if (code === "ERR_BUFFER_TOO_LARGE") return { kind: "limit" }; return code === "Z_BUF_ERROR" ? { kind: "truncated", spent: maxOutput } diff --git a/src/process/ProcessRunTokenObservations.ts b/src/process/ProcessRunTokenObservations.ts index 838a908df10..6152fddb227 100644 --- a/src/process/ProcessRunTokenObservations.ts +++ b/src/process/ProcessRunTokenObservations.ts @@ -1,3 +1,4 @@ +import { systemCodeFromError } from "../kernel/reportedSystemCode.js"; import { DarwinProcessOwnershipInspectionError } from "./DarwinProcessRunTokenReader.js"; import { assertProcessOwnershipInspectionActive, @@ -56,12 +57,7 @@ export const readProcessRunToken = async ( ) throw cause; rethrowProcessOwnershipInspectionFailure(cause); - const code = - cause instanceof Error && - "code" in cause && - typeof cause.code === "string" - ? cause.code - : undefined; + const code = systemCodeFromError(cause); return { state: "unavailable", ...(code === undefined ? {} : { code }), diff --git a/src/process/capture/FilesystemSnapshot.ts b/src/process/capture/FilesystemSnapshot.ts index 45e2831f9cc..6b11c3b8c09 100644 --- a/src/process/capture/FilesystemSnapshot.ts +++ b/src/process/capture/FilesystemSnapshot.ts @@ -1,3 +1,4 @@ +import { systemCodeFromError } from "../../kernel/reportedSystemCode.js"; import { assertNotCancelled } from "./ProcessScenarioRuntimeValidation.js"; import { observedSymlinkTarget } from "../../domain/symlinkTarget.js"; import { createHash } from "node:crypto"; @@ -44,12 +45,6 @@ const hasSameIdentity = ( before.ino === after.ino && (expected === "directory" ? after.isDirectory() : after.isSymbolicLink()); -const filesystemSystemCode = (cause: unknown): string | undefined => { - if (!(cause instanceof Error) || !("code" in cause)) return undefined; - const code = cause.code; - return typeof code === "string" ? code : undefined; -}; - const unavailableSystemCodes = new Set([ "EACCES", "EISDIR", @@ -61,7 +56,7 @@ const unavailableSystemCodes = new Set([ ]); const fileUnavailableSystemCode = (cause: unknown): string | undefined => { - const code = filesystemSystemCode(cause); + const code = systemCodeFromError(cause); return code !== undefined && unavailableSystemCodes.has(code) ? code : undefined; @@ -81,7 +76,7 @@ const readEntryObservation = async ( try { value = await read(); } catch (cause: unknown) { - const code = filesystemSystemCode(cause); + const code = systemCodeFromError(cause); // readlink reports EINVAL if the observed symlink was replaced by a file. if ( code === undefined || @@ -436,7 +431,7 @@ export const snapshotRoots = async ( try { return await realpath(path); } catch (cause: unknown) { - const code = filesystemSystemCode(cause); + const code = systemCodeFromError(cause); if (code === "ENOENT" || code === "ENOTDIR") return undefined; throw cause; } diff --git a/src/process/capture/ProcessSamplingObservation.ts b/src/process/capture/ProcessSamplingObservation.ts index 0f6efc1a241..aed9d5cca2c 100644 --- a/src/process/capture/ProcessSamplingObservation.ts +++ b/src/process/capture/ProcessSamplingObservation.ts @@ -1,3 +1,4 @@ +import { systemCodeFromError } from "../../kernel/reportedSystemCode.js"; import { isProcessInspectionFailure, processInspectionCancellations, @@ -152,12 +153,7 @@ export const readSamplingSource = async ( cause.availability === "absent" ) return err({ kind: "process-exited" }); - const systemCode = - cause instanceof Error && - "code" in cause && - typeof cause.code === "string" - ? cause.code - : undefined; + const systemCode = systemCodeFromError(cause); const reason = cause instanceof Error ? `${cause.name}: ${cause.message}` diff --git a/src/process/privateWorkspaceFailure.ts b/src/process/privateWorkspaceFailure.ts index 89cf3374ad7..7c8703b0d29 100644 --- a/src/process/privateWorkspaceFailure.ts +++ b/src/process/privateWorkspaceFailure.ts @@ -1,3 +1,4 @@ +import { systemCodeFromError } from "../kernel/reportedSystemCode.js"; import type { AnalysisError } from "../domain/analysisErrorBase.js"; import { AnalysisResourceConstraintError } from "../domain/analysisErrorCore.js"; import { ProviderAdapterError } from "../domain/providerAdapterError.js"; @@ -15,11 +16,6 @@ const DESCRIPTOR_EXHAUSTION_CODES: ReadonlySet = new Set([ "ENFILE", ]); -const systemCode = (cause: unknown): string | null => - cause instanceof Error && "code" in cause && typeof cause.code === "string" - ? cause.code - : null; - const systemPath = (cause: unknown): string | null => cause instanceof Error && "path" in cause && typeof cause.path === "string" ? cause.path @@ -40,7 +36,7 @@ export const privateWorkspaceFailure = ( cause: unknown, workspacePath: string | null, ): AnalysisError => { - const code = systemCode(cause); + const code = systemCodeFromError(cause) ?? null; const path = systemPath(cause) ?? workspacePath; const reason = errorMessage(cause); if (code !== null && (STORAGE_EXHAUSTION_CODES.has(code) || code === "EFBIG")) diff --git a/tests/boundary/mcp/mainErrors.test.ts b/tests/boundary/mcp/mainErrors.test.ts index 8c54c858e5f..482ae1a7a78 100644 --- a/tests/boundary/mcp/mainErrors.test.ts +++ b/tests/boundary/mcp/mainErrors.test.ts @@ -102,6 +102,16 @@ describe("MCP runtime errors", () => { cause: Object.assign(new Error("SECRET broken pipe"), { code: "EPIPE" }), message: MCP_CONNECTION_LOST, }, + { + name: "a broken pipe whose reported code changes on a second read", + get cause() { + const codes = ["EPIPE", "EIO"]; + return Object.defineProperty(new Error("SECRET broken pipe"), "code", { + get: () => codes.shift(), + }); + }, + message: MCP_CONNECTION_LOST, + }, ...notConnectedCases, { name: "a wrapped HTTP broken pipe",