diff --git a/src/lib/actions/sandbox/inference-invocation-probe.test.ts b/src/lib/actions/sandbox/inference-invocation-probe.test.ts index 2970636897f..00ffee42e2f 100644 --- a/src/lib/actions/sandbox/inference-invocation-probe.test.ts +++ b/src/lib/actions/sandbox/inference-invocation-probe.test.ts @@ -16,11 +16,14 @@ import path from "node:path"; import { describe, expect, it, vi } from "vitest"; import { isNvcfFunctionNotFoundForAccount } from "../../inference/nvcf-model-access"; +import type { SandboxExecCommandOptions } from "../../adapters/sandbox/command-transport"; import { buildDcodeSandboxInferenceInvocationRequest, buildSandboxInferenceInvocationCommand, probeSandboxInferenceInvocation, READINESS_INFERENCE_INVOCATION_TIMEOUT_MS, + REBUILD_INFERENCE_INVOCATION_TIMEOUT_MS, + resolveInferenceInvocationMaxTimeSeconds, } from "./inference-invocation-probe"; const input = { @@ -168,6 +171,105 @@ describe("sandbox inference invocation probe", () => { expect(JSON.stringify(result)).not.toContain("canary-replay-marker"); }); + it("keeps curl --max-time safely inside the outer exec timeout so a slow endpoint is not killed (#11162)", () => { + const readinessCommand = buildSandboxInferenceInvocationCommand( + input, + READINESS_INFERENCE_INVOCATION_TIMEOUT_MS, + ); + const rebuildCommand = buildSandboxInferenceInvocationCommand( + input, + REBUILD_INFERENCE_INVOCATION_TIMEOUT_MS, + ); + + const readinessMaxTime = Number(readinessCommand.match(/--max-time (\d+)/)?.[1]); + const rebuildMaxTime = Number(rebuildCommand.match(/--max-time (\d+)/)?.[1]); + + // curl --max-time must finish (clean exit 28) before the outer timeout can + // SIGTERM the subprocess and collapse a slow-but-healthy endpoint into a + // generic "unavailable" result. + expect(readinessMaxTime * 1000).toBeLessThan(READINESS_INFERENCE_INVOCATION_TIMEOUT_MS); + expect(rebuildMaxTime * 1000).toBeLessThan(REBUILD_INFERENCE_INVOCATION_TIMEOUT_MS); + expect( + resolveInferenceInvocationMaxTimeSeconds(READINESS_INFERENCE_INVOCATION_TIMEOUT_MS), + ).toBe(readinessMaxTime); + }); + + it("surfaces a probe timeout when the transport reports the subprocess was killed (#11162)", async () => { + const execute = vi.fn( + async ( + _sandbox: string, + _command: string, + _timeout?: number, + options?: SandboxExecCommandOptions, + ) => { + options?.onTransportFailure?.({ kind: "timeout", timeoutMs: 30_000 }); + return null; + }, + ); + + await expect(probeSandboxInferenceInvocation(input, { execute }, 30_000)).resolves.toEqual({ + ok: false, + detail: "sandbox inference invocation probe timed out after 30s", + httpStatus: null, + endpoint: "https://inference.local/v1/chat/completions", + }); + }); + + it("surfaces a subprocess error reason when the transport fails to spawn (#11162)", async () => { + const execute = vi.fn( + async ( + _sandbox: string, + _command: string, + _timeout?: number, + options?: SandboxExecCommandOptions, + ) => { + options?.onTransportFailure?.({ kind: "error", detail: "ENOENT" }); + return null; + }, + ); + + await expect(probeSandboxInferenceInvocation(input, { execute })).resolves.toEqual({ + ok: false, + detail: "sandbox inference invocation probe subprocess failed (ENOENT)", + httpStatus: null, + endpoint: "https://inference.local/v1/chat/completions", + }); + }); + + it("keeps the generic unavailable detail when the transport reports no reason (#11162)", async () => { + const execute = vi.fn(async () => null); + + await expect(probeSandboxInferenceInvocation(input, { execute })).resolves.toEqual({ + ok: false, + detail: "sandbox inference invocation probe was unavailable", + httpStatus: null, + endpoint: "https://inference.local/v1/chat/completions", + }); + }); + + it("reports a curl-level endpoint timeout (exit 28) as a timeout, not a generic exit (#11162)", async () => { + const execute = vi.fn(async () => ({ status: 28, stdout: "curl-error:28", stderr: "" })); + + await expect(probeSandboxInferenceInvocation(input, { execute })).resolves.toEqual({ + ok: false, + detail: + "sandbox inference invocation probe timed out waiting for the endpoint (curl exit 28)", + httpStatus: null, + endpoint: "https://inference.local/v1/chat/completions", + }); + }); + + it("reports a non-timeout curl exit accurately (#11162)", async () => { + const execute = vi.fn(async () => ({ status: 7, stdout: "curl-error:7", stderr: "" })); + + await expect(probeSandboxInferenceInvocation(input, { execute })).resolves.toEqual({ + ok: false, + detail: "sandbox inference invocation probe could not complete the request (curl exit 7)", + httpStatus: null, + endpoint: "https://inference.local/v1/chat/completions", + }); + }); + it("names the account entitlement cause behind an invocation 404 (#10879)", async () => { const execute = vi.fn(async () => ({ status: 1, @@ -297,7 +399,11 @@ describe("sandbox inference invocation probe", () => { "dcode-workspace", expect.any(String), expect.any(Number), - { gatewayName: "recorded-gateway", localDockerFallbackPolicy: "never" }, + { + gatewayName: "recorded-gateway", + localDockerFallbackPolicy: "never", + onTransportFailure: expect.any(Function), + }, ); }); @@ -323,7 +429,11 @@ describe("sandbox inference invocation probe", () => { "hermes-workspace", expect.any(String), expect.any(Number), - { gatewayName: "nemoclaw-19080", localDockerFallbackPolicy: "never" }, + { + gatewayName: "nemoclaw-19080", + localDockerFallbackPolicy: "never", + onTransportFailure: expect.any(Function), + }, ); expect(execute).toHaveBeenCalledOnce(); }); @@ -406,6 +516,53 @@ describe("sandbox inference invocation probe", () => { }); }); + it("surfaces a probe timeout when the Deep Agents Code launcher is killed by the outer timeout (#11162)", async () => { + const runBuffered = vi.fn(async () => ({ + outcome: { + kind: "failed" as const, + error: { kind: "timeout" as const, message: "OpenShell command timed out" }, + }, + stdout: "", + stderr: "", + })); + + await expect( + probeSandboxInferenceInvocation( + { ...input, agentName: "langchain-deepagents-code" }, + { commandExecutor: { runBuffered } }, + REBUILD_INFERENCE_INVOCATION_TIMEOUT_MS, + ), + ).resolves.toEqual({ + ok: false, + detail: "sandbox inference invocation probe timed out after 100s", + httpStatus: null, + endpoint: "https://inference.local/v1/chat/completions", + }); + }); + + it("surfaces a subprocess error when the Deep Agents Code launcher fails (#11162)", async () => { + const runBuffered = vi.fn(async () => ({ + outcome: { + kind: "failed" as const, + error: { kind: "invocation" as const, message: "OpenShell invocation failed" }, + }, + stdout: "", + stderr: "", + })); + + await expect( + probeSandboxInferenceInvocation( + { ...input, agentName: "langchain-deepagents-code" }, + { commandExecutor: { runBuffered } }, + ), + ).resolves.toEqual({ + ok: false, + detail: "sandbox inference invocation probe subprocess failed (invocation)", + httpStatus: null, + endpoint: "https://inference.local/v1/chat/completions", + }); + }); + it("accepts a served response body that serializes an empty tool call list (#9108)", async () => { const body = JSON.stringify({ object: "chat.completion", @@ -539,9 +696,13 @@ describe("sandbox inference invocation probe", () => { model, max_tokens: maxTokens, }); - expect(argv[argv.indexOf("--max-time") + 1]).toBe("90"); + // curl's --max-time is derived from the outer timeout so it finishes before + // the outer kill instead of being SIGTERM-collapsed into "unavailable" (#11162). + expect(argv[argv.indexOf("--max-time") + 1]).toBe( + String(resolveInferenceInvocationMaxTimeSeconds(REBUILD_INFERENCE_INVOCATION_TIMEOUT_MS)), + ); expect(Number(argv[argv.indexOf("--max-time") + 1]) * 1000).toBeLessThan( - READINESS_INFERENCE_INVOCATION_TIMEOUT_MS, + REBUILD_INFERENCE_INVOCATION_TIMEOUT_MS, ); }); diff --git a/src/lib/actions/sandbox/inference-invocation-probe.ts b/src/lib/actions/sandbox/inference-invocation-probe.ts index c9f984e0329..936d79ef51f 100644 --- a/src/lib/actions/sandbox/inference-invocation-probe.ts +++ b/src/lib/actions/sandbox/inference-invocation-probe.ts @@ -28,6 +28,10 @@ import { import { ROOT, shellQuote } from "../../runner"; import { buildSubprocessEnv } from "../../subprocess-env"; import { DCODE_MANAGED_EXEC_LAUNCHER } from "./connect-inference-route-probe"; +import { + classifyOutcomeTransportFailure, + type SandboxCommandTransportFailure, +} from "../../adapters/sandbox/command-transport"; import { executeSandboxExecCommand, type SandboxCommandResult, @@ -70,6 +74,31 @@ export const INFERENCE_INVOCATION_REQUEST_TIMEOUT_SECONDS = 90; export const READINESS_INFERENCE_INVOCATION_TIMEOUT_MS = 95_000; const INFERENCE_INVOCATION_MAX_RESPONSE_BYTES = 64 * 1024; +// curl's `--max-time` bounds the whole request (connect + transfer). It must +// sit safely inside the outer exec timeout so a slow-but-healthy endpoint is +// bounded by curl (clean exit 28) instead of being SIGTERM-killed by the outer +// timeout and collapsed into a generic "unavailable" result (#11162). The +// buffer reserves headroom for `openshell sandbox exec` spawn/attach overhead +// so curl finishes before the outer kill. Note: an operator override via +// NEMOCLAW_SANDBOX_EXEC_TIMEOUT_MS shortens only the outer exec timeout, not +// this derived budget; a genuine timeout there is still reported accurately as +// a timeout with the effective duration. +const INFERENCE_INVOCATION_CONNECT_TIMEOUT_SECONDS = 5; +const INFERENCE_INVOCATION_OUTER_TIMEOUT_BUFFER_MS = 5_000; + +/** + * Derive curl's `--max-time` (whole seconds) from the outer exec timeout so the + * request is always bounded by curl before the outer timeout can SIGTERM the + * subprocess. Clamped to at least 1s for a pathologically small outer timeout; + * the unit test asserts the derived budget stays strictly below every real + * outer timeout the callers use. + */ +export function resolveInferenceInvocationMaxTimeSeconds(timeoutMs: number): number { + const budgetMs = timeoutMs - INFERENCE_INVOCATION_OUTER_TIMEOUT_BUFFER_MS; + const seconds = Math.floor(budgetMs / 1000); + return Math.max(1, seconds); +} + /** Build the protocol-specific request used to verify sandbox inference. */ function buildProbeRequest(input: SandboxInferenceInvocationInput): { endpoint: string; @@ -124,6 +153,7 @@ export function resolveSandboxInferenceInvocationEndpoint( export function buildSandboxInferenceInvocationCommand( input: SandboxInferenceInvocationInput, + timeoutMs: number = REBUILD_INFERENCE_INVOCATION_TIMEOUT_MS, ): string { const request = buildProbeRequest(input); const headerArgs = ["Content-Type: application/json", ...request.headers] @@ -131,11 +161,12 @@ export function buildSandboxInferenceInvocationCommand( .join(" "); const payload = shellQuote(JSON.stringify(request.payload)); const endpoint = shellQuote(request.endpoint); + const maxTimeSeconds = resolveInferenceInvocationMaxTimeSeconds(timeoutMs); return [ "umask 077", "body=$(mktemp /tmp/nemoclaw-inference-invocation.XXXXXX) || exit 1", "trap 'rm -f \"$body\"' EXIT HUP INT TERM", - `code=$(curl -q -sS --connect-timeout 5 --max-time ${INFERENCE_INVOCATION_REQUEST_TIMEOUT_SECONDS} --max-filesize ${INFERENCE_INVOCATION_MAX_RESPONSE_BYTES} -o "$body" -w '%{http_code}' ${headerArgs} --data-binary ${payload} ${endpoint}) || { rc=$?; printf 'curl-error:%s\\n' "$rc"; exit "$rc"; }`, + `code=$(curl -q -sS --connect-timeout ${INFERENCE_INVOCATION_CONNECT_TIMEOUT_SECONDS} --max-time ${maxTimeSeconds} --max-filesize ${INFERENCE_INVOCATION_MAX_RESPONSE_BYTES} -o "$body" -w '%{http_code}' ${headerArgs} --data-binary ${payload} ${endpoint}) || { rc=$?; printf 'curl-error:%s\\n' "$rc"; exit "$rc"; }`, "printf '%s\\n' \"$code\"", // A non-2xx body never leaves the sandbox (#6195). A 404 is classified // here instead, so status can name the cause the onboarding probe already @@ -146,7 +177,7 @@ export function buildSandboxInferenceInvocationCommand( export function buildDcodeSandboxInferenceInvocationRequest( input: SandboxInferenceInvocationInput, - timeoutMilliseconds: number, + timeoutMs: number = REBUILD_INFERENCE_INVOCATION_TIMEOUT_MS, ): OpenShellSandboxBufferedCommandRequest { const gatewayName = input.gatewayName ?? input.runtimeSelection?.gatewayName; return { @@ -156,7 +187,7 @@ export function buildDcodeSandboxInferenceInvocationRequest( DCODE_MANAGED_EXEC_LAUNCHER, "/bin/sh", "-c", - buildSandboxInferenceInvocationCommand(input), + buildSandboxInferenceInvocationCommand(input, timeoutMs), ], sandboxEnvironment: { BASH_ENV: "", @@ -167,14 +198,32 @@ export function buildDcodeSandboxInferenceInvocationRequest( ? buildOpenShellRuntimeSelectionEnv(buildSubprocessEnv(), input.runtimeSelection) : buildSubprocessEnv(), tty: false, - timeoutMilliseconds, + timeoutMilliseconds: timeoutMs, }; } +/** Describe why the transport produced no result so the probe surfaces the real reason (#11162). */ +function describeInvocationTransportFailure( + failure: SandboxCommandTransportFailure | null, +): string { + if (failure?.kind === "timeout") { + const seconds = failure.timeoutMs / 1000; + const rendered = seconds >= 1 ? `${Math.round(seconds)}s` : `${failure.timeoutMs}ms`; + return `sandbox inference invocation probe timed out after ${rendered}`; + } + if (failure?.kind === "error") { + return failure.detail + ? `sandbox inference invocation probe subprocess failed (${failure.detail})` + : "sandbox inference invocation probe subprocess failed"; + } + return "sandbox inference invocation probe was unavailable"; +} + async function executeDcodeSandboxInferenceInvocation( input: SandboxInferenceInvocationInput, deps: SandboxInferenceInvocationDeps, timeoutMs: number, + onTransportFailure: (failure: SandboxCommandTransportFailure) => void, ): Promise { const commandExecutor = deps.commandExecutor ?? createCliOpenShellSandboxCommandExecutor({ hostCwd: ROOT }); @@ -182,7 +231,12 @@ async function executeDcodeSandboxInferenceInvocation( const completed = await commandExecutor.runBuffered( buildDcodeSandboxInferenceInvocationRequest(input, timeoutMs), ); - if (completed.outcome.kind !== "completed" || completed.stderr.trim()) { + if (completed.outcome.kind !== "completed") { + const failure = classifyOutcomeTransportFailure(completed.outcome.error, timeoutMs); + if (failure) onTransportFailure(failure); + return null; + } + if (completed.stderr.trim()) { return null; } return { @@ -190,7 +244,9 @@ async function executeDcodeSandboxInferenceInvocation( stdout: completed.stdout, stderr: completed.stderr, }; - } catch { + } catch (error) { + const code = (error as NodeJS.ErrnoException | undefined)?.code; + onTransportFailure(code ? { kind: "error", detail: code } : { kind: "error" }); return null; } } @@ -207,18 +263,28 @@ export async function probeSandboxInferenceInvocation( timeoutMs: number = REBUILD_INFERENCE_INVOCATION_TIMEOUT_MS, ): Promise { let result: SandboxCommandResult | null; + let transportFailure: SandboxCommandTransportFailure | null = null; + const onTransportFailure = (failure: SandboxCommandTransportFailure) => { + transportFailure = failure; + }; if (input.agentName === DCODE_AGENT_NAME) { - result = await executeDcodeSandboxInferenceInvocation(input, deps, timeoutMs); + result = await executeDcodeSandboxInferenceInvocation( + input, + deps, + timeoutMs, + onTransportFailure, + ); } else { const execute = deps.execute ?? executeSandboxExecCommand; const execOptions: SandboxExecCommandOptions = { ...(input.gatewayName ? { gatewayName: input.gatewayName } : {}), ...(input.runtimeSelection ? { runtimeSelection: input.runtimeSelection } : {}), localDockerFallbackPolicy: "never", + onTransportFailure, }; result = await execute( input.sandboxName, - buildSandboxInferenceInvocationCommand(input), + buildSandboxInferenceInvocationCommand(input, timeoutMs), timeoutMs, execOptions, ); @@ -226,7 +292,7 @@ export async function probeSandboxInferenceInvocation( if (!result) { return { ok: false, - detail: "sandbox inference invocation probe was unavailable", + detail: describeInvocationTransportFailure(transportFailure), httpStatus: null, endpoint: resolveSandboxInferenceInvocationEndpoint(input), }; @@ -252,21 +318,44 @@ export async function probeSandboxInferenceInvocation( }; } const httpStatus = result.stdout.match(/(?:^|\n)([1-5]\d\d)(?:\n|$)/)?.[1]; - // Only the fixed marker is read back, never the line that carried it, so an - // upstream body can still not reach diagnostics (#6195). - const nvcfFunctionNotFound = result.stdout - .split("\n") - .some((line) => line.trim() === NVCF_FUNCTION_NOT_FOUND_MARKER); - const detail = httpStatus - ? `sandbox inference invocation probe returned HTTP ${httpStatus}` - : `sandbox inference invocation probe exited with status ${result.status}`; + if (httpStatus) { + // Only the fixed marker is read back, never the line that carried it, so an + // upstream body can still not reach diagnostics (#6195). + const nvcfFunctionNotFound = result.stdout + .split("\n") + .some((line) => line.trim() === NVCF_FUNCTION_NOT_FOUND_MARKER); + const detail = `sandbox inference invocation probe returned HTTP ${httpStatus}`; + return { + ok: false, + detail: + httpStatus === "404" && nvcfFunctionNotFound + ? `${detail}: ${nvcfFunctionNotFoundMessage(input.model).replace(/\.$/, "")}` + : detail, + httpStatus: Number.parseInt(httpStatus, 10), + endpoint: resolveSandboxInferenceInvocationEndpoint(input), + }; + } + // curl exits non-zero with `curl-error:` on stdout when the request could + // not complete. Exit 28 is curl's own timeout; surface it as an endpoint + // timeout instead of a generic exit code so a slow-but-healthy endpoint that + // curl bounded is reported accurately (#11162). Only the curl exit code (never + // response content) is read from the output here. + const curlExit = result.stdout.match(/(?:^|\n)curl-error:(\d+)(?:\n|$)/)?.[1]; + if (curlExit === "28") { + return { + ok: false, + detail: + "sandbox inference invocation probe timed out waiting for the endpoint (curl exit 28)", + httpStatus: null, + endpoint: resolveSandboxInferenceInvocationEndpoint(input), + }; + } return { ok: false, - detail: - httpStatus === "404" && nvcfFunctionNotFound - ? `${detail}: ${nvcfFunctionNotFoundMessage(input.model).replace(/\.$/, "")}` - : detail, - httpStatus: httpStatus ? Number.parseInt(httpStatus, 10) : null, + detail: curlExit + ? `sandbox inference invocation probe could not complete the request (curl exit ${curlExit})` + : `sandbox inference invocation probe exited with status ${result.status}`, + httpStatus: null, endpoint: resolveSandboxInferenceInvocationEndpoint(input), }; } diff --git a/src/lib/adapters/sandbox/command-transport.test.ts b/src/lib/adapters/sandbox/command-transport.test.ts index f3057a34601..d5c9c199db9 100644 --- a/src/lib/adapters/sandbox/command-transport.test.ts +++ b/src/lib/adapters/sandbox/command-transport.test.ts @@ -67,6 +67,54 @@ describe("sandbox command transport", () => { }); }); + it("reports a timeout when the gateway-pinned exec is killed by the outer timeout (#11162)", async () => { + const deps = createDependencies({ + commandExecutor: { + runBuffered: vi.fn(async () => ({ + outcome: { + kind: "failed" as const, + error: { kind: "timeout" as const, message: "OpenShell command timed out" }, + }, + stdout: "", + stderr: "", + })), + } as OpenShellSandboxBufferedCommandExecutor, + }); + const failures: unknown[] = []; + + await expect( + executeSandboxExecCommandTransport(deps, "alpha", "id", 9000, { + localDockerFallbackPolicy: "never", + onTransportFailure: (failure) => failures.push(failure), + }), + ).resolves.toBeNull(); + expect(failures).toEqual([{ kind: "timeout", timeoutMs: 9000 }]); + }); + + it("reports a subprocess error kind when the gateway-pinned exec fails (#11162)", async () => { + const deps = createDependencies({ + commandExecutor: { + runBuffered: vi.fn(async () => ({ + outcome: { + kind: "failed" as const, + error: { kind: "invocation" as const, message: "OpenShell invocation failed" }, + }, + stdout: "", + stderr: "", + })), + } as OpenShellSandboxBufferedCommandExecutor, + }); + const failures: unknown[] = []; + + await expect( + executeSandboxExecCommandTransport(deps, "alpha", "id", 9000, { + localDockerFallbackPolicy: "never", + onTransportFailure: (failure) => failures.push(failure), + }), + ).resolves.toBeNull(); + expect(failures).toEqual([{ kind: "error", detail: "invocation" }]); + }); + it.each([ { result: { kind: "failed", reason: "configuration" }, expected: null }, { diff --git a/src/lib/adapters/sandbox/command-transport.ts b/src/lib/adapters/sandbox/command-transport.ts index 08141a799a3..969f8b91a6c 100644 --- a/src/lib/adapters/sandbox/command-transport.ts +++ b/src/lib/adapters/sandbox/command-transport.ts @@ -1,7 +1,10 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import type { OpenShellSandboxBufferedCommandExecutor } from "../openshell/sandbox-command"; +import type { + OpenShellSandboxBufferedCommandExecutor, + OpenShellSandboxCommandError, +} from "../openshell/sandbox-command"; import { namedOpenShellGateway, selectedOpenShellGateway } from "../openshell/sandbox-observer"; import { createCliOpenShellSandboxSshCommandExecutor } from "../openshell/sandbox-ssh-cli"; import type { OpenShellSandboxSshExecutor } from "../openshell/sandbox-ssh"; @@ -12,6 +15,18 @@ export type SandboxCommandResult = { stderr: string; }; +/** + * Why a sandbox exec transport produced no usable result. A subprocess that is + * killed by the outer timeout is a distinct condition from a subprocess that + * failed to spawn or exited abnormally; callers such as the inference + * invocation probe surface the real reason instead of a generic "unavailable" + * message (#11162). The `detail` is limited to a subprocess error code so no + * untrusted command output can leak through this boundary. + */ +export type SandboxCommandTransportFailure = + | { kind: "timeout"; timeoutMs: number } + | { kind: "error"; detail?: string }; + /** * Declares when a command is safe to repeat through the pinned local runtime. * `read-only` commands cannot leave a mutation to reconcile. `reconciled` @@ -22,6 +37,7 @@ export type LocalDockerFallbackPolicy = "never" | "unavailable-only" | "read-onl export type SandboxExecCommandOptions = { localDockerFallbackPolicy?: LocalDockerFallbackPolicy; gatewayName?: string; + onTransportFailure?: (failure: SandboxCommandTransportFailure) => void; runtimeEnv?: NodeJS.ProcessEnv; }; @@ -56,6 +72,24 @@ function resolveSandboxExecTimeout(timeout: number): number { return Number.isFinite(timeoutOverride) && timeoutOverride > 0 ? timeoutOverride : timeout; } +/** + * Classify a typed OpenShell command failure that yielded no usable result so + * callers can distinguish a slow endpoint (a timeout) from a genuine subprocess + * error (#11162). A `timeout` outcome reports the effective duration; every + * other transport failure kind reports its kind as the error detail. Only the + * error kind (never the error message or any captured output) crosses this + * boundary. An `unavailable` outcome is not a probe-transport failure — it means + * OpenShell itself was absent, so the caller keeps its generic message. + */ +export function classifyOutcomeTransportFailure( + error: OpenShellSandboxCommandError, + timeoutMs: number, +): SandboxCommandTransportFailure | null { + if (error.kind === "timeout") return { kind: "timeout", timeoutMs }; + if (error.kind === "unavailable") return null; + return { kind: "error", detail: error.kind }; +} + function permitsUnknownOutcomeFallback(policy: LocalDockerFallbackPolicy): boolean { return policy === "read-only" || policy === "reconciled"; } @@ -140,6 +174,11 @@ export async function executeSandboxExecCommandTransport( const markedCommand = deps.buildSandboxExecMarkedCommand(command); const effectiveTimeout = resolveSandboxExecTimeout(timeout); const fallbackPolicy = options.localDockerFallbackPolicy ?? "unavailable-only"; + // Track why the OpenShell transport produced no usable result so a caller + // that opted out of the local fallback can surface the real reason instead of + // a generic "unavailable" message (#11162). Only a subprocess error code or a + // timeout duration crosses this boundary — never captured command output. + let pendingFailure: SandboxCommandTransportFailure | null = null; const completed = await deps.commandExecutor.runBuffered({ sandboxName, target: options.gatewayName @@ -159,14 +198,23 @@ export async function executeSandboxExecCommandTransport( if (!permitsUnknownOutcomeFallback(fallbackPolicy)) return null; } else if (completed.outcome.error.kind === "cancelled") { return null; - } else if ( - completed.outcome.error.kind !== "unavailable" && - !permitsUnknownOutcomeFallback(fallbackPolicy) - ) { + } else { + pendingFailure = classifyOutcomeTransportFailure(completed.outcome.error, effectiveTimeout); + if ( + completed.outcome.error.kind !== "unavailable" && + !permitsUnknownOutcomeFallback(fallbackPolicy) + ) { + if (pendingFailure) options.onTransportFailure?.(pendingFailure); + return null; + } + } + if (fallbackPolicy === "never") { + if (pendingFailure) options.onTransportFailure?.(pendingFailure); return null; } - if (fallbackPolicy === "never") return null; - // Keep the fallback outside the OpenShell try/catch so a fail-closed identity - // refusal cannot be caught and retried against changing container state. - return executeLocalSandboxCommand(deps, sandboxName, markedCommand, effectiveTimeout); + // Keep the fallback outside the OpenShell outcome handling so a fail-closed + // identity refusal cannot be retried against changing container state. + const fallback = executeLocalSandboxCommand(deps, sandboxName, markedCommand, effectiveTimeout); + if (fallback === null && pendingFailure) options.onTransportFailure?.(pendingFailure); + return fallback; }